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
sportlabsMike/XLForm
Examples/Swift/SwiftExample/DynamicSelector/UsersTableViewController.swift
1
7900
// // UsersTableViewController.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. class UserCell : UITableViewCell { lazy var userImage : UIImageView = { let tempUserImage = UIImageView() tempUserImage.translatesAutoresizingMaskIntoConstraints = false tempUserImage.layer.masksToBounds = true tempUserImage.layer.cornerRadius = 10.0 return tempUserImage }() lazy var userName : UILabel = { let tempUserName = UILabel() tempUserName.translatesAutoresizingMaskIntoConstraints = false tempUserName.font = UIFont.systemFont(ofSize: 15.0) return tempUserName }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // Initialization code contentView.addSubview(userImage) contentView.addSubview(userName) contentView.addConstraints(layoutConstraints()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } // MARK: - Layout Constraints func layoutConstraints() -> [NSLayoutConstraint]{ let views = ["image": self.userImage, "name": self.userName ] as [String : Any] let metrics = [ "imgSize": 50.0, "margin": 12.0] var result = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(margin)-[image(imgSize)]-[name]", options:.alignAllTop, metrics: metrics, views: views) result += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(margin)-[image(imgSize)]", options:NSLayoutFormatOptions(), metrics:metrics, views: views) return result } } private let _UsersJSONSerializationSharedInstance = UsersJSONSerialization() class UsersJSONSerialization { lazy var userData : Array<AnyObject>? = { let dataString = "[" + "{\"id\":1,\"name\":\"Apu Nahasapeemapetilon\",\"imageName\":\"Apu_Nahasapeemapetilon.png\"}," + "{\"id\":7,\"name\":\"Bart Simpsons\",\"imageName\":\"Bart_Simpsons.png\"}," + "{\"id\":8,\"name\":\"Homer Simpsons\",\"imageName\":\"Homer_Simpsons.png\"}," + "{\"id\":9,\"name\":\"Lisa Simpsons\",\"imageName\":\"Lisa_Simpsons.png\"}," + "{\"id\":2,\"name\":\"Maggie Simpsons\",\"imageName\":\"Maggie_Simpsons.png\"}," + "{\"id\":3,\"name\":\"Marge Simpsons\",\"imageName\":\"Marge_Simpsons.png\"}," + "{\"id\":4,\"name\":\"Montgomery Burns\",\"imageName\":\"Montgomery_Burns.png\"}," + "{\"id\":5,\"name\":\"Ned Flanders\",\"imageName\":\"Ned_Flanders.png\"}," + "{\"id\":6,\"name\":\"Otto Mann\",\"imageName\":\"Otto_Mann.png\"}]" let jsonData = dataString.data(using: String.Encoding.utf8, allowLossyConversion: true) do { let result = try JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions()) as! Array<AnyObject> return result } catch let error as NSError { print("\(error)") } return nil }() class var sharedInstance: UsersJSONSerialization { return _UsersJSONSerializationSharedInstance } } class User: NSObject, XLFormOptionObject { let userId: Int let userName : String let userImage: String init(userId: Int, userName: String, userImage: String){ self.userId = userId self.userImage = userImage self.userName = userName } func formDisplayText() -> String { return self.userName } func formValue() -> Any { return self.userId as Any } } class UsersTableViewController : UITableViewController, XLFormRowDescriptorViewController { var rowDescriptor : XLFormRowDescriptor? var userCell : UserCell? fileprivate let kUserCellIdentifier = "UserCell" override init(style: UITableViewStyle) { super.init(style: style); } override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() tableView.register(UserCell.self, forCellReuseIdentifier: kUserCellIdentifier) tableView.tableFooterView = UIView(frame: CGRect.zero) } // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return UsersJSONSerialization.sharedInstance.userData!.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UserCell = tableView.dequeueReusableCell(withIdentifier: self.kUserCellIdentifier, for: indexPath) as! UserCell let usersData = UsersJSONSerialization.sharedInstance.userData! as! Array<Dictionary<String, AnyObject>> let userData = usersData[(indexPath as NSIndexPath).row] as Dictionary<String, AnyObject> let userId = userData["id"] as! Int cell.userName.text = userData["name"] as? String cell.userImage.image = UIImage(named: (userData["imageName"] as? String)!) if let value = rowDescriptor?.value { cell.accessoryType = ((value as? XLFormOptionObject)?.formValue() as? Int) == userId ? .checkmark : .none } return cell; } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 73.0 } //MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let usersData = UsersJSONSerialization.sharedInstance.userData! as! Array<Dictionary<String, AnyObject>> let userData = usersData[(indexPath as NSIndexPath).row] as Dictionary<String, AnyObject> let user = User(userId: (userData["id"] as! Int), userName: userData["name"] as! String, userImage: userData["imageName"] as! String) self.rowDescriptor!.value = user; if let popOver = self.presentedViewController, popOver.modalPresentationStyle == .popover { dismiss(animated: true, completion: nil) } else if parent is UINavigationController { navigationController?.popViewController(animated: true) } } }
mit
17cf144f6d4c16e65489476935fd3e46
37.349515
163
0.661392
4.802432
false
false
false
false
snailjj/iOSDemos
SnailSwiftDemos/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift
39
15664
// // UITableView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 4/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) #if !RX_NO_MODULE import RxSwift #endif import UIKit // Items extension Reactive where Base: UITableView { /** Binds sequences of elements to table view rows. - parameter source: Observable sequence of items. - parameter cellFactory: Transform between sequence elements and view cells. - returns: Disposable object that can be used to unbind. Example: let items = Observable.just([ "First Item", "Second Item", "Third Item" ]) items .bind(to: tableView.rx.items) { (tableView, row, element) in let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! cell.textLabel?.text = "\(element) @ row \(row)" return cell } .disposed(by: disposeBag) */ public func items<S: Sequence, O: ObservableType> (_ source: O) -> (_ cellFactory: @escaping (UITableView, Int, S.Iterator.Element) -> UITableViewCell) -> Disposable where O.E == S { return { cellFactory in let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory) return self.items(dataSource: dataSource)(source) } } /** Binds sequences of elements to table view rows. - parameter cellIdentifier: Identifier used to dequeue cells. - parameter source: Observable sequence of items. - parameter configureCell: Transform between sequence elements and view cells. - parameter cellType: Type of table view cell. - returns: Disposable object that can be used to unbind. Example: let items = Observable.just([ "First Item", "Second Item", "Third Item" ]) items .bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in cell.textLabel?.text = "\(element) @ row \(row)" } .disposed(by: disposeBag) */ public func items<S: Sequence, Cell: UITableViewCell, O : ObservableType> (cellIdentifier: String, cellType: Cell.Type = Cell.self) -> (_ source: O) -> (_ configureCell: @escaping (Int, S.Iterator.Element, Cell) -> Void) -> Disposable where O.E == S { return { source in return { configureCell in let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S> { (tv, i, item) in let indexPath = IndexPath(item: i, section: 0) let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell configureCell(i, item, cell) return cell } return self.items(dataSource: dataSource)(source) } } } /** Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation. This method will retain the data source for as long as the subscription isn't disposed (result `Disposable` being disposed). In case `source` observable sequence terminates successfully, the data source will present latest element until the subscription isn't disposed. - parameter dataSource: Data source used to transform elements to view cells. - parameter source: Observable sequence of items. - returns: Disposable object that can be used to unbind. Example let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Double>>() let items = Observable.just([ SectionModel(model: "First section", items: [ 1.0, 2.0, 3.0 ]), SectionModel(model: "Second section", items: [ 1.0, 2.0, 3.0 ]), SectionModel(model: "Third section", items: [ 1.0, 2.0, 3.0 ]) ]) dataSource.configureCell = { (dataSource, tv, indexPath, element) in let cell = tv.dequeueReusableCell(withIdentifier: "Cell")! cell.textLabel?.text = "\(element) @ row \(indexPath.row)" return cell } items .bind(to: tableView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) */ public func items< DataSource: RxTableViewDataSourceType & UITableViewDataSource, O: ObservableType> (dataSource: DataSource) -> (_ source: O) -> Disposable where DataSource.Element == O.E { return { source in // This is called for sideeffects only, and to make sure delegate proxy is in place when // data source is being bound. // This is needed because theoretically the data source subscription itself might // call `self.rx.delegate`. If that happens, it might cause weird side effects since // setting data source will set delegate, and UITableView might get into a weird state. // Therefore it's better to set delegate proxy first, just to be sure. _ = self.delegate // Strong reference is needed because data source is in use until result subscription is disposed return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak tableView = self.base] (_: RxTableViewDataSourceProxy, event) -> Void in guard let tableView = tableView else { return } dataSource.tableView(tableView, observedEvent: event) } } } } extension UITableView { /** Factory method that enables subclasses to implement their own `delegate`. - returns: Instance of delegate proxy that wraps `delegate`. */ public override func createRxDelegateProxy() -> RxScrollViewDelegateProxy { return RxTableViewDelegateProxy(parentObject: self) } /** Factory method that enables subclasses to implement their own `rx.dataSource`. - returns: Instance of delegate proxy that wraps `dataSource`. */ public func createRxDataSourceProxy() -> RxTableViewDataSourceProxy { return RxTableViewDataSourceProxy(parentObject: self) } } extension Reactive where Base: UITableView { /** Reactive wrapper for `dataSource`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var dataSource: DelegateProxy { return RxTableViewDataSourceProxy.proxyForObject(base) } /** Installs data source as forwarding delegate on `rx.dataSource`. Data source won't be retained. It enables using normal delegate mechanism with reactive delegate mechanism. - parameter dataSource: Data source object. - returns: Disposable object that can be used to unbind the data source. */ public func setDataSource(_ dataSource: UITableViewDataSource) -> Disposable { return RxTableViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base) } // events /** Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. */ public var itemSelected: ControlEvent<IndexPath> { let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didSelectRowAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. */ public var itemDeselected: ControlEvent<IndexPath> { let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didDeselectRowAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:accessoryButtonTappedForRowWithIndexPath:`. */ public var itemAccessoryButtonTapped: ControlEvent<IndexPath> { let source: Observable<IndexPath> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:accessoryButtonTappedForRowWith:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. */ public var itemInserted: ControlEvent<IndexPath> { let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:))) .filter { a in return UITableViewCellEditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .insert } .map { a in return (try castOrThrow(IndexPath.self, a[2])) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. */ public var itemDeleted: ControlEvent<IndexPath> { let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:))) .filter { a in return UITableViewCellEditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .delete } .map { a in return try castOrThrow(IndexPath.self, a[2]) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`. */ public var itemMoved: ControlEvent<ItemMovedEvent> { let source: Observable<ItemMovedEvent> = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:moveRowAt:to:))) .map { a in return (try castOrThrow(IndexPath.self, a[1]), try castOrThrow(IndexPath.self, a[2])) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:willDisplayCell:forRowAtIndexPath:`. */ public var willDisplayCell: ControlEvent<WillDisplayCellEvent> { let source: Observable<WillDisplayCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:willDisplay:forRowAt:))) .map { a in return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:didEndDisplayingCell:forRowAtIndexPath:`. */ public var didEndDisplayingCell: ControlEvent<DidEndDisplayingCellEvent> { let source: Observable<DidEndDisplayingCellEvent> = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didEndDisplaying:forRowAt:))) .map { a in return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, or any other data source conforming to `SectionedViewDataSourceType` protocol. ``` tableView.rx.modelSelected(MyModel.self) .map { ... ``` */ public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = self.itemSelected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in guard let view = view else { return Observable.empty() } return Observable.just(try view.rx.model(at: indexPath)) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, or any other data source conforming to `SectionedViewDataSourceType` protocol. ``` tableView.rx.modelDeselected(MyModel.self) .map { ... ``` */ public func modelDeselected<T>(_ modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = self.itemDeselected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in guard let view = view else { return Observable.empty() } return Observable.just(try view.rx.model(at: indexPath)) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, or any other data source conforming to `SectionedViewDataSourceType` protocol. ``` tableView.rx.modelDeleted(MyModel.self) .map { ... ``` */ public func modelDeleted<T>(_ modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = self.itemDeleted.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in guard let view = view else { return Observable.empty() } return Observable.just(try view.rx.model(at: indexPath)) } return ControlEvent(events: source) } /** Synchronous helper method for retrieving a model at indexPath through a reactive data source. */ public func model<T>(at indexPath: IndexPath) throws -> T { let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.items*` methods was used.") let element = try dataSource.model(at: indexPath) return castOrFatalError(element) } } #endif #if os(tvOS) extension Reactive where Base: UITableView { /** Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`. */ public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { let source = delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:))) .map { a -> (context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in let context = a[1] as! UIFocusUpdateContext let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2]) return (context: context, animationCoordinator: animationCoordinator) } return ControlEvent(events: source) } } #endif
apache-2.0
ea4d91f69f72fd1b8b927e85bf3adb6c
36.292857
200
0.625295
5.307692
false
false
false
false
mikaelbo/MBFacebookImagePicker
MBFacebookImagePicker/Entities/MBFacebookPicture.swift
1
1505
// // MBFacebookPicture.swift // FacebookImagePicker // // Copyright © 2017 Mikaelbo. All rights reserved. // import UIKit class MBFacebookImageURL: NSObject { let url: URL let imageSize: CGSize init(url: URL, imageSize: CGSize) { self.url = url self.imageSize = imageSize super.init() } } class MBFacebookPicture: NSObject { let thumbURL: URL let fullURL: URL let albumId: String let uid: String? let sourceImages: [MBFacebookImageURL] init(thumbURL: URL, fullURL: URL, albumId: String, uid: String?, sourceImages: [MBFacebookImageURL]) { self.thumbURL = thumbURL self.fullURL = fullURL self.albumId = albumId self.uid = uid self.sourceImages = sourceImages super.init() } func bestURLForSize(size: CGSize) -> URL { guard var bestImageURL = sourceImages.first else { return self.thumbURL } for imageURL in sourceImages { let currentFoundSize = bestImageURL.imageSize let sizeIsAcceptable = imageURL.imageSize.width >= size.width && imageURL.imageSize.height >= size.height let imageTotal = imageURL.imageSize.width * imageURL.imageSize.height let currentImageTotal = currentFoundSize.width * currentFoundSize.height if sizeIsAcceptable && imageTotal < currentImageTotal { bestImageURL = imageURL } } return bestImageURL.url } }
mit
884e85b24c127c580152ba9f2899b0be
26.851852
117
0.636303
4.47619
false
false
false
false
jmgc/swift
test/attr/attr_specialize.swift
1
15027
// RUN: %target-typecheck-verify-swift -enable-experimental-prespecialization // RUN: %target-swift-ide-test -enable-experimental-prespecialization -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module | %FileCheck %s struct S<T> {} public protocol P { } extension Int: P { } public protocol ProtocolWithDep { associatedtype Element } public class C1 { } class Base {} class Sub : Base {} class NonSub {} // Specialize freestanding functions with the correct number of concrete types. // ---------------------------------------------------------------------------- // CHECK: @_specialize(exported: false, kind: full, where T == Int) @_specialize(where T == Int) // CHECK: @_specialize(exported: false, kind: full, where T == S<Int>) @_specialize(where T == S<Int>) @_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}}, // expected-error@-1{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}} @_specialize(where T == T1) // expected-error{{cannot find type 'T1' in scope}} public func oneGenericParam<T>(_ t: T) -> T { return t } // CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Int) @_specialize(where T == Int, U == Int) @_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'U' in '_specialize' attribute}} public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) { return (t, u) } @_specialize(where T == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'nonGenericParam(x:)'}} func nonGenericParam(x: Int) {} // Specialize contextual types. // ---------------------------- class G<T> { // CHECK: @_specialize(exported: false, kind: full, where T == Int) @_specialize(where T == Int) @_specialize(where T == T) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}} @_specialize(where T == S<T>) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}} @_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}} // expected-error@-1{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}} func noGenericParams() {} // CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Float) @_specialize(where T == Int, U == Float) // CHECK: @_specialize(exported: false, kind: full, where T == Int, U == S<Int>) @_specialize(where T == Int, U == S<Int>) @_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error {{Missing constraint for 'U' in '_specialize' attribute}} func oneGenericParam<U>(_ t: T, u: U) -> (U, T) { return (u, t) } } // Specialize with requirements. // ----------------------------- protocol Thing {} struct AThing : Thing {} // CHECK: @_specialize(exported: false, kind: full, where T == AThing) @_specialize(where T == AThing) @_specialize(where T == Int) // expected-error{{same-type constraint type 'Int' does not conform to required protocol 'Thing'}} func oneRequirement<T : Thing>(_ t: T) {} protocol HasElt { associatedtype Element } struct IntElement : HasElt { typealias Element = Int } struct FloatElement : HasElt { typealias Element = Float } @_specialize(where T == FloatElement) @_specialize(where T == IntElement) // expected-error{{'T.Element' cannot be equal to both 'IntElement.Element' (aka 'Int') and 'Float'}} func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {} @_specialize(where T == Sub) @_specialize(where T == NonSub) // expected-error{{'T' requires that 'NonSub' inherit from 'Base'}} func superTypeRequirement<T : Base>(_ t: T) {} @_specialize(where X:_Trivial(8), Y == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'requirementOnNonGenericFunction(x:y:)'}} public func requirementOnNonGenericFunction(x: Int, y: Int) { } @_specialize(where Y == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} public func missingRequirement<X:P, Y>(x: X, y: Y) { } @_specialize(where) // expected-error{{expected type}} @_specialize() // expected-error{{expected a parameter label or a where clause in '_specialize' attribute}} expected-error{{expected declaration}} public func funcWithEmptySpecializeAttr<X: P, Y>(x: X, y: Y) { } @_specialize(where X:_Trivial(8), Y:_Trivial(32), Z == Int) // expected-error{{cannot find type 'Z' in scope}} // expected-error@-1{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}} @_specialize(where X:_Trivial(8), Y:_Trivial(32, 4)) @_specialize(where X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}} @_specialize(where Y:_Trivial(32)) // expected-error {{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} @_specialize(where Y: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} @_specialize(where Y: MyClass) // expected-error{{cannot find type 'MyClass' in scope}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} // expected-error@-1{{Only conformances to protocol types are supported by '_specialize' attribute}} @_specialize(where X:_Trivial(8), Y == Int) @_specialize(where X == Int, Y == Int) @_specialize(where X == Int, X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}} // expected-warning@-1{{redundant same-type constraint 'X' == 'Int'}} // expected-note@-2{{same-type constraint 'X' == 'Int' written here}} @_specialize(where Y:_Trivial(32), X == Float) @_specialize(where X1 == Int, Y1 == Int) // expected-error{{cannot find type 'X1' in scope}} expected-error{{cannot find type 'Y1' in scope}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}} // expected-error@-1 2{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}} public func funcWithTwoGenericParameters<X, Y>(x: X, y: Y) { } @_specialize(where X == Int, Y == Int) @_specialize(exported: true, where X == Int, Y == Int) @_specialize(exported: false, where X == Int, Y == Int) @_specialize(exported: false where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}} @_specialize(exported: yes, where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}} @_specialize(exported: , where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}} @_specialize(kind: partial, where X == Int, Y == Int) @_specialize(kind: partial, where X == Int) @_specialize(kind: full, where X == Int, Y == Int) @_specialize(kind: any, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}} @_specialize(kind: false, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}} @_specialize(kind: partial where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}} @_specialize(kind: partial, where X == Int, Y == Int) @_specialize(kind: , where X == Int, Y == Int) @_specialize(exported: true, kind: partial, where X == Int, Y == Int) @_specialize(exported: true, exported: true, where X == Int, Y == Int) // expected-error{{parameter 'exported' was already defined in '_specialize' attribute}} @_specialize(kind: partial, exported: true, where X == Int, Y == Int) @_specialize(kind: partial, kind: partial, where X == Int, Y == Int) // expected-error{{parameter 'kind' was already defined in '_specialize' attribute}} @_specialize(where X == Int, Y == Int, exported: true, kind: partial) // expected-error{{cannot find type 'exported' in scope}} expected-error{{cannot find type 'kind' in scope}} expected-error{{cannot find type 'partial' in scope}} expected-error{{expected type}} // expected-error@-1 2{{Only conformances to protocol types are supported by '_specialize' attribute}} public func anotherFuncWithTwoGenericParameters<X: P, Y>(x: X, y: Y) { } @_specialize(where T: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} @_specialize(where T: Int) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} @_specialize(where T: S1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} @_specialize(where T: C1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} @_specialize(where Int: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 1)}} expected-error{{Missing constraint for 'T' in '_specialize' attribute}} func funcWithForbiddenSpecializeRequirement<T>(_ t: T) { } @_specialize(where T: _Trivial(32), T: _Trivial(64), T: _Trivial, T: _RefCountedObject) // expected-error@-1{{generic parameter 'T' has conflicting constraints '_Trivial(64)' and '_Trivial(32)'}} // expected-error@-2{{generic parameter 'T' has conflicting constraints '_RefCountedObject' and '_Trivial(32)'}} // expected-warning@-3{{redundant constraint 'T' : '_Trivial'}} // expected-note@-4 3{{constraint 'T' : '_Trivial(32)' written here}} @_specialize(where T: _Trivial, T: _Trivial(64)) // expected-warning@-1{{redundant constraint 'T' : '_Trivial'}} // expected-note@-2 1{{constraint 'T' : '_Trivial(64)' written here}} @_specialize(where T: _RefCountedObject, T: _NativeRefCountedObject) // expected-warning@-1{{redundant constraint 'T' : '_RefCountedObject'}} // expected-note@-2 1{{constraint 'T' : '_NativeRefCountedObject' written here}} @_specialize(where Array<T> == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}} @_specialize(where T.Element == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}} public func funcWithComplexSpecializeRequirements<T: ProtocolWithDep>(t: T) -> Int { return 55555 } public protocol Proto: class { } @_specialize(where T: _RefCountedObject) @_specialize(where T: _Trivial) // expected-error@-1{{generic parameter 'T' has conflicting constraints '_Trivial' and '_NativeClass'}} @_specialize(where T: _Trivial(64)) // expected-error@-1{{generic parameter 'T' has conflicting constraints '_Trivial(64)' and '_NativeClass'}} public func funcWithABaseClassRequirement<T>(t: T) -> Int where T: C1 { return 44444 } public struct S1 { } @_specialize(exported: false, where T == Int64) public func simpleGeneric<T>(t: T) -> T { return t } @_specialize(exported: true, where S: _Trivial(64)) // Check that any bitsize size is OK, not only powers of 8. @_specialize(where S: _Trivial(60)) @_specialize(exported: true, where S: _RefCountedObject) @inline(never) public func copyValue<S>(_ t: S, s: inout S) -> Int64 where S: P{ return 1 } @_specialize(exported: true, where S: _Trivial) @_specialize(exported: true, where S: _Trivial(64)) @_specialize(exported: true, where S: _Trivial(32)) @_specialize(exported: true, where S: _RefCountedObject) @_specialize(exported: true, where S: _NativeRefCountedObject) @_specialize(exported: true, where S: _Class) @_specialize(exported: true, where S: _NativeClass) @inline(never) public func copyValueAndReturn<S>(_ t: S, s: inout S) -> S where S: P{ return s } struct OuterStruct<S> { struct MyStruct<T> { @_specialize(where T == Int, U == Float) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 2, but expected 3)}} expected-error{{Missing constraint for 'S' in '_specialize' attribute}} public func foo<U>(u : U) { } @_specialize(where T == Int, U == Float, S == Int) public func bar<U>(u : U) { } } } // Check _TrivialAtMostN constraints. @_specialize(exported: true, where S: _TrivialAtMost(64)) @inline(never) public func copy2<S>(_ t: S, s: inout S) -> S where S: P{ return s } // Check missing alignment. @_specialize(where S: _Trivial(64, )) // expected-error{{expected non-negative alignment to be specified in layout constraint}} // Check non-numeric size. @_specialize(where S: _Trivial(Int)) // expected-error{{expected non-negative size to be specified in layout constraint}} // Check non-numeric alignment. @_specialize(where S: _Trivial(64, X)) // expected-error{{expected non-negative alignment to be specified in layout constraint}} @inline(never) public func copy3<S>(_ s: S) -> S { return s } public func funcWithWhereClause<T>(t: T) where T:P, T: _Trivial(64) { // expected-error{{layout constraints are only allowed inside '_specialize' attributes}} } // rdar://problem/29333056 public protocol P1 { associatedtype DP1 associatedtype DP11 } public protocol P2 { associatedtype DP2 : P1 } public struct H<T> { } public struct MyStruct3 : P1 { public typealias DP1 = Int public typealias DP11 = H<Int> } public struct MyStruct4 : P2 { public typealias DP2 = MyStruct3 } @_specialize(where T==MyStruct4) public func foo<T: P2>(_ t: T) where T.DP2.DP11 == H<T.DP2.DP1> { } public func targetFun<T>(_ t: T) {} @_specialize(exported: true, target: targetFun(_:), where T == Int) public func specifyTargetFunc<T>(_ t: T) { } public struct Container { public func targetFun<T>(_ t: T) {} } extension Container { @_specialize(exported: true, target: targetFun(_:), where T == Int) public func specifyTargetFunc<T>(_ t: T) { } @_specialize(exported: true, target: targetFun2(_:), where T == Int) // expected-error{{target function 'targetFun2' could not be found}} public func specifyTargetFunc2<T>(_ t: T) { } }
apache-2.0
84d988a38534b0c5b060f3640f9a87cc
49.257525
392
0.699142
3.701232
false
false
false
false
kafejo/Tracker-Aggregator
TrackerAggregatorTests/TrackerAggregatorTests.swift
1
7865
// // TrackerAggregatorTests.swift // TrackerAggregatorTests // // Created by Ales Kocur on 25/08/2017. // Copyright © 2017 Rubicoin Ltd. All rights reserved. // import XCTest @testable import TrackerAggregator class TestableTracker: AnalyticsAdapter { var eventTrackingRule: EventTrackingRule? = nil var propertyTrackingRule: PropertyTrackingRule? = nil var trackedEvent: TrackableEvent? { didSet { trackedEventCallback?() } } var trackedEventCallback: (() -> Void)? = nil func track(event: TrackableEvent) { trackedEvent = event } var trackedPropertyCallback: (() -> Void)? = nil var trackedProperty: TrackableProperty? { didSet { trackedPropertyCallback?() } } func track(property: TrackableProperty) { trackedProperty = property } func configure() { sleep(1) } } struct TestEvent: TrackableEvent { let identifier: EventIdentifier = EventIdentifier(object: "Id", action: "Test") let metadata: [String : Any] = ["test": "m1"] } struct TestEvent2: TrackableEvent { let identifier: EventIdentifier = EventIdentifier(object: "Id2", action: "Test2") let metadata: [String : Any] = ["test": "m1"] } struct TestProperty: TrackableProperty { let identifier: String = "name" let value: String var trackedValue: TrackableValueType? { return value } } struct TestUpdateProperty: TrackableProperty { let identifier: String = "name2" let value: String var trackedValue: TrackableValueType? { return value } func generateUpdateEvents() -> [TrackableEvent] { return [TestEvent()] } } class TrackerAggregatorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testEventTracking() { // given let testableAdapter = TestableTracker() let testEvent = TestEvent() let globalTracker = GlobalTracker() // when globalTracker.set(adapters: [testableAdapter]) globalTracker.configureAdapters() // then let exp = expectation(description: "Test") testableAdapter.trackedEventCallback = { XCTAssertNotNil(testableAdapter.trackedEvent, "Event wasn't tracked") XCTAssertEqual(testableAdapter.trackedEvent?.identifier.formatted ?? "", "Id: Test") XCTAssertEqual((testableAdapter.trackedEvent?.metadata["test"] as? String) ?? "", "m1") exp.fulfill() } globalTracker.track(event: testEvent) self.waitForExpectations(timeout: 2.0) } func testUserPropertyTracking() { // given let testableAdapter = TestableTracker() let testProperty = TestProperty(value: "New Name") let globalTracker = GlobalTracker() // when globalTracker.set(adapters: [testableAdapter]) globalTracker.configureAdapters() // then let exp = expectation(description: "Test") testableAdapter.trackedPropertyCallback = { XCTAssertNotNil(testableAdapter.trackedProperty, "Property wasn't tracked") XCTAssertEqual(testableAdapter.trackedProperty?.identifier ?? "", "name") XCTAssertEqual((testableAdapter.trackedProperty?.trackedValue as? String) ?? "", "New Name") exp.fulfill() } globalTracker.update(property: testProperty) self.waitForExpectations(timeout: 2.0) } func testUpdateEvents() { // given let testProperty = TestUpdateProperty(value: "New Email") let testableAdapter = TestableTracker() let globalTracker = GlobalTracker() // when globalTracker.set(adapters: [testableAdapter]) globalTracker.configureAdapters() // then let exp = expectation(description: "Test") testableAdapter.trackedEventCallback = { XCTAssertNotNil(testableAdapter.trackedEvent, "Property wasn't tracked") XCTAssertEqual(testableAdapter.trackedEvent?.identifier.formatted ?? "", "Id: Test") XCTAssertEqual((testableAdapter.trackedEvent?.metadata["test"] as? String) ?? "", "m1") exp.fulfill() } globalTracker.update(property: testProperty) self.waitForExpectations(timeout: 2.0) } func testProhibitEventRule() { // given let testableAdapter = TestableTracker() let eventRule = EventTrackingRule(.prohibit, types: [TestEvent.self]) testableAdapter.eventTrackingRule = eventRule let event = TestEvent() let globalTracker = GlobalTracker() globalTracker.set(adapters: [testableAdapter]) // when globalTracker.track(event: event) globalTracker.configureAdapters() // then let exp = expectation(description: "Test") exp.isInverted = true testableAdapter.trackedEventCallback = { XCTAssertNil(testableAdapter.trackedEvent, "Property was tracked even when rulled out") exp.fulfill() } self.waitForExpectations(timeout: 2.0) } func testAllowEventRule() { // given let testableAdapter = TestableTracker() let eventRule = EventTrackingRule(.allow, types: [TestEvent.self]) testableAdapter.eventTrackingRule = eventRule let event = TestEvent() let globalTracker = GlobalTracker() globalTracker.set(adapters: [testableAdapter]) globalTracker.configureAdapters() // then let exp = expectation(description: "Test") testableAdapter.trackedEventCallback = { XCTAssertNotNil(testableAdapter.trackedEvent, "Property wasn't tracked") exp.fulfill() } globalTracker.track(event: event) self.waitForExpectations(timeout: 2.0) } func testProhibitPropertyRule() { // given let testableAdapter = TestableTracker() let propertyRule = PropertyTrackingRule(.prohibit, types: [TestProperty.self]) testableAdapter.propertyTrackingRule = propertyRule let prohibitedProperty = TestProperty(value: "New Value") let globalTracker = GlobalTracker() globalTracker.set(adapters: [testableAdapter]) // when globalTracker.update(property: prohibitedProperty) // then let exp = expectation(description: "Test") exp.isInverted = true testableAdapter.trackedPropertyCallback = { XCTAssertNil(testableAdapter.trackedProperty, "Property was tracked even when rulled out") exp.fulfill() } self.waitForExpectations(timeout: 2.0) } func testAllowPropertyRule() { // given let testableAdapter = TestableTracker() let propertyRule = PropertyTrackingRule(.allow, types: [TestProperty.self]) testableAdapter.propertyTrackingRule = propertyRule let prohibitedProperty = TestUpdateProperty(value: "New Value") let globalTracker = GlobalTracker() globalTracker.set(adapters: [testableAdapter]) // when globalTracker.update(property: prohibitedProperty) // then let exp = expectation(description: "Test") exp.isInverted = true testableAdapter.trackedPropertyCallback = { XCTAssertNil(testableAdapter.trackedProperty, "Property was tracked even when rulled out") exp.fulfill() } self.waitForExpectations(timeout: 2.0) } }
mit
c572aeb2f70d89c097c97af9329d75bf
28.675472
111
0.644837
4.809786
false
true
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AAAuthNameViewController.swift
2
4107
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation public class AAAuthNameViewController: AAAuthViewController { let transactionHash: String? let scrollView = UIScrollView() let welcomeLabel = UILabel() let field = UITextField() let fieldLine = UIView() var isFirstAppear = true public init(transactionHash: String? = nil) { self.transactionHash = transactionHash super.init(nibName: nil, bundle: nil) navigationItem.leftBarButtonItem = UIBarButtonItem(title: AALocalized("NavigationCancel"), style: .Plain, target: self, action: #selector(AAViewController.dismiss)) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { view.backgroundColor = UIColor.whiteColor() scrollView.keyboardDismissMode = .OnDrag scrollView.scrollEnabled = true scrollView.alwaysBounceVertical = true welcomeLabel.font = UIFont.lightSystemFontOfSize(23) welcomeLabel.text = AALocalized("AuthNameTitle") welcomeLabel.textColor = ActorSDK.sharedActor().style.authTitleColor welcomeLabel.textAlignment = .Center field.placeholder = AALocalized("AuthNamePlaceholder") field.keyboardType = .Default field.autocapitalizationType = .Words field.textColor = ActorSDK.sharedActor().style.authTextColor field.addTarget(self, action: #selector(AAAuthNameViewController.fieldDidChanged), forControlEvents: .EditingChanged) fieldLine.backgroundColor = ActorSDK.sharedActor().style.authSeparatorColor fieldLine.opaque = false scrollView.addSubview(welcomeLabel) scrollView.addSubview(fieldLine) scrollView.addSubview(field) view.addSubview(scrollView) super.viewDidLoad() } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() welcomeLabel.frame = CGRectMake(15, 90 - 66, view.width - 30, 28) fieldLine.frame = CGRectMake(10, 200 - 66, view.width - 20, 0.5) field.frame = CGRectMake(20, 156 - 66, view.width - 40, 44) scrollView.frame = view.bounds scrollView.contentSize = CGSizeMake(view.width, 240 - 66) } func fieldDidChanged() { // if field.text!.trim().length > 0 { // fieldSuccess.hidden = false // } else { // fieldSuccess.hidden = true // } } public override func nextDidTap() { let name = field.text!.trim() if name.length > 0 { if transactionHash != nil { let promise = Actor.doSignupWithName(name, withSex: ACSex.UNKNOWN(), withTransaction: transactionHash!) promise.then { (r: ACAuthRes!) -> () in let promise = Actor.doCompleteAuth(r).startUserAction() promise.then { (r: JavaLangBoolean!) -> () in self.onAuthenticated() } } promise.startUserAction() } else { if ActorSDK.sharedActor().authStrategy == .PhoneOnly || ActorSDK.sharedActor().authStrategy == .PhoneEmail { navigateNext(AAAuthPhoneViewController(name: name)) } else { navigateNext(AAAuthEmailViewController(name: name)) } } } else { shakeView(field, originalX: 20) shakeView(fieldLine, originalX: 10) } } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if isFirstAppear { isFirstAppear = false field.becomeFirstResponder() } } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) field.resignFirstResponder() } }
agpl-3.0
a9fbe43c250d2844aeb575d7c0e470bb
33.521008
172
0.602873
5.166038
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsComponents/SwitchTableViewCell/SwitchCellPresenter.swift
1
3526
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import FeatureSettingsDomain import Localization import PlatformKit import PlatformUIKit import RxSwift import ToolKit protocol SwitchCellPresenting { var accessibility: Accessibility { get } var labelContentPresenting: LabelContentPresenting { get } var switchViewPresenting: SwitchViewPresenting { get } } class EmailNotificationsSwitchCellPresenter: SwitchCellPresenting { private typealias AccessibilityId = Accessibility.Identifier.Settings.SettingsCell let accessibility: Accessibility = .id(AccessibilityId.EmailNotifications.title) let labelContentPresenting: LabelContentPresenting let switchViewPresenting: SwitchViewPresenting init(service: EmailNotificationSettingsServiceAPI) { labelContentPresenting = DefaultLabelContentPresenter( knownValue: LocalizationConstants.Settings.emailNotifications, descriptors: .settings ) switchViewPresenting = EmailSwitchViewPresenter(service: service) } } class CloudBackupSwitchCellPresenter: SwitchCellPresenting { private typealias AccessibilityId = Accessibility.Identifier.Settings.SettingsCell.CloudBackup private typealias LocalizedString = LocalizationConstants.Settings let accessibility: Accessibility = .id(AccessibilityId.title) let labelContentPresenting: LabelContentPresenting let switchViewPresenting: SwitchViewPresenting init(appSettings: BlockchainSettings.App, credentialsStore: CredentialsStoreAPI) { labelContentPresenting = DefaultLabelContentPresenter( knownValue: LocalizationConstants.Settings.cloudBackup, descriptors: .settings ) switchViewPresenting = CloudBackupSwitchViewPresenter( appSettings: appSettings, credentialsStore: credentialsStore ) } } class SMSTwoFactorSwitchCellPresenter: SwitchCellPresenting { private typealias AccessibilityId = Accessibility.Identifier.Settings.SettingsCell let accessibility: Accessibility = .id(AccessibilityId.TwoStepVerification.title) let labelContentPresenting: LabelContentPresenting let switchViewPresenting: SwitchViewPresenting init(service: SMSTwoFactorSettingsServiceAPI & SettingsServiceAPI) { labelContentPresenting = DefaultLabelContentPresenter( knownValue: LocalizationConstants.Settings.twoFactorAuthentication, descriptors: .settings ) switchViewPresenting = SMSSwitchViewPresenter(service: service) } } class BioAuthenticationSwitchCellPresenter: SwitchCellPresenting { private typealias AccessibilityId = Accessibility.Identifier.Settings.SettingsCell let accessibility: Accessibility = .id(AccessibilityId.BioAuthentication.title) let labelContentPresenting: LabelContentPresenting let switchViewPresenting: SwitchViewPresenting init( biometryProviding: BiometryProviding, appSettingsAuthenticating: AppSettingsAuthenticating, authenticationCoordinator: AuthenticationCoordinating ) { labelContentPresenting = BiometryLabelContentPresenter( provider: biometryProviding, descriptors: .settings ) switchViewPresenting = BiometrySwitchViewPresenter( provider: biometryProviding, settingsAuthenticating: appSettingsAuthenticating, authenticationCoordinator: authenticationCoordinator ) } }
lgpl-3.0
facba7f921872b81f3c52968b5202c23
36.105263
98
0.769929
6.088083
false
false
false
false
pdcgomes/RendezVous
RendezVous/LocalizedFileMerger.swift
1
10107
// // Merger.swift // RendezVous // // Created by Pedro Gomes on 31/07/2015. // Copyright © 2015 Pedro Gomes. All rights reserved. // import Foundation //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// class LocalizedFileMerger { let tracker: ChangeTracker //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// init(tracker: ChangeTracker) { self.tracker = tracker } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func checkDirectoryExists(path: String) -> Bool { let fileManager = NSFileManager.defaultManager() var isDir = ObjCBool(false) guard fileManager.fileExistsAtPath(path, isDirectory: &isDir) && isDir else { print("Invalid directory \(path)") return false } return true } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func checkIfIsStringsFile(file: NSURL) -> Bool { do { let fileWrapper = try NSFileWrapper(URL:file, options: []) return fileWrapper.directory == false && file.pathExtension == "strings" } catch { return false } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func findAndMerge(pathForGeneratedStrings: String, pathForTranslatedStrings: String) -> Bool { guard checkDirectoryExists(pathForGeneratedStrings) && checkDirectoryExists(pathForTranslatedStrings) else { return false } var generated = findStringsFilesAtPath(pathForGeneratedStrings) let langFolders = findLanguageFoldersAtPath(pathForTranslatedStrings) //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func reloadLanguageFiles() -> ([LocalizedFile], Dictionary<String, [LocalizedFile]>) { var translationFileList = [LocalizedFile]() var translationFileListByLanguage = Dictionary<String, [LocalizedFile]>(); for folder in langFolders { let files = findStringsFilesAtPath(folder) translationFileListByLanguage[folder] = files translationFileList += files } return (translationFileList, translationFileListByLanguage) } let (translationFileList, translationFileListByFolder) = reloadLanguageFiles() //////////////////////////////////////////////////////////////////////////////// // 1) Copy missing files //////////////////////////////////////////////////////////////////////////////// func extractPaths(files: [LocalizedFile]) -> Set<String> { return Set(files.map({ (file) -> String in return file.name })) } let fileManager = NSFileManager.defaultManager() let fromFiles = extractPaths(generated) var createdFileCount = 0 for (folder, files) in translationFileListByFolder { let existing = extractPaths(files) let filesToCreateList = fromFiles.subtract(existing) createdFileCount += filesToCreateList.count for file in filesToCreateList { let nameAndExtension = (file as NSString).lastPathComponent let createAtPath = (folder as NSString).stringByAppendingPathComponent(nameAndExtension) let copyFromPath = (pathForGeneratedStrings as NSString).stringByAppendingPathComponent(nameAndExtension) do { try fileManager.copyItemAtPath(copyFromPath, toPath: createAtPath) print("--> created \(createAtPath) ...") } catch {} } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// for var file in generated { do { try file.read() var mergeWithFiles = [LocalizedFile]() for (_, files) in translationFileListByFolder { let matches = files.filter({ (translatedFile: LocalizedFile) -> Bool in return translatedFile.name == file.name }) for match in matches { mergeWithFiles.append(match) } } for var mergeToFile in mergeWithFiles { try mergeToFile.read() doMergeFile(file, withFile: mergeToFile) } } catch { print("Oops, something went wrong") } } return true } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func doMergeFile(file: LocalizedFile, withFile: LocalizedFile) -> Bool { let fromKeys = file.allKeys() let toKeys = withFile.allKeys() var copy = withFile let deletedKeys = toKeys.subtract(fromKeys) var shouldSave = deletedKeys.count > 0 for key in deletedKeys { copy.removeKey(key) tracker.trackChange(withFile.path, change: Change(type: .Deleted, key: key)) } var createdKeys: [String] = [] var updatedKeys: [String] = [] for fromKey in fromKeys { let line = file[fromKey]! if let translatedLine = copy[fromKey] { // The key already existed, so we check for comment updates if translatedLine.comment != line.comment { shouldSave = true copy.add(LocalizedString(key: translatedLine.key, value: translatedLine.value, comment: line.comment)) updatedKeys.append(translatedLine.key) tracker.trackChange(withFile.path, change: Change( type: .Changed, key: line.key, newValue: line.comment.joinWithSeparator(""))) } } else { shouldSave = true copy.add(LocalizedString(key: line.key, value: line.value, comment: line.comment)) createdKeys.append(line.key) tracker.trackChange( withFile.path, change: Change(type: .Created, key: line.key, newValue: line.value)) } } guard shouldSave == true else { return true } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// do { try copy.toString().writeToFile(withFile.path, atomically: true, encoding: withFile.encoding.toStringEncoding()) } catch { tracker.trackError(withFile.path, error: NSError(domain: "", code: 1010, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Failed to save file", comment: "")])) } return true; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func findStringsFilesAtPath(path: String) -> [LocalizedFile] { var files: [LocalizedFile] = [] let fileManager = NSFileManager.defaultManager() let detector = FileEncodingDetector() do { let contentsOfDirectory = try fileManager.contentsOfDirectoryAtURL(NSURL.fileURLWithPath(path, isDirectory: true), includingPropertiesForKeys: [NSURLIsRegularFileKey], options: []) for file in contentsOfDirectory { if checkIfIsStringsFile(file) { let encoding = detector.detectEncodingForFileAtPath(path: file.path!) files.append(LocalizedFile(path: file.path!, encoding: encoding)) } } } catch {} return files } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// func findLanguageFoldersAtPath(path: String) -> [String] { do { let fileManager = NSFileManager.defaultManager() let folders = try fileManager.contentsOfDirectoryAtURL(NSURL(string: path)!, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: []) var paths = [String]() for folder in folders { if let path = folder.path { let isLanguageFolder = (path as NSString).lastPathComponent.hasSuffix(".lproj") if isLanguageFolder { paths.append(path) } } } return paths } catch { return [] } } }
mit
da070f43a111d8619b577ad95b2d45f7
39.75
192
0.426776
6.814565
false
false
false
false
toshiapp/toshi-ios-client
Tests/PaymentManagerTests.swift
1
4570
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. @testable import Toshi import XCTest import Foundation import Teapot class PaymentManagerTests: XCTestCase { func testPaymentInformation() { let mockTeapot = MockTeapot(bundle: Bundle(for: PaymentManagerTests.self), mockFilename: "transactionSkeleton") mockTeapot.overrideEndPoint(Cereal.shared.paymentAddress, withFilename: "getHighBalance") let parameters: [String: Any] = [ "from": "0x011c6dd9565b8b83e6a9ee3f06e89ece3251ef2f", "to": "0x011c6dd9565b8b83e6a9ee3f06e89ece3251ef2f", "value": "0x330a41d05c8a780a" ] let paymentManager = PaymentManager(parameters: parameters, mockTeapot: mockTeapot, exchangeRate: 10) let expectation = XCTestExpectation(description: "Get payment Info") paymentManager.fetchPaymentInfo { paymentInfo in XCTAssertEqual(paymentInfo.totalEthereumString, "3.6787 ETH") XCTAssertEqual(paymentInfo.totalFiatString, "$36.79 USD") XCTAssertEqual(paymentInfo.estimatedFeesFiatString, "$0.01 USD") XCTAssertEqual(paymentInfo.fiatString, "$36.78 USD") XCTAssertEqual(paymentInfo.balanceString, "$110.68 USD") XCTAssertTrue(paymentInfo.sufficientBalance) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) } func testPaymentInformationInsufficientBalance() { let mockTeapot = MockTeapot(bundle: Bundle(for: PaymentManagerTests.self), mockFilename: "transactionSkeleton") mockTeapot.overrideEndPoint(Cereal.shared.paymentAddress, withFilename: "getLowBalance") let parameters: [String: Any] = [ "from": "0x011c6dd9565b8b83e6a9ee3f06e89ece3251ef2f", "to": "0x011c6dd9565b8b83e6a9ee3f06e89ece3251ef2f", "value": "0x330a41d05c8a780a" ] let paymentManager = PaymentManager(parameters: parameters, mockTeapot: mockTeapot, exchangeRate: 10) let expectation = XCTestExpectation(description: "Get payment Info") paymentManager.fetchPaymentInfo { paymentInfo in XCTAssertEqual(paymentInfo.totalEthereumString, "3.6787 ETH") XCTAssertEqual(paymentInfo.totalFiatString, "$36.79 USD") XCTAssertEqual(paymentInfo.estimatedFeesFiatString, "$0.01 USD") XCTAssertEqual(paymentInfo.fiatString, "$36.78 USD") XCTAssertEqual(paymentInfo.balanceString, "$36.78 USD") XCTAssertFalse(paymentInfo.sufficientBalance) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) } func testPaymentInformationSufficientBalance() { let mockTeapot = MockTeapot(bundle: Bundle(for: PaymentManagerTests.self), mockFilename: "transactionSkeleton") mockTeapot.overrideEndPoint(Cereal.shared.paymentAddress, withFilename: "getExactBalance") let parameters: [String: Any] = [ "from": "0x011c6dd9565b8b83e6a9ee3f06e89ece3251ef2f", "to": "0x011c6dd9565b8b83e6a9ee3f06e89ece3251ef2f", "value": "0x330a41d05c8a780a" ] let paymentManager = PaymentManager(parameters: parameters, mockTeapot: mockTeapot, exchangeRate: 10) let expectation = XCTestExpectation(description: "Get payment Info") paymentManager.fetchPaymentInfo { paymentInfo in XCTAssertEqual(paymentInfo.totalEthereumString, "3.6787 ETH") XCTAssertEqual(paymentInfo.totalFiatString, "$36.79 USD") XCTAssertEqual(paymentInfo.estimatedFeesFiatString, "$0.01 USD") XCTAssertEqual(paymentInfo.fiatString, "$36.78 USD") XCTAssertEqual(paymentInfo.balanceString, "$36.79 USD") XCTAssertTrue(paymentInfo.sufficientBalance) expectation.fulfill() } wait(for: [expectation], timeout: 10.0) } }
gpl-3.0
8a0c55e8dd1687abbbba38ba22bd34d2
40.926606
119
0.694092
4.015817
false
true
false
false
yarshure/Surf
Surf/BarChartsView.swift
1
7308
// // BarChartsView.swift // Surf // // Created by yarshure on 14/02/2018. // Copyright © 2018 A.BIG.T. All rights reserved. // import UIKit import Charts import SFSocket import XRuler class BarChartsView: UIView,ChartViewDelegate { @IBOutlet var chartView:BarChartView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //self.backgroundColor = UIColor.gray } func setup(){ chartView.chartDescription?.enabled = false chartView.dragEnabled = true chartView.setScaleEnabled(true) chartView.pinchZoomEnabled = false // ChartYAxis *leftAxis = chartView.leftAxis; let xAxis = chartView.xAxis xAxis.labelPosition = .bottom chartView.rightAxis.enabled = false } override func awakeFromNib(){ setup() setup2() } func setup2(){ chartView.delegate = self chartView.drawBarShadowEnabled = false chartView.drawValueAboveBarEnabled = false chartView.maxVisibleCount = 60 let xAxis = chartView.xAxis xAxis.labelPosition = .bottom xAxis.labelFont = .systemFont(ofSize: 10) xAxis.granularity = 1 xAxis.labelCount = 7 //xAxis.valueFormatter = DayAxisValueFormatter(chart: chartView) let leftAxisFormatter = NumberFormatter() leftAxisFormatter.minimumFractionDigits = 0 leftAxisFormatter.maximumFractionDigits = 1 leftAxisFormatter.negativeSuffix = "" leftAxisFormatter.positiveSuffix = "" let leftAxis = chartView.leftAxis leftAxis.labelFont = .systemFont(ofSize: 10) leftAxis.labelCount = 4 leftAxis.valueFormatter = DefaultAxisValueFormatter(formatter: leftAxisFormatter) leftAxis.labelPosition = .outsideChart leftAxis.spaceTop = 0.15 leftAxis.axisMinimum = 0 // FIXME: HUH?? this replaces startAtZero = YES let rightAxis = chartView.rightAxis rightAxis.enabled = true rightAxis.labelFont = .systemFont(ofSize: 10) rightAxis.labelCount = 4 rightAxis.valueFormatter = leftAxis.valueFormatter rightAxis.spaceTop = 0.15 rightAxis.axisMinimum = 0 let l = chartView.legend l.horizontalAlignment = .left l.verticalAlignment = .bottom l.orientation = .horizontal l.drawInside = false l.form = .circle l.formSize = 9 l.font = UIFont(name: "HelveticaNeue-Light", size: 11)! l.xEntrySpace = 4 // chartView.legend = l // let marker = XYMarkerView(color: UIColor(white: 180/250, alpha: 1), // font: .systemFont(ofSize: 12), // textColor: .white, // insets: UIEdgeInsets(top: 8, left: 8, bottom: 20, right: 8), // xAxisValueFormatter: chartView.xAxis.valueFormatter!) // marker.chartView = chartView // marker.minimumSize = CGSize(width: 80, height: 40) // chartView.marker = marker // // sliderX.value = 12 // sliderY.value = 50 // slidersValueChanged(nil) } func updateFlow(_ flow:NetFlow) { let data = flow.totalFlows if data.count < 60 { var fill = Array<SFTraffic>.init(repeating: SFTraffic.init(), count: 60-data.count) fill.append(contentsOf: data) self.update(fill) }else { self.update(data) } } func update(_ data:[SFTraffic]){ //var yVals1:[BarChartDataEntry] = [] var index :Double = 0 var unit = "KB/s" var sbq:Double = 1.0 let rate = 1.2 let maxRx = data.max(by: { $0.rx < $1.rx}) let maxTx = data.max(by: { $0.tx < $1.tx}) let max = Int(maxRx!.rx) if max < 1024{ unit = "B/s" sbq = 1 }else if max >= 1024 && max < 1024*1024 { sbq = 1024.0 unit = "KB/s" }else if max >= 1024*1024 && max < 1024*1024*1024 { //return label + "\(x/1024/1024) MB" + s unit = "MB/s" sbq = 1024.0*1024.0 }else { //return label + "\(x/1024/1024/1024) GB" + s unit = "GB/s" sbq = 1024.0*1024.0*1024 } // for i in data { // let yy:Double = i / sbq // // let y = BarChartDataEntry(x: index, yValues: [yy, -yy])//BarChartDataEntry.init(x: index, y: yy) // yVals1.append(y) // index += 1 // } let yVals1 = data.map { dd -> BarChartDataEntry in let entry = BarChartDataEntry(x: index, yValues: [Double(dd.rx)/sbq, -(Double(dd.tx)/sbq)]) index += 1 return entry } var set1:BarChartDataSet if let cc = chartView { let leftAxis:YAxis = cc.leftAxis; leftAxis.labelTextColor = UIColor.cyan leftAxis.axisMaximum = Double(maxRx!.rx) * rate/sbq leftAxis.axisMinimum = -Double(maxTx!.tx) * rate/sbq if let d = cc.data { if d.dataSetCount > 0 { set1 = d.dataSets[0] as! BarChartDataSet // set1.values = yVals1 //set1.label = unit set1.stackLabels = [unit, unit] cc.data!.notifyDataChanged() cc.notifyDataSetChanged() } }else { set1 = BarChartDataSet.init(entries: yVals1, label: "") set1.stackLabels = [unit, unit] set1.colors = [UIColor(red: 61/255, green: 165/255, blue: 255/255, alpha: 1), UIColor(red: 23/255, green: 197/255, blue: 255/255, alpha: 1) ] set1.axisDependency = .left; //set1.drawFilledEnabled = true //set1.mode = .cubicBezier set1.drawValuesEnabled = false //set1.setColor(UIColor.red) // set1.setCircleColor(UIColor.white) // set1.lineWidth = 2.0; // set1.circleRadius = 3.0; // set1.fillAlpha = 65/255.0; // set1.drawCirclesEnabled = false // set1.fillColor = UIColor.brown set1.highlightColor = UIColor.yellow // set1.drawCircleHoleEnabled = false; // let ids:[IChartDataSet] = [set1] // let ldata:BarChartData = BarChartData(dataSets: set1) // ldata.setValueTextColor(UIColor.white) // ldata.setValueFont(UIFont.systemFont(ofSize: 9.0)) let data = BarChartData(dataSet: set1) data.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 10)!) data.barWidth = 0.9 cc.data = data } } } }
bsd-3-clause
a5ef9fa7c663533ad055bdf844906c55
33.305164
110
0.518681
4.546982
false
false
false
false
googlemaps/ios-on-demand-rides-deliveries-samples
swift/consumer_swiftui/App/Views/JourneySharingView.swift
1
4090
/* * Copyright 2022 Google LLC. All rights reserved. * * * 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 SwiftUI /// A journey sharing view containing `ControlPanelView` as well as `MapViewControllerBridge`. struct JourneySharingView: View { @EnvironmentObject var modelData: ModelData private static let notificationIdentifier = "NotificationIdentifier" private static let mapViewIdentifier = "MapView" var body: some View { VStack(alignment: .center) { MapViewControllerBridge() .edgesIgnoringSafeArea(.all) .accessibilityIdentifier(JourneySharingView.mapViewIdentifier) ControlPanelView( tapButtonAction: tapButtonAction, tapAddIntermediateDestinationAction: tapAddIntermediateDestinationAction) } } private func tapButtonAction() { switch modelData.customerState { case .initial: startPickupSelection() case .selectingPickup: startDropoffSelection() case .selectingDropoff: startTripPreview() case .tripPreview: bookTrip() case .booking: break case .journeySharing: cancelTrip() } } private func tapAddIntermediateDestinationAction() { modelData.intermediateDestinations.append(modelData.dropoffLocation) NotificationCenter.default.post( name: .intermediateDestinationDidAdd, object: nil, userInfo: nil) } /// Updates UI elements and customer state when the user indicates pickup location. private func startPickupSelection() { modelData.controlButtonLabel = Strings.controlPanelConfirmPickupButtonText modelData.staticLabel = Strings.tripInfoViewStaticText modelData.tripInfoLabel = Strings.selectPickupLocationText modelData.customerState = .selectingPickup NotificationCenter.default.post( name: .stateDidChange, object: MapViewController.selectPickupNotificationObjectType, userInfo: nil) } /// Updates UI elements and customer state when the user indicates drop-off location. private func startDropoffSelection() { modelData.controlButtonLabel = Strings.controlPanelConfirmDropoffButtonText modelData.tripInfoLabel = Strings.selectDropoffLocationText modelData.staticLabel = Strings.tripInfoViewStaticText modelData.customerState = .selectingDropoff modelData.intermediateDestinations.removeAll() NotificationCenter.default.post( name: .stateDidChange, object: MapViewController.selectDropoffNotificationObjectType, userInfo: nil) } /// Updates UI elements and customer state when the user previews the trip. private func startTripPreview() { modelData.staticLabel = "" modelData.controlButtonLabel = Strings.controlPanelConfirmTripButtonText modelData.customerState = .tripPreview modelData.tripInfoLabel = "" modelData.buttonColor = Color.green modelData.customerState = .tripPreview } /// Sends out a notification and lets `MapViewController` know that the user is booking /// a trip now. private func bookTrip() { NotificationCenter.default.post( name: .stateDidChange, object: MapViewController.bookTripNotificationObjectType, userInfo: nil) } /// Sends out a notification and lets `MapViewController` know that a user is cancelling /// a trip now. private func cancelTrip() { NotificationCenter.default.post( name: .stateDidChange, object: MapViewController.cancelTripNotificationObjectType, userInfo: nil) } } struct JourneySharingView_Previews: PreviewProvider { static var previews: some View { JourneySharingView() } }
apache-2.0
c83dff1fa1ded913d113b43157d012f7
34.565217
94
0.752078
4.874851
false
false
false
false
makdeniz/MrExtension
MrExtension/Classes/MrUtils.swift
1
1684
// // utils.swift // Yatirimlarim // // Created by murat on 1/1/17. // Copyright © 2017 Zenithsoft. All rights reserved. // import Foundation import SystemConfiguration import CoreData public struct Platform { public static var isSimulator: Bool { return TARGET_OS_SIMULATOR != 0 // Use this line in Xcode 7 or newer } } public class MrUtils{ public init() { } public func IsInternetAvailable() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags = SCNetworkReachabilityFlags.connectionAutomatic if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } //public class func showMyApps() -> UICollectionViewController { //let storyBoard = UIStoryboard(name: "MyAppsViewStoryboard", bundle: nil) //let vc = storyBoard.instantiateViewController(withIdentifier: "MyAppsViewSBI") as! MyAppsView //return vc //} }
mit
c65253485407a1748900a34506a8d885
26.145161
103
0.632799
4.906706
false
false
false
false
zehrer/SOGraphDB
Sources/SOGraphDB/Backend/XMLFileStore/GXL.swift
1
668
// // GXL.swift // SOGraphDB // // Created by Stephan Zehrer on 20.01.18. // import Foundation struct GLX { struct Elements { static let glx = "glx" static let graph = "graph" static let node = "node" static let relationship = "edge" static let property = "attr" } struct Attributes { static let id = "id" static let relStart = "from" static let relEnd = "to" static let key = "key" //Property } struct Property { static let string = "string" static let int = "int" static let bool = "bool" static let uid = "uid" } }
mit
0de3e8a9423cb1b6699d3f46e2c7f489
18.647059
42
0.531437
3.861272
false
false
false
false
WhatsTaste/WTImagePickerController
Vendor/Views/WTBadgeActionView.swift
1
3002
// // WTBadgeActionView.swift // WTImagePickerController // // Created by Jayce on 2017/2/17. // Copyright © 2017年 WhatsTaste. All rights reserved. // import UIKit private let spacing: CGFloat = 4 class WTBadgeActionView: UIView { override init(frame: CGRect) { super.init(frame: frame) // Initialization code addSubview(badgeView) addSubview(contentButton) addConstraint(NSLayoutConstraint.init(item: badgeView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint.init(item: badgeView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint.init(item: self, attribute: .bottom, relatedBy: .equal, toItem: badgeView, attribute: .bottom, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint.init(item: contentButton, attribute: .left, relatedBy: .equal, toItem: badgeView, attribute: .right, multiplier: 1, constant: spacing)) addConstraint(NSLayoutConstraint.init(item: self, attribute: .right, relatedBy: .equal, toItem: contentButton, attribute: .right, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint.init(item: contentButton, attribute: .top, relatedBy: .equal, toItem: badgeView, attribute: .top, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint.init(item: badgeView, attribute: .bottom, relatedBy: .equal, toItem: contentButton, attribute: .bottom, multiplier: 1, constant: 0)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var tintColor: UIColor! { didSet { badgeView.tintColor = tintColor contentButton.setTitleColor(tintColor, for: .normal) contentButton.setTitleColor(tintColor.withAlphaComponent(WTImagePickerControllerDisableAlphaComponent), for: .disabled) } } // MARK: - Properties public var badge: Int = 0 { didSet { badgeView.badge = String(badge) } } lazy public private(set) var badgeView: WTBadgeView = { let view = WTBadgeView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.clear view.isUserInteractionEnabled = false return view }() lazy public private(set) var contentButton: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.setTitleColor(self.tintColor, for: .normal) button.setTitleColor(self.tintColor.withAlphaComponent(WTImagePickerControllerDisableAlphaComponent), for: .disabled) return button }() }
mit
66e4c7f525a3366707ac7c5b352a5b2b
41.842857
176
0.681561
4.752773
false
false
false
false
apple/swift
test/SILGen/struct_resilience.swift
1
13459
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule %S/../Inputs/resilient_struct.swift // RUN: %target-swift-emit-silgen -I %t -enable-library-evolution %s | %FileCheck %s import resilient_struct // Resilient structs from outside our resilience domain are always address-only // CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience26functionWithResilientTypes_1f010resilient_A04SizeVAF_A2FXEtF : $@convention(thin) (@in_guaranteed Size, @noescape @callee_guaranteed (@in_guaranteed Size) -> @out Size) -> @out Size // CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@noescape @callee_guaranteed (@in_guaranteed Size) -> @out Size): func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size { // Stored properties of resilient structs from outside our resilience // domain are accessed through accessors // CHECK: copy_addr %1 to [init] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size var s2 = s // CHECK: copy_addr %1 to [init] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[GETTER:%.*]] = function_ref @$s16resilient_struct4SizeV1wSivg : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[GETTER]]([[SIZE_BOX]]) // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[OTHER_SIZE_BOX]] : $*Size // CHECK: [[SETTER:%.*]] = function_ref @$s16resilient_struct4SizeV1wSivs : $@convention(method) (Int, @inout Size) -> () // CHECK: apply [[SETTER]]([[RESULT]], [[WRITE]]) s2.w = s.w // CHECK: copy_addr %1 to [init] [[SIZE_BOX:%.*]] : $*Size // CHECK: [[FN:%.*]] = function_ref @$s16resilient_struct4SizeV1hSivg : $@convention(method) (@in_guaranteed Size) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]]) _ = s.h // CHECK: apply %2(%0, %1) // CHECK-NOT: destroy_value %2 // CHECK: return return f(s) } // Use modify for inout access of properties in resilient structs // from a different resilience domain public func inoutFunc(_ x: inout Int) {} // CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience18resilientInOutTestyy0c1_A04SizeVzF : $@convention(thin) (@inout Size) -> () func resilientInOutTest(_ s: inout Size) { // CHECK: function_ref @$s16resilient_struct4SizeV1wSivM // CHECK: function_ref @$s17struct_resilience9inoutFuncyySizF inoutFunc(&s.w) // CHECK: return } // Fixed-layout structs may be trivial or loadable // CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience28functionWithFixedLayoutTypes_1f010resilient_A05PointVAF_A2FXEtF : $@convention(thin) (Point, @noescape @callee_guaranteed (Point) -> Point) -> Point // CHECK: bb0(%0 : $Point, %1 : $@noescape @callee_guaranteed (Point) -> Point): func functionWithFixedLayoutTypes(_ p: Point, f: (Point) -> Point) -> Point { // Stored properties of fixed layout structs are accessed directly var p2 = p // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x // CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x // CHECK: assign [[RESULT]] to [[DEST]] : $*Int p2.x = p.x // CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y _ = p.y // CHECK: [[NEW_POINT:%.*]] = apply %1(%0) // CHECK: return [[NEW_POINT]] return f(p) } // Fixed-layout struct with resilient stored properties is still address-only // CHECK-LABEL: sil hidden [ossa] @$s17struct_resilience39functionWithFixedLayoutOfResilientTypes_1f010resilient_A09RectangleVAF_A2FXEtF : $@convention(thin) (@in_guaranteed Rectangle, @noescape @callee_guaranteed (@in_guaranteed Rectangle) -> @out Rectangle) -> @out Rectangle // CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@noescape @callee_guaranteed (@in_guaranteed Rectangle) -> @out Rectangle): func functionWithFixedLayoutOfResilientTypes(_ r: Rectangle, f: (Rectangle) -> Rectangle) -> Rectangle { return f(r) } // Make sure we generate getters and setters for stored properties of // resilient structs public struct MySize { // Static computed property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV10expirationSivgZ : $@convention(method) (@thin MySize.Type) -> Int // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV10expirationSivsZ : $@convention(method) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV10expirationSivMZ : $@yield_once @convention(method) (@thin MySize.Type) -> @yields @inout Int public static var expiration: Int { get { return copyright + 70 } set { copyright = newValue - 70 } } // Instance computed property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1dSivg : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1dSivs : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1dSivM : $@yield_once @convention(method) (@inout MySize) -> @yields @inout Int public var d: Int { get { return 0 } set { } } // Instance stored property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1wSivg : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1wSivs : $@convention(method) (Int, @inout MySize) -> () // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1wSivM : $@yield_once @convention(method) (@inout MySize) -> @yields @inout Int public var w: Int // Read-only instance stored property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1hSivg : $@convention(method) (@in_guaranteed MySize) -> Int public let h: Int // Weak property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV1iyXlSgvg : $@convention(method) (@in_guaranteed MySize) -> @owned Optional<AnyObject> public weak var i: AnyObject? // Static stored property // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV9copyrightSivgZ : $@convention(method) (@thin MySize.Type) -> Int // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV9copyrightSivsZ : $@convention(method) (Int, @thin MySize.Type) -> () // CHECK-LABEL: sil [ossa] @$s17struct_resilience6MySizeV9copyrightSivMZ : $@yield_once @convention(method) (@thin MySize.Type) -> @yields @inout Int public static var copyright: Int = 0 } // CHECK-LABEL: sil [ossa] @$s17struct_resilience28functionWithMyResilientTypes_1fAA0E4SizeVAE_A2EXEtF : $@convention(thin) (@in_guaranteed MySize, @noescape @callee_guaranteed (@in_guaranteed MySize) -> @out MySize) -> @out MySize public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize { // Stored properties of resilient structs from inside our resilience // domain are accessed directly // CHECK: copy_addr %1 to [init] [[SIZE_BOX:%[0-9]*]] : $*MySize var s2 = s // CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w // CHECK: [[SRC:%.*]] = load [trivial] [[SRC_ADDR]] : $*Int // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[SIZE_BOX]] : $*MySize // CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*MySize, #MySize.w // CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int s2.w = s.w // CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h // CHECK: [[RESULT:%.*]] = load [trivial] [[RESULT_ADDR]] : $*Int _ = s.h // CHECK: apply %2(%0, %1) // CHECK-NOT: destroy_value %2 // CHECK: return return f(s) } // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s17struct_resilience25publicTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> Int @_transparent public func publicTransparentFunction(_ s: MySize) -> Int { // Since the body of a public transparent function might be inlined into // other resilience domains, we have to use accessors // CHECK: [[SELF:%.*]] = alloc_stack $MySize // CHECK-NEXT: copy_addr %0 to [init] [[SELF]] // CHECK: [[GETTER:%.*]] = function_ref @$s17struct_resilience6MySizeV1wSivg // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]]) // CHECK-NEXT: destroy_addr [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: return [[RESULT]] return s.w } // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s17struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> @owned @callee_guaranteed () -> Int @_transparent public func publicTransparentLocalFunction(_ s: MySize) -> () -> Int { // CHECK-LABEL: sil shared [serialized] [ossa] @$s17struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVFSiycfU_ : $@convention(thin) (@in_guaranteed MySize) -> Int // CHECK: function_ref @$s17struct_resilience6MySizeV1wSivg : $@convention(method) (@in_guaranteed MySize) -> Int // CHECK: return {{.*}} : $Int return { s.w } } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17struct_resilience27internalTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> Int // CHECK: bb0([[ARG:%.*]] : $*MySize): @_transparent func internalTransparentFunction(_ s: MySize) -> Int { // The body of an internal transparent function will not be inlined into // other resilience domains, so we can access storage directly // CHECK: [[W_ADDR:%.*]] = struct_element_addr [[ARG]] : $*MySize, #MySize.w // CHECK-NEXT: [[RESULT:%.*]] = load [trivial] [[W_ADDR]] : $*Int // CHECK-NEXT: return [[RESULT]] return s.w } // CHECK-LABEL: sil [serialized] [ossa] @$s17struct_resilience23publicInlinableFunctionySiAA6MySizeVF : $@convention(thin) (@in_guaranteed MySize) -> Int @inlinable public func publicInlinableFunction(_ s: MySize) -> Int { // Since the body of a public transparent function might be inlined into // other resilience domains, we have to use accessors // CHECK: [[SELF:%.*]] = alloc_stack $MySize // CHECK-NEXT: copy_addr %0 to [init] [[SELF]] // CHECK: [[GETTER:%.*]] = function_ref @$s17struct_resilience6MySizeV1wSivg // CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]]) // CHECK-NEXT: destroy_addr [[SELF]] // CHECK-NEXT: dealloc_stack [[SELF]] // CHECK-NEXT: return [[RESULT]] return s.w } // Make sure that @usableFromInline entities can be resilient @usableFromInline struct VersionedResilientStruct { @usableFromInline let x: Int @usableFromInline let y: Int @usableFromInline init(x: Int, y: Int) { self.x = x self.y = y } // Non-inlinable initializer, assigns to self -- treated as a root initializer // CHECK-LABEL: sil [ossa] @$s17struct_resilience24VersionedResilientStructV5otherA2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct } // CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [rootself] [[SELF_BOX]] // CHECK: return @usableFromInline init(other: VersionedResilientStruct) { self = other } // Inlinable initializer, assigns to self -- treated as a delegating initializer // CHECK-LABEL: sil [serialized] [ossa] @$s17struct_resilience24VersionedResilientStructV6other2A2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct } // CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: return @usableFromInline @inlinable init(other2: VersionedResilientStruct) { self = other2 } } // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s17struct_resilience27useVersionedResilientStructyAA0deF0VADF : $@convention(thin) (@in_guaranteed VersionedResilientStruct) -> @out VersionedResilientStruct @usableFromInline @_transparent func useVersionedResilientStruct(_ s: VersionedResilientStruct) -> VersionedResilientStruct { // CHECK: function_ref @$s17struct_resilience24VersionedResilientStructV1ySivg // CHECK: function_ref @$s17struct_resilience24VersionedResilientStructV1xSivg // CHECK: function_ref @$s17struct_resilience24VersionedResilientStructV1x1yACSi_SitcfC return VersionedResilientStruct(x: s.y, y: s.x) // CHECK: return } // CHECK-LABEL: sil [serialized] [ossa] @$s17struct_resilience18inlinableInoutTestyyAA6MySizeVzF : $@convention(thin) (@inout MySize) -> () @inlinable public func inlinableInoutTest(_ s: inout MySize) { // Inlinable functions can be inlined in other resilience domains. // // Make sure we use modify for an inout access of a resilient struct // property inside an inlinable function. // CHECK: function_ref @$s17struct_resilience6MySizeV1wSivM inoutFunc(&s.w) // CHECK: return } // Initializers for resilient structs extension Size { // CHECK-LABEL: sil hidden [ossa] @$s16resilient_struct4SizeV0B11_resilienceE5otherA2C_tcfC : $@convention(method) (@in Size, @thin Size.Type) -> @out Size // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Size } // CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var Size } // CHECK: return init(other: Size) { self = other } }
apache-2.0
0481144305f8896382ff2da6940c5911
45.732639
277
0.677985
3.62288
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/IoTAnalytics/IoTAnalytics_Error.swift
1
3033
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for IoTAnalytics public struct IoTAnalyticsErrorType: AWSErrorType { enum Code: String { case internalFailureException = "InternalFailureException" case invalidRequestException = "InvalidRequestException" case limitExceededException = "LimitExceededException" case resourceAlreadyExistsException = "ResourceAlreadyExistsException" case resourceNotFoundException = "ResourceNotFoundException" case serviceUnavailableException = "ServiceUnavailableException" case throttlingException = "ThrottlingException" } private let error: Code public let context: AWSErrorContext? /// initialize IoTAnalytics public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// There was an internal failure. public static var internalFailureException: Self { .init(.internalFailureException) } /// The request was not valid. public static var invalidRequestException: Self { .init(.invalidRequestException) } /// The command caused an internal limit to be exceeded. public static var limitExceededException: Self { .init(.limitExceededException) } /// A resource with the same name already exists. public static var resourceAlreadyExistsException: Self { .init(.resourceAlreadyExistsException) } /// A resource with the specified name could not be found. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } /// The service is temporarily unavailable. public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) } /// The request was denied due to request throttling. public static var throttlingException: Self { .init(.throttlingException) } } extension IoTAnalyticsErrorType: Equatable { public static func == (lhs: IoTAnalyticsErrorType, rhs: IoTAnalyticsErrorType) -> Bool { lhs.error == rhs.error } } extension IoTAnalyticsErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
649cf92c398a986cef6c13989b48e25d
39.44
117
0.68579
5.256499
false
false
false
false
AndrewBennet/readinglist
ReadingList/Models/Migrations/BookMapping_12_13.swift
1
1995
import Foundation import CoreData import os.log class BookMapping_12_13: NSEntityMigrationPolicy { //swiftlint:disable:this type_name // Migrates ISBN-13 from String to Int64 @objc func isbn(forIsbn isbn: String?) -> NSNumber? { guard let isbnString = isbn, let isbnInt = Int64(isbnString) else { return nil } return NSNumber(value: isbnInt) } // Returns the provided Google Books ID, unless that already exists in the destination context. // We do not expect this to ever be the case, since the UI has prevented the addition of duplicate // Google Book IDs, but the unique constraint did not exist in the model. This is just to ensure // safety. @objc func googleBooksId(forGoogleBooksId googleBooksId: String?, manager: NSMigrationManager) -> String? { guard let googleBooksId = googleBooksId else { return nil } let existingGoogleBooksIdRequest = NSFetchRequest<NSManagedObject>(entityName: "Book") existingGoogleBooksIdRequest.predicate = NSPredicate(format: "googleBooksId == %@", googleBooksId) existingGoogleBooksIdRequest.fetchLimit = 1 let existingGoogleBooksIdCount = try! manager.destinationContext.count(for: existingGoogleBooksIdRequest) guard existingGoogleBooksIdCount == 0 else { os_log("Duplicate Google Books ID found during model 12 -> 13 migration: %{public}s", type: .error, googleBooksId) return nil } return googleBooksId } // Returns the currentPage attribute if the read state is CurrentlyReading, otherwise returns nil. @objc func currentPage(forCurrentPage currentPage: NSNumber?, readState: NSNumber) -> NSNumber? { guard let currentPage = currentPage else { return nil } if readState == 1 /* BookReadState.reading = 1 */ { return currentPage } else { os_log("Removing currentPage value for book in readState %d", readState) return nil } } }
gpl-3.0
0dd0804db076327304a544afed20c660
47.658537
126
0.696241
4.784173
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/SharedViews/PledgeShippingLocationShimmerLoadingView.swift
1
2087
import Foundation import Library import Prelude import UIKit final class PledgeShippingLocationShimmerLoadingView: UIView { // MARK: - Properties internal lazy var amountPlaceholder: UIView = { UIView(frame: .zero) }() private lazy var buttonPlaceholder: UIView = { UIView(frame: .zero) }() private lazy var rootStackView: UIStackView = { UIStackView(frame: .zero) }() // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) self.configureViews() self.setupConstraints() self.startLoading() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.layoutGradientLayers() } override func bindStyles() { super.bindStyles() _ = self.rootStackView |> \.isLayoutMarginsRelativeArrangement .~ true |> \.layoutMargins .~ .init(topBottom: Styles.grid(1)) _ = self.buttonPlaceholder |> roundedStyle(cornerRadius: Styles.gridHalf(3)) _ = self.amountPlaceholder |> roundedStyle(cornerRadius: Styles.gridHalf(3)) } // MARK: - Subviews private func configureViews() { _ = (self.rootStackView, self) |> ksr_addSubviewToParent() |> ksr_constrainViewToEdgesInParent() _ = ([self.buttonPlaceholder, UIView(), self.amountPlaceholder], self.rootStackView) |> ksr_addArrangedSubviewsToStackView() } private func setupConstraints() { NSLayoutConstraint.activate([ self.buttonPlaceholder.heightAnchor.constraint(equalToConstant: Styles.grid(3)), self.amountPlaceholder.heightAnchor.constraint(equalToConstant: Styles.grid(3)), self.buttonPlaceholder.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.4), self.amountPlaceholder.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.2) ]) } } // MARK: - ShimmerLoading extension PledgeShippingLocationShimmerLoadingView: ShimmerLoading { func shimmerViews() -> [UIView] { return [self.amountPlaceholder, self.buttonPlaceholder] } }
apache-2.0
fec170ab65135128aea1dd7a77d81d6a
26.826667
96
0.708673
4.576754
false
false
false
false
kevto/SwiftClient
SwiftClient/Constants.swift
1
3266
// // Constants.swift // SwiftClient // // Created by Adam Nalisnick on 10/30/14. // Copyright (c) 2014 Adam Nalisnick. All rights reserved. // import Foundation internal func base64Encode(string:String) -> String { return dataToString(stringToData(string).base64EncodedDataWithOptions([])) } internal func uriDecode(string:String) -> String{ return string.stringByRemovingPercentEncoding! } internal func uriEncode(string:AnyObject) -> String{ return string.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())! } internal func stringToData(string:String) -> NSData { return string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)! } internal func dataToString(data:NSData) -> String { return NSString(data: data, encoding: 1)! as String } internal func queryPair(key:String, value:AnyObject) -> String{ return uriEncode(key) + "=" + uriEncode(value) } internal func queryString(query:AnyObject) -> String?{ var pairs:[String]? if let dict = query as? Dictionary<String, AnyObject> { pairs = Array() for (key, value) in dict { pairs!.append(queryPair(key, value: value)) } } else if let array = query as? [String] { pairs = array } if let pairs = pairs { return pairs.joinWithSeparator("&") } return nil } // PARSERS private func parseJson(data:NSData, string: String) -> AnyObject?{ do { return try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) } catch { print(error) } return nil; } private func parseForm(data:NSData, string:String) -> AnyObject?{ let pairs = string.componentsSeparatedByString("&") var form:[String : String] = Dictionary() for pair in pairs { let parts = pair.componentsSeparatedByString("=") form[uriDecode(parts[0])] = uriDecode(parts[1]) } return form } //SERIALIZERS private func serializeJson(data:AnyObject) -> NSData? { if(data as? Array<AnyObject> != nil || data as? Dictionary<String, AnyObject> != nil){ //var error:NSError? do { return try NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions()) } catch { print(error) } } else if let dataString = data as? String{ return stringToData(dataString) } return nil } private func serializeForm(data:AnyObject) -> NSData? { if let queryString = queryString(data) { return stringToData(queryString) } else if let dataString = (data as? String ?? String(data)) as String? { return stringToData(dataString) } return nil } internal let types = [ "html": "text/html", "json": "application/json", "xml": "application/xml", "urlencoded": "application/x-www-form-urlencoded", "form": "application/x-www-form-urlencoded", "form-data": "application/x-www-form-urlencoded" ] internal let serializers = [ "application/x-www-form-urlencoded": serializeForm, "application/json": serializeJson ] internal let parsers = [ "application/x-www-form-urlencoded": parseForm, "application/json": parseJson ]
mit
d56502709d08e88e75c129552fc7fec4
25.770492
114
0.66534
4.187179
false
false
false
false
JohnSansoucie/MyProject2
BlueCapKit/Location/Beacon.swift
1
1245
// // Beacon.swift // BlueCap // // Created by Troy Stribling on 9/19/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import Foundation import CoreLocation public class Beacon { private let clbeacon : CLBeacon private let _discoveredAt = NSDate() public var discoveredAt : NSDate { return self._discoveredAt } internal init(clbeacon:CLBeacon) { self.clbeacon = clbeacon } public var major : Int? { if let major = self.clbeacon.major { return major.integerValue } else { return nil } } public var minor : Int? { if let minor = self.clbeacon.minor { return minor.integerValue } else { return nil } } public var proximityUUID : NSUUID? { if let nsuuid = self.clbeacon.proximityUUID { return nsuuid } else { return nil } } public var proximity : CLProximity { return self.clbeacon.proximity } public var accuracy : CLLocationAccuracy { return self.clbeacon.accuracy } public var rssi : Int { return self.clbeacon.rssi } }
mit
2ccd90b38d6545443e3fd1ac25b0a05c
19.75
53
0.554217
4.527273
false
false
false
false
marcelmueller/MyWeight
MyWeight/Screens/AccessDenied/AccessDeniedViewController.swift
1
1061
// // AccessDeniedViewController.swift // MyWeight // // Created by Diogo on 20/10/16. // Copyright © 2016 Diogo Tridapalli. All rights reserved. // import UIKit public protocol AccessDeniedViewControllerDelegate { func didFinish(on controller: AccessDeniedViewController) } public class AccessDeniedViewController: UIViewController { public var delegate: AccessDeniedViewControllerDelegate? var theView: AccessDeniedView { // I don't like this `!` but it's a framework limitation return self.view as! AccessDeniedView } override public func loadView() { let view = AccessDeniedView() self.view = view } override public func viewDidLoad() { let viewModel = AccessDeniedViewModel { [weak self] in self?.didFinish() } theView.viewModel = viewModel } override public func viewDidLayoutSubviews() { theView.topOffset = topLayoutGuide.length } func didFinish() { self.delegate?.didFinish(on: self) } }
mit
7a7206063ef5a76d060be4be90472a5b
20.632653
64
0.663208
4.711111
false
false
false
false
maarf/Books
Model/Objects/Book.swift
1
417
public struct Book: Codable, Equatable { public var id: String public var author: String public var title: String public var publishedAt: Date public var coverURL: URL public static func ==(lhs: Book, rhs: Book) -> Bool { return lhs.id == rhs.id && lhs.author == rhs.author && lhs.title == rhs.title && lhs.publishedAt == rhs.publishedAt && lhs.coverURL == rhs.coverURL } }
mit
adb7de803d1de2317f58d95101ce5112
26.8
55
0.642686
3.897196
false
false
false
false
xcodeswift/xcproj
Sources/XcodeProj/Scheme/XCScheme+StoreKitConfigurationFileReference.swift
1
951
import AEXML import Foundation extension XCScheme { public final class StoreKitConfigurationFileReference: Equatable { // MARK: - Attributes public var identifier: String // MARK: - Init public init(identifier: String) { self.identifier = identifier } init(element: AEXMLElement) throws { identifier = element.attributes["identifier"]! } // MARK: - XML func xmlElement() -> AEXMLElement { AEXMLElement(name: "StoreKitConfigurationFileReference", value: nil, attributes: [ "identifier": identifier, ]) } // MARK: - Equatable public static func == (lhs: StoreKitConfigurationFileReference, rhs: StoreKitConfigurationFileReference) -> Bool { lhs.identifier == rhs.identifier } } }
mit
51fd099baf94438f57359ec4507d47df
25.416667
122
0.546793
5.94375
false
true
false
false
tootbot/tootbot
Tootbot/Source/Networking/Authentication.swift
1
2043
// // Copyright (C) 2017 Tootbot Contributors // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // public enum Authentication: CustomStringConvertible, Equatable, Hashable { case authenticated(account: UserAccount) case unauthenticated(instanceURI: String) public static func ==(lhs: Authentication, rhs: Authentication) -> Bool { switch (lhs, rhs) { case (.authenticated(let leftAccount), .authenticated(let rightAccount)): return leftAccount == rightAccount case (.unauthenticated(let leftInstanceURI), .unauthenticated(let rightInstanceURI)): return leftInstanceURI == rightInstanceURI default: return false } } public var description: String { switch self { case .authenticated(let account): return String(describing: account) case .unauthenticated(let instanceURI): return instanceURI } } public var hashValue: Int { switch self { case .authenticated(let account): return account.hashValue case .unauthenticated(let instanceURI): return instanceURI.hashValue } } var instanceURI: String { switch self { case .authenticated(let account): return account.instanceURI case .unauthenticated(let instanceURI): return instanceURI } } }
agpl-3.0
4376ed5ed801163afd661c2cbdbcbe01
33.627119
93
0.667646
4.946731
false
false
false
false
qihuang2/Game3
Game3/Utility/ScoreKeeper.swift
1
4057
// // ScoreKeeper.swift // Game2 // // Created by Qi Feng Huang on 6/24/15. // Copyright (c) 2015 Qi Feng Huang. All rights reserved. // import Foundation //MARK: - SCORE KEEPER //Score keeper is archived to save game progress and prevent cheating class ScoreKeeper: NSObject { private var levelsUnlocked:Int = 1 //if levelsUnlocked = numberOfLevels +1, player beat all levels private var numberOfLevels: Int private var timeAttackLevelsCompleted: Int = 0 func encodeWithCoder(aCoder: NSCoder!){ aCoder.encodeInteger(self.levelsUnlocked, forKey: "levelsUnlocked") aCoder.encodeInteger(self.numberOfLevels, forKey: "numberOfLevels") aCoder.encodeInteger(self.timeAttackLevelsCompleted, forKey: "timeAttackLevelsCompleted") } required init(coder aDecoder: NSCoder!){ self.levelsUnlocked = aDecoder.decodeIntegerForKey("levelsUnlocked") self.numberOfLevels = aDecoder.decodeIntegerForKey("numberOfLevels") self.timeAttackLevelsCompleted = aDecoder.decodeIntegerForKey("timeAttackLevelsCompleted") } func resetLevelsUnlocked(){ self.levelsUnlocked = 1 } func getTimeAttackLevelsCompleted()->Int{ return self.timeAttackLevelsCompleted } func incrementTimeAttackLevelsCompleted(){ self.timeAttackLevelsCompleted++ } func resetTimeAttackLevelsCompleted(){ self.timeAttackLevelsCompleted = 0 } func getNumberOfLevels()->Int{ return self.numberOfLevels } init(numberOfLevels: Int = 0){ self.numberOfLevels = numberOfLevels super.init() } func getLevelsUnlocked()->Int{ return self.levelsUnlocked } func incrementLevelsUnlocked(){ if (self.levelsUnlocked < self.numberOfLevels+1){ self.levelsUnlocked++ } } //DELETE AFTERWARDS func setLevelsUnlocked(num:Int){ self.levelsUnlocked = num } } //MARK: - SAVE //archives score keeper class SaveHighScore:NSObject { let documentDirectories = getPrivateDocsDir() let filePath = getPrivateDocsDir().stringByAppendingPathComponent("scoreKeeper.archive") func archiveHighScore(#scoreKeeper: ScoreKeeper) { if NSKeyedArchiver.archiveRootObject(scoreKeeper, toFile: self.filePath) { print("Success writing to file!") } else { print("Unable to write to file!") } } func retrieveHighScore(#numberOfLevels: Int) -> NSObject { if let data = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? ScoreKeeper { checkScoreKeeperSize(data, numOfLevels: numberOfLevels) return data } else{ return ScoreKeeper(numberOfLevels: numberOfLevels) } } func checkScoreKeeperSize(scoreKeeper: ScoreKeeper, numOfLevels: Int){ // If number of levels is changed, create new array with correct num. of levels if (scoreKeeper.numberOfLevels != numOfLevels){ if scoreKeeper.numberOfLevels > numOfLevels{ //if we decrease number of level in game, levels unlocked will reset to prevent bugs //MAKE SURE YOU DON'T DECREASE NUMBER OF LEVELS scoreKeeper.resetLevelsUnlocked() } scoreKeeper.numberOfLevels = numOfLevels SaveHighScore().archiveHighScore(scoreKeeper: scoreKeeper) } } } //MARK: - DIRECTORY FUNCTION //returns dir of private file with saved game information func getPrivateDocsDir() -> String { let paths = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true) let documentsDirectory = paths[0].stringByAppendingPathComponent("Private Documents") var error: NSError? NSFileManager.defaultManager().createDirectoryAtPath( documentsDirectory, withIntermediateDirectories: true, attributes: nil, error: &error) return documentsDirectory }
mit
4c643cc5160d81fddeb437d7166b1430
29.969466
144
0.671432
4.959658
false
false
false
false
thepaddedcell/AffineTransformDemo
AffineTransformDemo/PathsViewController.swift
1
1081
// // PathsViewController.swift // AffineTransformDemo // // Created by Craig Stanford on 19/02/2015. // import UIKit class PathsViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let scaledView = UIImageView(frame: CGRectMake(50, 200, 400, 400)) scaledView.contentMode = UIViewContentMode.ScaleAspectFill scaledView.image = UIImage.imageWithBezierPath(UIBezierPath.rfPathForCross(), colour: UIColor.redColor(), size: CGSizeMake(100, 100)) self.view.addSubview(scaledView) let transformedView = UIImageView(frame: CGRectMake(500, 200, 400, 400)) transformedView.contentMode = UIViewContentMode.ScaleAspectFill transformedView.image = UIImage.imageWithBezierPath(UIBezierPath.rfPathForCross(), colour: UIColor.redColor(), size: transformedView.bounds.size) self.view.addSubview(transformedView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
unlicense
ba56a51f82c6ddd0be71de996cf3b2eb
33.870968
153
0.716929
4.847534
false
false
false
false
lanserxt/teamwork-ios-sdk
TeamWorkClient/TeamWorkClient/Requests/TWApiClient+Tasks.swift
1
24176
// // TWApiClient+Invoices.swift // TeamWorkClient // // Created by Anton Gubarenko on 02.02.17. // Copyright © 2017 Anton Gubarenko. All rights reserved. // import Foundation import Alamofire extension TWApiClient{ func getTasks(urlParams: String, _ responseBlock: @escaping (Bool, Int, [TodoItem]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getTasks.path) + (urlParams.isEmpty ? "" : "&" + urlParams) , method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.getTasks.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getTasksForProject(projectId: String, urlParams: String, _ responseBlock: @escaping (Bool, Int, [TodoItem]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getTasksForProject.path, projectId) + (urlParams.isEmpty ? "" : "&" + urlParams) , method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.getTasksForProject.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getTasksForTasklists(taskListId: String, urlParams: String, _ responseBlock: @escaping (Bool, Int, [TodoItem]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getTasksForTasklists.path, taskListId) + (urlParams.isEmpty ? "" : "&" + urlParams) , method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.getTasksForTasklists.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getTask(taskId: String, getFiles: Bool = true, nestSubTasks: Bool = false, includeCompletedSubtasks: Bool = false, _ responseBlock: @escaping (Bool, Int, TodoItem?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getTask.path, taskId, wrapBoolValue(getFiles), wrapBoolValue(nestSubTasks), wrapBoolValue(includeCompletedSubtasks)), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.getTask.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getTaskDependecies(taskId: String, _ responseBlock: @escaping (Bool, Int, Dependent?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getTaskDependecies.path, taskId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Dependent>.init(rootObjectName: TWApiClientConstants.APIPath.getTaskDependecies.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func markTaskComplete(taskId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.markTaskComplete.path, taskId), method: HTTPMethod.put, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.markTaskComplete.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func markTaskUncomplete(taskId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.markTaskUncomplete.path, taskId), method: HTTPMethod.put, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.markTaskUncomplete.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func createTaskInTasklist(taskListId: String, todoItem: [String: Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["todo-item" : todoItem] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createTaskInTasklist.path, taskListId), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.createTaskInTasklist.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func createSubTask(taskId: String, todoItem: [String: Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["todo-item" : todoItem] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createSubTask.path, taskId), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.createSubTask.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func updateTask(taskId: String, todoItem: [String: Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["todo-item" : todoItem] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateTask.path, taskId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.updateTask.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func deleteTask(taskId: String, todoItem: [String: Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteTask.path, taskId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.deleteTask.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func reorderTasksForTasklist(taskListId: String, todoItems: [String: Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["todo-items" : todoItems] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.reorderTasksForTasklist.path, taskListId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.reorderTasksForTasklist.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func getCompletedTasks(urlParams: String, page: Int = 1, pageSize: Int = 20, _ responseBlock: @escaping (Bool, Int, [TodoItem]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getCompletedTasks.path, page, pageSize) + (urlParams.isEmpty ? "" : "&" + urlParams) , method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.getCompletedTasks.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func changeCompletedDateForTask(taskId: String, todoItem: [String: Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["todo-item" : todoItem] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.changeCompletedDateForTask.path, taskId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<TodoItem>.init(rootObjectName: TWApiClientConstants.APIPath.changeCompletedDateForTask.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } }
mit
5b554792afdd1bed48e4cfbbd2b768b8
53.571106
289
0.530755
6.042239
false
false
false
false
ostatnicky/kancional-ios
Cancional/UI/Main/Cells/SongNameViewCell.swift
1
1713
// // SongNameViewCell.swift // Cancional // // Created by Jiri Ostatnicky on 11/08/2017. // Copyright © 2017 Jiri Ostatnicky. All rights reserved. // import UIKit class SongNameViewCell: GenericCollectionViewCell<Song> { static let height: CGFloat = 50 // MARK: - UI @IBOutlet weak var numberLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! // MARK: - Properties override var isHighlighted: Bool { didSet { animate(highlight: isHighlighted) } } var appearance: SongAppearance { return Persistence.instance.songAppearance } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() setupUI() } override func configure(withItem item: Song?) { numberLabel.text = item?.fullNumber nameLabel.text = item?.name updateAppearance() } } // MARK: - Private private extension SongNameViewCell { func setupUI() { numberLabel.backgroundColor = .clear numberLabel.layer.cornerRadius = 4 numberLabel.layer.borderWidth = 2 numberLabel.font = R.font.ubuntuMedium(size: 17) nameLabel.font = R.font.ubuntuMedium(size: 17) } func updateAppearance() { numberLabel.layer.borderColor = appearance.tileColor.cgColor numberLabel.textColor = appearance.tileColor nameLabel.textColor = appearance.textColor } func animate(highlight: Bool) { UIView.animate(withDuration: 0.1) { [weak self] in self?.contentView.backgroundColor = highlight ? UIColor.Cancional.darkTintColor().withAlphaComponent(0.1) : nil } } }
mit
840394035cbdec24702b38ac7f13419d
24.552239
123
0.634346
4.553191
false
false
false
false
MakiZz/30DaysToLearnSwift3.0
project 26 - coredata/project 26 - coredata/ViewController.swift
1
4308
// // ViewController.swift // project 26 - coredata // // Created by mk on 17/4/5. // Copyright © 2017年 maki. All rights reserved. // import UIKit import CoreData class ViewController: UITableViewController { var listItems = [NSManagedObject]() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .add, target: self, action: #selector(addItem)) } override func viewDidAppear(_ animated: Bool) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let managerContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ListEntity") do { let results = try managerContext.fetch(fetchRequest) listItems = results as! [NSManagedObject] self.tableView.reloadData() } catch { print("error") } } func addItem() { let alertController = UIAlertController.init(title: "New Resolution", message: "", preferredStyle: UIAlertControllerStyle.alert) let confirmAction = UIAlertAction.init(title: "Confirm", style:.default) { (_) in if let field = alertController.textFields![0] as? UITextField{ self.saveItem(itemToSave: field.text!) self.tableView.reloadData() } } let cancelAction = UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil) alertController.addTextField { (textField) in textField.placeholder = "Type somting..." } alertController.addAction(confirmAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } func saveItem(itemToSave: String) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let managerContext = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "ListEntity", in: managerContext) let item = NSManagedObject.init(entity: entity!, insertInto: managerContext) item.setValue(itemToSave, forKey: "item") do { try managerContext.save() listItems.append(item) } catch { print("error") } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell let item = listItems[indexPath.row] cell.textLabel?.text = item.value(forKey: "item") as! String cell.textLabel?.font = UIFont.init(name: "", size: 25) return cell } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let delete = UITableViewRowAction.init(style: .normal, title: "Delete") { (action, index) in let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.persistentContainer.viewContext tableView.reloadRows(at: [indexPath], with: .right) managedContext.delete(self.listItems[indexPath.row]) do{ try managedContext.save() self.listItems.remove(at: indexPath.row) self.tableView.reloadData() }catch{ print("error:delete") } } delete.backgroundColor = UIColor.red return [delete] } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } }
mit
e52eb8e4505f1f10653054d8be0ed604
30.888889
138
0.606039
5.498084
false
false
false
false
FotiosTragopoulos/Core-Geometry
Core Geometry/Par2ViewLine.swift
1
1694
// // Par2ViewLine.swift // Core Geometry // // Created by Fotios Tragopoulos on 13/01/2017. // Copyright © 2017 Fotios Tragopoulos. All rights reserved. // import UIKit class Par2ViewLine: UIView { override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let myShadowOffset = CGSize (width: 10, height: 10) context?.setShadow (offset: myShadowOffset, blur: 8) context?.saveGState() context?.setLineWidth(3.0) context?.setStrokeColor(UIColor.red.cgColor) let xView = viewWithTag(4)?.alignmentRect(forFrame: rect).midX let yView = viewWithTag(4)?.alignmentRect(forFrame: rect).midY let width = self.viewWithTag(4)?.frame.size.width let height = self.viewWithTag(4)?.frame.size.height let size = CGSize(width: width! * 0.8, height: height! * 0.8) let linePlacementX = CGFloat(size.width/2) let linePlacementY = CGFloat(size.height/2) context?.move(to: CGPoint(x: (xView! - linePlacementX), y: (yView! - linePlacementY))) context?.addLine(to: CGPoint(x: (xView! + linePlacementX), y: (yView! + linePlacementY))) let dashArray:[CGFloat] = [10, 4] context?.setLineDash(phase: 3, lengths: dashArray) context?.strokePath() context?.restoreGState() self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil) } }
apache-2.0
2b22bcb64b138415139a965b1e49b295
37.477273
219
0.637921
3.955607
false
false
false
false
dduan/swift
test/IDE/coloring.swift
4
17159
// RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | FileCheck %s // RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | FileCheck %s // XFAIL: broken_std_regex #line 17 "abc.swift" // CHECK: <#kw>#line</#kw> <int>17</int> <str>"abc.swift"</str> @available(iOS 8.0, OSX 10.10, *) // CHECK: <attr-builtin>@available</attr-builtin>(<kw>iOS</kw> <float>8.0</float>, <kw>OSX</kw> <float>10.10</float>, *) func foo() { // CHECK: <kw>if</kw> <#kw>#available</#kw> (<kw>OSX</kw> <float>10.10</float>, <kw>iOS</kw> <float>8.01</float>, *) {<kw>let</kw> <kw>_</kw> = <str>"iOS"</str>} if #available (OSX 10.10, iOS 8.01, *) {let _ = "iOS"} } enum List<T> { case Nil // rdar://21927124 // CHECK: <attr-builtin>indirect</attr-builtin> <kw>case</kw> Cons(T, List) indirect case Cons(T, List) } // CHECK: <kw>struct</kw> S { struct S { // CHECK: <kw>var</kw> x : <type>Int</type> var x : Int // CHECK: <kw>var</kw> y : <type>Int</type>.<type>Int</type> var y : Int.Int // CHECK: <kw>var</kw> a, b : <type>Int</type> var a, b : Int } enum EnumWithDerivedEquatableConformance : Int { // CHECK-LABEL: <kw>enum</kw> EnumWithDerivedEquatableConformance : {{(<type>)}}Int{{(</type>)?}} { case CaseA // CHECK-NEXT: <kw>case</kw> CaseA case CaseB, CaseC // CHECK-NEXT: <kw>case</kw> CaseB, CaseC case CaseD = 30, CaseE // CHECK-NEXT: <kw>case</kw> CaseD = <int>30</int>, CaseE } // CHECK-NEXT: } // CHECK: <kw>class</kw> MyCls { class MyCls { // CHECK: <kw>var</kw> www : <type>Int</type> var www : Int // CHECK: <kw>func</kw> foo(x: <type>Int</type>) {} func foo(x: Int) {} // CHECK: <kw>var</kw> aaa : <type>Int</type> { var aaa : Int { // CHECK: <kw>get</kw> {} get {} // CHECK: <kw>set</kw> {} set {} } // CHECK: <kw>var</kw> bbb : <type>Int</type> { var bbb : Int { // CHECK: <kw>set</kw> { set { // CHECK: <kw>var</kw> tmp : <type>Int</type> var tmp : Int } // CHECK: <kw>get</kw> { get { // CHECK: <kw>var</kw> tmp : <type>Int</type> var tmp : Int } } // CHECK: <kw>subscript</kw> (i : <type>Int</type>, j : <type>Int</type>) -> <type>Int</type> { subscript (i : Int, j : Int) -> Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>return</kw> i + j return i + j } // CHECK: <kw>set</kw>(v) { set(v) { // CHECK: v + i - j v + i - j } } // CHECK: <kw>func</kw> multi(<kw>_</kw> name: <type>Int</type>, otherpart x: <type>Int</type>) {} func multi(_ name: Int, otherpart x: Int) {} } // CHECK-LABEL: <kw>class</kw> Attributes { class Attributes { // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v0: <type>Int</type> @IBOutlet var v0: Int // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-id>@IBOutlet</attr-id> <kw>var</kw> {{(<attr-builtin>)?}}v1{{(</attr-builtin>)?}}: <type>String</type> @IBOutlet @IBOutlet var v1: String // CHECK: <attr-builtin>@objc</attr-builtin> <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v2{{(</attr-builtin>)?}}: <type>String</type> @objc @IBOutlet var v2: String // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-builtin>@objc</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v3{{(</attr-builtin>)?}}: <type>String</type> @IBOutlet @objc var v3: String // CHECK: <attr-builtin>@noreturn</attr-builtin> <kw>func</kw> f0() {} @noreturn func f0() {} // CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f1() {} @available(*, unavailable) func f1() {} // CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@IBAction</attr-builtin> <kw>func</kw> f2() {} @available(*, unavailable) @IBAction func f2() {} // CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f3() {} @IBAction @available(*, unavailable) func f3() {} // CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@noreturn</attr-builtin> <kw>func</kw> f4() {} @IBAction @available(*, unavailable) @noreturn func f4() {} // CHECK: <attr-builtin>mutating</attr-builtin> <kw>func</kw> func_mutating_1() {} mutating func func_mutating_1() {} // CHECK: <attr-builtin>nonmutating</attr-builtin> <kw>func</kw> func_mutating_2() {} nonmutating func func_mutating_2() {} } func stringLikeLiterals() { // CHECK: <kw>var</kw> us1: <type>UnicodeScalar</type> = <str>"a"</str> var us1: UnicodeScalar = "a" // CHECK: <kw>var</kw> us2: <type>UnicodeScalar</type> = <str>"ы"</str> var us2: UnicodeScalar = "ы" // CHECK: <kw>var</kw> ch1: <type>Character</type> = <str>"a"</str> var ch1: Character = "a" // CHECK: <kw>var</kw> ch2: <type>Character</type> = <str>"あ"</str> var ch2: Character = "あ" // CHECK: <kw>var</kw> s1 = <str>"abc абвгд あいうえお"</str> var s1 = "abc абвгд あいうえお" } // CHECK: <kw>var</kw> globComp : <type>Int</type> var globComp : Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>return</kw> <int>0</int> return 0 } } // CHECK: <comment-block>/* foo is the best */</comment-block> /* foo is the best */ // CHECK: <kw>func</kw> foo(n: <type>Float</type>) -> <type>Int</type> { func foo(n: Float) -> Int { // CHECK: <kw>var</kw> fnComp : <type>Int</type> var fnComp : Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>var</kw> a: <type>Int</type> // CHECK: <kw>return</kw> <int>0</int> var a: Int return 0 } } // CHECK: <kw>var</kw> q = {{(<type>)?}}MyCls{{(</type>)?}}() var q = MyCls() // CHECK: <kw>var</kw> ee = <str>"yoo"</str>; var ee = "yoo"; // CHECK: <kw>return</kw> <int>100009</int> return 100009 } // CHECK: <kw>protocol</kw> Prot { protocol Prot { // CHECK: <kw>typealias</kw> Blarg typealias Blarg // CHECK: <kw>func</kw> protMeth(x: <type>Int</type>) func protMeth(x: Int) // CHECK: <kw>var</kw> protocolProperty1: <type>Int</type> { <kw>get</kw> } var protocolProperty1: Int { get } // CHECK: <kw>var</kw> protocolProperty2: <type>Int</type> { <kw>get</kw> <kw>set</kw> } var protocolProperty2: Int { get set } } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-* { <kw>associativity</kw> left <kw>precedence</kw> <int>140</int> }{{$}} infix operator *-* { associativity left precedence 140 } // CHECK: <kw>func</kw> *-*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *-*(l: Int, r: Int) -> Int { return l } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-+* { <kw>associativity</kw> left }{{$}} infix operator *-+* { associativity left } // CHECK: <kw>func</kw> *-+*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *-+*(l: Int, r: Int) -> Int { return l } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *--* {}{{$}} infix operator *--* {} // CHECK: <kw>func</kw> *--*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *--*(l: Int, r: Int) -> Int { return l } // CHECK: <kw>protocol</kw> Prot2 : <type>Prot</type> {} protocol Prot2 : Prot {} // CHECK: <kw>class</kw> SubCls : <type>MyCls</type>, <type>Prot</type> {} class SubCls : MyCls, Prot {} // CHECK: <kw>func</kw> genFn<T : <type>Prot</type> <kw>where</kw> <type>T</type>.<type>Blarg</type> : <type>Prot2</type>>(<kw>_</kw>: <type>T</type>) -> <type>Int</type> {}{{$}} func genFn<T : Prot where T.Blarg : Prot2>(_: T) -> Int {} func f(x: Int) -> Int { // CHECK: <comment-line>// string interpolation is the best</comment-line> // string interpolation is the best // CHECK: <str>"This is string </str>\<anchor>(</anchor>genFn({(a:<type>Int</type> -> <type>Int</type>) <kw>in</kw> a})<anchor>)</anchor><str> interpolation"</str> "This is string \(genFn({(a:Int -> Int) in a})) interpolation" } // CHECK: <kw>func</kw> bar(x: <type>Int</type>) -> (<type>Int</type>, <type>Float</type>) { func bar(x: Int) -> (Int, Float) { // CHECK: foo({{(<type>)?}}Float{{(</type>)?}}()) foo(Float()) } class GenC<T1,T2> {} func test() { // CHECK: {{(<type>)?}}GenC{{(</type>)?}}<<type>Int</type>, <type>Float</type>>() var x = GenC<Int, Float>() } // CHECK: <kw>typealias</kw> MyInt = <type>Int</type> typealias MyInt = Int func test2(x: Int) { // CHECK: <str>"</str>\<anchor>(</anchor>x<anchor>)</anchor><str>"</str> "\(x)" } // CHECK: <kw>class</kw> Observers { class Observers { // CHECK: <kw>var</kw> p1 : <type>Int</type> { var p1 : Int { // CHECK: <kw>willSet</kw>(newValue) {} willSet(newValue) {} // CHECK: <kw>didSet</kw> {} didSet {} } // CHECK: <kw>var</kw> p2 : <type>Int</type> { var p2 : Int { // CHECK: <kw>didSet</kw> {} didSet {} // CHECK: <kw>willSet</kw> {} willSet {} } } // CHECK: <kw>func</kw> test3(o: <type>AnyObject</type>) { func test3(o: AnyObject) { // CHECK: <kw>let</kw> x = o <kw>as</kw>! <type>MyCls</type> let x = o as! MyCls } // CHECK: <kw>func</kw> test4(<kw>inout</kw> a: <type>Int</type>) {{{$}} func test4(inout a: Int) { // CHECK: <kw>if</kw> <#kw>#available</#kw> (<kw>OSX</kw> >= <float>10.10</float>, <kw>iOS</kw> >= <float>8.01</float>) {<kw>let</kw> OSX = <str>"iOS"</str>}}{{$}} if #available (OSX >= 10.10, iOS >= 8.01) {let OSX = "iOS"}} // CHECK: <kw>class</kw> MySubClass : <type>MyCls</type> { class MySubClass : MyCls { // CHECK: <attr-builtin>override</attr-builtin> <kw>func</kw> foo(x: <type>Int</type>) {} override func foo(x: Int) {} // CHECK: <attr-builtin>convenience</attr-builtin> <kw>init</kw>(a: <type>Int</type>) {} convenience init(a: Int) {} } // CHECK: <kw>var</kw> g1 = { (x: <type>Int</type>) -> <type>Int</type> <kw>in</kw> <kw>return</kw> <int>0</int> } var g1 = { (x: Int) -> Int in return 0 } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> ~~ { infix operator ~~ {} // CHECK: <attr-builtin>prefix</attr-builtin> <kw>operator</kw> *~~ { prefix operator *~~ {} // CHECK: <attr-builtin>postfix</attr-builtin> <kw>operator</kw> ~~* { postfix operator ~~* {} func test_defer() { defer { // CHECK: <kw>let</kw> x : <type>Int</type> = <int>0</int> let x : Int = 0 } } // FIXME: blah. // FIXME: blah blah // Something something, FIXME: blah // CHECK: <comment-line>// <comment-marker>FIXME: blah.</comment-marker></comment-line> // CHECK: <comment-line>// <comment-marker>FIXME: blah blah</comment-marker></comment-line> // CHECK: <comment-line>// Something something, <comment-marker>FIXME: blah</comment-marker></comment-line> /* FIXME: blah*/ // CHECK: <comment-block>/* <comment-marker>FIXME: blah*/</comment-marker></comment-block> /* * FIXME: blah * Blah, blah. */ // CHECK: <comment-block>/* // CHECK: * <comment-marker>FIXME: blah</comment-marker> // CHECK: * Blah, blah. // CHECK: */</comment-block> // TODO: blah. // TTODO: blah. // MARK: blah. // CHECK: <comment-line>// <comment-marker>TODO: blah.</comment-marker></comment-line> // CHECK: <comment-line>// T<comment-marker>TODO: blah.</comment-marker></comment-line> // CHECK: <comment-line>// <comment-marker>MARK: blah.</comment-marker></comment-line> // CHECK: <kw>func</kw> test5() -> <type>Int</type> { func test5() -> Int { // CHECK: <comment-line>// <comment-marker>TODO: something, something.</comment-marker></comment-line> // TODO: something, something. // CHECK: <kw>return</kw> <int>0</int> return 0 } func test6<T : Prot>(x: T) {} // CHECK: <kw>func</kw> test6<T : <type>Prot</type>>(x: <type>T</type>) {}{{$}} // http://whatever.com?ee=2&yy=1 and radar://123456 /* http://whatever.com FIXME: see in http://whatever.com/fixme http://whatever.com */ // CHECK: <comment-line>// <comment-url>http://whatever.com?ee=2&yy=1</comment-url> and <comment-url>radar://123456</comment-url></comment-line> // CHECK: <comment-block>/* <comment-url>http://whatever.com</comment-url> <comment-marker>FIXME: see in <comment-url>http://whatever.com/fixme</comment-url></comment-marker> // CHECK: <comment-url>http://whatever.com</comment-url> */</comment-block> // CHECK: <comment-line>// <comment-url>http://whatever.com/what-ever</comment-url></comment-line> // http://whatever.com/what-ever // CHECK: <kw>func</kw> <placeholder><#test1#></placeholder> () {} func <#test1#> () {} /// Brief. /// /// Simple case. /// /// - parameter x: A number /// - parameter y: Another number /// - returns: `x + y` func foo(x: Int, y: Int) -> Int { return x + y } // CHECK: <doc-comment-line>/// Brief. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// Simple case. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> x: A number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> y: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y` // CHECK: </doc-comment-line><kw>func</kw> foo(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y } /// Brief. /// /// Simple case. /// /// - Parameters: /// - x: A number /// - y: Another number /// ///- note: NOTE1 /// /// - NOTE: NOTE2 /// - note: Not a Note field (not at top level) /// - returns: `x + y` func bar(x: Int, y: Int) -> Int { return x + y } // CHECK: <doc-comment-line>/// Brief. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// Simple case. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>Parameters</doc-comment-field>: // CHECK: </doc-comment-line><doc-comment-line>/// - x: A number // CHECK: </doc-comment-line><doc-comment-line>/// - y: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y` // CHECK: </doc-comment-line><kw>func</kw> bar(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y } /** Does pretty much nothing. Not a parameter list: improper indentation. - Parameters: sdfadsf - WARNING: - WARNING: Should only have one field - $$$: Not a field. Empty field, OK: */ func baz() {} // CHECK: <doc-comment-block>/** // CHECK: Does pretty much nothing. // CHECK: Not a parameter list: improper indentation. // CHECK: - Parameters: sdfadsf // CHECK: - <doc-comment-field>WARNING</doc-comment-field>: - WARNING: Should only have one field // CHECK: - $$$: Not a field. // CHECK: Empty field, OK: // CHECK: */</doc-comment-block> // CHECK: <kw>func</kw> baz() {} /***/ func emptyDocBlockComment() {} // CHECK: <doc-comment-block>/***/</doc-comment-block> // CHECK: <kw>func</kw> emptyDocBlockComment() {} /** */ func emptyDocBlockComment2() {} // CHECK: <doc-comment-block>/** // CHECK: */ // CHECK: <kw>func</kw> emptyDocBlockComment2() {} /** */ func emptyDocBlockComment3() {} // CHECK: <doc-comment-block>/** */ // CHECK: <kw>func</kw> emptyDocBlockComment3() {} /**/ func malformedBlockComment(f : () throws -> ()) rethrows {} // CHECK: <doc-comment-block>/**/</doc-comment-block> // CHECK: <kw>func</kw> malformedBlockComment(f : () <kw>throws</kw> -> ()) <attr-builtin>rethrows</attr-builtin> {} //: playground doc comment line func playgroundCommentLine(f : () throws -> ()) rethrows {} // CHECK: <comment-line>//: playground doc comment line</comment-line> /*: playground doc comment multi-line */ func playgroundCommentMultiLine(f : () throws -> ()) rethrows {} // CHECK: <comment-block>/*: // CHECK: playground doc comment multi-line // CHECK: */</comment-block> /// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings) // CHECK: <doc-comment-line>/// [strict weak ordering](<comment-url>http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings</comment-url> func funcTakingFor(for internalName: Int) {} // CHECK: <kw>func</kw> funcTakingFor(for internalName: <type>Int</type>) {} func funcTakingIn(in internalName: Int) {} // CHECK: <kw>func</kw> funcTakingIn(in internalName: <type>Int</type>) {} _ = 123 // CHECK: <int>123</int> _ = -123 // CHECK: <int>-123</int> _ = -1 // CHECK: <int>-1</int> _ = -0x123 // CHECK: <int>-0x123</int> _ = -3.1e-5 // CHECK: <float>-3.1e-5</float> /** aaa - returns: something */ // CHECK: - <doc-comment-field>returns</doc-comment-field>: something "--\"\(x) --" // CHECK: <str>"--\"</str>\<anchor>(</anchor>x<anchor>)</anchor><str> --"</str> // Keep this as the last test /** Trailing off ... func unterminatedBlockComment() {} // CHECK: <comment-line>// Keep this as the last test</comment-line> // CHECK: <doc-comment-block>/** // CHECK: Trailing off ... // CHECK: func unterminatedBlockComment() {} // CHECK: </doc-comment-block>
apache-2.0
960ae84da61c96f04a8d5df85de4f317
34.23251
178
0.597909
2.872505
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKElectro/NKEBrowser/platform-ios/NKE_BrowserWindow_WK_IOS.swift
1
3740
/* * nodekit.io * * Copyright (c) 2016-7 OffGrid Networks. All Rights Reserved. * * 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. */ #if os(iOS) import Foundation import WebKit extension NKE_BrowserWindow { internal func WKScriptEnvironmentReady() -> Void { (self._webView as! WKWebView).navigationDelegate = self self._events.emit("did-finish-load", self._id) } internal func createWKWebView(options: Dictionary<String, AnyObject>) -> Int { hookKeyboard() let id = NKScriptContextFactory.sequenceNumber let createBlock = {() -> Void in let window = self.createWindow(options) as! UIWindow self._window = window let urlAddress: String = (options[NKEBrowserOptions.kPreloadURL] as? String) ?? "https://google.com" let url: NSURL? if (urlAddress == "file:///splash.nkar/splash/views/StartupSplash.html") { var urlpath = NKStorage.mainBundle.pathForResource("StartupSplash", ofType: "html", inDirectory: "splash.nkar/splash/views/") if (urlpath == nil) { urlpath = NSBundle(forClass: NKElectroHost.self).pathForResource("StartupSplash", ofType: "html", inDirectory: "splash.nkar/splash/views/") } url = NSURL.fileURLWithPath(urlpath!) } else { url = NSURL(string: urlAddress) } let config = WKWebViewConfiguration() let webPrefs = WKPreferences() webPrefs.javaScriptEnabled = true webPrefs.javaScriptCanOpenWindowsAutomatically = false config.preferences = webPrefs let webView = WKWebView(frame: CGRect.zero, configuration: config) self._webView = webView window.rootViewController?.view = webView webView.NKcreateScriptContext(id, options: [String: AnyObject](), delegate: self) let requestObj: NSURLRequest = NSURLRequest(URL: url!) webView.loadRequest(requestObj) window.rootViewController?.view.backgroundColor = UIColor(netHex: 0x2690F6) } if (NSThread.isMainThread()) { createBlock() } else { dispatch_async(dispatch_get_main_queue(), createBlock) } return id } } extension NKE_BrowserWindow: WKNavigationDelegate { func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { self._events.emit("did-finish-load", self._id) } func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { self._events.emit("did-fail-loading", (self._id, error.description)) } func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { self._events.emit("did-fail-loading", (self._id, error.description)) } } #endif
apache-2.0
6981cff74032e8567896bb2e758d0d06
26.29927
159
0.601872
4.934037
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Profile/View/CountryVCSectionView.swift
1
990
// // CountryVCSectionView.swift // DYZB // // Created by xiudou on 2017/7/18. // Copyright © 2017年 xiudo. All rights reserved. // import UIKit class CountryVCSectionView: UICollectionReusableView { fileprivate let titleLabel : UILabel = { let titleLabel = UILabel() titleLabel.font = UIFont.systemFont(ofSize: 12) return titleLabel }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white addSubview(titleLabel) } var title : String?{ didSet{ guard let title = title else { return } titleLabel.text = title } } override func layoutSubviews() { super.layoutSubviews() titleLabel.frame = CGRect(x: 5, y: 0, width: sScreenW, height: frame.height) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
7f55166c2a00337c5d473b318de7102c
21.953488
84
0.582573
4.633803
false
false
false
false
daltoniam/Starscream
Sources/Framer/FoundationHTTPHandler.swift
1
4368
////////////////////////////////////////////////////////////////////////////////////////////////// // // FoundationHTTPHandler.swift // Starscream // // Created by Dalton Cherry on 1/25/19. // Copyright © 2019 Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation #if os(watchOS) public typealias FoundationHTTPHandler = StringHTTPHandler #else public class FoundationHTTPHandler: HTTPHandler { var buffer = Data() weak var delegate: HTTPHandlerDelegate? public init() { } public func convert(request: URLRequest) -> Data { let msg = CFHTTPMessageCreateRequest(kCFAllocatorDefault, request.httpMethod! as CFString, request.url! as CFURL, kCFHTTPVersion1_1).takeRetainedValue() if let headers = request.allHTTPHeaderFields { for (aKey, aValue) in headers { CFHTTPMessageSetHeaderFieldValue(msg, aKey as CFString, aValue as CFString) } } if let body = request.httpBody { CFHTTPMessageSetBody(msg, body as CFData) } guard let data = CFHTTPMessageCopySerializedMessage(msg) else { return Data() } return data.takeRetainedValue() as Data } public func parse(data: Data) -> Int { let offset = findEndOfHTTP(data: data) if offset > 0 { buffer.append(data.subdata(in: 0..<offset)) } else { buffer.append(data) } if parseContent(data: buffer) { buffer = Data() } return offset } //returns true when the buffer should be cleared func parseContent(data: Data) -> Bool { var pointer = [UInt8]() data.withUnsafeBytes { pointer.append(contentsOf: $0) } let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() if !CFHTTPMessageAppendBytes(response, pointer, data.count) { return false //not enough data, wait for more } if !CFHTTPMessageIsHeaderComplete(response) { return false //not enough data, wait for more } if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { let nsHeaders = cfHeaders.takeRetainedValue() as NSDictionary var headers = [String: String]() for (key, value) in nsHeaders { if let key = key as? String, let value = value as? String { headers[key] = value } } let code = CFHTTPMessageGetResponseStatusCode(response) if code != HTTPWSHeader.switchProtocolCode { delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code, headers))) return true } delegate?.didReceiveHTTP(event: .success(headers)) return true } delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) return true } public func register(delegate: HTTPHandlerDelegate) { self.delegate = delegate } private func findEndOfHTTP(data: Data) -> Int { let endBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var pointer = [UInt8]() data.withUnsafeBytes { pointer.append(contentsOf: $0) } var k = 0 for i in 0..<data.count { if pointer[i] == endBytes[k] { k += 1 if k == 4 { return i + 1 } } else { k = 0 } } return -1 } } #endif
apache-2.0
4250b00bc0d6cfc3e7d3a4768d1ec104
34.217742
106
0.560568
4.917793
false
false
false
false
zhxnlai/simple-twitter-client
twitter/twitter/ZLBalancedFlowLayout.swift
1
15201
// // ZLLazyBalancedFlowLayout.swift // ZLLazyBalancedFlowLayoutDemo // // Created by Zhixuan Lai on 12/20/14. // Copyright (c) 2014 Zhixuan Lai. All rights reserved. // import UIKit class ZLBalancedFlowLayout: UICollectionViewFlowLayout { /// The ideal row height of items in the grid var rowHeight: CGFloat = 100 { didSet { invalidateLayout() } } /// The option to enforce the ideal row height by changing the aspect ratio of the item if necessary. var enforcesRowHeight: Bool = false { didSet { invalidateLayout() } } private var headerFrames = [CGRect](), footerFrames = [CGRect]() private var itemFrames = [[CGRect]](), itemOriginYs = [[CGFloat]]() private var contentSize = CGSizeZero // TODO: shouldInvalidateLayoutForBoundsChange // MARK: - UICollectionViewLayout override func prepareLayout() { resetItemFrames() contentSize = CGSizeZero if let collectionView = self.collectionView { contentSize = scrollDirection == .Vertical ? CGSize(width: collectionView.bounds.width - collectionView.contentInset.left - collectionView.contentInset.right, height: 0) : CGSize(width: 0, height: collectionView.bounds.size.height - collectionView.contentInset.top - collectionView.contentInset.bottom) for section in (0..<collectionView.numberOfSections()) { headerFrames.append(self.collectionView(collectionView, frameForHeader: true, inSection: section, updateContentSize: &contentSize)) let (frames, originYs) = self.collectionView(collectionView, framesForItemsInSection: section, updateContentSize: &contentSize) itemFrames.append(frames) itemOriginYs.append(originYs) footerFrames.append(self.collectionView(collectionView, frameForHeader: false, inSection: section, updateContentSize: &contentSize)) } } } override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() if let collectionView = self.collectionView { // can be further optimized for section in (0..<collectionView.numberOfSections()) { var sectionIndexPath = NSIndexPath(forItem: 0, inSection: section) if let headerAttributes = layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader, atIndexPath: sectionIndexPath) { if headerAttributes.frame.size != CGSizeZero && CGRectIntersectsRect(headerAttributes.frame, rect) { layoutAttributes.append(headerAttributes) } } if let footerAttributes = layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionFooter, atIndexPath: sectionIndexPath) { if footerAttributes.frame.size != CGSizeZero && CGRectIntersectsRect(footerAttributes.frame, rect) { layoutAttributes.append(footerAttributes) } } var minY = CGFloat(0), maxY = CGFloat(0) if (scrollDirection == .Vertical) { minY = CGRectGetMinY(rect)-CGRectGetHeight(rect) maxY = CGRectGetMaxY(rect) } else { minY = CGRectGetMinX(rect)-CGRectGetWidth(rect) maxY = CGRectGetMaxX(rect) } let lowerIndex = binarySearch(itemOriginYs[section], value: minY) let upperIndex = binarySearch(itemOriginYs[section], value: maxY) for item in lowerIndex..<upperIndex { layoutAttributes.append(self.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: item, inSection: section))) } } } return layoutAttributes } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { var attributes = super.layoutAttributesForItemAtIndexPath(indexPath) attributes.frame = itemFrames[indexPath.section][indexPath.row] return attributes } override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { var attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, withIndexPath: indexPath) switch (elementKind) { case UICollectionElementKindSectionHeader: attributes.frame = headerFrames[indexPath.section] case UICollectionElementKindSectionFooter: attributes.frame = footerFrames[indexPath.section] default: return nil } // If there is no header or footer, we need to return nil to prevent a crash from UICollectionView private methods. if(CGRectIsEmpty(attributes.frame)) { return nil; } return attributes } override func collectionViewContentSize() -> CGSize { return contentSize } // MARK: - UICollectionViewLayout Helpers private func collectionView(collectionView:UICollectionView, frameForHeader isForHeader:Bool, inSection section:Int, inout updateContentSize contentSize:CGSize) -> CGRect { var size = referenceSizeForHeader(isForHeader, inSection: section), frame = CGRectZero if (scrollDirection == .Vertical) { frame = CGRect(x: 0, y: contentSize.height, width: CGRectGetWidth(collectionView.bounds), height: size.height); contentSize = CGSize(width: contentSize.width, height: contentSize.height+size.height) } else { frame = CGRect(x: contentSize.width, y: 0, width: size.width, height: CGRectGetHeight(collectionView.bounds)); contentSize = CGSize(width: contentSize.width+size.width, height: contentSize.height) } return frame } private func collectionView(collectionView:UICollectionView, framesForItemsInSection section:Int, inout updateContentSize contentSize:CGSize) -> ([CGRect], [CGFloat]) { let maxWidth = Float(scrollDirection == .Vertical ? contentSize.width : contentSize.height), widths = map(0..<collectionView.numberOfItemsInSection(section), {(item: Int) -> Float in let itemSize = self.sizeForItemAtIndexPath(NSIndexPath(forItem: item, inSection: section)), ratio = self.scrollDirection == .Vertical ? itemSize.width/itemSize.height : itemSize.height/itemSize.width return min(Float(ratio*self.rowHeight), Float(maxWidth)) }) // parition widths var partitions = partition(widths, max: Float(maxWidth)) let minimumInteritemSpacing = minimumInteritemSpacingForSection(section), minimumLineSpacing = minimumLineSpacingForSection(section), inset = insetForSection(section) var framesInSection = [CGRect](), originYsInSection = [CGFloat](), origin = scrollDirection == .Vertical ? CGPoint(x: inset.left, y: contentSize.height+inset.top) : CGPoint(x: contentSize.width+inset.left, y: inset.top) for row in partitions { // contentWidth/summedWidth let innerMargin = Float(CGFloat(row.count-1)*minimumInteritemSpacing), outterMargin = scrollDirection == .Vertical ? Float(inset.left+inset.right) : Float(inset.top+inset.bottom), contentWidth = maxWidth - outterMargin - innerMargin, widthRatio = CGFloat(contentWidth/row.reduce(0, combine: +)), heightRatio = enforcesRowHeight ? 1 : widthRatio for width in row { let size = scrollDirection == .Vertical ? CGSize(width: CGFloat(width)*widthRatio, height: rowHeight*heightRatio) : CGSize(width: rowHeight*heightRatio, height: CGFloat(width)*widthRatio) let frame = CGRect(origin: origin, size: size) framesInSection.append(frame) if scrollDirection == .Vertical { origin = CGPoint(x: origin.x+frame.width+minimumInteritemSpacing, y: origin.y) originYsInSection.append(origin.y) } else { origin = CGPoint(x: origin.x, y: origin.y+frame.height+minimumInteritemSpacing) originYsInSection.append(origin.x) } } if scrollDirection == .Vertical { origin = CGPoint(x: inset.left, y: origin.y+framesInSection.last!.height+minimumLineSpacing+inset.bottom) } else { origin = CGPoint(x: origin.x+framesInSection.last!.width+minimumLineSpacing+inset.right, y: inset.top) } } if scrollDirection == .Vertical { contentSize = CGSize(width: contentSize.width, height: origin.y) } else { contentSize = CGSize(width: origin.x, height: contentSize.height) } return (framesInSection, originYsInSection) } private func resetItemFrames() { headerFrames = [CGRect]() footerFrames = [CGRect]() itemFrames = [[CGRect]]() itemOriginYs = [[CGFloat]]() } // MARK: - Delegate Helpers private func referenceSizeForHeader(isForHeader: Bool, inSection section: Int) -> CGSize { if let collectionView = self.collectionView { if let delegate = collectionView.delegate? as? UICollectionViewDelegateFlowLayout { var size:CGSize? = nil if isForHeader { size = delegate.collectionView?(collectionView, layout: self, referenceSizeForHeaderInSection: section) } else { size = delegate.collectionView?(collectionView, layout: self, referenceSizeForFooterInSection: section) } if let size = size { return size } } } if isForHeader { return headerReferenceSize } else { return footerReferenceSize } } private func minimumLineSpacingForSection(section: Int) -> CGFloat { if let collectionView = self.collectionView { if let delegate = collectionView.delegate? as? UICollectionViewDelegateFlowLayout { if let minimumLineSpacing = delegate.collectionView?(collectionView, layout: self, minimumLineSpacingForSectionAtIndex: section) { return minimumLineSpacing } } } return minimumLineSpacing } private func minimumInteritemSpacingForSection(section: Int) -> CGFloat { if let collectionView = self.collectionView { if let delegate = collectionView.delegate? as? UICollectionViewDelegateFlowLayout { if let minimumInteritemSpacing = delegate.collectionView?(collectionView, layout: self, minimumInteritemSpacingForSectionAtIndex: section) { return minimumInteritemSpacing } } } return minimumInteritemSpacing } private func sizeForItemAtIndexPath(indexPath: NSIndexPath) -> CGSize { if let collectionView = self.collectionView { if let delegate = collectionView.delegate? as? UICollectionViewDelegateFlowLayout { if let size = delegate.collectionView?(collectionView, layout: self, sizeForItemAtIndexPath:indexPath) { return size } } } return itemSize } private func insetForSection(section: Int) -> UIEdgeInsets { if let collectionView = self.collectionView { if let delegate = collectionView.delegate? as? UICollectionViewDelegateFlowLayout { if let inset = delegate.collectionView?(collectionView, layout: self, insetForSectionAtIndex: section) { return inset } } } return sectionInset } // MARK: - () private func binarySearch<T: Comparable>(array: Array<T>, value:T) -> Int{ var imin=0, imax=array.count while imin<imax { var imid = imin+(imax-imin)/2 if array[imid] < value { imin = imid+1 } else { imax = imid } } return imin } // parition the widths in to rows using dynamic programming O(n^2) private func partition(values: [Float], max:Float) -> [[Float]] { var numValues = values.count if numValues == 0 { return [] } var slacks = [[Float]](count: numValues, repeatedValue: [Float](count: numValues, repeatedValue: Float.infinity)) for var from=0; from<numValues; from++ { for var to=from; to<numValues; to++ { var slack = to==from ? max-values[to] : slacks[from][to-1]-values[to] if slack >= 0 { slacks[from][to] = slack } else { break } } } // build up values of optimal solutions var opt = [Float](count: numValues, repeatedValue: 0) opt[0] = pow(slacks[0][0], 2) for var to=1; to<numValues; to++ { var minVal = Float.infinity for var from=0; from<=to; from++ { var slack = pow(slacks[from][to], 2) if slack > pow(max, 2) { continue } var opp = (from==0 ? 0 : opt[from-1]) minVal = min(minVal, slack+opp) } opt[to] = minVal } // traceback the optimal solution var partitions = [[Float]]() findSolution(values, slacks: slacks, opt: opt, to: numValues-1, partitions: &partitions) return partitions } // traceback solution private func findSolution(values: [Float], slacks:[[Float]], opt: [Float], to: Int, inout partitions: [[Float]]) { if to<0 { partitions = partitions.reverse() } else { var minVal = Float.infinity, minIndex = 0 for var from=to; from>=0; from-- { if slacks[from][to] == Float.infinity { continue } var curVal = pow(slacks[from][to], 2) + (from==0 ? 0 : opt[from-1]) if minVal > curVal { minVal = curVal minIndex = from } } partitions.append([Float](values[minIndex...to])) findSolution(values, slacks: slacks, opt: opt, to: minIndex-1, partitions: &partitions) } } }
mit
dfefb663361a08a7fac0ea8646deb9ef
43.317784
176
0.597987
5.467986
false
false
false
false
benlangmuir/swift
test/Generics/sr15009.swift
2
511
// RUN: %target-typecheck-verify-swift -debug-generic-signatures 2>&1 | %FileCheck %s // https://github.com/apple/swift/issues/57339 // CHECK: sr15009.(file).P@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.[P]A.[Q]B, Self.[P]A : Q> protocol P { associatedtype A: Q where A.B == Self } // CHECK: sr15009.(file).Q@ // CHECK-NEXT: Requirement signature: <Self where Self : CaseIterable, Self == Self.[Q]B.[P]A, Self.[Q]B : P> protocol Q: CaseIterable { associatedtype B: P where B.A == Self }
apache-2.0
f4a16492a0a0d14d91f788c66f61e01a
45.454545
109
0.677104
3.023669
false
false
false
false
dmonagle/vapor-graph
Tests/VaporGraphTests/GraphModelStoreTests.swift
1
1639
// // GraphModelStoreTests.swift // Graph // // Created by David Monagle on 20/3/17. // // import XCTest import Fluent @testable import VaporGraph class GraphModelStoreTests: XCTestCase { func testStoreAndRetrieve() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let store = GraphModelStore() let dave = Person(named: "Dave") dave.id = 1 XCTAssertEqual(store.count, 0) try store.add(dave) XCTAssertEqual(store.count, 1) let retrieved : Person? = store.retrieve(id: 1) XCTAssertNotNil(retrieved) XCTAssertEqual(retrieved?.name, "Dave") } func testFilter() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let store = GraphModelStore() let dave = Person(named: "Dave") dave.id = 1 let alan = Person(named: "Alan") alan.id = 2 try store.add(dave) try store.add(alan) let f1 : [Person] = try store.filter { person in return person.name == "Dave" ? true : false } XCTAssertEqual(f1.count, 1) XCTAssertEqual(f1[0].name, "Dave") } static var allTests : [(String, (GraphModelStoreTests) -> () throws -> Void)] { return [ ("testStoreAndRetrieve", testStoreAndRetrieve), ("testFilter", testFilter), ] } }
mit
7c3386fcbda8c6b98bb582a7bfb0426b
27.258621
96
0.580842
4.370667
false
true
false
false
feiin/DWBubbleMenuButton.Swift
DWBubbleMenuButton.Swift/DWBubbleMenuButton.Swift/DWBubbleMenuButton.swift
1
18734
// // DWBubbleMenuButton.swift // DWBubbleMenuButton.Swift // // Created by feiin on 14/10/25. // Copyright (c) 2014 year swiftmi. All rights reserved. // import Foundation import UIKit ///ExpansionDirection enum ExpansionDirection:Int{ case directionLeft = 0 case directionRight case directionUp case directionDown } ///---- ///DWBubbleMenuViewDelegate protocol protocol DWBubbleMenuViewDelegate:NSObjectProtocol{ func bubbleMenuButtonWillExpand(_ expandableView:DWBubbleMenuButton) func bubbleMenuButtonDidExpand(_ expandableView:DWBubbleMenuButton) func bubbleMenuButtonWillCollapse(_ expandableView:DWBubbleMenuButton) func bubbleMenuButtonDidCollapse(_ expandableView:DWBubbleMenuButton) } ///DWBubbleMenuButton class DWBubbleMenuButton:UIView,UIGestureRecognizerDelegate{ var tapGestureRecognizer:UITapGestureRecognizer! var buttonContainer:[UIButton] = [] var originFrame:CGRect! var direction:ExpansionDirection? weak var delegate:DWBubbleMenuViewDelegate? var buttonSpacing:CGFloat = 20 var _homeButtonView:UIView? var homeButtonView:UIView?{ get{ return _homeButtonView } set{ if(self._homeButtonView != newValue){ self._homeButtonView = newValue } if self._homeButtonView!.isDescendant(of: self) == false { self.addSubview(self._homeButtonView!) } } } var animationDuration:Double = 0.25 var isCollapsed:Bool = false var collapseAfterSelection = false var animatedHighlighting = false var standbyAlpha:CGFloat = 0.0 var highlightAlpha:CGFloat = 0.0 func handleTapGesture(_ sender: UITapGestureRecognizer) { if sender.state == .ended { let touchLocation:CGPoint = self.tapGestureRecognizer.location(in: self) if (self.collapseAfterSelection && isCollapsed == false && self.homeButtonView!.frame.contains(touchLocation) == false) { self.dismissButtons() } } } func _animateWithBlock(_ block: (() -> Void)!){ UIView.transition(with: self, duration: self.animationDuration, options: UIViewAnimationOptions.beginFromCurrentState, animations: block, completion: nil) } func _setTouchHighlighted(_ highlighted:Bool) { let alphaValue = highlighted ? highlightAlpha : standbyAlpha; if (self.homeButtonView!.alpha == alphaValue) { return } if (animatedHighlighting) { self._animateWithBlock{ if(self.homeButtonView != nil){ self.homeButtonView!.alpha = alphaValue; } } } else { self._animateWithBlock{ if(self.homeButtonView != nil){ self.homeButtonView!.alpha = alphaValue; } } } } ///add buttons func addButtons(_ buttons:[UIButton]){ for button in buttons{ self.addButton(button) } if(self.homeButtonView != nil){ self.bringSubview(toFront: self.homeButtonView!) } } ///add button func addButton(_ button:UIButton){ if !self._containsButton(button) { self.buttonContainer.append(button) self.addSubview(button) button.isHidden=true } } func _containsButton(_ button:UIButton)->Bool { for b in self.buttonContainer { if b == button{ return true } } return false } func showButtons(){ if (self.delegate?.responds(to: Selector("bubbleMenuButtonWillExpand:")) != nil) { self.delegate?.bubbleMenuButtonWillExpand(self) } self._prepareForButtonExpansion() self.isUserInteractionEnabled = false CATransaction.begin() CATransaction.setAnimationDuration(animationDuration) CATransaction.setCompletionBlock{ for btn in self.buttonContainer { (btn as UIButton).transform = CGAffineTransform.identity } if(self.delegate != nil){ if (self.delegate?.responds(to: Selector("bubbleMenuButtonDidExpand:")) != nil) { self.delegate?.bubbleMenuButtonDidExpand(self) } } self.isUserInteractionEnabled = true } var btnContainer:[UIButton] = buttonContainer if self.direction == .directionUp || direction == .directionLeft { btnContainer = Array(self.buttonContainer.reversed()) } for i in 0..<btnContainer.count { let index = btnContainer.count - (i + 1) let button = btnContainer[index] button.isHidden = false // position animation let positionAnimation = CABasicAnimation(keyPath: "position") var originPosition = CGPoint.zero var finalPosition = CGPoint.zero switch (self.direction!) { case .directionLeft: originPosition = CGPoint(x: self.frame.size.width - self.homeButtonView!.frame.size.width, y: self.frame.size.height/2) let x = self.frame.size.width - self.homeButtonView!.frame.size.width - button.frame.size.width/2.0 - self.buttonSpacing - ((button.frame.size.width + self.buttonSpacing)*CGFloat(index)) finalPosition = CGPoint(x:x,y: self.frame.size.height/2.0) case .directionRight: originPosition = CGPoint(x: self.homeButtonView!.frame.size.width, y: self.frame.size.height/2.0) let x = self.homeButtonView!.frame.size.width + self.buttonSpacing + button.frame.size.width/2.0 + ((button.frame.size.width + self.buttonSpacing)*CGFloat(index)) finalPosition = CGPoint(x:x, y: self.frame.size.height/2.0) case .directionUp: originPosition = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height - self.homeButtonView!.frame.size.height) finalPosition = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height - self.homeButtonView!.frame.size.height - self.buttonSpacing - button.frame.size.height/2.0 - ((button.frame.size.height + self.buttonSpacing)*CGFloat(index))); case .directionDown: originPosition = CGPoint(x: self.frame.size.width/2.0, y: self.homeButtonView!.frame.size.height) finalPosition = CGPoint(x: self.frame.size.width/2.0, y: self.homeButtonView!.frame.size.height + self.buttonSpacing + button.frame.size.height/2.0 + ((button.frame.size.height + self.buttonSpacing)*CGFloat(index))); } positionAnimation.duration = self.animationDuration; positionAnimation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseInEaseOut) positionAnimation.fromValue = NSValue(cgPoint:originPosition) positionAnimation.toValue = NSValue(cgPoint:finalPosition) positionAnimation.beginTime = CACurrentMediaTime() + (self.animationDuration/Double(btnContainer.count)*Double(i)); positionAnimation.fillMode = kCAFillModeForwards; positionAnimation.isRemovedOnCompletion = false; button.layer.add(positionAnimation,forKey: "positionAnimation") button.layer.position = finalPosition; // scale animation let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.duration = self.animationDuration; scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) scaleAnimation.fromValue = NSNumber(value: 0.01 as Float) scaleAnimation.toValue = NSNumber(value: 1.0 as Float) scaleAnimation.beginTime = CACurrentMediaTime() + (animationDuration/Double(btnContainer.count) * Double(i)) + 0.03; scaleAnimation.fillMode = kCAFillModeForwards; scaleAnimation.isRemovedOnCompletion = false; button.layer.add(scaleAnimation, forKey: "scaleAnimation") button.transform = CGAffineTransform(scaleX: 0.01, y: 0.01); } CATransaction.commit() isCollapsed = false } func _finishCollapse(){ self.frame = originFrame; } func dismissButtons(){ if (self.delegate?.responds(to: Selector("bubbleMenuButtonWillCollapse:")) != nil) { self.delegate?.bubbleMenuButtonWillCollapse(self) } self.isUserInteractionEnabled = false; CATransaction.begin() CATransaction.setAnimationDuration(self.animationDuration) CATransaction.setCompletionBlock{ self._finishCollapse() for btn in self.buttonContainer { let button = btn as UIButton button.transform = CGAffineTransform.identity button.isHidden = true } if (self.delegate != nil) { if (self.delegate?.responds(to: Selector("bubbleMenuButtonDidCollapse:")) != nil) { self.delegate?.bubbleMenuButtonDidCollapse(self) } } self.isUserInteractionEnabled = true; } var index=0; let arr = (0...(buttonContainer.count-1)).reversed() for i in arr { var button = buttonContainer[i] if (self.direction == .directionDown || self.direction == .directionRight) { button = buttonContainer[index] } // scale animation let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.duration = self.animationDuration; scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) scaleAnimation.fromValue = NSNumber(value: 1.0 as Float) scaleAnimation.toValue = NSNumber(value: 0.01 as Float) scaleAnimation.beginTime = CACurrentMediaTime() + (self.animationDuration/Double(buttonContainer.count) * Double(index)) + 0.03; scaleAnimation.fillMode = kCAFillModeForwards; scaleAnimation.isRemovedOnCompletion = false; button.layer.add(scaleAnimation, forKey: "scaleAnimation") button.transform = CGAffineTransform(scaleX: 1.0, y: 1.0); // position animation let positionAnimation = CABasicAnimation(keyPath: "position") let originPosition = button.layer.position; var finalPosition = CGPoint.zero; switch (self.direction!) { case .directionLeft: finalPosition = CGPoint(x: self.frame.size.width - self.homeButtonView!.frame.size.width, y: self.frame.size.height/2.0) case .directionRight: finalPosition = CGPoint(x: self.homeButtonView!.frame.size.width, y: self.frame.size.height/2.0) case .directionUp: finalPosition = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height - self.homeButtonView!.frame.size.height); case .directionDown: finalPosition = CGPoint(x: self.frame.size.width/2.0, y: self.homeButtonView!.frame.size.height) } positionAnimation.duration = self.animationDuration; positionAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) positionAnimation.fromValue = NSValue(cgPoint:originPosition) positionAnimation.toValue = NSValue(cgPoint:finalPosition) positionAnimation.beginTime = CACurrentMediaTime() + (self.animationDuration/Double(self.buttonContainer.count) * Double(index)); positionAnimation.fillMode = kCAFillModeForwards; positionAnimation.isRemovedOnCompletion = false; button.layer.add(positionAnimation, forKey:"positionAnimation") button.layer.position = originPosition; index += 1; } CATransaction.commit() isCollapsed = true; } func _prepareForButtonExpansion(){ let buttonHeight:CGFloat = self._combinedButtonHeight() let buttonWidth:CGFloat = self._combinedButtonWidth() switch(self.direction!){ case .directionUp: self.homeButtonView!.autoresizingMask = UIViewAutoresizing.flexibleTopMargin var frame = self.frame frame.origin.y -= buttonHeight frame.size.height += buttonHeight self.frame = frame case .directionDown: self.homeButtonView!.autoresizingMask = UIViewAutoresizing.flexibleBottomMargin var frame = self.frame frame.size.height += buttonHeight self.frame = frame case .directionLeft: self.homeButtonView!.autoresizingMask = UIViewAutoresizing.flexibleLeftMargin var frame = self.frame frame.origin.x -= buttonWidth frame.size.width += buttonWidth self.frame = frame case .directionRight: self.homeButtonView!.autoresizingMask = UIViewAutoresizing.flexibleRightMargin var frame = self.frame frame.size.width += buttonWidth self.frame = frame } } func _combinedButtonHeight() -> CGFloat { var height:CGFloat = 0; for button in buttonContainer { height += button.frame.size.height + self.buttonSpacing } return height } func _combinedButtonWidth() -> CGFloat { var width:CGFloat = 0; for button in buttonContainer { width += button.frame.size.width + self.buttonSpacing } return width } func _defaultInit() { self.clipsToBounds = true; self.layer.masksToBounds = true; self.direction = .directionUp; self.animatedHighlighting = true; self.collapseAfterSelection = true; self.standbyAlpha = 1.0; self.highlightAlpha = 0.450; self.originFrame = self.frame; self.buttonSpacing = 20.0; isCollapsed = true; self.originFrame = self.frame; self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(DWBubbleMenuButton.handleTapGesture(_:))) self.tapGestureRecognizer.cancelsTouchesInView = false self.tapGestureRecognizer.delegate = self self.addGestureRecognizer(self.tapGestureRecognizer) } override init(frame: CGRect) { super.init(frame: frame) _defaultInit() } convenience init(frame: CGRect,expansionDirection direction:ExpansionDirection) { self.init(frame: frame) self._defaultInit() self.direction = direction } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //pragma mark - //pragma mark Touch Handling Methods override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) // var touch = touches.first self._setTouchHighlighted(true) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) //print("touchesMoved") let touch = touches.first! as UITouch self._setTouchHighlighted(false) if(self.homeButtonView!.frame.contains(touch.location(in: self))) { if(isCollapsed){ self.showButtons() } else{ self.dismissButtons() } } } override func touchesCancelled(_ touches:Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) self._setTouchHighlighted(false) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) let touch=touches.first! as UITouch self._setTouchHighlighted(self.homeButtonView!.frame.contains(touch.location(in: self))) } //pragma mark - //pragma mark UIGestureRecognizer Delegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { let touchLocation = touch.location(in: self) if (self._subviewForPoint(touchLocation) != self && collapseAfterSelection) { return true; } return false; } func _subviewForPoint(_ point:CGPoint) -> UIView { for subView in self.subviews { if (subView.frame.contains(point)) { return subView ; } } return self } }
mit
26561300cdbf8efb867f5581f992828e
31.637631
162
0.568645
5.498679
false
false
false
false
toggl/superday
teferi/UI/Modules/Permissions/PermissionPresenter.swift
1
1493
import UIKit enum PermissionRequestType { case location case motion case notification } class PermissionPresenter { private weak var viewController : PermissionViewController! private let viewModelLocator : ViewModelLocator private init(viewModelLocator: ViewModelLocator) { self.viewModelLocator = viewModelLocator } static func create(with viewModelLocator: ViewModelLocator, type:PermissionRequestType) -> PermissionViewController { let presenter = PermissionPresenter(viewModelLocator: viewModelLocator) let viewController = StoryboardScene.Main.permission.instantiate() let viewModel = permissionViewModel(forType: type, viewModelLocator: viewModelLocator) viewController.inject(presenter: presenter, viewModel: viewModel) presenter.viewController = viewController return viewController } private static func permissionViewModel(forType type:PermissionRequestType, viewModelLocator:ViewModelLocator) -> PermissionViewModel { switch type { case .motion: return viewModelLocator.getMotionPermissionViewModel() case .location: return viewModelLocator.getLocationPermissionViewModel() case .notification: return viewModelLocator.getNotificationPermissionViewModel() } } func dismiss() { viewController.dismiss(animated: true) } }
bsd-3-clause
ba53655adbc041908a74d872ad6bc751
28.86
137
0.701942
6.380342
false
false
false
false
thisIsAndrewH/Distractification-iOS
Distractification-iOS/AppDelegate.swift
1
5123
// // AppDelegate.swift // Distractification-iOS // // Created by Andrew Harris on 5/20/16. // Copyright © 2016 Andrew Harris. All rights reserved. // import UIKit import Firebase import FirebaseMessaging import FirebaseInstanceID @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Register for remote notifications let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() // Override point for customization after application launch. FIRApp.configure() // Add observer for InstanceID token refresh callback. NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotificaiton), name: kFIRInstanceIDTokenRefreshNotification, object: nil) return true } // [START receive_message] func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. // TODO: Handle data of notification // Print message ID. print("Message ID: \(userInfo["gcm.message_id"]!)") // Print full message. print("%@", userInfo) } // [END receive_message] // [START refresh_token] func tokenRefreshNotificaiton(notification: NSNotification) { let refreshedToken = FIRInstanceID.instanceID().token()! print("InstanceID token: \(refreshedToken)") // Connect to FCM since connection may have failed when attempted before having a token. connectToFcm() } // [END refresh_token] // [START connect_to_fcm] func connectToFcm() { FIRMessaging.messaging().connectWithCompletion { (error) in if (error != nil) { print("Unable to connect with FCM. \(error)") } else { print("Connected to FCM.") } } } // [END connect_to_fcm] 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. if (SettingsViewController().reminderToggleStatus == true) { Reminder().setReminder() } } 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. // [START disconnect_from_fcm] FIRMessaging.messaging().disconnect() print("Disconnected from FCM.") // [END disconnect_from_fcm] let timeEnteredBackground = NSDate() userDefaults.setValue(timeEnteredBackground, forKey: "timeEnteredBackground") } 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. //clears reminder since it's not needed if the user is already in the app if (SettingsViewController().reminderToggleStatus == true) { Reminder().clearReminder() } } 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. Utilities().printWrapper("When the app was last used: " + String(userDefaults.valueForKey("timeEnteredBackground"))) connectToFcm() } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
6604b4bcd6431929d7724cdee0d33b61
41.683333
285
0.675908
5.531317
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch12/12.5使用下标.playground/section-1.swift
1
1244
// 本书网站:http://www.51work6.com/swift.php // 智捷iOS课堂在线课堂:http://v.51work6.com // 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973 // 智捷iOS课堂微信公共账号:智捷iOS课堂 // 作者微博:http://weibo.com/516inc // 官方csdn博客:http://blog.csdn.net/tonny_guan // Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected] struct DoubleDimensionalArray { let rows: Int, columns: Int var grid: [Int] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns grid = Array(count: rows * columns, repeatedValue: 0) } subscript(row: Int, col: Int) -> Int { get { return grid[(row * columns) + col] } set (newValue1){ grid[(row * columns) + col] = newValue1 } } } let COL_NUM = 10 let ROW_NUM = 10 var ary2 = DoubleDimensionalArray(rows: ROW_NUM, columns: COL_NUM) for var i = 0; i < ROW_NUM; i++ { for var j = 0; j < COL_NUM; j++ { ary2[i,j] = i * j } } for var i = 0; i < ROW_NUM; i++ { for var j = 0; j < COL_NUM; j++ { print("\t \(ary2[i,j])") } print("\n") }
gpl-2.0
ab80324f265ea873dae4af1e6336383a
21.5
66
0.546263
2.88946
false
false
false
false
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/App/Common/SideMenuManager.swift
1
17193
// SideMenuManager // SlideMenu // // Created by Uber - Abdul on 21/02/17. // Copyright © 2017 example.com. All rights reserved. // import UIKit open class SideMenuManager : NSObject { @objc public enum MenuPushStyle : Int { case defaultBehavior, popWhenPossible, replace, preserve, preserveAndHideBackButton, subMenu } @objc public enum MenuPresentMode : Int { case menuSlideIn, viewSlideOut, viewSlideInOut, menuDissolveIn } // Bounds which has been allocated for the app on the whole device screen internal static var appScreenRect: CGRect { let appWindowRect = UIApplication.shared.keyWindow?.bounds ?? UIWindow().bounds return appWindowRect } /** The push style of the menu. There are six modes in MenuPushStyle: - defaultBehavior: The view controller is pushed onto the stack. - popWhenPossible: If a view controller already in the stack is of the same class as the pushed view controller, the stack is instead popped back to the existing view controller. This behavior can help users from getting lost in a deep navigation stack. - preserve: If a view controller already in the stack is of the same class as the pushed view controller, the existing view controller is pushed to the end of the stack. This behavior is similar to a UITabBarController. - preserveAndHideBackButton: Same as .preserve and back buttons are automatically hidden. - replace: Any existing view controllers are released from the stack and replaced with the pushed view controller. Back buttons are automatically hidden. This behavior is ideal if view controllers require a lot of memory or their state doesn't need to be preserved.. - subMenu: Unlike all other behaviors that push using the menu's presentingViewController, this behavior pushes view controllers within the menu. Use this behavior if you want to display a sub menu. */ open static var menuPushStyle: MenuPushStyle = .defaultBehavior /** The presentation mode of the menu. There are four modes in MenuPresentMode: - menuSlideIn: Menu slides in over of the existing view. - viewSlideOut: The existing view slides out to reveal the menu. - viewSlideInOut: The existing view slides out while the menu slides in. - menuDissolveIn: The menu dissolves in over the existing view controller. */ open static var menuPresentMode: MenuPresentMode = .viewSlideOut /// Prevents the same view controller (or a view controller of the same class) from being pushed more than once. Defaults to true. open static var menuAllowPushOfSameClassTwice = true /// Width of the menu when presented on screen, showing the existing view controller in the remaining space. Default is 75% of the screen width. open static var menuWidth: CGFloat = max(round(min((appScreenRect.width), (appScreenRect.height)) * 0.75), 240) /// Duration of the animation when the menu is presented without gestures. Default is 0.35 seconds. open static var menuAnimationPresentDuration: Double = 0.35 /// Duration of the animation when the menu is dismissed without gestures. Default is 0.35 seconds. open static var menuAnimationDismissDuration: Double = 0.35 /// Duration of the remaining animation when the menu is partially dismissed with gestures. Default is 0.2 seconds. open static var menuAnimationCompleteGestureDuration: Double = 0.20 /// Amount to fade the existing view controller when the menu is presented. Default is 0 for no fade. Set to 1 to fade completely. open static var menuAnimationFadeStrength: CGFloat = 0 /// The amount to scale the existing view controller or the menu view controller depending on the `menuPresentMode`. Default is 1 for no scaling. Less than 1 will shrink, greater than 1 will grow. open static var menuAnimationTransformScaleFactor: CGFloat = 1 /// The background color behind menu animations. Depending on the animation settings this may not be visible. If `menuFadeStatusBar` is true, this color is used to fade it. Default is black. open static var menuAnimationBackgroundColor: UIColor? /// The shadow opacity around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 0.5 for 50% opacity. open static var menuShadowOpacity: Float = 0.5 /// The shadow color around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is black. open static var menuShadowColor = UIColor.black /// The radius of the shadow around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 5. open static var menuShadowRadius: CGFloat = 5 /// The left menu swipe to dismiss gesture. open static weak var menuLeftSwipeToDismissGesture: UIPanGestureRecognizer? /// The right menu swipe to dismiss gesture. open static weak var menuRightSwipeToDismissGesture: UIPanGestureRecognizer? /// Enable or disable interaction with the presenting view controller while the menu is displayed. Enabling may make it difficult to dismiss the menu or cause exceptions if the user tries to present and already presented menu. Default is false. open static var menuPresentingViewControllerUserInteractionEnabled: Bool = false /// The strength of the parallax effect on the existing view controller. Does not apply to `menuPresentMode` when set to `ViewSlideOut`. Default is 0. open static var menuParallaxStrength: Int = 0 /// Draws the `menuAnimationBackgroundColor` behind the status bar. Default is true. open static var menuFadeStatusBar = true /// The animation options when a menu is displayed. Ignored when displayed with a gesture. open static var menuAnimationOptions: UIViewAnimationOptions = .curveEaseInOut /// The animation spring damping when a menu is displayed. Ignored when displayed with a gesture. open static var menuAnimationUsingSpringWithDamping: CGFloat = 1 /// The animation initial spring velocity when a menu is displayed. Ignored when displayed with a gesture. open static var menuAnimationInitialSpringVelocity: CGFloat = 1 /// -Warning: Deprecated. Use `menuPushStyle = .subMenu` instead. @available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .subMenu` instead.") open static var menuAllowSubmenus: Bool { get { return menuPushStyle == .subMenu } set { if newValue { menuPushStyle = .subMenu } } } /// -Warning: Deprecated. Use `menuPushStyle = .popWhenPossible` instead. @available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .popWhenPossible` instead.") open static var menuAllowPopIfPossible: Bool { get { return menuPushStyle == .popWhenPossible } set { if newValue { menuPushStyle = .popWhenPossible } } } /// -Warning: Deprecated. Use `menuPushStyle = .replace` instead. @available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .replace` instead.") open static var menuReplaceOnPush: Bool { get { return menuPushStyle == .replace } set { if newValue { menuPushStyle = .replace } } } /// -Warning: Deprecated. Use `menuAnimationTransformScaleFactor` instead. @available(*, deprecated, renamed: "menuAnimationTransformScaleFactor") open static var menuAnimationShrinkStrength: CGFloat { get { return menuAnimationTransformScaleFactor } set { menuAnimationTransformScaleFactor = newValue } } // prevent instantiation fileprivate override init() {} /** The blur effect style of the menu if the menu's root view controller is a UITableViewController or UICollectionViewController. - Note: If you want cells in a UITableViewController menu to show vibrancy, make them a subclass of UITableViewVibrantCell. */ open static var menuBlurEffectStyle: UIBlurEffectStyle? { didSet { if oldValue != menuBlurEffectStyle { updateMenuBlurIfNecessary() } } } /// The left menu. open static var menuLeftNavigationController: UISideMenuNavigationController? { willSet { if menuLeftNavigationController?.presentingViewController == nil { removeMenuBlurForMenu(menuLeftNavigationController) } } didSet { guard oldValue?.presentingViewController == nil else { print("SideMenu Warning: menuLeftNavigationController cannot be modified while it's presented.") menuLeftNavigationController = oldValue return } setupNavigationController(menuLeftNavigationController, leftSide: true) } } /// The right menu. open static var menuRightNavigationController: UISideMenuNavigationController? { willSet { if menuRightNavigationController?.presentingViewController == nil { removeMenuBlurForMenu(menuRightNavigationController) } } didSet { guard oldValue?.presentingViewController == nil else { print("SideMenu Warning: menuRightNavigationController cannot be modified while it's presented.") menuRightNavigationController = oldValue return } setupNavigationController(menuRightNavigationController, leftSide: false) } } fileprivate class func setupNavigationController(_ forMenu: UISideMenuNavigationController?, leftSide: Bool) { guard let forMenu = forMenu else { return } if menuEnableSwipeGestures { let exitPanGesture = UIPanGestureRecognizer() exitPanGesture.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handleHideMenuPan(_:))) forMenu.view.addGestureRecognizer(exitPanGesture) if leftSide { menuLeftSwipeToDismissGesture = exitPanGesture } else { menuRightSwipeToDismissGesture = exitPanGesture } } forMenu.transitioningDelegate = SideMenuTransition.singleton forMenu.modalPresentationStyle = .overFullScreen forMenu.leftSide = leftSide updateMenuBlurIfNecessary() } /// Enable or disable gestures that would swipe to present or dismiss the menu. Default is true. open static var menuEnableSwipeGestures: Bool = true { didSet { menuLeftSwipeToDismissGesture?.view?.removeGestureRecognizer(menuLeftSwipeToDismissGesture!) menuRightSwipeToDismissGesture?.view?.removeGestureRecognizer(menuRightSwipeToDismissGesture!) setupNavigationController(menuLeftNavigationController, leftSide: true) setupNavigationController(menuRightNavigationController, leftSide: false) } } fileprivate class func updateMenuBlurIfNecessary() { let menuBlurBlock = { (forMenu: UISideMenuNavigationController?) in if let forMenu = forMenu { setupMenuBlurForMenu(forMenu) } } menuBlurBlock(menuLeftNavigationController) menuBlurBlock(menuRightNavigationController) } fileprivate class func setupMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) { removeMenuBlurForMenu(forMenu) guard let forMenu = forMenu, let menuBlurEffectStyle = menuBlurEffectStyle, let view = forMenu.visibleViewController?.view , !UIAccessibilityIsReduceTransparencyEnabled() else { return } if forMenu.originalMenuBackgroundColor == nil { forMenu.originalMenuBackgroundColor = view.backgroundColor } let blurEffect = UIBlurEffect(style: menuBlurEffectStyle) let blurView = UIVisualEffectView(effect: blurEffect) view.backgroundColor = UIColor.clear if let tableViewController = forMenu.visibleViewController as? UITableViewController { tableViewController.tableView.backgroundView = blurView tableViewController.tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect) tableViewController.tableView.reloadData() } else { blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] blurView.frame = view.bounds view.insertSubview(blurView, at: 0) } } fileprivate class func removeMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) { guard let forMenu = forMenu, let originalMenuBackgroundColor = forMenu.originalMenuBackgroundColor, let view = forMenu.visibleViewController?.view else { return } view.backgroundColor = originalMenuBackgroundColor forMenu.originalMenuBackgroundColor = nil if let tableViewController = forMenu.visibleViewController as? UITableViewController { tableViewController.tableView.backgroundView = nil tableViewController.tableView.separatorEffect = nil tableViewController.tableView.reloadData() } else if let blurView = view.subviews[0] as? UIVisualEffectView { blurView.removeFromSuperview() } } /** Adds screen edge gestures to a view to present a menu. - Parameter toView: The view to add gestures to. - Parameter forMenu: The menu (left or right) you want to add a gesture for. If unspecified, gestures will be added for both sides. - Returns: The array of screen edge gestures added to `toView`. */ @discardableResult open class func menuAddScreenEdgePanGesturesToPresent(toView: UIView, forMenu:UIRectEdge? = nil) -> [UIScreenEdgePanGestureRecognizer] { var array = [UIScreenEdgePanGestureRecognizer]() if forMenu != .right { let leftScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer() leftScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handlePresentMenuLeftScreenEdge(_:))) leftScreenEdgeGestureRecognizer.edges = .left leftScreenEdgeGestureRecognizer.cancelsTouchesInView = true toView.addGestureRecognizer(leftScreenEdgeGestureRecognizer) array.append(leftScreenEdgeGestureRecognizer) if SideMenuManager.menuLeftNavigationController == nil { print("SideMenu Warning: menuAddScreenEdgePanGesturesToPresent for the left side was called before menuLeftNavigationController has been defined. The gesture will not work without a menu.") } } if forMenu != .left { let rightScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer() rightScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handlePresentMenuRightScreenEdge(_:))) rightScreenEdgeGestureRecognizer.edges = .right rightScreenEdgeGestureRecognizer.cancelsTouchesInView = true toView.addGestureRecognizer(rightScreenEdgeGestureRecognizer) array.append(rightScreenEdgeGestureRecognizer) if SideMenuManager.menuRightNavigationController == nil { print("SideMenu Warning: menuAddScreenEdgePanGesturesToPresent for the right side was called before menuRightNavigationController has been defined. The gesture will not work without a menu.") } } return array } /** Adds a pan edge gesture to a view to present menus. - Parameter toView: The view to add a pan gesture to. - Returns: The pan gesture added to `toView`. */ @discardableResult open class func menuAddPanGestureToPresent(toView: UIView) -> UIPanGestureRecognizer { let panGestureRecognizer = UIPanGestureRecognizer() panGestureRecognizer.addTarget(SideMenuTransition.self, action:#selector(SideMenuTransition.handlePresentMenuPan(_:))) toView.addGestureRecognizer(panGestureRecognizer) if SideMenuManager.menuLeftNavigationController ?? SideMenuManager.menuRightNavigationController == nil { print("SideMenu Warning: menuAddPanGestureToPresent called before menuLeftNavigationController or menuRightNavigationController have been defined. Gestures will not work without a menu.") } return panGestureRecognizer } }
mit
0a7a92c51d525b37e5c0eedd1a057dbd
46.623269
271
0.689565
5.749833
false
false
false
false
aksskas/DouYuZB
DYZB/DYZB/Classes/Home/ViewModel/RecommendViewModel.swift
1
4026
// // RecommendViewModel.swift // DYZB // // Created by aksskas on 2017/9/21. // Copyright © 2017年 aksskas. All rights reserved. // import UIKit class RecommendViewModel { lazy var groups = [AnchorGroupModel]() lazy var cycleModels = [CycleModel]() private var firstPartGroup: AnchorGroupModel! private var secondPartGroup: AnchorGroupModel! private lazy var thirdPartGroups = [AnchorGroupModel]() } extension RecommendViewModel { func requestData(finishCallback: @escaping () -> ()) { let disGroup = DispatchGroup() // 1. 请求推荐数据 disGroup.enter() NetworkTools.requestData(type: .get, URL: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time": Date().getTimeStr]) { result in guard let resultDict = result as? [String: Any], let dataArray = resultDict["data"] as? [[String: Any]] else { return } var gameModels = [AnchorModel]() for element in dataArray { guard let data = try? JSONSerialization.data(withJSONObject: element), let model = try? decoder.decode(AnchorModel.self, from: data) else { return } gameModels.append(model) } let group = AnchorGroupModel(room_list: gameModels, tag_name: "热门", icon_url: "home_header_hot") self.firstPartGroup = group disGroup.leave() } // 2. 请求第二部分颜值数据 disGroup.enter() NetworkTools.requestData(type: .get, URL: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters:["limit": "4", "offset": "0", "time": Date().getTimeStr]) { result in guard let resultDict = result as? [String: Any], let dataArray = resultDict["data"] as? [[String: Any]] else { return } var prettyModels = [AnchorModel]() for element in dataArray { guard let data = try? JSONSerialization.data(withJSONObject: element), let model = try? decoder.decode(AnchorModel.self, from: data) else { return } prettyModels.append(model) } let group = AnchorGroupModel(room_list: prettyModels, tag_name: "颜值", icon_url: "home_header_phone") self.secondPartGroup = group disGroup.leave() } // 3. 请求游戏数据 disGroup.enter() NetworkTools.requestData(type: .get, URL: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters:["limit": "4", "offset": "0", "time": Date().getTimeStr] ) { result in guard let resultDict = result as? [String: Any], let dataArray = resultDict["data"] as? [Any] else { return } for element in dataArray { guard let data = try? JSONSerialization.data(withJSONObject: element),let model = try? decoder.decode(AnchorGroupModel.self, from: data) else { return } self.thirdPartGroups.append(model) } disGroup.leave() } disGroup.notify(queue: DispatchQueue.main) { self.groups.append(self.firstPartGroup) self.groups.append(self.secondPartGroup) self.groups.append(contentsOf: self.thirdPartGroups) finishCallback() } } func requestCycleData(finishCallback: @escaping () -> ()) { NetworkTools.requestData(type: .get, URL: "http://capi.douyucdn.cn/api/v1/slide/6", parameters: ["version":"2.300"]) { result in guard let resultDict = result as? [String: Any], let dataArray = resultDict["data"] as? [Any] else { return } for element in dataArray { guard let data = try? JSONSerialization.data(withJSONObject: element),let model = try? decoder.decode(CycleModel.self, from: data) else { return } self.cycleModels.append(model) finishCallback() } } } }
mit
15c236d257bdb2147b3e8de49b6b47f5
39.520408
180
0.592546
4.461798
false
false
false
false
bmoliveira/BOShareComposer
BOShareComposer/Classes/ShareOptions.swift
1
985
// // ShareOptions.swift // Pods // // Created by Bruno Oliveira on 20/07/16. // // import Foundation public struct ShareOptions { // Buttons tint color public var tintColor: UIColor // Composer title public var title: String // Dismiss button text public var dismissText: String // Completion button text public var confirmText: String // Parse link metadata and show image public var showMetadata = true // Keyboard appearence public var keyboardAppearance: UIKeyboardAppearance public init (tintColor: UIColor = UIView().tintColor, title: String = "Share", dismissText: String = "Cancel", confirmText: String = "Send", showMetadata: Bool = true, keyboardAppearance: UIKeyboardAppearance = .Dark) { self.tintColor = tintColor self.title = title self.dismissText = dismissText self.confirmText = confirmText self.showMetadata = showMetadata self.keyboardAppearance = keyboardAppearance } }
mit
b27386bc5ebb99c0883a762311db383b
23.02439
112
0.702538
4.646226
false
false
false
false
MainasuK/Bangumi-M
Percolator/Percolator/Progress.swift
1
663
// // Progress.swift // Percolator // // Created by Cirno MainasuK on 2016-7-20. // Copyright © 2016年 Cirno MainasuK. All rights reserved. // import Foundation import SwiftyJSON typealias EpisodeID = Int typealias Progress = [EpisodeID : Status] enum Status: Int { case queue = 1 // 想看 case watched = 2 // 看过 case drop = 3 // 抛弃 case none // 无状态 (撤销) func toURLParams() -> String { switch self { case .queue: return "queue" case .watched: return "watched" case .drop: return "drop" case .none: return "remove" } } }
mit
6b736ea33e42098d053b9d5b18bc4724
20.931034
58
0.564465
3.533333
false
false
false
false
lucasleelz/LemoniOS
LemoniOS/Classes/Widgets/MessageInputToolBar.swift
2
3121
// // MessageInputToolBar.swift // LemoniOS // // Created by lucas on 16/7/9. // Copyright © 2016年 三只小猪. All rights reserved. // import UIKit struct MessageInputToolBarUX { static let sendButtonNormalTitleColor = UIColor(hue: 210.0/360, saturation: 0.94, brightness: 1.0, alpha: 1.0) static let sendButtonHighlightedTitleColor = UIColor(hue: 210.0/360, saturation: 0.94, brightness: 1.0, alpha: 1.0) static let sendButtonDisabledTitleColor = UIColor.lightGray() static let sendButtonFont = UIFont.boldSystemFont(ofSize: 17) static let sendButtonTintColor = sendButtonNormalTitleColor } class MessageInputToolBar: UIToolbar { var preferredDefaultHeight: CGFloat = 44.0 { willSet { assert(newValue > 0.0, "最小值必须是正数。") } } var maximumHeight: Int = NSNotFound private lazy var contentView: MessageToolbarContentView = { var result = Bundle.main .loadNibNamed(String(MessageToolbarContentView.self), owner: nil, options: nil) .first as! MessageToolbarContentView return result }() private lazy var sendButton: UIButton = { let sendTitle = "发送" let result = UIButton(type: .custom) result.setTitle(sendTitle, for: []) result.setTitleColor(MessageInputToolBarUX.sendButtonNormalTitleColor, for: []) result.setTitleColor(MessageInputToolBarUX.sendButtonHighlightedTitleColor, for: [.highlighted]) result.setTitleColor(MessageInputToolBarUX.sendButtonDisabledTitleColor, for: [.disabled]) result.titleLabel?.font = MessageInputToolBarUX.sendButtonFont result.titleLabel?.adjustsFontSizeToFitWidth = true result.titleLabel?.minimumScaleFactor = 0.85 result.contentMode = .center result.backgroundColor = UIColor.clear() result.tintColor = MessageInputToolBarUX.sendButtonTintColor let maxHeight: CGFloat = 32 let sendTitleRect = sendTitle.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: maxHeight), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSFontAttributeName : MessageInputToolBarUX.sendButtonFont], context: nil) result.frame = CGRect(x: 0.0, y: 0.0, width: sendTitleRect.integral.width, height: maxHeight) return result }() override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.white() self.addSubview(self.contentView) setupContentViewConstraints() self.setNeedsUpdateConstraints() self.contentView.leftBarButtonItem = nil self.contentView.rightBarButtonItem = self.sendButton toggleSendButtonEnabled() } private func setupContentViewConstraints() { self.lz_pinAllEdgesOfSubView(subView: self.contentView) } private func toggleSendButtonEnabled() { self.contentView.rightBarButtonItem?.isEnabled = self.contentView.textView.hasText() } }
mit
c00d9e1ffdccd3629d649b5ca8ad863b
37.123457
265
0.684262
4.870662
false
false
false
false
Drusy/auvergne-webcams-ios
AuvergneWebcams/Webcam.swift
1
3496
// // Webcam.swift // AuvergneWebcams // // Created by Drusy on 09/11/2016. // // import Foundation import ObjectMapper import SwiftyUserDefaults import RealmSwift class Webcam: Object, Mappable { enum ContentType: String { case image = "image" case viewsurf = "viewsurf" } #if DEBUG static let refreshInterval: TimeInterval = 60 * 1 #else static let refreshInterval: TimeInterval = 60 * 10 #endif static let retryCount: Int = 3 // Update from WS @objc dynamic var uid: Int = 0 @objc dynamic var order: Int = 0 @objc dynamic var title: String? @objc dynamic var imageHD: String? @objc dynamic var imageLD: String? @objc dynamic var viewsurf: String? @objc dynamic var mapImageName: String? @objc dynamic var isHidden: Bool = false @objc dynamic var latitude: Double = -1 @objc dynamic var longitude: Double = -1 private let sections: LinkingObjects<WebcamSection> = LinkingObjects(fromType: WebcamSection.self, property: "webcams") var section: WebcamSection? { return sections.first } // MARK: - Camera content type @objc private dynamic var type: String? var contentType: ContentType { get { guard let stringType = type else { return .image } return ContentType(rawValue: stringType) ?? .image } } // Internal data @objc dynamic var favorite: Bool = false @objc dynamic var lastUpdate: Date? var tags = List<WebcamTag>() // MARK: - required convenience init?(map: Map) { self.init() } func mapping(map: Map) { var tagsArray = [String]() uid <- map["uid"] order <- map["order"] title <- map["title"] imageHD <- map["imageHD"] imageLD <- map["imageLD"] viewsurf <- map["viewsurf"] mapImageName <- map["mapImageName"] type <- map["type"] latitude <- map["latitude"] longitude <- map["longitude"] isHidden <- map["hidden"] tagsArray <- map["tags"] setTags(from: tagsArray) let realm = try? Realm() if let webcam = realm?.object(ofType: Webcam.self, forPrimaryKey: uid) { lastUpdate = webcam.lastUpdate favorite = webcam.favorite } } override static func primaryKey() -> String? { return #keyPath(Webcam.uid) } // MARK: - func setTags(from arrayString: [String]) { for tag in arrayString { let webcamTag = WebcamTag() webcamTag.tag = tag tags.append(webcamTag) } } func isLowQualityOnly() -> Bool { var lowQuality: Bool = false switch contentType { case .image: lowQuality = (imageHD == nil) case .viewsurf: return false } return lowQuality } func isUpToDate() -> Bool { guard let update = lastUpdate else { return true } // 48h return (Date().timeIntervalSince1970 - update.timeIntervalSince1970) < (60 * 60 * 48) } func preferredImage() -> String? { if Defaults[.prefersHighQuality] { return imageHD ?? imageLD } else { return imageLD ?? imageHD } } func preferredViewsurf() -> String? { return viewsurf } }
apache-2.0
a6b5963c31a4e2187a3feaa835654202
24.518248
123
0.562357
4.459184
false
false
false
false
nodes-vapor/sugar
Sources/Sugar/Authentication/JWTAuthenticationMiddleware.swift
1
2323
import Authentication import JWT import Vapor /// A middleware that authenticates by extracting and verifying a JWT (JSON Web Token) from the /// Authorization header. By default it will also load the user (or whatever authenticatable entity /// is used) from the database but this can be disabled for performance reasons if it is not needed. /// /// Authentication is skipped if authentication has already occurred, e.g. in a previous middleware. public final class JWTAuthenticationMiddleware<A: JWTAuthenticatable>: Middleware { let signer: JWTSigner let shouldAuthenticate: Bool /// Creates a new JWT Authentication Middleware /// /// - Parameters: /// - signer: the signer which with to verify the JWTs /// - shouldAuthenticate: whether full authentication (which usually includes a database /// query) should be performed public init(signer: JWTSigner, shouldAuthenticate: Bool = true) { self.signer = signer self.shouldAuthenticate = shouldAuthenticate } /// See `Middleware.respond` public func respond( to req: Request, chainingTo next: Responder ) throws -> Future<Response> { // return early if authentication has already occurred if try req.isAuthenticated(A.self) { return try next.respond(to: req) } guard let bearer = req.http.headers.bearerAuthorization else { return try next.respond(to: req) } let jwt: JWT<A.JWTPayload> do { jwt = try JWT<A.JWTPayload>(from: bearer.token, verifiedUsing: signer) } catch let error as JWTError where error.identifier == "exp" { return try req.future(HTTPResponse(status: .unauthorized)).encode(for: req) } guard shouldAuthenticate else { // we've verified the JWT and authentication is not requested so we're done return try next.respond(to: req) } return try A .authenticate(using: jwt.payload, on: req) .unwrap(or: AuthenticationError.userNotFound) .flatMap(to: Response.self) { object in // store the authenticated object on the request try req.authenticate(object) return try next.respond(to: req) } } }
mit
9e6288cd14fac5acc671e6afef689020
37.081967
100
0.650882
4.770021
false
false
false
false
Swamii/adventofcode2016
Sources/utils.swift
1
3208
import Foundation enum Side: String { case left = "L" case right = "R" } enum CompassPoint: Int { case north = 1 case east = 2 case south = 3 case west = 4 static var first = CompassPoint.north static var last = CompassPoint.west } enum Direction: Character { case up = "U" case right = "R" case down = "D" case left = "L" } struct Size { let width: Int let height: Int } /// Regex wrapper /// from NSHipster - http://nshipster.com/swift-literal-convertible/ struct Regex { let pattern: String let options: NSRegularExpression.Options let matcher: NSRegularExpression init(pattern: String, options: NSRegularExpression.Options = NSRegularExpression.Options()) { self.pattern = pattern self.options = options self.matcher = try! NSRegularExpression(pattern: self.pattern, options: self.options) } func match(_ string: String, options: NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions()) -> Bool { let numberOfMatches = matcher.numberOfMatches( in: string, options: options, range: NSRange(location: 0, length: string.utf16.count) ) return numberOfMatches != 0 } func search(input: String, options: NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions()) -> [String] { let matches = matcher.matches(in: input, options: options, range: NSRange(location: 0, length: input.utf16.count)) var groups = [String]() for match in matches as [NSTextCheckingResult] { // range at index 0: full match, skip that and add all groups to list for index in 1..<match.numberOfRanges { let substring = (input as NSString).substring(with: match.rangeAt(index)) groups.append(substring) } } return groups } func firstMatch(input: String, options: NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions()) -> NSTextCheckingResult? { let match = matcher.firstMatch( in: input, options: options, range: NSRange(location: 0, length: input.utf16.count) ) return match } } func *(lhs: String, rhs: Int) -> String { var strings = [String]() for _ in 0..<rhs { strings.append(lhs) } return strings.joined() } extension String { mutating func popTo(length: Int) -> String { let range = self.startIndex..<self.index(self.startIndex, offsetBy: length) let chars = self[range] removeSubrange(range) return chars } subscript(i: Int) -> String { return String(self[self.index(self.startIndex, offsetBy: i)]) } subscript(range: Range<Int>) -> String { let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound) let endIndex = self.index(self.startIndex, offsetBy: range.upperBound, limitedBy: self.endIndex) ?? self.endIndex return self[startIndex..<endIndex] } }
mit
5ca3ad3c68b0b610e023e4f967f68d64
28.431193
132
0.611908
4.582857
false
false
false
false
PlutoMa/SwiftProjects
017.3D Touch Quick Action/3DTouchQuickAction/3DTouchQuickAction/ViewController.swift
1
2471
// // ViewController.swift // 3DTouchQuickAction // // Created by Dareway on 2017/10/30. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit import SafariServices class ViewController: UIViewController { var actionLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() actionLabel = UILabel(frame: CGRect(x: 50, y: 50, width: 400, height: 50)) actionLabel.text = "Please Press the 3D action" view.addSubview(actionLabel) NotificationCenter.default.addObserver(self, selector: #selector(shortCutActionClicked(sender:)), name: NSNotification.Name.init("ShortcutAction"), object: nil) let fingerPrintImageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 128, height: 128)) fingerPrintImageView.image = UIImage(named: "fingerprint.png") view.addSubview(fingerPrintImageView) fingerPrintImageView.center = view.center self.registerForPreviewing(with: self, sourceView: self.view) } @objc func shortCutActionClicked(sender: Notification) -> Void { let shortcutItem = sender.userInfo?["shortcutItem"] as! UIApplicationShortcutItem if shortcutItem.type == "LoveItem" { changeLabel(with: "Yes, I do ❤️ you!") } } func changeLabel(with name: String) -> Void { actionLabel.text = name } } extension ViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { previewingContext.sourceRect = CGRect(x: 10, y: 10, width: view.frame.width - 20, height: view.frame.height - 10) return SFSafariViewController(url: URL(string: "http://www.qq.com")!) } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { self.show(viewControllerToCommit, sender: self) } } extension SFSafariViewController { open override var previewActionItems: [UIPreviewActionItem] { let deleteAction = UIPreviewAction(title: "删除", style: .destructive) { (previewAction, vc) in print("Delete") } let doneAction = UIPreviewAction(title: "完成", style: .default) { (previewAction, vc) in print("Done") } return [deleteAction,doneAction] } }
mit
58bc016110a374835b24f6fd933cc0a4
34.594203
168
0.674267
4.669202
false
false
false
false
Codility-BMSTU/Codility
Codility/Codility/OBTransferViewController.swift
1
19861
// // OBTransferViewController.swift // Codility // // Created by Кирилл Володин on 16.09.17. // Copyright © 2017 Кирилл Володин. All rights reserved. // //клава import UIKit import ContactsUI import EPContactsPicker import RNCryptor class OBTransferViewController: UIViewController, EPPickerDelegate, UITextFieldDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var backButton: OBBackBarButtonItem! var contact = "" var encodedData: String? var JKHMArker : Bool = false var accountCell: OBAccountTransferCell? var confirmCell: OBTransferConfirmCell? var simpleCellFrom: OBSimpleTransferCell? var simpleCellTo: OBSimpleTransferCell? var isForSecond: Bool = false var accountDictionary: Dictionary<String, String> = [ "INNTextFieled" : "", "accountTextFieled" : "", "BIKtextFieled" : "", "corpAccountTextFieled" : "", "bankNameTextFieled" : "", "sumTextFieled" : "" ] override func viewDidLoad() { super.viewDidLoad() setupHeader() setupTableView() if((encodedData) != nil){ decodeData() } // NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(sender:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) // // NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(sender:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() self.tableView.contentOffset.y = 0 return true } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { self.tableView.contentOffset.y = 150 return true } // func keyboardWillShow(sender: NSNotification) { // self.view.frame.origin.y = -80 // Move view 150 points upward // } // // func keyboardWillHide(sender: NSNotification) { // self.view.frame.origin.y = 0 // Move view to original position // } func decodeData() { let data = Data(base64Encoded: self.encodedData!) do { let password = "Secret password" let originalData = try RNCryptor.decrypt(data: data!, withPassword: password) let parameterDictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: originalData) as? Dictionary<String,Any> accountDictionary["INNTextFieled"] = parameterDictionary?["INNTextFieled"] as? String accountDictionary["accountTextFieled"] = parameterDictionary?["accountTextFieled"] as? String accountDictionary["BIKtextFieled"] = parameterDictionary?["BIKtextFieled"] as? String accountDictionary["corpAccountTextFieled"] = parameterDictionary?["corpAccountTextFieled"] as? String accountDictionary["bankNameTextFieled"] = parameterDictionary?["bankNameTextFieled"] as? String accountDictionary["sumTextFieled"] = parameterDictionary?["sumTextFieled"] as? String } catch { print(error) } } func encode() -> String? { var parameterDictionary = Dictionary<String, Any>() if accountCell != nil && confirmCell != nil { parameterDictionary["INNTextFieled"] = accountCell?.INNTextFieled.text parameterDictionary["accountTextFieled"] = accountCell?.accountTextFieled.text parameterDictionary["BIKtextFieled"] = accountCell?.BIKtextFieled.text parameterDictionary["corpAccountTextFieled"] = accountCell?.corpAccountTextFieled.text parameterDictionary["bankNameTextFieled"] = accountCell?.bankNameTextFieled.text parameterDictionary["sumTextFieled"] = confirmCell?.sumTextField.text let data = NSKeyedArchiver.archivedData(withRootObject: parameterDictionary) let password = "Secret password" let ciphertext = RNCryptor.encrypt(data: data, withPassword: password) return ciphertext.base64EncodedString() } return nil } func setupHeader() { switch OBTransferType.transferType { case .selfTransfer: self.navigationItem.title = "Между своими счетами" case .phoneTransfer: self.navigationItem.title = "По номеру телефона" case .organisationTransfer: self.navigationItem.title = "Перевод на счет" case .emailTransfer: self.navigationItem.title = "Перевод по E-mail" case .linkTransfer: self.navigationItem.title = "Оплатите счет" } } func setupTableView() { self.tableView.delegate = self self.tableView.dataSource = self self.tableView.tableFooterView = UIView() self.tableView.register(UINib(nibName: "OBSimpleTransferCell", bundle: nil), forCellReuseIdentifier: "OBSimpleTransferCell") self.tableView.register(UINib(nibName: "OBAccountTransferCell", bundle: nil), forCellReuseIdentifier: "OBAccountTransferCell") self.tableView.register(UINib(nibName: "OBTransferConfirmCell", bundle: nil), forCellReuseIdentifier: "OBTransferConfirmCell") } @IBAction func goBack(_ sender: OBBackBarButtonItem) { self.navigationController?.popViewController(animated: true) } func chooseContact() { var value = SubtitleCellValue.phoneNumber if OBTransferType.transferType == .emailTransfer { value = SubtitleCellValue.email } let contactPickerScene = EPContactsPicker(delegate: self, multiSelection:false, subtitleCellType: value) let navigationController = UINavigationController(rootViewController: contactPickerScene) self.present(navigationController, animated: true, completion: nil) } func epContactPicker(_: EPContactsPicker, didCancel error : NSError) { print("error choosing contact") } func epContactPicker(_: EPContactsPicker, didSelectContact contact : EPContact) { if OBTransferType.transferType == .phoneTransfer { if !contact.phoneNumbers.isEmpty { self.contact = contact.phoneNumbers[0].phoneNumber } } else { if !contact.emails.isEmpty { self.contact = contact.emails[0].email } } tableView.reloadData() } // //сallback добавить // func createQRCode() { // // } func createQRCode() { if let data = encode() { self.performSegue(withIdentifier: OBSegueRouter.toCreateQR, sender: data) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == OBSegueRouter.toCreateQR { let viewcontroller = segue.destination as! OBCreateQRViewController viewcontroller.encodedData = sender as! String } } func createLink() { if let encodedData = encode() { let data = "bank://" + encodedData let objectsToShare = [data] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) self.present(activityVC, animated: true, completion: nil) } } func openCardPicker() { isForSecond = false self.performSegue(withIdentifier: OBSegueRouter.toCardPicker, sender: nil) } func openSecondCardPicker() { isForSecond = true self.performSegue(withIdentifier: OBSegueRouter.toCardPicker, sender: nil) } } extension OBTransferViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // switch OBTransferType.transferType { // case .selfTransfer: // return 3 // case .phoneTransfer: // return 3 // case .organisationTransfer: // return 2 // case .emailTransfer: // return 3 // case .linkTransfer: // return 3 // } return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch OBTransferType.transferType { case .selfTransfer: if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBSimpleTransferCell", for: indexPath) as! OBSimpleTransferCell cell.button.setImage(UIImage.OBImage.peopleHome, for: .normal) cell.button.addTarget(self, action: #selector(openCardPicker), for: .touchUpInside) self.simpleCellFrom = cell cell.textField.placeholder = "Введите номер карты" return cell } else if indexPath.row == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBSimpleTransferCell", for: indexPath) as! OBSimpleTransferCell cell.button.setImage(UIImage.OBImage.peopleHome, for: .normal) cell.titleLabel.text = "Куда перевести" cell.textField.placeholder = "Введите номер карты" cell.button.addTarget(self, action: #selector(openSecondCardPicker), for: .touchUpInside) self.simpleCellTo = cell return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "OBTransferConfirmCell", for: indexPath) as! OBTransferConfirmCell return cell } case .phoneTransfer: if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBSimpleTransferCell", for: indexPath) as! OBSimpleTransferCell cell.button.setImage(UIImage.OBImage.peopleHome, for: .normal) cell.textField.placeholder = "Введите номер карты" cell.button.addTarget(self, action: #selector(openCardPicker), for: .touchUpInside) self.simpleCellFrom = cell return cell } else if indexPath.row == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBSimpleTransferCell", for: indexPath) as! OBSimpleTransferCell cell.button.setImage(UIImage.OBImage.phoneHome, for: .normal) cell.button.addTarget(self, action: #selector(chooseContact), for: .touchUpInside) cell.titleLabel.text = "Куда перевести" cell.textField.text = contact return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "OBTransferConfirmCell", for: indexPath) as! OBTransferConfirmCell return cell } case .organisationTransfer: if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBSimpleTransferCell", for: indexPath) as! OBSimpleTransferCell cell.button.setImage(UIImage.OBImage.peopleHome, for: .normal) cell.textField.placeholder = "Введите номер карты" cell.button.addTarget(self, action: #selector(openCardPicker), for: .touchUpInside) self.simpleCellFrom = cell return cell } else if indexPath.row == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBAccountTransferCell", for: indexPath) as! OBAccountTransferCell self.accountCell = cell cell.corpAccountTextFieled.delegate = self cell.bankNameTextFieled.delegate = self // NotificationCenter.default.addObserver(cell.corpAccountTextFieled, selector: #selector(keyboardWillShow(sender:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) // NotificationCenter.default.addObserver(cell.corpAccountTextFieled, selector: #selector(keyboardWillHide(sender:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) // // NotificationCenter.default.addObserver(cell.bankNameTextFieled, selector: #selector(keyboardWillShow(sender:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) // NotificationCenter.default.addObserver(cell.bankNameTextFieled, selector: #selector(keyboardWillHide(sender:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "OBTransferConfirmCell", for: indexPath) as! OBTransferConfirmCell self.confirmCell = cell cell.createLinkButton.isHidden = false cell.createQRCodeButton.isHidden = false cell.createLinkButton.addTarget(self, action: #selector(createLink), for: .touchUpInside) cell.createQRCodeButton.addTarget(self, action: #selector(createQRCode), for: .touchUpInside) cell.sumTextField.delegate = self // NotificationCenter.default.addObserver(cell.sumTextField, selector: #selector(keyboardWillShow(sender:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) // NotificationCenter.default.addObserver(cell.sumTextField, selector: #selector(keyboardWillHide(sender:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) return cell } case .emailTransfer: if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBSimpleTransferCell", for: indexPath) as! OBSimpleTransferCell cell.button.setImage(UIImage.OBImage.peopleHome, for: .normal) cell.textField.placeholder = "Введите номер карты" cell.button.addTarget(self, action: #selector(openCardPicker), for: .touchUpInside) self.simpleCellFrom = cell return cell } else if indexPath.row == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBSimpleTransferCell", for: indexPath) as! OBSimpleTransferCell cell.button.setImage(UIImage.OBImage.emailHome, for: .normal) cell.button.addTarget(self, action: #selector(chooseContact), for: .touchUpInside) cell.titleLabel.text = "Куда перевести" cell.textField.placeholder = "Введите e-mail" cell.textField.text = contact return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "OBTransferConfirmCell", for: indexPath) as! OBTransferConfirmCell return cell } case .linkTransfer: if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBSimpleTransferCell", for: indexPath) as! OBSimpleTransferCell cell.button.setImage(UIImage.OBImage.peopleHome, for: .normal) cell.textField.placeholder = "Введите номер карты" cell.button.addTarget(self, action: #selector(openCardPicker), for: .touchUpInside) self.simpleCellFrom = cell return cell } else if indexPath.row == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "OBAccountTransferCell", for: indexPath) as! OBAccountTransferCell cell.INNTextFieled.text = accountDictionary["INNTextFieled"] cell.accountTextFieled.text = accountDictionary["accountTextFieled"] cell.bankNameTextFieled.text = accountDictionary["bankNameTextFieled"] cell.BIKtextFieled.text = accountDictionary["BIKtextFieled"] cell.corpAccountTextFieled.text = accountDictionary["corpAccountTextFieled"] cell.INNTextFieled.isEnabled = false cell.accountTextFieled.isEnabled = false cell.bankNameTextFieled.isEnabled = false cell.BIKtextFieled.isEnabled = false cell.corpAccountTextFieled.isEnabled = false return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "OBTransferConfirmCell", for: indexPath) as! OBTransferConfirmCell cell.createLinkButton.isHidden = true cell.createQRCodeButton.isHidden = true cell.sumTextField.text = accountDictionary["sumTextFieled"] cell.sumTextField.isEnabled = false cell.confirmTransferButton.addTarget(self, action: #selector(confirmTransfer), for:.touchUpInside) return cell } } } func confirmTransfer() { let request = OBCreateInvoiceRequest(rqUID: "", invoiceCreateSum: accountDictionary["sumTextFieled"]!, invoiceCreatePayeeINN: accountDictionary["INNTextFieled"]!, invoiceCreatePayeeAcc: accountDictionary["accountTextFieled"]!, invoiceCreatePayeeBIK: accountDictionary["BIKtextFieled"]!, invoiceCreatePayeeCorrAcc: accountDictionary["corpAccountTextFieled"]!, invoiceCreatePayeeBankname: "Открытие") OBAPIManager.createInvoiceRequest(request: request) } } extension OBTransferViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return getHeightForCurrentTransferType(indexPath) } func getHeightForCurrentTransferType(_ indexPath: IndexPath) -> CGFloat { switch OBTransferType.transferType { case .selfTransfer: if indexPath.row == 0 { return 77 } else if indexPath.row == 1 { return 77 } else { return 148 } case .phoneTransfer: if indexPath.row == 0 { return 77 } else if indexPath.row == 1 { return 77 } else { return 148 } case .organisationTransfer: if indexPath.row == 0 { return 77 } else if indexPath.row == 1 { return 246 } else { return 148 } case .emailTransfer: if indexPath.row == 0 { return 77 } else if indexPath.row == 1 { return 77 } else { return 148 } case .linkTransfer: if indexPath.row == 0 { return 77 } else if indexPath.row == 1 { return 246 } else { return 148 } } } func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return false } }
apache-2.0
c8529f42e659d34b399acb1241ffbdd1
42.450111
406
0.618136
4.889222
false
false
false
false
volochaev/firebase-and-facebook
firebase-example/PostCell.swift
1
1080
// // PostCell.swift // firebase-example // // Created by Nikolai Volochaev on 02/11/15. // Copyright © 2015 Nikolai Volochaev. All rights reserved. // import UIKit class PostCell: UITableViewCell { @IBOutlet weak var showcaseImg: UIImageView! @IBOutlet weak var postDescription: UITextView! @IBOutlet weak var postAuthor: UILabel! @IBOutlet weak var postAuthorImg: UIImageView! @IBOutlet weak var postLikes: UILabel! var post: Post! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) postAuthorImg.clipsToBounds = true showcaseImg.clipsToBounds = true } override func drawRect(rect: CGRect) { postAuthorImg.layer.cornerRadius = postAuthorImg.frame.size.width / 2 } func configureCell(post: Post) { self.post = post self.postDescription.text = post.postDescription self.postLikes.text = "\(post.postLikes)" } }
mit
faf5659dc18fd6cd60d53d13a91df343
25.317073
77
0.666358
4.333333
false
false
false
false
schluchter/berlin-transport
berlin-transport/berlin-trnsprt/BTHafasAPIClient.swift
1
1369
// // BTHafasRequestHandler.swift // berlin-transport // // Created by Thomas Schluchter on 11/5/14. // Copyright (c) 2014 Thomas Schluchter. All rights reserved. // import Foundation import AFNetworking import Ono import AFOnoResponseSerializer class BTHafasAPIClient { class func send(xml: String) { let bodyData = xml.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)! let req = NSMutableURLRequest(URL: NSURL(string: kBTHafasServerURL)!) req.HTTPMethod = "POST" req.setValue("application/xml", forHTTPHeaderField: "Content-Type") req.HTTPBody = bodyData let ops = AFHTTPRequestOperation(request: req) ops.responseSerializer = AFOnoResponseSerializer.XMLResponseSerializer() ops.setCompletionBlockWithSuccess({ (ops: AFHTTPRequestOperation!, res: AnyObject!) -> Void in if let connectionXML = res as? ONOXMLDocument { NSNotificationCenter.defaultCenter().postNotificationName("BTHafasAPIClientDidReceiveResponse", object: connectionXML) } }, failure: { (ops: AFHTTPRequestOperation!, err: NSError!) -> Void in NSNotificationCenter.defaultCenter().postNotificationName("BTHafasAPIClientDidNotReceiveValidResponse", object: err) }) ops.start() } }
mit
b4a0f1d623f00440bd8a36e0cb389242
37.055556
134
0.688824
4.871886
false
false
false
false
Gorgodzila/iOS-Trainings
NewMyInstagramm/NewMyInstagramm/RegistrationDetails.swift
1
2427
// // RegistrationDetails.swift // NewMyInstagramm // // Created by Korneli Mamulashvili on 6/5/17. // Copyright © 2017 Kakha Mamulashvili. All rights reserved. // import UIKit class RegistrationDetails: UIViewController { var transferedtext = String() @IBOutlet weak var userEmailField: UITextField! @IBOutlet weak var userPasswField: UITextField! @IBOutlet weak var userPassRepeatField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func registerButtonTapped(_ sender: AnyObject) { let userEmail = userEmailField.text let userPassw = userPasswField.text let repeatPass = userPassRepeatField.text // Check for empty fields if ((userEmail!.isEmpty || userPassw!.isEmpty || repeatPass!.isEmpty)) { // Display alert message displayMyAlertMessage(userMessage:"All fields are required") return } // Check if password match if (userPassw != repeatPass) { displayMyAlertMessage(userMessage: "Password do not match") return } // MARK * - Store Data let defaults = UserDefaults.standard defaults.set(userEmail, forKey: "userEmail") defaults.set(userPassw, forKey: "userPassw") defaults.synchronize() // Display alert message with confirmation let myAlert = UIAlertController(title: "Alert", message:"Registration is successful. Thank you", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) { action in self.dismiss(animated: true, completion: nil) } myAlert.addAction(okAction) self.present(myAlert, animated: true, completion: nil) } func displayMyAlertMessage(userMessage: String) { let myAlert = UIAlertController(title: "Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil) myAlert.addAction(okAction) self.present(myAlert, animated: true, completion: nil) } }
apache-2.0
f6dfa0b5c6a91a5bc0dcad37f674dd87
25.659341
150
0.625309
5.002062
false
false
false
false
KrishMunot/swift
test/DebugInfo/inout.swift
3
2442
// RUN: %target-swift-frontend %s -emit-ir -g -module-name inout -o %t.ll // RUN: cat %t.ll | FileCheck %s // RUN: cat %t.ll | FileCheck %s --check-prefix=PROMO-CHECK // RUN: cat %t.ll | FileCheck %s --check-prefix=FOO-CHECK // LValues are direct values, too. They are reference types, though. func Close(_ fn: () -> Int64) { fn() } typealias MyFloat = Float // CHECK: define hidden void @_TF5inout13modifyFooHeap // CHECK: %[[ALLOCA:.*]] = alloca %Vs5Int64* // CHECK: %[[ALLOCB:.*]] = alloca %Sf // CHECK: call void @llvm.dbg.declare(metadata // CHECK-SAME: %[[ALLOCA]], metadata ![[A:[0-9]+]] // CHECK: call void @llvm.dbg.declare(metadata // CHECK-SAME: %[[ALLOCB]], metadata ![[B:[0-9]+]], metadata !{{[0-9]+}}) // Closure with promoted capture. // PROMO-CHECK: define {{.*}}@_TTSf2i___TFF5inout13modifyFooHeapFTRVs5Int64Sf_T_U_FT_S0_ // PROMO-CHECK: call void @llvm.dbg.declare(metadata {{(i32|i64)}}* % // PROMO-CHECK-SAME: metadata ![[A1:[0-9]+]], metadata ![[EMPTY_EXPR:[0-9]+]]) // PROMO-CHECK: ![[EMPTY_EXPR]] = !DIExpression() // PROMO-CHECK: ![[A1]] = !DILocalVariable(name: "a", arg: 1 // PROMO-CHECK-SAME: type: !"_TtVs5Int64" func modifyFooHeap(_ a: inout Int64, // CHECK-DAG: ![[A]] = !DILocalVariable(name: "a", arg: 1{{.*}} line: [[@LINE-1]],{{.*}} type: !"_TtRVs5Int64" _ b: MyFloat) { var b = b if (b > 2.71) { a = a + 12// Set breakpoint here } // Close over the variable to disable promotion of the inout shadow. Close({ a }) } // Inout reference type. // FOO-CHECK: define {{.*}}@_TF5inout9modifyFooFTRVs5Int64Sf_T_ // FOO-CHECK: call void @llvm.dbg.declare(metadata %Vs5Int64** % // FOO-CHECK-SAME: metadata ![[U:[0-9]+]], metadata ![[EMPTY_EXPR:.*]]) // FOO-CHECK: ![[EMPTY_EXPR]] = !DIExpression() func modifyFoo(_ u: inout Int64, // FOO-CHECK-DAG: !DILocalVariable(name: "v", arg: 2{{.*}} line: [[@LINE+2]],{{.*}} type: ![[MYFLOAT:[0-9]+]] // FOO-CHECK-DAG: [[U]] = !DILocalVariable(name: "u", arg: 1{{.*}} line: [[@LINE-2]],{{.*}} type: !"_TtRVs5Int64" _ v: MyFloat) // FOO-CHECK-DAG: ![[MYFLOAT]] = !DIDerivedType(tag: DW_TAG_typedef, name: "_Tta5inout7MyFloat",{{.*}} baseType: !"_TtSf" { if (v > 2.71) { u = u - 41 } } func main() -> Int64 { var c = 11 as Int64 modifyFoo(&c, 3.14) var d = 64 as Int64 modifyFooHeap(&d, 1.41) return 0 } main()
apache-2.0
53cf463ee13e89333a2fbd7c96a5d794
36
121
0.579853
2.988984
false
false
false
false
altyus/clubhouse-ios-api
Pod/Classes/API_Labels.swift
1
3614
// // API_Labels.swift // Pods // // Created by AL TYUS on 3/27/16. // // import Foundation import Alamofire import SwiftyJSON public enum LabelParam: Param { case ExternalId(String) case Name(String) public var param: (key: String, value: AnyObject) { switch self { case .ExternalId(let externalId): return ("external_id", externalId) case .Name(let name): return ("name", name) } } } public extension ClubhouseAPI { enum LabelRouter: URLRequestConvertible { case ListLabels case CreateLabel(params: [String: AnyObject]) case UpdateLabel(labelId: Int, params: [String: AnyObject]) case DeleteLabel(labelId: Int) var method: Alamofire.Method { switch self { case .ListLabels: return .GET case .CreateLabel: return .POST case .UpdateLabel: return .PUT case .DeleteLabel: return .DELETE } } var path: String { switch self { case .ListLabels, .CreateLabel: return "labels" case .UpdateLabel(let labelId): return "labels/\(labelId)" case .DeleteLabel(let labelId): return "labels/\(labelId)" } } public var URLRequest: NSMutableURLRequest { let mutableURLRequest = ClubhouseAPI.URLRequest(method, path: path) switch self { case .CreateLabel(let parameters): return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 case .UpdateLabel(_ , let parameters): return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 default: return mutableURLRequest } } } func listLabels(success: ([Label]) -> Void, failure: Failure) { request(LabelRouter.ListLabels, success: { response in guard let labels = Label.objects(JSON(response).array) else { return failure(nil) } success(labels) }, failure: { error in failure(error) }) } func createLabel(name: String, optionalParams: [LabelParam], success: (Label) -> Void, failure: Failure) { let params = [LabelParam.Name(name)] + optionalParams request(LabelRouter.CreateLabel(params: params.toParams()), success: { response in guard let response = response as? [String: AnyObject] else { return failure(nil) } success(Label(json: JSON(response))) }, failure: { error in failure(error) }) } func updateLabel(labelId: Int, name: String, success: (Label) -> Void, failure: Failure) { request(LabelRouter.UpdateLabel(labelId: labelId, params: [LabelParam.Name(name)].toParams()), success: { response in guard let response = response as? [String: AnyObject] else { return failure(nil) } success(Label(json: JSON(response))) }, failure: { error in failure(error) }) } func deleteLabel(labelId: Int, sucess: () -> Void, failure: Failure) { request(LabelRouter.DeleteLabel(labelId: labelId), success: { _ in sucess() }, failure: { error in failure(error) }) } }
mit
c1e54a5e63f396130258e2879b6e6a4d
31.567568
125
0.549806
4.76781
false
false
false
false
fousa/trackkit
Sources/Classes/Parser/NMEA/Extensions/String+NMEA.swift
1
1082
// // TrackKit // // Created by Jelle Vandebeeck on 15/03/16. // extension String { private static var timeFormatter: DateFormatter { let formatter = DateFormatter() formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "HHmmss" return formatter } var nmeaTimeValue: Date? { // Remove the `.` from the date string when set. let dateComponent = components(separatedBy: ".") guard let dateString = dateComponent.first, dateString != "" else { return nil } return String.timeFormatter.date(from: dateString) } var nmeaNavigationReceiverWarning: NavigationReceiverWarning? { return NavigationReceiverWarning(rawValue: self) } var nmeaGPSQuality: GPSQuality? { return GPSQuality(rawValue: self) } var integerValue: Int? { return Int(self) } var doubleValue: Double? { return Double(self) } var checksumEscapedString: String? { return components(separatedBy: "*").first } }
mit
ee5804910e9e9b50a39034324f967eda
22.521739
67
0.626617
4.623932
false
true
false
false
Vadim-Yelagin/DataSourceExample
DataSourceExample/Examples/AutoDiffSectionsViewModel.swift
1
1422
// // AutoDiffSectionsViewModel.swift // DataSourceExample // // Created by Vadim Yelagin on 14/08/15. // Copyright (c) 2015 Fueled. All rights reserved. // import Foundation import DataSource import ReactiveCocoa import UIKit final class AutoDiffSectionsViewModel: ExampleViewModel { let title = "Auto Diff Sections" var dataSource: DataSource { return autoDiffDataSource } lazy var actions: [ExampleViewModelAction] = { return [ExampleViewModelAction(title: "Random") { [weak self] in self?.random() }] }() let autoDiffDataSource = AutoDiffSectionsDataSource( sections: randomSections(), findItemMoves: true, compareSections: { let header0 = $0.supplementaryItems[UICollectionView.elementKindSectionHeader] as! String let header1 = $1.supplementaryItems[UICollectionView.elementKindSectionHeader] as! String return header0 == header1 }, compareItems: { $0 === $1 }) func random() { self.autoDiffDataSource.sections.value = randomSections() } } private func randomSections() -> [DataSourceSection<ExampleItem>] { var sections: [DataSourceSection<ExampleItem>] = [] for i in 0 ..< 10 { if arc4random_uniform(2) == 0 { continue } let header = "Section \(RandomData.spell(i))" let items = StaticData.randomItems() sections.append(DataSourceSection(items: items, supplementaryItems: [UICollectionView.elementKindSectionHeader: header])) } return sections }
mit
059cb1748fba354e1f7f0ca05270ed0f
24.854545
123
0.738397
3.771883
false
false
false
false
morpheby/aTarantula
aTarantula/utils/Utils.swift
1
2281
// // Utils.swift // CrossroadRegex // // Created by Ilya Mikhaltsou on 6/16/17. // // import Foundation public protocol WeakType { associatedtype Element: AnyObject var value: Element? {get set} init(_ value: Element) } public class Weak<T: AnyObject>: WeakType { public typealias Element = T weak public var value : Element? required public init (_ value: Element) { self.value = value } } public extension Array where Element: WeakType { public init(_ arr: Array<Element.Element>) { self.init(arr.map { (x: Element.Element) -> Element in Element(x) }) } public mutating func reap() { self = self.filter { x in x.value != nil } } } public extension Collection { /// Returns the element at the specified index iff it is within bounds, otherwise nil. public subscript (safe index: Index) -> Iterator.Element? { return indices.contains(index) ? self[index] : nil } } public func synchronized<T>(_ lockObj: AnyObject!, do closure: () throws -> T) rethrows -> T { objc_sync_enter(lockObj) defer { objc_sync_exit(lockObj) } return try closure() } public struct IOError: Error { public let path: String } public class FileTextOutputStream: TextOutputStream { var file: FileHandle public init(fileAtPath: String, append: Bool) throws { if !FileManager.default.fileExists(atPath: fileAtPath) { FileManager.default.createFile(atPath: fileAtPath, contents: nil, attributes: nil) } if let s = FileHandle(forWritingAtPath: fileAtPath) { if append { s.seekToEndOfFile() } s.truncateFile(atOffset: s.offsetInFile) file = s } else { throw IOError(path: fileAtPath) } } deinit { file.closeFile() } public func write(_ s: String) { let data = s.data(using: .utf8)! file.write(data) } } public extension Dictionary { } @inline(__always) public func logDebug(file: String = #file, line: Int = #line, function: String = #function, _ log: @autoclosure () -> Any) { #if DEBUG debugPrint("\(Date().description) \(file):\(line):\(function)", log()) #endif }
gpl-3.0
ae2b56d580712ce927ffe1507bef950d
23.526882
124
0.612012
4.015845
false
false
false
false
liuwin7/meizi_app_ios
meinv/class/beauty/BeautiesTableViewController.swift
1
11298
// // BeautiesTableViewController.swift // meinv // // Created by tropsci on 16/3/14. // Copyright © 2016年 topsci. All rights reserved. // import UIKit import Alamofire import Argo import MBProgressHUD import SDWebImage import DZNEmptyDataSet class BeautiesTableViewController: UITableViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var meBarButtonItem: UIBarButtonItem! var request: Request? var hud: MBProgressHUD? var beautyList: [Beauty]! var types : [String]! var displayState: BeautyTableDisplayState! var manager: Manager! var beautyType: String! { didSet { self.title = NSLocalizedString(beautyType, comment:beautyType) var parameters = [ "type": beautyType, ] if let uuid = NSUserDefaults.standardUserDefaults().userUUID { parameters["user_uuid"] = uuid } request = self.manager.request(.POST, GlobalConstant.kAPI_Beauties, parameters:parameters , encoding: .JSON).responseJSON { (response) -> Void in guard let value = response.result.value else { self.hud?.mode = .Text self.hud?.labelText = NSLocalizedString("Network Error", comment: "Network Error") self.hud?.hide(true, afterDelay: 1.5) self.displayState = .errorStete self.tableView.reloadData() self.request = nil return } let result:RequestResult = Argo.decode(value)! switch result.code { case .NoError: self.hud?.labelText = "" self.hud?.hide(true, afterDelay: 0.25) self.beautyList = result.beauties! self.displayState = .emptyState self.tableView.reloadData() case .InvalidType: self.hud?.mode = .Text self.hud?.labelText = result.desc self.hud?.hide(true, afterDelay: 1.0) self.beautyList = [] self.displayState = .errorStete self.tableView.reloadData() default: self.hud?.mode = .Text self.hud?.labelText = "未知的错误类型" self.hud?.hide(true, afterDelay: 1.0) self.displayState = .errorStete } self.request = nil } } } @IBAction func showMeAction(sender: UIBarButtonItem) { guard let beautyNavigationController = self.navigationController as? BeautyNavigationViewController else { print("Error") return } guard let center = beautyNavigationController.centerViewController else { print("Error") return } center.showLeftViewController() } @IBAction func changeTheme(sender: UIBarButtonItem) { if self.request != nil { let alertView = UIAlertView(title: NSLocalizedString("Alert", comment: "Alert"), message: NSLocalizedString("Please Waitting...", comment: "Please Waitting..."), delegate: nil, cancelButtonTitle: nil, otherButtonTitles: NSLocalizedString("OK", comment: "OK")) alertView.show() return } self.hud = MBProgressHUD.showHUDAddedTo(view, animated: true) self.request = self.manager.request(.POST, GlobalConstant.kAPI_Types, parameters:nil , encoding: .JSON).responseJSON { (response) -> Void in guard let value = response.result.value else { self.hud?.mode = .Text self.hud?.labelText = NSLocalizedString("Network Error", comment: "Network Error") self.hud?.hide(true, afterDelay: 0.5) self.request = nil return } let result:RequestResult = Argo.decode(value)! switch result.code { case .InvalidType: self.hud?.mode = .Text self.hud?.labelText = result.desc self.hud?.hide(true, afterDelay: 0.5) case .NoError: self.hud?.hide(true, afterDelay: 0.25) let actionSheet = UIActionSheet(title: NSLocalizedString("Change Theme", comment: "Change Theme"), delegate: self, cancelButtonTitle: NSLocalizedString("Cancel", comment: "Cancel"), destructiveButtonTitle: nil ) self.types = result.types! for type in self.types { actionSheet.addButtonWithTitle(NSLocalizedString(type, comment: type)) } actionSheet.showInView(self.view) default: self.hud?.mode = .Text self.hud?.labelText = "未知的错误类型" self.hud?.hide(true, afterDelay: 1.0) self.displayState = .errorStete } self.request = nil } } // MARK: - UIViewController override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) if let request = request { request.cancel() } } override func viewDidAppear(animated: Bool) { super.viewDidDisappear(animated) if let nickname = NSUserDefaults.standardUserDefaults().userNickname { self.meBarButtonItem.title = nickname } if request != nil && self.hud == nil { self.hud = MBProgressHUD.showHUDAddedTo(view, animated: true) } } override func viewDidLoad() { super.viewDidLoad() let config = NSURLSessionConfiguration.defaultSessionConfiguration() config.timeoutIntervalForRequest = 10 self.manager = Manager(configuration: config) self.beautyList = [] self.beautyType = "qingxin" tableView.emptyDataSetDelegate = self tableView.emptyDataSetSource = self tableView.tableHeaderView = UIView() displayState = .emptyState } func updateNickname() { if let nickname = NSUserDefaults.standardUserDefaults().userNickname { self.meBarButtonItem.title = nickname } } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return beautyList.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("beauty_cell_id", forIndexPath: indexPath) as! BeautyTableViewCell cell.beautyModel = beautyList[indexPath.row] cell.favoriteDelegate = self return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let beauty = self.beautyList[indexPath.row] return CGFloat(beauty.height) + 8 * 2 + 21 } } extension BeautiesTableViewController { enum BeautyTableDisplayState: Int { case emptyState case errorStete } } // MARK: - DZNEmptyDataSetDelegate, DZNEmptyDataSetSource extension BeautiesTableViewController: DZNEmptyDataSetDelegate, DZNEmptyDataSetSource { func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let state:BeautyTableDisplayState = displayState var description:NSAttributedString! switch state { case .emptyState: description = NSAttributedString(string: "一大波妹子正在向你奔袭^_^") case .errorStete: description = NSAttributedString(string: "妹子跑丢了/(ㄒoㄒ)/~~") } return description } func buttonTitleForEmptyDataSet(scrollView: UIScrollView!, forState state: UIControlState) -> NSAttributedString! { return NSAttributedString(string: "重新🔍妹子") } func spaceHeightForEmptyDataSet(scrollView: UIScrollView!) -> CGFloat { return 40 } func emptyDataSet(scrollView: UIScrollView!, didTapButton button: UIButton!) { self.hud = MBProgressHUD.showHUDAddedTo(view, animated: true) let type = self.beautyType self.beautyType = type } } // MARK: - UIActionSheetDelegate extension BeautiesTableViewController: UIActionSheetDelegate { func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == 0 { return } let type = self.types[buttonIndex - 1] self.beautyType = type } } // MARK: - BeautyTableViewCellProtocol extension BeautiesTableViewController : BeautyTableViewCellProtocol { func favorite(beauty: Beauty, completedBlock: (Bool) -> Void) { let uuid = NSUserDefaults.standardUserDefaults().userUUID guard let user_uuid = uuid else { // alert user to login let alert = UIAlertController(title: "提示", message: "登录之后,才可以点赞哟😊", preferredStyle: .Alert) let loginAction = UIAlertAction(title: "去登录", style:.Destructive, handler: { (action) -> Void in // jump to login self.performSegueWithIdentifier("show_login_segue_id", sender: self) }) let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil) alert.addAction(loginAction) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) completedBlock(false) return } if request != nil { // alert waiting let alertController = UIAlertController(title: "提示", message: "请稍后", preferredStyle: .Alert) let alertAction = UIAlertAction(title: "确定", style: .Default, handler: nil) alertController.addAction(alertAction) } let params:[String: String] = ["user_uuid": user_uuid, "beauty_uuid": "\(beauty.beautyID)"] request = self.manager.request(.POST, GlobalConstant.kAPI_Favorite, parameters: params, encoding: .JSON).responseJSON( completionHandler: { (response) -> Void in guard let value = response.result.value else { self.request = nil return } self.request = nil let result:RequestResult = Argo.decode(value)! switch result.code { case .NoError: completedBlock(true) default: completedBlock(false) } }) } }
mit
5acfb71136c7c53a87115ea72378a014
35.613115
169
0.58646
5.257533
false
false
false
false
hstdt/GodEye
GodEye/Classes/Controller/GodEyeController+Show.swift
1
3475
// // GodEyeController+Show.swift // Pods // // Created by zixun on 16/12/27. // // import Foundation import AssistiveButton extension GodEyeController { var animating: Bool { get { return objc_getAssociatedObject(self, &Define.Key.Associated.Animation) as? Bool ?? false } set { objc_setAssociatedObject(self, &Define.Key.Associated.Animation, newValue, .OBJC_ASSOCIATION_ASSIGN) } } var showing: Bool { get { return objc_getAssociatedObject(self, &Define.Key.Associated.Showing) as? Bool ?? false } set { objc_setAssociatedObject(self, &Define.Key.Associated.Showing, newValue, .OBJC_ASSOCIATION_ASSIGN) } } class func show() { self.shared.showConsole() } class func hide() { self.shared.hideConsole() } private func hideConsole() { if self.animating == false && self.view.superview != nil { UIApplication.shared.mainWindow()?.findAndResignFirstResponder() self.animating = true UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.4) UIView.setAnimationDelegate(self) UIView.setAnimationDidStop(#selector(GodEyeController.consoleHidden)) self.view.frame = UIScreen.offscreenFrame() UIView.commitAnimations() } } private func showConsole() { if self.animating == false && self.view.superview == nil { UIApplication.shared.mainWindow()?.findAndResignFirstResponder() self.view.frame = UIScreen.offscreenFrame() self.setViewPlace() self.animating = true UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.4) UIView.setAnimationDelegate(self) UIView.setAnimationDidStop(#selector(GodEyeController.consoleShown)) self.view.frame = UIScreen.onscreenFrame() self.view.transform = self.viewTransform() UIView.commitAnimations() } } @objc private func consoleShown() { self.showing = true self.animating = false UIApplication.shared.mainWindow()?.findAndResignFirstResponder() } @objc private func consoleHidden() { self.showing = false self.animating = false self.view.removeFromSuperview() } private func setViewPlace() { guard let superView = UIApplication.shared.mainWindow() else { return } superView.addSubview(self.view) //bring AssistiveButton to front for subview in superView.subviews { if subview.isKind(of: AssistiveButton.classForCoder()) { superView.bringSubview(toFront: subview) } } } private func viewTransform() -> CGAffineTransform { var angle: Double = 0.0 switch UIApplication.shared.statusBarOrientation { case .portraitUpsideDown: angle = M_PI case .landscapeLeft: angle = -M_PI_2 case .landscapeRight: angle = M_PI_2 default: angle = 0 } return CGAffineTransform(rotationAngle: CGFloat(angle)) } }
mit
00b128c7b3f826075697ff2c37c8fc2d
27.958333
112
0.575252
5.095308
false
false
false
false
sqlpro/swift03-basic
Delegate-ImagePicker/Delegate-ImagePicker/ViewController.swift
1
1853
import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet var imgView: UIImageView! @IBAction func pick(_ sender: AnyObject) { // 이미지 피커 컨트롤러 인스턴스 생성 let picker = UIImagePickerController( ) picker.sourceType = .photoLibrary // 이미지 소스로 사진 라이브러리 선택 picker.allowsEditing = true // 이미지 편집 기능 On picker.delegate = self // 델리게이트 지정 // 이미지 피커 컨트롤러 실행 self.present(picker, animated: false) } // 이미지 피커에서 이미지를 선택하지 않고 취소했을 때 호출되는 메소드 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { // 이미지 피커 컨트롤러 창 닫기 self.dismiss(animated: false) { () in // 알림창 호출 let alert = UIAlertController(title: "", message: "이미지 선택이 취소되었습니다", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "확인", style: .cancel)) self.present(alert, animated: false) } } // 이미지 피커에서 이미지를 선택했을 때 호출되는 메소드 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // 이미지 피커 컨트롤러 창 닫기 picker.dismiss(animated: false) { () in // 이미지를 이미지 뷰에 표시 let img = info[UIImagePickerControllerEditedImage] as? UIImage self.imgView.image = img } } }
gpl-3.0
a1a2ff683c988adb5090e78bf9e6a7b8
32.23913
119
0.572269
3.729268
false
false
false
false
a412657308/kkvapor
Sources/App/main.swift
1
21836
import Vapor import VaporPostgreSQL import HTTP import Auth import TurnstileCrypto import Foundation //import VaporMySQL // MARK: - 0.初始化 let drop = Droplet() let auth = AuthMiddleware(user:SQFriend.self) drop.middleware.append(auth) do { try drop.addProvider(VaporPostgreSQL.Provider.self) } catch { print("Error adding provider: \(error)") } drop.preparations = [SQFriend.self,SQRcToken.self,SQAllUser.self,SQProfile.self,SQActive.self,SQBanner.self,SQPic.self,SQPerson.self,SQAnimal.self] drop.get { req in return try drop.view.make("welcome", [ "message": drop.localization[req.lang, "welcome", "title"] ]) } // MARK: - 1.朋友 第三方登陆 API drop.group("friends") { friends in // MARK: - 1.1 如果该用户已经登陆过,可以从cookie中获取用户信息 let protect = ProtectMiddleware(error: Abort.custom(status: .forbidden, message: "Not authorized.") ) friends.group(protect) { secure in secure.get("secure") { req in let haveFriend = try req.user() let rc = try SQRcToken.query().filter("account",haveFriend.account).first() return try JSON(node: [ "result" : "0", "token":rc!.token, "rctoken":rc!.rctoken, "data": haveFriend.makeJSON() ]) } } friends.post("friendLogin") { req in guard let openid = req.data["openid"]?.string else { throw Abort.badRequest } let rc = try SQRcToken.query().filter("openid",openid).first() if rc != nil { // 用户直接登陆 let haveFriend = try SQFriend.query().filter("account",rc!.account).first() // let creds = Identifier(id: (haveFriend?.id)!) // 缓存用户登录信息,下次直接从cookie获取 // try req.auth.login(creds) return try JSON(node: [ "result" : "0", "token":rc!.token, "rctoken":rc!.rctoken, "data": haveFriend!.makeJSON() ]) } else { // 用户不存在,创建用户 return try JSON(node: [ "result" : "4040", ]) } } // 保存融云token 接口 friends.post("rctoken") { req in guard let username = req.data["username"]?.string else { throw Abort.badRequest } guard let sex = req.data["sex"]?.string else { throw Abort.badRequest } guard let headimgurl = req.data["headimgurl"]?.string else { throw Abort.badRequest } guard let openid = req.data["openid"]?.string else { throw Abort.badRequest } guard let deviceno = req.data["deviceno"]?.string else { throw Abort.badRequest } guard let way = req.data["way"]?.string else { throw Abort.badRequest } guard let rctoken = req.data["rctoken"]?.string else { throw Abort.badRequest } guard let rcuserid = req.data["rcuserid"]?.string else { throw Abort.badRequest } // =================================== 条件限制 =================================== // let haveRc = try SQRcToken.query().filter("openid",openid).first() if haveRc != nil { // 已经存在 return try JSON(node: [ "result" : "4000", ]) } let allF = try SQFriend.query().filter("deviceno",deviceno).all() if allF.count >= 10 { return try JSON(node: [ "result" : "4000", ]) } // =================================== 条件限制 =================================== // // 生成账号 var acc_date = Date().timeIntervalSince1970*100 let acc_tempTimeStr = String(format: "%.f", acc_date) let account_RandStr = URandom().secureToken let account = way + acc_tempTimeStr + account_RandStr // 生成token var date = Date().timeIntervalSince1970*100 let tempTimeStr = String(format: "%.f", date) let randStr = URandom().secureToken let token = tempTimeStr + randStr var friend = SQFriend(username: username,sex:sex, headimgurl: headimgurl,rcuserid:rcuserid, deviceno: deviceno, way: way, account: account, pwd:"", aboutme:"", zannum:0, photos:"",tags:"", activities:"") try friend.save() var rc = SQRcToken(account:account, token:token, openid:openid, rctoken: rctoken) try rc.save() return try JSON(node: [ "result" : "0", "token":rc.token, "rctoken":rc.rctoken, "data": friend.makeJSON() ]) } // 所有用户赞 接口 friends.post("zan") { req in guard let rcuserid = req.data["rcuserid"]?.string else { throw Abort.badRequest } var friend = try SQFriend.query().filter("rcuserid", rcuserid).first() friend?.zannum += 1 try friend?.save() return try JSON(node: [ "result" : "0", ]) } } // MARK: - 2.个人资料 drop.group("user") { user in // 查询个人中心资料 user.post("profile") { req in guard let account = req.data["account"]?.string else { throw Abort.badRequest } var friend = try SQFriend.query().filter("account", account).first() if friend != nil { return try JSON(node: [ "result" : "0", "data":JSON(node: friend!.makeJSON()) ]) } else { return try JSON(node: [ "result" : "1", ]) } } // 更新个人中心资料 user.post("updateNick") { req in guard let account = req.data["account"]?.string else { throw Abort.badRequest } guard let token = req.data["token"]?.string else { throw Abort.badRequest } guard let username = req.data["username"]?.string else { throw Abort.badRequest } var friend = try SQFriend.query().filter("account", account).first() if friend != nil { var rcModel = try SQRcToken.query().filter("token", token).first() if rcModel != nil { if (rcModel?.token.equals(any: token))! { friend?.username = username try friend?.save() return try JSON(node: [ "result" : "0", ]) } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } user.post("updateAboutMe") { req in guard let account = req.data["account"]?.string else { throw Abort.badRequest } guard let token = req.data["token"]?.string else { throw Abort.badRequest } guard let aboutme = req.data["aboutme"]?.string else { throw Abort.badRequest } var friend = try SQFriend.query().filter("account", account).first() if friend != nil { var rcModel = try SQRcToken.query().filter("token", token).first() if rcModel != nil { if (rcModel?.token.equals(any: token))! { friend?.aboutme = aboutme try friend?.save() return try JSON(node: [ "result" : "0", ]) } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } user.post("updateTags") { req in guard let account = req.data["account"]?.string else { throw Abort.badRequest } guard let token = req.data["token"]?.string else { throw Abort.badRequest } guard let tags = req.data["tags"]?.string else { throw Abort.badRequest } var friend = try SQFriend.query().filter("account", account).first() if friend != nil { var rcModel = try SQRcToken.query().filter("token", token).first() if rcModel != nil { if (rcModel?.token.equals(any: token))! { friend?.tags = tags try friend?.save() return try JSON(node: [ "result" : "0", ]) } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } user.post("updatePhotos") { req in guard let account = req.data["account"]?.string else { throw Abort.badRequest } guard let token = req.data["token"]?.string else { throw Abort.badRequest } guard let photos = req.data["photos"]?.string else { throw Abort.badRequest } var friend = try SQFriend.query().filter("account", account).first() if friend != nil { var rcModel = try SQRcToken.query().filter("token", token).first() if rcModel != nil { if (rcModel?.token.equals(any: token))! { friend?.photos = photos try friend?.save() return try JSON(node: [ "result" : "0", "photos" : photos ]) } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } user.post("updateHeaderImage") { req in guard let account = req.data["account"]?.string else { throw Abort.badRequest } guard let token = req.data["token"]?.string else { throw Abort.badRequest } guard let headimgurl = req.data["headimgurl"]?.string else { throw Abort.badRequest } var friend = try SQFriend.query().filter("account", account).first() if friend != nil { var rcModel = try SQRcToken.query().filter("token", token).first() if rcModel != nil { if (rcModel?.token.equals(any: token))! { friend?.headimgurl = headimgurl try friend?.save() return try JSON(node: [ "result" : "0", "headimgurl" : headimgurl ]) } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } else { return try JSON(node: [ "result" : "1", ]) } } } // MARK: - 3.广场 API drop.group("allUsers") { allUsers in allUsers.get("allFriends") { req in let friends = try SQFriend.all() let sqpic = try SQPic.all().first return try JSON(node: [ "result" : "0", "data" : JSON(node: friends.makeJSON()), "pic" : sqpic?.pic, "color" : "FC6E5E" ]) } } // MARK: - 4.banner API drop.group("sqbanner") { sqbanner in sqbanner.get("banner") { req in return try JSON(node: SQBanner.all().makeJSON()) } // 新增banner条 sqbanner.post("addbanner") { req in guard let imgurl = req.data["imgurl"]?.string else { throw Abort.badRequest } guard let neturl = req.data["neturl"]?.string else { throw Abort.badRequest } guard let btype = req.data["btype"]?.int else { throw Abort.badRequest } guard let squserid = req.data["squserid"]?.string else { throw Abort.badRequest } guard let bannertext = req.data["bannertext"]?.string else { throw Abort.badRequest } var banner = SQBanner(imgurl: imgurl, neturl: neturl, btype: btype, squserid: squserid, bannertext: bannertext) try banner.save() return try JSON(node: [ "result" : "0" ]) } sqbanner.post("sqpic") { rep in guard let pic = rep.data["pic"]?.string else { throw Abort.badRequest } var sqpic = SQPic(pic: pic) try sqpic.save() return try JSON(node: [ "result" : "0" ]) } } // MARK: - 5.动态 API drop.group("sqacitves") { sqacitves in sqacitves.post("act") { req in guard let page = req.data["page"]?.int else { throw Abort.badRequest } return try JSON(node: [ "result" : "0", "data" : JSON(node: SQActive.all().makeJSON()), "haveMore":"Y" ]) } sqacitves.post("release") { req in guard let username = req.data["username"]?.string else { throw Abort.badRequest } guard let sex = req.data["sex"]?.string else { throw Abort.badRequest } guard let headimgurl = req.data["headimgurl"]?.string else { throw Abort.badRequest } guard let account = req.data["account"]?.string else { throw Abort.badRequest } guard let token = req.data["token"]?.string else { throw Abort.badRequest } guard let actcontent = req.data["actcontent"]?.string else { throw Abort.badRequest } guard let zancount = req.data["zancount"]?.int else { throw Abort.badRequest } guard let commoncount = req.data["commoncount"]?.int else { throw Abort.badRequest } guard let photostr = req.data["photostr"]?.string else { throw Abort.badRequest } guard let sqlocal = req.data["sqlocal"]?.string else { throw Abort.badRequest } guard let acttime = req.data["acttime"]?.string else { throw Abort.badRequest } guard let rcuserid = req.data["rcuserid"]?.string else { throw Abort.badRequest } guard let width = req.data["width"]?.double else { throw Abort.badRequest } guard let height = req.data["height"]?.double else { throw Abort.badRequest } var rcToken = try SQRcToken.query().filter("account", account).first() if (rcToken?.token.equals(any: token))! { var act = SQActive(username: username, sex: sex, headimgurl: headimgurl, account: account, actcontent: actcontent, photostr: photostr, zancount: zancount, commoncount: commoncount, sqlocal: sqlocal, acttime: acttime, rcuserid: rcuserid, width: width, height: height) try act.save() var fri = try SQFriend.query().filter("account", account).first() if (fri?.activities.equals(any: ""))! { fri?.activities = acttime } else { fri?.activities = (fri?.activities)! + "," + acttime } try fri?.save() return try JSON(node: [ "result" : "0", "data" : JSON(node: act.makeJSON()) ]) } else { return try JSON(node: [ "result" : "1", ]) } } sqacitves.post("zan") { req in guard let id = req.data["id"]?.string else { throw Abort.badRequest } var act = try SQActive.query().filter("id", id).first() act?.zancount += 1 try act?.save() return try JSON(node: [ "result" : "0", ]) } } // MARK: - 6.Apple 专用 drop.group("apple") { apple in apple.post("login") { req in guard let account = req.data["account"]?.string else { throw Abort.badRequest } guard let pwd = req.data["pwd"]?.string else { throw Abort.badRequest } if account.equals(any: "123456789") && pwd.equals(any: "123654") { let haveFriend = try SQFriend.query().filter("id", 1).first() let rc = try SQRcToken.query().filter("account", (haveFriend?.account)!).first() return try JSON(node: [ "result" : "0", "token":rc!.token, "rctoken":rc!.rctoken, "data": haveFriend!.makeJSON() ]) } let f = try SQFriend.query().filter("name",.greaterThan, 21).all() let haveFriend = try SQFriend.query().filter("pwd", "123").first() let rc = try SQRcToken.query().filter("account", (haveFriend?.account)!).first() return try JSON(node: [ "result" : "1" ]) } } // MARK: - 7.网页接口 drop.get("/srsq") { request in let dict = request.json return try drop.view.make("srsq/index.html") } drop.get("/home") { request in let id = request.data["id"]?.int if id != nil { return try JSON(node: [ "result" : "1", "data":JSON(node: SQActive.find(id!)?.makeJSON()) ]) } return try drop.view.make("home/welcome.html") } drop.get("shareData") { request in guard let id = request.data["id"]?.string else { throw Abort.badRequest } var act = try SQActive.find(id) if act != nil { return try JSON(node: [ "result" : "0", "data":JSON(node: act?.makeJSON()) ]) } else { return try JSON(node: [ "result" : "1", ]) } } drop.get("profileShare") { request in guard let account = request.data["id"]?.string else { throw Abort.badRequest } var act = try SQFriend.query().filter("account", account).first(); if act != nil { return try JSON(node: [ "result" : "0", "data":JSON(node: act?.makeJSON()) ]) } else { return try JSON(node: [ "result" : "1", ]) } } drop.get("/share") { request in return try drop.view.make("share/index.html") } // MARK: - 8.1 版本更新 drop.post("version") { request in guard let version = request.data["version"]?.string else { throw Abort.badRequest } if version.equals(any: "1.5.0") { return try JSON(node: [ "result": "0", "msg": "0" ]) } else { return try JSON(node: [ "result": "1", "msg": "发现新版:1.3.0,更新内容:\n1.优化即时聊天IM\n2.压缩安装包大小\n3.极限省流量\n4.支持上传相册\n5.无限制内容分享\n6.动态发布支持连接,点击可调转\n7.社区列表流畅度提升\n8.支持https\n9.消息推送、自定义推送\n10.安全的cookie自动登录策略" ]) } } // MARK: - 8.2 安全策略 drop.post("cysafee") { request in guard let v = request.data["v"]?.string else { throw Abort.badRequest } guard let c = request.data["c"]?.int else { throw Abort.badRequest } return try JSON(node: [ "l": "111", "s": "1", "c": "0", ]) } // MARK: - 9.1 演示 API drop.get("leaf") { request in return try drop.view.make("template", [ "greeting": "Hello, world!" ]) } drop.get("session") { request in let json = try JSON(node: [ "session.data": "\(request.session().data["name"] ?? "")", "request.cookies": "\(request.cookies)", "instructions": "Refresh to see cookie and session get set." ]) var response = try Response(status: .ok, json: json) try request.session().data["name"] = "Vapor" response.cookies["test"] = "123" return response } drop.get("data", Int.self) { request, int in return try JSON(node: [ "int": int, "name": request.data["name"]?.string ?? "no name" ]) } drop.get("json") { request in return try JSON(node: [ "number": 123, "string": "test", "array": try JSON(node: [ 0, 1, 2, 3 ]), "dict": try JSON(node: [ "name": "Vapor", "lang": "Swift" ]) ]) } // MARK: - 10 待调查 // 1.cookie 时长 drop.resource("posts", PostController()) drop.run()
mit
7b85cf26e1bcdeb8a74badfc362707bb
31.156391
278
0.478442
4.168421
false
false
false
false
Candyroot/DesignPattern
factory/factory/NYPizzaStore.swift
1
1084
// // NYPizzaStore.swift // Chapter4 // // Created by Bing Liu on 11/2/14. // Copyright (c) 2014 UnixOSS. All rights reserved. // import Cocoa public class NYPizzaStore: PizzaStore { public override func createPizza(type: String) -> Pizza? { var pizza: Pizza? let ingredientFactory: PizzaIngredientFactory = NYPizzaIngredientFactory() switch type { case "cheese": pizza = CheesePizza(ingredientFactory: ingredientFactory) pizza!.name = "New York Style Cheese Pizza" case "veggie": pizza = VeggiePizza(ingredientFactory: ingredientFactory) pizza!.name = "New York Style Veggie Pizza" case "clam": pizza = ClamPizza(ingredientFactory: ingredientFactory) pizza!.name = "New York Style Clam Pizza" case "pepperoni": pizza = PepperoniPizza(ingredientFactory: ingredientFactory) pizza!.name = "New York Style Pepperoni Pizza" default: pizza = nil } return pizza } }
apache-2.0
45a67e7bfc320cd0b7f0cce48b802f29
29.971429
82
0.608856
4.121673
false
false
false
false
cotkjaer/Silverback
Silverback/Approximate.swift
1
1893
// // Approximate.swift // Silverback // // Created by Christian Otkjær on 14/12/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import CoreGraphics //MARK: - Approximate equals public func equal<C:Comparable where C:Subtractable, C:AbsoluteValuable>(lhs: C, _ rhs: C, accuracy: C) -> Bool { return abs(rhs - lhs) <= accuracy// || lhs - rhs <= accuracy } // //public func equal(lhs: CGFloat, _ rhs: CGFloat, accuracy: CGFloat) -> Bool { // return abs(rhs - lhs) <= accuracy //} // //public func equal(lhs: Float, _ rhs: Float, accuracy: Float) -> Bool { // return abs(rhs - lhs) <= accuracy //} // //public func equal(lhs: Double, _ rhs: Double, accuracy: Double) -> Bool { // return abs(rhs - lhs) <= accuracy //} // MARK: Fuzzy equality public protocol FuzzyEquatable { func ==%(lhs: Self, rhs: Self) -> Bool } infix operator ==% { associativity none precedence 130 } // MARK: Fuzzy inequality infix operator !=% { associativity none precedence 130 } public func !=% <T: FuzzyEquatable> (lhs: T, rhs: T) -> Bool { return !(lhs ==% rhs) } // MARK: Float extension Float: FuzzyEquatable {} public func ==% (lhs: Float, rhs: Float) -> Bool { let epsilon = Float(FLT_EPSILON) // TODO: FLT vs DBL return equal(lhs, rhs, accuracy: epsilon) } // MARK: Double extension Double: FuzzyEquatable {} public func ==% (lhs: Double, rhs: Double) -> Bool { let epsilon = Double(FLT_EPSILON) // TODO: FLT vs DBL return equal(lhs, rhs, accuracy: epsilon) } // Mark: CGFloat extension CGFloat: FuzzyEquatable {} public func ==% (lhs: CGFloat, rhs: CGFloat) -> Bool { let epsilon = CGFloat(FLT_EPSILON) // TODO: FLT vs DBL return equal(lhs, rhs, accuracy: epsilon) } // MARK: CGPoint extension CGPoint: FuzzyEquatable {} public func ==% (lhs: CGPoint, rhs: CGPoint) -> Bool { return lhs.x ==% rhs.x && lhs.y ==% rhs.y }
mit
f8a662e46917205d1ce810d49609b7de
22.333333
111
0.647619
3.309982
false
false
false
false
eBardX/XestiMonitors
Sources/Core/CoreMotion/AccelerometerMonitor.swift
1
3381
// // AccelerometerMonitor.swift // XestiMonitors // // Created by J. G. Pusey on 2016-12-16. // // © 2016 J. G. Pusey (see LICENSE.md) // #if os(iOS) || os(watchOS) import CoreMotion import Foundation /// /// An `AccelerometerMonitor` instance monitors the device’s accelerometer /// for periodic raw measurements of the acceleration along the three /// spatial axes. /// public class AccelerometerMonitor: BaseMonitor { /// /// Encapsulates updates to the measurement of the acceleration along /// the three spatial axes. /// public enum Event { /// /// The acceleration measurement has been updated. /// case didUpdate(Info) } /// /// Encapsulates the measurement of the acceleration along the three /// spatial axes at a moment of time. /// public enum Info { /// /// The acceleration measurement. /// case data(CMAccelerometerData) /// /// The error encountered in attempting to obtain the acceleration /// measurement. /// case error(Error) /// /// No acceleration measurement is available. /// case unknown } /// /// Initializes a new `AccelerometerMonitor`. /// /// - Parameters: /// - interval: The interval, in seconds, for providing /// acceleration measurements to the handler. /// - queue: The operation queue on which the handler executes. /// Because the events might arrive at a high rate, /// using the main operation queue is not recommended. /// - handler: The handler to call periodically when a new /// acceleration measurement is available. /// public init(interval: TimeInterval, queue: OperationQueue, handler: @escaping (Event) -> Void) { self.handler = handler self.interval = interval self.motionManager = MotionManagerInjector.inject() self.queue = queue } /// /// The latest acceleration measurement available. /// public var info: Info { guard let data = motionManager.accelerometerData else { return .unknown } return .data(data) } /// /// A Boolean value indicating whether an accelerometer is available on /// the device. /// public var isAvailable: Bool { return motionManager.isAccelerometerAvailable } private let handler: (Event) -> Void private let interval: TimeInterval private let motionManager: MotionManagerProtocol private let queue: OperationQueue override public func cleanupMonitor() { motionManager.stopAccelerometerUpdates() super.cleanupMonitor() } override public func configureMonitor() { super.configureMonitor() motionManager.accelerometerUpdateInterval = interval motionManager.startAccelerometerUpdates(to: queue) { [unowned self] data, error in var info: Info if let error = error { info = .error(error) } else if let data = data { info = .data(data) } else { info = .unknown } self.handler(.didUpdate(info)) } } } #endif
mit
df839b64dca8380f41efe023c4f369dc
25.809524
90
0.588218
5.14939
false
false
false
false
erkekin/EERegression
EERegression/swix/swix/ndarray/complex-math.swift
1
2959
// // math.swift // swix // // Created by Scott Sievert on 7/11/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate // integration func cumtrapz(x:ndarray)->ndarray{ // integrate and see the steps at each iteration let y = zeros_like(x) var dx:CDouble = 1.0 vDSP_vtrapzD(!x, 1.stride, &dx, !y, 1.stride, x.n.length) return y } func trapz(x:ndarray)->Double{ // integrate and get the final value return cumtrapz(x)[-1] } // basic definitions func inner(x:ndarray, y:ndarray)->Double{ // the inner product. aka dot product, but I use dot product as a short for matrix multiplication return sum(x * y) } func outer(x:ndarray, y:ndarray)->matrix{ // the outer product. var (xm, ym) = meshgrid(x, y: y) return xm * ym } // fourier transforms func fft(x: ndarray) -> (ndarray, ndarray){ let N:CInt = x.n.cint var yr = zeros(N.int) var yi = zeros(N.int) // setup for the accelerate calling let radix:FFTRadix = FFTRadix(FFT_RADIX2) let pass:vDSP_Length = vDSP_Length((log2(N.double)+1.0).int) let setup:FFTSetupD = vDSP_create_fftsetupD(pass, radix) let log2n:Int = (log2(N.double)+1.0).int let z = zeros(N.int) var x2:DSPDoubleSplitComplex = DSPDoubleSplitComplex(realp: !x, imagp:!z) var y = DSPDoubleSplitComplex(realp:!yr, imagp:!yi) let dir = FFTDirection(FFT_FORWARD) let stride = 1.stride // perform the actual computation vDSP_fft_zropD(setup, &x2, stride, &y, stride, log2n.length, dir) // this divide seems wrong yr /= 2.0 yi /= 2.0 return (yr, yi) } func ifft(yr: ndarray, yi: ndarray) -> ndarray{ let N = yr.n var x = zeros(N) // setup for the accelerate calling let radix:FFTRadix = FFTRadix(FFT_RADIX2) let pass:vDSP_Length = vDSP_Length((log2(N.double)+1.0).int) let setup:FFTSetupD = vDSP_create_fftsetupD(pass, radix) let log2n:Int = (log2(N.double)+1.0).int let z = zeros(N) var x2:DSPDoubleSplitComplex = DSPDoubleSplitComplex(realp: !yr, imagp:!yi) var result:DSPDoubleSplitComplex = DSPDoubleSplitComplex(realp: !x, imagp:!z) let dir = FFTDirection(FFT_INVERSE) let stride = 1.stride // doing the actual computation vDSP_fft_zropD(setup, &x2, stride, &result, stride, log2n.length, dir) // this divide seems wrong x /= 16.0 return x } func fftconvolve(x:ndarray, kernel:ndarray)->ndarray{ // convolve two arrays using the fourier transform. // zero padding, assuming kernel is smaller than x var k_pad = zeros_like(x) k_pad[0..<kernel.n] = kernel // performing the fft var (Kr, Ki) = fft(k_pad) var (Xr, Xi) = fft(x) // computing the multiplication (yes, a hack) // (xr+xi*j) * (yr+yi*j) = xr*xi - xi*yi + j*(xi*yr) + j*(yr*xi) let Yr = Xr*Kr - Xi*Ki let Yi = Xr*Ki + Xi*Kr let y = ifft(Yr, yi: Yi) return y }
gpl-2.0
5053c0eb1908e9b1e7d30bc36e69a77c
29.204082
101
0.636702
3.134534
false
false
false
false
alex520biao/ALPodTemplate
setup/test_examples/quick.swift
2
1086
// https://github.com/Quick/Quick import Quick import Nimble import PROJECT class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will exentually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } }
mit
8456fcb001327df7fd29577ecafedc79
20.6
60
0.391667
5
false
false
false
false
polarize/OpenAdblock
Open Adblock/Open Adblock/Adblocker.swift
2
2457
// // Adblocker.swift // Open Adblock // // Created by Saagar Jha on 8/21/15. // Copyright © 2015 OpenAdblock. All rights reserved. // import Foundation class Adblocker { static let sharedInstance = Adblocker() var ruleNames = [String]() var whitelist = [String]() init() { copyFile() // let data = NSData(contentsOfURL: NSURL(fileURLWithPath: ((NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("blockerList") as NSString).stringByAppendingPathExtension("json")!)) // var jsonData: AnyObject? // do { // jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) // } catch _ { // assertionFailure("Error parsing JSON") // } // //print(jsonData) // for json in jsonData as! [AnyObject] { // if let trigger = (json as! [String: AnyObject])["trigger"] { // if let rule = (trigger as! [String: AnyObject])["url-filter"] { // ruleNames.append(rule as! String) // //print(website) // } // } // } } func copyFile() { let bundlePath = ((NSBundle.mainBundle().resourcePath! as NSString).stringByAppendingPathComponent("blockerList") as NSString).stringByAppendingPathExtension("json")! let documentsPath = ((NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("blockerList") as NSString).stringByAppendingPathExtension("json")! let fileManager = NSFileManager.defaultManager() if !fileManager.fileExistsAtPath(documentsPath) { do { try fileManager.copyItemAtPath(bundlePath, toPath: documentsPath) } catch _ { assertionFailure("Could not copy blockerList") } } } func getWhitelist() -> [String] { return whitelist } func addWhitelistedWebsite(url: String) { whitelist.append(url) } func containsWhitelistedWebsite(url: String) -> Bool { return whitelist.indexOf(url) != nil } func removeWhitelistedWebsite(url: String) { whitelist.removeAtIndex(whitelist.indexOf(url)!) } func setWhitelisted(url: String, whitelist toWhitelist: Bool) { } }
apache-2.0
6be2ac6f2873836bbb1f686e4e97797e
34.608696
267
0.619707
4.951613
false
false
false
false
librerose/YoutubeView
YoutubeViewSample/YoutubeViewSample/ViewController.swift
1
1050
// // ViewController.swift // YoutubeViewSample // // Created by Meng on 15/10/30. // Copyright © 2015年 Libre Rose. All rights reserved. // import UIKit import YoutubeView class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { view.addSubview(videoView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() //_videoView = nil } var videoView: YoutubeView { if nil == _videoView { // Custom a rect let rect = CGRect(x: 0, y: 20, width: view.bounds.size.width, height: view.bounds.size.height - 120) // a Youtube video: Naxi Song by Chen Sisi let url = "https://www.youtube.com/embed/hW33XnBE1_4" _videoView = YoutubeView(frame: rect, embedURL: url) _videoView?.backgroundColor = UIColor.redColor() } return _videoView! } var _videoView: YoutubeView? }
mit
799843465a4f2db5841c639b2486fc12
23.928571
112
0.61127
4.204819
false
false
false
false
SwiftKit/Staging
Source/ThreadLocal.swift
1
1430
// // ThreadLocal.swift // SwiftKit // // Created by Tadeas Kriz on 13/10/15. // Copyright © 2015 Tadeas Kriz. All rights reserved. // import Foundation open class ThreadLocal<T: AnyObject>: ThreadLocalParametrized<Void, T> { public convenience init(create: @escaping () -> T) { self.init(id: UUID().uuidString, create: create) } public override init(id: String, create: @escaping () -> T) { super.init(id: id, create: create) } open func get() -> T { return super.get() } } open class ThreadLocalParametrized<PARAMS, T: AnyObject> { fileprivate let id: String fileprivate let create: (PARAMS) -> T public convenience init(create: @escaping (PARAMS) -> T) { self.init(id: UUID().uuidString, create: create) } public init(id: String, create: @escaping (PARAMS) -> T) { self.id = id self.create = create } open func get(_ parameters: PARAMS) -> T { if let cachedObject = Thread.current.threadDictionary[id] as? T { return cachedObject } else { let newObject = create(parameters) set(newObject) return newObject } } open func set(_ value: T) { Thread.current.threadDictionary[id] = value } open func remove() { Thread.current.threadDictionary.removeObject(forKey: id) } }
mit
e87ee311895b821bc22b6acf78c4a796
24.070175
73
0.587124
3.969444
false
false
false
false
mindbody/Conduit
Sources/Conduit/Networking/Serialization/QueryString.swift
1
9513
// // QueryString.swift // Conduit // // Created by Matthew Holden on 8/2/16. // Copyright © 2017 MINDBODY. All rights reserved. // import Foundation /// Formatting options for non-standard query string datatypes public struct QueryStringFormattingOptions { /// Defines how arrays should be formatted within a query string public enum ArrayFormat { /// param=value1&param=value2&param=value3 case duplicatedKeys /// param[]=value1&param[]=value2&param[]=value3 case bracketed /// param[0]=value1&param[1]=value2&param[3]=value3 case indexed /// param=value1,value2,value3 case commaSeparated } /// Defines how dictionaires should be formatted within a query string public enum DictionaryFormat { /// param.key1=value1&param.key2=value2&param.key3.key4=value3 case dotNotated /// param[key1]=value1&param[key2]=value2&param[key3][key4]=value3 case subscripted } /// Defines how plus symbols should be encoded within a query string public enum PlusSymbolEncodingRule { /// param1=some+value => param1=some+value case decoded /// param1=some+value => param1=some%20value case replacedWithEncodedSpace /// param1=some+value => param1=some%2Bvalue case replacedWithEncodedPlus } /// Defines how spaces should be encoded within a query string public enum SpaceEncodingRule { /// param1=some value => param1=some%20value case encoded /// param1=some value => param1=some+value case replacedWithDecodedPlus } /// The format in which arrays should be serialized within a query string public var arrayFormat: ArrayFormat = .indexed /// The format in which dictionaries should be serialized within a query string public var dictionaryFormat: DictionaryFormat = .subscripted /// Includes any reserved delimiter characters that should be URL-encoded /// By default, reserved characters listed in [RFC 3986 Section 6.2.2](https://www.ietf.org/rfc/rfc3986.txt) /// are not encoded. This doesn't include conflicting delimiter characters (&=#[]%) which /// are always encoded. /// /// - Note: Non-reserved characters, characters listed above (&=#[]%), and /// characters with special encoding rules (+ ) will be ignored. If more complex encoding is required, /// then percent-encoding will need to be handled manually. public var percentEncodedReservedCharacterSet: CharacterSet? /// Determines whether '+' should be replaced with '%2B' or '%20'. By default, /// this follows Apple's behavior of not encoding plus symbols. /// /// [View Radar](http://www.openradar.me/24076063) public var plusSymbolEncodingRule: PlusSymbolEncodingRule = .replacedWithEncodedPlus /// Determines whether ' ' should be replaced with '%20' or '+'. By default, /// this follows Apple's behavior of encoding to '%20'. public var spaceEncodingRule: SpaceEncodingRule = .encoded public init() {} } internal struct QueryString { var parameters: Any? var url: URL var formattingOptions: QueryStringFormattingOptions init(parameters: Any?, url: URL, formattingOptions: QueryStringFormattingOptions = QueryStringFormattingOptions()) { self.parameters = parameters self.url = url self.formattingOptions = formattingOptions } func encodeURL() throws -> URL { guard let params = parameters else { return url } var queryItems = [URLQueryItem]() switch params { case let dictionary as [String: Any]: queryItems.append(contentsOf: queryItemsFromDictionary(dict: dictionary)) case let number as NSNumber: let newPath = "\(url.absoluteString)?\(number.stringValue)" guard let newUrl = URL(string: newPath) else { throw RequestSerializerError.serializationFailure } return newUrl default: let newPath = "\(url.absoluteString)?\(params)" guard let newUrl = URL(string: newPath) else { throw RequestSerializerError.serializationFailure } return newUrl } guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { throw RequestSerializerError.serializationFailure } components.queryItems = queryItems /// Respect encoding rules if let percentEncodedQuery = components.percentEncodedQuery { components.percentEncodedQuery = format(percentEncodedQuery: percentEncodedQuery) } guard let finalURL = components.url else { throw RequestSerializerError.serializationFailure } return finalURL } private func format(percentEncodedQuery: String) -> String { /// To avoid nasty bugs, we're going to trade a tiny bit of performance for /// cleaner code. We'll take the original version of the encoded query and identify/ /// replace '+' and '%20' with their own hashes for later search/replace let spaceIdentifier = UUID().uuidString let plusIdentifier = UUID().uuidString var searchablePercentEncodedQuery = percentEncodedQuery.replacingOccurrences(of: "%20", with: spaceIdentifier) searchablePercentEncodedQuery = searchablePercentEncodedQuery.replacingOccurrences(of: "+", with: plusIdentifier) let plusSymbolReplacement: String switch formattingOptions.plusSymbolEncodingRule { case .decoded: plusSymbolReplacement = "+" case .replacedWithEncodedPlus: plusSymbolReplacement = "%2B" case .replacedWithEncodedSpace: plusSymbolReplacement = "%20" } let spaceReplacement: String switch formattingOptions.spaceEncodingRule { case .encoded: spaceReplacement = "%20" case .replacedWithDecodedPlus: spaceReplacement = "+" } var newPercentEncodedQuery = searchablePercentEncodedQuery.replacingOccurrences(of: plusIdentifier, with: plusSymbolReplacement) newPercentEncodedQuery = newPercentEncodedQuery.replacingOccurrences(of: spaceIdentifier, with: spaceReplacement) if var percentEncodedReservedCharacterSet = formattingOptions.percentEncodedReservedCharacterSet { // Only encode reserved characters that don't conflict with query delimiters or special encoding rules let reservedCharacterSet = CharacterSet(charactersIn: "!*'();:@$,/?") percentEncodedReservedCharacterSet = percentEncodedReservedCharacterSet.intersection(reservedCharacterSet) newPercentEncodedQuery = newPercentEncodedQuery .addingPercentEncoding(withAllowedCharacters: percentEncodedReservedCharacterSet.inverted) ?? newPercentEncodedQuery } return newPercentEncodedQuery } private func queryItemsFromDictionary(dict: [String: Any]) -> [URLQueryItem] { return dict.flatMap { kvp in queryItemsFrom(parameter: (kvp.key, kvp.value)) } } private func queryItemsFrom(parameter: (String, Any)) -> [URLQueryItem] { let name = parameter.0 var value: String? if let parameterValue = parameter.1 as? [Any] { return queryItemsFrom(arrayParameter: (name, parameterValue)) } if let parameterValue = parameter.1 as? [String: Any] { return queryItemsFrom(dictionaryParameter: (name, parameterValue)) } if let parameterValue = parameter.1 as? String { value = parameterValue } else if let parameterValue = parameter.1 as? NSNumber { value = parameterValue.stringValue } else if parameter.1 is NSNull { value = nil } else { value = "\(parameter.1)" } return [URLQueryItem(name: name, value: value)] } private func queryItemsFrom(arrayParameter parameter: (String, [Any])) -> [URLQueryItem] { let key = parameter.0 let value = parameter.1 switch formattingOptions.arrayFormat { case .indexed: return value.enumerated().flatMap { queryItemsFrom(parameter: ("\(key)[\($0)]", $1)) } case .bracketed: return value.flatMap { queryItemsFrom(parameter: ("\(key)[]", $0)) } case .duplicatedKeys: return value.flatMap { queryItemsFrom(parameter: (key, $0)) } case .commaSeparated: let queryItemValue = value.map { "\($0)" }.joined(separator: ",") return [URLQueryItem(name: key, value: queryItemValue)] } } private func queryItemsFrom(dictionaryParameter parameter: (String, [String: Any])) -> [URLQueryItem] { let key = parameter.0 let value = parameter.1 switch formattingOptions.dictionaryFormat { case .dotNotated: return value.flatMap { queryItemsFrom(parameter: ("\(key).\($0)", $1)) } case .subscripted: return value.flatMap { queryItemsFrom(parameter: ("\(key)[\($0)]", $1)) } } } }
apache-2.0
f73cebaa78f5afea924b80703f0ff0ea
38.144033
132
0.639298
5.152763
false
false
false
false
ccarnino/SwiftyPCA9685
Examples/SetPwmOnChannel/CommandLine+AppArguments.swift
1
3340
// // main.swift // SwiftyPCA9685 // // Created by Claudio Carnino on 17/08/2016. // Copyright © 2016 Tugulab. All rights reserved. // import Foundation extension CommandLine { /// Structs who holds struct AppArguments { let busNumber: Int let address: Int let frequency: Int let channel: PCA9685Module.Channel let dutyCycle: Double } private enum ArgumentName: String { case busNumber = "bus-number" case address case frequency case channel case dutyCycle = "duty-cycle" static var list: [ArgumentName] { return [.busNumber, .address, .frequency, .channel, .dutyCycle] } } /// Returns a dictionary of the app arguments and the respective value set static func appArguments() -> AppArguments? { var commandLineArguments = [ArgumentName: Any]() // Look for all valid arguments in the input array ArgumentName.list.forEach { appArgument in for commandLineArgument in CommandLine.arguments { let argumentPrefix = "\(appArgument.rawValue)=" let doesItemContainsAppArgumentPrefix = commandLineArgument.contains(argumentPrefix) if doesItemContainsAppArgumentPrefix { guard let equalSymbolIndex = commandLineArgument.characters.index(of: "=") else { continue } let valueStartIndex = commandLineArgument.index(after: equalSymbolIndex) let argumentValue = commandLineArgument.substring(from: valueStartIndex) guard !argumentValue.isEmpty else { continue } // Cast the argument value depending on the argument switch appArgument { case .busNumber: commandLineArguments[.busNumber] = Int(argumentValue) case .address: commandLineArguments[.address] = Int(strtoul(argumentValue, nil, 16)) // From hexadecimal string case .frequency: commandLineArguments[.frequency] = Int(argumentValue) case .channel: commandLineArguments[.channel] = Int(argumentValue) case .dutyCycle: commandLineArguments[.dutyCycle] = Double(argumentValue) } } } } // Check that all the required arguments have been set guard let busNumber = commandLineArguments[.busNumber] as? Int, let address = commandLineArguments[.address] as? Int, let frequency = commandLineArguments[.frequency] as? Int, let channelRawValue = commandLineArguments[.channel] as? Int, let channel = PCA9685Module.Channel(rawValue: channelRawValue), let dutyCycle = commandLineArguments[.dutyCycle] as? Double else { return nil } return AppArguments(busNumber: busNumber, address: address, frequency: frequency, channel: channel, dutyCycle: dutyCycle) } }
mit
3cbec51493b81d311fbf61330314d945
36.943182
129
0.565738
5.429268
false
false
false
false
mono0926/LicensePlist
Sources/LicensePlistCore/Entity/VersionInfo.swift
1
1395
import Foundation public struct VersionInfo: Equatable { var dictionary: [String: String] = [:] func version(name: String) -> String? { return dictionary[name] } public static func==(lhs: VersionInfo, rhs: VersionInfo) -> Bool { return lhs.dictionary == rhs.dictionary } } extension VersionInfo { init(podsManifest: String) { let nsPodManifest = podsManifest as NSString let regex = try! NSRegularExpression(pattern: "- (.*) \\(([0-9.]*)\\)", options: []) dictionary = regex.matches(in: podsManifest, options: [], range: NSRange(location: 0, length: nsPodManifest.length)) .reduce([String: String]()) { sum, match in let numberOfRanges = match.numberOfRanges guard numberOfRanges == 3 else { assert(false, "maybe invalid regular expression to: \(nsPodManifest.substring(with: match.range))") return sum } let name = nsPodManifest.substring(with: match.range(at: 1)) let version = nsPodManifest.substring(with: match.range(at: 2)) var sum = sum sum[name] = version if let prefix = name.components(separatedBy: "/").first, sum[prefix] == nil { sum[prefix] = version } return sum } } }
mit
f4105c15ed163695e0d75d9efa930e1f
37.75
124
0.563441
4.57377
false
false
false
false
rizainuddin/ios-nd-alien-adventure-swift-3
Alien Adventure/XORCipherKeySearch.swift
1
1321
// // XORCipherKeySearch.swift // Alien Adventure // // Created by Jarrod Parkes on 10/3/15. // Copyright © 2015 Udacity. All rights reserved. // import Foundation extension Hero { func xorCipherKeySearch(encryptedString: [UInt8]) -> UInt8 { // NOTE: This code doesn't exactly mimic what is in the Lesson. We've // added some print statements so that there are no warnings for // unused variables 😀. var key: UInt8 key = 0 for x in UInt8.min..<UInt8.max { print(x) var decrypted: [UInt8] decrypted = [UInt8]() for character in encryptedString { // ADD CODE: perform decryption print(character) } if let decryptedString = String(bytes: decrypted, encoding: String.Encoding.utf8), decryptedString == "udacity" { // ADD CODE: found match, now what? } } return key } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 3"
mit
5155c99d9ee4aac8232e24a878353e22
29.627907
235
0.563402
4.73741
false
false
false
false
DivineDominion/mac-licensing-fastspring-cocoafob
Trial-Expire-While-Running/MyNewApp/ExistingLicenseViewController.swift
1
1206
// Copyright (c) 2015-2019 Christian Tietze // // See the file LICENSE for copying permission. import Cocoa public protocol HandlesRegistering: AnyObject { func register(name: String, licenseCode: String) } public class ExistingLicenseViewController: NSViewController { @IBOutlet public weak var licenseeTextField: NSTextField! @IBOutlet public weak var licenseCodeTextField: NSTextField! @IBOutlet public weak var registerButton: NSButton! public var eventHandler: HandlesRegistering? @IBAction public func register(_ sender: AnyObject) { guard let eventHandler = eventHandler else { return } let name = licenseeTextField.stringValue let licenseCode = licenseCodeTextField.stringValue eventHandler.register(name: name, licenseCode: licenseCode) } public func displayEmptyForm() { licenseeTextField.stringValue = "" licenseCodeTextField.stringValue = "" } public func display(license: License) { licenseeTextField.stringValue = license.name licenseCodeTextField.stringValue = license.licenseCode } }
mit
b87d28dd871edf432ea459e5e9439428
27.046512
67
0.677446
5.583333
false
false
false
false
jpedrosa/sua_nc
Sources/murmurhash3.swift
2
5899
public class MurmurHash3 { // MurmurHash3 32 bits. // Translated to Swift by referring to the following sources: // * https://github.com/jwerle/murmurhash.c // * https://en.wikipedia.org/wiki/MurmurHash public static func doHash32(key: UnsafePointer<UInt8>, maxBytes: Int, seed: UInt32 = 0) -> UInt32 { let c1: UInt32 = 0xcc9e2d51 let c2: UInt32 = 0x1b873593 let r1: UInt32 = 15 let r2: UInt32 = 13 let m: UInt32 = 5 let n: UInt32 = 0xe6546b64 var hash: UInt32 = seed var k: UInt32 = 0 let l = maxBytes / 4 // chunk length let chunks = UnsafeBufferPointer<UInt32>( start: UnsafePointer<UInt32>(key), count: l) let tail = UnsafeBufferPointer<UInt8>( start: UnsafePointer<UInt8>(key) + (l * 4), count: 4) for chunk in chunks { k = chunk &* c1 k = (k << r1) | (k >> (32 - r1)) k = k &* c2 hash ^= k hash = (hash << r2) | (hash >> (32 - r2)) hash = ((hash &* m) &+ n) } k = 0 // remainder switch maxBytes & 3 { // `len % 4' case 3: k ^= UInt32(tail[2]) << 16 fallthrough case 2: k ^= UInt32(tail[1]) << 8 fallthrough case 1: k ^= UInt32(tail[0]) k = k &* c1 k = (k << r1) | (k >> (32 - r1)) k = k &* c2 hash ^= k default: () // Ignore. } hash ^= UInt32(maxBytes) hash ^= hash >> 16 hash = hash &* 0x85ebca6b hash ^= hash >> 13 hash = hash &* 0xc2b2ae35 hash ^= hash >> 16 return hash } public static func hash32(key: String, seed: UInt32 = 0) -> UInt32 { var a = [UInt8](key.utf8) return doHash32(&a, maxBytes: a.count, seed: seed) } public static func hash32CChar(key: [CChar], maxBytes: Int, seed: UInt32 = 0) -> UInt32 { let ap = UnsafePointer<UInt8>(key) return doHash32(ap, maxBytes: maxBytes, seed: seed) } public static func hash32Bytes(key: [UInt8], maxBytes: Int, seed: UInt32 = 0) -> UInt32 { var a = key return doHash32(&a, maxBytes: maxBytes, seed: seed) } // MurmurHash3 128 bits. // Translated it to Swift using the following references: // * [qhash.c](https://github.com/wolkykim/qlibc/blob/8e5e6669fae0eb63e4fb171e7c84985b0828c720/src/utilities/qhash.c) // * [MurmurHash3.cpp](https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp) public static func doHash128(key: UnsafePointer<UInt8>, maxBytes: Int, seed: UInt64 = 0) -> (h1: UInt64, h2: UInt64) { let c1: UInt64 = 0x87c37b91114253d5 let c2: UInt64 = 0x4cf5ad432745937f let nblocks = maxBytes / 16 var h1 = seed var h2 = seed var k1: UInt64 = 0 var k2: UInt64 = 0 let blocks = UnsafeBufferPointer<UInt64>( start: UnsafePointer<UInt64>(key), count: nblocks) let tail = UnsafeBufferPointer<UInt8>( start: UnsafePointer<UInt8>(key) + (nblocks * 16), count: 16) for i in 0..<nblocks { k1 = blocks[(i * 2) + 0] k2 = blocks[(i * 2) + 1] k1 = k1 &* c1 k1 = (k1 << 31) | (k1 >> (64 - 31)) k1 = k1 &* c2 h1 ^= k1 h1 = (h1 << 27) | (h1 >> (64 - 27)) h1 = h1 &+ h2 h1 = (h1 &* 5) &+ 0x52dce729 k2 = k2 &* c2 k2 = (k2 << 33) | (k2 >> (64 - 33)) k2 = k2 &* c1 h2 ^= k2 h2 = (h2 << 31) | (h2 >> (64 - 31)) h2 = h2 &+ h1 h2 = (h2 &* 5) &+ 0x38495ab5 } k1 = 0 k2 = 0 // Remainder. switch maxBytes & 15 { // maxBytes % 15 case 15: k2 ^= UInt64(tail[14]) << 48 fallthrough case 14: k2 ^= UInt64(tail[13]) << 40 fallthrough case 13: k2 ^= UInt64(tail[12]) << 32 fallthrough case 12: k2 ^= UInt64(tail[11]) << 24 fallthrough case 11: k2 ^= UInt64(tail[10]) << 16 fallthrough case 10: k2 ^= UInt64(tail[9]) << 8 fallthrough case 9: k2 ^= UInt64(tail[8]) << 0 k2 = k2 &* c2 k2 = (k2 << 33) | (k2 >> (64 - 33)) k2 = k2 &* c1 h2 ^= k2 fallthrough case 8: k1 ^= UInt64(tail[7]) << 56 fallthrough case 7: k1 ^= UInt64(tail[6]) << 48 fallthrough case 6: k1 ^= UInt64(tail[5]) << 40 fallthrough case 5: k1 ^= UInt64(tail[4]) << 32 fallthrough case 4: k1 ^= UInt64(tail[3]) << 24 fallthrough case 3: k1 ^= UInt64(tail[2]) << 16 fallthrough case 2: k1 ^= UInt64(tail[1]) << 8 fallthrough case 1: k1 ^= UInt64(tail[0]) << 0 k1 = k1 &* c1 k1 = (k1 << 31) | (k1 >> (64 - 31)) k1 = k1 &* c2 h1 ^= k1 default: () // Ignore. } h1 ^= UInt64(maxBytes) h2 ^= UInt64(maxBytes) h1 = h1 &+ h2 h2 = h2 &+ h1 h1 ^= h1 >> 33 h1 = h1 &* 0xff51afd7ed558ccd h1 ^= h1 >> 33 h1 = h1 &* 0xc4ceb9fe1a85ec53 h1 ^= h1 >> 33 h2 ^= h2 >> 33 h2 = h2 &* 0xff51afd7ed558ccd h2 ^= h2 >> 33 h2 = h2 &* 0xc4ceb9fe1a85ec53 h2 ^= h2 >> 33 h1 = h1 &+ h2 h2 = h2 &+ h1 return (h1, h2) } public static func hash128(key: String, seed: UInt64 = 0) -> (h1: UInt64, h2: UInt64) { var a = [UInt8](key.utf8) return doHash128(&a, maxBytes: a.count, seed: seed) } public static func hash128CChar(key: [CChar], maxBytes: Int, seed: UInt64 = 0) -> (h1: UInt64, h2: UInt64) { let ap = UnsafePointer<UInt8>(key) return doHash128(ap, maxBytes: maxBytes, seed: seed) } public static func hash128Bytes(key: [UInt8], maxBytes: Int, seed: UInt64 = 0) -> (h1: UInt64, h2: UInt64) { var a = key return doHash128(&a, maxBytes: maxBytes, seed: seed) } }
apache-2.0
f789acf145c04a68d26a7e16ea5bbf88
24.986784
119
0.513138
3.036027
false
false
false
false
soapyigu/Swift30Projects
Project 28 - SceneDetector/SceneDetector/ViewController.swift
1
5026
/** * Copyright (c) 2017 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * 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 CoreML import Vision class ViewController: UIViewController { // MARK: - IBOutlets @IBOutlet weak var scene: UIImageView! @IBOutlet weak var answerLabel: UILabel! // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() guard let image = UIImage(named: "train_night") else { fatalError("no starting image") } scene.image = image } } // MARK: - IBActions extension ViewController { @IBAction func pickImage(_ sender: Any) { let pickerController = UIImagePickerController() pickerController.delegate = self pickerController.sourceType = .savedPhotosAlbum present(pickerController, animated: true) } } // MARK: - UIImagePickerControllerDelegate extension ViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) dismiss(animated: true) guard let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage else { fatalError("couldn't load image from Photos") } scene.image = image guard let ciImage = CIImage(image: image) else { fatalError("couldn't convert UIImage to CIImage") } detectScene(image: ciImage) } } // MARK: - UINavigationControllerDelegate extension ViewController: UINavigationControllerDelegate { } // MARK: - Private functions extension ViewController { func detectScene(image: CIImage) { answerLabel.text = "detecting scene..." // Load the ML model through its generated class guard let model = try? VNCoreMLModel(for: GoogLeNetPlaces().model) else { fatalError("can't load Places ML model") } // Define a Vision request service with the ML model let request = VNCoreMLRequest(model: model) { [weak self] request, error in guard let results = request.results, let topResult = results.first as? VNClassificationObservation else { fatalError("unexpected result type from VNCoreMLRequest") } // Update UI on main queue let article = (["a", "e", "i", "o", "u"].contains(topResult.identifier.first!)) ? "an" : "a" DispatchQueue.main.async { [weak self] in self?.answerLabel.text = "\(Int(topResult.confidence * 100))% it's \(article) \(topResult.identifier)" } } // Create a request handler with the image provided let handler = VNImageRequestHandler(ciImage: image) // Perform the request service with the request handler DispatchQueue.global(qos: .userInteractive).async { do { try handler.perform([request]) } catch { print(error) } } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue }
apache-2.0
653b162d32607d8007e2e43835c55aa9
35.42029
142
0.727019
4.754967
false
false
false
false
ricardopereira/Smartime
Smartime/MainViewController.swift
1
7792
// // MainViewController.swift // Smartime // // Created by Ricardo Pereira on 02/04/2015. // Copyright (c) 2015 Ricardo Pereira. All rights reserved. // import UIKit import QRCodeReader import Runes import ReactiveCocoa import Dodo import AudioToolbox class MainView: UIView { override func drawRect(rect: CGRect) { StyleKit.drawMain(frame: self.bounds) } } class MainViewController: SlidePageViewController { let sourceSignal: SignalProducer<[String:TicketViewModel], NoError> private let navigationOffset = CGFloat(50) private var setupDone = false @IBOutlet weak var qrCodeButton: UIButton! @IBOutlet weak var aboutButton: UIButton! @IBOutlet weak var ticketsButton: UIButton! init(slider: SliderController) { // Reactive signal sourceSignal = slider.ticketsCtrl.items.producer super.init(slider: slider, nibName: "MainViewController", bundle: nil) sourceSignal.start(next: { data in self.slider.nextPage() }) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() view.bounds.size = CGSize(width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) } override func viewDidLoad() { super.viewDidLoad() // Events qrCodeButton.addTarget(self, action: Selector("didTouchQRCode:"), forControlEvents: .TouchUpInside) aboutButton.addTarget(self, action: Selector("didTouchAbout:"), forControlEvents: .TouchUpInside) ticketsButton.addTarget(self, action: Selector("didTouchTickets:"), forControlEvents: .TouchUpInside) // Setup message bar view.dodo.topLayoutGuide = self.topLayoutGuide view.dodo.bottomLayoutGuide = self.bottomLayoutGuide observeSignals() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !setupDone { aboutButton.center.y = aboutButton.center.y + navigationOffset ticketsButton.center.y = ticketsButton.center.y + navigationOffset } } // MARK: Features func observeSignals() { slider.ticketsCtrl.signalTicketNumberCall.observe { ticket in let alertController = UIAlertController(title: "Senha \(ticket.current)", message: "\nChegou a sua vez!\n\n Desloque-se ao:\n Serviço - \(ticket.service)\n Balcão - \(ticket.desk)", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(okAction) AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) SoundPlayer().playSound("TicketCall.wav") self.showViewController(alertController, sender: nil) } slider.ticketsCtrl.signalError.observe { messageError in self.view.dodo.style.leftButton.icon = .Close self.view.dodo.style.leftButton.onTap = { self.view.dodo.hide() } self.view.dodo.error(messageError) } slider.ticketsCtrl.signalAdvertisement.observe { image in delay(3) { let adVC = AdViewController(ad: image) adVC.modalPresentationStyle = .OverCurrentContext adVC.modalTransitionStyle = .CrossDissolve self.showViewController(adVC, sender: nil) } } } func qrCodeResult(reader: QRCodeReaderViewController, data: String) { println(data) let stringToJsonData: String -> NSData? = { $0.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) } let dataToJsonObject: NSData -> AnyObject? = { var err: NSError? return NSJSONSerialization.JSONObjectWithData($0, options: .MutableLeaves, error: &err) } reader.dismissViewControllerAnimated(true, completion: { () -> Void in // Confirmation if let json = data >>- stringToJsonData >>- dataToJsonObject >>- { $0 as? NSDictionary } { println(json) self.showTicketDialog(json) } }) } func showTicketDialog(ticketDemand: NSDictionary) { let service = ticketDemand["service"] as? String ?? "" let terminalId = ticketDemand["terminalId"] as? String ?? "" if service.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" { return } let alertController = UIAlertController(title: "Senha", message: "Deseja tirar senha para o serviço \"\(service)\"?", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "Cancelar", style: .Cancel, handler: nil) alertController.addAction(cancelAction) let okAction = UIAlertAction(title: "OK", style: .Default) { (action) in // Send request let ticketRequirements = TicketRequirements(service: service, terminalId: terminalId, device: self.slider.ticketsCtrl.deviceToken) self.slider.ticketsCtrl.remote.requestTicket(ticketRequirements) } alertController.addAction(okAction) self.showViewController(alertController, sender: nil) } // MARK: Actions func didTouchQRCode(sender: AnyObject?) { #if (arch(i386) || arch(x86_64)) && os(iOS) // Simulator: test showTicketDialog(["service":"A"]) #else let reader = QRCodeReaderViewController() reader.resultCallback = qrCodeResult reader.cancelCallback = { $0.dismissViewControllerAnimated(true, completion: nil) } self.showViewController(reader, sender: nil) #endif } func didTouchAbout(sender: AnyObject?) { slider.prevPage() } func didTouchTickets(sender: AnyObject?) { slider.nextPage() } // MARK: Slider Page override func pageDidAppear() { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) setupDone = true } var oldOffset = CGFloat(0.0) override func pageDidScroll(position: CGFloat, offset: CGFloat) { let yOffset: CGFloat //println("Position:\(position) Offset:\(offset) Old:\(oldOffset)") // 0->1 -50 - Offset:1.0 Position:320.0 - Offset > Old // 1<-0 +50 - Offset:0.0 Position:0.0 - Offset < Old // 1->2 +50 - Offset:1.99 Position:639.5 - Offset > Old // 2->1 -50 - Offset:1.0 Position:320.0 - Offset < Old if offset > oldOffset && offset > 0 && offset <= 1 { // 0->1 yOffset = (oldOffset - offset) * navigationOffset } else if offset < oldOffset && offset > 0 && offset <= 1 { // 1<-0 yOffset = (oldOffset - offset) * navigationOffset } else if offset > oldOffset && offset > 1 && offset <= 2 { // 1->2 yOffset = (offset - oldOffset) * navigationOffset } else if offset < oldOffset && offset > 1 && offset <= 2 { // 2->1 yOffset = (offset - oldOffset) * navigationOffset } else { yOffset = 0 } aboutButton.center.y = aboutButton.center.y + yOffset ticketsButton.center.y = ticketsButton.center.y + yOffset oldOffset = offset } }
mit
acc259f53b3e24b31bd605ae593f2646
34.244344
217
0.604314
4.865084
false
false
false
false
nathankot/RxSwift
RxSwift/RxSwift/Observables/Implementations/CombineLatest.swift
3
3738
// // CombineLatest.swift // Rx // // Created by Krunoslav Zaher on 3/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation protocol CombineLatestProtocol : class { func next(index: Int) func fail(error: ErrorType) func done(index: Int) } class CombineLatestSink<O: ObserverType> : Sink<O>, CombineLatestProtocol { typealias Element = O.Element var lock = NSRecursiveLock() var hasValueAll: Bool var hasValue: [Bool] var isDone: [Bool] init(arity: Int, observer: O, cancel: Disposable) { self.hasValueAll = false self.hasValue = [Bool](count: arity, repeatedValue: false) self.isDone = [Bool](count: arity, repeatedValue: false) super.init(observer: observer, cancel: cancel) } func getResult() -> RxResult<Element> { return abstractMethod() } func performLocked(@noescape action: () -> Void) { return lock.calculateLocked(action) } func next(index: Int) { if !hasValueAll { hasValue[index] = true var hasValueAll = true for hasValue in self.hasValue { if !hasValue { hasValueAll = false; break; } } self.hasValueAll = hasValueAll; } if hasValueAll { _ = getResult().flatMap { res in trySendNext(observer, res) return SuccessResult }.recoverWith { e -> RxResult<Void> in trySendError(observer, e) self.dispose() return SuccessResult } } else { var allOthersDone = true var arity = self.isDone.count for var i = 0; i < arity; ++i { if i != index && !isDone[i] { allOthersDone = false break } } if allOthersDone { trySendCompleted(observer) self.dispose() } } } func fail(error: ErrorType) { trySendError(observer, error) dispose() } func done(index: Int) { isDone[index] = true var allDone = true for done in self.isDone { if !done { allDone = false break } } if allDone { trySendCompleted(observer) dispose() } } deinit { } } class CombineLatestObserver<ElementType> : ObserverType { typealias Element = ElementType typealias ValueSetter = (Element) -> Void let parent: CombineLatestProtocol let lock: NSRecursiveLock let index: Int let this: Disposable let setLatestValue: ValueSetter init(lock: NSRecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: ValueSetter, this: Disposable) { self.lock = lock self.parent = parent self.index = index self.this = this self.setLatestValue = setLatestValue } func on(event: Event<Element>) { lock.performLocked { switch event { case .Next(let boxedValue): let value = boxedValue.value setLatestValue(value) parent.next(index) case .Error(let error): this.dispose() parent.fail(error) case .Completed: this.dispose() parent.done(index) } } } }
mit
ba181673ebba20f3f0a730054b5e0b89
24.263514
123
0.505618
5.044534
false
true
false
false
AutomationStation/BouncerBuddy
BouncerBuddy(version1.0)/BouncerBuddy/RegisterViewController.swift
1
9160
// // RegisterViewController.swift // BouncerBuddy // // Created by Sha Wu on 16/3/2. // Copyright © 2016年 Sheryl Hong. All rights reserved. // import UIKit class RegisterViewController: UIViewController { @IBOutlet weak var userEmailtextfield: UITextField! @IBOutlet weak var usernameTextfield: UITextField! @IBOutlet weak var userPasswordTextfield: UITextField! @IBOutlet weak var reenterpassword: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func Registertapped(sender: AnyObject) { let userEmail = userEmailtextfield.text; let userName = usernameTextfield.text; let userPassword = userPasswordTextfield.text; let repeatPassword = reenterpassword.text; //Check empty fields& check if password match // Check for empty fields if(userEmail!.isEmpty || userPassword!.isEmpty || repeatPassword!.isEmpty) { // Display alert message displayMyAlertMessage("All fields are required"); return; } //Check if passwords match if(userPassword != repeatPassword) { // Display an alert message displayMyAlertMessage("Passwords do not match"); return; } //store data to mysql let post:NSString = "user_email=\(userEmail!)&user_name=\(userName!)&user_password=\(userPassword!)&c_password=\(repeatPassword)" NSLog("PostData: %@",post); let url:NSURL = NSURL(string: "https://cgi.soic.indiana.edu/~hong43/connect.php")! let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! let postLength:NSString = String( postData.length ) let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = postData request.setValue(postLength as String, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var reponseError: NSError? var response: NSURLResponse? var urlData: NSData? do { urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) } catch let error as NSError { reponseError = error urlData = nil } if ( urlData != nil ) { let res = response as! NSHTTPURLResponse!; NSLog("Response code: %ld", res.statusCode); if (res.statusCode >= 200 && res.statusCode < 300) { let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)! NSLog("Response ==> %@", responseData); var error: NSError? let jsonData:NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers )) as! NSDictionary let success:NSInteger = jsonData.valueForKey("success") as! NSInteger //[jsonData[@"success"] integerValue]; NSLog("Success: %ld", success); if(success == 1) { NSLog("Sign Up SUCCESS"); self.dismissViewControllerAnimated(true, completion: nil) } else { var error_msg:NSString if jsonData["error_message"] as? NSString != nil { error_msg = jsonData["error_message"] as! NSString } else { error_msg = "Unknown Error" } let alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = error_msg as String alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { let alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "Connection Failed" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { let alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = "Connection Failure" if let error = reponseError { alertView.message = (error.localizedDescription) } alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } /** let myUrl = NSURL(string: "https://cgi.soic.indiana.edu/~hong43/userRegister.php"); let request = NSMutableURLRequest(URL:myUrl!); request.HTTPMethod = "POST"; let postString = "email=\(userEmail!)&name=\(userName!)&password=\(userPassword!)"; request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding); NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in dispatch_async(dispatch_get_main_queue()) { //spinningActivity.hide(true) if error != nil { self.displayMyAlertMessage(error!.localizedDescription) return } do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary if let parseJSON = json { let resultValue = parseJSON["status"] as? String var isUserRegistered:Bool = false; if( resultValue == "Success"){ isUserRegistered = true; } var messageToDisplay:String = parseJSON["message"] as! String!; if(!isUserRegistered) { messageToDisplay = parseJSON["message"] as! String!; } let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in self.dismissViewControllerAnimated(true, completion: nil) } myAlert.addAction(okAction); self.presentViewController(myAlert, animated: true, completion: nil); } } catch{ print(error) } } }).resume() */ } // alert function func displayMyAlertMessage(userMessage:String) { let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.Alert); let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.Default, handler:nil); myAlert.addAction(okAction); self.presentViewController(myAlert, animated:true, completion:nil); } //back to sign in @IBAction func backtosignin(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
f78d8dbf05b713ee574e71e4b52a3982
35.7751
165
0.517091
6.297799
false
false
false
false
davidisaaclee/VectorSwift
Example/Tests/CustomVectors.swift
1
2298
// // CustomVectors.swift // VectorSwift // // Created by David Lee on 4/9/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import VectorSwift extension Float: Field { public static let additionIdentity: Float = 0 public static let multiplicationIdentity: Float = 1 public func toThePowerOf(_ exponent: Float) -> Float { return powf(self, exponent) } } public final class CustomVector2 { let x: Float let y: Float public init(x: Float, y: Float) { self.x = x self.y = y } public convenience init<T>(collection: T) where T: Collection, T.Iterator.Element == Float { var g = collection.makeIterator() guard let x = g.next(), let y = g.next() else { fatalError() } self.init(x: x, y: y) } } extension CustomVector2: Vector { public typealias Index = Int public static let additionIdentity: CustomVector2 = CustomVector2(collection: [0, 0]) public static let multiplicationIdentity: CustomVector2 = CustomVector2(collection: [1, 1]) public var numberOfDimensions: Int { return 2 } public subscript(index: Int) -> Float { switch index { case 0: return x case 1: return y default: fatalError() } } public func index(after i: Int) -> Int { return i + 1 } } extension CustomVector2: Equatable {} public struct CustomVector3 { let x: Float let y: Float let z: Float public init(x: Float, y: Float, z: Float) { self.x = x self.y = y self.z = z } public init<T: Collection>(collection: T) where T.Iterator.Element == Float { var it = collection.makeIterator() guard let x = it.next(), let y = it.next(), let z = it.next() else { fatalError() } self.init(x: x, y: y, z: z) } } extension CustomVector3: Vector { public typealias Index = Int public static let additionIdentity: CustomVector3 = CustomVector3(collection: [0, 0, 0]) public static let multiplicationIdentity: CustomVector3 = CustomVector3(collection: [1, 1, 1]) public var numberOfDimensions: Int { return 3 } public subscript(index: Int) -> Float { switch index { case 0: return self.x case 1: return self.y case 2: return self.z default: fatalError() } } public func index(after i: Int) -> Int { return i + 1 } } extension CustomVector3: Equatable {}
mit
ffec5501087683e3021b073089a5dc98
19.149123
95
0.670004
3.267425
false
false
false
false
FandyLiu/FDDemoCollection
Swift/Apply/Apply/ApplyOtherViewControllerTwo.swift
1
731
// // ApplyOtherViewControllerTwo.swift // Apply // // Created by 刘欢 on 2017/4/19. // Copyright © 2017年 fandy. All rights reserved. // import UIKit class ApplyOtherViewControllerTwo: ApplyBaseViewControllerTypeOne { override func viewDidLoad() { super.viewDidLoad() title = "帮人申请" // 设置 head 样式 let account = "13685475986" let name = "李瑞" headViewStyle = .custom(topImage: "2j", titles: ["申请人账号:" + account, "申请人姓名:" + name]) nextVC = ApplyOtherViewControllerThree() applyStepModel = ApplyModel.shareApplyModel.applyOtherModel.stepTwo } }
mit
e8f3a8ab94a284890f488c05e5c4b188
26.36
76
0.590643
4.071429
false
false
false
false
mpangburn/RayTracer
RayTracer/Models/Light.swift
1
1309
// // Light.swift // RayTracer // // Created by Michael Pangburn on 6/26/17. // Copyright © 2017 Michael Pangburn. All rights reserved. // import Foundation /// Represents a light emitted in 3D space. struct Light { /// The position of the light. var position: Point /// The color of the light. var color: Color /// Values representing possible light intensities. enum Intensity: Int { case low case medium case high var value: Double { return Double(self.rawValue + 1) / 2 } } /// The intensity of the light. var intensity: Intensity } // MARK: Light properties extension Light { /// The effective color of the light, factoring in intensity. var effectiveColor: Color { return color.withComponentsScaled(by: intensity.value) } } extension Light: Equatable { } func == (lhs: Light, rhs: Light) -> Bool { return lhs.position == rhs.position && lhs.color == rhs.color && lhs.intensity == rhs.intensity } extension Light: CustomStringConvertible, CustomDebugStringConvertible { var description: String { return "Light(position: \(self.position), color: \(self.color))" } var debugDescription: String { return self.description } }
mit
abfbd4d3ddec0e6d3076f86bb083fef3
19.4375
72
0.633028
4.316832
false
false
false
false
practicalswift/swift
test/SILOptimizer/definite_init_failable_initializers.swift
4
66032
// RUN: %target-swift-frontend -emit-sil -enable-sil-ownership %s | %FileCheck %s // High-level tests that DI handles early returns from failable and throwing // initializers properly. The main complication is conditional release of self // and stored properties. // FIXME: not all of the test cases have CHECKs. Hopefully the interesting cases // are fully covered, though. //// // Structs with failable initializers //// protocol Pachyderm { init() } class Canary : Pachyderm { required init() {} } // <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer struct TrivialFailableStruct { init?(blah: ()) { } init?(wibble: ()) { self.init(blah: wibble) } } struct FailableStruct { let x, y: Canary init(noFail: ()) { x = Canary() y = Canary() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC // CHECK: bb0(%0 : $@thin FailableStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[SELF]] init?(failBeforeInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV30failAfterPartialInitializationACSgyt_tcfC // CHECK: bb0(%0 : $@thin FailableStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: store [[CANARY]] to [[X_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[X_ADDR]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[SELF]] init?(failAfterPartialInitialization: ()) { x = Canary() return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV27failAfterFullInitializationACSgyt_tcfC // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY1:%.*]] = apply // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: store [[CANARY1]] to [[X_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct // CHECK: [[CANARY2:%.*]] = apply // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct // CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: store [[CANARY2]] to [[Y_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterFullInitialization: ()) { x = Canary() y = Canary() return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByAssignmentACSgyt_tcfC // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[CANARY]] = apply // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct // CHECK-NEXT: store [[CANARY]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[SELF_VALUE:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[SELF_VALUE]] init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableStruct(noFail: ()) return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByDelegationACSgyt_tcfC // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14FailableStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV20failDuringDelegationACSgyt_tcfC // CHECK: bb0 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK-NEXT: release_value [[SELF_OPTIONAL]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableStruct>) // // CHECK: [[SUCC_BB]]: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: retain_value [[SELF_VALUE]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableStruct>) // // CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableStruct>) // CHECK-NEXT: return [[NEW_SELF]] // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO init!(failDuringDelegation3: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation4: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation5: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableStruct { init?(failInExtension: ()) { self.init(failInExtension: failInExtension) } init?(assignInExtension: ()) { self = FailableStruct(noFail: ()) } } struct FailableAddrOnlyStruct<T : Pachyderm> { var x, y: T init(noFail: ()) { x = T() y = T() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failBeforeInitialization{{.*}}tcfC // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: inject_enum_addr %0 // CHECK: return init?(failBeforeInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterPartialInitialization{{.*}}tcfC // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: [[X_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: dealloc_stack [[X_BOX]] // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[X_ADDR]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: inject_enum_addr %0 // CHECK: return init?(failAfterPartialInitialization: ()) { x = T() return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterFullInitialization{{.*}}tcfC // CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T> // CHECK: [[X_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: dealloc_stack [[X_BOX]] // CHECK-NEXT: [[Y_BOX:%.*]] = alloc_stack $T // CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type // CHECK-NEXT: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1 // CHECK-NEXT: apply [[T_INIT_FN]]<T>([[Y_BOX]], [[T_TYPE]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]] // CHECK-NEXT: copy_addr [take] [[Y_BOX]] to [initialization] [[Y_ADDR]] // CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T> // CHECK-NEXT: dealloc_stack [[Y_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: inject_enum_addr %0 // CHECK: return init?(failAfterFullInitialization: ()) { x = T() y = T() return nil } init?(failAfterWholeObjectInitializationByAssignment: ()) { self = FailableAddrOnlyStruct(noFail: ()) return nil } init?(failAfterWholeObjectInitializationByDelegation: ()) { self.init(noFail: ()) return nil } // Optional to optional init?(failDuringDelegation: ()) { self.init(failBeforeInitialization: ()) } // IUO to optional init!(failDuringDelegation2: ()) { self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!' } // non-optional to optional init(failDuringDelegation3: ()) { self.init(failBeforeInitialization: ())! // necessary '!' } // non-optional to IUO init(failDuringDelegation4: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } } extension FailableAddrOnlyStruct { init?(failInExtension: ()) { self.init(failBeforeInitialization: failInExtension) } init?(assignInExtension: ()) { self = FailableAddrOnlyStruct(noFail: ()) } } //// // Structs with throwing initializers //// func unwrap(_ x: Int) throws -> Int { return x } struct ThrowStruct { var x: Canary init(fail: ()) throws { x = Canary() } init(noFail: ()) { x = Canary() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV28failBeforeOrDuringDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV29failBeforeOrDuringDelegation2ACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]]([[RESULT]], %1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringDelegation: Int) throws { try self.init(fail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV19failAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV27failDuringOrAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:.*]] : $ThrowStruct): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV27failBeforeOrAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV16throwsToOptionalACSgSi_tcfC // CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]]([[ARG1]], [[ARG2]]) : $@convention(method) (Int, @thin ThrowStruct.Type) -> (@owned ThrowStruct, @error Error), normal [[TRY_APPLY_SUCC_BB:bb[0-9]+]], error [[TRY_APPLY_FAIL_BB:bb[0-9]+]] // // CHECK: [[TRY_APPLY_SUCC_BB]]([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[NEW_SELF]] // CHECK-NEXT: br [[TRY_APPLY_CONT:bb[0-9]+]]([[SELF_OPTIONAL]] : $Optional<ThrowStruct>) // // CHECK: [[TRY_APPLY_CONT]]([[SELF_OPTIONAL:%.*]] : $Optional<ThrowStruct>): // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK: release_value [[SELF_OPTIONAL]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<ThrowStruct>) // // CHECK: [[SUCC_BB]]: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: retain_value [[SELF_VALUE]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<ThrowStruct>) // // CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<ThrowStruct>): // CHECK-NEXT: return [[NEW_SELF]] : $Optional<ThrowStruct> // // CHECK: [[TRY_APPLY_FAIL_BB]]([[ERROR]] : $Error): // CHECK-NEXT: strong_release [[ERROR:%.*]] : $Error // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt // CHECK-NEXT: br [[TRY_APPLY_CONT]]([[NEW_SELF]] : $Optional<ThrowStruct>) init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsToOptionalThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowStruct(noFail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV25failDuringSelfReplacementACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]]([[SELF_TYPE]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct): // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct // CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failDuringSelfReplacement: Int) throws { try self = ThrowStruct(fail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV24failAfterSelfReplacementACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct // CHECK: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[SELF_TYPE]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct // CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: retain_value [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterSelfReplacement: Int) throws { self = ThrowStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { try self = ThrowStruct(fail: ()) } } struct ThrowAddrOnlyStruct<T : Pachyderm> { var x : T init(fail: ()) throws { x = T() } init(noFail: ()) { x = T() } init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init(fail: ()) } init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } init(failDuringDelegation: Int) throws { try self.init(fail: ()) } init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } init(failDuringOrAfterDelegation: Int) throws { try self.init(fail: ()) try unwrap(failDuringOrAfterDelegation) } init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } init?(throwsToOptional: Int) { try? self.init(failDuringDelegation: throwsToOptional) } init(throwsToIUO: Int) { try! self.init(failDuringDelegation: throwsToIUO) } init?(throwsToOptionalThrows: Int) throws { try? self.init(fail: ()) } init(throwsOptionalToThrows: Int) throws { self.init(throwsToOptional: throwsOptionalToThrows)! } init?(throwsOptionalToOptional: Int) { try! self.init(throwsOptionalToThrows: throwsOptionalToOptional) } init(failBeforeSelfReplacement: Int) throws { try unwrap(failBeforeSelfReplacement) self = ThrowAddrOnlyStruct(noFail: ()) } init(failAfterSelfReplacement: Int) throws { self = ThrowAddrOnlyStruct(noFail: ()) try unwrap(failAfterSelfReplacement) } } extension ThrowAddrOnlyStruct { init(failInExtension: ()) throws { try self.init(fail: failInExtension) } init(assignInExtension: ()) throws { self = ThrowAddrOnlyStruct(noFail: ()) } } //// // Classes with failable initializers //// class FailableBaseClass { var member: Canary init(noFail: ()) { member = Canary() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc // CHECK: bb0(%0 : $FailableBaseClass): // CHECK: [[METATYPE:%.*]] = metatype $@thick FailableBaseClass.Type // CHECK: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]] // CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK: return [[RESULT]] init?(failBeforeFullInitialization: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC27failAfterFullInitializationACSgyt_tcfc // CHECK: bb0(%0 : $FailableBaseClass): // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary // CHECK-NEXT: store [[CANARY]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*Canary // CHECK-NEXT: strong_release %0 // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: return [[NEW_SELF]] init?(failAfterFullInitialization: ()) { member = Canary() return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC20failBeforeDelegationACSgyt_tcfC // CHECK: bb0(%0 : $@thick FailableBaseClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: return [[RESULT]] convenience init?(failBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfC // CHECK: bb0(%0 : $@thick FailableBaseClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: [[INIT_FN:%.*]] = class_method %0 // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: return [[RESULT]] convenience init?(failAfterDelegation: ()) { self.init(noFail: ()) return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfC // CHECK: bb0(%0 : $@thick FailableBaseClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass // CHECK: [[INIT_FN:%.*]] = class_method %0 // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK: release_value [[SELF_OPTIONAL]] // CHECK: br [[FAIL_TRAMPOLINE_BB:bb[0-9]+]] // // CHECK: [[SUCC_BB]]: // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: strong_retain [[SELF_VALUE]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableBaseClass>) // // CHECK: [[FAIL_TRAMPOLINE_BB]]: // CHECK: dealloc_stack [[SELF_BOX]] // CHECK: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt // CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableBaseClass>) // // CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableBaseClass>): // CHECK-NEXT: return [[NEW_SELF]] // Optional to optional convenience init?(failDuringDelegation: ()) { self.init(failBeforeFullInitialization: ()) } // IUO to optional convenience init!(failDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!' } // IUO to IUO convenience init!(noFailDuringDelegation: ()) { self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!' } // non-optional to optional convenience init(noFailDuringDelegation2: ()) { self.init(failBeforeFullInitialization: ())! // necessary '!' } } extension FailableBaseClass { convenience init?(failInExtension: ()) throws { self.init(failBeforeFullInitialization: failInExtension) } } // Chaining to failable initializers in a superclass class FailableDerivedClass : FailableBaseClass { var otherMember: Canary // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc // CHECK: bb0(%0 : $FailableDerivedClass): // CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick FailableDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref %0 : $FailableDerivedClass, [[METATYPE]] : $@thick FailableDerivedClass.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: return [[RESULT]] init?(derivedFailBeforeDelegation: ()) { return nil } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc // CHECK: bb0(%0 : $FailableDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK: [[CANARY:%.*]] = apply // CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary // CHECK-NEXT: store [[CANARY]] to [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*Canary // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0 // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc // CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]] // CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // // CHECK: [[FAIL_BB]]: // CHECK-NEXT: release_value [[SELF_OPTIONAL]] // CHECK: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt // CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableDerivedClass>) // // CHECK: [[SUCC_BB]]: // CHECK-NEXT: [[BASE_SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]] // CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_ref_cast [[BASE_SELF_VALUE]] // CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]] // CHECK-NEXT: strong_retain [[SELF_VALUE]] // CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt.1, [[SELF_VALUE]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableDerivedClass>) // // CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableDerivedClass>): // CHECK-NEXT: return [[NEW_SELF]] : $Optional<FailableDerivedClass> init?(derivedFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failBeforeFullInitialization: ()) } init?(derivedFailAfterDelegation: ()) { self.otherMember = Canary() super.init(noFail: ()) return nil } // non-optional to IUO init(derivedNoFailDuringDelegation: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // necessary '!' } // IUO to IUO init!(derivedFailDuringDelegation2: ()) { self.otherMember = Canary() super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!' } } extension FailableDerivedClass { convenience init?(derivedFailInExtension: ()) throws { self.init(derivedFailDuringDelegation: derivedFailInExtension) } } //// // Classes with throwing initializers //// class ThrowBaseClass { required init() throws {} init(noFail: ()) {} } class ThrowDerivedClass : ThrowBaseClass { // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfc // CHECK: bb0(%0 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %0 to [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0 // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc // CHECK-NEXT: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] required init() throws { try super.init() } override init(noFail: ()) { try! super.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitializationACSi_tKcfc // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1 // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] : $ThrowDerivedClass // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) super.init(noFail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK0ACSi_SitKcfc // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] : $*ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int) // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2 // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref %2 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) try super.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitializationACSi_tKcfc // CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: store %1 to [[SELF_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1 // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterFullInitialization: Int) throws { super.init(noFail: ()) try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitialization0h6DuringjK0ACSi_SitKcfc // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] // CHECK-NEXT: [[DERIVED_SELF:%.*]] = upcast %2 // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc // CHECK: try_apply [[INIT_FN]]([[DERIVED_SELF]]) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failAfterFullInitialization: Int, failDuringFullInitialization: Int) throws { try super.init() try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h5AfterjK0ACSi_SitKcfc // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %2 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[TWO:%.*]] = integer_literal $Builtin.Int2, -2 // CHECK-NEXT: store [[TWO]] to [[BITMAP_BOX]] // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2 // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[ONE]] to [[BITMAP_BOX]] // CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]]) // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%1) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2) : $Builtin.Int1 // CHECK-NEXT: cond_br [[COND]], bb6, bb10 // CHECK: bb6: // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[SHIFTED:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) : $Builtin.Int2 // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[SHIFTED]] : $Builtin.Int2) : $Builtin.Int1 // CHECK-NEXT: cond_br [[COND]], bb7, bb8 // CHECK: bb7: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb9 // CHECK: bb8: // CHECK-NEXT: br bb9 // CHECK: bb9: // CHECK-NEXT: br bb11 // CHECK: bb10: // CHECK-NEXT: [[BITMAP:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[BITMAP]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb11 // CHECK: bb11: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] : $Error init(failBeforeFullInitialization: Int, failAfterFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) super.init(noFail: ()) try unwrap(failAfterFullInitialization) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK00h5AfterjK0ACSi_S2itKcfc // CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $Int, %3 : $ThrowDerivedClass): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: store %3 to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %3 // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: store [[ONE]] to [[BITMAP_BOX]] // CHECK: try_apply [[INIT_FN]]([[BASE_SELF]]) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass): // CHECK-NEXT: [[NEG_ONE:%.*]] = integer_literal $Builtin.Int2, -1 // CHECK-NEXT: store [[NEG_ONE]] to [[BITMAP_BOX]] // CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%2) // CHECK: bb3([[RESULT:%.*]] : $Int): // CHECK-NEXT: strong_retain [[DERIVED_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[DERIVED_SELF]] // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb7([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb7([[ERROR]] : $Error) // CHECK: bb6([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb7([[ERROR]] : $Error) // CHECK: bb7([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb8, bb12 // CHECK: bb8: // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1 // CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) // CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2) // CHECK-NEXT: cond_br [[COND]], bb9, bb10 // CHECK: bb9: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb11 // CHECK: bb10: // CHECK-NEXT: br bb11 // CHECK: bb11: // CHECK-NEXT: br bb13 // CHECK: bb12: // CHECK-NEXT: [[SELF:%.*]] = load [[SELF_BOX]] // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type // CHECK-NEXT: dealloc_partial_ref [[SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type // CHECK-NEXT: br bb13 // CHECK: bb13: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int, failAfterFullInitialization: Int) throws { try unwrap(failBeforeFullInitialization) try super.init() try unwrap(failAfterFullInitialization) } convenience init(noFail2: ()) { try! self.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failBeforeDelegation: Int) throws { try unwrap(failBeforeDelegation) self.init(noFail: ()) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC20failDuringDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] : $Error convenience init(failDuringDelegation: Int) throws { try self.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeOrDuringDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR1:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR1]] : $Error) // CHECK: bb4([[ERROR2:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR2]] : $Error) // CHECK: bb5([[ERROR3:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failBeforeOrDuringDelegation: Int) throws { try unwrap(failBeforeOrDuringDelegation) try self.init() } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC29failBeforeOrDuringDelegation2ACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[ARG:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfC // CHECK-NEXT: try_apply [[INIT_FN]]([[ARG]], %1) // CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR1]] : $Error) // CHECK: bb4([[ERROR2:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR2]] : $Error) // CHECK: bb5([[ERROR3:%.*]] : $Error): // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failBeforeOrDuringDelegation2: Int) throws { try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2)) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC19failAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failAfterDelegation: Int) throws { self.init(noFail: ()) try unwrap(failAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failDuringOrAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfC // CHECK-NEXT: try_apply [[INIT_FN]](%1) // CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass): // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR1:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR1]] : $Error) // CHECK: bb4([[ERROR2:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR2]] : $Error) // CHECK: bb5([[ERROR3:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK: cond_br {{.*}}, bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR3]] convenience init(failDuringOrAfterDelegation: Int) throws { try self.init() try unwrap(failDuringOrAfterDelegation) } // CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failBeforeOrAfterDelegationACSi_tKcfC // CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type): // CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1 // CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass // CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0 // CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb1([[RESULT:%.*]] : $Int): // CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfC // CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1) // CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1 // CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]] // CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]] // CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF // CHECK-NEXT: try_apply [[UNWRAP_FN]](%0) // CHECK: bb2([[RESULT:%.*]] : $Int): // CHECK-NEXT: strong_retain [[NEW_SELF]] // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: return [[NEW_SELF]] // CHECK: bb3([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb4([[ERROR:%.*]] : $Error): // CHECK-NEXT: br bb5([[ERROR]] : $Error) // CHECK: bb5([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]] // CHECK: cond_br {{.*}}, bb6, bb7 // CHECK: bb6: // CHECK-NEXT: destroy_addr [[SELF_BOX]] // CHECK-NEXT: br bb8 // CHECK: bb7: // CHECK-NEXT: br bb8 // CHECK: bb8: // CHECK-NEXT: dealloc_stack [[SELF_BOX]] // CHECK-NEXT: dealloc_stack [[BITMAP_BOX]] // CHECK-NEXT: throw [[ERROR]] convenience init(failBeforeOrAfterDelegation: Int) throws { try unwrap(failBeforeOrAfterDelegation) self.init(noFail: ()) try unwrap(failBeforeOrAfterDelegation) } } //// // Enums with failable initializers //// enum FailableEnum { case A init?(a: Int64) { self = .A } init!(b: Int64) { self.init(a: b)! // unnecessary-but-correct '!' } init(c: Int64) { self.init(a: c)! // necessary '!' } init(d: Int64) { self.init(b: d)! // unnecessary-but-correct '!' } } //// // Protocols and protocol extensions //// // Delegating to failable initializers from a protocol extension to a // protocol. protocol P1 { init?(p1: Int64) } extension P1 { init!(p1a: Int64) { self.init(p1: p1a)! // unnecessary-but-correct '!' } init(p1b: Int64) { self.init(p1: p1b)! // necessary '!' } } protocol P2 : class { init?(p2: Int64) } extension P2 { init!(p2a: Int64) { self.init(p2: p2a)! // unnecessary-but-correct '!' } init(p2b: Int64) { self.init(p2: p2b)! // necessary '!' } } // Delegating to failable initializers from a protocol extension to a // protocol extension. extension P1 { init?(p1c: Int64) { self.init(p1: p1c) } init!(p1d: Int64) { self.init(p1c: p1d)! // unnecessary-but-correct '!' } init(p1e: Int64) { self.init(p1c: p1e)! // necessary '!' } } extension P2 { init?(p2c: Int64) { self.init(p2: p2c) } init!(p2d: Int64) { self.init(p2c: p2d)! // unnecessary-but-correct '!' } init(p2e: Int64) { self.init(p2c: p2e)! // necessary '!' } } //// // type(of: self) with uninitialized self //// func use(_ a : Any) {} class DynamicTypeBase { var x: Int init() { use(type(of: self)) x = 0 } convenience init(a : Int) { use(type(of: self)) self.init() } } class DynamicTypeDerived : DynamicTypeBase { override init() { use(type(of: self)) super.init() } convenience init(a : Int) { use(type(of: self)) self.init() } } struct DynamicTypeStruct { var x: Int init() { use(type(of: self)) x = 0 } init(a : Int) { use(type(of: self)) self.init() } }
apache-2.0
9b07e8e6055288c4887da885749bbe90
41.989583
227
0.622183
3.261967
false
false
false
false
jopamer/swift
stdlib/public/core/Join.swift
1
6220
//===--- Join.swift - Protocol and Algorithm for concatenation ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A sequence that presents the elements of a base sequence of sequences /// concatenated using a given separator. @_fixed_layout // FIXME(sil-serialize-all) public struct JoinedSequence<Base : Sequence> where Base.Element : Sequence { public typealias Element = Base.Element.Element @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base @usableFromInline // FIXME(sil-serialize-all) internal var _separator: ContiguousArray<Element> /// Creates an iterator that presents the elements of the sequences /// traversed by `base`, concatenated using `separator`. /// /// - Complexity: O(`separator.count`). @inlinable // FIXME(sil-serialize-all) public init<Separator : Sequence>(base: Base, separator: Separator) where Separator.Element == Element { self._base = base self._separator = ContiguousArray(separator) } } extension JoinedSequence { /// An iterator that presents the elements of the sequences traversed /// by a base iterator, concatenated using a given separator. @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator { @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base.Iterator @usableFromInline // FIXME(sil-serialize-all) internal var _inner: Base.Element.Iterator? @usableFromInline // FIXME(sil-serialize-all) internal var _separatorData: ContiguousArray<Element> @usableFromInline // FIXME(sil-serialize-all) internal var _separator: ContiguousArray<Element>.Iterator? @_frozen // FIXME(sil-serialize-all) @usableFromInline // FIXME(sil-serialize-all) internal enum JoinIteratorState { case start case generatingElements case generatingSeparator case end } @usableFromInline // FIXME(sil-serialize-all) internal var _state: JoinIteratorState = .start /// Creates a sequence that presents the elements of `base` sequences /// concatenated using `separator`. /// /// - Complexity: O(`separator.count`). @inlinable // FIXME(sil-serialize-all) public init<Separator: Sequence>(base: Base.Iterator, separator: Separator) where Separator.Element == Element { self._base = base self._separatorData = ContiguousArray(separator) } } } extension JoinedSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element.Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. @inlinable // FIXME(sil-serialize-all) public mutating func next() -> Element? { while true { switch _state { case .start: if let nextSubSequence = _base.next() { _inner = nextSubSequence.makeIterator() _state = .generatingElements } else { _state = .end return nil } case .generatingElements: let result = _inner!.next() if _fastPath(result != nil) { return result } _inner = _base.next()?.makeIterator() if _inner == nil { _state = .end return nil } if !_separatorData.isEmpty { _separator = _separatorData.makeIterator() _state = .generatingSeparator } case .generatingSeparator: let result = _separator!.next() if _fastPath(result != nil) { return result } _state = .generatingElements case .end: return nil } } } } extension JoinedSequence: Sequence { /// Return an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(base: _base.makeIterator(), separator: _separator) } @inlinable // FIXME(sil-serialize-all) public func _copyToContiguousArray() -> ContiguousArray<Element> { var result = ContiguousArray<Element>() let separatorSize: Int = numericCast(_separator.count) let reservation = _base._preprocessingPass { () -> Int in var r = 0 for chunk in _base { r += separatorSize + chunk.underestimatedCount } return r - separatorSize } if let n = reservation { result.reserveCapacity(numericCast(n)) } if separatorSize == 0 { for x in _base { result.append(contentsOf: x) } return result } var iter = _base.makeIterator() if let first = iter.next() { result.append(contentsOf: first) while let next = iter.next() { result.append(contentsOf: _separator) result.append(contentsOf: next) } } return result } } extension Sequence where Element : Sequence { /// Returns the concatenated elements of this sequence of sequences, /// inserting the given separator between each element. /// /// This example shows how an array of `[Int]` instances can be joined, using /// another `[Int]` instance as the separator: /// /// let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] /// let joined = nestedNumbers.joined(separator: [-1, -2]) /// print(Array(joined)) /// // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]" /// /// - Parameter separator: A sequence to insert between each of this /// sequence's elements. /// - Returns: The joined sequence of elements. @inlinable // FIXME(sil-serialize-all) public func joined<Separator : Sequence>( separator: Separator ) -> JoinedSequence<Self> where Separator.Element == Element.Element { return JoinedSequence(base: self, separator: separator) } }
apache-2.0
fb6ad7172b758659d458deb3a6936a24
31.227979
80
0.639871
4.436519
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionDomain/TransactionAPI/TransactionProcessor/TransactionEngine/FiatDepositTransactionEngine.swift
1
5951
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import MoneyKit import PlatformKit import RxSwift import ToolKit final class FiatDepositTransactionEngine: TransactionEngine { var fiatExchangeRatePairs: Observable<TransactionMoneyValuePairs> { .empty() } let currencyConversionService: CurrencyConversionServiceAPI let walletCurrencyService: FiatCurrencyServiceAPI let canTransactFiat: Bool = true var askForRefreshConfirmation: AskForRefreshConfirmation! var sourceAccount: BlockchainAccount! var transactionTarget: TransactionTarget! var sourceBankAccount: LinkedBankAccount! { sourceAccount as? LinkedBankAccount } var target: FiatAccount { transactionTarget as! FiatAccount } var targetAsset: FiatCurrency { target.fiatCurrency } var sourceAsset: FiatCurrency { sourceBankAccount.fiatCurrency } // MARK: - Private Properties private let paymentMethodsService: PaymentMethodTypesServiceAPI private let transactionLimitsService: TransactionLimitsServiceAPI private let bankTransferRepository: BankTransferRepositoryAPI // MARK: - Init init( walletCurrencyService: FiatCurrencyServiceAPI = resolve(), currencyConversionService: CurrencyConversionServiceAPI = resolve(), paymentMethodsService: PaymentMethodTypesServiceAPI = resolve(), transactionLimitsService: TransactionLimitsServiceAPI = resolve(), bankTransferRepository: BankTransferRepositoryAPI = resolve() ) { self.walletCurrencyService = walletCurrencyService self.currencyConversionService = currencyConversionService self.transactionLimitsService = transactionLimitsService self.paymentMethodsService = paymentMethodsService self.bankTransferRepository = bankTransferRepository } // MARK: - TransactionEngine func assertInputsValid() { precondition(sourceAccount is LinkedBankAccount) precondition(transactionTarget is FiatAccount) } func initializeTransaction() -> Single<PendingTransaction> { fetchBankTransferLimits(fiatCurrency: target.fiatCurrency) .map { [sourceAsset, target] paymentLimits -> PendingTransaction in PendingTransaction( amount: .zero(currency: sourceAsset), available: paymentLimits.maximum ?? .zero(currency: sourceAsset), feeAmount: .zero(currency: sourceAsset), feeForFullAvailable: .zero(currency: sourceAsset), feeSelection: .init(selectedLevel: .none, availableLevels: []), selectedFiatCurrency: target.fiatCurrency, limits: paymentLimits ) } } func doBuildConfirmations(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { .just(pendingTransaction .update( confirmations: [ TransactionConfirmations.Source(value: sourceAccount.label), TransactionConfirmations.Destination(value: target.label), TransactionConfirmations.FiatTransactionFee(fee: pendingTransaction.feeAmount), TransactionConfirmations.FundsArrivalDate.default, TransactionConfirmations.Total(total: pendingTransaction.amount) ] ) ) } func update(amount: MoneyValue, pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { .just(pendingTransaction.update(amount: amount)) } func doValidateAll(pendingTransaction: PendingTransaction) -> Single<PendingTransaction> { validateAmount(pendingTransaction: pendingTransaction) .updateTxValiditySingle(pendingTransaction: pendingTransaction) } func execute(pendingTransaction: PendingTransaction) -> Single<TransactionResult> { sourceAccount .receiveAddress .asSingle() .map(\.address) .flatMap(weak: self) { (self, identifier) -> Single<String> in self.bankTransferRepository .startBankTransfer( id: identifier, amount: pendingTransaction.amount ) .map(\.paymentId) .asObservable() .asSingle() } .map { TransactionResult.hashed(txHash: $0, amount: pendingTransaction.amount) } } func doUpdateFeeLevel( pendingTransaction: PendingTransaction, level: FeeLevel, customFeeAmount: MoneyValue ) -> Single<PendingTransaction> { .just(pendingTransaction) } // MARK: - Private Functions private func fetchBankTransferLimits(fiatCurrency: FiatCurrency) -> Single<TransactionLimits> { paymentMethodsService .eligiblePaymentMethods(for: fiatCurrency) .map { paymentMethodTypes -> PaymentMethodType? in paymentMethodTypes.first(where: { $0.isSuggested && $0.method == .bankAccount(fiatCurrency.currencyType) || $0.isSuggested && $0.method == .bankTransfer(fiatCurrency.currencyType) }) } .flatMap { [transactionLimitsService] paymentMethodType -> Single<TransactionLimits> in guard case .suggested(let paymentMethod) = paymentMethodType else { return .just(TransactionLimits.zero(for: fiatCurrency.currencyType)) } return transactionLimitsService.fetchLimits( for: paymentMethod, targetCurrency: fiatCurrency.currencyType, limitsCurrency: fiatCurrency.currencyType, product: .simplebuy ) .asSingle() } } }
lgpl-3.0
0b1fd7c6126207f7a9e4840d1fef75c1
38.932886
107
0.651092
6.127703
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureDashboard/Sources/FeatureDashboardUI/Components/SimpleBalanceCell/SimpleBalanceTableViewCell.swift
1
5322
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import PlatformUIKit import RxCocoa import RxSwift final class SimpleBalanceTableViewCell: UITableViewCell { /// Presenter should be injected var presenter: HistoricalBalanceCellPresenter? { willSet { disposeBag = DisposeBag() } didSet { guard let presenter = presenter else { assetBalanceView.presenter = nil badgeImageView.viewModel = nil assetTitleLabel.content = .empty return } assetBalanceView.presenter = presenter.balancePresenter presenter.thumbnail .drive(badgeImageView.rx.viewModel) .disposed(by: disposeBag) presenter.name .drive(assetTitleLabel.rx.content) .disposed(by: disposeBag) presenter.assetNetworkContent .compactMap { $0 } .drive(assetNetworkLabel.rx.content) .disposed(by: disposeBag) presenter.assetNetworkContent .map { $0 == nil } .drive(tagView.rx.isHidden) .disposed(by: disposeBag) presenter.displayCode .drive(assetCodeLabel.rx.content) .disposed(by: disposeBag) } } private var disposeBag = DisposeBag() // MARK: Private IBOutlets private var assetTitleLabel: UILabel = .init() private var assetCodeLabel: UILabel = .init() private var tagView = UIView() private var assetNetworkLabel: UILabel = .init() private var badgeImageView: BadgeImageView = .init() private var assetBalanceView: AssetBalanceView = .init() private var bottomSeparatorView: UIView = .init() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } // MARK: - Lifecycle @available(*, unavailable) required init?(coder: NSCoder) { nil } override func prepareForReuse() { super.prepareForReuse() presenter = nil } // MARK: - Private private func setup() { contentView.addSubview(badgeImageView) contentView.addSubview(assetBalanceView) contentView.addSubview(bottomSeparatorView) assetTitleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal) assetTitleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) assetTitleLabel.numberOfLines = 1 tagView.addSubview(assetNetworkLabel) tagView.isHidden = true tagView.layer.cornerRadius = 4 tagView.layer.borderColor = UIColor.gray2.cgColor tagView.layer.borderWidth = 1 assetNetworkLabel.layoutToSuperview(.centerX, .centerY) assetNetworkLabel.layoutToSuperview(.top, offset: 3) assetNetworkLabel.layoutToSuperview(.left, offset: Spacing.standard) assetNetworkLabel.layoutToSuperview(.right, offset: -Spacing.standard) assetNetworkLabel.layoutToSuperview(.bottom, offset: -3) let assetCodeAndBadgeContainer = UIStackView( arrangedSubviews: [assetCodeLabel, tagView] ) assetCodeAndBadgeContainer.axis = .horizontal assetCodeAndBadgeContainer.alignment = .center assetCodeAndBadgeContainer.spacing = Spacing.standard let assetStackView = UIStackView( arrangedSubviews: [assetTitleLabel, assetCodeAndBadgeContainer] ) assetStackView.spacing = Spacing.interItem assetStackView.axis = .vertical assetStackView.alignment = .top contentView.addSubview(assetStackView) assetStackView.layoutToSuperview(.centerY) assetStackView.layoutToSuperview(.top, relation: .greaterThanOrEqual, offset: Spacing.inner) assetStackView.layout(edge: .leading, to: .trailing, of: badgeImageView, offset: Spacing.inner) assetStackView.layoutToSuperview(.bottom, relation: .lessThanOrEqual, offset: Spacing.inner) assetStackView.layout(edge: .trailing, to: .leading, of: assetBalanceView, offset: -Spacing.inner) badgeImageView.layout(dimension: .height, to: 32) badgeImageView.layout(dimension: .width, to: 32) badgeImageView.layoutToSuperview(.centerY) badgeImageView.layoutToSuperview(.leading, offset: Spacing.inner) assetBalanceView.layout(to: .top, of: assetStackView) assetBalanceView.layoutToSuperview(.centerY) assetBalanceView.layoutToSuperview(.trailing, offset: -Spacing.inner) assetBalanceView.layoutToSuperview(.bottom, relation: .lessThanOrEqual, offset: Spacing.inner) bottomSeparatorView.layout(dimension: .height, to: 1) bottomSeparatorView.layoutToSuperview(.trailing, priority: .defaultHigh) bottomSeparatorView.layoutToSuperview(.bottom, priority: .defaultHigh) bottomSeparatorView.layoutToSuperview(.width, relation: .equal, ratio: 0.82) bottomSeparatorView.backgroundColor = .lightBorder assetBalanceView.shimmer( estimatedFiatLabelSize: CGSize(width: 90, height: 16), estimatedCryptoLabelSize: CGSize(width: 100, height: 14) ) } }
lgpl-3.0
19daee7e8a5a23e99a5fc9b5a6fcb410
38.125
106
0.674121
5.019811
false
false
false
false
machelix/KYCircularProgress
Source/KYCircularProgress.swift
1
9295
// KYCircularProgress.swift // // Copyright (c) 2014-2015 Kengo Yokoyama. // // 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 // MARK: - KYCircularProgress public class KYCircularProgress: UIView { /** Typealias of progressChangedClosure. */ public typealias progressChangedHandler = (progress: Double, circularView: KYCircularProgress) -> Void /** This closure is called when set value to `progress` property. */ private var progressChangedClosure: progressChangedHandler? /** Main progress view. */ private var progressView: KYCircularShapeView! /** Gradient mask layer of `progressView`. */ private var gradientLayer: CAGradientLayer! /** Guide view of `progressView`. */ private var progressGuideView: KYCircularShapeView? /** Mask layer of `progressGuideView`. */ private var guideLayer: CALayer? /** Current progress value. (0.0 - 1.0) */ @IBInspectable public var progress: Double = 0.0 { didSet { let clipProgress = max( min(progress, Double(1.0)), Double(0.0) ) progressView.updateProgress(clipProgress) progressChangedClosure?(progress: clipProgress, circularView: self) } } /** Progress start angle. */ public var startAngle: Double = 0.0 { didSet { progressView.startAngle = startAngle progressGuideView?.startAngle = startAngle } } /** Progress end angle. */ public var endAngle: Double = 0.0 { didSet { progressView.endAngle = endAngle progressGuideView?.endAngle = endAngle } } /** Main progress line width. */ @IBInspectable public var lineWidth: Double = 8.0 { didSet { progressView.shapeLayer().lineWidth = CGFloat(lineWidth) } } /** Guide progress line width. */ @IBInspectable public var guideLineWidth: Double = 8.0 { didSet { progressGuideView?.shapeLayer().lineWidth = CGFloat(guideLineWidth) } } /** Progress bar path. You can create various type of progress bar. */ public var path: UIBezierPath? { didSet { progressView.shapeLayer().path = path?.CGPath progressGuideView?.shapeLayer().path = path?.CGPath } } /** Progress bar colors. You can set many colors in `colors` property, and it makes gradation color in `colors`. */ public var colors: [UIColor]? { didSet { updateColors(colors) } } /** Progress guide bar color. */ @IBInspectable public var progressGuideColor: UIColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 0.2) { didSet { guideLayer?.backgroundColor = progressGuideColor.CGColor } } /** Switch of progress guide view. If you set to `true`, progress guide view is enabled. */ @IBInspectable public var showProgressGuide: Bool = false { didSet { setNeedsLayout() layoutIfNeeded() configureProgressGuideLayer(showProgressGuide) } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureProgressLayer() } public override init(frame: CGRect) { super.init(frame: frame) configureProgressLayer() } /** Create `KYCircularProgress` with progress guide. - parameter frame: `KYCircularProgress` frame. - parameter showProgressGuide: If you set to `true`, progress guide view is enabled. */ public init(frame: CGRect, showProgressGuide: Bool) { super.init(frame: frame) configureProgressLayer() self.showProgressGuide = showProgressGuide } /** This closure is called when set value to `progress` property. - parameter completion: progress changed closure. */ public func progressChangedClosure(completion: progressChangedHandler) { progressChangedClosure = completion } private func configureProgressLayer() { progressView = KYCircularShapeView(frame: bounds) progressView.shapeLayer().fillColor = UIColor.clearColor().CGColor progressView.shapeLayer().path = path?.CGPath progressView.shapeLayer().lineWidth = CGFloat(lineWidth) progressView.shapeLayer().strokeColor = tintColor.CGColor gradientLayer = CAGradientLayer(layer: layer) gradientLayer.frame = progressView.frame gradientLayer.startPoint = CGPointMake(0, 0.5) gradientLayer.endPoint = CGPointMake(1, 0.5) gradientLayer.mask = progressView.shapeLayer() gradientLayer.colors = colors ?? [UIColor(rgba: 0x9ACDE755).CGColor, UIColor(rgba: 0xE7A5C955).CGColor] layer.addSublayer(gradientLayer) } private func configureProgressGuideLayer(showProgressGuide: Bool) { if showProgressGuide && progressGuideView == nil { progressGuideView = KYCircularShapeView(frame: bounds) progressGuideView!.shapeLayer().fillColor = UIColor.clearColor().CGColor progressGuideView!.shapeLayer().path = progressView.shapeLayer().path progressGuideView!.shapeLayer().lineWidth = CGFloat(guideLineWidth) progressGuideView!.shapeLayer().strokeColor = tintColor.CGColor guideLayer = CAGradientLayer(layer: layer) guideLayer!.frame = progressGuideView!.frame guideLayer!.mask = progressGuideView!.shapeLayer() guideLayer!.backgroundColor = progressGuideColor.CGColor guideLayer!.zPosition = -1 progressGuideView!.updateProgress(1.0) layer.addSublayer(guideLayer!) } } private func updateColors(colors: [UIColor]?) { var convertedColors: [CGColorRef] = [] if let colors = colors { for color in colors { convertedColors.append(color.CGColor) } if convertedColors.count == 1 { convertedColors.append(convertedColors.first!) } } else { convertedColors = [UIColor(rgba: 0x9ACDE7FF).CGColor, UIColor(rgba: 0xE7A5C9FF).CGColor] } gradientLayer.colors = convertedColors } } // MARK: - KYCircularShapeView class KYCircularShapeView: UIView { var startAngle = 0.0 var endAngle = 0.0 override class func layerClass() -> AnyClass { return CAShapeLayer.self } private func shapeLayer() -> CAShapeLayer { return layer as! CAShapeLayer } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) updateProgress(0) } override func layoutSubviews() { super.layoutSubviews() if startAngle == endAngle { endAngle = startAngle + (M_PI * 2) } shapeLayer().path = shapeLayer().path ?? layoutPath().CGPath } private func layoutPath() -> UIBezierPath { let halfWidth = CGFloat(CGRectGetWidth(frame) / 2.0) return UIBezierPath(arcCenter: CGPointMake(halfWidth, halfWidth), radius: halfWidth - shapeLayer().lineWidth, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true) } private func updateProgress(progress: Double) { CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) shapeLayer().strokeEnd = CGFloat(progress) CATransaction.commit() } } // MARK: - UIColor Extension extension UIColor { convenience public init(rgba: Int64) { let red = CGFloat((rgba & 0xFF000000) >> 24) / 255.0 let green = CGFloat((rgba & 0x00FF0000) >> 16) / 255.0 let blue = CGFloat((rgba & 0x0000FF00) >> 8) / 255.0 let alpha = CGFloat( rgba & 0x000000FF) / 255.0 self.init(red: red, green: green, blue: blue, alpha: alpha) } }
mit
26270ade986302ca44cbfd1cb2750c26
31.614035
196
0.63432
4.861402
false
false
false
false
bardonadam/SlidingTabBar
Example/SlidingTabBar/ViewController.swift
1
2319
// // ViewController.swift // SlidingTabBar // // Created by Adam Bardon on 03/03/2016. // Copyright (c) 2016 Adam Bardon. All rights reserved. // import UIKit import SlidingTabBar class ViewController: UITabBarController, SlidingTabBarDataSource, SlidingTabBarDelegate, UITabBarControllerDelegate { var tabBarView: SlidingTabBar! var fromIndex: Int! var toIndex: Int! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tabBar.hidden = true let tabBarFrame = self.tabBar.frame self.selectedIndex = 1 tabBarView = SlidingTabBar(frame: tabBarFrame, initialTabBarItemIndex: 1) tabBarView.tabBarBackgroundColor = UIColor(rgba: "#39434E") tabBarView.tabBarItemTintColor = UIColor(rgba: "#6F8595") tabBarView.selectedTabBarItemTintColor = UIColor(rgba: "#FDFCFA") tabBarView.selectedTabBarItemColors = [UIColor(rgba: "#D93434"), UIColor(rgba: "#81DB34"), UIColor(rgba: "#25BCEE"), UIColor(rgba: "#F8C60D"), UIColor(rgba: "#F59618")] tabBarView.slideAnimationDuration = 0.6 tabBarView.datasource = self tabBarView.delegate = self tabBarView.setup() // UITabBarControllerDelegate, for animationControllerForTransitionFromViewController self.delegate = self self.view.addSubview(tabBarView) } // MARK: - SlidingTabBarDataSource func tabBarItemsInSlidingTabBar(tabBarView: SlidingTabBar) -> [UITabBarItem] { return tabBar.items! } // MARK: - SlidingTabBarDelegate func didSelectViewController(tabBarView: SlidingTabBar, atIndex index: Int, from: Int) { self.fromIndex = from self.toIndex = index self.selectedIndex = index } // MARK: - UITabBarControllerDelegate func tabBarController(tabBarController: UITabBarController, animationControllerForTransitionFromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SlidingTabAnimatedTransitioning(transitionDuration: 0.6, direction: .Reverse, fromIndex: self.fromIndex, toIndex: self.toIndex) } }
mit
f37ce0d83033c3cf28ef631324dd79e4
34.676923
225
0.684778
5.096703
false
false
false
false
nirmankarta/eddystone
tools/gatt-config/ios/Beaconfig/Beaconfig/SlotDataContentView.swift
2
64111
// Copyright 2016 Google Inc. All rights reserved. // // 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 Foundation let kLeadingConstraint: CGFloat = 8 let kSlotDataMarginConstraint: CGFloat = 8 let kLabelWidth: CGFloat = 250 let kLabelHeight: CGFloat = 20 let kPickerViewHeight: CGFloat = 100 let kTextViewHeight: CGFloat = 25 let kTextFieldHeight: CGFloat = 30 let kSliderHeight: CGFloat = 25 let kLightGrayColor = UIColor(red:0.96, green:0.96, blue:0.96, alpha:1.0) let kGreenColor = UIColor(hue: kNavBarTintColourHue, saturation: kNavBarTintSaturation, brightness: kNavBarTintBrightness, alpha: kNavBarTintAlpha) let kHolderViewBorderWidth: CGFloat = 0.3 let kURLTextViewWidth: CGFloat = 55 let kUIDNamespaceTextViewWidth: CGFloat = 125 let kUIDInstanceTextViewWidth: CGFloat = 62 let kUIDInstanceLength = 12 let kUIDNamespaceLength = 20 let kPassCodeLength = 32 class SlotDataContentView: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate, GIDSignInUIDelegate { var didChangeSlotData = false var frameTypePickerView: UIPickerView = UIPickerView() let slotContentScrollView = UIScrollView() let slotContentView = UIView() var txPowerSlider: UISlider? var txPowerTextView: UITextView? var advIntervalSlider: UISlider? var advIntervalTextView: UITextView? var slotDataURL: UITextField? var namespaceTextView: UITextField? var instanceTextView: UITextField? var slotData: Dictionary <String, NSData> = [:] var broadcastCapabilities: NSDictionary = [:] var currentSlotUpdateData: Dictionary <String, NSData> = [:] var lockCodeBottomConstraints: NSLayoutConstraint? var lockButtonBottomConstraints: NSLayoutConstraint? var changeLockCodeButton: UIButton? var factoryResetButton: UIButton? var changeLockCodeView: UIView? var factoryResetView: UIView? var globalHolder: UIView? var oldLockCode: UITextField? var newLockCode: UITextField? var changeLockCodeCallback: ((oldCode: String, newCode: String) -> Void)? var factoryResetCallback: (() -> Void)? var remainConnectableCallback: ((on: Bool) -> Void)? var remainConnectableSwitch: UISwitch? var instanceText: UITextView! var namespaceText: UITextView! var oldCodeCharactersCounter: UITextView! var newCodeCharactersCounter: UITextView! var frameTypeChange: FrameTypeChange = .NotSet var signInHolder: UIView! var selectHolder: UIView! var signInWithGoogleCallback: ((viewToDisable: UIView, selectViewHolder: UIView) -> Void)? var showAlert: ((title: String, description: String, buttonText: String) -> Void)? let frameTypes: NSMutableArray = [BeaconInfo.EddystoneFrameType.UIDFrameType.description, BeaconInfo.EddystoneFrameType.URLFrameType.description, BeaconInfo.EddystoneFrameType.TelemetryFrameType.description, BeaconInfo.EddystoneFrameType.EIDFrameType.description, BeaconInfo.EddystoneFrameType.NotSetFrameType.description] enum FrameTypeChange: NSNumber { case UID = 0 case URL = 1 case TLM = 2 case EID = 3 case NotSet = 4 } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if string.characters.count == 0 { return true } let currentText = textField.text ?? "" let text = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string) let currentCharacterCount = textField.text?.characters.count ?? 0 if (range.length + range.location > currentCharacterCount){ return false } let newLength = currentCharacterCount + string.characters.count - range.length var hasRightLength: Bool = false if textField == instanceTextView { if newLength <= kUIDInstanceLength { hasRightLength = true } } else if textField == namespaceTextView { if newLength <= kUIDNamespaceLength { hasRightLength = true } } else if textField == oldLockCode || textField == newLockCode { if newLength <= kPassCodeLength { hasRightLength = true } } return StringUtils.inHexadecimalString(text) && hasRightLength } func textFieldDidChange(textField : UITextField){ if let length = textField.text?.characters.count { if textField == instanceTextView { instanceText.text = "Instance (\(length)/\(kUIDInstanceLength)):" } else if textField == namespaceTextView { namespaceText.text = "Namespace (\(length)/\(kUIDNamespaceLength)):" } else if textField == oldLockCode { oldCodeCharactersCounter.text = "\(length)/\(kPassCodeLength)" } else if textField == newLockCode { newCodeCharactersCounter.text = "\(length)/\(kPassCodeLength)" } } } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return false } func setUICallbacks(changeLockCodeCallback: (oldCode: String, newCode: String) -> Void, factoryResetCallback: () -> Void, remainConnectableCallback: (on: Bool) -> Void, showAlert: (title: String, description: String, buttonText: String) -> Void, signIn: (viewToDisable: UIView, selectViewHolder: UIView) -> Void) { self.changeLockCodeCallback = changeLockCodeCallback self.factoryResetCallback = factoryResetCallback self.remainConnectableCallback = remainConnectableCallback self.showAlert = showAlert self.signInWithGoogleCallback = signIn } override func viewDidLoad() { super.viewDidLoad() frameTypePickerView.dataSource = self frameTypePickerView.delegate = self } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return frameTypes.count } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { for subview in slotContentView.subviews { subview.removeFromSuperview() } switch row { case FrameTypeChange.UID.rawValue: frameTypeChange = .UID; setAsUIDTypeContentView(slotData, capabilities: broadcastCapabilities) case FrameTypeChange.URL.rawValue: frameTypeChange = .URL; setAsURLTypeContentView(slotData, capabilities: broadcastCapabilities) case FrameTypeChange.TLM.rawValue: frameTypeChange = .TLM; setAsTLMTypeContentView(slotData, capabilities: broadcastCapabilities) // Not sure what to do with the EID frame for now, so setting // the EID would mean setting no frame case FrameTypeChange.EID.rawValue: frameTypeChange = .EID; setAsEIDTypeContentView(slotData, capabilities: broadcastCapabilities) case FrameTypeChange.NotSet.rawValue: frameTypeChange = .NotSet; setAsNoFrameTypeContentView(broadcastCapabilities) default: break } } func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { let pickerLabel = UILabel() pickerLabel.textColor = UIColor.blackColor() pickerLabel.text = frameTypes[row] as? String pickerLabel.font = UIFont(name: "Arial-BoldMT", size: 15) pickerLabel.textAlignment = NSTextAlignment.Center return pickerLabel } func createContentView() { slotContentScrollView.frame = view.bounds slotContentView.backgroundColor = kLightGrayColor slotContentView.frame.origin = CGPointMake(0,0) /// TODO: set slotContentView height to fit the content inside it slotContentView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height + 100) slotContentScrollView.addSubview(slotContentView) slotContentScrollView.contentSize = slotContentView.bounds.size } /// Creates a label with a specific text and sets its constraints func createLabelWithText(text: String, view: UIView) -> UILabel { let textLabel = UILabel() textLabel.text = text textLabel.textColor = kGreenColor textLabel.font = UIFont.systemFontOfSize(19, weight: UIFontWeightSemibold) view.addSubview(textLabel) CustomViews.setConstraints(textLabel, holderView: view, topView: view, leftView: nil, rightView: nil, height: kLabelHeight, width: kLabelWidth, pinTopAttribute: .Top, setBottomConstraints: false, marginConstraint: kSlotDataMarginConstraint) return textLabel } func createControlButton(text: String, holderView: UIView, topElement: UIView, setBottomConstraints: Bool, rightView: UIView?) -> UIButton { let button = UIButton() holderView.addSubview(button) CustomViews.setConstraints(button, holderView: holderView, topView: topElement, leftView: nil, rightView: rightView, height: 20, width: 80, pinTopAttribute: .Bottom, setBottomConstraints: setBottomConstraints, marginConstraint: kSlotDataMarginConstraint) button.setTitle(text, forState: UIControlState.Normal) button.setTitleColor(kGreenColor, forState: UIControlState.Normal) button.titleLabel!.font = UIFont.systemFontOfSize(14, weight: UIFontWeightSemibold) button.titleLabel?.textAlignment = .Left button.titleLabel!.font = UIFont(name: "Arial-BoldMT", size: 14) button.titleLabel?.textAlignment = .Right return button } func createButtonWithText(text: String, holderView: UIView, topElement: UIView, setBottomConstraints: Bool) -> UIButton { let button = UIButton() holderView.addSubview(button) CustomViews.setConstraints(button, holderView: holderView, topView: topElement, leftView: nil, rightView: nil, height: 25, width: nil, pinTopAttribute: .Bottom, setBottomConstraints: setBottomConstraints, marginConstraint: kSlotDataMarginConstraint) button.setTitle(text, forState: UIControlState.Normal) button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) button.titleLabel!.font = UIFont.systemFontOfSize(15, weight: UIFontWeightRegular) button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left button.titleLabel?.font = UIFont(name: "Arial", size: kTextFontSize) button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: -5, right: 0) return button } func createTextField(placeholder: String, holderView: UIView, topView: UIView, leftView: UIView?, topAttribute: NSLayoutAttribute) -> UITextField { let textField = UITextField() holderView.addSubview(textField) textField.attributedPlaceholder = NSAttributedString(string:placeholder, attributes:[NSForegroundColorAttributeName: UIColor.grayColor()]) CustomViews.setConstraints(textField, holderView: holderView, topView: topView, leftView: leftView, rightView: nil, height: kTextFieldHeight, width: nil, pinTopAttribute: topAttribute, setBottomConstraints: false, marginConstraint: kSlotDataMarginConstraint) textField.layer.backgroundColor = UIColor.whiteColor().CGColor textField.layer.borderColor = UIColor.grayColor().CGColor textField.layer.borderWidth = 0.0 textField.layer.masksToBounds = false CustomViews.addShadow(textField) textField.font = UIFont(name: "Menlo-Regular", size: kTextFieldFontSize) textField.autocapitalizationType = .None textField.layer.sublayerTransform = CATransform3DMakeTranslation(3, 0, 0) return textField } func createChangeLockCodeView() { changeLockCodeView = UIView() changeLockCodeView?.backgroundColor = kLightGrayColor globalHolder?.addSubview(changeLockCodeView!) CustomViews.setConstraints(changeLockCodeView!, holderView: globalHolder!, topView: changeLockCodeButton!, leftView: nil, rightView: nil, height: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraints: false, marginConstraint: kSlotDataMarginConstraint) } func createFactoryResetView() { factoryResetView = UIView() factoryResetView?.backgroundColor = kLightGrayColor globalHolder?.addSubview(factoryResetView!) CustomViews.setConstraints(factoryResetView!, holderView: globalHolder!, topView: factoryResetButton!, leftView: nil, rightView: nil, height: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraints: false, marginConstraint: kSlotDataMarginConstraint) } func showChangeLockCodeView() { oldCodeCharactersCounter = createTextView("0/\(kPassCodeLength)", holderView: changeLockCodeView!, topView: changeLockCodeView!, leftView: nil, rightView: nil, width: kFrameTitleWidth, pinTopAttribute: .Top, setBottomConstraint: false) oldCodeCharactersCounter.backgroundColor = kLightGrayColor oldLockCode = createTextField("Insert old lock code", holderView: changeLockCodeView!, topView: changeLockCodeView!, leftView: oldCodeCharactersCounter, topAttribute: .Top) oldLockCode?.delegate = self oldLockCode?.addTarget(self, action: #selector(textFieldDidChange), forControlEvents: .EditingChanged) newCodeCharactersCounter = createTextView("0/\(kPassCodeLength)", holderView: changeLockCodeView!, topView: oldCodeCharactersCounter!, leftView: nil, rightView: nil, width: kFrameTitleWidth, pinTopAttribute: .Bottom, setBottomConstraint: false) newLockCode = createTextField("Insert new lock code", holderView: changeLockCodeView!, topView: oldLockCode!, leftView: newCodeCharactersCounter, topAttribute: .Bottom) newLockCode?.delegate = self newLockCode?.addTarget(self, action: #selector(textFieldDidChange), forControlEvents: .EditingChanged) newCodeCharactersCounter.backgroundColor = kLightGrayColor let saveButton = createControlButton("SAVE", holderView: changeLockCodeView!, topElement: newLockCode!, setBottomConstraints: true, rightView: changeLockCodeView) let cancelButton = createControlButton("CANCEL", holderView: changeLockCodeView!, topElement: newLockCode!, setBottomConstraints: true, rightView: saveButton) cancelButton.addTarget(self, action: #selector(cancelButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) saveButton.addTarget(self, action: #selector(saveLockCodeButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) } func showFactoryResetView() { let warningTextView = createTextView("Are you sure you want to factory reset all the data?", holderView: factoryResetView!, topView: factoryResetView!, leftView: nil, rightView: nil, width: nil, pinTopAttribute: .Top, setBottomConstraint: false) warningTextView.backgroundColor = kLightGrayColor let resetButton = createControlButton("RESET", holderView: factoryResetView!, topElement: warningTextView, setBottomConstraints: true, rightView: factoryResetView) let cancelButton = createControlButton("CANCEL", holderView: factoryResetView!, topElement: warningTextView, setBottomConstraints: true, rightView: resetButton) cancelButton.addTarget(self, action: #selector(cancelFactoryResetButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) resetButton.addTarget(self, action: #selector(performFactoryReset), forControlEvents: UIControlEvents.TouchUpInside) } func saveLockCodeButtonPressed() { if let callback = changeLockCodeCallback, oldCode = oldLockCode?.text, newCode = newLockCode?.text { if oldCode.characters.count != kPassCodeLength { if let alert = showAlert { alert(title: "Old Passkey", description: "The old passkey does not have the right number of characters.", buttonText: "Dismiss") } return } if newCode.characters.count != kPassCodeLength { if let alert = showAlert { alert(title: "New Passkey", description: "The new passkey does not have the right number of characters.", buttonText: "Dismiss") } return } callback(oldCode: oldCode, newCode: newCode) } } func lockCodeChanged() { for subview in changeLockCodeView!.subviews { subview.removeFromSuperview() } let textView = createTextView("Lock code has been successfully changed!", holderView: changeLockCodeView!, topView: changeLockCodeView!, leftView: nil, rightView: nil, width: nil, pinTopAttribute: .Top, setBottomConstraint: true) textView.backgroundColor = kLightGrayColor } func performFactoryReset() { if let callback = factoryResetCallback { callback() } } func cancelFactoryResetButtonPressed() { for subview in factoryResetView!.subviews { subview.removeFromSuperview() } } func cancelButtonPressed() { for subview in changeLockCodeView!.subviews { subview.removeFromSuperview() } } func changeLockCodeButtonPressed() { if changeLockCodeView!.subviews.count == 0 { showChangeLockCodeView() } else if changeLockCodeView!.subviews.count == 1 { for subview in changeLockCodeView!.subviews { subview.removeFromSuperview() } } else { cancelButtonPressed() } } func factoryResetButtonPressed() { if factoryResetView?.subviews.count == 0 { showFactoryResetView() } else { cancelFactoryResetButtonPressed() } } func createTextView(text: String, holderView: UIView, topView: UIView, leftView: UIView?, rightView: UIView?, width: CGFloat?, pinTopAttribute: NSLayoutAttribute, setBottomConstraint: Bool) -> UITextView { let textView = UITextView() holderView.addSubview(textView) textView.textAlignment = NSTextAlignment.Left textView.text = text textView.editable = false textView.dataDetectorTypes = UIDataDetectorTypes.All textView.textContainer.maximumNumberOfLines = 3 textView.scrollEnabled = false CustomViews.setConstraints(textView, holderView: holderView, topView: topView, leftView: leftView, rightView: rightView, height: nil, width: width, pinTopAttribute: pinTopAttribute, setBottomConstraints: setBottomConstraint, marginConstraint: kSlotDataMarginConstraint) textView.textColor = UIColor.darkGrayColor() return textView } func createHolder(topElement: UIView, setBottomConstraints: Bool, pinTopAttribute: NSLayoutAttribute) -> UIView { let holder: UIView = UIView() slotContentView.addSubview(holder) CustomViews.setConstraints(holder, holderView: slotContentView, topView: topElement, leftView: nil, rightView: nil, height: nil, width: nil, pinTopAttribute: pinTopAttribute, setBottomConstraints: setBottomConstraints, marginConstraint: kSlotDataMarginConstraint) holder.backgroundColor = UIColor.whiteColor() CustomViews.addShadow(holder) return holder } func createURLTextView(slotData: Dictionary <String, NSData>, topElement: UIView) -> UIView { let URLHolder = createHolder(topElement, setBottomConstraints: false, pinTopAttribute: .Bottom) let broadcastedURLLabel = createLabelWithText("Broadcasted URL", view: URLHolder) var text: String = "" let container = UIView() URLHolder.addSubview(container) CustomViews.setConstraints(container, holderView: URLHolder, topView: broadcastedURLLabel, leftView: nil, rightView: nil, height: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraints: true, marginConstraint: kSlotDataMarginConstraint) container.backgroundColor = kLightGrayColor if let urlData = slotData[slotDataURLKey], url = String(data: urlData, encoding: NSUTF8StringEncoding) { text = "\(url)" } else { text = "URL not set" } let URLTextView = createTextView("URL: ", holderView: container, topView: container, leftView: nil, rightView: nil, width: kURLTextViewWidth, pinTopAttribute: .Top, setBottomConstraint: true) URLTextView.backgroundColor = kLightGrayColor slotDataURL = createTextField(text, holderView: container, topView: container, leftView: URLTextView, topAttribute: .Top) return URLHolder } func createSlider(value: Int, holderView: UIView, topView: UIView, minVal: Float, maxVal: Float) -> UISlider { let slider = UISlider() slider.minimumValue = minVal slider.maximumValue = maxVal slider.setValue(Float(value), animated: false) slider.continuous = true holderView.addSubview(slider) CustomViews.setConstraints(slider, holderView: holderView, topView: topView, leftView: nil, rightView: nil, height: kSliderHeight, width: nil, pinTopAttribute: .Bottom, setBottomConstraints: true, marginConstraint: kSlotDataMarginConstraint) return slider } func createFrameTypePicker(frameType: Int, topView: UIView, setPageBottomConstraints: Bool) -> UIView { let frameTypePickerHolder = createHolder(topView, setBottomConstraints: false, pinTopAttribute: .Top) let frameTypeLabel = createLabelWithText("Frame Type", view: frameTypePickerHolder) frameTypePickerHolder.addSubview(frameTypePickerView) CustomViews.setConstraints(frameTypePickerView, holderView: frameTypePickerHolder, topView: frameTypeLabel, leftView: nil, rightView: nil, height: kPickerViewHeight, width: nil, pinTopAttribute: .Bottom, setBottomConstraints: true, marginConstraint: kSlotDataMarginConstraint) frameTypePickerView.selectRow(frameType, inComponent: 0, animated: false) return frameTypePickerHolder } func createTxPowerHolder(slotData: Dictionary <String, NSData>, topElement: UIView, topAttribute: NSLayoutAttribute, setBottomConstraints: Bool) -> UIView { let txPowerHolder = createHolder(topElement, setBottomConstraints: setBottomConstraints, pinTopAttribute: topAttribute) let txPowerLabel = createLabelWithText("TX Power", view: txPowerHolder) var txPower: Int8 = 0 var txPowerText: String! if let txPowerData = slotData[slotDataTxPowerKey] { txPowerData.getBytes(&txPower, length: sizeof(Int8)) txPowerText = "\(txPower)" } else { txPowerText = "Unknown" } txPowerTextView = createTextView("Radio TX Power: \(txPowerText) dBm", holderView: txPowerHolder, topView: txPowerLabel, leftView: nil, rightView: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: false) txPowerSlider = createSlider(Int(txPower), holderView: txPowerHolder, topView: txPowerTextView!, minVal: -40, maxVal: 4) txPowerSlider?.addTarget(self, action: #selector(SlotDataContentView.txPowerChanged), forControlEvents: UIControlEvents.AllEvents) return txPowerHolder } func txPowerChanged() { let stepSize = 4 let value = Int(txPowerSlider!.value) txPowerSlider!.value = Float(value - value % stepSize) txPowerTextView!.text = "Radio TX Power: \(Int(txPowerSlider!.value)) dBm" } func createAdvIntervalHolder(slotData: Dictionary <String, NSData>, topElement: UIView, pinTop: NSLayoutAttribute, setBottomConstraints: Bool) -> UIView { let advIntervalHolder = createHolder(topElement, setBottomConstraints: setBottomConstraints, pinTopAttribute: pinTop) let advIntervalLabel = createLabelWithText("Advertising Interval", view: advIntervalHolder) var advInterval: UInt16 = 0 var advIntervalText: String! if let advIntervalData = slotData[slotDataAdvIntervalKey] { advIntervalData.getBytes(&advInterval, length: sizeof(UInt16)) advIntervalText = "\(advInterval)" } else { advIntervalText = "Unknown" } advIntervalTextView = createTextView("Advertising Interval: \(advIntervalText)", holderView: advIntervalHolder, topView: advIntervalLabel, leftView: nil, rightView: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: false) advIntervalSlider = createSlider(Int(advInterval), holderView: advIntervalHolder, topView: advIntervalTextView!, minVal: 0, maxVal: 1000) advIntervalSlider?.addTarget(self, action: #selector(SlotDataContentView.advIntervalChanged), forControlEvents: UIControlEvents.AllEvents) return advIntervalHolder } func advIntervalChanged() { let stepSize = 50 let value = Int(advIntervalSlider!.value) advIntervalSlider!.value = Float(value - value % stepSize) advIntervalTextView!.text = "Advertising Interval: \(Int(advIntervalSlider!.value))" } func byteToString(byte: UInt8) -> String { var value: String = String(byte, radix: 16) if value.characters.count == 1 { value += "0" } return value } func createUIDTextView(slotData: Dictionary <String, NSData>, topElement: UIView) -> UIView { let UIDHolder = createHolder(topElement, setBottomConstraints: false, pinTopAttribute: .Bottom) let UIDLabel = createLabelWithText("Beacon ID", view: UIDHolder) var strNamespace: String = "" var strInstance: String = "" if let value = slotData[slotDataUIDKey] { /// The UID has 10 bytes for Namespace and 6 bytes for Instance var namespace: [UInt8] = [UInt8](count: 10, repeatedValue: 0) var instance: [UInt8] = [UInt8](count: 6, repeatedValue: 0) value.getBytes(&namespace, length: 10 * sizeof(UInt8)) value.getBytes(&instance, range: NSMakeRange(10, 6 * sizeof(UInt8))) for byte in namespace { strNamespace += byteToString(byte) } for byte in instance { strInstance += byteToString(byte) } } else { strNamespace = "nil" strInstance = "nil" } let container = UIView() UIDHolder.addSubview(container) container.backgroundColor = kLightGrayColor CustomViews.setConstraints(container, holderView: UIDHolder, topView: UIDLabel, leftView: nil, rightView: nil, height: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraints: true, marginConstraint: kSlotDataMarginConstraint) namespaceText = createTextView("Namespace:", holderView: container, topView: container, leftView: nil, rightView: nil, width: kUIDNamespaceTextViewWidth, pinTopAttribute: .Top, setBottomConstraint: false) let namespaceDescription = "\(strNamespace)" let instanceDescription = "\(strInstance)" namespaceTextView = createTextField(namespaceDescription, holderView: container, topView: container, leftView: namespaceText, topAttribute: .Top) instanceText = createTextView("Instance:", holderView: container, topView: namespaceText, leftView: nil, rightView: nil, width: kUIDNamespaceTextViewWidth, pinTopAttribute: .Bottom, setBottomConstraint: true) instanceTextView = createTextField(instanceDescription, holderView: container, topView: namespaceTextView!, leftView: instanceText, topAttribute: .Bottom) instanceText.dataDetectorTypes = .None namespaceText.dataDetectorTypes = .None namespaceText.backgroundColor = kLightGrayColor instanceText.backgroundColor = kLightGrayColor namespaceTextView!.delegate = self instanceTextView!.delegate = self if strNamespace != "nil" { namespaceTextView?.text = strNamespace } if strInstance != "nil" { instanceTextView?.text = strInstance } namespaceTextView?.addTarget(self, action: #selector(textFieldDidChange), forControlEvents: .EditingChanged) instanceTextView?.addTarget(self, action: #selector(textFieldDidChange), forControlEvents: .EditingChanged) return UIDHolder } func createTLMTextView(slotData: Dictionary <String, NSData>, topElement: UIView) -> UIView { let TLMHolder = createHolder(topElement, setBottomConstraints: false, pinTopAttribute: .Bottom) let TLMLabel = createLabelWithText("Telemetry", view: TLMHolder) let container = UIView() TLMHolder.addSubview(container) CustomViews.setConstraints(container, holderView: TLMHolder, topView: TLMLabel, leftView: nil, rightView: nil, height: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraints: true, marginConstraint: kSlotDataMarginConstraint) if let value = slotData[slotDataTLMKey], (battery, temperature, PDU, time) = BeaconInfo.parseTLMFromFrame(value) { let (days, hours, minutes) = BeaconInfo.convertDeciseconds(time) let batteryDescription = "Battery voltage:" let batteryVoltageTextView = createTextView(batteryDescription, holderView: container, topView: TLMLabel, leftView: nil, rightView: nil, width: kFrameDescriptionWidth, pinTopAttribute: .Bottom, setBottomConstraint: false) createTextView("\(battery) mV/bit", holderView: container, topView: TLMLabel, leftView: nil, rightView: container, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: false) let line1 = createLine(container, topView: batteryVoltageTextView) let temperatureDescription = "Beacon temperature:" let temperatureTextView = createTextView(temperatureDescription, holderView: container, topView: line1, leftView: nil, rightView: nil, width: kFrameDescriptionWidth, pinTopAttribute: .Bottom, setBottomConstraint: false) createTextView("\(temperature)°C", holderView: container, topView: line1, leftView: nil, rightView: container, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: false) let line2 = createLine(container, topView: temperatureTextView) let advPDUDescription = "Advertising PDU count:" let advPDUTextView = createTextView(advPDUDescription, holderView: container, topView: line2, leftView: nil, rightView: nil, width: kFrameDescriptionWidth, pinTopAttribute: .Bottom, setBottomConstraint: false) createTextView("\(PDU)", holderView: container, topView: line2, leftView: nil, rightView: container, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: false) let line3 = createLine(container, topView: advPDUTextView) let timeSinceRebootDescription = "Time since power-on or reboot:" createTextView(timeSinceRebootDescription, holderView: container, topView: line3, leftView: nil, rightView: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: false) let timeView = createTextView("\(days) days\n\(hours) hours\n\(minutes) mins", holderView: container, topView: line3, leftView: nil, rightView: container, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: true) timeView.textAlignment = .Right } else { createTextView("No telemetry data", holderView: TLMHolder, topView: TLMLabel, leftView: nil, rightView: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: true) } return TLMHolder } func createLine(holderView: UIView, topView: UIView) -> UIView { let lineView = UIView() holderView.addSubview(lineView) CustomViews.setConstraints(lineView, holderView: holderView, topView: topView, leftView: nil, rightView: nil, height: 1.0, width: nil, pinTopAttribute: .Bottom, setBottomConstraints: false, marginConstraint: kSlotDataMarginConstraint) lineView.backgroundColor = UIColor.lightGrayColor() return lineView } func createGlobalView() -> UIView { globalHolder = createHolder(slotContentView, setBottomConstraints: false, pinTopAttribute: .Top) let globalLabel = createLabelWithText("Global Settings", view: globalHolder!) changeLockCodeButton = createButtonWithText("Change lock code", holderView: globalHolder!, topElement: globalLabel, setBottomConstraints: false) changeLockCodeButton!.addTarget(self, action: #selector(changeLockCodeButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) createChangeLockCodeView() let lineView = createLine(globalHolder!, topView: changeLockCodeView!) factoryResetButton = createButtonWithText("Factory reset", holderView: globalHolder!, topElement: lineView, setBottomConstraints: false) factoryResetButton!.addTarget(self, action: #selector(factoryResetButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) createFactoryResetView() let secondLineView = createLine(globalHolder!, topView: factoryResetView!) createButtonWithText("Remain Connectable", holderView: globalHolder!, topElement: secondLineView, setBottomConstraints: false) remainConnectableSwitch = UISwitch() remainConnectableSwitch!.onTintColor = kGreenColor remainConnectableSwitch!.addTarget(self, action: #selector(switchValueChanged), forControlEvents: UIControlEvents.ValueChanged) globalHolder?.addSubview(remainConnectableSwitch!) CustomViews.setConstraints(remainConnectableSwitch!, holderView: globalHolder!, topView: secondLineView, leftView: nil, rightView: globalHolder, height: nil, width: kFrameTitleWidth, pinTopAttribute: .Bottom, setBottomConstraints: true, marginConstraint: kSlotDataMarginConstraint) return globalHolder! } func displaySignInWarningView(topView: UIView) { signInHolder = createHolder(topView, setBottomConstraints: false, pinTopAttribute: .Bottom) let signInLabel = createLabelWithText("Sign In", view: signInHolder) let signInWarningTextView = createTextView("In order to configure the EID, you must sign in " + "with Google. Do you want to do that now?", holderView: signInHolder, topView: signInLabel, leftView: nil, rightView: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: false) signInWarningTextView.backgroundColor = kLightGrayColor let signInButton = createControlButton("SIGN IN", holderView: signInHolder, topElement: signInWarningTextView, setBottomConstraints: true, rightView: signInHolder) let cancelButton = createControlButton("CANCEL", holderView: signInHolder, topElement: signInWarningTextView, setBottomConstraints: true, rightView: signInButton) cancelButton.addTarget(self, action: #selector(cancelSignInButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) signInButton.addTarget(self, action: #selector(signInButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) } func displayProjectSelectionWarningView(topView: UIView) { selectHolder = createHolder(topView, setBottomConstraints: false, pinTopAttribute: .Bottom) let signInLabel = createLabelWithText("Select Project", view: selectHolder) let selectProjectTextView = createTextView("In order to configure the EID, you must select a " + "Google project associated with the user you are " + "currently signed in with. " + "Do you want to do that now?", holderView: selectHolder, topView: signInLabel, leftView: nil, rightView: nil, width: nil, pinTopAttribute: .Bottom, setBottomConstraint: false) selectProjectTextView.backgroundColor = kLightGrayColor let selectButton = createControlButton("SELECT", holderView: selectHolder, topElement: selectProjectTextView, setBottomConstraints: true, rightView: selectHolder) let cancelButton = createControlButton("CANCEL", holderView: selectHolder, topElement: selectProjectTextView, setBottomConstraints: true, rightView: selectButton) cancelButton.addTarget(self, action: #selector(cancelSignInButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) selectButton.addTarget(self, action: #selector(signInButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) } func signInButtonPressed() { signInWithGoogleCallback!(viewToDisable: signInHolder, selectViewHolder: selectHolder) } func cancelSignInButtonPressed() { frameTypePickerView.selectRow(Int(FrameTypeChange.NotSet.rawValue), inComponent: 0, animated: true) signInHolder.removeFromSuperview() selectHolder.removeFromSuperview() } func switchValueChanged() { if let callback = remainConnectableCallback { callback(on: remainConnectableSwitch!.on) } } func setAsURLTypeContentView(slotData: Dictionary <String, NSData>, capabilities: NSDictionary) { frameTypeChange = .URL self.slotData = slotData self.broadcastCapabilities = capabilities createContentView() slotContentScrollView.addSubview(slotContentView) let pickerView = createFrameTypePicker(frameTypes .indexOfObject(BeaconInfo.EddystoneFrameType.URLFrameType.description), topView: slotContentView, setPageBottomConstraints: false) let textView = createURLTextView(slotData, topElement: pickerView) var txPowerView: UIView? if let perSlotTxPowerSupported = capabilities[perSlotTxPowerSupportedKey] as? Bool, perSlotAdvIntervSupported = capabilities[perSlotAdvIntervalsSupportedKey] as? Bool { if perSlotTxPowerSupported && !perSlotAdvIntervSupported { txPowerView = createTxPowerHolder(slotData, topElement: textView, topAttribute: .Bottom, setBottomConstraints: false) } else if perSlotTxPowerSupported { txPowerView = createTxPowerHolder(slotData, topElement: textView, topAttribute: .Bottom, setBottomConstraints: false) createAdvIntervalHolder(slotData, topElement: txPowerView!, pinTop: .Bottom, setBottomConstraints: false) } else if perSlotAdvIntervSupported { createAdvIntervalHolder(slotData, topElement: textView, pinTop: .Bottom, setBottomConstraints: false) } } } func setAsUIDTypeContentView(slotData: Dictionary <String, NSData>, capabilities: NSDictionary) { frameTypeChange = .UID self.slotData = slotData self.broadcastCapabilities = capabilities createContentView() slotContentScrollView.addSubview(slotContentView) let pickerView = createFrameTypePicker(frameTypes .indexOfObject(BeaconInfo.EddystoneFrameType.UIDFrameType.description), topView: slotContentView, setPageBottomConstraints: false) let textView = createUIDTextView(slotData, topElement: pickerView) var txPowerView: UIView? if let perSlotTxPowerSupported = capabilities[perSlotTxPowerSupportedKey] as? Bool, perSlotAdvIntervSupported = capabilities[perSlotAdvIntervalsSupportedKey] as? Bool { if perSlotTxPowerSupported && !perSlotAdvIntervSupported { txPowerView = createTxPowerHolder(slotData, topElement: textView, topAttribute: .Bottom, setBottomConstraints: false) } else if perSlotTxPowerSupported { txPowerView = createTxPowerHolder(slotData, topElement: textView, topAttribute: .Bottom, setBottomConstraints: false) createAdvIntervalHolder(slotData, topElement: txPowerView!, pinTop: .Bottom, setBottomConstraints: false) } else if perSlotAdvIntervSupported { createAdvIntervalHolder(slotData, topElement: textView, pinTop: .Bottom, setBottomConstraints: false) } } } func setAsTLMTypeContentView(slotData: Dictionary <String, NSData>, capabilities: NSDictionary) { frameTypeChange = .TLM self.slotData = slotData self.broadcastCapabilities = capabilities createContentView() slotContentScrollView.addSubview(slotContentView) let pickerView = createFrameTypePicker(frameTypes .indexOfObject(BeaconInfo.EddystoneFrameType.TelemetryFrameType.description), topView: slotContentView, setPageBottomConstraints: false) let textView = createTLMTextView(slotData, topElement: pickerView) var txPowerView: UIView? if let perSlotTxPowerSupported = capabilities[perSlotTxPowerSupportedKey] as? Bool, perSlotAdvIntervSupported = capabilities[perSlotAdvIntervalsSupportedKey] as? Bool { if perSlotTxPowerSupported && !perSlotAdvIntervSupported { txPowerView = createTxPowerHolder(slotData, topElement: textView, topAttribute: .Bottom, setBottomConstraints: false) } else if perSlotTxPowerSupported { txPowerView = createTxPowerHolder(slotData, topElement: textView, topAttribute: .Bottom, setBottomConstraints: false) createAdvIntervalHolder(slotData, topElement: txPowerView!, pinTop: .Bottom, setBottomConstraints: false) } else if perSlotAdvIntervSupported { createAdvIntervalHolder(slotData, topElement: textView, pinTop: .Bottom, setBottomConstraints: false) } } } func setAsEIDTypeContentView(slotData: Dictionary <String, NSData>, capabilities: NSDictionary) { frameTypeChange = .EID self.slotData = slotData self.broadcastCapabilities = capabilities createContentView() slotContentScrollView.addSubview(slotContentView) let pickerView = createFrameTypePicker(frameTypes .indexOfObject(BeaconInfo.EddystoneFrameType.EIDFrameType.description), topView: slotContentView, setPageBottomConstraints: false) displayProjectSelectionWarningView(pickerView) selectHolder.hidden = true if GIDSignIn.sharedInstance().currentUser == nil { displaySignInWarningView(pickerView) } else if EIDConfiguration.projectID == nil { selectHolder.hidden = false } } func setAsNoFrameTypeContentView(capabilities: NSDictionary) { self.broadcastCapabilities = capabilities frameTypeChange = .NotSet createContentView() slotContentScrollView.addSubview(slotContentView) createFrameTypePicker(frameTypes .indexOfObject(BeaconInfo.EddystoneFrameType.NotSetFrameType.description), topView: slotContentView, setPageBottomConstraints: false) } func setAsGlobalContentView(broadcastCapabilities: NSDictionary, slotData: Dictionary <String, NSData> ) { var txPowerView: UIView? createContentView() self.slotData = slotData self.broadcastCapabilities = broadcastCapabilities slotContentScrollView.addSubview(slotContentView) let globalView = createGlobalView() slotContentView.addSubview(globalView) if let perSlotTxPowerSupported = broadcastCapabilities[perSlotTxPowerSupportedKey] as? Bool, perSlotAdvIntervSupported = broadcastCapabilities[perSlotAdvIntervalsSupportedKey] as? Bool { if !perSlotTxPowerSupported && perSlotAdvIntervSupported { txPowerView = createTxPowerHolder(slotData, topElement: globalView, topAttribute: .Bottom, setBottomConstraints: false) } else if !perSlotTxPowerSupported { txPowerView = createTxPowerHolder(slotData, topElement: globalView, topAttribute: .Bottom, setBottomConstraints: false) createAdvIntervalHolder(slotData, topElement: txPowerView!, pinTop: .Bottom, setBottomConstraints: false) } else if !perSlotAdvIntervSupported { createAdvIntervalHolder(slotData, topElement: globalView, pinTop: .Bottom, setBottomConstraints: false) } } } func parseURLTextToFrame(URLText: String) -> NSData { var URL: String? = URLText var byte: UInt8 = 0 var URLBytes: [UInt8] = [] var URLData: NSData URLBytes.append(BeaconInfo.EddystoneURLFrameTypeID) while URL?.characters.count != 0 { (byte, URL) = BeaconInfo.byteFromEncodedString(URL!) URLBytes.append(byte) } URLData = NSData(bytes: URLBytes, length: URLBytes.count * sizeof(UInt8)) return URLData } func parseDataToUIDFrame(namespace: String, instance: String) -> NSData { var UIDData: NSData = NSData() var UIDBytes: [UInt8] = [] UIDBytes.append(BeaconInfo.EddystoneUIDFrameTypeID) let namespaceBytes = StringUtils.transformStringToByteArray(namespace) let instanceBytes = StringUtils.transformStringToByteArray(instance) UIDBytes.appendContentsOf(namespaceBytes) UIDBytes.appendContentsOf(instanceBytes) UIDData = NSData(bytes: UIDBytes, length: UIDBytes.count * sizeof(UInt8)) return UIDData } func getUpdateData() -> Dictionary <String, NSData>? { currentSlotUpdateData.removeAll() if let currentTxPowerSlider = txPowerSlider { var txPower: Int8 = Int8(currentTxPowerSlider.value) let value = NSData(bytes: &txPower, length: sizeof(Int8)) if value != slotData[slotDataTxPowerKey] { currentSlotUpdateData[slotDataTxPowerKey] = value didChangeSlotData = true } } if let currentAdvIntervalSlider = advIntervalSlider { var advInterval: UInt16 = UInt16(currentAdvIntervalSlider.value) let value = NSData(bytes: &advInterval, length: sizeof(UInt16)) if value != slotData[slotDataAdvIntervalKey] { currentSlotUpdateData[slotDataAdvIntervalKey] = value didChangeSlotData = true } } switch frameTypeChange { case .URL: if var slotDataURLtext = slotDataURL?.text { if slotDataURLtext.characters.count == 0 { slotDataURLtext = (slotDataURL?.placeholder)! } currentSlotUpdateData[slotDataURLKey] = parseURLTextToFrame(slotDataURLtext) } case .UID: if var instanceData = instanceTextView?.text, namespaceData = namespaceTextView?.text { if namespaceData.characters.count == 0 { namespaceData = (namespaceTextView?.placeholder)! } else if namespaceData.characters.count != kUIDNamespaceLength { if let alert = showAlert { alert(title: "Namespace", description: "Namespace too short. It must have exactly 20 characters.", buttonText: "OK") } return nil } if instanceData.characters.count == 0 { instanceData = (instanceTextView?.placeholder)! } else if instanceData.characters.count != kUIDInstanceLength { if let alert = showAlert { alert(title: "Instance", description: "Instance too short. It must have exactly 12 characters.", buttonText: "OK") } return nil } if namespaceData != "nil" && instanceData != "nil" { currentSlotUpdateData[slotDataUIDKey] = parseDataToUIDFrame(namespaceData, instance: instanceData) } } case .TLM: currentSlotUpdateData[slotDataTLMKey] = NSData(bytes: [BeaconInfo.EddystoneTLMFrameTypeID], length: 1) case .NotSet: currentSlotUpdateData[slotDataNoFrameKey] = NSData(bytes: [], length: 0) case .EID: if GIDSignIn.sharedInstance().currentUser != nil { if EIDConfiguration.projectID != nil { currentSlotUpdateData[slotDataEIDKey] = NSData(bytes: [BeaconInfo.EddystoneEIDFrameTypeID], length: 1) } else { if let alert = showAlert { alert(title: "Project", description: "You are unable to configure the beacon to broadcast EID " + "without having a Google Project selected.", buttonText: "OK") } return nil } } else { if let alert = showAlert { alert(title: "Sign In", description: "You are unable to configure the beacon to broadcast EID " + "without signing in with a Google account.", buttonText: "OK") } return nil } } return currentSlotUpdateData } }
apache-2.0
5fc2cb0a242044fc5b7b6c767120b369
44.500355
100
0.545235
6.09179
false
false
false
false
volendavidov/NagBar
NagBar/ThrukParser.swift
1
5389
// // ThrukParser.swift // NagBar // // Created by Volen Davidov on 02.07.16. // Copyright © 2016 Volen Davidov. All rights reserved. // import Foundation import SwiftyJSON // Icinga2 and Thruk JSON formats are very simillar with some exceptions. Time and status formats are the same. // The Icinga2 JSON parser can be used as a generic JSON parser for other monitoring systems as well. class ThrukParser : Icinga2Parser { override func getHostForHost(_ json: JSON) -> String { return json["display_name"].string ?? "" } override func getHostForService(_ json: JSON) -> String { return json["host_name"].string ?? "" } override func getService(_ json: JSON) -> String { return json["description"].string ?? "" } override func getAttempt(_ json: JSON) -> String { let attempt = json["current_attempt"].int != nil ? String(json["current_attempt"].int!) : "" let maxCheckAttempts = json["max_check_attempts"].int != nil ? String(json["max_check_attempts"].int!) : "" // we also want to add the current_notification_number which is a feature supported by Thruk let currentNotificationNumber = json["current_notification_number"].int != nil ? String(json["current_notification_number"].int!) : "" let attemptString = attempt + "/" + maxCheckAttempts + " #" + currentNotificationNumber return attemptString } override func getStatusForHost(_ json: JSON) -> String { let status = self.hostStatusTranslate(Float(json["state"].int!)) return self.getStatus(json, status: status) } override func getStatusForService(_ json: JSON) -> String { let status = self.serviceStatusTranslate(Float(json["state"].int!)) return self.getStatus(json, status: status) } override func getLastCheckForHost(_ json: JSON) -> String { var lastCheck = self.unixToTimestamp(json["last_check"].double) // If the host is pending, it will have value 0 for "state" which does not make sense and it will look as the host is OK. However, the value of "last_check" is 0, so we use it instead; this block must be after the block setting item.status. The same workaround is applied for services. if json["last_check"].double == 0 { lastCheck = "N/A" } return lastCheck } override func getLastCheckForService(_ json: JSON) -> String { return self.getLastCheckForHost(json) } override func getDurationForHost(_ json: JSON) -> String { return self.timeSinceSecondsToString(json["last_state_change"].double) } override func getDurationForService(_ json: JSON) -> String { return self.getDurationForHost(json) } override func getItemURLForService(_ json: JSON) -> String { let monitoringHost = URL(string: self.monitoringInstance!.url)!.scheme! + "://" + URL(string: self.monitoringInstance!.url)!.host! + "/thruk/cgi-bin/" return String(format: monitoringHost + "extinfo.cgi?type=2&host=%@&service=%@", self.getHostForService(json), self.getService(json)) } override func getItemURLForHost(_ json: JSON) -> String { let monitoringHost = URL(string: self.monitoringInstance!.url)!.scheme! + "://" + URL(string: self.monitoringInstance!.url)!.host! + "/thruk/cgi-bin/" return String(format: monitoringHost + "extinfo.cgi?type=1&host=%@", self.getHostForHost(json)) } override func getStatusInformationForHost(_ json: JSON) -> String { return json["plugin_output"].string ?? "" } override func getStatusInformationForService(_ json: JSON) -> String { return self.getStatusInformationForHost(json) } override func getAcknowledgementForHost(_ json: JSON) -> Bool { return json["acknowledged"].boolValue } override func getAcknowledgementForService(_ json: JSON) -> Bool { return json["acknowledged"].boolValue } override func getDowntimeForHost(_ json: JSON) -> Bool { return json["scheduled_downtime_depth"].boolValue } override func getDowntimeForService(_ json: JSON) -> Bool { return json["scheduled_downtime_depth"].boolValue } override func getJSON(_ data: NSData) -> [JSON]? { guard let json = try? JSON(data: data as Data) else { return nil } guard let jsonResults = json.array else { return nil } return jsonResults } override func postProcessHosts(_ results: Array<HostMonitoringItem>) -> Array<HostMonitoringItem> { return results } override func postProcessServices(_ results: Array<ServiceMonitoringItem>) -> Array<ServiceMonitoringItem> { return results } private func getStatus(_ json: JSON, status: String) -> String { // If the host is pending, it will have value 0 for "state" which does not make sense and it will look as the host is OK. However, the value of "last_check" is 0, so we use it instead; this block must be after the block setting item.status. The same workaround is applied for services. if json["last_check"].double == 0 { return "N/A" } else { return status } } }
apache-2.0
2b046e067733cf917847e598538f75c9
38.911111
293
0.641425
4.348668
false
false
false
false
saeta/penguin
Sources/PenguinParallel/NonblockingThreadPool/NonBlockingThreadPool.swift
1
25416
// Copyright 2020 Penguin Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import PenguinStructures /// An efficient, work-stealing, general purpose compute thread pool. /// /// `NonBlockingThreadPool` can be cleaned up by calling `shutDown()` which will block until all /// threads in the threadpool have exited. If `shutDown()` is never called, `NonBlockingThreadPool` /// will never be deallocated. /// /// NonBlockingThreadPool uses atomics to implement a non-blocking thread pool. During normal /// execution, no locks are acquired or released. This can result in efficient parallelism across /// many cores. `NonBlockingThreadPool` is designed to scale from laptops to high-core-count /// servers. Although the thread pool size can be manually tuned, often the most efficient /// configuration is a one-to-one mapping between hardware threads and worker threads, as this /// allows full use of the hardware while avoiding unnecessary context switches. I/O heavy workloads /// may want to reduce the thread pool count to dedicate a core or two to I/O processing. /// /// Each thread managed by this thread pool maintains its own fixed-size pending task queue. The /// workers loop, trying to get their next tasks from their own queue first, and if that queue is /// empty, the worker tries to steal work from the pending task queues of other threads in the pool. /// /// `NonBlockingThreadPool` implements important optimizations based on the calling thread. There /// are key fast-paths taken when calling functions on `NonBlockingThreadPool` from threads that /// have been registered with the pool (or from threads managed by the pool itself). In order /// to help users build performant applications, `NonBlockingThreadPool` will trap (and exit the /// process) if functions are called on it from non-fast-path'd threads by default. You can change /// this behavior by setting `allowNonFastPathThreads: true` at initialization. /// /// In order to avoid wasting excessive CPU cycles, the worker threads managed by /// `NonBlockingThreadPool` will suspend themselves (using locks to inform the host kernel). /// `NonBlockingThreadPool` is parameterized by an environment, which allows this thread pool to /// seamlessly interoperate within a larger application by reusing its concurrency primitives (such /// as locks and condition variables, which are used for thread parking), as well as even allowing /// a custom thread allocator. /// /// Local tasks typically execute in LIFO order, which is often optimal for cache locality of /// compute intensive tasks. Other threads attempt to steal work "FIFO"-style, which admits an /// efficient (dynamic) schedule for typical divide-and-conquor algorithms. /// /// This implementation is inspired by the Eigen thread pool library, TFRT, as well as: /// /// "Thread Scheduling for Multiprogrammed Multiprocessors" /// Nimar S. Arora, Robert D. Blumofe, C. Greg Plaxton /// public class NonBlockingThreadPool<Environment: ConcurrencyPlatform>: ComputeThreadPool { public typealias Task = () -> Void public typealias ThrowingTask = () throws -> Void typealias Queue = TaskDeque<Task, Environment> let allowNonFastPathThreads: Bool let totalThreadCount: Int let externalFastPathThreadCount: Int var externalFastPathThreadSeenCount: Int = 0 let coprimes: [Int] let queues: [Queue] var cancelledStorage: AtomicUInt64 var blockedCountStorage: AtomicUInt64 var spinningState: AtomicUInt64 let condition: NonblockingCondition<Environment> let waitingMutex: [Environment.ConditionMutex] // TODO: modify condition to add per-thread wakeup let externalWaitingMutex: Environment.ConditionMutex var threads: [Environment.Thread] private let perThreadKey = Environment.ThreadLocalStorage.makeKey( for: Type<PerThreadState<Environment>>()) /// Initialize a new thread pool with `threadCount` threads using threading environment /// `environment`. /// /// - Parameter name: a human-readable name for the threadpool. /// - Parameter threadCount: the number of worker threads in the thread pool. /// - Parameter environment: an instance of the environment. /// - Parameter externalFastPathThreadCount: the maximum number of external threads with fast-path /// access to the threadpool. /// - Parameter allowNonFastPathThreads: true if non-fast-path'd threads are allowed to submit /// work into the pool or not. (Note: non-fast-path'd threads can always dispatch work into the /// pool.) public init( name: String, threadCount: Int, environment: Environment, externalFastPathThreadCount: Int = 1, allowNonFastPathThreads: Bool = false ) { self.allowNonFastPathThreads = allowNonFastPathThreads let totalThreadCount = threadCount + externalFastPathThreadCount self.totalThreadCount = totalThreadCount self.externalFastPathThreadCount = externalFastPathThreadCount self.coprimes = positiveCoprimes(totalThreadCount) self.queues = (0..<totalThreadCount).map { _ in Queue.make() } self.cancelledStorage = AtomicUInt64() self.blockedCountStorage = AtomicUInt64() self.spinningState = AtomicUInt64() self.condition = NonblockingCondition(threadCount: threadCount) // Only block pool threads. self.waitingMutex = (0..<totalThreadCount).map { _ in Environment.ConditionMutex() } self.externalWaitingMutex = Environment.ConditionMutex() self.threads = [] for i in 0..<threadCount { threads.append( environment.makeThread(name: "\(name)-\(i)-of-\(threadCount)") { Self.workerThread(state: PerThreadState(threadId: i, pool: self)) }) } // Register current thread as a fast-path thread. registerCurrentThread() } deinit { // Shut ourselves down, just in case. shutDown() } /// Registers the current thread with the thread pool for fast-path operation. public func registerCurrentThread() { externalWaitingMutex.lock() defer { externalWaitingMutex.unlock() } let threadId = threads.count + externalFastPathThreadSeenCount externalFastPathThreadSeenCount += 1 let state = PerThreadState(threadId: threadId, pool: self) perThreadKey.localValue = state } public func dispatch(_ fn: @escaping Task) { if let local = perThreadKey.localValue { // Push onto local queue. if let bounced = queues[local.threadId].pushFront(fn) { // If local queue is full, execute immediately. bounced() } else { wakeupWorkerIfRequired() } } else { // Called not from within the threadpool; pick a victim thread from the pool at random. // TODO: use a faster RNG! let victim = Int.random(in: 0..<queues.count) if let bounced = queues[victim].pushBack(fn) { // If queue is full, execute inline. bounced() } else { wakeupWorkerIfRequired() } } } public func join(_ a: Task, _ b: Task) { // add `b` to the work queue (and execute it immediately if queue is full). // if added to the queue, maybe wakeup worker if required. // // then execute `a`. // // while `b` hasn't yet completed, do work locally, or do work remotely. Once the background // task has completed, it will atomically set a bit in the local data structure, and we can // then continue execution. // // If we should park ourselves to wait for `b` to finish executing and there's absolutely no // work we can do ourselves, we wait on the current thread's ConditionMutex. When `b` is // finally available, the completer must trigger the ConditionMutex. withoutActuallyEscaping(b) { b in var workItem = WorkItem(b) let unretainedPool = Unmanaged.passUnretained(self) withUnsafeMutablePointer(to: &workItem) { workItem in let perThread = perThreadKey.localValue // Stash in stack variable for performance. // Enqueue `b` into a work queue. if let localThreadIndex = perThread?.threadId { // Push to front of local queue. if let bounced = queues[localThreadIndex].pushFront( { runWorkItem(workItem, pool: unretainedPool) } ) { bounced() } else { wakeupWorkerIfRequired() } } else { precondition( allowNonFastPathThreads, """ Non-fast-path thread disallowed. (Set `allowNonFastPathThreads: true` when initializing \(String(describing: type(of: self))) to allow `join` to be called from non-registered threads. Note: this may make debugging performance problems more difficult.) """) let victim = Int.random(in: 0..<queues.count) // push to back of victim queue. if let bounced = queues[victim].pushBack( { runWorkItem(workItem, pool: unretainedPool) } ) { bounced() } else { wakeupWorkerIfRequired() } } // Execute `a`. a() if let perThread = perThread { // Thread pool thread... execute work on the threadpool. let q = queues[perThread.threadId] // While `b` is not done, try and be useful while !workItem.pointee.isDoneAcquiring() { if let task = q.popFront() ?? perThread.steal() ?? perThread.spin() { task() } else { // No work to be done without blocking, so we block ourselves specially. // This state occurs when another thread stole `b`, but hasn't finished and there's // nothing else useful for us to do. waitingMutex[perThread.threadId].lock() // Set our handle in the workItem's state. var state = WorkItemState(workItem.pointee.stateStorage.valueRelaxed) while !state.isDone { let newState = state.settingWakeupThread(perThread.threadId) if workItem.pointee.stateStorage.cmpxchgAcqRel( original: &state.underlying, newValue: newState.underlying) { break } } if !state.isDone { waitingMutex[perThread.threadId].await { workItem.pointee.isDoneAcquiring() // What about cancellation? } } waitingMutex[perThread.threadId].unlock() } } } else { // Do a quick check to see if we can fast-path return... if !workItem.pointee.isDoneAcquiring() { // We ran on the user's thread, so we now wait on the pool's global lock. externalWaitingMutex.lock() // Set the sentinal thread index. var state = WorkItemState(workItem.pointee.stateStorage.valueRelaxed) while !state.isDone { let newState = state.settingWakeupThread(-1) if workItem.pointee.stateStorage.cmpxchgAcqRel( original: &state.underlying, newValue: newState.underlying) { break } } if !state.isDone { externalWaitingMutex.await { workItem.pointee.isDoneAcquiring() // What about cancellation? } } externalWaitingMutex.unlock() } } } } } public func join(_ a: ThrowingTask, _ b: ThrowingTask) throws { // Because the implementation doesn't support early cancellation of tasks (extra coordination // overhead not worth it for the normal case of non-throwing execution), we implement the // throwing case in terms of the non-throwing case. var err: Error? = nil let lock = Environment.Mutex() join( { do { try a() } catch { lock.lock() err = error lock.unlock() } }, { do { try b() } catch { lock.lock() err = error lock.unlock() } }) if let e = err { throw e } } /// Executes `fn`, optionally in parallel, spanning the range `0..<n`. public func parallelFor(n: Int, _ fn: VectorizedParallelForBody) { let grainSize = max(n / maxParallelism, 1) // TODO: Make adaptive! func executeParallelFor(_ start: Int, _ end: Int) { if start + grainSize >= end { fn(start, end, n) } else { // Divide into 2 & recurse. let rangeSize = end - start let midPoint = start + (rangeSize / 2) self.join({ executeParallelFor(start, midPoint) }, { executeParallelFor(midPoint, end)}) } } executeParallelFor(0, n) } /// Executes `fn`, optionally in parallel, spanning the range `0..<n`. public func parallelFor(n: Int, _ fn: ThrowingVectorizedParallelForBody) throws { var err: Error? = nil let lock = Environment.Mutex() parallelFor(n: n) { start, end, total in do { try fn(start, end, total) } catch { lock.lock() defer { lock.unlock() } err = error } } if let err = err { throw err } } /// Requests that all threads in the threadpool exit and cleans up their associated resources. /// /// This function returns only once all threads have exited and their resources have been /// deallocated. /// /// Note: if a work item was submitted to the threadpool that never completes (i.e. has an /// infinite loop), this function will never return. public func shutDown() { cancelled = true condition.notify(all: true) // Wait until each thread has stopped. for thread in threads { thread.join() } threads.removeAll() // Remove threads that have been shut down. } public var maxParallelism: Int { totalThreadCount } public var currentThreadIndex: Int? { perThreadKey.localValue?.threadId } } extension NonBlockingThreadPool { /// Controls whether the thread pool threads should exit and shut down. fileprivate var cancelled: Bool { get { cancelledStorage.valueRelaxed == 1 } set { assert(newValue == true) cancelledStorage.setRelaxed(1) } } /// The number of threads that are blocked on a condition. fileprivate var blockedThreadCount: Int { Int(blockedCountStorage.valueRelaxed) } /// The number of threads that are actively executing. fileprivate var activeThreadCount: Int { threads.count - blockedThreadCount } /// Wakes up a worker if required. /// /// This function should be called right after adding a new task to a per-thread queue. /// /// If there are threads spinning in the steal loop, there is no need to unpark a waiting thread, /// as the task will get picked up by one of the spinners. private func wakeupWorkerIfRequired() { var state = NonBlockingSpinningState(spinningState.valueRelaxed) while true { // if the number of tasks submitted without notifying parked threads is equal to the number of // spinning threads, we must wake up one of the parked threads if state.noNotifyCount == state.spinningCount { condition.notify() return } let newState = state.incrementingNoNotifyCount() if spinningState.cmpxchgRelaxed(original: &state.underlying, newValue: newState.underlying) { return } } } /// Called to determine if a thread should start spinning. fileprivate func shouldStartSpinning() -> Bool { if activeThreadCount > Constants.minActiveThreadsToStartSpinning { return false } // ??? var state = NonBlockingSpinningState(spinningState.valueRelaxed) while true { if (state.spinningCount - state.noNotifyCount) >= Constants.maxSpinningThreads { return false } let newState = state.incrementingSpinningCount() if spinningState.cmpxchgRelaxed(original: &state.underlying, newValue: newState.underlying) { return true } } } /// Called when a thread stops spinning. /// /// - Returns: `true` if there is a task to steal; false otherwise. fileprivate func stopSpinning() -> Bool { var state = NonBlockingSpinningState(spinningState.valueRelaxed) while true { var newState = state.decrementingSpinningCount() // If there was a task submitted without notifying a thread, try to claim it. let noNotifyTask = state.hasNoNotifyTask if noNotifyTask { newState.decrementNoNotifyCount() } if spinningState.cmpxchgRelaxed(original: &state.underlying, newValue: newState.underlying) { return noNotifyTask } } } /// The worker thread's run loop. private static func workerThread(state: PerThreadState<Environment>) { state.pool.perThreadKey.localValue = state let q = state.pool.queues[state.threadId] while !state.isCancelled { if let task = q.popFront() ?? state.steal() ?? state.spin() ?? state.parkUntilWorkAvailable() { task() // Execute the task. } } } } extension NonBlockingThreadPool where Environment: DefaultInitializable { /// Creates `self` using a default-initialized `Environment`, and the specified `name` and /// `threadCount`. public convenience init(name: String, threadCount: Int) { self.init(name: name, threadCount: threadCount, environment: Environment()) } } fileprivate final class PerThreadState<Environment: ConcurrencyPlatform> { typealias Task = NonBlockingThreadPool<Environment>.Task init(threadId: Int, pool: NonBlockingThreadPool<Environment>) { self.threadId = threadId self.pool = pool self.totalThreadCount = pool.totalThreadCount self.workerThreadCount = pool.totalThreadCount - pool.externalFastPathThreadCount self.coprimes = pool.coprimes self.queues = pool.queues self.condition = pool.condition self.rng = PCGRandomNumberGenerator(state: UInt64(threadId)) } let threadId: Int let pool: NonBlockingThreadPool<Environment> // Note: this creates a reference cycle. // The reference cycle is okay, because you just call `pool.shutDown()`, which will deallocate the // threadpool. // // Note: because you cannot dereference an object in Swift that is in it's `deinit`, it is not // possible to provide a safer API that doesn't leak by default without inducing an extra pointer // dereference on critical paths. :-( let totalThreadCount: Int let workerThreadCount: Int let coprimes: [Int] let queues: [NonBlockingThreadPool<Environment>.Queue] let condition: NonblockingCondition<Environment> var rng: PCGRandomNumberGenerator var isCancelled: Bool { pool.cancelled } func steal() -> Task? { let r = rng.next() var selectedThreadId = Int(r.reduced(into: UInt64(totalThreadCount))) let step = coprimes[Int(r.reduced(into: UInt64(coprimes.count)))] assert( step < totalThreadCount, "step: \(step), pool threadcount: \(totalThreadCount)") for i in 0..<totalThreadCount { assert( selectedThreadId < totalThreadCount, "\(selectedThreadId) is too big on iteration \(i); max: \(totalThreadCount), step: \(step)" ) if let task = queues[selectedThreadId].popBack() { return task } selectedThreadId += step if selectedThreadId >= totalThreadCount { selectedThreadId -= totalThreadCount } } return nil } func spin() -> Task? { let spinCount = workerThreadCount > 0 ? Constants.spinCount / workerThreadCount : 0 if pool.shouldStartSpinning() { // Call steal spin_count times; break if steal returns something. for _ in 0..<spinCount { if let task = steal() { _ = pool.stopSpinning() return task } } // Stop spinning & optionally make one more check. let existsNoNotifyTask = pool.stopSpinning() if existsNoNotifyTask { return steal() } } return nil } func parkUntilWorkAvailable() -> Task? { // Already did a best-effort emptiness check in steal, so prepare for blocking. condition.preWait() // Now we do a reliable emptiness check. if let nonEmptyQueueIndex = findNonEmptyQueueIndex() { condition.cancelWait() // Steal from `nonEmptyQueueIndex`. return queues[nonEmptyQueueIndex].popBack() } let blockedCount = pool.blockedCountStorage.increment() + 1 // increment returns old value. if blockedCount == pool.threads.count { // TODO: notify threads that could be waiting for "all blocked" event. (Useful for quiescing.) } if isCancelled { pool.condition.cancelWait() return nil } condition.commitWait(threadId) _ = pool.blockedCountStorage.decrement() return nil } private func findNonEmptyQueueIndex() -> Int? { let r = rng.next() let increment = totalThreadCount == 1 ? 1 : coprimes[Int(r.reduced(into: UInt64(coprimes.count)))] var threadIndex = Int(r.reduced(into: UInt64(totalThreadCount))) for _ in 0..<totalThreadCount { if !queues[threadIndex].isEmpty { return threadIndex } threadIndex += increment if threadIndex >= totalThreadCount { threadIndex -= totalThreadCount } } return nil } } fileprivate struct WorkItem { let op: () -> Void var stateStorage: AtomicUInt64 init(_ op: @escaping () -> Void) { self.op = op stateStorage = AtomicUInt64() } mutating func isDoneAcquiring() -> Bool { WorkItemState(stateStorage.valueAcquire).isDone } } fileprivate func runWorkItem<Environment: ConcurrencyPlatform>( _ item: UnsafeMutablePointer<WorkItem>, pool poolUnmanaged: Unmanaged<NonBlockingThreadPool<Environment>> // Avoid refcount traffic. ) { assert(!item.pointee.isDoneAcquiring(), "Work item done before even starting execution?!?") item.pointee.op() // Execute the function. var state = WorkItemState(item.pointee.stateStorage.valueRelaxed) while true { assert(!state.isDone, "state: \(state)") let newState = state.markingDone() if item.pointee.stateStorage.cmpxchgAcqRel( original: &state.underlying, newValue: newState.underlying) { if let wakeupThread = state.wakeupThread { let pool = poolUnmanaged.takeUnretainedValue() // Do a lock & unlock on the corresponding thread lock. if wakeupThread != -1 { pool.waitingMutex[wakeupThread].lock() pool.waitingMutex[wakeupThread].unlock() } else { pool.externalWaitingMutex.lock() pool.externalWaitingMutex.unlock() } } return } } } fileprivate struct WorkItemState { var underlying: UInt64 init(_ underlying: UInt64) { self.underlying = underlying } var isDone: Bool { underlying & Self.completedMask != 0 } func markingDone() -> Self { assert(underlying & Self.completedMask == 0) return Self(underlying | Self.completedMask) } var wakeupThread: Int? { if underlying & Self.requiresWakeupMask == 0 { return nil } let tid = underlying & Self.wakeupMask return tid == Self.externalThreadValue ? -1 : Int(tid) } func settingWakeupThread(_ threadId: Int) -> Self { var tmp = self tmp.setWakeupThread(threadId) return tmp } mutating func setWakeupThread(_ threadId: Int) { assert(!isDone) let tid = threadId == -1 ? Self.externalThreadValue : UInt64(threadId) assert(tid & Self.wakeupMask == tid, "\(threadId) -> \(tid) problem") underlying |= (tid | Self.requiresWakeupMask) assert( wakeupThread == threadId, "threadId: \(threadId), wakeup thread: \(String(describing: wakeupThread))" ) } static let requiresWakeupShift: UInt64 = 32 static let requiresWakeupMask: UInt64 = 1 << requiresWakeupShift static let wakeupMask: UInt64 = requiresWakeupMask - 1 static let completedShift: UInt64 = requiresWakeupShift + 1 static let completedMask: UInt64 = 1 << completedShift static let externalThreadValue: UInt64 = wakeupMask } extension WorkItemState: CustomStringConvertible { public var description: String { let wakeupThreadStr: String if let wakeupThread = wakeupThread { wakeupThreadStr = "\(wakeupThread)" } else { wakeupThreadStr = "<none>" } return "WorkItemState(isDone: \(isDone), wakeupThread: \(wakeupThreadStr)))" } } fileprivate enum Constants { // TODO: convert to runtime parameter? (More spinners reduce latency, but cost extra CPU cycles.) static let maxSpinningThreads = 1 /// The number of steal loop spin interations before parking. /// /// Note: this number is divided by the number of threads, to get the spin count for each thread. static let spinCount = 5000 /// The minimum number of active threads before thread pool threads are allowed to spin. static let minActiveThreadsToStartSpinning = 4 }
apache-2.0
5aeb2c9ca4ce463c1d7d7e428f59cd10
36.877794
100
0.672647
4.333504
false
false
false
false
santosli/100-Days-of-Swift-3
Project 34/Project 34/SLSpeakerSegue.swift
1
2100
// // SLSpeakerSegue.swift // Project 34 // // Created by Santos on 24/01/2017. // Copyright © 2017 santos. All rights reserved. // import UIKit class SLSpeakerSegue: UIStoryboardSegue { override func perform() { let fromViewController = source as! ViewController let toViewController = destination as! SLSpeakerViewController let containerView: UIView? = fromViewController.view.superview containerView?.addSubview(toViewController.view) let speakerButton = fromViewController.voiceIconView // Create CAShapeLayerS let rectShape = CAShapeLayer() toViewController.view.layer.mask = rectShape rectShape.fillColor = UIColor.white.cgColor let startShape = UIBezierPath(ovalIn: (speakerButton.frame)).cgPath let endShape = UIBezierPath(arcCenter: speakerButton.center, radius: 500, startAngle: 0, endAngle: CGFloat(M_PI * 2), clockwise: true).cgPath // set initial shape rectShape.path = startShape // animate the `path` let animation = CABasicAnimation(keyPath: "path") animation.fromValue = startShape animation.toValue = endShape animation.duration = 0.2 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) // animation curve is Ease Out animation.fillMode = kCAFillModeBoth // keep to value after finishing animation.isRemovedOnCompletion = false // don't remove after finishing rectShape.add(animation, forKey: animation.keyPath) UIView.animate(withDuration: 0.2, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: { toViewController.redVoiceIconView.frame = CGRect(x: 160, y: 550, width: 60, height: 60) toViewController.redVoiceIconView.alpha = 1.0 }, completion: { finished in let fromVC = self.source let toVC = self.destination fromVC.present(toVC, animated: false, completion: nil) }) } }
apache-2.0
641ead744e5d50de1a797ddbe701da90
35.189655
149
0.664602
5.057831
false
false
false
false
qichen0401/QCUtilitySwift
QCUtilitySwift/Classes/GameCenterManager.swift
1
2116
// // GameCenterManager.swift // Pods // // Created by Qi Chen on 6/28/17. // // import UIKit import GameKit open class GameCenterManager: NSObject, GKGameCenterControllerDelegate { public static let shared = GameCenterManager() open func authenticate() { let localPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = { viewController, error in if let vc = viewController, let rootViewController = UIApplication.rootViewController { rootViewController.present(vc, animated: true, completion: nil) } else if localPlayer.isAuthenticated { print("GameCenterManager authentication succeeded.") } else { print("GameCenterManager authentication failed.") if let err = error { print(err.localizedDescription) } } } } open func report(score s: Int64, leaderboardIdentifier identifier: String) { if GKLocalPlayer.localPlayer().isAuthenticated { let score = GKScore(leaderboardIdentifier: identifier) score.value = s GKScore.report([score]) { (error) in if let err = error { print(err.localizedDescription) } } } } open func showLeaderboard(leaderboardIdentifier identifier: String) { let gameCenterViewController = GKGameCenterViewController() gameCenterViewController.gameCenterDelegate = self gameCenterViewController.viewState = .leaderboards gameCenterViewController.leaderboardIdentifier = identifier if let rootViewController = UIApplication.rootViewController { rootViewController.present(gameCenterViewController, animated: true, completion: nil) } } // MARK: - GKGameCenterControllerDelegate public func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) { gameCenterViewController.dismiss(animated: true, completion: nil) } }
mit
fc277c1cebb3714a742e8bf894919378
34.266667
107
0.646503
5.734417
false
false
false
false
Norod/Filterpedia
Filterpedia/customFilters/FilmicEffects.swift
1
5020
// // FilmicEffects.swift // Filterpedia // // Created by Simon Gladman on 09/02/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import CoreImage // MARKL Bleach Bypass // Based on http://developer.download.nvidia.com/shaderlibrary/webpages/shader_library.html#post_bleach_bypass class BleachBypassFilter: CIFilter { var inputImage : CIImage? var inputAmount = CGFloat(1) override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Bleach Bypass Filter", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputAmount": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 1, kCIAttributeDisplayName: "Amount", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar] ] } override func setDefaults() { inputAmount = 1 } let bleachBypassKernel = CIColorKernel(string: "kernel vec4 bleachBypassFilter(__sample image, float amount) \n" + "{ \n" + " float luma = dot(image.rgb, vec3(0.2126, 0.7152, 0.0722));" + " float l = min(1.0, max (0.0, 10.0 * (luma - 0.45))); \n" + " vec3 result1 = vec3(2.0) * image.rgb * vec3(luma); \n" + " vec3 result2 = 1.0 - 2.0 * (1.0 - luma) * (1.0 - image.rgb); \n" + " vec3 newColor = mix(result1,result2,l); \n" + " return mix(image, vec4(newColor.r, newColor.g, newColor.b, image.a), amount); \n" + "}" ) override var outputImage: CIImage! { guard let inputImage = inputImage, let bleachBypassKernel = bleachBypassKernel else { return nil } let extent = inputImage.extent let arguments = [inputImage, inputAmount] as [Any] return bleachBypassKernel.apply(withExtent: extent, arguments: arguments) } } // MARK: 3 Strip TechnicolorFilter // Based on shader code from http://001.vade.info/ class TechnicolorFilter: CIFilter { var inputImage : CIImage? var inputAmount = CGFloat(1) override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Technicolor Filter", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputAmount": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 1, kCIAttributeDisplayName: "Amount", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar] ] } override func setDefaults() { inputAmount = 1 } let technicolorKernel = CIColorKernel(string: "kernel vec4 technicolorFilter(__sample image, float amount)" + "{" + " vec3 redmatte = 1.0 - vec3(image.r - ((image.g + image.b)/2.0));" + " vec3 greenmatte = 1.0 - vec3(image.g - ((image.r + image.b)/2.0));" + " vec3 bluematte = 1.0 - vec3(image.b - ((image.r + image.g)/2.0)); " + " vec3 red = greenmatte * bluematte * image.r; " + " vec3 green = redmatte * bluematte * image.g; " + " vec3 blue = redmatte * greenmatte * image.b; " + " return mix(image, vec4(red.r, green.g, blue.b, image.a), amount);" + "}" ) override var outputImage: CIImage! { guard let inputImage = inputImage, let technicolorKernel = technicolorKernel else { return nil } let extent = inputImage.extent let arguments = [inputImage, inputAmount] as [Any] return technicolorKernel.apply(withExtent: extent, arguments: arguments) } }
gpl-3.0
c4edeb08933a9c013618d481dfc3ca8c
32.684564
110
0.583383
4.231872
false
false
false
false
appcompany/SwiftSky
Tests/Data Tests/ExtraDataTest.swift
1
3222
// // ExtraDataTest.swift // SwiftSky // // Created by Luca Silverentand on 11/04/2017. // Copyright © 2017 App Company.io. All rights reserved. // import Quick import Nimble @testable import SwiftSky class ExtraDataTest : QuickSpec { override func spec() { describe("pressure") { let pressure = Pressure(500, withUnit: .millibar) context("creation", { it("should have") { expect(pressure.value).to(equal(500)) expect(pressure.unit).to(equal(PressureUnit.millibar)) } }) context("labels", { it("should be") { expect(pressure.label).to(equal("500 mb")) expect(pressure.label(as: .hectopascal)).to(equal("500 hPa")) } }) context("value conversion", { it("should be") { expect(pressure.value(as: .hectopascal)).to(equal(500)) } }) } describe("ozone") { it("should create") { let ozone = Ozone(600) expect(ozone.value).to(equal(600)) expect(ozone.label).to(equal("600 DU")) } } let bearing = Bearing(180) describe("bearing") { it("should create") { expect(bearing.zeroToOne).to(equal(0.5)) expect(bearing.degrees).to(equal(180)) expect(bearing.label).to(equal("180°")) expect(bearing.cardinalLabel).to(equal("S")) } } describe("wind") { it("should have no data") { let wind = Wind(bearing: nil, speed: nil, gust: nil) expect(wind.hasData).to(equal(false)) } it("should have bearing") { let wind = Wind(bearing: bearing, speed: nil, gust: nil) expect(wind.hasData).to(equal(true)) } it("should have speed") { let wind = Wind(bearing: nil, speed: Speed(10, withUnit: .meterPerSecond), gust: nil) expect(wind.hasData).to(equal(true)) } it("should have gust") { let wind = Wind(bearing: nil, speed: nil, gust: Speed(10, withUnit: .meterPerSecond)) expect(wind.hasData).to(equal(true)) } } describe("storm") { it("should have no data") { let wind = Storm(bearing: nil, distance: nil, origin: nil) expect(wind.hasData).to(equal(false)) } it("should have speed") { let wind = Storm(bearing: bearing, distance: nil, origin: nil) expect(wind.hasData).to(equal(true)) } it("should have distance") { let wind = Storm(bearing: nil, distance: Distance(100, withUnit: .meter), origin: nil) expect(wind.hasData).to(equal(true)) } } } }
mit
5824a50f17e0f1facb2425b4509bb848
30.881188
102
0.461801
4.497207
false
false
false
false
esttorhe/Hermes
Hermes/HermesBulletinView.swift
1
10077
import UIKit protocol HermesBulletinViewDelegate: class { func bulletinViewDidClose(bulletinView: HermesBulletinView, explicit: Bool) func bulletinViewNotificationViewForNotification(notification: HermesNotification) -> HermesNotificationView? } let kMargin: CGFloat = 8 let kNotificationHeight: CGFloat = 110 class HermesBulletinView: UIView, UIScrollViewDelegate, HermesNotificationDelegate { weak var delegate: HermesBulletinViewDelegate? var currentNotification: HermesNotification { get { var page = pageFromOffset(scrollView.contentOffset) return notifications[page] } } let scrollView = UIScrollView() var backgroundView: UIVisualEffectView? var currentPage: Int = 0 var timer: NSTimer? var notifications = [HermesNotification]() { didSet { for notification in notifications { notification.delegate = self } layoutNotifications() } } var tabView = UIView() var blurEffectStyle: UIBlurEffectStyle = .Dark { didSet { backgroundView?.removeFromSuperview() if blurEffectStyle == .Dark { tabView.backgroundColor = UIColor(white: 1, alpha: 0.6) } else { tabView.backgroundColor = UIColor(white: 0, alpha: 0.1) } remakeBackgroundView() } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "pan:") addGestureRecognizer(panGestureRecognizer) remakeBackgroundView() scrollView.contentInset = UIEdgeInsetsMake(0, kMargin, 0, kMargin) scrollView.delegate = self addSubview(scrollView) addSubview(tabView) } private func remakeBackgroundView() { let blurEffect = UIBlurEffect(style: blurEffectStyle) backgroundView = UIVisualEffectView(effect: blurEffect) backgroundView?.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin insertSubview(backgroundView!, atIndex: 0) } func pan(gesture: UIPanGestureRecognizer) { timer?.invalidate() var pan = gesture.translationInView(gesture.view!.superview!) var startFrame = bulletinFrameInView(gesture.view!.superview!) var frame = startFrame var dy: CGFloat = 0 var height = gesture.view?.superview!.bounds.size.height var k = height! * 0.2 if pan.y < 0 { pan.y = pan.y / k dy = k * pan.y / (sqrt(pan.y * pan.y + 1)) } else { dy = pan.y } frame.origin.y += dy self.frame = frame if gesture.state == .Ended { var layoutViewFrame = layoutViewFrameInView(gesture.view!.superview!) let velocity = gesture.velocityInView(gesture.view!.superview!) if dy > layoutViewFrame.size.height * 0.5 || velocity.y > 500{ close(explicit: true) } else { animateIn() } } } func animateIn() { var bulletinFrame = bulletinFrameInView(self.superview!) UIView.animateWithDuration(0.4, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.frame = bulletinFrame }, completion: { completed in self.scheduleCloseTimer() }) } func show(view: UIView = (UIApplication.sharedApplication().windows[0] as? UIView)!, animated: Bool = true) { // Add to main queue in case the view loaded but wasn't added to the window yet. This seems to happen in my storyboard test app dispatch_async(dispatch_get_main_queue(),{ view.addSubview(self) var bulletinFrame = self.bulletinFrameInView(self.superview!) var startFrame = bulletinFrame startFrame.origin.y += self.superview!.bounds.size.height self.frame = startFrame self.animateIn() }) } func scheduleCloseTimer() { if currentNotification.autoClose { timer = NSTimer.scheduledTimerWithTimeInterval(currentNotification.autoCloseTimeInterval, target: self, selector: "nextPageOrClose", userInfo: nil, repeats: false) } } func close(#explicit: Bool) { timer?.invalidate() userInteractionEnabled = false var startFrame = bulletinFrameInView(superview!) var offScreenFrame = startFrame offScreenFrame.origin.y = superview!.bounds.size.height UIView.animateWithDuration(0.2, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.frame = offScreenFrame }, completion: { completed in self.removeFromSuperview() self.userInteractionEnabled = true self.delegate?.bulletinViewDidClose(self, explicit: explicit) }) } func contentOffsetForPage(page: Int) -> CGPoint { var boundsWidth = scrollView.bounds.size.width var pageWidth = boundsWidth - 2 * kMargin var contentOffset = CGPointMake(pageWidth * CGFloat(page) - scrollView.contentInset.left, scrollView.contentOffset.y) if contentOffset.x < -scrollView.contentInset.left { contentOffset.x = -scrollView.contentInset.left } else if contentOffset.x + scrollView.contentInset.right + scrollView.bounds.size.width > scrollView.contentSize.width { contentOffset.x = scrollView.contentSize.width - scrollView.bounds.size.width + scrollView.contentInset.right } return contentOffset } func nextPageOrClose() { currentPage = pageFromOffset(scrollView.contentOffset) var boundsWidth = scrollView.bounds.size.width var pageWidth = boundsWidth - 2 * kMargin var totalPages = Int(scrollView.contentSize.width / pageWidth) if currentPage + 1 >= totalPages { close(explicit: false) } else { var newPage = currentPage + 1 CATransaction.begin() scrollView.setContentOffset(contentOffsetForPage(newPage), animated: true) CATransaction.setCompletionBlock({ self.scheduleCloseTimer() }) CATransaction.commit() } } func bulletinFrameInView(view: UIView) -> CGRect { var bulletinFrame = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height * 0.5) var notificationViewFrame = layoutViewFrameInView(view) bulletinFrame.origin = CGPointMake(0, view.bounds.size.height - notificationViewFrame.size.height) return bulletinFrame } func layoutViewFrameInView(view: UIView) -> CGRect { return CGRectMake(0, 0, view.bounds.size.width, kNotificationHeight) } func notificationViewFrameInView(view: UIView) -> CGRect { var frame = layoutViewFrameInView(view) frame.origin.x += kMargin frame.size.width -= kMargin * 2 frame.origin.y += 9 // TODO: configurable frame.size.height -= 9 // TODO: configurable return frame } func layoutNotifications() { // TODO: handle a relayout -- relaying out this view right now adds duplicate noitficationViews if superview == nil { return } var notificationViewFrame = notificationViewFrameInView(superview!) for (i, notification) in enumerate(notifications) { notificationViewFrame.origin.x = CGFloat(i) * notificationViewFrame.size.width var notificationView = delegate?.bulletinViewNotificationViewForNotification(notification) if notificationView == nil { notificationView = HermesDefaultNotificationView() } notificationView!.frame = notificationViewFrame notificationView!.notification = notification if notification.action != nil { var tapGesture = UITapGestureRecognizer(target: self, action: "action:") notificationView?.addGestureRecognizer(tapGesture) } scrollView.addSubview(notificationView!) } scrollView.contentSize = CGSizeMake(CGRectGetMaxX(notificationViewFrame), scrollView.bounds.size.height) } func action(tapGesture: UITapGestureRecognizer) { var notificationView = tapGesture.view as! HermesNotificationView if let notification = notificationView.notification { notification.invokeAction() } } override func layoutSubviews() { backgroundView?.frame = CGRectMake(0, 0, bounds.size.width, superview!.bounds.size.height) scrollView.frame = bounds var tabViewFrame = CGRectMake(0, 4, 40, 2) tabView.frame = tabViewFrame tabView.center = CGPointMake(bounds.size.width / 2, tabView.center.y) layoutNotifications() } func pageFromOffset(offset: CGPoint) -> Int { var boundsWidth = scrollView.bounds.size.width var pageWidth = boundsWidth return Int((offset.x + pageWidth * 0.5) / pageWidth) } // MARK: - Overrides override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { var rect = bounds rect.origin.y -= 44 rect.size.height += 44 return CGRectContainsPoint(rect, point) } // MARK: - UIScrollViewDelegate func scrollViewWillBeginDragging(scrollView: UIScrollView) { timer?.invalidate() currentPage = pageFromOffset(scrollView.contentOffset) } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { var currentPage = self.currentPage var targetOffset = targetContentOffset.memory var targetPage = pageFromOffset(targetOffset) var newPage = currentPage if targetPage > currentPage { newPage++ } else if targetPage < currentPage { newPage-- } targetContentOffset.initialize(self.contentOffsetForPage(newPage)) } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { scheduleCloseTimer() } // MARK: - HermesNotificationDelegate func notificationDidChangeAutoClose(notification: HermesNotification) { if notification == currentNotification { if notification.autoClose { scheduleCloseTimer() } else { timer?.invalidate() } } } }
mit
af25b889593da9b1688de422ad3c86a1
32.257426
171
0.699018
4.847042
false
false
false
false
mobilabsolutions/jenkins-ios
JenkinsiOS/Model/JenkinsAPI/Job/JobListResult.swift
1
923
// // JobListResult.swift // JenkinsiOS // // Created by Robert on 27.10.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import Foundation enum JobListResult { case job(job: Job) case folder(folder: Job) init?(json: [String: AnyObject]) { guard let job = Job(json: json, minimalVersion: true) else { return nil } if job.color == .folder { self = JobListResult.folder(folder: job) } else { self = JobListResult.job(job: job) } } var data: Job { switch self { case let .job(job): return job case let .folder(folder): return folder } } var name: String { return data.name } var url: URL { return data.url } var color: JenkinsColor? { return data.color } var description: String? { return data.description } }
mit
38ffb86dfcdc8b29bc522dad7c5e49ef
18.208333
61
0.557484
3.90678
false
false
false
false
cfraz89/RxSwift
RxSwift/Observables/Implementations/Merge.swift
1
13378
// // Merge.swift // RxSwift // // Created by Krunoslav Zaher on 3/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // // MARK: Limited concurrency version final class MergeLimitedSinkIter<S: ObservableConvertibleType, O: ObserverType> : ObserverType , LockOwnerType , SynchronizedOnType where S.E == O.E { typealias E = O.E typealias DisposeKey = CompositeDisposable.DisposeKey typealias Parent = MergeLimitedSink<S, O> private let _parent: Parent private let _disposeKey: DisposeKey var _lock: RecursiveLock { return _parent._lock } init(parent: Parent, disposeKey: DisposeKey) { _parent = parent _disposeKey = disposeKey } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next: _parent.forwardOn(event) case .error: _parent.forwardOn(event) _parent.dispose() case .completed: _parent._group.remove(for: _disposeKey) if let next = _parent._queue.dequeue() { _parent.subscribe(next, group: _parent._group) } else { _parent._activeCount = _parent._activeCount - 1 if _parent._stopped && _parent._activeCount == 0 { _parent.forwardOn(.completed) _parent.dispose() } } } } } final class MergeLimitedSink<S: ObservableConvertibleType, O: ObserverType> : Sink<O> , ObserverType , LockOwnerType , SynchronizedOnType where S.E == O.E { typealias E = S typealias QueueType = Queue<S> fileprivate let _maxConcurrent: Int let _lock = RecursiveLock() // state fileprivate var _stopped = false fileprivate var _activeCount = 0 fileprivate var _queue = QueueType(capacity: 2) fileprivate let _sourceSubscription = SingleAssignmentDisposable() fileprivate let _group = CompositeDisposable() init(maxConcurrent: Int, observer: O, cancel: Cancelable) { _maxConcurrent = maxConcurrent let _ = _group.insert(_sourceSubscription) super.init(observer: observer, cancel: cancel) } func run(_ source: Observable<S>) -> Disposable { let _ = _group.insert(_sourceSubscription) let disposable = source.subscribe(self) _sourceSubscription.setDisposable(disposable) return _group } func subscribe(_ innerSource: E, group: CompositeDisposable) { let subscription = SingleAssignmentDisposable() let key = group.insert(subscription) if let key = key { let observer = MergeLimitedSinkIter(parent: self, disposeKey: key) let disposable = innerSource.asObservable().subscribe(observer) subscription.setDisposable(disposable) } } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next(let value): let subscribe: Bool if _activeCount < _maxConcurrent { _activeCount += 1 subscribe = true } else { _queue.enqueue(value) subscribe = false } if subscribe { self.subscribe(value, group: _group) } case .error(let error): forwardOn(.error(error)) dispose() case .completed: if _activeCount == 0 { forwardOn(.completed) dispose() } else { _sourceSubscription.dispose() } _stopped = true } } } final class MergeLimited<S: ObservableConvertibleType> : Producer<S.E> { private let _source: Observable<S> private let _maxConcurrent: Int init(source: Observable<S>, maxConcurrent: Int) { _source = source _maxConcurrent = maxConcurrent } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { let sink = MergeLimitedSink<S, O>(maxConcurrent: _maxConcurrent, observer: observer, cancel: cancel) let subscription = sink.run(_source) return (sink: sink, subscription: subscription) } } // MARK: Merge final class MergeBasicSink<S: ObservableConvertibleType, O: ObserverType> : MergeSink<S, S, O> where O.E == S.E { override init(observer: O, cancel: Cancelable) { super.init(observer: observer, cancel: cancel) } override func performMap(_ element: S) throws -> S { return element } } // MARK: flatMap final class FlatMapSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : MergeSink<SourceType, S, O> where O.E == S.E { typealias Selector = (SourceType) throws -> S private let _selector: Selector init(selector: @escaping Selector, observer: O, cancel: Cancelable) { _selector = selector super.init(observer: observer, cancel: cancel) } override func performMap(_ element: SourceType) throws -> S { return try _selector(element) } } final class FlatMapWithIndexSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : MergeSink<SourceType, S, O> where O.E == S.E { typealias Selector = (SourceType, Int) throws -> S private var _index = 0 private let _selector: Selector init(selector: @escaping Selector, observer: O, cancel: Cancelable) { _selector = selector super.init(observer: observer, cancel: cancel) } override func performMap(_ element: SourceType) throws -> S { return try _selector(element, try incrementChecked(&_index)) } } // MARK: FlatMapFirst final class FlatMapFirstSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : MergeSink<SourceType, S, O> where O.E == S.E { typealias Selector = (SourceType) throws -> S private let _selector: Selector override var subscribeNext: Bool { return _group.count == MergeNoIterators } init(selector: @escaping Selector, observer: O, cancel: Cancelable) { _selector = selector super.init(observer: observer, cancel: cancel) } override func performMap(_ element: SourceType) throws -> S { return try _selector(element) } } // It's value is one because initial source subscription is always in CompositeDisposable private let MergeNoIterators = 1 final class MergeSinkIter<SourceType, S: ObservableConvertibleType, O: ObserverType> : ObserverType where O.E == S.E { typealias Parent = MergeSink<SourceType, S, O> typealias DisposeKey = CompositeDisposable.DisposeKey typealias E = O.E private let _parent: Parent private let _disposeKey: DisposeKey init(parent: Parent, disposeKey: DisposeKey) { _parent = parent _disposeKey = disposeKey } func on(_ event: Event<E>) { switch event { case .next(let value): _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { _parent.forwardOn(.next(value)) // } case .error(let error): _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { _parent.forwardOn(.error(error)) _parent.dispose() // } case .completed: _parent._group.remove(for: _disposeKey) // If this has returned true that means that `Completed` should be sent. // In case there is a race who will sent first completed, // lock will sort it out. When first Completed message is sent // it will set observer to nil, and thus prevent further complete messages // to be sent, and thus preserving the sequence grammar. if _parent._stopped && _parent._group.count == MergeNoIterators { _parent._lock.lock(); defer { _parent._lock.unlock() } // lock { _parent.forwardOn(.completed) _parent.dispose() // } } } } } class MergeSink<SourceType, S: ObservableConvertibleType, O: ObserverType> : Sink<O> , ObserverType where O.E == S.E { typealias ResultType = O.E typealias Element = SourceType fileprivate let _lock = RecursiveLock() fileprivate var subscribeNext: Bool { return true } // state fileprivate let _group = CompositeDisposable() fileprivate let _sourceSubscription = SingleAssignmentDisposable() fileprivate var _stopped = false override init(observer: O, cancel: Cancelable) { super.init(observer: observer, cancel: cancel) } func performMap(_ element: SourceType) throws -> S { rxAbstractMethod() } func on(_ event: Event<SourceType>) { switch event { case .next(let element): if !subscribeNext { return } do { let value = try performMap(element) subscribeInner(value.asObservable()) } catch let e { forwardOn(.error(e)) dispose() } case .error(let error): _lock.lock(); defer { _lock.unlock() } // lock { forwardOn(.error(error)) dispose() // } case .completed: _lock.lock(); defer { _lock.unlock() } // lock { _stopped = true if _group.count == MergeNoIterators { forwardOn(.completed) dispose() } else { _sourceSubscription.dispose() } //} } } func subscribeInner(_ source: Observable<O.E>) { let iterDisposable = SingleAssignmentDisposable() if let disposeKey = _group.insert(iterDisposable) { let iter = MergeSinkIter(parent: self, disposeKey: disposeKey) let subscription = source.subscribe(iter) iterDisposable.setDisposable(subscription) } } func run(_ source: Observable<SourceType>) -> Disposable { let _ = _group.insert(_sourceSubscription) let subscription = source.subscribe(self) _sourceSubscription.setDisposable(subscription) return _group } } // MARK: Producers final class FlatMap<SourceType, S: ObservableConvertibleType>: Producer<S.E> { typealias Selector = (SourceType) throws -> S private let _source: Observable<SourceType> private let _selector: Selector init(source: Observable<SourceType>, selector: @escaping Selector) { _source = source _selector = selector } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { let sink = FlatMapSink(selector: _selector, observer: observer, cancel: cancel) let subscription = sink.run(_source) return (sink: sink, subscription: subscription) } } final class FlatMapWithIndex<SourceType, S: ObservableConvertibleType>: Producer<S.E> { typealias Selector = (SourceType, Int) throws -> S private let _source: Observable<SourceType> private let _selector: Selector init(source: Observable<SourceType>, selector: @escaping Selector) { _source = source _selector = selector } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { let sink = FlatMapWithIndexSink<SourceType, S, O>(selector: _selector, observer: observer, cancel: cancel) let subscription = sink.run(_source) return (sink: sink, subscription: subscription) } } final class FlatMapFirst<SourceType, S: ObservableConvertibleType>: Producer<S.E> { typealias Selector = (SourceType) throws -> S private let _source: Observable<SourceType> private let _selector: Selector init(source: Observable<SourceType>, selector: @escaping Selector) { _source = source _selector = selector } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { let sink = FlatMapFirstSink<SourceType, S, O>(selector: _selector, observer: observer, cancel: cancel) let subscription = sink.run(_source) return (sink: sink, subscription: subscription) } } final class Merge<S: ObservableConvertibleType> : Producer<S.E> { private let _source: Observable<S> init(source: Observable<S>) { _source = source } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == S.E { let sink = MergeBasicSink<S, O>(observer: observer, cancel: cancel) let subscription = sink.run(_source) return (sink: sink, subscription: subscription) } }
mit
7b612afd64de19739e35d2f1408fab98
30.699052
140
0.600583
4.683824
false
false
false
false