hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
0edfb8c410337a01ff56d71f114479174b8bf13e
13,088
// // TSSwitchPayInfoView.swift // ThinkSNS + // // Created by lip on 2017/7/11. // Copyright © 2017年 ZhiYiCX. All rights reserved. // import UIKit import SnapKit protocol TSSwitchPayInfoViewDelegate: class { func paySwitchValueChanged(_ paySwitch: UISwitch) func fieldBeginEditing() -> Void func fieldEndEditing() -> Void } extension TSSwitchPayInfoViewDelegate { func fieldBeginEditing() -> Void { } func fieldEndEditing() -> Void { } } class TSSwitchPayInfoView: UIView { // MARK: - /// 是否隐藏更多信息 var isHiddenMoreInfo: Bool = false /// 是否开启了收费开关 var paySwitchIsOn: Bool { return self.paySwitch.isOn } /// 配置后的支付价格 var payPrice: Int = 0 /// 代理 weak var delegate: TSSwitchPayInfoViewDelegate? // MARK: - ui // MARK: 开关容器 /// 开关容器视图 private weak var switchContentView: UIView! // 开关容器视图的顶部线条 private weak var topLine: UIView! /// 开关容器内的信息标签 private weak var switchInfoLabel: UILabel! /// 开关容器内的开关 weak var paySwitch: UISwitch! // 开关容器视图的低部线条 private weak var bottomLine: UIView! // MARK: 支付详细配置 /// 支付详情容器视图 private weak var detailContentView: UIView! /// 支付详细配置 private weak var settingInfoLabel: UILabel! /// 支付按钮组 private var payMentBtns: Array<UIButton>! /// 中间的线条 private weak var midLine: UIView! /// 底部的线条 private weak var footLine: UIView! /// 详情内输入框提示标签 private weak var promptLeftInfoLabel: UILabel! /// 详情内输入框提示标签 private weak var promptRightInfoLabel: UILabel! /// 金额输入框 private(set) weak var priceTextField: UITextField! /// 备注信息 private weak var remarkLabel: UILabel! // MARK: - lifecycle init() { super.init(frame: CGRect.zero) self.createUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() self.createUI() } // MARK: - func func priceTextFieldResignFirstResponder() { priceTextField.resignFirstResponder() } @objc private func paySwitchValueChanged(_ paySwitch: UISwitch) { priceTextFieldResignFirstResponder() delegate?.paySwitchValueChanged(paySwitch) guard isHiddenMoreInfo == false else { return } payPrice = 0 for btn in payMentBtns { btn.isEnabled = true btn.layer.borderColor = TSColor.normal.imagePlaceholder.cgColor } detailContentView.isHidden = !paySwitch.isOn bottomLine.isHidden = paySwitch.isOn } @objc private func priceBtnTaped(_ priceBtn: UIButton) { priceTextFieldResignFirstResponder() if priceTextField.text != nil { priceTextField.text = nil } for (index, btn) in payMentBtns.enumerated() { btn.isEnabled = true btn.layer.borderColor = TSColor.normal.imagePlaceholder.cgColor if priceBtn == btn { payPrice = TSAppConfig.share.localInfo.feedItems[index] } } priceBtn.isEnabled = false priceBtn.layer.borderColor = TSColor.main.theme.cgColor } @objc private func userInputPrice(_ priceTextField: UITextField) { let str: String = priceTextField.text ?? "0" if str.isEmpty == false { TSAccountRegex.checkAndUplodTextFieldText(textField: priceTextField, stringCountLimit: 8) payPrice = Int(str)! for btn in payMentBtns { btn.isEnabled = true btn.layer.borderColor = TSColor.normal.imagePlaceholder.cgColor } if str.first == "0" || !TSAccountRegex.isPayMoneyFormat(str) { payPrice = 0 priceTextField.text = nil } } } // MARK: - init and layout override func layoutSubviews() { super.layoutSubviews() switchContentView.snp.makeConstraints { (make) in make.height.equalTo(50) make.top.equalTo(self.snp.top) make.left.equalTo(self.snp.left) make.right.equalTo(self.snp.right) } topLine.snp.makeConstraints { (line) in line.height.equalTo(0.5) line.top.equalTo(switchContentView.snp.top) line.left.equalTo(switchContentView.snp.left) line.right.equalTo(switchContentView.snp.right) } switchInfoLabel.snp.makeConstraints { (make) in make.centerY.equalTo(switchContentView.snp.centerY) make.left.equalTo(switchContentView.snp.left).offset(25) } paySwitch.snp.makeConstraints { (make) in // make.height.equalTo(switchContentView.snp.height) make.centerY.equalTo(switchContentView.snp.centerY) make.right.equalTo(switchContentView.snp.right).offset(-11.5) } bottomLine.snp.makeConstraints { (line) in line.height.equalTo(0.5) line.bottom.equalTo(switchContentView.snp.bottom) line.left.equalTo(switchContentView.snp.left) line.right.equalTo(switchContentView.snp.right) } detailContentView.snp.makeConstraints { (make) in make.top.equalTo(switchContentView.snp.bottom) make.bottom.equalTo(self.snp.bottom) make.left.equalToSuperview() make.right.equalToSuperview() } settingInfoLabel.snp.makeConstraints { (make) in make.top.equalTo(detailContentView.snp.top).offset(19) make.left.equalTo(detailContentView.snp.left).offset(15) } for (index, btn) in payMentBtns.enumerated() { let btnWidth = (ScreenSize.ScreenWidth - CGFloat(payMentBtns.count + 1) * 15 ) / CGFloat(payMentBtns.count) let btnLeftSpace = CGFloat(index) * btnWidth + 15 * CGFloat(index + 1) btn.snp.makeConstraints({ (make) in make.top.equalTo(detailContentView.snp.top).offset(46.5) make.size.equalTo(CGSize(width: btnWidth, height: 35)) make.left.equalTo(detailContentView.snp.left).offset(btnLeftSpace) }) } midLine.snp.makeConstraints { (line) in line.top.equalTo(detailContentView.snp.top).offset(101.5) line.left.equalToSuperview() line.right.equalToSuperview() line.height.equalTo(0.5) } footLine.snp.makeConstraints { (line) in line.top.equalTo(midLine.snp.bottom).offset(49.5) line.left.equalToSuperview() line.right.equalToSuperview() line.height.equalTo(0.5) } promptLeftInfoLabel.snp.makeConstraints { (make) in make.top.equalTo(detailContentView).offset(17.5 + 102) make.left.equalTo(detailContentView).offset(15) } promptRightInfoLabel.snp.makeConstraints { (make) in make.top.equalTo(promptLeftInfoLabel) make.height.equalTo(14) make.right.equalTo(detailContentView.snp.right).offset(-15.5) } priceTextField.snp.makeConstraints { (make) in make.top.equalTo(promptLeftInfoLabel.snp.top).offset(-2) make.right.equalTo(promptRightInfoLabel.snp.left).offset(-9) make.left.equalTo(promptLeftInfoLabel.snp.right).offset(9) } remarkLabel.snp.makeConstraints { (make) in make.top.equalTo(footLine.snp.bottom).offset(15) make.left.equalTo(detailContentView).offset(15) } } private func createUI() { // 开关容器视图 let switchContentView = UIView() switchContentView.backgroundColor = UIColor.white self.switchContentView = switchContentView // 顶部线条 let topLine = UIView() topLine.backgroundColor = TSColor.inconspicuous.disabled self.topLine = topLine // 开关信息标签 let switchInfoLabel = UILabel() switchInfoLabel.text = "是否收费" switchInfoLabel.font = UIFont.systemFont(ofSize: TSFont.ContentText.text.rawValue) switchInfoLabel.textColor = TSColor.normal.blackTitle self.switchInfoLabel = switchInfoLabel // 开关 let paySwitch = UISwitch() paySwitch.transform = CGAffineTransform(scaleX: 0.7, y: 0.7) paySwitch.isOn = false paySwitch.addTarget(self, action: #selector(paySwitchValueChanged(_:)), for: .valueChanged) self.paySwitch = paySwitch // 顶部线条 let bottomLine = UIView() bottomLine.backgroundColor = TSColor.inconspicuous.disabled self.bottomLine = bottomLine self.addSubview(switchContentView) switchContentView.addSubview(topLine) switchContentView.addSubview(switchInfoLabel) switchContentView.addSubview(paySwitch) switchContentView.addSubview(bottomLine) // 支付详情容器视图 let detailContentView = UIView() detailContentView.isHidden = true switchContentView.backgroundColor = UIColor.white self.detailContentView = detailContentView // 支付详细配置标签 let settingInfoLabel = UILabel() settingInfoLabel.text = "设置文字收费金额" settingInfoLabel.textColor = TSColor.normal.minor settingInfoLabel.font = UIFont.systemFont(ofSize: TSFont.ContentText.sectionTitle.rawValue) self.settingInfoLabel = settingInfoLabel // 支付按钮 payMentBtns = [UIButton]() for price in TSAppConfig.share.localInfo.feedItems { payMentBtns.append(self.custom(pricebtn: "\(price)")) } // 中间的线条 let midLine = UIView() midLine.backgroundColor = TSColor.inconspicuous.disabled self.midLine = midLine // 底部的线条 let footLine = UIView() footLine.backgroundColor = TSColor.inconspicuous.disabled self.footLine = footLine // 详情内输入框提示标签 let promptLeftInfoLabel = UILabel() promptLeftInfoLabel.text = "自定义金额" promptLeftInfoLabel.font = UIFont.systemFont(ofSize: TSFont.ContentText.text.rawValue) promptLeftInfoLabel.textColor = TSColor.normal.blackTitle self.promptLeftInfoLabel = promptLeftInfoLabel // 详情内输入框提示标签 let promptRightInfoLabel = UILabel() promptRightInfoLabel.text = TSAppConfig.share.localInfo.goldName promptRightInfoLabel.font = UIFont.systemFont(ofSize: TSFont.ContentText.text.rawValue) promptRightInfoLabel.textColor = TSColor.normal.blackTitle self.promptRightInfoLabel = promptRightInfoLabel // 金额输入框 let priceTextField = UITextField() priceTextField.placeholder = "输入金额" priceTextField.keyboardType = .numberPad priceTextField.textAlignment = .right priceTextField.font = UIFont.systemFont(ofSize: TSFont.ContentText.text.rawValue) priceTextField.textColor = TSColor.normal.blackTitle priceTextField.delegate = self priceTextField.addTarget(self, action: #selector(userInputPrice(_:)), for: .allEditingEvents) self.priceTextField = priceTextField // 备注信息 let remarkLabel = UILabel() remarkLabel.textColor = TSColor.normal.minor remarkLabel.text = "注:超过" + "\(TSAppConfig.share.localInfo.feedLimit)" + "字部分内容收费" remarkLabel.font = UIFont.systemFont(ofSize: TSFont.ContentText.sectionTitle.rawValue) self.remarkLabel = remarkLabel self.addSubview(detailContentView) detailContentView.addSubview(settingInfoLabel) for btn in payMentBtns { detailContentView.addSubview(btn) } detailContentView.addSubview(midLine) detailContentView.addSubview(footLine) detailContentView.addSubview(promptLeftInfoLabel) detailContentView.addSubview(promptRightInfoLabel) detailContentView.addSubview(priceTextField) detailContentView.addSubview(remarkLabel) } private func custom(pricebtn withPrice: String) -> UIButton { let priceBtn = UIButton(type: .custom) priceBtn.addTarget(self, action: #selector(priceBtnTaped(_:)), for: .touchUpInside) priceBtn.setTitle(withPrice, for: .normal) priceBtn.setTitleColor(TSColor.normal.blackTitle, for: .normal) priceBtn.setTitleColor(TSColor.main.theme, for: .disabled) priceBtn.setTitleColor(TSColor.normal.blackTitle, for: .normal) priceBtn.setTitleColor(TSColor.main.theme, for: .disabled) priceBtn.backgroundColor = TSColor.main.white priceBtn.clipsToBounds = true priceBtn.layer.cornerRadius = 6 priceBtn.layer.borderColor = TSColor.normal.imagePlaceholder.cgColor priceBtn.layer.borderWidth = 0.5 return priceBtn } } extension TSSwitchPayInfoView: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { self.delegate?.fieldBeginEditing() } func textFieldDidEndEditing(_ textField: UITextField) { self.delegate?.fieldEndEditing() } }
37.181818
119
0.650061
1655eb0fd203419250492ba9131d4a3581b6a59a
10,468
// LNICoverFlowLayout.swift // // The MIT License (MIT) // // Copyright (c) 2017 Loud Noise Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit /** Collection Flow Layout in Swift 3. Adds cover flow effect to collection view scrolling. Currently supports only horizontal flow direction. */ open class LNICoverFlowLayout:UICollectionViewFlowLayout { /** * Maximum degree that can be applied to individual item. * Default to 45 degrees. */ open var maxCoverDegree:CGFloat = 45 { didSet { if maxCoverDegree < -360 { maxCoverDegree = -360 } else if maxCoverDegree > 360 { maxCoverDegree = 360 } } } /** * Determines how elements covers each other. * Should be in range 0..1. * Default to 0.25. * Examples: * 0 means that items are placed within a continuous line. * 0.5 means that half of 3rd and 1st item will be behind 2nd. */ open var coverDensity:CGFloat = 0.25 { didSet { if coverDensity < 0 { coverDensity = 0 } else if coverDensity > 1 { coverDensity = 1 } } } /** * Min opacity that can be applied to individual item. * Default to 1.0 (alpha 100%). */ open var minCoverOpacity:CGFloat = 1.0 { didSet { if minCoverOpacity < 0 { minCoverOpacity = 0 } else if minCoverOpacity > 1 { minCoverOpacity = 1 } } } /** * Min scale that can be applied to individual item. * Default to 1.0 (no scale). */ open var minCoverScale:CGFloat = 1.0 { didSet { if minCoverScale < 0 { minCoverScale = 0 } else if minCoverScale > 1 { minCoverScale = 1 } } } // Private Constant. Not a good naming convention but keeping as close to inspiration as possible fileprivate let kDistanceToProjectionPlane:CGFloat = 500.0 // MARK: Overrides // Thanks to property initializations we do not need to override init(*) override open func prepare() { super.prepare() assert(self.collectionView?.numberOfSections == 1, "[LNICoverFlowLayout]: Multiple sections are not supported") assert(self.scrollDirection == .horizontal, "[LNICoverFlowLayout]: Vertical scrolling is not supported") } override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let idxPaths = indexPathsContainedInRect(rect) var resultingAttributes = [UICollectionViewLayoutAttributes]() for path in idxPaths { resultingAttributes.append(layoutAttributesForItem(at: path)) } return resultingAttributes } override open func layoutAttributesForItem(at indexPath:IndexPath)->UICollectionViewLayoutAttributes { let attributes = UICollectionViewLayoutAttributes(forCellWith:indexPath) attributes.size = self.itemSize attributes.center = CGPoint(x: collectionViewWidth()*CGFloat(indexPath.row) + collectionViewWidth(), y: collectionViewHeight()/2) let contentOffsetX = collectionView?.contentOffset.x ?? 0 return interpolateAttributes(attributes, forOffset: contentOffsetX) } override open var collectionViewContentSize : CGSize { if let collectionView = collectionView { return CGSize(width: collectionView.bounds.size.width * CGFloat(collectionView.numberOfItems(inSection: 0)), height: collectionView.bounds.size.height) } return CGSize.zero } // MARK: Accessors fileprivate func collectionViewHeight() -> CGFloat { let height = collectionView?.bounds.size.height ?? 0 return height } fileprivate func collectionViewWidth() -> CGFloat { let width = collectionView?.bounds.size.width ?? 0 return width } // MARK: Private fileprivate func itemCenterForRow(_ row:Int)->CGPoint { let collectionViewSize = collectionView?.bounds.size ?? CGSize.zero return CGPoint(x: CGFloat(row) * collectionViewSize.width + collectionViewSize.width / 2, y: collectionViewSize.height/2) } fileprivate func minXForRow(_ row:Int)->CGFloat { return itemCenterForRow(row - 1).x + (1.0 / 2 - self.coverDensity) * self.itemSize.width } fileprivate func maxXForRow(_ row:Int)->CGFloat { return itemCenterForRow(row + 1).x - (1.0 / 2 - self.coverDensity) * self.itemSize.width } fileprivate func minXCenterForRow(_ row:Int)->CGFloat { let halfWidth = self.itemSize.width / 2 let maxRads = degreesToRad(self.maxCoverDegree) let center = itemCenterForRow(row - 1).x let prevItemRightEdge = center + halfWidth let projectedLeftEdgeLocal = halfWidth * cos(maxRads) * kDistanceToProjectionPlane / (kDistanceToProjectionPlane + halfWidth * sin(maxRads)) return prevItemRightEdge - (self.coverDensity * self.itemSize.width) + projectedLeftEdgeLocal + minimumInteritemSpacing } fileprivate func maxXCenterForRow(_ row:Int)->CGFloat { let halfWidth = self.itemSize.width / 2 let maxRads = degreesToRad(self.maxCoverDegree) let center = itemCenterForRow(row + 1).x let nextItemLeftEdge = center - halfWidth let projectedRightEdgeLocal = fabs(halfWidth * cos(maxRads) * kDistanceToProjectionPlane / (-halfWidth * sin(maxRads) - kDistanceToProjectionPlane)) return nextItemLeftEdge + (self.coverDensity * self.itemSize.width) - projectedRightEdgeLocal - minimumInteritemSpacing } fileprivate func degreesToRad(_ degrees:CGFloat)->CGFloat { return CGFloat(Double(degrees) * .pi / 180) } fileprivate func indexPathsContainedInRect(_ rect:CGRect)->[IndexPath] { let noI = collectionView?.numberOfItems(inSection: 0) ?? 0 if noI == 0 { return [] } let cvW = collectionViewWidth() // Find min and max rows that can be determined for sure var minRow = Int(max(rect.origin.x/cvW, 0)) var maxRow = 0 if cvW != 0 { maxRow = Int(rect.maxX / cvW) } // Additional check for rows that also can be included (our rows are moving depending on content size) let candidateMinRow = max(minRow-1, 0) if maxXForRow(candidateMinRow) >= rect.origin.x { minRow = candidateMinRow } let candidateMaxRow = min(maxRow + 1, noI - 1) if minXForRow(candidateMaxRow) <= rect.maxX { maxRow = candidateMaxRow } // Simply add index paths between min and max. var resultingIdxPaths = [IndexPath]() // Fix for 1-item collections - see issue #8 - Thanks gstrobl17 if maxRow > 0 && (minRow < maxRow || noI != 1) { for i in minRow...maxRow { resultingIdxPaths.append(IndexPath(row: i, section: 0)) } } else { resultingIdxPaths = [IndexPath(row: 0, section: 0)] } return resultingIdxPaths } fileprivate func interpolateAttributes(_ attributes:UICollectionViewLayoutAttributes, forOffset offset:CGFloat)->UICollectionViewLayoutAttributes { let attributesPath = attributes.indexPath let minInterval = CGFloat(attributesPath.row - 1) * collectionViewWidth() let maxInterval = CGFloat(attributesPath.row + 1) * collectionViewWidth() let minX = minXCenterForRow(attributesPath.row) let maxX = maxXCenterForRow(attributesPath.row) let spanX = maxX - minX // Interpolate by formula let interpolatedX = min(max(minX + ((spanX / (maxInterval - minInterval)) * (offset - minInterval)), minX), maxX) attributes.center = CGPoint(x: interpolatedX, y: attributes.center.y) var transform = CATransform3DIdentity // Add perspective transform.m34 = -1.0 / kDistanceToProjectionPlane // Then rotate. let angle = -self.maxCoverDegree + (interpolatedX - minX) * 2 * self.maxCoverDegree / spanX transform = CATransform3DRotate(transform, degreesToRad(angle), 0, 1, 0) // Then scale: 1 - abs(1 - Q - 2 * x * (1 - Q)) let scale = 1.0 - abs(1 - self.minCoverScale - (interpolatedX - minX) * 2 * (1.0 - self.minCoverScale) / spanX) transform = CATransform3DScale(transform, scale, scale, scale) // Apply transform attributes.transform3D = transform // Add opacity: 1 - abs(1 - Q - 2 * x * (1 - Q)) let opacity = 1.0 - abs(1 - self.minCoverOpacity - (interpolatedX - minX) * 2 * (1 - self.minCoverOpacity) / spanX) attributes.alpha = opacity // print(String(format:"IDX: %d. MinX: %.2f. MaxX: %.2f. Interpolated: %.2f. Interpolated angle: %.2f", // attributesPath.row, // minX, // maxX, // interpolatedX, // angle)); return attributes } }
36.096552
156
0.635365
2f83f31dceb2419e93d1cb5871ec3edcbc208d9e
4,836
import Nimble import UIKit func allContentSizeCategories() -> [UIContentSizeCategory] { return [ .extraSmall, .small, .medium, .large, .extraLarge, .extraExtraLarge, .extraExtraExtraLarge, .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge ] } func shortCategoryName(_ category: UIContentSizeCategory) -> String { return category.rawValue.replacingOccurrences(of: "UICTContentSizeCategory", with: "") } func combinePredicates<T>(_ predicates: [Predicate<T>], ignoreFailures: Bool = false, deferred: (() -> Void)? = nil) -> Predicate<T> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in defer { deferred?() } return try predicates.reduce(true) { acc, matcher -> Bool in guard acc || ignoreFailures else { return false } let result = try matcher.matches(actualExpression, failureMessage: failureMessage) return result && acc } } } public func haveValidDynamicTypeSnapshot(named name: String? = nil, usesDrawRect: Bool = false, tolerance: CGFloat? = nil, sizes: [UIContentSizeCategory] = allContentSizeCategories(), isDeviceAgnostic: Bool = false) -> Predicate<Snapshotable> { let mock = NBSMockedApplication() let predicates: [Predicate<Snapshotable>] = sizes.map { category in let sanitizedName = sanitizedTestName(name) let nameWithCategory = "\(sanitizedName)_\(shortCategoryName(category))" return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in mock.mockPreferredContentSizeCategory(category) updateTraitCollection(on: actualExpression) let predicate: Predicate<Snapshotable> if isDeviceAgnostic { predicate = haveValidDeviceAgnosticSnapshot(named: nameWithCategory, usesDrawRect: usesDrawRect, tolerance: tolerance) } else { predicate = haveValidSnapshot(named: nameWithCategory, usesDrawRect: usesDrawRect, tolerance: tolerance) } return try predicate.matches(actualExpression, failureMessage: failureMessage) } } return combinePredicates(predicates) { mock.stopMockingPreferredContentSizeCategory() } } public func recordDynamicTypeSnapshot(named name: String? = nil, usesDrawRect: Bool = false, sizes: [UIContentSizeCategory] = allContentSizeCategories(), isDeviceAgnostic: Bool = false) -> Predicate<Snapshotable> { let mock = NBSMockedApplication() let predicates: [Predicate<Snapshotable>] = sizes.map { category in let sanitizedName = sanitizedTestName(name) let nameWithCategory = "\(sanitizedName)_\(shortCategoryName(category))" return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in mock.mockPreferredContentSizeCategory(category) updateTraitCollection(on: actualExpression) let predicate: Predicate<Snapshotable> if isDeviceAgnostic { predicate = recordDeviceAgnosticSnapshot(named: nameWithCategory, usesDrawRect: usesDrawRect) } else { predicate = recordSnapshot(named: nameWithCategory, usesDrawRect: usesDrawRect) } return try predicate.matches(actualExpression, failureMessage: failureMessage) } } return combinePredicates(predicates, ignoreFailures: true) { mock.stopMockingPreferredContentSizeCategory() } } private func updateTraitCollection(on expression: Expression<Snapshotable>) { // swiftlint:disable:next force_try force_unwrapping let instance = try! expression.evaluate()! updateTraitCollection(on: instance) } private func updateTraitCollection(on element: Snapshotable) { if let environment = element as? UITraitEnvironment { if let vc = environment as? UIViewController { vc.beginAppearanceTransition(true, animated: false) vc.endAppearanceTransition() } environment.traitCollectionDidChange(nil) if let view = environment as? UIView { view.subviews.forEach(updateTraitCollection(on:)) } else if let vc = environment as? UIViewController { vc.childViewControllers.forEach(updateTraitCollection(on:)) if vc.isViewLoaded { updateTraitCollection(on: vc.view) } } } }
39.966942
120
0.647022
91bdc9cce91b4a2c63cab7329daae817b97a1e30
318
// // FavoriteBooks.swift // NYTBestsellers // // Created by Manny Yusuf on 2/8/19. // Copyright © 2019 Pursuit. All rights reserved. // import Foundation struct FavoriteBooks: Codable { let imageData: Data let author: String let description: String let createdAt: String let title: String }
17.666667
50
0.688679
bf0a43a540f11deb9d7ca15cf081eb5182179819
1,413
// // Double Extensions Tests.swift // MIDIKit • https://github.com/orchetect/MIDIKit // #if !os(watchOS) import XCTest @testable import MIDIKit final class DoubleExtensions_Tests: XCTestCase { func testInitBipolarUnitInterval_Float() { XCTAssertEqual(Double(bipolarUnitInterval: Float(-1.0)), 0.00) XCTAssertEqual(Double(bipolarUnitInterval: Float(-0.5)), 0.25) XCTAssertEqual(Double(bipolarUnitInterval: Float( 0.0)), 0.50) XCTAssertEqual(Double(bipolarUnitInterval: Float( 0.5)), 0.75) XCTAssertEqual(Double(bipolarUnitInterval: Float( 1.0)), 1.00) } func testInitBipolarUnitInterval_Double() { XCTAssertEqual(Double(bipolarUnitInterval: -1.0), 0.00) XCTAssertEqual(Double(bipolarUnitInterval: -0.5), 0.25) XCTAssertEqual(Double(bipolarUnitInterval: 0.0), 0.50) XCTAssertEqual(Double(bipolarUnitInterval: 0.5), 0.75) XCTAssertEqual(Double(bipolarUnitInterval: 1.0), 1.00) } func testBipolarUnitIntervalValue() { XCTAssertEqual(0.00.bipolarUnitIntervalValue, -1.0) XCTAssertEqual(0.25.bipolarUnitIntervalValue, -0.5) XCTAssertEqual(0.50.bipolarUnitIntervalValue, 0.0) XCTAssertEqual(0.75.bipolarUnitIntervalValue, 0.5) XCTAssertEqual(1.00.bipolarUnitIntervalValue, 1.0) } } #endif
30.717391
70
0.665959
08faea9d733fd5f84a09a34344d2725970d8a891
7,476
// // Services.swift // PHP Monitor // // Copyright © 2021 Nico Verbruggen. All rights reserved. // import Foundation import AppKit class Actions { // MARK: - Detect PHP Versions public static func detectPhpVersions() -> [String] { let files = Shell.pipe("ls \(Paths.optPath) | grep php@") var versionsOnly = Self.extractPhpVersions(from: files.components(separatedBy: "\n")) // Make sure the aliased version is detected // The user may have `php` installed, but not e.g. `[email protected]` // We should also detect that as a version that is installed let phpAlias = App.shared.brewPhpVersion // Avoid inserting a duplicate if (!versionsOnly.contains(phpAlias)) { versionsOnly.append(phpAlias); } print("The PHP versions that were detected are: \(versionsOnly)") return versionsOnly } /** Extracts valid PHP versions from an array of strings. This array of strings is usually retrieved from `grep`. */ public static func extractPhpVersions( from versions: [String], checkBinaries: Bool = true ) -> [String] { var output : [String] = [] versions.filter { (version) -> Bool in // Omit everything that doesn't start with php@ // (e.g. [email protected] won't be detected) return version.starts(with: "php@") }.forEach { (string) in let version = string.components(separatedBy: "php@")[1] // Only append the version if it doesn't already exist (avoid dupes), // is supported and where the binary exists (avoids broken installs) if !output.contains(version) && Constants.SupportedPhpVersions.contains(version) && (checkBinaries ? Shell.fileExists("\(Paths.optPath)/php@\(version)/bin/php") : true) { output.append(version) } } return output } // MARK: - Services public static func restartPhpFpm() { brew("services restart \(App.phpInstall!.formula)", sudo: true) } public static func restartNginx() { brew("services restart nginx", sudo: true) } public static func restartDnsMasq() { brew("services restart dnsmasq", sudo: true) } public static func stopAllServices() { brew("services stop \(App.phpInstall!.formula)", sudo: true) brew("services stop nginx", sudo: true) brew("services stop dnsmasq", sudo: true) } /** Switching to a new PHP version involves: - unlinking the current version - stopping the active services - linking the new desired version Please note that depending on which version is installed, the version that is switched to may or may not be identical to `php` (without @version). */ public static func switchToPhpVersion( version: String, availableVersions: [String], completed: @escaping () -> Void ) { print("Switching to \(version), unlinking all versions...") let group = DispatchGroup() availableVersions.forEach { (available) in group.enter() DispatchQueue.global(qos: .userInitiated).async { let formula = (available == App.shared.brewPhpVersion) ? "php" : "php@\(available)" brew("unlink \(formula)") brew("services stop \(formula)", sudo: true) group.leave() } } group.notify(queue: .global(qos: .userInitiated)) { print("All versions have been unlinked!") print("Linking the new version!") let formula = (version == App.shared.brewPhpVersion) ? "php" : "php@\(version)" brew("link \(formula) --overwrite --force") brew("services start \(formula)", sudo: true) print("The new version has been linked!") completed() } } // MARK: - Finding Config Files public static func openGenericPhpConfigFolder() { let files = [NSURL(fileURLWithPath: "\(Paths.etcPath)/php")]; NSWorkspace.shared.activateFileViewerSelecting(files as [URL]) } public static func openGlobalComposerFolder() { let file = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(".composer/composer.json") NSWorkspace.shared.activateFileViewerSelecting([file] as [URL]) } public static func openPhpConfigFolder(version: String) { let files = [NSURL(fileURLWithPath: "\(Paths.etcPath)/php/\(version)/php.ini")]; NSWorkspace.shared.activateFileViewerSelecting(files as [URL]) } public static func openValetConfigFolder() { let file = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent(".config/valet") NSWorkspace.shared.activateFileViewerSelecting([file] as [URL]) } // MARK: - Quick Fix /** Detects all currently available PHP versions, and unlinks each and every one of them. After this, the brew services are also stopped, the latest PHP version is linked, and php + nginx are restarted. If this does not solve the issue, the user may need to install additional extensions and/or run `composer global update`. */ public static func fixMyPhp() { brew("services restart dnsmasq", sudo: true) detectPhpVersions().forEach { (version) in let formula = (version == App.shared.brewPhpVersion) ? "php" : "php@\(version)" brew("unlink php@\(version)") brew("services stop \(formula)") brew("services stop \(formula)", sudo: true) } brew("services stop php") brew("services stop nginx") brew("link php") brew("services restart dnsmasq", sudo: true) brew("services stop php", sudo: true) brew("services stop nginx", sudo: true) } // MARK: Common Shell Commands /** Runs a `brew` command. Can run as superuser. */ public static func brew(_ command: String, sudo: Bool = false) { Shell.run("\(sudo ? "sudo " : "")" + "\(Paths.brew) \(command)") } /** Runs `sed` in order to replace all occurrences of a string in a specific file with another. */ public static func sed(file: String, original: String, replacement: String) { // Escape slashes (or `sed` won't work) let e_original = original.replacingOccurrences(of: "/", with: "\\/") let e_replacment = replacement.replacingOccurrences(of: "/", with: "\\/") Shell.run("sed -i '' 's/\(e_original)/\(e_replacment)/g' \(file)") } /** Uses `grep` to determine whether a particular query string can be found in a particular file. */ public static func grepContains(file: String, query: String) -> Bool { return Shell.pipe(""" grep -q '\(query)' \(file); [ $? -eq 0 ] && echo "YES" || echo "NO" """) .trimmingCharacters(in: .whitespacesAndNewlines) .contains("YES") } }
33.675676
126
0.580391
9c452088d75e516a09c6ef1e5879d275187826b8
2,156
// // AXUIElement+DFPermissionApplication.swift // WindowSnap // // Created by raymond on 2021/1/7. // import Foundation import Cocoa extension AXUIElement{ public static let systemWide:AXUIElement = AXUIElementCreateSystemWide() public static func application(pid:pid_t) -> AXUIElement{ return AXUIElementCreateApplication(pid) } public static func focusedApplication() -> AXUIElement? { let systemWide = AXUIElement.systemWide if let app = systemWide.value(attributeKey: kAXFocusedApplicationAttribute) as! AXUIElement? { return app }else{ return nil } } public static func frontmostApplication() -> AXUIElement?{ if let app = NSWorkspace.shared.frontmostApplication{ return AXUIElement.application(pid: app.processIdentifier) } return nil } /// 获取指定application在指定x和y下的AXUIElement /// - Parameters: /// - app: application的AXUIElement /// - x: 坐标系的X /// - y: 坐标系的Y /// - error: AXError,以此来获取错误信息 /// - Returns: 符合条件的AXUIElement public static func elementAtPositionInApplication(app:AXUIElement, x:Float, y: Float, error:inout AXError) -> AXUIElement? { var element : AXUIElement? error = AXUIElementCopyElementAtPosition(app, x, y, &element) return element } /// 获取指定application在指定x和y下的AXUIElement /// - Parameters: /// - app: application的AXUIElement /// - x: 坐标系的X /// - y: 坐标系的Y /// - Returns: 符合条件的AXUIElement public static func elementAtPositionInApplication(app:AXUIElement, x:Float, y: Float) -> AXUIElement? { var error : AXError = AXError.failure return elementAtPositionInApplication(app: app, x: x, y: y, error: &error) } public func pid(error:inout AXError) -> pid_t{ var pid : pid_t = 0 error = AXUIElementGetPid(self, &pid) return pid } public func pid() -> pid_t{ var error : AXError = AXError.failure return pid(error: &error) } }
26.95
128
0.616883
f416bafd50a7c748b3fdc8c5f7840fc8c6dcaa97
608
// // ASLocalizeBetterTests.swift // ASLocalizeBetterTests // // Created by Andrea on 17/01/2018. // Copyright © 2018 Andrea Stevanato. All rights reserved. // import XCTest @testable import ASLocalizeBetter class ASLocalizeBetterTests: 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() } }
25.333333
111
0.682566
8f8f2e56695e1495aba3515e708b996549325fcd
571
// // Observable.swift // dramas_sample // // Created by Rock Chen on 2020/9/13. // Copyright © 2020 Rock Chen. All rights reserved. // import Foundation /// 輕量的觀察者模式 class Observable<T> { typealias Observer = (T) -> () // 用於數據改變的執行 private var observer: Observer? // 數據發生變更,則通過觀察者告知 var value: T { didSet { observer?(value) } } init(_ value: T) { self.value = value } func observer(_ observer: Observer?) { self.observer = observer observer?(value) } }
17.30303
52
0.549912
297894aab40b9162f9b9f6d18566549021170c85
53,044
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: proto/common/common.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } /// Next ID = 21. public enum Common_CurrencyCode: SwiftProtobuf.Enum { public typealias RawValue = Int case unknownCurrencyCode // = 0 case usd // = 1 case eur // = 2 case jpy // = 3 case gbp // = 4 case aud // = 5 case cad // = 6 case chf // = 7 case cny // = 8 case hkd // = 9 case nzd // = 10 case sek // = 11 case krw // = 12 case sgd // = 13 case nok // = 14 case mxn // = 15 case inr // = 16 case rub // = 17 case zar // = 18 case `try` // = 19 case brl // = 20 case UNRECOGNIZED(Int) public init() { self = .unknownCurrencyCode } public init?(rawValue: Int) { switch rawValue { case 0: self = .unknownCurrencyCode case 1: self = .usd case 2: self = .eur case 3: self = .jpy case 4: self = .gbp case 5: self = .aud case 6: self = .cad case 7: self = .chf case 8: self = .cny case 9: self = .hkd case 10: self = .nzd case 11: self = .sek case 12: self = .krw case 13: self = .sgd case 14: self = .nok case 15: self = .mxn case 16: self = .inr case 17: self = .rub case 18: self = .zar case 19: self = .try case 20: self = .brl default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unknownCurrencyCode: return 0 case .usd: return 1 case .eur: return 2 case .jpy: return 3 case .gbp: return 4 case .aud: return 5 case .cad: return 6 case .chf: return 7 case .cny: return 8 case .hkd: return 9 case .nzd: return 10 case .sek: return 11 case .krw: return 12 case .sgd: return 13 case .nok: return 14 case .mxn: return 15 case .inr: return 16 case .rub: return 17 case .zar: return 18 case .try: return 19 case .brl: return 20 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension Common_CurrencyCode: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Common_CurrencyCode] = [ .unknownCurrencyCode, .usd, .eur, .jpy, .gbp, .aud, .cad, .chf, .cny, .hkd, .nzd, .sek, .krw, .sgd, .nok, .mxn, .inr, .rub, .zar, .try, .brl, ] } #endif // swift(>=4.2) /// Next ID = 4. public enum Common_DeviceType: SwiftProtobuf.Enum { public typealias RawValue = Int case unknownDeviceType // = 0 case desktop // = 1 case mobile // = 2 case tablet // = 3 case UNRECOGNIZED(Int) public init() { self = .unknownDeviceType } public init?(rawValue: Int) { switch rawValue { case 0: self = .unknownDeviceType case 1: self = .desktop case 2: self = .mobile case 3: self = .tablet default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unknownDeviceType: return 0 case .desktop: return 1 case .mobile: return 2 case .tablet: return 3 case .UNRECOGNIZED(let i): return i } } } #if swift(>=4.2) extension Common_DeviceType: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Common_DeviceType] = [ .unknownDeviceType, .desktop, .mobile, .tablet, ] } #endif // swift(>=4.2) /// Next ID = 7. public struct Common_EntityPath { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var platformID: UInt64 = 0 public var customerID: UInt64 = 0 public var accountID: UInt64 = 0 public var campaignID: UInt64 = 0 public var promotionID: UInt64 = 0 public var contentID: UInt64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } /// Common submessage that scopes helps scope a request/log to a user. /// /// Next ID = 4. public struct Common_UserInfo { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Optional. The Platform's actual user ID. /// This field will be cleared from our transaction logs. public var userID: String = String() /// Optional. This is a user UUID that is different from user_id and /// can quickly be disassociated from the actual user ID. This is useful: /// 1. in case the user wants to be forgotten. /// 2. logging unauthenticated users. /// The user UUID is in a different ID space than user_id. public var logUserID: String = String() /// Optional, defaults to false. Indicates that the user is from the /// marketplace or Promoted team. public var isInternalUser: Bool = false public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } /// Info about the client. /// Next ID = 3. public struct Common_ClientInfo { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var clientType: Common_ClientInfo.ClientType = .unknownRequestClient public var trafficType: Common_ClientInfo.TrafficType = .unknownTrafficType public var unknownFields = SwiftProtobuf.UnknownStorage() /// Next ID = 5; public enum ClientType: SwiftProtobuf.Enum { public typealias RawValue = Int case unknownRequestClient // = 0 /// Your (customer) server. case platformServer // = 1 /// Your (customer) client. case platformClient // = 2 case UNRECOGNIZED(Int) public init() { self = .unknownRequestClient } public init?(rawValue: Int) { switch rawValue { case 0: self = .unknownRequestClient case 1: self = .platformServer case 2: self = .platformClient default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unknownRequestClient: return 0 case .platformServer: return 1 case .platformClient: return 2 case .UNRECOGNIZED(let i): return i } } } /// Used to indicate the type of traffic. We can use this to prioritize resources. /// Next ID = 6. public enum TrafficType: SwiftProtobuf.Enum { public typealias RawValue = Int case unknownTrafficType // = 0 /// Live traffic. case production // = 1 /// Replayed traffic. We'd like similar to PRODUCTION level. case replay // = 2 /// Shadow traffic to delivery during logging. case shadow // = 4 case UNRECOGNIZED(Int) public init() { self = .unknownTrafficType } public init?(rawValue: Int) { switch rawValue { case 0: self = .unknownTrafficType case 1: self = .production case 2: self = .replay case 4: self = .shadow default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unknownTrafficType: return 0 case .production: return 1 case .replay: return 2 case .shadow: return 4 case .UNRECOGNIZED(let i): return i } } } public init() {} } #if swift(>=4.2) extension Common_ClientInfo.ClientType: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Common_ClientInfo.ClientType] = [ .unknownRequestClient, .platformServer, .platformClient, ] } extension Common_ClientInfo.TrafficType: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [Common_ClientInfo.TrafficType] = [ .unknownTrafficType, .production, .replay, .shadow, ] } #endif // swift(>=4.2) /// Locale for session /// Next ID = 3. public struct Common_Locale { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// CodeReview - Which ISO code is this? ISO 639-1? 2? 3? /// "en", "zh_Hant", "fr" public var languageCode: String = String() /// CodeReview - Which ISO code? ISO 3166-1? /// "US", "CA", "FR" public var regionCode: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } /// Rectangle size in pixels /// Next ID = 3. public struct Common_Size { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var width: UInt32 = 0 public var height: UInt32 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } /// Device screen /// Next ID = 3. public struct Common_Screen { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Android: DisplayMetrics.widthPixels/heightPixels /// iOS: UIScreen.nativeBounds.width/height public var size: Common_Size { get {return _size ?? Common_Size()} set {_size = newValue} } /// Returns true if `size` has been explicitly set. public var hasSize: Bool {return self._size != nil} /// Clears the value of `size`. Subsequent reads from it will return its default value. public mutating func clearSize() {self._size = nil} /// Natural scale factor. /// Android: DisplayMetrics.density /// iOS: UIScreen.scale public var scale: Float = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _size: Common_Size? = nil } /// A sub-message containing Device info. /// Next ID = 13. public struct Common_Device { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var deviceType: Common_DeviceType { get {return _storage._deviceType} set {_uniqueStorage()._deviceType = newValue} } /// Android: android.os.Build.BRAND /// (eg. "google", "verizon", "tmobile", "Samsung") /// iOS: "Apple" public var brand: String { get {return _storage._brand} set {_uniqueStorage()._brand = newValue} } /// Android: android.os.Build.MANUFACTURER /// (eg. "HTC", "Motorola", "HUAWEI") /// iOS: "Apple" public var manufacturer: String { get {return _storage._manufacturer} set {_uniqueStorage()._manufacturer = newValue} } /// Android: android.os.Build.MODEL /// (eg. "GT-S5830L", "MB860") /// iOS: "iPhoneXX,YY" or "iPadXX,YY" public var identifier: String { get {return _storage._identifier} set {_uniqueStorage()._identifier = newValue} } /// Android: android.os.Build.VERSION.RELEASE /// iOS: "14.4.1" public var osVersion: String { get {return _storage._osVersion} set {_uniqueStorage()._osVersion = newValue} } /// Deprecated. public var locale: Common_Locale { get {return _storage._locale ?? Common_Locale()} set {_uniqueStorage()._locale = newValue} } /// Returns true if `locale` has been explicitly set. public var hasLocale: Bool {return _storage._locale != nil} /// Clears the value of `locale`. Subsequent reads from it will return its default value. public mutating func clearLocale() {_uniqueStorage()._locale = nil} public var screen: Common_Screen { get {return _storage._screen ?? Common_Screen()} set {_uniqueStorage()._screen = newValue} } /// Returns true if `screen` has been explicitly set. public var hasScreen: Bool {return _storage._screen != nil} /// Clears the value of `screen`. Subsequent reads from it will return its default value. public mutating func clearScreen() {_uniqueStorage()._screen = nil} /// Optional. We'll use IP Address to guess the user's /// location when necessary and possible on desktop. /// Most likely in a server integration this should be the value /// of the X-Forwarded-For header. public var ipAddress: String { get {return _storage._ipAddress} set {_uniqueStorage()._ipAddress = newValue} } /// Optional. User device's actual geolocation if available. public var location: Common_Location { get {return _storage._location ?? Common_Location()} set {_uniqueStorage()._location = newValue} } /// Returns true if `location` has been explicitly set. public var hasLocation: Bool {return _storage._location != nil} /// Clears the value of `location`. Subsequent reads from it will return its default value. public mutating func clearLocation() {_uniqueStorage()._location = nil} /// Optional. Information about the user's web client (on web or mobile browser). public var browser: Common_Browser { get {return _storage._browser ?? Common_Browser()} set {_uniqueStorage()._browser = newValue} } /// Returns true if `browser` has been explicitly set. public var hasBrowser: Bool {return _storage._browser != nil} /// Clears the value of `browser`. Subsequent reads from it will return its default value. public mutating func clearBrowser() {_uniqueStorage()._browser = nil} /// Optional. Version string for platform app. public var platformAppVersion: String { get {return _storage._platformAppVersion} set {_uniqueStorage()._platformAppVersion = newValue} } /// Optional. Version string for mobile SDK. public var promotedMobileSdkVersion: String { get {return _storage._promotedMobileSdkVersion} set {_uniqueStorage()._promotedMobileSdkVersion = newValue} } public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _storage = _StorageClass.defaultInstance } /// https://raw.githubusercontent.com/snowplow/iglu-central/master/schemas/org.ietf/http_client_hints/jsonschema/1-0-0 /// A newer alternative to user agent strings. /// Next ID = 8. public struct Common_ClientHints { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var isMobile: Bool = false public var brand: [Common_ClientHintBrand] = [] public var architecture: String = String() public var model: String = String() public var platform: String = String() public var platformVersion: String = String() public var uaFullVersion: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } /// https://raw.githubusercontent.com/snowplow/iglu-central/master/schemas/org.ietf/http_client_hints/jsonschema/1-0-0 /// a part of ClientHints. /// Next ID = 3. public struct Common_ClientHintBrand { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var brand: String = String() public var version: String = String() public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } /// A sub-message containing Browser info. /// Next ID = 4. public struct Common_Browser { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var userAgent: String = String() public var viewportSize: Common_Size { get {return _viewportSize ?? Common_Size()} set {_viewportSize = newValue} } /// Returns true if `viewportSize` has been explicitly set. public var hasViewportSize: Bool {return self._viewportSize != nil} /// Clears the value of `viewportSize`. Subsequent reads from it will return its default value. public mutating func clearViewportSize() {self._viewportSize = nil} public var clientHints: Common_ClientHints { get {return _clientHints ?? Common_ClientHints()} set {_clientHints = newValue} } /// Returns true if `clientHints` has been explicitly set. public var hasClientHints: Bool {return self._clientHints != nil} /// Clears the value of `clientHints`. Subsequent reads from it will return its default value. public mutating func clearClientHints() {self._clientHints = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _viewportSize: Common_Size? = nil fileprivate var _clientHints: Common_ClientHints? = nil } /// Next ID = 4. public struct Common_Location { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// [-90, 90] public var latitude: Double = 0 /// [-180, 180] public var longitude: Double = 0 /// Optional. Accuracy of location if known. public var accuracyInMeters: Double = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } /// A message containing timing information. /// /// We can add common timing info to this message. Down the road, we might /// make more specific Timing messages (e.g. MetricsTiming). We can reuse /// the field numbers. /// /// Next ID = 4. public struct Common_Timing { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// Optional. Client timestamp when event was created. public var clientLogTimestamp: UInt64 = 0 public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} } /// Supports custom properties per platform. /// Next ID = 4. public struct Common_Properties { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var structField: Common_Properties.OneOf_StructField? = nil /// Optional. Contains protobuf serialized bytes. public var structBytes: Data { get { if case .structBytes(let v)? = structField {return v} return Data() } set {structField = .structBytes(newValue)} } /// Optional. Can be converted to/from JSON. public var `struct`: SwiftProtobuf.Google_Protobuf_Struct { get { if case .struct(let v)? = structField {return v} return SwiftProtobuf.Google_Protobuf_Struct() } set {structField = .struct(newValue)} } public var unknownFields = SwiftProtobuf.UnknownStorage() public enum OneOf_StructField: Equatable { /// Optional. Contains protobuf serialized bytes. case structBytes(Data) /// Optional. Can be converted to/from JSON. case `struct`(SwiftProtobuf.Google_Protobuf_Struct) #if !swift(>=4.1) public static func ==(lhs: Common_Properties.OneOf_StructField, rhs: Common_Properties.OneOf_StructField) -> Bool { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch (lhs, rhs) { case (.structBytes, .structBytes): return { guard case .structBytes(let l) = lhs, case .structBytes(let r) = rhs else { preconditionFailure() } return l == r }() case (.struct, .struct): return { guard case .struct(let l) = lhs, case .struct(let r) = rhs else { preconditionFailure() } return l == r }() default: return false } } #endif } public init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "common" extension Common_CurrencyCode: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "UNKNOWN_CURRENCY_CODE"), 1: .same(proto: "USD"), 2: .same(proto: "EUR"), 3: .same(proto: "JPY"), 4: .same(proto: "GBP"), 5: .same(proto: "AUD"), 6: .same(proto: "CAD"), 7: .same(proto: "CHF"), 8: .same(proto: "CNY"), 9: .same(proto: "HKD"), 10: .same(proto: "NZD"), 11: .same(proto: "SEK"), 12: .same(proto: "KRW"), 13: .same(proto: "SGD"), 14: .same(proto: "NOK"), 15: .same(proto: "MXN"), 16: .same(proto: "INR"), 17: .same(proto: "RUB"), 18: .same(proto: "ZAR"), 19: .same(proto: "TRY"), 20: .same(proto: "BRL"), ] } extension Common_DeviceType: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "UNKNOWN_DEVICE_TYPE"), 1: .same(proto: "DESKTOP"), 2: .same(proto: "MOBILE"), 3: .same(proto: "TABLET"), ] } extension Common_EntityPath: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".EntityPath" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "platform_id"), 2: .standard(proto: "customer_id"), 4: .standard(proto: "account_id"), 5: .standard(proto: "campaign_id"), 6: .standard(proto: "promotion_id"), 3: .standard(proto: "content_id"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt64Field(value: &self.platformID) }() case 2: try { try decoder.decodeSingularUInt64Field(value: &self.customerID) }() case 3: try { try decoder.decodeSingularUInt64Field(value: &self.contentID) }() case 4: try { try decoder.decodeSingularUInt64Field(value: &self.accountID) }() case 5: try { try decoder.decodeSingularUInt64Field(value: &self.campaignID) }() case 6: try { try decoder.decodeSingularUInt64Field(value: &self.promotionID) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.platformID != 0 { try visitor.visitSingularUInt64Field(value: self.platformID, fieldNumber: 1) } if self.customerID != 0 { try visitor.visitSingularUInt64Field(value: self.customerID, fieldNumber: 2) } if self.contentID != 0 { try visitor.visitSingularUInt64Field(value: self.contentID, fieldNumber: 3) } if self.accountID != 0 { try visitor.visitSingularUInt64Field(value: self.accountID, fieldNumber: 4) } if self.campaignID != 0 { try visitor.visitSingularUInt64Field(value: self.campaignID, fieldNumber: 5) } if self.promotionID != 0 { try visitor.visitSingularUInt64Field(value: self.promotionID, fieldNumber: 6) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_EntityPath, rhs: Common_EntityPath) -> Bool { if lhs.platformID != rhs.platformID {return false} if lhs.customerID != rhs.customerID {return false} if lhs.accountID != rhs.accountID {return false} if lhs.campaignID != rhs.campaignID {return false} if lhs.promotionID != rhs.promotionID {return false} if lhs.contentID != rhs.contentID {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_UserInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".UserInfo" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "user_id"), 2: .standard(proto: "log_user_id"), 3: .standard(proto: "is_internal_user"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.userID) }() case 2: try { try decoder.decodeSingularStringField(value: &self.logUserID) }() case 3: try { try decoder.decodeSingularBoolField(value: &self.isInternalUser) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.userID.isEmpty { try visitor.visitSingularStringField(value: self.userID, fieldNumber: 1) } if !self.logUserID.isEmpty { try visitor.visitSingularStringField(value: self.logUserID, fieldNumber: 2) } if self.isInternalUser != false { try visitor.visitSingularBoolField(value: self.isInternalUser, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_UserInfo, rhs: Common_UserInfo) -> Bool { if lhs.userID != rhs.userID {return false} if lhs.logUserID != rhs.logUserID {return false} if lhs.isInternalUser != rhs.isInternalUser {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_ClientInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".ClientInfo" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "client_type"), 2: .standard(proto: "traffic_type"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &self.clientType) }() case 2: try { try decoder.decodeSingularEnumField(value: &self.trafficType) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.clientType != .unknownRequestClient { try visitor.visitSingularEnumField(value: self.clientType, fieldNumber: 1) } if self.trafficType != .unknownTrafficType { try visitor.visitSingularEnumField(value: self.trafficType, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_ClientInfo, rhs: Common_ClientInfo) -> Bool { if lhs.clientType != rhs.clientType {return false} if lhs.trafficType != rhs.trafficType {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_ClientInfo.ClientType: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "UNKNOWN_REQUEST_CLIENT"), 1: .same(proto: "PLATFORM_SERVER"), 2: .same(proto: "PLATFORM_CLIENT"), ] } extension Common_ClientInfo.TrafficType: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "UNKNOWN_TRAFFIC_TYPE"), 1: .same(proto: "PRODUCTION"), 2: .same(proto: "REPLAY"), 4: .same(proto: "SHADOW"), ] } extension Common_Locale: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Locale" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "language_code"), 2: .standard(proto: "region_code"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.languageCode) }() case 2: try { try decoder.decodeSingularStringField(value: &self.regionCode) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.languageCode.isEmpty { try visitor.visitSingularStringField(value: self.languageCode, fieldNumber: 1) } if !self.regionCode.isEmpty { try visitor.visitSingularStringField(value: self.regionCode, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_Locale, rhs: Common_Locale) -> Bool { if lhs.languageCode != rhs.languageCode {return false} if lhs.regionCode != rhs.regionCode {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_Size: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Size" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "width"), 2: .same(proto: "height"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt32Field(value: &self.width) }() case 2: try { try decoder.decodeSingularUInt32Field(value: &self.height) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.width != 0 { try visitor.visitSingularUInt32Field(value: self.width, fieldNumber: 1) } if self.height != 0 { try visitor.visitSingularUInt32Field(value: self.height, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_Size, rhs: Common_Size) -> Bool { if lhs.width != rhs.width {return false} if lhs.height != rhs.height {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_Screen: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Screen" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "size"), 2: .same(proto: "scale"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._size) }() case 2: try { try decoder.decodeSingularFloatField(value: &self.scale) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._size { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } if self.scale != 0 { try visitor.visitSingularFloatField(value: self.scale, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_Screen, rhs: Common_Screen) -> Bool { if lhs._size != rhs._size {return false} if lhs.scale != rhs.scale {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_Device: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Device" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "device_type"), 2: .same(proto: "brand"), 3: .same(proto: "manufacturer"), 4: .same(proto: "identifier"), 5: .standard(proto: "os_version"), 6: .same(proto: "locale"), 7: .same(proto: "screen"), 8: .standard(proto: "ip_address"), 9: .same(proto: "location"), 10: .same(proto: "browser"), 11: .standard(proto: "platform_app_version"), 12: .standard(proto: "promoted_mobile_sdk_version"), ] fileprivate class _StorageClass { var _deviceType: Common_DeviceType = .unknownDeviceType var _brand: String = String() var _manufacturer: String = String() var _identifier: String = String() var _osVersion: String = String() var _locale: Common_Locale? = nil var _screen: Common_Screen? = nil var _ipAddress: String = String() var _location: Common_Location? = nil var _browser: Common_Browser? = nil var _platformAppVersion: String = String() var _promotedMobileSdkVersion: String = String() static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _deviceType = source._deviceType _brand = source._brand _manufacturer = source._manufacturer _identifier = source._identifier _osVersion = source._osVersion _locale = source._locale _screen = source._screen _ipAddress = source._ipAddress _location = source._location _browser = source._browser _platformAppVersion = source._platformAppVersion _promotedMobileSdkVersion = source._promotedMobileSdkVersion } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularEnumField(value: &_storage._deviceType) }() case 2: try { try decoder.decodeSingularStringField(value: &_storage._brand) }() case 3: try { try decoder.decodeSingularStringField(value: &_storage._manufacturer) }() case 4: try { try decoder.decodeSingularStringField(value: &_storage._identifier) }() case 5: try { try decoder.decodeSingularStringField(value: &_storage._osVersion) }() case 6: try { try decoder.decodeSingularMessageField(value: &_storage._locale) }() case 7: try { try decoder.decodeSingularMessageField(value: &_storage._screen) }() case 8: try { try decoder.decodeSingularStringField(value: &_storage._ipAddress) }() case 9: try { try decoder.decodeSingularMessageField(value: &_storage._location) }() case 10: try { try decoder.decodeSingularMessageField(value: &_storage._browser) }() case 11: try { try decoder.decodeSingularStringField(value: &_storage._platformAppVersion) }() case 12: try { try decoder.decodeSingularStringField(value: &_storage._promotedMobileSdkVersion) }() default: break } } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if _storage._deviceType != .unknownDeviceType { try visitor.visitSingularEnumField(value: _storage._deviceType, fieldNumber: 1) } if !_storage._brand.isEmpty { try visitor.visitSingularStringField(value: _storage._brand, fieldNumber: 2) } if !_storage._manufacturer.isEmpty { try visitor.visitSingularStringField(value: _storage._manufacturer, fieldNumber: 3) } if !_storage._identifier.isEmpty { try visitor.visitSingularStringField(value: _storage._identifier, fieldNumber: 4) } if !_storage._osVersion.isEmpty { try visitor.visitSingularStringField(value: _storage._osVersion, fieldNumber: 5) } if let v = _storage._locale { try visitor.visitSingularMessageField(value: v, fieldNumber: 6) } if let v = _storage._screen { try visitor.visitSingularMessageField(value: v, fieldNumber: 7) } if !_storage._ipAddress.isEmpty { try visitor.visitSingularStringField(value: _storage._ipAddress, fieldNumber: 8) } if let v = _storage._location { try visitor.visitSingularMessageField(value: v, fieldNumber: 9) } if let v = _storage._browser { try visitor.visitSingularMessageField(value: v, fieldNumber: 10) } if !_storage._platformAppVersion.isEmpty { try visitor.visitSingularStringField(value: _storage._platformAppVersion, fieldNumber: 11) } if !_storage._promotedMobileSdkVersion.isEmpty { try visitor.visitSingularStringField(value: _storage._promotedMobileSdkVersion, fieldNumber: 12) } } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_Device, rhs: Common_Device) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._deviceType != rhs_storage._deviceType {return false} if _storage._brand != rhs_storage._brand {return false} if _storage._manufacturer != rhs_storage._manufacturer {return false} if _storage._identifier != rhs_storage._identifier {return false} if _storage._osVersion != rhs_storage._osVersion {return false} if _storage._locale != rhs_storage._locale {return false} if _storage._screen != rhs_storage._screen {return false} if _storage._ipAddress != rhs_storage._ipAddress {return false} if _storage._location != rhs_storage._location {return false} if _storage._browser != rhs_storage._browser {return false} if _storage._platformAppVersion != rhs_storage._platformAppVersion {return false} if _storage._promotedMobileSdkVersion != rhs_storage._promotedMobileSdkVersion {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_ClientHints: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".ClientHints" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "is_mobile"), 2: .same(proto: "brand"), 3: .same(proto: "architecture"), 4: .same(proto: "model"), 5: .same(proto: "platform"), 6: .standard(proto: "platform_version"), 7: .standard(proto: "ua_full_version"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularBoolField(value: &self.isMobile) }() case 2: try { try decoder.decodeRepeatedMessageField(value: &self.brand) }() case 3: try { try decoder.decodeSingularStringField(value: &self.architecture) }() case 4: try { try decoder.decodeSingularStringField(value: &self.model) }() case 5: try { try decoder.decodeSingularStringField(value: &self.platform) }() case 6: try { try decoder.decodeSingularStringField(value: &self.platformVersion) }() case 7: try { try decoder.decodeSingularStringField(value: &self.uaFullVersion) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.isMobile != false { try visitor.visitSingularBoolField(value: self.isMobile, fieldNumber: 1) } if !self.brand.isEmpty { try visitor.visitRepeatedMessageField(value: self.brand, fieldNumber: 2) } if !self.architecture.isEmpty { try visitor.visitSingularStringField(value: self.architecture, fieldNumber: 3) } if !self.model.isEmpty { try visitor.visitSingularStringField(value: self.model, fieldNumber: 4) } if !self.platform.isEmpty { try visitor.visitSingularStringField(value: self.platform, fieldNumber: 5) } if !self.platformVersion.isEmpty { try visitor.visitSingularStringField(value: self.platformVersion, fieldNumber: 6) } if !self.uaFullVersion.isEmpty { try visitor.visitSingularStringField(value: self.uaFullVersion, fieldNumber: 7) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_ClientHints, rhs: Common_ClientHints) -> Bool { if lhs.isMobile != rhs.isMobile {return false} if lhs.brand != rhs.brand {return false} if lhs.architecture != rhs.architecture {return false} if lhs.model != rhs.model {return false} if lhs.platform != rhs.platform {return false} if lhs.platformVersion != rhs.platformVersion {return false} if lhs.uaFullVersion != rhs.uaFullVersion {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_ClientHintBrand: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".ClientHintBrand" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "brand"), 2: .same(proto: "version"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.brand) }() case 2: try { try decoder.decodeSingularStringField(value: &self.version) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.brand.isEmpty { try visitor.visitSingularStringField(value: self.brand, fieldNumber: 1) } if !self.version.isEmpty { try visitor.visitSingularStringField(value: self.version, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_ClientHintBrand, rhs: Common_ClientHintBrand) -> Bool { if lhs.brand != rhs.brand {return false} if lhs.version != rhs.version {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_Browser: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Browser" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "user_agent"), 2: .standard(proto: "viewport_size"), 3: .standard(proto: "client_hints"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.userAgent) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._viewportSize) }() case 3: try { try decoder.decodeSingularMessageField(value: &self._clientHints) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.userAgent.isEmpty { try visitor.visitSingularStringField(value: self.userAgent, fieldNumber: 1) } if let v = self._viewportSize { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } if let v = self._clientHints { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_Browser, rhs: Common_Browser) -> Bool { if lhs.userAgent != rhs.userAgent {return false} if lhs._viewportSize != rhs._viewportSize {return false} if lhs._clientHints != rhs._clientHints {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_Location: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Location" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "latitude"), 2: .same(proto: "longitude"), 3: .standard(proto: "accuracy_in_meters"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularDoubleField(value: &self.latitude) }() case 2: try { try decoder.decodeSingularDoubleField(value: &self.longitude) }() case 3: try { try decoder.decodeSingularDoubleField(value: &self.accuracyInMeters) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.latitude != 0 { try visitor.visitSingularDoubleField(value: self.latitude, fieldNumber: 1) } if self.longitude != 0 { try visitor.visitSingularDoubleField(value: self.longitude, fieldNumber: 2) } if self.accuracyInMeters != 0 { try visitor.visitSingularDoubleField(value: self.accuracyInMeters, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_Location, rhs: Common_Location) -> Bool { if lhs.latitude != rhs.latitude {return false} if lhs.longitude != rhs.longitude {return false} if lhs.accuracyInMeters != rhs.accuracyInMeters {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_Timing: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Timing" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "client_log_timestamp"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularUInt64Field(value: &self.clientLogTimestamp) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.clientLogTimestamp != 0 { try visitor.visitSingularUInt64Field(value: self.clientLogTimestamp, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_Timing, rhs: Common_Timing) -> Bool { if lhs.clientLogTimestamp != rhs.clientLogTimestamp {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Common_Properties: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Properties" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "struct_bytes"), 2: .same(proto: "struct"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { var v: Data? try decoder.decodeSingularBytesField(value: &v) if let v = v { if self.structField != nil {try decoder.handleConflictingOneOf()} self.structField = .structBytes(v) } }() case 2: try { var v: SwiftProtobuf.Google_Protobuf_Struct? var hadOneofValue = false if let current = self.structField { hadOneofValue = true if case .struct(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v { if hadOneofValue {try decoder.handleConflictingOneOf()} self.structField = .struct(v) } }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch self.structField { case .structBytes?: try { guard case .structBytes(let v)? = self.structField else { preconditionFailure() } try visitor.visitSingularBytesField(value: v, fieldNumber: 1) }() case .struct?: try { guard case .struct(let v)? = self.structField else { preconditionFailure() } try visitor.visitSingularMessageField(value: v, fieldNumber: 2) }() case nil: break } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Common_Properties, rhs: Common_Properties) -> Bool { if lhs.structField != rhs.structField {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
36.207509
134
0.696177
e63f1dd0e11b27487bcc947a0f2739f0d723cbee
2,881
// // UITextField+PlumKit.swift // PlumKit // // Created by Kingiol on 15/12/14. // Copyright © 2015年 Kingiol. All rights reserved. // import Foundation public extension UITextField { // get textfield trim text public var trimText: String? { return text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } // set textfield has text limit length public var textLimitLength: Int? { set { self.setAssociatedObject(textLimitLength!, forKey: "textLimitLength"); self.addTarget(self, action: "textFieldChanged:", forControlEvents: .EditingChanged) } get { return self.getAssociatedObjectForKey("textLimitLength") as? Int } } private func textFieldChanged(textField: UITextField) { let textFieldText = textField.text! //获取高亮部分 var textPosition: UITextPosition? if let selectedRanage = textField.markedTextRange { textPosition = textField.positionFromPosition(selectedRanage.start, offset: 0) } let maxLength = self.textLimitLength! // 没有高亮选择的字,则对已输入的文字进行字数统计和限制 if textPosition == nil { let castTextFieldText = textFieldText as NSString if textFieldText.characters.count > maxLength { let rangeIndex = castTextFieldText.rangeOfComposedCharacterSequenceAtIndex(maxLength) if rangeIndex.length == 1 { textField.text = castTextFieldText.substringToIndex(maxLength) }else { let rangeRange = castTextFieldText.rangeOfComposedCharacterSequencesForRange(NSMakeRange(0, maxLength)) textField.text = castTextFieldText.substringWithRange(rangeRange) } } } sendActionsForControlEvents(.EditingChanged) // NSString *text = textField.text; // // // UITextRange *selectedRange = [textField markedTextRange]; // UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0]; // // NSInteger maxLegnth = 5; // // // if (!position) // { // if (text.length > maxLegnth) // { // NSRange rangeIndex = [text rangeOfComposedCharacterSequenceAtIndex:maxLegnth]; // if (rangeIndex.length == 1) // { // textField.text = [text substringToIndex:maxLegnth]; // } // else // { // NSRange rangeRange = [text rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLegnth)]; // textField.text = [text substringWithRange:rangeRange]; // } // } // } } }
34.710843
123
0.58799
336b7d1bb10d1250a14a880b18d22d04edb6cbfd
966
// // Account.swift // StreamOneSDK // // Created by Nicky Gerritsen on 16-08-15. // Copyright © 2015 StreamOne. All rights reserved. // import Foundation import Argo import Curry /** A basic account as returned from the API */ public class BasicAccount : NSObject, Decodable { /// Account ID public let id: String /// The name of this account public let name: String /** Construct a new basic account - Parameter id: The ID of the account - Parameter name: The name of the customer */ public init(id: String, name: String) { self.id = id self.name = name } /** Decode a JSON object into an account - Parameter json: The JSON to decode - Returns: The decoded account */ public static func decode(json: JSON) -> Decoded<BasicAccount> { return curry(BasicAccount.init) <^> json <| "id" <*> json <| "name" } }
21.466667
68
0.595238
0a753e53000e5cb3ebabc7de9e30882a5433c57b
2,926
// // OAuthViewController.swift // WeiBoDemo // // Created by wei on 2017/4/11. // Copyright © 2017年 wei. All rights reserved. // import UIKit import SVProgressHUD class OAuthViewController: UIViewController { let App_Key = "3656833625" let App_Secret = "4c79a95e8c8e402bbb8bc8030e33e50b" let redirect_url = "http://wmonkey.top" override func loadView() { view = webView } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.plain, target: self, action: #selector(dismissSelf)) //1. 获取未授权的RequestToken let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(App_Key)&response_type=code&redirect_uri=\(redirect_url)" let url = URL(string: urlStr) let request = URLRequest(url: url!) webView.loadRequest(request) } func dismissSelf() { dismiss(animated: true, completion: nil) SVProgressHUD.dismiss() } // MARK: 懒加载 /// private lazy var webView: UIWebView = { let wv = UIWebView() wv.delegate = self return wv }() } extension OAuthViewController: UIWebViewDelegate { func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{ // "https://api.weibo.com/oauth2/authorize?client_id=3656833625&response_type=code&redirect_uri=http://wmonkey.top") // "https://api.weibo.com/oauth2/authorize") // "https://api.weibo.com/oauth2/authorize#") // "https://api.weibo.com/oauth2/authorize") // "http://wmonkey.top/?code=20302dea19864397915ae39396d80367") let urlStr = request.url?.absoluteString if !(urlStr?.hasPrefix(redirect_url))!{ return true } let codeStr = "code=" if (request.url?.query?.hasPrefix(codeStr))!{ //授权成功, 取出授权token let code = request.url!.query?.substring(from: codeStr.endIndex) loadAccessToken(code: code!) // print(code ?? "dd") }else{ //取消授权 self.dismissSelf() } return false } func webViewDidStartLoad(_ webView: UIWebView) { SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.dark) SVProgressHUD.showInfo(withStatus: "正在加载...") } func webViewDidFinishLoad(_ webView: UIWebView) { SVProgressHUD.dismiss() } private func loadAccessToken(code: String) { NetworkManager().getAccessToken(code: code) { (account, error) in if error != nil { }else{ //保存用户信息 account?.saveAccount() self.dismissSelf() } } } }
29.26
153
0.591251
097acee7e92710ac2a671e4a552ade8cfefcb835
1,312
// // MonsterAilments.swift // MHWDB // // Created by Joe on 8/16/20. // Copyright © 2020 Gathering Hall Studios. All rights reserved. // import Foundation extension Monster { var ailments: [String] { func value(_ hasValue: Bool?, _ output: String) -> String? { return hasValue == true ? output : nil } let ailments: [String?] = [ ailmentRoar.map { "Roar (\($0))" }, ailmentWind.map { "Wind (\($0))" }, ailmentTremor.map { "Tremor (\($0))" }, value(ailmentDefensedown, "Defense Down"), value(ailmentParalysis, "Paralysis"), value(ailmentPoison, "Poison"), value(ailmentSleep, "Sleep"), value(ailmentStun, "Stun"), value(ailmentBleed, "Bleed"), value(ailmentMud, "Mud"), value(ailmentEffluvia, "Effluvia"), value(ailmentFireblight, "FireBlight"), value(ailmentIceblight, "IceBlight"), value(ailmentThunderblight, "ThunderBlight"), value(ailmentWaterblight, "WaterBlight"), value(ailmentBlastblight, "BlastBlight"), value(ailmentDragonblight, "DragonBlight") //value(ailmentRegional, ""), ] return ailments.compactMap { $0 } } }
31.238095
68
0.560976
6ae7cf64cd9aa6d27b4f866e5f3fe784acef1c68
66,736
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2019 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest import Dispatch @testable import NIO @testable import NIOHTTP1 extension ChannelPipeline { fileprivate func assertDoesNotContainUpgrader() throws { try self.assertDoesNotContain(handlerType: HTTPServerUpgradeHandler.self) } func assertDoesNotContain<Handler: ChannelHandler>(handlerType: Handler.Type, file: StaticString = #file, line: UInt = #line) throws { do { let context = try self.context(handlerType: handlerType).wait() XCTFail("Found handler: \(context.handler)", file: file, line: line) } catch ChannelPipelineError.notFound { // Nothing to see here } } fileprivate func assertContainsUpgrader() throws { try self.assertContains(handlerType: HTTPServerUpgradeHandler.self) } func assertContains<Handler: ChannelHandler>(handlerType: Handler.Type) throws { do { _ = try self.context(handlerType: handlerType).wait() } catch ChannelPipelineError.notFound { XCTFail("Did not find handler") } } fileprivate func removeUpgrader() throws { try self.context(handlerType: HTTPServerUpgradeHandler.self).flatMap { self.removeHandler(context: $0) }.wait() } // Waits up to 1 second for the upgrader to be removed by polling the pipeline // every 50ms checking for the handler. fileprivate func waitForUpgraderToBeRemoved() throws { for _ in 0..<20 { do { _ = try self.context(handlerType: HTTPServerUpgradeHandler.self).wait() // handler present, keep waiting usleep(50) } catch ChannelPipelineError.notFound { // No upgrader, we're good. return } } XCTFail("Upgrader never removed") } } extension EmbeddedChannel { func readAllOutboundBuffers() throws -> ByteBuffer { var buffer = self.allocator.buffer(capacity: 100) while var writtenData = try self.readOutbound(as: ByteBuffer.self) { buffer.writeBuffer(&writtenData) } return buffer } func readAllOutboundString() throws -> String { var buffer = try self.readAllOutboundBuffers() return buffer.readString(length: buffer.readableBytes)! } } private func serverHTTPChannelWithAutoremoval(group: EventLoopGroup, pipelining: Bool, upgraders: [HTTPServerProtocolUpgrader], extraHandlers: [ChannelHandler], _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void) throws -> (Channel, EventLoopFuture<Channel>) { let p = group.next().makePromise(of: Channel.self) let c = try ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) .childChannelInitializer { channel in p.succeed(channel) let upgradeConfig = (upgraders: upgraders, completionHandler: upgradeCompletionHandler) return channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: pipelining, withServerUpgrade: upgradeConfig).flatMap { let futureResults = extraHandlers.map { channel.pipeline.addHandler($0) } return EventLoopFuture.andAllSucceed(futureResults, on: channel.eventLoop) } }.bind(host: "127.0.0.1", port: 0).wait() return (c, p.futureResult) } private class SingleHTTPResponseAccumulator: ChannelInboundHandler { typealias InboundIn = ByteBuffer private var receiveds: [InboundIn] = [] private let allDoneBlock: ([InboundIn]) -> Void public init(completion: @escaping ([InboundIn]) -> Void) { self.allDoneBlock = completion } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let buffer = self.unwrapInboundIn(data) self.receiveds.append(buffer) if let finalBytes = buffer.getBytes(at: buffer.writerIndex - 4, length: 4), finalBytes == [0x0D, 0x0A, 0x0D, 0x0A] { self.allDoneBlock(self.receiveds) } } } private class ExplodingHandler: ChannelInboundHandler { typealias InboundIn = Any public func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTFail("Received unexpected read") } } private func connectedClientChannel(group: EventLoopGroup, serverAddress: SocketAddress) throws -> Channel { return try ClientBootstrap(group: group) .connect(to: serverAddress) .wait() } private func setUpTestWithAutoremoval(pipelining: Bool = false, upgraders: [HTTPServerProtocolUpgrader], extraHandlers: [ChannelHandler], _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void) throws -> (EventLoopGroup, Channel, Channel, Channel) { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) let (serverChannel, connectedServerChannelFuture) = try serverHTTPChannelWithAutoremoval(group: group, pipelining: pipelining, upgraders: upgraders, extraHandlers: extraHandlers, upgradeCompletionHandler) let clientChannel = try connectedClientChannel(group: group, serverAddress: serverChannel.localAddress!) return (group, serverChannel, clientChannel, try connectedServerChannelFuture.wait()) } internal func assertResponseIs(response: String, expectedResponseLine: String, expectedResponseHeaders: [String]) { var lines = response.split(separator: "\r\n", omittingEmptySubsequences: false).map { String($0) } // We never expect a response body here. This means we need the last two entries to be empty strings. XCTAssertEqual("", lines.removeLast()) XCTAssertEqual("", lines.removeLast()) // Check the response line is correct. let actualResponseLine = lines.removeFirst() XCTAssertEqual(expectedResponseLine, actualResponseLine) // For each header, find it in the actual response headers and remove it. for expectedHeader in expectedResponseHeaders { guard let index = lines.firstIndex(of: expectedHeader) else { XCTFail("Could not find header \"\(expectedHeader)\"") return } lines.remove(at: index) } // That should be all the headers. XCTAssertEqual(lines.count, 0) } private class ExplodingUpgrader: HTTPServerProtocolUpgrader { let supportedProtocol: String let requiredUpgradeHeaders: [String] private enum Explosion: Error { case KABOOM } public init(forProtocol `protocol`: String, requiringHeaders: [String] = []) { self.supportedProtocol = `protocol` self.requiredUpgradeHeaders = requiringHeaders } public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture<HTTPHeaders> { XCTFail("buildUpgradeResponse called") return channel.eventLoop.makeFailedFuture(Explosion.KABOOM) } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> { XCTFail("upgrade called") return context.eventLoop.makeSucceededFuture(()) } } private class UpgraderSaysNo: HTTPServerProtocolUpgrader { let supportedProtocol: String let requiredUpgradeHeaders: [String] = [] public enum No: Error { case no } public init(forProtocol `protocol`: String) { self.supportedProtocol = `protocol` } public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture<HTTPHeaders> { return channel.eventLoop.makeFailedFuture(No.no) } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> { XCTFail("upgrade called") return context.eventLoop.makeSucceededFuture(()) } } private class SuccessfulUpgrader: HTTPServerProtocolUpgrader { let supportedProtocol: String let requiredUpgradeHeaders: [String] private let onUpgradeComplete: (HTTPRequestHead) -> () private let buildUpgradeResponseFuture: (Channel, HTTPHeaders) -> EventLoopFuture<HTTPHeaders> public init(forProtocol `protocol`: String, requiringHeaders headers: [String], buildUpgradeResponseFuture: @escaping (Channel, HTTPHeaders) -> EventLoopFuture<HTTPHeaders>, onUpgradeComplete: @escaping (HTTPRequestHead) -> ()) { self.supportedProtocol = `protocol` self.requiredUpgradeHeaders = headers self.onUpgradeComplete = onUpgradeComplete self.buildUpgradeResponseFuture = buildUpgradeResponseFuture } public convenience init(forProtocol `protocol`: String, requiringHeaders headers: [String], onUpgradeComplete: @escaping (HTTPRequestHead) -> ()) { self.init(forProtocol: `protocol`, requiringHeaders: headers, buildUpgradeResponseFuture: { $0.eventLoop.makeSucceededFuture($1) }, onUpgradeComplete: onUpgradeComplete) } public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture<HTTPHeaders> { var headers = initialResponseHeaders headers.add(name: "X-Upgrade-Complete", value: "true") return self.buildUpgradeResponseFuture(channel, headers) } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> { self.onUpgradeComplete(upgradeRequest) return context.eventLoop.makeSucceededFuture(()) } } private class UpgradeDelayer: HTTPServerProtocolUpgrader { let supportedProtocol: String let requiredUpgradeHeaders: [String] = [] private var upgradePromise: EventLoopPromise<Void>? public init(forProtocol `protocol`: String) { self.supportedProtocol = `protocol` } public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture<HTTPHeaders> { var headers = initialResponseHeaders headers.add(name: "X-Upgrade-Complete", value: "true") return channel.eventLoop.makeSucceededFuture(headers) } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> { self.upgradePromise = context.eventLoop.makePromise() return self.upgradePromise!.futureResult } public func unblockUpgrade() { self.upgradePromise!.succeed(()) } } private class UpgradeResponseDelayer: HTTPServerProtocolUpgrader { let supportedProtocol: String let requiredUpgradeHeaders: [String] = [] private var context: ChannelHandlerContext? private let buildUpgradeResponseHandler: () -> EventLoopFuture<Void> public init(forProtocol `protocol`: String, buildUpgradeResponseHandler: @escaping () -> EventLoopFuture<Void>) { self.supportedProtocol = `protocol` self.buildUpgradeResponseHandler = buildUpgradeResponseHandler } public func buildUpgradeResponse(channel: Channel, upgradeRequest: HTTPRequestHead, initialResponseHeaders: HTTPHeaders) -> EventLoopFuture<HTTPHeaders> { return self.buildUpgradeResponseHandler().map { var headers = initialResponseHeaders headers.add(name: "X-Upgrade-Complete", value: "true") return headers } } public func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> { return context.eventLoop.makeSucceededFuture(()) } } private class UserEventSaver<EventType>: ChannelInboundHandler { public typealias InboundIn = Any public var events: [EventType] = [] public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { events.append(event as! EventType) context.fireUserInboundEventTriggered(event) } } private class ErrorSaver: ChannelInboundHandler { public typealias InboundIn = Any public typealias InboundOut = Any public var errors: [Error] = [] public func errorCaught(context: ChannelHandlerContext, error: Error) { errors.append(error) context.fireErrorCaught(error) } } private class DataRecorder<T>: ChannelInboundHandler { public typealias InboundIn = T private var data: [T] = [] public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let datum = self.unwrapInboundIn(data) self.data.append(datum) } // Must be called from inside the event loop on pain of death! public func receivedData() ->[T] { return self.data } } private class ReentrantReadOnChannelReadCompleteHandler: ChannelInboundHandler { typealias InboundIn = Any typealias InboundOut = Any private var didRead = false func channelReadComplete(context: ChannelHandlerContext) { // Make sure we only do this once. if !self.didRead { self.didRead = true let data = ByteBuffer.forString("re-entrant read from channelReadComplete!") // Please never do this. context.channel.pipeline.fireChannelRead(NIOAny(data)) } context.fireChannelReadComplete() } } extension ByteBuffer { static func forString(_ string: String) -> ByteBuffer { var buf = ByteBufferAllocator().buffer(capacity: string.utf8.count) buf.writeString(string) return buf } } class HTTPServerUpgradeTestCase: XCTestCase { func testUpgradeWithoutUpgrade() throws { let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [ExplodingUpgrader(forProtocol: "myproto")], extraHandlers: []) { (_: ChannelHandlerContext) in XCTFail("upgrade completed") } defer { XCTAssertNoThrow(try client.close().wait()) XCTAssertNoThrow(try server.close().wait()) XCTAssertNoThrow(try group.syncShutdownGracefully()) } let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // At this time the channel pipeline should not contain our handler: it should have removed itself. try connectedServer.pipeline.waitForUpgraderToBeRemoved() } func testUpgradeAfterInitialRequest() throws { let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [ExplodingUpgrader(forProtocol: "myproto")], extraHandlers: []) { (_: ChannelHandlerContext) in XCTFail("upgrade completed") } defer { XCTAssertNoThrow(try client.close().wait()) XCTAssertNoThrow(try server.close().wait()) XCTAssertNoThrow(try group.syncShutdownGracefully()) } // This request fires a subsequent upgrade in immediately. It should also be ignored. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\n\r\nOPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nConnection: upgrade\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // At this time the channel pipeline should not contain our handler: it should have removed itself. try connectedServer.pipeline.waitForUpgraderToBeRemoved() } func testUpgradeHandlerBarfsOnUnexpectedOrdering() throws { let channel = EmbeddedChannel() defer { XCTAssertEqual(true, try? channel.finish().isClean) } let handler = HTTPServerUpgradeHandler(upgraders: [ExplodingUpgrader(forProtocol: "myproto")], httpEncoder: HTTPResponseEncoder(), extraHTTPHandlers: []) { (_: ChannelHandlerContext) in XCTFail("upgrade completed") } let data = HTTPServerRequestPart.body(ByteBuffer.forString("hello")) XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait()) do { try channel.writeInbound(data) XCTFail("Writing of bad data did not error") } catch HTTPServerUpgradeErrors.invalidHTTPOrdering { // Nothing to see here. } // The handler removed itself from the pipeline and passed the unexpected // data on. try channel.pipeline.assertDoesNotContainUpgrader() let receivedData: HTTPServerRequestPart = try channel.readInbound()! XCTAssertEqual(data, receivedData) } func testSimpleUpgradeSucceeds() throws { var upgradeRequest: HTTPRequestHead? = nil var upgradeHandlerCbFired = false var upgraderCbFired = false let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"]) { req in upgradeRequest = req XCTAssert(upgradeHandlerCbFired) upgraderCbFired = true } let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], extraHandlers: []) { (context) in // This is called before the upgrader gets called. XCTAssertNil(upgradeRequest) upgradeHandlerCbFired = true // We're closing the connection now. context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let completePromise = group.next().makePromise(of: Void.self) let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) completePromise.succeed(()) } XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait()) // This request is safe to upgrade. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // Let the machinery do its thing. XCTAssertNoThrow(try completePromise.futureResult.wait()) // At this time we want to assert that everything got called. Their own callbacks assert // that the ordering was correct. XCTAssert(upgradeHandlerCbFired) XCTAssert(upgraderCbFired) // We also want to confirm that the upgrade handler is no longer in the pipeline. try connectedServer.pipeline.assertDoesNotContainUpgrader() } func testUpgradeRequiresCorrectHeaders() throws { let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [ExplodingUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"])], extraHandlers: []) { (_: ChannelHandlerContext) in XCTFail("upgrade completed") } defer { XCTAssertNoThrow(try client.close().wait()) XCTAssertNoThrow(try server.close().wait()) XCTAssertNoThrow(try group.syncShutdownGracefully()) } let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nConnection: upgrade\r\nUpgrade: myproto\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // At this time the channel pipeline should not contain our handler: it should have removed itself. try connectedServer.pipeline.waitForUpgraderToBeRemoved() } func testUpgradeRequiresHeadersInConnection() throws { let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [ExplodingUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"])], extraHandlers: []) { (_: ChannelHandlerContext) in XCTFail("upgrade completed") } defer { XCTAssertNoThrow(try client.close().wait()) XCTAssertNoThrow(try server.close().wait()) XCTAssertNoThrow(try group.syncShutdownGracefully()) } // This request is missing a 'Kafkaesque' connection header. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nConnection: upgrade\r\nUpgrade: myproto\r\nKafkaesque: true\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // At this time the channel pipeline should not contain our handler: it should have removed itself. try connectedServer.pipeline.waitForUpgraderToBeRemoved() } func testUpgradeOnlyHandlesKnownProtocols() throws { let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [ExplodingUpgrader(forProtocol: "myproto")], extraHandlers: []) { (_: ChannelHandlerContext) in XCTFail("upgrade completed") } defer { XCTAssertNoThrow(try client.close().wait()) XCTAssertNoThrow(try server.close().wait()) XCTAssertNoThrow(try group.syncShutdownGracefully()) } let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nConnection: upgrade\r\nUpgrade: something-else\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // At this time the channel pipeline should not contain our handler: it should have removed itself. try connectedServer.pipeline.waitForUpgraderToBeRemoved() } func testUpgradeRespectsClientPreference() throws { var upgradeRequest: HTTPRequestHead? = nil var upgradeHandlerCbFired = false var upgraderCbFired = false let explodingUpgrader = ExplodingUpgrader(forProtocol: "exploder") let successfulUpgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"]) { req in upgradeRequest = req XCTAssert(upgradeHandlerCbFired) upgraderCbFired = true } let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [explodingUpgrader, successfulUpgrader], extraHandlers: []) { context in // This is called before the upgrader gets called. XCTAssertNil(upgradeRequest) upgradeHandlerCbFired = true // We're closing the connection now. context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let completePromise = group.next().makePromise(of: Void.self) let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) completePromise.succeed(()) } XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait()) // This request is safe to upgrade. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto, exploder\r\nKafkaesque: yup\r\nConnection: upgrade, kafkaesque\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // Let the machinery do its thing. XCTAssertNoThrow(try completePromise.futureResult.wait()) // At this time we want to assert that everything got called. Their own callbacks assert // that the ordering was correct. XCTAssert(upgradeHandlerCbFired) XCTAssert(upgraderCbFired) // We also want to confirm that the upgrade handler is no longer in the pipeline. try connectedServer.pipeline.waitForUpgraderToBeRemoved() } func testUpgradeFiresUserEvent() throws { // The user event is fired last, so we don't see it until both other callbacks // have fired. let eventSaver = UserEventSaver<HTTPServerUpgradeEvents>() let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: []) { req in XCTAssertEqual(eventSaver.events.count, 0) } let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], extraHandlers: [eventSaver]) { context in XCTAssertEqual(eventSaver.events.count, 0) context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let completePromise = group.next().makePromise(of: Void.self) let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) completePromise.succeed(()) } XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait()) // This request is safe to upgrade. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade,kafkaesque\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // Let the machinery do its thing. XCTAssertNoThrow(try completePromise.futureResult.wait()) // At this time we should have received one user event. We schedule this onto the // event loop to guarantee thread safety. XCTAssertNoThrow(try connectedServer.eventLoop.scheduleTask(deadline: .now()) { XCTAssertEqual(eventSaver.events.count, 1) if case .upgradeComplete(let proto, let req) = eventSaver.events[0] { XCTAssertEqual(proto, "myproto") XCTAssertEqual(req.method, .OPTIONS) XCTAssertEqual(req.uri, "*") XCTAssertEqual(req.version, HTTPVersion(major: 1, minor: 1)) } else { XCTFail("Unexpected event: \(eventSaver.events[0])") } }.futureResult.wait()) // We also want to confirm that the upgrade handler is no longer in the pipeline. try connectedServer.pipeline.waitForUpgraderToBeRemoved() } func testUpgraderCanRejectUpgradeForPersonalReasons() throws { var upgradeRequest: HTTPRequestHead? = nil var upgradeHandlerCbFired = false var upgraderCbFired = false let explodingUpgrader = UpgraderSaysNo(forProtocol: "noproto") let successfulUpgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"]) { req in upgradeRequest = req XCTAssert(upgradeHandlerCbFired) upgraderCbFired = true } let errorCatcher = ErrorSaver() let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [explodingUpgrader, successfulUpgrader], extraHandlers: [errorCatcher]) { context in // This is called before the upgrader gets called. XCTAssertNil(upgradeRequest) upgradeHandlerCbFired = true // We're closing the connection now. context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let completePromise = group.next().makePromise(of: Void.self) let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) completePromise.succeed(()) } XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait()) // This request is safe to upgrade. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: noproto,myproto\r\nKafkaesque: yup\r\nConnection: upgrade, kafkaesque\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // Let the machinery do its thing. XCTAssertNoThrow(try completePromise.futureResult.wait()) // At this time we want to assert that everything got called. Their own callbacks assert // that the ordering was correct. XCTAssert(upgradeHandlerCbFired) XCTAssert(upgraderCbFired) // We also want to confirm that the upgrade handler is no longer in the pipeline. try connectedServer.pipeline.waitForUpgraderToBeRemoved() // And we want to confirm we saved the error. XCTAssertEqual(errorCatcher.errors.count, 1) switch(errorCatcher.errors[0]) { case UpgraderSaysNo.No.no: break default: XCTFail("Unexpected error: \(errorCatcher.errors[0])") } } func testUpgradeIsCaseInsensitive() throws { let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["WeIrDcAsE"]) { req in } let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], extraHandlers: []) { context in context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let completePromise = group.next().makePromise(of: Void.self) let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) completePromise.succeed(()) } XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait()) // This request is safe to upgrade. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nWeirdcase: yup\r\nConnection: upgrade,weirdcase\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(ByteBuffer.forString(request)).wait()) // Let the machinery do its thing. XCTAssertNoThrow(try completePromise.futureResult.wait()) // We also want to confirm that the upgrade handler is no longer in the pipeline. try connectedServer.pipeline.waitForUpgraderToBeRemoved() } func testDelayedUpgradeBehaviour() throws { let g = DispatchGroup() g.enter() let upgrader = UpgradeDelayer(forProtocol: "myproto") let (group, server, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], extraHandlers: []) { context in g.leave() } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let completePromise = group.next().makePromise(of: Void.self) let clientHandler = SingleHTTPResponseAccumulator { buffers in let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) completePromise.succeed(()) } XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait()) // This request is safe to upgrade. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nConnection: upgrade\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) g.wait() // Ok, we don't think this upgrade should have succeeded yet, but neither should it have failed. We want to // dispatch onto the server event loop and check that the channel still contains the upgrade handler. try connectedServer.pipeline.assertContainsUpgrader() // Ok, let's unblock the upgrade now. The machinery should do its thing. try server.eventLoop.submit { upgrader.unblockUpgrade() }.wait() XCTAssertNoThrow(try completePromise.futureResult.wait()) client.close(promise: nil) try connectedServer.pipeline.waitForUpgraderToBeRemoved() } func testBuffersInboundDataDuringDelayedUpgrade() throws { let g = DispatchGroup() g.enter() let upgrader = UpgradeDelayer(forProtocol: "myproto") let dataRecorder = DataRecorder<ByteBuffer>() let (group, server, client, _) = try setUpTestWithAutoremoval(upgraders: [upgrader], extraHandlers: [dataRecorder]) { context in g.leave() } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let completePromise = group.next().makePromise(of: Void.self) let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) completePromise.succeed(()) } XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait()) // This request is safe to upgrade, but is immediately followed by non-HTTP data that will probably // blow up the HTTP parser. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nConnection: upgrade\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // Wait for the upgrade machinery to run. g.wait() // Ok, send the application data in. let appData = "supersecretawesome data definitely not http\r\nawesome\r\ndata\ryeah" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(appData))).wait()) // Now we need to wait a little bit before we move forward. This needs to give time for the // I/O to settle. 100ms should be plenty to handle that I/O. try server.eventLoop.scheduleTask(in: .milliseconds(100)) { upgrader.unblockUpgrade() }.futureResult.wait() client.close(promise: nil) XCTAssertNoThrow(try completePromise.futureResult.wait()) // Let's check that the data recorder saw everything. let data = try server.eventLoop.submit { dataRecorder.receivedData() }.wait() let resultString = data.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") XCTAssertEqual(resultString, appData) } func testDelayedUpgradeResponse() throws { let channel = EmbeddedChannel() defer { XCTAssertNoThrow(try channel.finish()) } var upgradeRequested = false let delayedPromise = channel.eventLoop.makePromise(of: Void.self) let delayedUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") { XCTAssertFalse(upgradeRequested) upgradeRequested = true return delayedPromise.futureResult } XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withServerUpgrade: (upgraders: [delayedUpgrader], completionHandler: { context in })).wait()) // Let's send in an upgrade request. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) // Upgrade has been requested but not proceeded. XCTAssertTrue(upgradeRequested) XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) XCTAssertNoThrow(try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self))) // Ok, now we can upgrade. Upgrader should be out of the pipeline, and we should have seen the 101 response. delayedPromise.succeed(()) channel.embeddedEventLoop.run() XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) XCTAssertNoThrow(assertResponseIs(response: try channel.readAllOutboundString(), expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"])) } func testChainsDelayedUpgradesAppropriately() throws { enum No: Error { case no } let channel = EmbeddedChannel() defer { do { let complete = try channel.finish() XCTAssertTrue(complete.isClean) } catch No.no { // ok } catch { XCTFail("Unexpected error: \(error)") } } var upgradingProtocol = "" let failingProtocolPromise = channel.eventLoop.makePromise(of: Void.self) let failingProtocolUpgrader = UpgradeResponseDelayer(forProtocol: "failingProtocol") { XCTAssertEqual(upgradingProtocol, "") upgradingProtocol = "failingProtocol" return failingProtocolPromise.futureResult } let myprotoPromise = channel.eventLoop.makePromise(of: Void.self) let myprotoUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") { XCTAssertEqual(upgradingProtocol, "failingProtocol") upgradingProtocol = "myproto" return myprotoPromise.futureResult } XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withServerUpgrade: (upgraders: [myprotoUpgrader, failingProtocolUpgrader], completionHandler: { context in })).wait()) // Let's send in an upgrade request. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: failingProtocol, myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) // Upgrade has been requested but not proceeded for the failing protocol. XCTAssertEqual(upgradingProtocol, "failingProtocol") XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self))) XCTAssertNoThrow(try channel.throwIfErrorCaught()) // Ok, now we'll fail the promise. This will catch an error, but the upgrade won't happen: instead, the second handler will be fired. failingProtocolPromise.fail(No.no) XCTAssertEqual(upgradingProtocol, "myproto") XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self))) do { try channel.throwIfErrorCaught() XCTFail("Did not throw") } catch No.no { // ok } catch { XCTFail("Unexpected error: \(error)") } // Ok, now we can upgrade. Upgrader should be out of the pipeline, and we should have seen the 101 response. myprotoPromise.succeed(()) channel.embeddedEventLoop.run() XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) assertResponseIs(response: try channel.readAllOutboundString(), expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) } func testDelayedUpgradeResponseDeliversFullRequest() throws { enum No: Error { case no } let channel = EmbeddedChannel() defer { do { let isCleanOnFinish = try channel.finish().isClean XCTAssertTrue(isCleanOnFinish) } catch No.no { // ok } catch { XCTFail("Unexpected error: \(error)") } } var upgradeRequested = false let delayedPromise = channel.eventLoop.makePromise(of: Void.self) let delayedUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") { XCTAssertFalse(upgradeRequested) upgradeRequested = true return delayedPromise.futureResult } XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withServerUpgrade: (upgraders: [delayedUpgrader], completionHandler: { context in })).wait()) // Let's send in an upgrade request. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) // Upgrade has been requested but not proceeded. XCTAssertTrue(upgradeRequested) XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self))) XCTAssertNoThrow(try channel.throwIfErrorCaught()) // Ok, now we fail the upgrade. This fires an error, and then delivers the original request. delayedPromise.fail(No.no) XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self))) do { try channel.throwIfErrorCaught() XCTFail("Did not throw") } catch No.no { // ok } catch { XCTFail("Unexpected error: \(error)") } switch try channel.readInbound(as: HTTPServerRequestPart.self) { case .some(.head): // ok break case let t: XCTFail("Expected .head, got \(String(describing: t))") } switch try channel.readInbound(as: HTTPServerRequestPart.self) { case .some(.end): // ok break case let t: XCTFail("Expected .head, got \(String(describing: t))") } XCTAssertNoThrow(XCTAssertNil(try channel.readInbound(as: HTTPServerRequestPart.self))) } func testDelayedUpgradeResponseDeliversFullRequestAndPendingBits() throws { enum No: Error { case no } let channel = EmbeddedChannel() defer { do { let isCleanOnFinish = try channel.finish().isClean XCTAssertTrue(isCleanOnFinish) } catch No.no { // ok } catch { XCTFail("Unexpected error: \(error)") } } var upgradeRequested = false let delayedPromise = channel.eventLoop.makePromise(of: Void.self) let delayedUpgrader = UpgradeResponseDelayer(forProtocol: "myproto") { XCTAssertFalse(upgradeRequested) upgradeRequested = true return delayedPromise.futureResult } // Here we're disabling the pipeline handler, because otherwise it makes this test case impossible to reach. XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false, withServerUpgrade: (upgraders: [delayedUpgrader], completionHandler: { context in })).wait()) // Let's send in an upgrade request. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) // Upgrade has been requested but not proceeded. XCTAssertTrue(upgradeRequested) XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self))) XCTAssertNoThrow(try channel.throwIfErrorCaught()) // We now need to inject an extra buffered request. To do this we grab the context for the HTTPRequestDecoder and inject some reads. XCTAssertNoThrow(try channel.pipeline.context(handlerType: ByteToMessageHandler<HTTPRequestDecoder>.self).map { context in let requestHead = HTTPServerRequestPart.head(.init(version: .init(major: 1, minor: 1), method: .GET, uri: "/test")) context.fireChannelRead(NIOAny(requestHead)) context.fireChannelRead(NIOAny(HTTPServerRequestPart.end(nil))) }.wait()) // Ok, now we fail the upgrade. This fires an error, and then delivers the original request and the buffered one. delayedPromise.fail(No.no) XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) XCTAssertNoThrow(XCTAssertNil(try channel.readOutbound(as: ByteBuffer.self))) do { try channel.throwIfErrorCaught() XCTFail("Did not throw") } catch No.no { // ok } catch { XCTFail("Unexpected error: \(error)") } switch try channel.readInbound(as: HTTPServerRequestPart.self) { case .some(.head(let h)): XCTAssertEqual(h.method, .OPTIONS) case let t: XCTFail("Expected .head, got \(String(describing: t))") } switch try channel.readInbound(as: HTTPServerRequestPart.self) { case .some(.end): // ok break case let t: XCTFail("Expected .head, got \(String(describing: t))") } switch try channel.readInbound(as: HTTPServerRequestPart.self) { case .some(.head(let h)): XCTAssertEqual(h.method, .GET) case let t: XCTFail("Expected .head, got \(String(describing: t))") } switch try channel.readInbound(as: HTTPServerRequestPart.self) { case .some(.end): // ok break case let t: XCTFail("Expected .head, got \(String(describing: t))") } XCTAssertNoThrow(XCTAssertNil(try channel.readInbound(as: HTTPServerRequestPart.self))) } func testRemovesAllHTTPRelatedHandlersAfterUpgrade() throws { let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: []) { req in } let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(pipelining: true, upgraders: [upgrader], extraHandlers: []) { context in } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } // First, validate the pipeline is right. XCTAssertNoThrow(try connectedServer.pipeline.assertContains(handlerType: ByteToMessageHandler<HTTPRequestDecoder>.self)) XCTAssertNoThrow(try connectedServer.pipeline.assertContains(handlerType: HTTPResponseEncoder.self)) XCTAssertNoThrow(try connectedServer.pipeline.assertContains(handlerType: HTTPServerPipelineHandler.self)) // This request is safe to upgrade. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // Let the machinery do its thing. XCTAssertNoThrow(try connectedServer.pipeline.waitForUpgraderToBeRemoved()) // At this time we should validate that none of the HTTP handlers in the pipeline exist. XCTAssertNoThrow(try connectedServer.pipeline.assertDoesNotContain(handlerType: ByteToMessageHandler<HTTPRequestDecoder>.self)) XCTAssertNoThrow(try connectedServer.pipeline.assertDoesNotContain(handlerType: HTTPResponseEncoder.self)) XCTAssertNoThrow(try connectedServer.pipeline.assertDoesNotContain(handlerType: HTTPServerPipelineHandler.self)) } func testUpgradeWithUpgradePayloadInlineWithRequestWorks() throws { enum ReceivedTheWrongThingError: Error { case error } var upgradeRequest: HTTPRequestHead? = nil var upgradeHandlerCbFired = false var upgraderCbFired = false class CheckWeReadInlineAndExtraData: ChannelDuplexHandler { typealias InboundIn = ByteBuffer typealias OutboundIn = Never typealias OutboundOut = Never enum State { case fresh case added case inlineDataRead case extraDataRead case closed } private let firstByteDonePromise: EventLoopPromise<Void> private let secondByteDonePromise: EventLoopPromise<Void> private let allDonePromise: EventLoopPromise<Void> private var state = State.fresh init(firstByteDonePromise: EventLoopPromise<Void>, secondByteDonePromise: EventLoopPromise<Void>, allDonePromise: EventLoopPromise<Void>) { self.firstByteDonePromise = firstByteDonePromise self.secondByteDonePromise = secondByteDonePromise self.allDonePromise = allDonePromise } func handlerAdded(context: ChannelHandlerContext) { XCTAssertEqual(.fresh, self.state) self.state = .added } func channelRead(context: ChannelHandlerContext, data: NIOAny) { var buf = self.unwrapInboundIn(data) XCTAssertEqual(1, buf.readableBytes) let stringRead = buf.readString(length: buf.readableBytes) switch self.state { case .added: XCTAssertEqual("A", stringRead) self.state = .inlineDataRead if stringRead == .some("A") { self.firstByteDonePromise.succeed(()) } else { self.firstByteDonePromise.fail(ReceivedTheWrongThingError.error) } case .inlineDataRead: XCTAssertEqual("B", stringRead) self.state = .extraDataRead context.channel.close(promise: nil) if stringRead == .some("B") { self.secondByteDonePromise.succeed(()) } else { self.secondByteDonePromise.fail(ReceivedTheWrongThingError.error) } default: XCTFail("channel read in wrong state \(self.state)") } } func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) { XCTAssertEqual(.extraDataRead, self.state) self.state = .closed context.close(mode: mode, promise: promise) self.allDonePromise.succeed(()) } } let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"]) { req in upgradeRequest = req XCTAssert(upgradeHandlerCbFired) upgraderCbFired = true } let promiseGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try promiseGroup.syncShutdownGracefully()) } let firstByteDonePromise = promiseGroup.next().makePromise(of: Void.self) let secondByteDonePromise = promiseGroup.next().makePromise(of: Void.self) let allDonePromise = promiseGroup.next().makePromise(of: Void.self) let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], extraHandlers: []) { (context) in // This is called before the upgrader gets called. XCTAssertNil(upgradeRequest) upgradeHandlerCbFired = true _ = context.channel.pipeline.addHandler(CheckWeReadInlineAndExtraData(firstByteDonePromise: firstByteDonePromise, secondByteDonePromise: secondByteDonePromise, allDonePromise: allDonePromise)) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let completePromise = group.next().makePromise(of: Void.self) let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) completePromise.succeed(()) } XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait()) // This request is safe to upgrade. var request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" request += "A" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) XCTAssertNoThrow(try firstByteDonePromise.futureResult.wait() as Void) XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString("B"))).wait()) XCTAssertNoThrow(try secondByteDonePromise.futureResult.wait() as Void) XCTAssertNoThrow(try allDonePromise.futureResult.wait() as Void) // Let the machinery do its thing. XCTAssertNoThrow(try completePromise.futureResult.wait()) // At this time we want to assert that everything got called. Their own callbacks assert // that the ordering was correct. XCTAssert(upgradeHandlerCbFired) XCTAssert(upgraderCbFired) // We also want to confirm that the upgrade handler is no longer in the pipeline. try connectedServer.pipeline.assertDoesNotContainUpgrader() XCTAssertNoThrow(try allDonePromise.futureResult.wait()) } func testDeliversBytesWhenRemovedDuringPartialUpgrade() throws { let channel = EmbeddedChannel() defer { XCTAssertNoThrow(try channel.finish()) } let delayer = UpgradeDelayer(forProtocol: "myproto") defer { delayer.unblockUpgrade() } XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withServerUpgrade: (upgraders: [delayer], completionHandler: { context in })).wait()) // Let's send in an upgrade request. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) channel.embeddedEventLoop.run() // Upgrade has been requested but not proceeded. XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) XCTAssertNoThrow(try XCTAssertNil(channel.readInbound(as: ByteBuffer.self))) // The 101 has been sent. guard var responseBuffer = try assertNoThrowWithValue(channel.readOutbound(as: ByteBuffer.self)) else { XCTFail("did not send response") return } XCTAssertNoThrow(try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self))) assertResponseIs(response: responseBuffer.readString(length: responseBuffer.readableBytes)!, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) // Now send in some more bytes. XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString("B"))) XCTAssertNoThrow(try XCTAssertNil(channel.readInbound(as: ByteBuffer.self))) // Now we're going to remove the handler. XCTAssertNoThrow(try channel.pipeline.removeUpgrader()) // This should have delivered the pending bytes and the buffered request, and in all ways have behaved // as though upgrade simply failed. XCTAssertEqual(try assertNoThrowWithValue(channel.readInbound(as: ByteBuffer.self)), ByteBuffer.forString("B")) XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) XCTAssertNoThrow(try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self))) } func testDeliversBytesWhenReentrantlyCalledInChannelReadCompleteOnRemoval() throws { // This is a very specific test: we want to make sure that even the very last gasp of the HTTPServerUpgradeHandler // can still deliver bytes if it gets them. let channel = EmbeddedChannel() defer { XCTAssertNoThrow(try channel.finish()) } let delayer = UpgradeDelayer(forProtocol: "myproto") defer { delayer.unblockUpgrade() } XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withServerUpgrade: (upgraders: [delayer], completionHandler: { context in })).wait()) // Let's send in an upgrade request. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString(request))) channel.embeddedEventLoop.run() // Upgrade has been requested but not proceeded. XCTAssertNoThrow(try channel.pipeline.assertContainsUpgrader()) XCTAssertNoThrow(try XCTAssertNil(channel.readInbound(as: ByteBuffer.self))) // The 101 has been sent. guard var responseBuffer = try assertNoThrowWithValue(channel.readOutbound(as: ByteBuffer.self)) else { XCTFail("did not send response") return } XCTAssertNoThrow(try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self))) assertResponseIs(response: responseBuffer.readString(length: responseBuffer.readableBytes)!, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) // Now send in some more bytes. XCTAssertNoThrow(try channel.writeInbound(ByteBuffer.forString("B"))) XCTAssertNoThrow(try XCTAssertNil(channel.readInbound(as: ByteBuffer.self))) // Ok, now we put in a special handler that does a weird readComplete hook thing. XCTAssertNoThrow(try channel.pipeline.addHandler(ReentrantReadOnChannelReadCompleteHandler()).wait()) // Now we're going to remove the upgrade handler. XCTAssertNoThrow(try channel.pipeline.removeUpgrader()) // We should have received B and then the re-entrant read in that order. XCTAssertEqual(try assertNoThrowWithValue(channel.readInbound(as: ByteBuffer.self)), ByteBuffer.forString("B")) XCTAssertEqual(try assertNoThrowWithValue(channel.readInbound(as: ByteBuffer.self)), ByteBuffer.forString("re-entrant read from channelReadComplete!")) XCTAssertNoThrow(try channel.pipeline.assertDoesNotContainUpgrader()) XCTAssertNoThrow(try XCTAssertNil(channel.readOutbound(as: ByteBuffer.self))) } func testWeTolerateUpgradeFuturesFromWrongEventLoops() throws { var upgradeRequest: HTTPRequestHead? = nil var upgradeHandlerCbFired = false var upgraderCbFired = false let otherELG = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try otherELG.syncShutdownGracefully()) } let upgrader = SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: ["kafkaesque"], buildUpgradeResponseFuture: { // this is the wrong EL otherELG.next().makeSucceededFuture($1) }) { req in upgradeRequest = req XCTAssert(upgradeHandlerCbFired) upgraderCbFired = true } let (group, _, client, connectedServer) = try setUpTestWithAutoremoval(upgraders: [upgrader], extraHandlers: []) { (context) in // This is called before the upgrader gets called. XCTAssertNil(upgradeRequest) upgradeHandlerCbFired = true // We're closing the connection now. context.close(promise: nil) } defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let completePromise = group.next().makePromise(of: Void.self) let clientHandler = ArrayAccumulationHandler<ByteBuffer> { buffers in let resultString = buffers.map { $0.getString(at: $0.readerIndex, length: $0.readableBytes)! }.joined(separator: "") assertResponseIs(response: resultString, expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["X-Upgrade-Complete: true", "upgrade: myproto", "connection: upgrade"]) completePromise.succeed(()) } XCTAssertNoThrow(try client.pipeline.addHandler(clientHandler).wait()) // This request is safe to upgrade. let request = "OPTIONS * HTTP/1.1\r\nHost: localhost\r\nUpgrade: myproto\r\nKafkaesque: yup\r\nConnection: upgrade\r\nConnection: kafkaesque\r\n\r\n" XCTAssertNoThrow(try client.writeAndFlush(NIOAny(ByteBuffer.forString(request))).wait()) // Let the machinery do its thing. XCTAssertNoThrow(try completePromise.futureResult.wait()) // At this time we want to assert that everything got called. Their own callbacks assert // that the ordering was correct. XCTAssert(upgradeHandlerCbFired) XCTAssert(upgraderCbFired) // We also want to confirm that the upgrade handler is no longer in the pipeline. try connectedServer.pipeline.assertDoesNotContainUpgrader() } }
46.668531
192
0.636718
eff6be3074878cd5e6db27735ca8c8fe3562cc46
3,083
// // createEventViewController.swift // RaiderCalendarIOS // // Created by CUNHA MATTHIEU on 14/01/2019. // Copyright © 2019 VM. All rights reserved. // import UIKit class createEventViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var eventName: UITextField! @IBOutlet weak var groupeName: UIPickerView! @IBOutlet weak var datePicker: UIDatePicker! var pickerData: [String] = [] var selectedGroupe: Int=0 var groupList: [Groupe]=[] override func viewDidLoad() { super.viewDidLoad() // Connect data: self.groupeName.delegate = self self.groupeName.dataSource = self // Do any additional setup after loading the view. let user1 = User() self.groupList = user1.getGroupeList(userToken: Token.token) for group in self.groupList{ self.pickerData.append(group.getName()) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // load code self.pickerData = [] let user1 = User() self.groupList = user1.getGroupeList(userToken: Token.token) for group in self.groupList{ self.pickerData.append(group.getName()) } self.groupeName.reloadAllComponents() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // This method is triggered whenever the user makes a change to the picker selection. // The parameter named row and component represents what was selected. self.selectedGroupe=row } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } // The number of rows of data func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.pickerData.count } // The data to return fopr the row and component (column) that's being passed in func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.pickerData[row] } @IBAction func onClickCreate(_ sender: UIButton) { let event = Event(name: eventName.text!,date: datePicker.date) event.saveNew() let groupe = groupList[selectedGroupe] let eventStatus = EventStatus() eventStatus.inviteGroupe(eventId: event.getId(),groupeId: groupe.getId()) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
31.459184
111
0.652611
8f3763963a0f1169ec4f8b764989a93fd012816a
750
// // PageView.swift // WeChatChat // // Created by Ryn on 2020/12/20. // import SwiftUI struct PageView<Page: View>: View { var pages: [Page] @State private var currentPage = 0 var body: some View { ZStack(alignment: .bottomTrailing) { PageViewController(pages: pages, currentPage: $currentPage) PageControl(numberOfPages: pages.count, currentPage: $currentPage) .frame(width: CGFloat(pages.count * 18)) .padding(.trailing) } } } struct PageView_Previews: PreviewProvider { static var previews: some View { PageView(pages: ModelData().features.map { FeatureCard(landmark: $0) }) .aspectRatio(3 / 2, contentMode: .fit) } }
25
79
0.613333
fb7b35946bf677b2a6006685f54f0cd60b2fdb18
4,806
//Copyright © 2019 Vincode, Inc. All rights reserved. import AppKit import RSParser import RSWeb public extension Notification.Name { static let OPMLDidLoad = Notification.Name(rawValue: "OPMLDidLoad") static let UserDidAddOPML = Notification.Name(rawValue: "UserDidAddOPML") } final class OPMLLoader { private static let opmlDirectoryURL = URL(string: "https://gist.githubusercontent.com/vincode-io/dec612f2da3270c94f2e0ca11f242753/raw/")! private lazy var downloadSession: DownloadSession = { return DownloadSession(delegate: self) }() static var shared = { OPMLLoader() }() struct UserInfoKey { public static let opmlDocument = "opmlDocument" // OPMLDidDownload } var directoryEntries = [String : OPMLDirectoryEntry]() var progress: DownloadProgress { return downloadSession.progress } func load() { download(OPMLLoader.opmlDirectoryURL) { [weak self] (data: Data?, response: URLResponse?, error: Error?) in guard let data = data else { let error = NSLocalizedString("Unable to load OPML Directory", comment: "Unable to load OPML Directory") NSApplication.shared.presentError(error) return } let decoder = JSONDecoder() guard var entries = try? decoder.decode([OPMLDirectoryEntry].self, from: data) else { let error = NSLocalizedString("Unable to decode OPML Directory", comment: "Unable to decode OPML Directory") NSApplication.shared.presentError(error) return } entries.forEach { self?.directoryEntries[$0.url] = $0 } if let userURLs = AppDefaults.userSubscriptions { for userURL in userURLs { entries.append(OPMLDirectoryEntry(title: nil, url: userURL, description: nil, contributeURL: nil, userDefined: nil)) } } self?.downloadSession.downloadObjects(Set(entries) as NSSet) } } func loadUserDefined(url: String) { guard let downloadURL = URL(string: url) else { return } download(downloadURL) { (data: Data?, response: URLResponse?, error: Error?) in guard let url = response?.url?.absoluteString, let data = data else { let error = NSLocalizedString("OPML Not Found", comment: "OPML Not Found") NSApplication.shared.presentError(error) return } let parserData = ParserData(url: url, data: data) if let opmlDocument = try? RSOPMLParser.parseOPML(with: parserData) { var userInfo = [String: Any]() userInfo[OPMLLoader.UserInfoKey.opmlDocument] = opmlDocument NotificationCenter.default.post(name: .UserDidAddOPML, object: nil, userInfo: userInfo) } else { let error = NSLocalizedString("Invalid OPML Format", comment: "Invalid OPML Format") NSApplication.shared.presentError(error) return } } } func loadLocal(url: URL) { guard let data = try? Data(contentsOf: url) else { return } let parserData = ParserData(url: url.absoluteString, data: data) if let opmlDocument = try? RSOPMLParser.parseOPML(with: parserData) { var userInfo = [String: Any]() userInfo[OPMLLoader.UserInfoKey.opmlDocument] = opmlDocument NotificationCenter.default.post(name: .UserDidAddOPML, object: self, userInfo: userInfo) } } } // MARK: - DownloadSessionDelegate extension OPMLLoader: DownloadSessionDelegate { func downloadSession(_ downloadSession: DownloadSession, requestForRepresentedObject representedObject: AnyObject) -> URLRequest? { guard let entry = representedObject as? OPMLDirectoryEntry else { return nil } guard let url = URL(string: entry.url) else { return nil } return URLRequest(url: url) } func downloadSession(_ downloadSession: DownloadSession, downloadDidCompleteForRepresentedObject representedObject: AnyObject, response: URLResponse?, data: Data, error: NSError?) { guard let entry = representedObject as? OPMLDirectoryEntry else { return } if let error = error { print("Error downloading \(entry.url) - \(error)") return } let parserData = ParserData(url: entry.url, data: data) if let opmlDocument = try? RSOPMLParser.parseOPML(with: parserData) { if entry.title != nil { opmlDocument.title = entry.title } var userInfo = [String: Any]() userInfo[OPMLLoader.UserInfoKey.opmlDocument] = opmlDocument NotificationCenter.default.post(name: .OPMLDidLoad, object: self, userInfo: userInfo) } } func downloadSession(_ downloadSession: DownloadSession, shouldContinueAfterReceivingData data: Data, representedObject: AnyObject) -> Bool { return true } func downloadSession(_ downloadSession: DownloadSession, didReceiveUnexpectedResponse response: URLResponse, representedObject: AnyObject) { } func downloadSession(_ downloadSession: DownloadSession, didReceiveNotModifiedResponse: URLResponse, representedObject: AnyObject) { } }
28.778443
182
0.725551
896ad2837903cb23091f71fc98dbc8006a76a83a
6,624
// // Copyright © 2020 Anonyome Labs, Inc. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation import SudoKeyManager import SudoUser import AWSAppSync import SudoLogging import SudoApiClient /// Result returned by APIs for retrieve Sudo owernship proof. The API can fail /// with an error or return a signed proof in form of JWT. /// /// - success: Ownership proof was retrieved successfully. /// - failure: Ownership proof retrieval failed with an error. public enum GetOwnershipProofResult { case success(jwt: String) case failure(cause: Error) } // Protocol encapsulating APIs for issuing ownership proofs. // These APIs are used by other Sudo platform clients and any // app developed using this SDK is not expected to use these // APIs directly. public protocol OwnershipProofIssuer: AnyObject { /// Retrieves a signed owernship proof for the specified owner. The owership /// proof JWT has the follow payload. /// /// { /// "jti": "DBEEF4EB-F84A-4AB7-A45E-02B05B93F5A3", /// "owner": "cd73a478-23bd-4c70-8c2b-1403e2085845", /// "iss": "sudoplatform.sudoservice", /// "aud": "sudoplatform.virtualcardservice", /// "exp": 1578986266, /// "sub": "da17f346-cf49-4db4-98c2-862f85515fc4", /// "iat": 1578982666 /// } /// /// "owner" is an unique ID of an identity managed by the issuing service. In /// case of Sudo service this represents unique reference to a Sudo. /// "sub" is the subject to which this proof is issued to i.e. the user. /// "aud" is the target audience of the proof. /// /// - Parameters: /// - ownerId: Owner ID. /// - subject: Subject to which the proof is issued to. /// - audience: Target audience for this proof. /// - completion: Completion handler to pass back the proof or any error. func getOwnershipProof(ownerId: String, subject: String, audience: String, completion: @escaping (GetOwnershipProofResult) -> Void) throws } /// `OwnershipProofIssuer` implementation that uses Sudo service to issue the required /// ownership proof. class DefaultOwnershipProofIssuer: OwnershipProofIssuer { private struct Constants { static let sudoNotFoundError = "sudoplatform.sudo.SudoNotFound" static let serviceError = "sudoplatform.ServiceError" static let insufficientEntitlementsError = "sudoplatform.InsufficientEntitlementsError" } private let graphQLClient: SudoApiClient private let logger: Logger private let queue = DispatchQueue(label: "com.sudoplatform.sudoprofiles.client.ownership.issuer") /// Initializes a `DefaultOwnershipProofIssuer`. /// /// - Parameters: /// - graphQLClient: GraphQL client to use to contact Sudo service. /// - logger: Logger to use for logging. init(graphQLClient: SudoApiClient, logger: Logger = Logger.sudoProfilesClientLogger) throws { self.graphQLClient = graphQLClient self.logger = logger } func getOwnershipProof(ownerId: String, subject: String, audience: String, completion: @escaping (GetOwnershipProofResult) -> Void) throws { do { try self.graphQLClient.perform( mutation: GetOwnershipProofMutation(input: GetOwnershipProofInput(sudoId: ownerId, audience: audience)), queue: self.queue, resultHandler: { (result, error) in if let error = error { self.logger.error("Failed to retrieve ownership proof: \(error)") return completion(.failure(cause: SudoProfilesClientError.fromApiOperationError(error: error))) } guard let result = result else { return completion(.failure(cause: SudoProfilesClientError.fatalError(description: "Mutation completed successfully but result is missing."))) } if let error = result.errors?.first { self.logger.error("Failed to retrieve ownership proof: \(error)") return completion(.failure(cause: SudoProfilesClientError.fromApiOperationError(error: error))) } guard let jwt = result.data?.getOwnershipProof?.jwt else { return completion(.failure(cause: SudoProfilesClientError.fatalError(description: "Mutation result did not contain required object."))) } completion(.success(jwt: jwt)) }) } catch { throw SudoProfilesClientError.fromApiOperationError(error: error) } } } /// `OwnershipProofIssuer` implementation that uses a locally stored RSA private key /// to generated the ownership proof. Mainly used for testing. public class ClientOwnershipProofIssuer: OwnershipProofIssuer { private let keyManager: SudoKeyManager private let keyId: String private let issuer: String /// Initializes a `ClientOwnershipProofIssuer`. /// /// - Parameters: /// - privateKey: PEM encoded RSA private key to use for signing the ownership proof. /// - keyManager: `KeyManager` instance to use for cryptographic operations. /// - keyId: Key ID to use for storing the RSA private key in the keychain. /// - issuer: Issuer name to use for the ownership proof. public init(privateKey: String, keyManager: SudoKeyManager, keyId: String, issuer: String) throws { var privateKey = privateKey privateKey = privateKey.replacingOccurrences(of: "\n", with: "") privateKey = privateKey.replacingOccurrences(of: "-----BEGIN RSA PRIVATE KEY-----", with: "") privateKey = privateKey.replacingOccurrences(of: "-----END RSA PRIVATE KEY-----", with: "") guard let keyData = Data(base64Encoded: privateKey) else { throw SudoProfilesClientError.invalidConfig } self.keyManager = keyManager self.keyId = keyId self.issuer = issuer try self.keyManager.deleteKeyPair(keyId) try self.keyManager.addPrivateKey(keyData, name: keyId) } public func getOwnershipProof(ownerId: String, subject: String, audience: String, completion: @escaping (GetOwnershipProofResult) -> Void) throws { let jwt = JWT(issuer: self.issuer, audience: audience, subject: subject, id: UUID().uuidString) jwt.payload["owner"] = ownerId let encoded = try jwt.signAndEncode(keyManager: self.keyManager, keyId: self.keyId) completion(GetOwnershipProofResult.success(jwt: encoded)) } }
41.660377
165
0.666667
61cffb937230558abb235425616cdcc0a22da5ec
5,089
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s class C {} enum Foo { case X(C, Int) } // <rdar://problem/16020428> // CHECK-LABEL: sil hidden @_TF6tuples8matchFooFT1xOS_3Foo_T_ func matchFoo(x x: Foo) { switch x { case .X(let x): () } } protocol P { func foo() } struct A : P { func foo() {} } func make_int() -> Int { return 0 } func make_p() -> P { return A() } func make_xy() -> (x: Int, y: P) { return (make_int(), make_p()) } // CHECK-LABEL: sil hidden @_TF6tuples17testShuffleOpaqueFT_T_ func testShuffleOpaque() { // CHECK: [[X:%.*]] = alloc_box $P // CHECK: [[Y:%.*]] = alloc_box $Int // CHECK: [[T0:%.*]] = function_ref @_TF6tuples7make_xyFT_T1xSi1yPS_1P__ // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $(x: Int, y: P) // CHECK-NEXT: apply [[T0]]([[TEMP]]#1) // CHECK-NEXT: [[T0:%.*]] = tuple_element_addr [[TEMP]]#1 : $*(x: Int, y: P), 0 // CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*Int // CHECK-NEXT: [[T2:%.*]] = tuple_element_addr [[TEMP]]#1 : $*(x: Int, y: P), 1 // CHECK-NEXT: store [[T1]] to [[Y]]#1 // CHECK-NEXT: copy_addr [take] [[T2]] to [initialization] [[X]]#1 // CHECK-NEXT: dealloc_stack [[TEMP]] var (x,y) : (y:P, x:Int) = make_xy() // CHECK-NEXT: [[PAIR:%.*]] = alloc_box $(y: P, x: Int) // CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]]#1 : $*(y: P, x: Int), 0 // CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[PAIR]]#1 : $*(y: P, x: Int), 1 // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples7make_xyFT_T1xSi1yPS_1P__ // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $(x: Int, y: P) // CHECK-NEXT: apply [[T0]]([[TEMP]]#1) // CHECK-NEXT: [[T0:%.*]] = tuple_element_addr [[TEMP]]#1 : $*(x: Int, y: P), 0 // CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*Int // CHECK-NEXT: [[T2:%.*]] = tuple_element_addr [[TEMP]]#1 : $*(x: Int, y: P), 1 // CHECK-NEXT: store [[T1]] to [[PAIR_1]] // CHECK-NEXT: copy_addr [take] [[T2]] to [initialization] [[PAIR_0]] // CHECK-NEXT: dealloc_stack [[TEMP]] var pair : (y:P, x:Int) = make_xy() // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples7make_xyFT_T1xSi1yPS_1P__ // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $(x: Int, y: P) // CHECK-NEXT: apply [[T0]]([[TEMP]]#1) // CHECK-NEXT: [[T0:%.*]] = tuple_element_addr [[TEMP]]#1 : $*(x: Int, y: P), 0 // CHECK-NEXT: [[T1:%.*]] = load [[T0]] : $*Int // CHECK-NEXT: [[T2:%.*]] = tuple_element_addr [[TEMP]]#1 : $*(x: Int, y: P), 1 // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $(y: P, x: Int) // CHECK-NEXT: [[TEMP2_0:%.*]] = tuple_element_addr [[TEMP2]]#1 : $*(y: P, x: Int), 0 // CHECK-NEXT: copy_addr [take] [[T2]] to [initialization] [[TEMP2_0]] // CHECK-NEXT: [[TEMP2_1:%.*]] = tuple_element_addr [[TEMP2]]#1 : $*(y: P, x: Int), 1 // CHECK-NEXT: store [[T1]] to [[TEMP2_1]] // CHECK-NEXT: copy_addr [take] [[TEMP2]]#1 to [[PAIR]]#1 // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: dealloc_stack [[TEMP]] pair = make_xy() } func testShuffleTuple() { // CHECK: [[X:%.*]] = alloc_box $P // CHECK: [[Y:%.*]] = alloc_box $Int // CHECK: [[T0:%.*]] = function_ref @_TF6tuples8make_intFT_Si // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]() // CHECK-NEXT: store [[T1]] to [[Y]]#1 // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples6make_pFT_PS_1P_ // CHECK-NEXT: apply [[T0]]([[X]]#1) var (x,y) : (y:P, x:Int) = (x: make_int(), y: make_p()) // CHECK-NEXT: [[PAIR:%.*]] = alloc_box $(y: P, x: Int) // CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]]#1 : $*(y: P, x: Int), 0 // CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[PAIR]]#1 : $*(y: P, x: Int), 1 // CHECK-NEXT: // function_ref // CHECK: [[T0:%.*]] = function_ref @_TF6tuples8make_intFT_Si // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]() // CHECK-NEXT: store [[T1]] to [[PAIR_1]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples6make_pFT_PS_1P_ // CHECK-NEXT: apply [[T0]]([[PAIR_0]]) var pair : (y:P, x:Int) = (x: make_int(), y: make_p()) // This isn't really optimal; we should be evaluating make_p directly // into the temporary. // CHECK-NEXT: // function_ref // CHECK: [[T0:%.*]] = function_ref @_TF6tuples8make_intFT_Si // CHECK-NEXT: [[INT:%.*]] = apply [[T0]]() // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6tuples6make_pFT_PS_1P_ // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $P // CHECK-NEXT: apply [[T0]]([[TEMP]]#1) // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $(y: P, x: Int) // CHECK-NEXT: [[TEMP2_0:%.*]] = tuple_element_addr [[TEMP2]]#1 : $*(y: P, x: Int), 0 // CHECK-NEXT: copy_addr [take] [[TEMP]]#1 to [initialization] [[TEMP2_0]] // CHECK-NEXT: [[TEMP2_1:%.*]] = tuple_element_addr [[TEMP2]]#1 : $*(y: P, x: Int), 1 // CHECK-NEXT: store [[INT]] to [[TEMP2_1]] // CHECK-NEXT: copy_addr [take] [[TEMP2]]#1 to [[PAIR]]#1 // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: dealloc_stack [[TEMP]] pair = (x: make_int(), y: make_p()) }
44.252174
87
0.563175
8a4b767337a3f72839a14542588facf27bddb5e3
739
// // SavedPostsListView.swift // RedditOs // // Created by Thomas Ricouard on 24/07/2020. // import SwiftUI import Backend struct SavedPostsListView: View { @EnvironmentObject private var currentUser: CurrentUserStore @State private var displayMode = SubredditPostRow.DisplayMode.large var body: some View { PostsListView(posts: currentUser.savedPosts, displayMode: $displayMode) { currentUser.fetchSaved(after: currentUser.savedPosts?.last) }.onAppear { currentUser.fetchSaved(after: nil) } .navigationTitle("Saved") } } struct SavedPostListView_Previews: PreviewProvider { static var previews: some View { SavedPostsListView() } }
23.09375
71
0.682003
690afd65a62819d293093cc996d01c892f5307e2
1,250
// // CountDownTimerUITests.swift // CountDownTimerUITests // // Created by apple on 16/1/3. // Copyright © 2016年 apple. All rights reserved. // import XCTest class CountDownTimerUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.783784
182
0.6656
189209bc370d939c22b421c0e9dab3efaa1ebc1b
153
// // Bezier.swift // Example iOS // // Created by Colin Duffy on 12/29/19. // Copyright © 2019 Reza Ali. All rights reserved. // import Foundation
15.3
51
0.660131
f72a923554e2962e045285b622007afd940eff2a
882
// // DeleteAllRevokedChatInviteLinks.swift // tl2swift // // Generated automatically. Any changes will be lost! // Based on TDLib 1.8.0-fa8feefe // https://github.com/tdlib/td/tree/fa8feefe // import Foundation /// Deletes all revoked chat invite links created by a given chat administrator. Requires administrator privileges and can_invite_users right in the chat for own links and owner privileges for other links public struct DeleteAllRevokedChatInviteLinks: Codable, Equatable { /// Chat identifier public let chatId: Int64? /// User identifier of a chat administrator, which links will be deleted. Must be an identifier of the current user for non-owner public let creatorUserId: Int64? public init( chatId: Int64?, creatorUserId: Int64? ) { self.chatId = chatId self.creatorUserId = creatorUserId } }
27.5625
204
0.719955
90d6b88a18032199a1a24d2eb8a32225c75140b4
5,986
// // iPadKeyboardLayoutProvider.swift // KeyboardKit // // Created by Daniel Saidi on 2021-02-02. // Copyright © 2021 Daniel Saidi. All rights reserved. // import SwiftUI /** This class provides layouts that correspond to an iPad with a home button, adding iPad-specific system buttons around a basic set of input actions. You can inherit this class and override any open properties and functions to customize the standard behavior. `TODO` This class is currently used for iPad Air/Pro. These device types should use a different layout. `TODO` This class sizes buttons according to their expected size on an English keyboard. Other locales and orientations may need customizations. `IMPORTANT` This layout provider has only been tested for a couple of locales. If you create a new input set and use it with this layout, you may find that buttons are incorrectly sized or placed. If so, create a new layout provider either from scratch or by inheriting this one. Also, open an issue if you think that a supported locale get the wrong size. */ open class iPadKeyboardLayoutProvider: BaseKeyboardLayoutProvider { // MARK: - Overrides /** Get keyboard actions for the provided context and inputs. */ open override func actions(for context: KeyboardContext, inputs: KeyboardInputRows) -> KeyboardActionRows { var actions = super.actions(for: context, inputs: inputs) assert(actions.count > 2, "iPad layouts require at least 3 input rows.") let last = actions.suffix(3) actions.removeLast(3) actions.append(last[0] + [.backspace]) actions.append([.none] + last[1] + [.newLine]) actions.append(lowerLeadingActions(for: context) + last[2] + lowerTrailingActions(for: context)) actions.append(bottomActions(for: context)) return actions } open override func itemSizeWidth(for context: KeyboardContext, action: KeyboardAction, row: Int, index: Int) -> KeyboardLayoutItemWidth { if isSecondRowSpacer(action, row: row, index: index) { return .inputPercentage(0.4) } if isSecondBottomSwitcher(action, row: row, index: index) { return .inputPercentage(2) } switch action { case dictationReplacement: return .input case .backspace: return .percentage(0.1) case .dismissKeyboard: return .inputPercentage(1.8) case .keyboardType: return row == 2 ? .available : .input case .nextKeyboard: return .input default: return super.itemSizeWidth(for: context, action: action, row: row, index: index) } } // MARK: - iPad Specific /** Get the bottom action row that should be below the main rows on input buttons. */ open func bottomActions(for context: KeyboardContext) -> KeyboardActionRow { var result = KeyboardActions() let needsDictation = context.needsInputModeSwitchKey if let action = keyboardSwitchActionForBottomRow(for: context) { result.append(action) } result.append(.nextKeyboard) if needsDictation, let action = dictationReplacement { result.append(action) } result.append(.space) if let action = keyboardSwitchActionForBottomRow(for: context) { result.append(action) } result.append(.dismissKeyboard) return result } open func lowerLeadingActions(for context: KeyboardContext) -> KeyboardActions { guard let action = keyboardSwitchActionForBottomInputRow(for: context) else { return [] } return [action] } open func lowerTrailingActions(for context: KeyboardContext) -> KeyboardActions { guard let action = keyboardSwitchActionForBottomInputRow(for: context) else { return [] } return [action] } } private extension iPadKeyboardLayoutProvider { func isSecondBottomSwitcher(_ action: KeyboardAction, row: Int, index: Int) -> Bool { switch action { case .keyboardType: return row == 3 && index > 3 default: return false } } func isSecondRowSpacer(_ action: KeyboardAction, row: Int, index: Int) -> Bool { switch action { case .none: return row == 1 && index == 0 default: return false } } } struct iPadKeyboardLayoutProvider_Previews: PreviewProvider { static var context = KeyboardContext.preview static var input = StandardKeyboardInputSetProvider(context: context) static var layout = iPadKeyboardLayoutProvider(inputSetProvider: input) static func previews(for locale: Locale, title: String) -> some View { ScrollView { Text(title).font(.title) preview(for: locale, type: .alphabetic(.lowercased)) preview(for: locale, type: .numeric) preview(for: locale, type: .symbolic) }.padding() } static func preview(for locale: Locale, type: KeyboardType) -> some View { context.locale = locale context.keyboardType = type return VStack { SystemKeyboard( layout: layout.keyboardLayout(for: context), appearance: StandardKeyboardAppearance(context: context), actionHandler: PreviewKeyboardActionHandler(), width: 768) .frame(width: 768) .environmentObject(context) .environmentObject(InputCalloutContext.preview) .environmentObject(SecondaryInputCalloutContext.preview) .background(Color.gray) } } static var previews: some View { Group { previews(for: LocaleKey.english.locale, title: "English") previews(for: LocaleKey.german.locale, title: "German") previews(for: LocaleKey.italian.locale, title: "Italian") previews(for: LocaleKey.swedish.locale, title: "Swedish") }.previewLayout(.sizeThatFits) } }
38.127389
141
0.664049
ed0cc557e3472d0fe600f78861890757b670c516
2,815
// // Constants.swift // ZiMu // // Created by FanYuepan on 2018/3/25. // Copyright © 2018年 Fancy. All rights reserved. // import Foundation import UIKit /// third party /// size let kWindow = UIApplication.shared.keyWindow let kScreenFrame = UIScreen.main.bounds let kScreenWidth: CGFloat = UIScreen.main.bounds.size.width let kScreenHeight: CGFloat = UIScreen.main.bounds.size.height let IPHONE6_SCREEN_WIDTH: CGFloat = 375.0 let IPHONE6_SCREEN_HEIGHT: CGFloat = 667.0 let kNavigationBarHeight: CGFloat = 44.0 let kTabbarHeight: CGFloat = (Device() == .simulator(.iPhoneX) || Device() == .iPhoneX) ? (49.0 + 34.0) : 49.0 let kStatusBarHeight: CGFloat = (Device() == .simulator(.iPhoneX) || Device() == .iPhoneX) ? 44.0 : 20.0 let kTabbarSafeBottomMargin: CGFloat = (Device() == .simulator(.iPhoneX) || Device() == .iPhoneX) ? 34.0 : 0 /// system let kNotificationCenter = NotificationCenter.default let kUserDefaults = UserDefaults.standard let kBundle = Bundle.main let kApplication = UIApplication.shared let kAppDelegate = kApplication.delegate as! AppDelegate /// notification /// Font let kFontLightName = "PingFangSC-Light" let kFontMediumName = "PingFangSC-Medium" let kFontRegularName = "PingFangSC-Regular" let kFontSemiboldName = "PingFangSC-Semibold" /// url routes let APP_STORE_DOWNLOAD_URL = "https://itunes.apple.com/cn/app/zimu/id1373116179?l=zh&ls=1&mt=8" let APP_STORE_COMMENT_URL = "https://itunes.apple.com/cn/app/zimu/id1373116179?mt=8&action=write-review" /// 语言 let APP_LANGUAGE = "AppLanguage" /// 中英语 let CHINESE_SIMPLIFIED = "zh-Hans" let ENGLISH = "en" /// catch key /// network let OFFICIAL_SITE = "http://www.zimuxia.cn/" let CAT_KOREA = "fix韩语社" let CAT_GERMANY = "昆仑德语社" let CAT_JAPAN = "fix日语社" let CAT_FRANCE = "fix法语社" let CAT_USA_TV = "欧美剧集" let CAT_USA_MOVIE = "欧美电影" let CAT_USA_DOCUMENTARY = "综艺纪录" // MARK: - typealias typealias VoidCallback = (() -> Void) // MARK:-Public function /// measure code run time /// /// - Parameter f: code for measure func measure(f: ()->()) { let start = CACurrentMediaTime() f() let end = CACurrentMediaTime() dPrint("测量时间:\(end - start)") } /// debug log /// /// - Parameter item: any object to log func dPrint(_ item: @autoclosure () -> Any) { #if DEBUG print(item()) #endif } /// debug info log /// /// - Parameter item: any message to log func dPrint(message: String = "", file: String = #file, function: String = #function, lineNum: Int = #line) { #if DEBUG let data = Date(timeIntervalSinceNow: 0) let formater = DateFormatter() formater.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" let dateString = formater.string(from: data) print("< \(dateString) \(URL(string: file)!.lastPathComponent),\(function),(\(lineNum)) > \(message)") #endif }
27.871287
110
0.693073
ab04f4d67cad1a15dbb0f98fab8bdf855278f4da
321
struct CoordinatePoint { var x: Int var y: Int } class Position { var point: CoordinatePoint? // 현재 사람 위치를 모를 수 있다 let name: String init(name: String) { self.name = name } } let yagomPosition: Position = Position(name: "yagom") yagomPosition.point = CoordinatePoint(x: 20, y: 10)
16.894737
53
0.629283
c1cb23d4bcb37cb4d8b6e71d32b67c50489b2a14
2,047
// // File.swift // // // Created by iOS on 2020/11/20. // import Foundation ///https://www.jianshu.com/p/6e963d82b129 @propertyWrapper public struct UserDefault<T> { private let key: String private let defaultValue: T? public init(_ key: String, defaultValue: T? = nil) { self.key = key self.defaultValue = defaultValue } public var wrappedValue: T? { get { return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue } set { if newValue == nil { UserDefaults.standard.removeObject(forKey: key) } else { UserDefaults.standard.set(newValue, forKey: key) } } } } @propertyWrapper public struct UserDefaultSuite<T> { private let suiteName: String private let key: String private let defaultValue: T? public init(_ suiteName: String, key: String, defaultValue: T? = nil) { self.key = key self.defaultValue = defaultValue self.suiteName = suiteName } public var wrappedValue: T? { get { return UserDefaults(suiteName: suiteName)?.object(forKey: key) as? T ?? defaultValue } set { if newValue == nil { UserDefaults(suiteName: suiteName)?.removeObject(forKey: key) } else { UserDefaults(suiteName: suiteName)?.set(newValue, forKey: key) } } } } //MARK: 使用示例 // /////封装一个UserDefault配置文件 //struct UserDefaultsConfig { // @UserDefault(key: "username", defaultValue: "123") // static var username: String //} //struct UserDefaultsSu { // @UserDefaultSuite(suiteName: "app", key: "test", defaultValue: "123") // static var test: String //} // /////具体的业务代码。 //print("修改前\(UserDefaultsConfig.username)") //UserDefaultsConfig.username = "789" //print("修改后\(UserDefaultsConfig.username)") //print("修改前\(UserDefaultsSu.test)") //UserDefaultsSu.test = "789" //print("修改后\(UserDefaultsSu.test)")
24.963415
96
0.598925
e227fd8cf8377cd523cd504361938b5b394bfd7f
86
import Foundation protocol ForegroundModuleInput: AnyObject { func configure() }
14.333333
43
0.77907
7a7c58339e3d18f1715bf424e6a99aa59fd925c2
3,745
// // Copyright (c) 2019 Adyen B.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // /// A view representing a form card number item. internal final class FormCardNumberItemView: FormValueItemView<FormCardNumberItem> { /// Initializes the form card number item view. /// /// - Parameter item: The item represented by the view. internal required init(item: FormCardNumberItem) { super.init(item: item) addSubview(stackView) configureConstraints() } internal required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal override var childItemViews: [AnyFormItemView] { return [textItemView] } // MARK: - Text Item View private lazy var textItemView: FormTextItemView = { let textItemView = FormTextItemView(item: item) textItemView.showsSeparator = false return textItemView }() // MARK: - Card Type Logos View private lazy var cardTypeLogosView: UIStackView = { let arrangedSubviews = item.cardTypeLogos.map(CardTypeLogoView.init) let cardTypeLogosView = UIStackView(arrangedSubviews: arrangedSubviews) cardTypeLogosView.axis = .horizontal cardTypeLogosView.spacing = 4.0 cardTypeLogosView.preservesSuperviewLayoutMargins = true cardTypeLogosView.isLayoutMarginsRelativeArrangement = true return cardTypeLogosView }() // MARK: - Stack View private lazy var stackView: UIStackView = { let stackView = UIStackView(arrangedSubviews: [textItemView, cardTypeLogosView]) stackView.axis = .horizontal stackView.alignment = .lastBaseline stackView.distribution = .fill stackView.preservesSuperviewLayoutMargins = true stackView.translatesAutoresizingMaskIntoConstraints = false return stackView }() // MARK: - Layout private func configureConstraints() { let constraints = [ stackView.topAnchor.constraint(equalTo: topAnchor), stackView.leadingAnchor.constraint(equalTo: leadingAnchor), stackView.trailingAnchor.constraint(equalTo: trailingAnchor), stackView.bottomAnchor.constraint(equalTo: bottomAnchor) ] NSLayoutConstraint.activate(constraints) } } // MARK: - FormCardNumberItemView.CardTypeLogoView private extension FormCardNumberItemView { private class CardTypeLogoView: NetworkImageView, Observer { internal init(cardTypeLogo: FormCardNumberItem.CardTypeLogo) { super.init(frame: .zero) imageURL = cardTypeLogo.url layer.masksToBounds = true layer.cornerRadius = 3.0 layer.borderWidth = 1.0 / UIScreen.main.nativeScale layer.borderColor = UIColor(white: 0.0, alpha: 0.2).cgColor setContentHuggingPriority(.required, for: .horizontal) setContentHuggingPriority(.required, for: .vertical) setContentCompressionResistancePriority(.required, for: .horizontal) setContentCompressionResistancePriority(.required, for: .vertical) bind(cardTypeLogo.isHidden, to: self, at: \.isHidden) } internal required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal override var intrinsicContentSize: CGSize { return CGSize(width: 24.0, height: 16.0) } } }
32.850877
100
0.641389
72b7e70134ca5d80d0c7ae7a1c16628558208181
262
// // MultipleAnimationsApp.swift // MultipleAnimations // // Created by Giordano Scalzo on 05/07/2021. // import SwiftUI @main struct MultipleAnimationsApp: App { var body: some Scene { WindowGroup { ContentView() } } }
14.555556
45
0.618321
71788e201cc27f8c3d67505d3266840a7f9379c1
2,472
// // PreviewSupplementaryView.swift // ImagePickerSheet // // Created by Laurin Brandner on 06/09/14. // Copyright (c) 2014 Laurin Brandner. All rights reserved. // import UIKit class PreviewSupplementaryView: UICollectionReusableView { private let button: UIButton = { let button = UIButton() button.tintColor = .white button.isUserInteractionEnabled = false button.setImage(PreviewSupplementaryView.checkmarkImage, for: .normal) button.setImage(PreviewSupplementaryView.selectedCheckmarkImage, for: .selected) return button }() var buttonInset = UIEdgeInsets.zero var selected: Bool = false { didSet { button.isSelected = selected reloadButtonBackgroundColor() } } class var checkmarkImage: UIImage? { let bundle = Bundle(for: ImagePickerSheetController.self) let image = UIImage(named: "PreviewSupplementaryView-Checkmark", in: bundle, compatibleWith: nil) return image?.withRenderingMode(.alwaysTemplate) } class var selectedCheckmarkImage: UIImage? { let bundle = Bundle(for: ImagePickerSheetController.self) let image = UIImage(named: "PreviewSupplementaryView-Checkmark-Selected", in: bundle, compatibleWith: nil) return image?.withRenderingMode(.alwaysTemplate) } // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { addSubview(button) } // MARK: - Other Methods override func prepareForReuse() { super.prepareForReuse() selected = false } override func tintColorDidChange() { super.tintColorDidChange() reloadButtonBackgroundColor() } private func reloadButtonBackgroundColor() { button.backgroundColor = (selected) ? tintColor : nil } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() button.sizeToFit() button.frame.origin = CGPoint(x: buttonInset.left, y: bounds.height-button.frame.height-buttonInset.bottom) button.layer.cornerRadius = button.frame.height / 2.0 } }
26.580645
115
0.625809
11baf0989b81bef0efed220406644467329a43cd
543
// // FormLabelCell.swift // masai // // Created by Thomas Svitil on 06.09.17. // Copyright © 2017 Codepool GmbH. All rights reserved. // import Foundation import UIKit class FormLabelCell: FormCell { // MARK: View private var cellView: FormLabelCellView? override func createView(forceRecreation: Bool) -> FormCellView { if let cv = cellView, forceRecreation == false { return cv } cellView = FormLabelCellView(cell: self) return cellView! } }
19.392857
69
0.61326
c11e06dc8cf1a69910cf86940aeea61c750ab93c
7,617
import AEXML import Foundation import PathKit extension XCScheme { public final class ProfileAction: SerialAction { // MARK: - Static private static let defaultBuildConfiguration = "Release" // MARK: - Attributes public var buildableProductRunnable: BuildableProductRunnable? public var buildConfiguration: String public var shouldUseLaunchSchemeArgsEnv: Bool public var savedToolIdentifier: String public var ignoresPersistentStateOnLaunch: Bool public var useCustomWorkingDirectory: Bool public var debugDocumentVersioning: Bool public var askForAppToLaunch: Bool? public var commandlineArguments: CommandLineArguments? public var environmentVariables: [EnvironmentVariable]? public var macroExpansion: BuildableReference? public var enableTestabilityWhenProfilingTests: Bool // MARK: - Init public init(buildableProductRunnable: BuildableProductRunnable?, buildConfiguration: String, preActions: [ExecutionAction] = [], postActions: [ExecutionAction] = [], macroExpansion: BuildableReference? = nil, shouldUseLaunchSchemeArgsEnv: Bool = true, savedToolIdentifier: String = "", ignoresPersistentStateOnLaunch: Bool = false, useCustomWorkingDirectory: Bool = false, debugDocumentVersioning: Bool = true, askForAppToLaunch: Bool? = nil, commandlineArguments: CommandLineArguments? = nil, environmentVariables: [EnvironmentVariable]? = nil, enableTestabilityWhenProfilingTests: Bool = true) { self.buildableProductRunnable = buildableProductRunnable self.buildConfiguration = buildConfiguration self.macroExpansion = macroExpansion self.shouldUseLaunchSchemeArgsEnv = shouldUseLaunchSchemeArgsEnv self.savedToolIdentifier = savedToolIdentifier self.useCustomWorkingDirectory = useCustomWorkingDirectory self.debugDocumentVersioning = debugDocumentVersioning self.askForAppToLaunch = askForAppToLaunch self.commandlineArguments = commandlineArguments self.environmentVariables = environmentVariables self.ignoresPersistentStateOnLaunch = ignoresPersistentStateOnLaunch self.enableTestabilityWhenProfilingTests = enableTestabilityWhenProfilingTests super.init(preActions, postActions) } override init(element: AEXMLElement) throws { buildConfiguration = element.attributes["buildConfiguration"] ?? ProfileAction.defaultBuildConfiguration shouldUseLaunchSchemeArgsEnv = element.attributes["shouldUseLaunchSchemeArgsEnv"].map { $0 == "YES" } ?? true savedToolIdentifier = element.attributes["savedToolIdentifier"] ?? "" useCustomWorkingDirectory = element.attributes["useCustomWorkingDirectory"] == "YES" debugDocumentVersioning = element.attributes["debugDocumentVersioning"].map { $0 == "YES" } ?? true askForAppToLaunch = element.attributes["askForAppToLaunch"].map { $0 == "YES" || $0 == "Yes" } ignoresPersistentStateOnLaunch = element.attributes["ignoresPersistentStateOnLaunch"].map { $0 == "YES" } ?? false let buildableProductRunnableElement = element["BuildableProductRunnable"] if buildableProductRunnableElement.error == nil { buildableProductRunnable = try BuildableProductRunnable(element: buildableProductRunnableElement) } let buildableReferenceElement = element["MacroExpansion"]["BuildableReference"] if buildableReferenceElement.error == nil { macroExpansion = try BuildableReference(element: buildableReferenceElement) } let commandlineOptions = element["CommandLineArguments"] if commandlineOptions.error == nil { commandlineArguments = try CommandLineArguments(element: commandlineOptions) } let environmentVariables = element["EnvironmentVariables"] if environmentVariables.error == nil { self.environmentVariables = try EnvironmentVariable.parseVariables(from: environmentVariables) } enableTestabilityWhenProfilingTests = element.attributes["enableTestabilityWhenProfilingTests"].map { $0 != "No" } ?? true try super.init(element: element) } // MARK: - XML func xmlElement() -> AEXMLElement { let element = AEXMLElement(name: "ProfileAction", value: nil, attributes: [ "buildConfiguration": buildConfiguration, "shouldUseLaunchSchemeArgsEnv": shouldUseLaunchSchemeArgsEnv.xmlString, "savedToolIdentifier": savedToolIdentifier, "useCustomWorkingDirectory": useCustomWorkingDirectory.xmlString, "debugDocumentVersioning": debugDocumentVersioning.xmlString, ]) super.writeXML(parent: element) if ignoresPersistentStateOnLaunch { element.attributes["ignoresPersistentStateOnLaunch"] = ignoresPersistentStateOnLaunch.xmlString } if !enableTestabilityWhenProfilingTests { element.attributes["enableTestabilityWhenProfilingTests"] = "No" } if let buildableProductRunnable = buildableProductRunnable { element.addChild(buildableProductRunnable.xmlElement()) } if let commandlineArguments = commandlineArguments { element.addChild(commandlineArguments.xmlElement()) } if let environmentVariables = environmentVariables { element.addChild(EnvironmentVariable.xmlElement(from: environmentVariables)) } if let macroExpansion = macroExpansion { let macro = element.addChild(name: "MacroExpansion") macro.addChild(macroExpansion.xmlElement()) } return element } // MARK: - Equatable override func isEqual(to: Any?) -> Bool { guard let rhs = to as? ProfileAction else { return false } return super.isEqual(to: to) && buildableProductRunnable == rhs.buildableProductRunnable && buildConfiguration == rhs.buildConfiguration && shouldUseLaunchSchemeArgsEnv == rhs.shouldUseLaunchSchemeArgsEnv && savedToolIdentifier == rhs.savedToolIdentifier && ignoresPersistentStateOnLaunch == rhs.ignoresPersistentStateOnLaunch && useCustomWorkingDirectory == rhs.useCustomWorkingDirectory && debugDocumentVersioning == rhs.debugDocumentVersioning && askForAppToLaunch == rhs.askForAppToLaunch && commandlineArguments == rhs.commandlineArguments && environmentVariables == rhs.environmentVariables && macroExpansion == rhs.macroExpansion && enableTestabilityWhenProfilingTests == rhs.enableTestabilityWhenProfilingTests } } }
53.265734
134
0.635027
9058574da255e0f968192e1d9b0834630dd61bfa
5,275
// // KeyboardViewController + PerKey.swift // PrismUI // // Created by Erik Bautista on 9/8/20. // Copyright © 2020 ErrorErrorError. All rights reserved. // import Cocoa extension KeyboardViewController { func setupPerKeyLayout(model: PrismDeviceModel) { let keyboardMap = model == .perKey ? KeyboardLayout.perKeyMap : KeyboardLayout.perKeyGS65KeyMap let keyboardKeyNames = model == .perKey ? KeyboardLayout.perKeyNames : KeyboardLayout.perKeyGS65KeyNames let keycodeArray = (model == .perKey ? KeyboardLayout.perKeyCodes : KeyboardLayout.perKeyGS65KeyCodes) let padding: CGFloat = 5 let desiredKeyWidth: CGFloat = model == .perKey ? 56 : 66 let desiredKeyHeight = desiredKeyWidth let keyboardHeight = 6 * desiredKeyHeight let keyboardWidth = ((model == .perKey) ? 20 : 15) * desiredKeyWidth let xOffset: CGFloat = (view.frame.width - keyboardWidth) / 2 var height: CGFloat = 0 if #available(macOS 11.0, *) { height = view.safeAreaRect.height } else { height = view.frame.height } var xPos: CGFloat = xOffset var yPos: CGFloat = (height - keyboardHeight) / 2 + keyboardHeight - desiredKeyHeight for (index, row) in keyboardMap.enumerated() { for (subIndex, widthFract) in row.enumerated() { let isDoubleHeight = model == .perKey && (index == 3 || index == 5) && (subIndex + 1 == row.count) let keyWidth = (desiredKeyWidth * widthFract) - padding let keyHeight = (isDoubleHeight ? (2 * desiredKeyHeight) - padding : desiredKeyHeight - padding) let keyChar = keyboardKeyNames[index][subIndex] let keyView: PerKeyColorView = { let keycode = keycodeArray[index][subIndex] let prismKey = PrismKey(region: getRegionKey(keyChar, keycode: keycode), keycode: keycode) let key = PerKeyColorView(text: keyChar, key: prismKey) key.frame = NSRect(x: xPos + padding, y: yPos - padding, width: keyWidth, height: keyHeight) key.delegate = self return key }() PrismKeyboardDevice.keys.add(keyView.prismKey!) view.addSubview(keyView) xPos += desiredKeyWidth * widthFract } xPos = xOffset yPos -= desiredKeyHeight } let keyboardFrame = NSRect(x: xOffset + padding, y: (height - keyboardHeight) / 2 - padding, width: keyboardWidth - padding, height: keyboardHeight - padding) originView = OriginEffectView(frame: keyboardFrame) originView?.isHidden = true view.addSubview(originView!) NotificationCenter.default.addObserver(self, selector: #selector(handleOriginToggle), name: .prismOriginToggled, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateOriginView), name: .updateOriginView, object: nil) } private func getRegionKey(_ char: String, keycode: UInt8) -> UInt8 { var region: UInt8 if char.contains("ESC") { region = PrismKeyboardDevice.regions[0] } else if char == "A" { region = PrismKeyboardDevice.regions[1] } else if char.contains("ENTER") { region = PrismKeyboardDevice.regions[2] } else if char == "F7" { region = PrismKeyboardDevice.regions[3] } else { region = PrismKeyboardDevice.getRegionFromKeycode(keycode) } return region } } extension KeyboardViewController { @objc func handleOriginToggle(notification: Notification) { guard let originView = originView else { return } if let shouldHide = notification.object as? Bool { originView.isHidden = shouldHide } else { originView.isHidden = !originView.isHidden } } @objc func updateOriginView(notification: Notification) { guard let originView = originView else { return } if let point = notification.object as? PrismPoint { originView.setOrigin(origin: point) } else if let type = notification.object as? PrismDirection { originView.typeOfRad = type } else if let transitions = notification.object as? [PrismTransition] { originView.colorArray = transitions.compactMap { $0.color.nsColor } } } } extension KeyboardViewController: ColorViewDelegate { func didSelect(_ sender: ColorView) { if !PrismKeyboardDevice.keysSelected.contains(sender) { PrismKeyboardDevice.keysSelected.add(sender) } } func didDeselect(_ sender: ColorView) { if PrismKeyboardDevice.keysSelected.contains(sender) { PrismKeyboardDevice.keysSelected.remove(sender) } } } // MARK: Notification broadcast extension Notification.Name { public static let prismEffectOriginChanged: Notification.Name = .init(rawValue: "prismEffectOriginChanged") }
40.891473
114
0.613081
62dfdf895361dd7221c6bcefb8a60b205a548049
4,265
// // MasterTimelineDefaultCellLayout.swift // NetNewsWire // // Created by Brent Simmons on 2/6/16. // Copyright © 2016 Ranchero Software, LLC. All rights reserved. // import UIKit import RSCore struct MasterTimelineDefaultCellLayout: MasterTimelineCellLayout { static let cellPadding = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 16) static let unreadCircleMarginLeft = CGFloat(integerLiteral: 0) static let unreadCircleDimension = CGFloat(integerLiteral: 12) static let unreadCircleMarginRight = CGFloat(integerLiteral: 8) static let starDimension = CGFloat(integerLiteral: 16) static let avatarSize = CGSize(width: 48.0, height: 48.0) static let avatarMarginRight = CGFloat(integerLiteral: 8) static let avatarCornerRadius = CGFloat(integerLiteral: 4) static var titleFont: UIFont { return UIFont.preferredFont(forTextStyle: .headline) } static let titleBottomMargin = CGFloat(integerLiteral: 1) static var feedNameFont: UIFont { return UIFont.preferredFont(forTextStyle: .footnote) } static let feedRightMargin = CGFloat(integerLiteral: 8) static var dateFont: UIFont { return UIFont.preferredFont(forTextStyle: .footnote) } static let dateMarginBottom = CGFloat(integerLiteral: 1) static var summaryFont: UIFont { return UIFont.preferredFont(forTextStyle: .body) } let height: CGFloat let unreadIndicatorRect: CGRect let starRect: CGRect let avatarImageRect: CGRect let titleRect: CGRect let summaryRect: CGRect let feedNameRect: CGRect let dateRect: CGRect let separatorInsets: UIEdgeInsets init(width: CGFloat, insets: UIEdgeInsets, cellData: MasterTimelineCellData) { var currentPoint = CGPoint.zero currentPoint.x = MasterTimelineDefaultCellLayout.cellPadding.left + insets.left + MasterTimelineDefaultCellLayout.unreadCircleMarginLeft currentPoint.y = MasterTimelineDefaultCellLayout.cellPadding.top // Unread Indicator and Star self.unreadIndicatorRect = MasterTimelineDefaultCellLayout.rectForUnreadIndicator(currentPoint) self.starRect = MasterTimelineDefaultCellLayout.rectForStar(currentPoint) // Start the point at the beginning position of the main block currentPoint.x += MasterTimelineDefaultCellLayout.unreadCircleDimension + MasterTimelineDefaultCellLayout.unreadCircleMarginRight // Separator Insets self.separatorInsets = UIEdgeInsets(top: 0, left: currentPoint.x, bottom: 0, right: 0) // Avatar if cellData.showAvatar { self.avatarImageRect = MasterTimelineDefaultCellLayout.rectForAvatar(currentPoint) currentPoint.x = self.avatarImageRect.maxX + MasterTimelineDefaultCellLayout.avatarMarginRight } else { self.avatarImageRect = CGRect.zero } let textAreaWidth = width - (currentPoint.x + MasterTimelineDefaultCellLayout.cellPadding.right + insets.right) // Title Text Block let (titleRect, numberOfLinesForTitle) = MasterTimelineDefaultCellLayout.rectForTitle(cellData, currentPoint, textAreaWidth) self.titleRect = titleRect // Summary Text Block if self.titleRect != CGRect.zero { currentPoint.y = self.titleRect.maxY + MasterTimelineDefaultCellLayout.titleBottomMargin } self.summaryRect = MasterTimelineDefaultCellLayout.rectForSummary(cellData, currentPoint, textAreaWidth, numberOfLinesForTitle) currentPoint.y = [self.titleRect, self.summaryRect].maxY() // Feed Name and Pub Date self.dateRect = MasterTimelineDefaultCellLayout.rectForDate(cellData, currentPoint, textAreaWidth) let feedNameWidth = textAreaWidth - (MasterTimelineDefaultCellLayout.feedRightMargin + self.dateRect.size.width) self.feedNameRect = MasterTimelineDefaultCellLayout.rectForFeedName(cellData, currentPoint, feedNameWidth) self.height = [self.avatarImageRect, self.feedNameRect].maxY() + MasterTimelineDefaultCellLayout.cellPadding.bottom } } // MARK: - Calculate Rects extension MasterTimelineDefaultCellLayout { static func rectForDate(_ cellData: MasterTimelineCellData, _ point: CGPoint, _ textAreaWidth: CGFloat) -> CGRect { var r = CGRect.zero let size = SingleLineUILabelSizer.size(for: cellData.dateString, font: MasterTimelineDefaultCellLayout.dateFont) r.size = size r.origin.x = (point.x + textAreaWidth) - size.width r.origin.y = point.y return r } }
34.674797
138
0.788042
2222b48e6f97cf5a6aa2eb32444e4c512c8a9c70
1,786
// // RectangleFieldView.swift // Views // // Created by Cédric Bahirwe on 12/01/2021. // import SwiftUI struct RectangleFieldView: View { var body: some View { VStack(spacing: 15) { Text("Owner Name") .font(.system(size: 18, weight: .bold, design: .rounded)) Text("Your owner name can be changed later. Names that are personally identifiable or infringe on a third party's right are not permitted.") .multilineTextAlignment(.center) .font(.system(size: 15, weight: .light, design: .rounded)) .lineSpacing(5) TextField("Owner Name", text: .constant("")) .padding(.vertical, 3) .padding(.leading, 8) .font(.system(size: 16, weight: .regular, design: .rounded)) .overlay( Rectangle().strokeBorder(Color.black)) Button(action: {}, label: { Text("OK") .bold() .foregroundColor(.gray) .frame(maxWidth: .infinity) .frame(height: 40) .background(Color.gray.opacity(0.5)) .cornerRadius(8) }) } .padding() .padding(.bottom,5) .frame(maxWidth: 420) .background(Color.white.opacity(0.5)) .cornerRadius(15) .shadow(color: Color.black.opacity(0.2), radius: 3, x: 3, y: 3) .shadow(color: Color.white.opacity(0.7), radius: 3, x: -2, y: -2) .foregroundColor(.black) } } struct RectangleFieldView_Previews: PreviewProvider { static var previews: some View { RectangleFieldView() .previewLayout(.fixed(width: 460, height: 300)) } }
33.698113
152
0.529115
76b51883ef83136e62a484b688da4f8cadeb2604
519
import Foundation internal struct FIFOQueue<T> { private var popQueue: [T] = [] private var pushQueue: [T] = [] public init() { } public mutating func push(_ value: T) { pushQueue.append(value) } public mutating func pop() -> T? { if popQueue.count == 0 && pushQueue.count > 0 { movePushQueueToPopQueue() } return popQueue.popLast() } private mutating func movePushQueueToPopQueue() { while let next = pushQueue.popLast() { popQueue.append(next) } } }
17.896552
51
0.622351
0909d0536980e9b0d82ffee6d8766c8ac756c77d
1,522
import Foundation extension Array { func concat(with element: Element) -> Array<Element> { var current = self current.append(element) return current } func concat<S : Sequence>(with elements: S) -> Array<Element> where S.Element == Element { var current = self current.append(contentsOf: elements) return current } public func toDictionary<Key: Hashable, OutboundValue>( withKey selectKey: (Element) -> Key, andValue selectValue: (Element) -> OutboundValue ) -> [Key: OutboundValue] { var dict = [Key: OutboundValue]() for element in self { dict[selectKey(element)] = selectValue(element) } return dict } public func toDictionaryOfArrays<Key: Hashable, OutboundValue>( withKey selectKey: (Element) -> Key, andValue selectValue: (Element) -> OutboundValue ) -> [Key: [OutboundValue]] { var dict = [Key: [OutboundValue]]() for element in self { if dict[selectKey(element)] == nil { dict[selectKey(element)] = [] } dict[selectKey(element)] = dict[selectKey(element)]?.concat(with: selectValue(element)) } return dict } public func toDictionary<Key: Hashable>(withKey selectKey: (Element) -> Key) -> [Key: Element] { var dict = [Key: Element]() for element in self { dict[selectKey(element)] = element } return dict } }
30.44
100
0.5841
5b3523284dcb4d96a56439a2c78ce600d7d1b4de
110
// // Constants.ErrorCodes.swift // Serengeti // // Created by Sammie on 12/11/2021. // import Foundation
12.222222
36
0.672727
d67ffafc4083f4280781a90380327ae36fadfdc2
2,169
// // AppDelegate.swift // MKLabel // // Created by Lokukumar on 08/09/2020. // Copyright (c) 2020 Lokukumar. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.148936
285
0.754265
29b114a8b01ece0c31da427f5722ce7025734467
528
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -Ounchecked %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // rdar://30579970 // REQUIRES: optimized_stdlib // FIXME: https://bugs.swift.org/browse/SR-2808 // XFAIL: resilient_stdlib // We were missing target transform info and not vectorizing the loop below. // CHECK: xor <2 x i64> public func f(a: UnsafePointer<Int>, b: UnsafePointer<Int>, count: Int) -> Int { var c = 0 for i in 0..<count { c = a[i] ^ b[i] ^ c } return c }
21.12
112
0.668561
fbd01792006e3b084a17b65d8796c1bf5f3eaab8
10,317
// // StringExtension.swift // MerchantDashboard // // Created by Tien Nhat Vu on 3/17/16. // Copyright © 2016 Tien Nhat Vu. All rights reserved. // import Foundation // MARK: Common extension String { public subscript (regex: String) -> String? { if let range = self.range(of: regex, options: .regularExpression, range: nil, locale: nil) { return String(self[range]) } return nil } public func index(fromStart index: Int) -> Index { return index <= 0 ? startIndex : self.index(startIndex, offsetBy: min(index, count-1)) } public func index(fromEnd index: Int) -> Index { return index <= 0 ? self.index(before: endIndex) : self.index(endIndex, offsetBy: max(-index, -count)) } public subscript (range: CountableRange<Int>) -> String { return String(self[index(fromStart: range.lowerBound)..<index(fromStart: range.upperBound)]) } public subscript (range: CountableClosedRange<Int>) -> String { return String(self[index(fromStart: range.lowerBound)...index(fromStart: range.upperBound)]) } public subscript (range: PartialRangeThrough<Int>) -> String { return String(self[...index(fromStart: range.upperBound)]) } public subscript (range: CountablePartialRangeFrom<Int>) -> String { return String(self[index(fromStart: range.lowerBound)...]) } public func replace(in r: CountableRange<Int>, with string: String) -> String { return self.replacingCharacters(in: index(fromStart: r.lowerBound)..<index(fromStart: r.upperBound), with: string) } public func replace(in r: CountableClosedRange<Int>, with string: String) -> String { return self.replacingCharacters(in: index(fromStart: r.lowerBound)...index(fromStart: r.upperBound), with: string) } public func firstCharacterUppercase() -> String { if !self.isEmpty { return String(self[self.startIndex]).uppercased()+String(self[self.index(after: self.startIndex)...]) } else { return self } } /// Remove front and back until reach characters not in set /// /// - Parameter set: CharacterSet /// - Returns: New String public func trim(in set: CharacterSet = .whitespacesAndNewlines) -> String { return trimmingCharacters(in: set) } /// Remove all characters in the characterSet /// /// - Parameter characterSet: CharacterSet /// - Returns: New String public func removeCharacters(from characterSet: CharacterSet) -> String { let passed = self.unicodeScalars.filter { !characterSet.contains($0) } return String(String.UnicodeScalarView(passed)) } /// Remove all characters in the characterSet inside the string /// /// - Parameter characterString: string to get characters from /// - Returns: New String public func removeCharacters(from characterString: String) -> String { return removeCharacters(from: CharacterSet(charactersIn: characterString)) } /// Convert NSRange to Range /// /// - Parameter nsRange: NSRange /// - Returns: optional Range<String.Index> public func rangeFromNSRange(_ nsRange : NSRange) -> Range<String.Index>? { let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex) let to16 = utf16.index(from16!, offsetBy: nsRange.length, limitedBy: utf16.endIndex) if let from = String.Index(from16!, within: self), let to = String.Index(to16!, within: self) { return from ..< to } return nil } public func getSize(attribute: [NSAttributedString.Key: Any], width: CGFloat = UIScreen.main.bounds.size.width, height: CGFloat = .greatestFiniteMagnitude) -> CGRect { guard self.isNotEmpty else { return .zero } let sizeOfText = (self as NSString).boundingRect(with: CGSize(width: width, height: height), options: [NSStringDrawingOptions.usesLineFragmentOrigin, NSStringDrawingOptions.usesFontLeading], attributes: attribute, context: nil) return sizeOfText } /// Will have hyphen (-) on word break public func hyphenationString() -> NSAttributedString { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.hyphenationFactor = 1.0 return NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.paragraphStyle:paragraphStyle]) } } // MARK: Validation extension String { public var isNotEmpty: Bool { get { return !self.isEmpty } } public func isValidEmail() -> Bool { let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat) return emailPredicate.evaluate(with: self) } public func isValidURL() -> Bool { let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) if let match = detector.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)) { // it is a link, if the match covers the whole string return match.range.length == self.utf16.count } else { return false } } } // MARK: Conversion extension String { /// Localize string, won't work with genstrings /// /// - Parameter comment: comment /// - Returns: Localized string public func localized(comment: String = "") -> String { return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: comment) } /// Format non-decimal number string to string with decimal dot after numbersAfterDecimal /// /// - Parameter numbersAfterDecimal: numbers of characters after dot /// - Returns: formatted string public func formatDecimalString(numbersAfterDecimal: Int) -> String { guard let _ = Decimal(string: self) else { return "0.00" } var modPrice = self guard numbersAfterDecimal > 0 else { return self } if let dot = modPrice.range(of: ".") { modPrice.removeSubrange(dot) } while modPrice.count < numbersAfterDecimal+1 { modPrice.insert("0", at: modPrice.startIndex) } while modPrice.count > numbersAfterDecimal+1 && modPrice.first! == "0" { modPrice.remove(at: modPrice.startIndex) } modPrice.insert(".", at: modPrice.index(fromEnd: numbersAfterDecimal)) return modPrice } public static func generateRandomString(length: Int, charactersIn chars: String = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") -> String { let upperBound = UInt32(chars.count) return String((0..<length).map { _ -> Character in return chars[chars.index(chars.startIndex, offsetBy: Int(arc4random_uniform(upperBound)))] }) } public func toDate(format: String, dateFormatter: DateFormatter = DateFormatter.shared) -> Date? { dateFormatter.dateFormat = format //dateFormatter.timeZone = TimeZone(abbreviation: "GMT") return dateFormatter.date(from: self) } public func toBase64() -> String { return self.data(using: .utf8)!.base64EncodedString() } //To use with currency code public func toCurrencySymbol() -> String { // let result = Locale.availableIdentifiers.map{ Locale(identifier: $0) }.first{ $0.currencyCode == self } // return result?.currencySymbol ?? self guard let result = Locale.availableIdentifiers.first(where: { (identifier) -> Bool in return Locale(identifier: identifier).currencyCode == self }) else { return self } return Locale(identifier: result).currencySymbol ?? self } //To use with number string public func toCurrencyFormatter(currencyCode: String, formatter: NumberFormatter = NumberFormatter()) -> String { let number = NSDecimalNumber(string: self) if number != NSDecimalNumber.notANumber { formatter.numberStyle = .currency formatter.currencyCode = currencyCode guard let formattedStr = formatter.string(from: number) else { return self } return formattedStr } return self } public func toCountryName(locale: Locale = Locale(identifier: "en_US")) -> String? { return locale.localizedString(forRegionCode: self) ?? self } public func toFlag() -> String { let base : UInt32 = 127397 var s = "" for v in self.unicodeScalars { s.unicodeScalars.append(UnicodeScalar(base + v.value)!) } return String(s) } public func stringConvertedFromHTML() -> String { var text = self.replacingOccurrences(of: "<br>", with: "\n") text = text.replacingOccurrences(of: "<br />", with: "\n") text = text.replacingOccurrences(of: "<li>", with: "• ") text = text.replacingOccurrences(of: "</li>", with: "\n") text = text.replacingOccurrences(of: "<ul>", with: "\n") text = text.replacingOccurrences(of: "&nbsp;", with: " ") text = text.replacingOccurrences(of: "&amp;", with: "&") text = text.replacingOccurrences(of: "&gt;", with: ">") text = text.replacingOccurrences(of: "&lt;", with: "<") text = text.replacingOccurrences(of: "\n\n", with: "\n") text = text.stringByStrippingHTML() return text.trimmingCharacters(in: CharacterSet(charactersIn: "\n\(unichar(0x0085))")).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } fileprivate func stringByStrippingHTML() -> String { var string = self while string.range(of: "<[^>]+>", options: [.regularExpression], range: nil, locale: nil) != nil { let range = string.range(of: "<[^>]+>", options: [.regularExpression], range: nil, locale: nil) string = string.replacingCharacters(in: range!, with: "") // string.stringByStrippingHTML() } return string } }
40.143969
235
0.632548
e8ca2426f1f776a8854eaeca39bd68dc6de1a192
11,370
// ScanfileProtocol.swift // Copyright (c) 2020 FastlaneTools public protocol ScanfileProtocol: class { /// Path to the workspace file var workspace: String? { get } /// Path to the project file var project: String? { get } /// The project's scheme. Make sure it's marked as `Shared` var scheme: String? { get } /// The name of the simulator type you want to run tests on (e.g. 'iPhone 6') var device: String? { get } /// Array of devices to run the tests on (e.g. ['iPhone 6', 'iPad Air']) var devices: [String]? { get } /// Should skip auto detecting of devices if none were specified var skipDetectDevices: Bool { get } /// Enabling this option will automatically killall Simulator processes before the run var forceQuitSimulator: Bool { get } /// Enabling this option will automatically erase the simulator before running the application var resetSimulator: Bool { get } /// Enabling this option will disable the simulator from showing the 'Slide to type' prompt var disableSlideToType: Bool { get } /// Enabling this option will launch the first simulator prior to calling any xcodebuild command var prelaunchSimulator: Bool? { get } /// Enabling this option will automatically uninstall the application before running it var reinstallApp: Bool { get } /// The bundle identifier of the app to uninstall (only needed when enabling reinstall_app) var appIdentifier: String? { get } /// Array of strings matching Test Bundle/Test Suite/Test Cases to run var onlyTesting: String? { get } /// Array of strings matching Test Bundle/Test Suite/Test Cases to skip var skipTesting: String? { get } /// The testplan associated with the scheme that should be used for testing var testplan: String? { get } /// Array of strings matching test plan configurations to run var onlyTestConfigurations: String? { get } /// Array of strings matching test plan configurations to skip var skipTestConfigurations: String? { get } /// Run tests using the provided `.xctestrun` file var xctestrun: String? { get } /// The toolchain that should be used for building the application (e.g. `com.apple.dt.toolchain.Swift_2_3, org.swift.30p620160816a`) var toolchain: String? { get } /// Should the project be cleaned before building it? var clean: Bool { get } /// Should code coverage be generated? (Xcode 7 and up) var codeCoverage: Bool? { get } /// Should the address sanitizer be turned on? var addressSanitizer: Bool? { get } /// Should the thread sanitizer be turned on? var threadSanitizer: Bool? { get } /// Should the HTML report be opened when tests are completed? var openReport: Bool { get } /// Disable xcpretty formatting of build, similar to `output_style='raw'` but this will also skip the test results table var disableXcpretty: Bool? { get } /// The directory in which all reports will be stored var outputDirectory: String { get } /// Define how the output should look like. Valid values are: standard, basic, rspec, or raw (disables xcpretty during xcodebuild) var outputStyle: String? { get } /// Comma separated list of the output types (e.g. html, junit, json-compilation-database) var outputTypes: String { get } /// Comma separated list of the output files, corresponding to the types provided by :output_types (order should match). If specifying an output type of json-compilation-database with :use_clang_report_name enabled, that option will take precedence var outputFiles: String? { get } /// The directory where to store the raw log var buildlogPath: String { get } /// If the logs generated by the app (e.g. using NSLog, perror, etc.) in the Simulator should be written to the output_directory var includeSimulatorLogs: Bool { get } /// Suppress the output of xcodebuild to stdout. Output is still saved in buildlog_path var suppressXcodeOutput: Bool? { get } /// A custom xcpretty formatter to use var formatter: String? { get } /// Pass in xcpretty additional command line arguments (e.g. '--test --no-color' or '--tap --no-utf') var xcprettyArgs: String? { get } /// The directory where build products and other derived data will go var derivedDataPath: String? { get } /// Should zip the derived data build products and place in output path? var shouldZipBuildProducts: Bool { get } /// Should an Xcode result bundle be generated in the output directory var resultBundle: Bool { get } /// Generate the json compilation database with clang naming convention (compile_commands.json) var useClangReportName: Bool { get } /// Specify the exact number of test runners that will be spawned during parallel testing. Equivalent to -parallel-testing-worker-count var concurrentWorkers: Int? { get } /// Constrain the number of simulator devices on which to test concurrently. Equivalent to -maximum-concurrent-test-simulator-destinations var maxConcurrentSimulators: Int? { get } /// Do not run test bundles in parallel on the specified destinations. Testing will occur on each destination serially. Equivalent to -disable-concurrent-testing var disableConcurrentTesting: Bool { get } /// Should debug build be skipped before test build? var skipBuild: Bool { get } /// Test without building, requires a derived data path var testWithoutBuilding: Bool? { get } /// Build for testing only, does not run tests var buildForTesting: Bool? { get } /// The SDK that should be used for building the application var sdk: String? { get } /// The configuration to use when building the app. Defaults to 'Release' var configuration: String? { get } /// Pass additional arguments to xcodebuild. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS="-ObjC -lstdc++" var xcargs: String? { get } /// Use an extra XCCONFIG file to build your app var xcconfig: String? { get } /// App name to use in slack message and logfile name var appName: String? { get } /// Target version of the app being build or tested. Used to filter out simulator version var deploymentTargetVersion: String? { get } /// Create an Incoming WebHook for your Slack group to post results there var slackUrl: String? { get } /// #channel or @username var slackChannel: String? { get } /// The message included with each message posted to slack var slackMessage: String? { get } /// Use webhook's default username and icon settings? (true/false) var slackUseWebhookConfiguredUsernameAndIcon: Bool { get } /// Overrides the webhook's username property if slack_use_webhook_configured_username_and_icon is false var slackUsername: String { get } /// Overrides the webhook's image property if slack_use_webhook_configured_username_and_icon is false var slackIconUrl: String { get } /// Don't publish to slack, even when an URL is given var skipSlack: Bool { get } /// Only post on Slack if the tests fail var slackOnlyOnFailure: Bool { get } /// Use only if you're a pro, use the other options instead var destination: String? { get } /// Platform to build when using a Catalyst enabled app. Valid values are: ios, macos var catalystPlatform: String? { get } /// **DEPRECATED!** Use `--output_files` instead - Sets custom full report file name when generating a single report var customReportFileName: String? { get } /// Allows for override of the default `xcodebuild` command var xcodebuildCommand: String { get } /// Sets a custom path for Swift Package Manager dependencies var clonedSourcePackagesPath: String? { get } /// Lets xcodebuild use system's scm configuration var useSystemScm: Bool { get } /// Should this step stop the build if the tests fail? Set this to false if you're using trainer var failBuild: Bool { get } } public extension ScanfileProtocol { var workspace: String? { return nil } var project: String? { return nil } var scheme: String? { return nil } var device: String? { return nil } var devices: [String]? { return nil } var skipDetectDevices: Bool { return false } var forceQuitSimulator: Bool { return false } var resetSimulator: Bool { return false } var disableSlideToType: Bool { return true } var prelaunchSimulator: Bool? { return nil } var reinstallApp: Bool { return false } var appIdentifier: String? { return nil } var onlyTesting: String? { return nil } var skipTesting: String? { return nil } var testplan: String? { return nil } var onlyTestConfigurations: String? { return nil } var skipTestConfigurations: String? { return nil } var xctestrun: String? { return nil } var toolchain: String? { return nil } var clean: Bool { return false } var codeCoverage: Bool? { return nil } var addressSanitizer: Bool? { return nil } var threadSanitizer: Bool? { return nil } var openReport: Bool { return false } var disableXcpretty: Bool? { return nil } var outputDirectory: String { return "./test_output" } var outputStyle: String? { return nil } var outputTypes: String { return "html,junit" } var outputFiles: String? { return nil } var buildlogPath: String { return "~/Library/Logs/scan" } var includeSimulatorLogs: Bool { return false } var suppressXcodeOutput: Bool? { return nil } var formatter: String? { return nil } var xcprettyArgs: String? { return nil } var derivedDataPath: String? { return nil } var shouldZipBuildProducts: Bool { return false } var resultBundle: Bool { return false } var useClangReportName: Bool { return false } var concurrentWorkers: Int? { return nil } var maxConcurrentSimulators: Int? { return nil } var disableConcurrentTesting: Bool { return false } var skipBuild: Bool { return false } var testWithoutBuilding: Bool? { return nil } var buildForTesting: Bool? { return nil } var sdk: String? { return nil } var configuration: String? { return nil } var xcargs: String? { return nil } var xcconfig: String? { return nil } var appName: String? { return nil } var deploymentTargetVersion: String? { return nil } var slackUrl: String? { return nil } var slackChannel: String? { return nil } var slackMessage: String? { return nil } var slackUseWebhookConfiguredUsernameAndIcon: Bool { return false } var slackUsername: String { return "fastlane" } var slackIconUrl: String { return "https://fastlane.tools/assets/img/fastlane_icon.png" } var skipSlack: Bool { return false } var slackOnlyOnFailure: Bool { return false } var destination: String? { return nil } var catalystPlatform: String? { return nil } var customReportFileName: String? { return nil } var xcodebuildCommand: String { return "env NSUnbufferedIO=YES xcodebuild" } var clonedSourcePackagesPath: String? { return nil } var useSystemScm: Bool { return false } var failBuild: Bool { return true } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.60]
41.801471
252
0.698505
79bf0daa0a35b061f04d37de1f8b690bc6b4c857
225
// Copyright © 2019 Optimove. All rights reserved. class Pipe { var next: Pipe? func deliver(_: CommonOperation) throws { fatalError("No implementation. Expect to be implemented by inheretance.") } }
18.75
81
0.671111
50d41b0b2968628e775a4c73c1d9c66e60031311
215
// // DefaultCollectionViewCell.swift // GitHubTest // // Created by bruno on 10/02/20. // Copyright © 2020 bruno. All rights reserved. // import UIKit class DefaultCollectionViewCell: UICollectionViewCell {}
17.916667
56
0.734884
db18e9e3c9ca4570cd6609d7be9e08fe0c8d7f5f
685
import QueueServer import ScheduleStrategy import Models import QueueModels public class QueueServerFixture: QueueServer { public var isDepleted = false public var hasAnyAliveWorker = true public var ongoingJobIds = Set<JobId>() public init() {} public func start() throws -> Int { return 1 } public func schedule(bucketSplitter: BucketSplitter, testEntryConfigurations: [TestEntryConfiguration], prioritizedJob: PrioritizedJob) { ongoingJobIds.insert(prioritizedJob.jobId) } public func queueResults(jobId: JobId) throws -> JobResults { return JobResults(jobId: jobId, testingResults: []) } }
25.37037
141
0.69781
226f814b5ab138d8841587c324949aded31c10fe
1,904
// // CryptoHashable.swift // DiffableDataSource // // Copyright (c) 2021 Rocket Insights, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import CryptoKit import Foundation // Typealiases allowing us to substitute a different hashing algorithm and corresponding digest type. typealias CryptoAlgorithm = SHA512 typealias CryptoDigest = SHA512Digest protocol CryptoHashable { var cryptoHash: CryptoDigest { get } } extension CryptoHashable { var cryptoHash: CryptoDigest { // Compute the cryptographic hash of the raw bytes of `self`. This will test equality of value types. This will only test for pointer equality for reference types. return withUnsafeBytes(of: self) { var hasher = CryptoAlgorithm() hasher.update(bufferPointer: $0) return hasher.finalize() } } }
39.666667
171
0.733718
87df0a5ccbeee462eed47438c16664f0b0658b20
5,465
// // SearchingViewController.swift // MyApp // // Created by PCI0001 on 3/8/19. // Copyright © 2019 Asian Tech Co., Ltd. All rights reserved. // import UIKit protocol SearchingViewControllerDelegate: class { func controller(_ controller: SearchingViewController, needsPerform action: SearchingViewController.Action) } final class SearchingViewController: UIViewController { enum Action { case keyOfHistory(keySearched: String) } @IBOutlet private weak var containerView: UIView! @IBOutlet private weak var correctButton: UIButton! @IBOutlet private weak var recentlyButton: UIButton! @IBOutlet private weak var historyButton: UIButton! private var pageVC: UIPageViewController? private var viewControllers: [UIViewController] = [] let searchCorrectVC = SearchCorrectViewController() let recentlyVC = RecentlyViewController() let historyVC = HistorySearchViewController() var searchParam: SearchResultViewController.SearchParam? { didSet { searchCorrectVC.searchCorrect(isLoadMore: false, searchParams: searchParam) } } var searchType: SearchType = .correctly { didSet { switchingPage() } } weak var delegate: SearchingViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() setupContainerView() } private func setupContainerView() { viewControllers.append(searchCorrectVC) viewControllers.append(recentlyVC) viewControllers.append(historyVC) pageVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) if let pageVC = pageVC { containerView.addSubview(pageVC.view) addChildViewController(pageVC) pageVC.view.frame = containerView.bounds pageVC.setViewControllers([searchCorrectVC], direction: .forward, animated: true, completion: nil) } setDisplayTab() historyVC.delegate = self } private func switchingPage() { guard let pageVC = pageVC, let vcs = pageVC.viewControllers else { return } let viewVC = viewControllers[searchType.rawValue] if !vcs.contains(viewVC) { setDisplayTab() pageVC.setViewControllers([viewVC], direction: getAnimation(), animated: true, completion: nil) } } private func getAnimation() -> UIPageViewController.NavigationDirection { switch searchType { case .correctly: return .reverse case .recently: return .forward case .history: return .forward } } private func setDisplayTab() { switch searchType { case .correctly: setButtonSelected(button: correctButton) case .recently: setButtonSelected(button: recentlyButton) case .history: setButtonSelected(button: historyButton) } } private func setButtonSelected(button: UIButton) { let attributeNormal1 = NSAttributedString(string: correctButton.titleLabel?.text ?? "", attributes: Config.attributesForNormal) correctButton.setAttributedTitle(attributeNormal1, for: .normal) let attributeNormal2 = NSAttributedString(string: historyButton.titleLabel?.text ?? "", attributes: Config.attributesForNormal) historyButton.setAttributedTitle(attributeNormal2, for: .normal) let attributeNormal3 = NSAttributedString(string: recentlyButton.titleLabel?.text ?? "", attributes: Config.attributesForNormal) recentlyButton.setAttributedTitle(attributeNormal3, for: .normal) let attributeSelected = NSAttributedString(string: button.titleLabel?.text ?? "", attributes: Config.attributesForSelected) button.setAttributedTitle(attributeSelected, for: .normal) } @IBAction private func searchTypeButtonTouchUpInside(_ sender: UIButton) { guard let type = SearchType(rawValue: sender.tag) else { return } switch type { case .correctly: guard searchType != .correctly else { return } searchType = .correctly case .recently: guard searchType != .recently else { return } searchType = .recently case .history: guard searchType != .history else { return } searchType = .history } } } extension SearchingViewController: HistorySearchViewControllerDelegate { func controller(_ controller: HistorySearchViewController, needsPerform action: HistorySearchViewController.Action) { switch action { case .keyOfHistory(let keySearched): delegate?.controller(self, needsPerform: .keyOfHistory(keySearched: keySearched)) searchType = .correctly switchingPage() } } } extension SearchingViewController { enum SearchType: Int { case correctly case recently case history } struct Config { static let attributesForSelected: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.black] static let attributesForNormal: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13), NSAttributedString.Key.foregroundColor: UIColor.gray] } }
36.433333
136
0.676121
1643d068e1b7e28ea6573f996df53de52d08c6d6
517
// // Error.swift // WHCoreServices // // Created by Wayne Hsiao on 2019/4/5. // Copyright © 2019 Wayne Hsiao. All rights reserved. // import Foundation //public enum GitHubEndpointError: Error { // case invalidGitHubEndpoint(endpoint: EndpointFactory) // case invalidGitHubEndpointable(endpoint: Endpoint) //} public enum APIError: Error { case getAccessTokenError case getOperationError case postOperationError case parameterError case parseError case bearerTokenExpiredError }
21.541667
59
0.738878
9b95513a932e8208f751c9c81a1114cf8675b303
23,354
// // ViewModuleRouterPerformTests.swift // ZIKViewRouterTests // // Created by zuik on 2018/4/26. // Copyright © 2018 zuik. All rights reserved. // import UIKit import ZRouter class ViewModuleRouterPerformTests: ZIKViewRouterTestCase { weak var testRouter: ModuleViewRouter<AViewModuleInput>? { willSet { self.router = newValue?.router self.strongTestRouter = newValue } } var strongTestRouter: ModuleViewRouter<AViewModuleInput>? override func leaveTestView(completion: @escaping (Bool, ZIKRouteAction, Error?) -> Void) { XCTAssertNotNil(testRouter) testRouter?.removeRoute(configuring: { (config) in config.successHandler = { print("LeaveTestView succeed") self.leaveTestViewExpectation.fulfill() } config.errorHandler = { (_, _) in print("LeaveTestView failed") if type(of: self).allowLeaveTestViewFailing() { self.leaveTestViewExpectation.fulfill() } } config.completionHandler = completion }) strongTestRouter = nil strongRouter = nil } override func leaveTest() { if testRouter == nil || testRouter?.state == .unrouted || testRouter?.state == .removed { strongTestRouter = nil strongRouter = nil leaveTestViewExpectation.fulfill() leaveSourceView() return } leaveTestView { (_, _, _) in self.leaveSourceView() } } override func setUp() { super.setUp() self.routeType = .presentModally } override func tearDown() { super.tearDown() assert(testRouter == nil, "Didn't leave test view") self.testRouter = nil self.strongTestRouter = nil } func path(from source: UIViewController) ->ViewRoutePath { var routeSource: ZIKViewRouteSource? = source if self.routeType == .addAsSubview { routeSource = source.view } let path = ViewRoutePath(path: ZIKViewRoutePath(routeType: routeType, source: routeSource)) XCTAssertNotNil(path) return path! } func configure(routeConfiguration config: ViewRouteConfig, source: ZIKViewRouteSource?) { config.animated = true config.routeType = self.routeType } func testPerformWithPrepareDestination() { let expectation = self.expectation(description: "prepareDestination") enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: self.path(from: source), configuring: { (config, prepareModule) in self.configure(routeConfiguration: config.config.configuration, source: source) prepareModule({ module in module.title = "test title" module.makeDestinationCompletion({ (destination) in XCTAssert(destination.title == "test title") }) expectation.fulfill() }) config.successHandler = { destination in XCTAssert(destination is AViewInput) self.handle({ XCTAssert(self.router?.state == .routed) self.leaveTest() }) } }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } func testPerformWithSuccessCompletionHandler() { let expectation = self.expectation(description: "completionHandler") enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: self.path(from: source), configuring: { (config, prepareModule) in self.configure(routeConfiguration: config.config.configuration, source: source) prepareModule({ module in module.title = "test title" module.makeDestinationCompletion({ (destination) in XCTAssert(destination.title == "test title") }) }) config.completionHandler = { (success, destination, action, error) in XCTAssertTrue(success) XCTAssertNil(error) expectation.fulfill() self.handle({ XCTAssert(self.router?.state == .routed) self.leaveTest() }) } }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } func testPerformWithErrorCompletionHandler() { let expectation = self.expectation(description: "completionHandler") enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: .extensible(path: ZIKViewRoutePath(routeType: self.routeType, source: nil)), configuring: { (config, prepareModule) in self.configure(routeConfiguration: config.config.configuration, source: source) prepareModule({ module in module.title = "test title" module.makeDestinationCompletion({ (destination) in XCTAssert(destination.title == "test title") }) }) config.completionHandler = { (success, destination, action, error) in XCTAssertFalse(success) XCTAssertNotNil(error) expectation.fulfill() self.handle({ XCTAssert(self.router == nil || self.router?.state == .unrouted) self.leaveTest() }) } }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } func testPerformWithSuccessCompletion() { let expectation = self.expectation(description: "completionHandler") enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: self.path(from: source), completion: { (success, destination, action, error) in XCTAssertTrue(success) XCTAssertNil(error) expectation.fulfill() self.handle({ XCTAssert(self.router?.state == .routed) self.leaveTest() }) }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } func testPerformWithErrorCompletion() { let expectation = self.expectation(description: "completionHandler") enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: .extensible(path: ZIKViewRoutePath(routeType: self.routeType, source: nil)), completion: { (success, destination, action, error) in XCTAssertFalse(success) XCTAssertNotNil(error) expectation.fulfill() self.handle({ XCTAssert(self.router == nil || self.router?.state == .unrouted) self.leaveTest() }) }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } func testPerformRouteWithSuccessCompletion() { let expectation = self.expectation(description: "completionHandler") expectation.assertForOverFulfill = true enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: self.path(from: source), completion: { (success, destination, action, error) in XCTAssertTrue(success) XCTAssertNil(error) self.handle({ XCTAssert(self.router?.state == .routed) self.testRouter?.removeRoute(successHandler: { XCTAssert(self.router?.state == .removed) self.testRouter?.performRoute(completion: { (success, destination, action, error) in XCTAssert(self.router?.state == .routed) XCTAssertTrue(success) XCTAssertNil(error) expectation.fulfill() self.leaveTest() }) }) }) }) } waitForExpectations(timeout: 500, handler: { if let error = $0 {print(error)}}) } func testPerformRouteWithErrorCompletion() { let expectation = self.expectation(description: "completionHandler") expectation.assertForOverFulfill = true enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: self.path(from: source), completion: { (success, destination, action, error) in XCTAssertTrue(success) XCTAssertNil(error) self.handle({ XCTAssert(self.router?.state == .routed) XCTAssertTrue(self.router!.shouldRemoveBeforePerform()) self.testRouter?.performRoute(completion: { (success, destination, action, error) in XCTAssertFalse(success) XCTAssertNotNil(error) expectation.fulfill() self.leaveTest() }) }) }) } waitForExpectations(timeout: 500, handler: { if let error = $0 {print(error)}}) } func testPerformWithSuccess() { let expectation = self.expectation(description: "successHandler") enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: self.path(from: source), configuring: { (config, prepareModule) in self.configure(routeConfiguration: config.config.configuration, source: source) prepareModule({ module in module.title = "test title" module.makeDestinationCompletion({ (destination) in XCTAssert(destination.title == "test title") }) }) config.successHandler = { d in expectation.fulfill() self.handle({ XCTAssert(self.router?.state == .routed) self.leaveTest() }) } }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } func testPerformWithPerformerSuccess() { let providerHandlerExpectation = self.expectation(description: "successHandler") providerHandlerExpectation.expectedFulfillmentCount = 2 let performerHandlerExpectation = self.expectation(description: "performerSuccessHandler") performerHandlerExpectation.assertForOverFulfill = true enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: self.path(from: source), configuring: { (config, prepareModule) in self.configure(routeConfiguration: config.config.configuration, source: source) prepareModule({ module in module.title = "test title" module.makeDestinationCompletion({ (destination) in XCTAssert(destination.title == "test title") }) }) config.successHandler = { d in providerHandlerExpectation.fulfill() } config.performerSuccessHandler = { d in performerHandlerExpectation.fulfill() self.handle({ XCTAssert(self.router?.state == .routed) self.testRouter?.removeRoute(successHandler: { XCTAssert(self.router?.state == .removed) self.testRouter?.performRoute(successHandler: { (d) in XCTAssert(self.router?.state == .routed) self.leaveTest() }) }) }) } }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } func testPerformWithError() { let providerHandlerExpectation = self.expectation(description: "errorHandler") let performerHandlerExpectation = self.expectation(description: "performerErrorHandler") enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: .extensible(path: ZIKViewRoutePath(routeType: self.routeType, source: nil)), configuring: { (config, prepareModule) in self.configure(routeConfiguration: config.config.configuration, source: source) prepareModule({ module in module.title = "test title" module.makeDestinationCompletion({ (destination) in XCTAssert(destination.title == "test title") }) }) config.successHandler = { d in XCTAssert(false, "successHandler should not be called") } config.performerSuccessHandler = { d in XCTAssert(false, "performerSuccessHandler should not be called") } config.errorHandler = { (action, error) in providerHandlerExpectation.fulfill() } config.performerErrorHandler = { (action, error) in performerHandlerExpectation.fulfill() self.handle({ XCTAssert(self.router == nil || self.router?.state == .unrouted) self.leaveTest() }) } }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } func testPerformOnDestinationSuccess() { let providerHandlerExpectation = self.expectation(description: "errorHandler") let performerHandlerExpectation = self.expectation(description: "performerErrorHandler") let completionHandlerExpectation = self.expectation(description: "completionHandler") enterTest { (source) in let destination = Router.makeDestination(to: RoutableViewModule<AViewModuleInput>()) self.testRouter = Router .to(RoutableViewModule<AViewModuleInput>())? .perform( onDestination: destination!, path: self.path(from: source), configuring: { (config, prepareModule) in self.configure(routeConfiguration: config.config.configuration, source: source) prepareModule({ module in module.title = "test title" module.makeDestinationCompletion({ (destination) in XCTAssert(destination.title == "test title") }) }) config.successHandler = { d in providerHandlerExpectation.fulfill() } config.performerSuccessHandler = { d in performerHandlerExpectation.fulfill() } config.completionHandler = { (success, destination, action, error) in completionHandlerExpectation.fulfill() self.handle({ XCTAssert(self.router?.state == .routed) self.leaveTest() }) } config.errorHandler = { (action, error) in XCTAssert(false, "errorHandler should not be called") } config.performerErrorHandler = { (action, error) in XCTAssert(false, "performerErrorHandler should not be called") } }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } } class ViewModuleRouterPerformWithoutAnimationTests: ViewModuleRouterPerformTests { override func configure(routeConfiguration config: ViewRouteConfig, source: ZIKViewRouteSource?) { super.configure(routeConfiguration: config, source: source) config.animated = false } } class ViewModuleRouterPerformPresentAsPopoverTests: ViewModuleRouterPerformTests { override func setUp() { super.setUp() self.routeType = .presentAsPopover } override func path(from source: UIViewController) -> ViewRoutePath { return .presentAsPopover(from: source, configure: { (popoverConfig) in popoverConfig.sourceView = source.view popoverConfig.sourceRect = CGRect(x: 0, y: 0, width: 50, height: 10) }) } override func testPerformWithSuccessCompletion() { leaveTest() waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } override func testPerformRouteWithSuccessCompletion() { leaveTest() waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } override func testPerformRouteWithErrorCompletion() { let expectation = self.expectation(description: "completionHandler") enterTest { (source) in self.testRouter = Router.perform( to: RoutableViewModule<AViewModuleInput>(), path: self.path(from: source), configuring: { (config, prepareModule) in self.configure(routeConfiguration: config.config.configuration, source: source) prepareModule({ module in module.title = "test title" module.makeDestinationCompletion({ (destination) in XCTAssert(destination.title == "test title") }) }) config.performerSuccessHandler = { d in self.handle({ XCTAssert(self.router?.state == .routed) self.testRouter?.performRoute(completion: { (success, destination, action, error) in XCTAssertFalse(success) XCTAssertNotNil(error) expectation.fulfill() XCTAssert(self.router?.state == .routed) self.leaveTest() }) }) } }) } waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } } class ViewModuleRouterPerformPresentAsPopoverWithoutAnimationTests: ViewModuleRouterPerformPresentAsPopoverTests { override func setUp() { super.setUp() self.routeType = .presentAsPopover } override func configure(routeConfiguration config: ViewRouteConfig, source: ZIKViewRouteSource?) { super.configure(routeConfiguration: config, source: source) config.animated = false } } class ViewModuleRouterPerformPushTests: ViewModuleRouterPerformTests { override func setUp() { super.setUp() self.routeType = .push } } class ViewModuleRouterPerformPushWithoutAnimationTests: ViewModuleRouterPerformWithoutAnimationTests { override func setUp() { super.setUp() self.routeType = .push } } class ViewModuleRouterPerformShowTests: ViewModuleRouterPerformTests { override func setUp() { super.setUp() self.routeType = .show } } class ViewModuleRouterPerformShowWithoutAnimationTests: ViewModuleRouterPerformWithoutAnimationTests { override func setUp() { super.setUp() self.routeType = .show } } class ViewModuleRouterPerformShowDetailTests: ViewModuleRouterPerformTests { override func setUp() { super.setUp() self.routeType = .showDetail } override class func allowLeaveTestViewFailing() ->Bool { if UI_USER_INTERFACE_IDIOM() == .pad { return true } return false } override func testPerformWithPerformerSuccess() { leaveTest() waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } override func testPerformRouteWithSuccessCompletion() { leaveTest() waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } } class ViewModuleRouterPerformShowDetailWithoutAnimationTests: ViewModuleRouterPerformWithoutAnimationTests { override func setUp() { super.setUp() self.routeType = .showDetail } override class func allowLeaveTestViewFailing() ->Bool { if UI_USER_INTERFACE_IDIOM() == .pad { return true } return false } override func testPerformWithPerformerSuccess() { leaveTest() waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } override func testPerformRouteWithSuccessCompletion() { leaveTest() waitForExpectations(timeout: 5, handler: { if let error = $0 {print(error)}}) } } class ViewModuleRouterPerformCustomTests: ViewModuleRouterPerformTests { override func setUp() { super.setUp() self.routeType = .custom } }
42.231465
114
0.534127
337661daea9c1336e3a25d7b795af96bd4604545
431
// // NetworkError.swift // // Created by 서상민 on 2021/04/28. // import Foundation /// 네트워크 에러 public enum NetworkError: LocalizedError { /// 도메인을 알 수 없음 case unknownDomain /// 설명 public var errorDescription: String? { get { switch self { case .unknownDomain: return "Info.plist에 \"API_URL\" 이름의 Key를 생성하여 주소 값을 입력해 주세요!" } } } }
17.24
77
0.531323
f9d81622c3f889ff896bdc37f77bb2fc19fe8307
1,731
// // EXFileManager.swift // KTSZ // // Created by cfans on 2018/10/22. // Copyright © 2018年 cfans. All rights reserved. // import Foundation extension FileManager { func copyfileToUserDocumentDirectory(forResource name: String, ofType ext: String) throws { let fileName = "\(name).\(ext)" if let bundlePath = Bundle.main.path(forResource: name, ofType: ext), let destPath = getFileFullPath(fileName: fileName) { if !self.fileExists(atPath: destPath) { print("copy") try self.copyItem(atPath: bundlePath, toPath: destPath) }else{ print("copy OK ") } } } func getFileFullPath(fileName:String)->String?{ if let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first{ return URL(fileURLWithPath: destPath) .appendingPathComponent(fileName).path } return nil } } extension FileManager { func removeIfExisted(_ url:URL) -> Void { if FileManager.default.fileExists(atPath: url.path) { do { try FileManager.default.removeItem(atPath: url.path) } catch { print("Failed to delete file") } } } func tempFileUrl(_ outputName:String) ->URL{ let path = NSTemporaryDirectory().appending(outputName) let exportURL = URL.init(fileURLWithPath: path) removeIfExisted(exportURL) return exportURL } }
29.844828
81
0.539573
e5a0f65a725f853dc3d95d980cd48e393c326c4a
2,843
// // AppDelegate.swift // dreamteam // // Created by Holofox on 04.08.2019. // Copyright © 2019 Holofox. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) let navControllers = ( entries: EntriesListBuilder.build(usingNavigationFactory: NavigationBuilder.build), add: AddBuilder.build(usingNavigationFactory: NavigationBuilder.build), edit: EditListBuilder.build(usingNavigationFactory: NavigationBuilder.build), group: GroupListBuilder.build(usingNavigationFactory: NavigationBuilder.build) ) let tabBarController = TabBarBuilder.build(usingNavControllers: navControllers) window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.606557
285
0.737953
03fd3b248e595cc46053a148d311f4240b56be3c
495
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache 2.0 */ import Foundation protocol ReconnectionStrategyProtocol { func reconnectAfter(attempt: Int) -> TimeInterval? } struct ExponentialReconnection: ReconnectionStrategyProtocol { let multiplier: Double init(multiplier: Double = 0.3) { self.multiplier = multiplier } func reconnectAfter(attempt: Int) -> TimeInterval? { multiplier * exp(Double(attempt)) } }
21.521739
62
0.705051
3a780a45e20a6571a9815356f28bc98ae14ff482
3,301
// // XPCConvertible.swift // SwiftyXPC // // Created by Charles Srstka on 7/22/21. // import CoreFoundation import XPC public protocol XPCConvertible: _XPCConvertible { static func fromXPCObject(_ xpcObject: xpc_object_t) -> Self? func toXPCObject() -> xpc_object_t? } public protocol _XPCConvertible { static func _fromXPCObject(_ xpcObject: xpc_object_t) -> _XPCConvertible? func toXPCObject() -> xpc_object_t? } extension XPCConvertible { public static func _fromXPCObject(_ xpcObject: xpc_object_t) -> _XPCConvertible? { self.fromXPCObject(xpcObject) } } public func convertFromXPC(_ object: xpc_object_t) -> XPCConvertible? { switch xpc_get_type(object) { case XPC_TYPE_NULL: return CFNull.fromXPCObject(object) case XPC_TYPE_BOOL: return Bool.fromXPCObject(object) case XPC_TYPE_INT64: return Int64.fromXPCObject(object) case XPC_TYPE_UINT64: return UInt64.fromXPCObject(object) case XPC_TYPE_DOUBLE: return Double.fromXPCObject(object) case XPC_TYPE_DATE: return CFDate.fromXPCObject(object) case XPC_TYPE_DATA: return CFData.fromXPCObject(object) case XPC_TYPE_ENDPOINT: return XPCEndpoint(connection: object) case XPC_TYPE_FD: return XPCFileDescriptorWrapper.fromXPCObject(object) case XPC_TYPE_STRING: return String.fromXPCObject(object) case XPC_TYPE_UUID: return CFUUID.fromXPCObject(object) case XPC_TYPE_ARRAY: return [Any].fromXPCObject(object) case XPC_TYPE_DICTIONARY: if CFError.isXPCEncodedError(object) { return CFError.fromXPCObject(object) } else if CFURL.isXPCEncodedURL(object) { return CFURL.fromXPCObject(object) } else { return [String : Any].fromXPCObject(object) } default: return nil } } public func convertToXPC(_ obj: Any) -> xpc_object_t? { if let convertible = obj as? _XPCConvertible { return convertible.toXPCObject() } else { switch CFGetTypeID(obj as AnyObject) { case CFNullGetTypeID(): return unsafeBitCast(obj, to: CFNull.self).toXPCObject() case CFBooleanGetTypeID(): return unsafeBitCast(obj, to: CFBoolean.self).toXPCObject() case CFNumberGetTypeID(): return unsafeBitCast(obj, to: CFNumber.self).toXPCObject() case CFDateGetTypeID(): return unsafeBitCast(obj, to: CFDate.self).toXPCObject() case CFDataGetTypeID(): return unsafeBitCast(obj, to: CFData.self).toXPCObject() case CFStringGetTypeID(): return unsafeBitCast(obj, to: CFString.self).toXPCObject() case CFUUIDGetTypeID(): return unsafeBitCast(obj, to: CFUUID.self).toXPCObject() case CFArrayGetTypeID(): return unsafeBitCast(obj, to: CFArray.self).toXPCObject() case CFDictionaryGetTypeID(): return unsafeBitCast(obj, to: CFDictionary.self).toXPCObject() case CFURLGetTypeID(): return unsafeBitCast(obj, to: CFURL.self).toXPCObject() case CFErrorGetTypeID(): return unsafeBitCast(obj, to: CFError.self).toXPCObject() default: return nil } } }
33.683673
86
0.669494
eb18979211a45338445918c30f7d04efca860fd8
994
// // Config.swift // WebRTC-Demo // // Created by Stasel on 30/01/2019. // Copyright © 2019 Stasel. All rights reserved. // import Foundation // Set this to the machine's address which runs the signaling server fileprivate let defaultSignalingServerUrl = URL(string: "ws://[2601:648:8402:4870:8188:40fd:9439:6851]:8080")! // We use Google's public stun servers. For production apps you should deploy your own stun/turn servers. fileprivate let defaultIceServers = ["stun:stun.l.google.com:19302", "stun:stun1.l.google.com:19302", "stun:stun2.l.google.com:19302", "stun:stun3.l.google.com:19302", "stun:stun4.l.google.com:19302"] struct Config { let signalingServerUrl: URL let webRTCIceServers: [String] static let `default` = Config(signalingServerUrl: defaultSignalingServerUrl, webRTCIceServers: defaultIceServers) }
36.814815
117
0.632797
9b3328ba6dda07495da82402c18e41dfdf125a98
281
import Swish internal struct AnyRequestMatcher<T: Request>: RequestMatcher { func match<S>(_: S) -> Result<S.ResponseObject, SwishError>? where S: Request { return response as? Result<S.ResponseObject, SwishError> } let response: Result<T.ResponseObject, SwishError> }
28.1
81
0.743772
38581a8936ca8e67bab746d6905047f4b0ca9a6c
2,378
// // SignUpGradientButton.swift // Recipes // // Created by Het Prajapati on 7/3/21. // import SwiftUI struct SignUpGradientButton: View { //MARK: - PROPERTIES @State private var angle = 0.0 var gradients: [Color] = [ Color.init(red: 207/255, green: 154/255, blue: 253/255), Color.init(red: 16/255, green: 27/255, blue: 46/255), Color.init(red: 34/255, green: 41/255, blue: 85/255) ] var buttonTitle: String var buttonAction: () -> Void var body: some View { Button(action: buttonAction, label: { GeometryReader() {geometry in ZStack{ AngularGradient(gradient: Gradient(colors: gradients), center: .center, angle: .degrees(angle)) .blendMode(.overlay) .blur(radius: 8.0) .mask( RoundedRectangle(cornerRadius: 16.0) .frame(height: 50) .frame(maxWidth: geometry.size.width - 16) .blur(radius: 8.0) ) .onAppear(){ withAnimation(.linear(duration: 5)){ self.angle += 350 } } SignUpGradientText(text: buttonTitle) .font(.headline) .frame(width: geometry.size.width - 16) .frame(height: 50) .background( Color("tertiaryBackground") .opacity(0.9) ) .overlay( RoundedRectangle(cornerRadius: 16.0) .stroke(Color.white, lineWidth: 1.0) .blendMode(.normal) .opacity(0.7) ) .cornerRadius(16.0) } } .frame(height: 50) }) } } // //struct SignUpGradientButton_Previews: PreviewProvider { // static var previews: some View { // SignUpGradientButton(buttonTitle: <#String#>, buttonAction: <#() -> Void#>) // } //}
33.027778
115
0.418839
5d8e89bef4221652355235b3db3cad1545da48d4
2,752
// // BuildPhaseAppenderTests.swift // XcodeProjectTests // // Created by Yudai Hirose on 2019/07/24. // import XCTest @testable import XcodeProjectCore class BuildFileAppenderTests: XCTestCase { func make() -> BuildFileAppender { return BuildFileAppenderImpl() } func testAppend() { XCTContext.runActivity(named: "When append file is not exist", block: { _ in let xcodeproject = makeXcodeProject() let appender = make() let mockIDGenerator = StringGeneratorMock() mockIDGenerator.generateReturnValue = "ABC" let maker = FileReferenceMakerImpl(hashIDGenerator: mockIDGenerator) let fileRef = FileReferenceAppenderImpl(fileReferenceMaker: maker) .append(context: xcodeproject.context, filePath: "iOSTestProject/Hoge.swift") let originalObjects = xcodeproject.context.objects XCTAssertEqual(originalObjects.keys.count, xcodeproject.context.objects.keys.count) XCTAssertEqual(originalObjects.values.compactMap { $0 as? PBX.BuildFile }.count, xcodeproject.context.objects.values.compactMap { $0 as? PBX.BuildFile }.count) appender.append(context: xcodeproject.context, fileRefID: fileRef.id, targetName: "iOSTestProject", fileName: fileRef.path!) XCTAssertEqual(originalObjects.keys.count + 1, xcodeproject.context.objects.keys.count) XCTAssertEqual(originalObjects.values.compactMap { $0 as? PBX.BuildFile }.count + 1, xcodeproject.context.objects.values.compactMap { $0 as? PBX.BuildFile }.count) }) XCTContext.runActivity(named: "When append file is exist", block: { _ in let xcodeproject = makeXcodeProject() let appender = make() let originalObjects = xcodeproject.context.objects let fileRef = FileRefExtractorImpl(groupExtractor: GroupExtractorImpl()).extract(context: xcodeproject.context, groupPath: "iOSTestProject", fileName: "AppDelegate.swift")! XCTAssertEqual(originalObjects.keys.count, xcodeproject.context.objects.keys.count) XCTAssertEqual(originalObjects.values.compactMap { $0 as? PBX.BuildFile }.count, xcodeproject.context.objects.values.compactMap { $0 as? PBX.BuildFile }.count) appender.append(context: xcodeproject.context, fileRefID: fileRef.id, targetName: "iOSTestProject", fileName: fileRef.path!) XCTAssertEqual(originalObjects.keys.count, xcodeproject.context.objects.keys.count) XCTAssertEqual(originalObjects.values.compactMap { $0 as? PBX.BuildFile }.count, xcodeproject.context.objects.values.compactMap { $0 as? PBX.BuildFile }.count) }) } }
52.923077
184
0.695494
f8f1fe7496ecce640987f244605ee0a2f402a6b3
973
extension _VKAPI { ///Utilites. More - https://vk.com/dev/ public struct Utils { ///Checks whether a link is blocked in VK. More - https://vk.com/dev/utils.checkLink public static func checkLink(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "utils.checkLink", parameters: parameters) } ///Detects a type of object (e.g., user, community, application) and its ID by screen name. More - https://vk.com/dev/utils.resolveScreenName public static func resolveScreenName(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "utils.resolveScreenName", parameters: parameters) } ///Returns the current time of the VK server. More - https://vk.com/dev/utils.getServerTime public static func getServerTime(parameters: [VK.Arg : String] = [:]) -> Request { return Request(method: "utils.getServerTime", parameters: parameters) } } }
37.423077
145
0.652621
26a40b6f6a4fa23e7af5657bd3ca6a2ba6536c0f
4,806
// // MovieListMocks.swift // The Movie DB ClientTests // // Created by Amadeu Cavalcante on 21/05/2018. // Copyright © 2018 Amadeu Cavalcante Filho. All rights reserved. // import Foundation @testable import The_Movie_DB_Client final class MovieListMocks { private init() {} final class UpcomingMovieOutput: UpcomingMovieOutputProtocol { var onUpcomingMovieRetrievedInvoked = false var onErrorInvoked = false var upcomingMovies: MovieUpcomingResponse? var configuration: TMDbApiConfigurationResponse? func onUpcomingMovieRetrieved(_ movies: MovieUpcomingResponse, _ configuration: TMDbApiConfigurationResponse?) { onUpcomingMovieRetrievedInvoked = true self.upcomingMovies = movies self.configuration = configuration } func onError() { onErrorInvoked = true } } final class TMDbApiConfigurationOutput: TMDbApiConfigurationOutputProtocol { var onTMDbApiConfigurationRetrievedInvoked = false var onErrorInvoked = false var configuration: TMDbApiConfigurationResponse? func onTMDbApiConfigurationRetrieved(_ config: TMDbApiConfigurationResponse) { onTMDbApiConfigurationRetrievedInvoked = true configuration = config } func onError() { onErrorInvoked = true } } final class RemoteDataManagerInput: MovieListRemoteDataManagerInputProtocol { var fetchUpcomingMovieInvoked = false var fetchSearchInvoked = false var fetchTMDbApiConfigurationInvoked = false var saveMovieInvoked = false var saveTMDbApiConfigurationInvoked = false var remoteUpcomingRequestHandler: UpcomingMovieOutputProtocol? var remoteTMDbConfigurationRequestHandler: TMDbApiConfigurationOutputProtocol? var remoteSearchMovieRequestHandler: SearchMovieOutputProtocol? private var movieResponse: MovieUpcomingResponse? private var tmdbApiConfigurationResponse: TMDbApiConfigurationResponse? private var movieDetail: MovieDetailsResponse? private let error: Error? init(error: Error? = nil) { let bundle = Bundle(for: type(of: self)) if let path = bundle.path(forResource: "get_movie_detail_response", ofType: "json") { let data = try! Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) let jsonResult = try! JSONSerialization.jsonObject(with: data, options: .mutableLeaves) let jsonData = try! JSONSerialization.data(withJSONObject: jsonResult) let movieDetail = try! JSONDecoder().decode(MovieDetailsResponse.self, from: jsonData) self.movieDetail = movieDetail } self.error = error } func getUpcomingReleases(forPageAt page: Int) { fetchUpcomingMovieInvoked = true remoteUpcomingRequestHandler? .onUpcomingMovieRetrieved(movieResponse!, tmdbApiConfigurationResponse) } } final class LocalDataManagerInput: MovieListLocalDataManagerInputProtocol { var fetchMovieInvoked = false var fetchSearchInvoked = false var fetchTMDbApiConfigurationInvoked = false var saveMovieInvoked = false var saveTMDbApiConfigurationInvoked = false var saveMovieParameters: MovieUpcomingResponse? var saveTMDbApiConfigurationParameters: TMDbApiConfigurationResponse? private var movies: [Movie] = [] private var configurationEntity: ConfigurationEntity? private let error: Error? init(movies: [Movie], configuration: ConfigurationEntity? = nil, error: Error? = nil) { self.movies = movies self.configurationEntity = configuration self.error = error } func getNextMoviesReleases() throws -> [Movie] { fetchMovieInvoked = true return movies } func searchMovie(forTitle title: String) throws -> [Movie] { fetchSearchInvoked = true return movies } func getTMDbApiConfiguration() throws -> ConfigurationEntity? { fetchTMDbApiConfigurationInvoked = true return configurationEntity } func saveMovie(forMovieUpcomingResponse movieUpcomingResponse: MovieUpcomingResponse) throws { saveMovieInvoked = true saveMovieParameters = movieUpcomingResponse } func saveTMDbApiConfiguration(forConfiguration configuration: TMDbApiConfigurationResponse) throws { saveTMDbApiConfigurationInvoked = true saveTMDbApiConfigurationParameters = configuration } } }
33.84507
120
0.679567
e6fe8d4ee095d8234109b5b8aa16f91389c49040
2,182
// // AppDelegate.swift // BuildingShadows // // Created by Vibhor Gupta on 12/26/17. // Copyright © 2017 Vibhor Gupta. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.425532
285
0.755729
20419a739215482a609f17931d6a74ae6d22d39d
443
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "FocusEntity", platforms: [.iOS(.v13), .macOS(.v10_15)], products: [ .library(name: "FocusEntity", targets: ["FocusEntity"]) ], dependencies: [], targets: [ .target(name: "FocusEntity", dependencies: []) ], swiftLanguageVersions: [.v5] )
24.611111
96
0.681716
fc74107e32245c0c55fd177b5a9353c0a277f867
3,895
// // MapController+MapKit.swift // _OnTheMap // // Created by admin on 2/2/19. // Copyright © 2019 admin. All rights reserved. // import UIKit import MapKit extension StudentLocationMapController { func setupMap(){ loadLocationsArray() convertLocationsToAnnotations() self.mapView.addAnnotations(annotations) //There's a singular & plural for 'addAnnotation'. OMG } private func convertLocationsToAnnotations(){ for dictionary in locations { let latitude = CLLocationDegrees(dictionary[locationsIndex.latitude.rawValue] as! Double) let longitude = CLLocationDegrees(dictionary[locationsIndex.longitude.rawValue] as! Double) let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let firstName = dictionary[locationsIndex.firstName.rawValue] as! String let lastName = dictionary[locationsIndex.lastName.rawValue] as! String let mediaURL = dictionary[locationsIndex.mediaURL.rawValue] as! String let tempAnnotation = MKPointAnnotation() tempAnnotation.coordinate = coordinate tempAnnotation.title = "\(firstName) \(lastName)" tempAnnotation.subtitle = mediaURL annotations.append(tempAnnotation) } } private func loadLocationsArray(){ StudentInformationModel.getVerifiedStudentLocations.forEach { let tempAnnotation: [String:Any] = [ locationsIndex.objectId.rawValue: $0.objectId, locationsIndex.uniqueKey.rawValue: $0.uniqueKey, locationsIndex.firstName.rawValue: $0.firstName, locationsIndex.lastName.rawValue: $0.lastName, locationsIndex.mapString.rawValue: $0.mapString, locationsIndex.mediaURL.rawValue: $0.mediaURL, locationsIndex.latitude.rawValue: $0.latitude, locationsIndex.longitude.rawValue: $0.longitude, locationsIndex.createdAt.rawValue: $0.createdAt, locationsIndex.updatedAt.rawValue: $0.updatedAt ] locations.append(tempAnnotation) } } //MARK:- MKMapViewDelegagate -- MAP Specific functions func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) // pinView?.clusteringIdentifier = "identifier" pinView?.displayPriority = .defaultHigh pinView!.canShowCallout = true pinView!.tintColor = .blue pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } else { pinView!.annotation = annotation } return pinView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { print("\n\nAnnotations.Count ---> \(annotations.count)") guard var _stringToURL = view.annotation?.subtitle as? String else { UIApplication.shared.open(URL(string: "https://www.google.com")!) //MediaURL = empty. Load google return } let backupURL = URL(string: "https://www.google.com/search?q=" + _stringToURL)! //URL is invalid, convert string to google search query if _stringToURL._isValidURL { _stringToURL = _stringToURL._prependHTTPifNeeded() let url = URL(string: _stringToURL) ?? backupURL UIApplication.shared.open(url) } else { UIApplication.shared.open(backupURL) } } }
42.802198
144
0.646727
225d90baa5057715188364d725455c9e980ea619
8,983
import KsApi import Prelude import ReactiveSwift import ReactiveExtensions import Result public protocol LoginViewModelInputs { /// String value of email textfield text func emailChanged(_ email: String?) /// Call when email textfield keyboard returns. func emailTextFieldDoneEditing() /// Call when the environment has been logged into. func environmentLoggedIn() /// Call when login button is pressed. func loginButtonPressed() /// Call with onepassword's available ability. func onePassword(isAvailable available: Bool) /// Call when the onepassword button is tapped. func onePasswordButtonTapped() /// Call when onepassword finds a login. func onePasswordFoundLogin(email: String?, password: String?) /// String value of password textfield text func passwordChanged(_ password: String?) /// Call when password textfield keyboard returns. func passwordTextFieldDoneEditing() /// Call when reset password button is pressed. func resetPasswordButtonPressed() /// Call when the view did load. func viewDidLoad() /// Call when the view will appear. func viewWillAppear() } public protocol LoginViewModelOutputs { /// Emits when to dismiss a textfield keyboard var dismissKeyboard: Signal<(), NoError> { get } /// Emits text that should be put into the email field. var emailText: Signal<String, NoError> { get } /// Sets whether the email text field is the first responder. var emailTextFieldBecomeFirstResponder: Signal<(), NoError> { get } /// Bool value whether form is valid var isFormValid: Signal<Bool, NoError> { get } /// Emits an access token envelope that can be used to update the environment. var logIntoEnvironment: Signal<AccessTokenEnvelope, NoError> { get } /// Emits a boolean that determines if the onepassword button should be hidden or not. var onePasswordButtonHidden: Signal<Bool, NoError> { get } /// Emits when we should request from the onepassword extension a login. var onePasswordFindLoginForURLString: Signal<String, NoError> { get } /// Emits text that should be put into the password field. var passwordText: Signal<String, NoError> { get } /// Emits when the password textfield should become the first responder var passwordTextFieldBecomeFirstResponder: Signal<(), NoError> { get } /// Emits when a login success notification should be posted. var postNotification: Signal<Notification, NoError> { get } /// Emits when a login error has occurred and a message should be displayed. var showError: Signal<String, NoError> { get } /// Emits when the reset password screen should be shown var showResetPassword: Signal<(), NoError> { get } /// Emits when TFA is required for login. var tfaChallenge: Signal<(email: String, password: String), NoError> { get } } public protocol LoginViewModelType { var inputs: LoginViewModelInputs { get } var outputs: LoginViewModelOutputs { get } } public final class LoginViewModel: LoginViewModelType, LoginViewModelInputs, LoginViewModelOutputs { public init() { let emailAndPassword = Signal.combineLatest( .merge(self.emailChangedProperty.signal.skipNil(), self.prefillEmailProperty.signal.skipNil()), .merge(self.passwordChangedProperty.signal.skipNil(), self.prefillPasswordProperty.signal.skipNil()) ) self.emailTextFieldBecomeFirstResponder = self.viewDidLoadProperty.signal self.isFormValid = self.viewWillAppearProperty.signal.mapConst(false).take(first: 1) .mergeWith(emailAndPassword.map(isValid)) let tryLogin = Signal.merge( self.loginButtonPressedProperty.signal, self.passwordTextFieldDoneEditingProperty.signal, Signal.combineLatest( self.prefillEmailProperty.signal, self.prefillPasswordProperty.signal ).ignoreValues() ) let loginEvent = emailAndPassword .takeWhen(tryLogin) .switchMap { email, password in AppEnvironment.current.apiService.login(email: email, password: password, code: nil) .materialize() } self.logIntoEnvironment = loginEvent.values() let tfaError = loginEvent.errors() .filter { $0.ksrCode == .TfaRequired } .ignoreValues() self.tfaChallenge = emailAndPassword .takeWhen(tfaError) .map { (email: $0, password: $1) } self.postNotification = self.environmentLoggedInProperty.signal .mapConst(Notification(name: .ksr_sessionStarted)) self.dismissKeyboard = self.passwordTextFieldDoneEditingProperty.signal self.passwordTextFieldBecomeFirstResponder = self.emailTextFieldDoneEditingProperty.signal self.showError = loginEvent.errors() .filter { $0.ksrCode != .TfaRequired } .map { env in env.errorMessages.first ?? Strings.login_errors_unable_to_log_in() } self.showResetPassword = self.resetPasswordPressedProperty.signal self.onePasswordButtonHidden = self.onePasswordIsAvailable.signal.map(negate) self.onePasswordFindLoginForURLString = self.onePasswordButtonTappedProperty.signal .map { AppEnvironment.current.apiService.serverConfig.webBaseUrl.absoluteString } self.emailText = self.prefillEmailProperty.signal.skipNil() self.passwordText = self.prefillPasswordProperty.signal.skipNil() Signal.combineLatest(self.emailText, self.passwordText) .observeValues { _ in AppEnvironment.current.koala.trackAttemptingOnePasswordLogin() } self.onePasswordIsAvailable.signal .observeValues { AppEnvironment.current.koala.trackLoginFormView(onePasswordIsAvailable: $0) } self.logIntoEnvironment .observeValues { _ in AppEnvironment.current.koala.trackLoginSuccess(authType: Koala.AuthType.email) } self.showError .observeValues { _ in AppEnvironment.current.koala.trackLoginError(authType: Koala.AuthType.email) } } public var inputs: LoginViewModelInputs { return self } public var outputs: LoginViewModelOutputs { return self } fileprivate let viewWillAppearProperty = MutableProperty(()) public func viewWillAppear() { self.viewWillAppearProperty.value = () } fileprivate let emailChangedProperty = MutableProperty<String?>(nil) public func emailChanged(_ email: String?) { self.emailChangedProperty.value = email } fileprivate let passwordChangedProperty = MutableProperty<String?>(nil) public func passwordChanged(_ password: String?) { self.passwordChangedProperty.value = password } fileprivate let loginButtonPressedProperty = MutableProperty(()) public func loginButtonPressed() { self.loginButtonPressedProperty.value = () } fileprivate let onePasswordButtonTappedProperty = MutableProperty(()) public func onePasswordButtonTapped() { self.onePasswordButtonTappedProperty.value = () } fileprivate let prefillEmailProperty = MutableProperty<String?>(nil) fileprivate let prefillPasswordProperty = MutableProperty<String?>(nil) public func onePasswordFoundLogin(email: String?, password: String?) { self.prefillEmailProperty.value = email self.prefillPasswordProperty.value = password } fileprivate let onePasswordIsAvailable = MutableProperty(false) public func onePassword(isAvailable available: Bool) { self.onePasswordIsAvailable.value = available } fileprivate let emailTextFieldDoneEditingProperty = MutableProperty(()) public func emailTextFieldDoneEditing() { self.emailTextFieldDoneEditingProperty.value = () } fileprivate let passwordTextFieldDoneEditingProperty = MutableProperty(()) public func passwordTextFieldDoneEditing() { self.passwordTextFieldDoneEditingProperty.value = () } fileprivate let environmentLoggedInProperty = MutableProperty(()) public func environmentLoggedIn() { self.environmentLoggedInProperty.value = () } fileprivate let resetPasswordPressedProperty = MutableProperty(()) public func resetPasswordButtonPressed() { self.resetPasswordPressedProperty.value = () } fileprivate let viewDidLoadProperty = MutableProperty(()) public func viewDidLoad() { self.viewDidLoadProperty.value = () } public let dismissKeyboard: Signal<(), NoError> public let emailText: Signal<String, NoError> public let emailTextFieldBecomeFirstResponder: Signal<(), NoError> public let isFormValid: Signal<Bool, NoError> public let logIntoEnvironment: Signal<AccessTokenEnvelope, NoError> public var onePasswordButtonHidden: Signal<Bool, NoError> public let onePasswordFindLoginForURLString: Signal<String, NoError> public let passwordText: Signal<String, NoError> public let passwordTextFieldBecomeFirstResponder: Signal<(), NoError> public let postNotification: Signal<Notification, NoError> public let showError: Signal<String, NoError> public let showResetPassword: Signal<(), NoError> public let tfaChallenge: Signal<(email: String, password: String), NoError> } private func isValid(email: String, password: String) -> Bool { return isValidEmail(email) && !password.isEmpty }
37.902954
108
0.757319
ab0fa32149824c303a90b25195306160f6331d61
951
// // GoogleMapDirectionLibTests.swift // GoogleMapDirectionLibTests // // Created by TriNgo on 5/12/20. // Copyright © 2020 RoverDream. All rights reserved. // import XCTest @testable import GoogleMapDirectionLib class GoogleMapDirectionLibTests: XCTestCase { override func 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. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.171429
111
0.672976
72da08f6ca83a1aa100ac82a3cd468dd4f1dfdc0
6,203
import AsyncHTTPClient import Foundation import NIO import NIOHTTP1 import Papyrus /// An error that occurred when requesting a `Papyrus.Endpoint`. public struct PapyrusClientError: Error { /// What went wrong. public let message: String /// The `HTTPClient.Response` of the failed response. public let response: HTTPClient.Response /// The response body, converted to a String, if there is one. public var bodyString: String? { guard let body = response.body else { return nil } var copy = body return copy.readString(length: copy.writerIndex) } } extension PapyrusClientError: CustomStringConvertible { public var description: String { """ \(message) Response: \(response.headers) Status: \(response.status.code) \(response.status.reasonPhrase) Body: \(bodyString ?? "N/A") """ } } extension Endpoint { /// Requests a `Papyrus.Endpoint`, returning a future with the /// decoded `Endpoint.Response`. /// /// - Parameters: /// - dto: An instance of the request DTO; `Endpoint.Request`. /// - client: The HTTPClient to request this with. Defaults to /// `Client.default`. /// - Returns: A future containing the decoded `Endpoint.Response` /// as well as the raw response of the `HTTPClient`. public func request( _ dto: Request, with client: HTTPClient = .default ) -> EventLoopFuture<(content: Response, response: HTTPClient.Response)> { return catchError { client.performRequest( baseURL: baseURL, parameters: try parameters(dto: dto), encoder: jsonEncoder, decoder: jsonDecoder ) } } } extension Endpoint where Request == Empty { /// Requests a `Papyrus.Endpoint` where the `Request` type is /// `Empty`, returning a future with the decoded /// `Endpoint.Response`. /// /// - Parameters: /// - client: The HTTPClient to request this with. Defaults to /// `Client.default`. /// - decoder: The decoder with which to decode response data to /// `Endpoint.Response`. Defaults to `JSONDecoder()`. /// - Returns: A future containing the decoded `Endpoint.Response` /// as well as the raw response of the `HTTPClient`. public func request( with client: HTTPClient = .default ) -> EventLoopFuture<(content: Response, response: HTTPClient.Response)> { return catchError { client.performRequest( baseURL: baseURL, parameters: try parameters(dto: .value), encoder: jsonEncoder, decoder: jsonDecoder ) } } } extension HTTPClient { /// Performs a request with the given request information. /// /// - Parameters: /// - baseURL: The base URL of the endpoint to request. /// - parameters: Information needed to make a request such as /// method, body, headers, etc. /// - encoder: The encoder with which to encode /// `Endpoint.Request` to request data to Defaults to /// `JSONEncoder()`. /// - decoder: A decoder with which to decode the response type, /// `Response`, from the `HTTPClient.Response`. /// - Returns: A future containing the decoded response and the /// raw `HTTPClient.Response`. fileprivate func performRequest<Response: Codable>( baseURL: String, parameters: HTTPComponents, encoder: JSONEncoder, decoder: JSONDecoder ) -> EventLoopFuture<(content: Response, response: HTTPClient.Response)> { catchError { var fullURL = baseURL + parameters.fullPath var headers = HTTPHeaders(parameters.headers.map { $0 }) var bodyData: Data? if parameters.bodyEncoding == .json { headers.add(name: "Content-Type", value: "application/json") bodyData = try parameters.body.map { try encoder.encode($0) } } else if parameters.bodyEncoding == .urlEncoded, let urlParams = try parameters.urlParams() { headers.add(name: "Content-Type", value: "application/x-www-form-urlencoded") bodyData = urlParams.data(using: .utf8) fullURL = baseURL + parameters.basePath + parameters.query } let request = try HTTPClient.Request( url: fullURL, method: HTTPMethod(rawValue: parameters.method), headers: headers, body: bodyData.map { HTTPClient.Body.data($0) } ) return execute(request: request) .flatMapThrowing { response in guard (200...299).contains(response.status.code) else { throw PapyrusClientError( message: "The response code was not successful", response: response ) } if Response.self == Empty.self { return (Empty.value as! Response, response) } guard let bodyBuffer = response.body else { throw PapyrusClientError( message: "Unable to decode response type `\(Response.self)`; the body of the response was empty!", response: response ) } // Decode do { let responseJSON = try HTTPBody(buffer: bodyBuffer).decodeJSON(as: Response.self, with: decoder) return (responseJSON, response) } catch { throw PapyrusClientError( message: "Error decoding `\(Response.self)` from the response. \(error)", response: response ) } } } } }
38.290123
126
0.551669
edfd80fcf3d68dac342a1f2487d38b1ae5babc53
1,031
// // Service.swift // qeeptouch // // Created by Javi on 4/17/16. // Copyright © 2016 QeepTouch. All rights reserved. // import Foundation import SwiftyJSON enum ServiceErrorType:Int { case notConnectedToNetwork = 8000 case responseDoesNotContainExpectedResult } extension NSError { convenience init(errorType:ServiceErrorType, message: String) { let userInfo = NSDictionary(dictionary: [NSLocalizedDescriptionKey: message] ) self.init(domain: "ErrorDomain", code: errorType.rawValue, userInfo: userInfo as [NSObject : AnyObject]) } } class Service: NetworkRequester { var baseURLString = "https://api-v2.olx.com/" // function for parsing dict func search( searchString:String, successBlock: (json:JSON) ->(), failBlock: (error: NSError) -> () ) { executeGETRequestAndValidateResponse(baseURLString+"/items?location=www.olx.com.ar&searchTerm=\(searchString)", successBlock: successBlock, failBlock: failBlock) } }
25.775
169
0.685742
91700ae8fc6307d85a8e061353e5510311f2e31a
9,849
@objc(MWMRouteManagerViewController) final class RouteManagerViewController: MWMViewController, UITableViewDataSource, UITableViewDelegate { let viewModel: RouteManagerViewModelProtocol @IBOutlet private var dimView: RouteManagerDimView! @IBOutlet private weak var footerViewHeight: NSLayoutConstraint! @IBOutlet private weak var headerView: RouteManagerHeaderView! @IBOutlet private weak var footerView: RouteManagerFooterView! @IBOutlet private weak var headerViewHeight: NSLayoutConstraint! @IBOutlet private weak var managerView: UIView! @IBOutlet private weak var managerWidth: NSLayoutConstraint! @IBOutlet private weak var minManagerTopOffset: NSLayoutConstraint! @IBOutlet private weak var tableView: RouteManagerTableView! lazy var chromeView: UIView = { let view = UIView() view.backgroundColor = UIColor.blackStatusBarBackground() return view }() weak var containerView: UIView! private var canDeleteRow: Bool { return viewModel.routePoints.count > 2 } final class DragCell { weak var controller: RouteManagerViewController! let snapshot: UIView var indexPath: IndexPath init(controller: RouteManagerViewController, cell: UITableViewCell, dragPoint: CGPoint, indexPath: IndexPath) { self.controller = controller snapshot = cell.snapshot self.indexPath = indexPath addSubView(cell: cell, dragPoint: dragPoint) controller.tableView.heightUpdateStyle = .off if controller.canDeleteRow { controller.dimView.state = .visible } } private func addSubView(cell: UITableViewCell, dragPoint: CGPoint) { let view = controller.containerView! view.addSubview(snapshot) snapshot.center = view.convert(cell.center, from: controller.tableView) cell.isHidden = true UIView.animate(withDuration: kDefaultAnimationDuration, animations: { [snapshot] in snapshot.center = dragPoint let scaleFactor: CGFloat = 1.05 snapshot.transform = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor) }) } func move(dragPoint: CGPoint, indexPath: IndexPath?, inManagerView: Bool) { snapshot.center = dragPoint if controller.canDeleteRow { controller.dimView.state = inManagerView ? .visible : .binOpenned } guard let newIP = indexPath else { return } let tv = controller.tableView! let cell = tv.cellForRow(at: newIP) let canMoveCell: Bool if let cell = cell { let (centerX, centerY) = (snapshot.width / 2, snapshot.height / 2) canMoveCell = cell.point(inside: cell.convert(CGPoint(x: centerX, y: 1.5 * centerY), from: snapshot), with: nil) && cell.point(inside: cell.convert(CGPoint(x: centerX, y: 0.5 * centerY), from: snapshot), with: nil) } else { canMoveCell = true } guard canMoveCell else { return } let currentIP = self.indexPath if newIP != currentIP { let (currentRow, newRow) = (currentIP.row, newIP.row) controller.viewModel.movePoint(at: currentRow, to: newRow) tv.moveRow(at: currentIP, to: newIP) let reloadRows = (min(currentRow, newRow) ... max(currentRow, newRow)).map { IndexPath(row: $0, section: 0) } tv.reloadRows(at: reloadRows, with: .fade) tv.cellForRow(at: newIP)?.isHidden = true self.indexPath = newIP Statistics.logEvent(kStatRouteManagerRearrange) } } func drop(inManagerView: Bool) { let removeSnapshot = { self.snapshot.removeFromSuperview() self.controller.dimView.state = .hidden } let containerView = controller.containerView! let tv = controller.tableView! if inManagerView || !controller.canDeleteRow { let dropCenter = tv.cellForRow(at: indexPath)?.center ?? snapshot.center UIView.animate(withDuration: kDefaultAnimationDuration, animations: { [snapshot] in snapshot.center = containerView.convert(dropCenter, from: tv) snapshot.transform = CGAffineTransform.identity }, completion: { [indexPath] _ in tv.reloadRows(at: [indexPath], with: .none) removeSnapshot() }) } else { tv.heightUpdateStyle = .animated tv.update { controller.viewModel.deletePoint(at: indexPath.row) tv.deleteRows(at: [indexPath], with: .automatic) } let dimView = controller.dimView! UIView.animate(withDuration: kDefaultAnimationDuration, animations: { [snapshot] in snapshot.center = containerView.convert(dimView.binDropPoint, from: dimView) let scaleFactor: CGFloat = 0.2 snapshot.transform = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor) }, completion: { _ in removeSnapshot() }) } } deinit { controller.tableView.heightUpdateStyle = .deferred } } var dragCell: DragCell? @objc init(viewModel: RouteManagerViewModelProtocol) { self.viewModel = viewModel super.init(nibName: toString(type(of: self)), bundle: nil) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupTableView() setupLayout() viewModel.refreshControlsCallback = { [unowned viewModel, unowned self] in let points = viewModel.routePoints self.footerView.isPlanButtonEnabled = points.count >= 2 self.headerView.isLocationButtonEnabled = true points.forEach { if $0.isMyPosition { self.headerView.isLocationButtonEnabled = false } } } viewModel.refreshControlsCallback() viewModel.reloadCallback = { [tableView] in tableView?.reloadSections(IndexSet(integer: 0), with: .fade) } viewModel.startTransaction() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) dimView.setViews(container: containerView, controller: view, manager: managerView) containerView.insertSubview(chromeView, at: 0) Statistics.logEvent(kStatRouteManagerOpen) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) Statistics.logEvent(kStatRouteManagerClose) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if preferredContentSize != managerView.size { preferredContentSize = managerView.size } } private func setupLayout() { alternative(iPhone: { self.managerWidth.isActive = false }, iPad: { self.minManagerTopOffset.isActive = false })() } private func setupTableView() { tableView.register(cellClass: RouteManagerCell.self) tableView.estimatedRowHeight = 48 tableView.rowHeight = UITableViewAutomaticDimension } @IBAction func onCancel() { viewModel.cancelTransaction() dismiss(animated: true, completion: nil) } @IBAction func onPlan() { viewModel.finishTransaction() dismiss(animated: true, completion: nil) } @IBAction func onAdd() { viewModel.addLocationPoint() tableView.heightUpdateStyle = .off tableView.update({ tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .fade) }, completion: { self.tableView.heightUpdateStyle = .deferred }) } @IBAction private func gestureRecognized(_ longPress: UIGestureRecognizer) { let locationInView = gestureLocation(longPress, in: containerView) let locationInTableView = gestureLocation(longPress, in: tableView) switch longPress.state { case .began: guard let indexPath = tableView.indexPathForRow(at: locationInTableView), let cell = tableView.cellForRow(at: indexPath) else { return } dragCell = DragCell(controller: self, cell: cell, dragPoint: locationInView, indexPath: indexPath) case .changed: guard let dragCell = dragCell else { return } let indexPath = tableView.indexPathForRow(at: locationInTableView) let inManagerView = managerView.point(inside: gestureLocation(longPress, in: managerView), with: nil) dragCell.move(dragPoint: locationInView, indexPath: indexPath, inManagerView: inManagerView) default: guard let dragCell = dragCell else { return } let inManagerView = managerView.point(inside: gestureLocation(longPress, in: managerView), with: nil) dragCell.drop(inManagerView: inManagerView) self.dragCell = nil } } private func gestureLocation(_ gestureRecognizer: UIGestureRecognizer, in view: UIView) -> CGPoint { var location = gestureRecognizer.location(in: view) iPhoneSpecific { location.x = view.width / 2 } return location } // MARK: - UITableViewDataSource func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return viewModel.routePoints.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withCellClass: RouteManagerCell.self, indexPath: indexPath) as! RouteManagerCell let row = indexPath.row cell.set(model: viewModel.routePoints[row], atIndex: row) return cell } func tableView(_ tableView: UITableView, commit _: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { viewModel.deletePoint(at: indexPath.row) } // MARK: - UITableViewDelegate func tableView(_: UITableView, editingStyleForRowAt _: IndexPath) -> UITableViewCellEditingStyle { return canDeleteRow ? .delete : .none } }
37.448669
125
0.678749
89a4d1c438d18000b0d6ed54beefa0db0be60702
19,921
// // Copyright (c) 2019 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // @testable import Adyen import XCTest class PaymentMethodTests: XCTestCase { func testDecodingPaymentMethods() throws { let dictionary = [ "storedPaymentMethods": [ storedCreditCardDictionary, storedCreditCardDictionary, storedPayPalDictionary, [ "type": "unknown", "id": "9314881977134903", "name": "Stored Redirect Payment Method", "supportedShopperInteractions": ["Ecommerce"] ], [ "type": "unknown", "name": "Invalid Stored Payment Method" ], storedBcmcDictionary, storedDeditCardDictionary, storedBlik ], "paymentMethods": [ creditCardDictionary, issuerListDictionary, sepaDirectDebitDictionary, [ "type": "unknown", "name": "Redirect Payment Method" ], [ "name": "Invalid Payment Method" ], bcmcCardDictionary, applePayDictionary, payPalDictionary, giroPayDictionaryWithOptionalDetails, giroPayDictionaryWithNonOptionalDetails, weChatQRDictionary, weChatWebDictionary, weChatMiniProgramDictionary, bcmcMobileQR, qiwiWallet, weChatSDKDictionary, debitCardDictionary, mbway, blik, googlePay, dokuWallet, giftCard ] ] // Stored payment methods let paymentMethods = try Coder.decode(dictionary) as PaymentMethods XCTAssertEqual(paymentMethods.stored.count, 7) XCTAssertTrue(paymentMethods.stored[0] is StoredCardPaymentMethod) XCTAssertTrue(paymentMethods.stored[1] is StoredCardPaymentMethod) XCTAssertEqual((paymentMethods.stored[1] as! StoredCardPaymentMethod).fundingSource!, .credit) // Test StoredCardPaymentMethod localization let storedCardPaymentMethod = paymentMethods.stored[1] as! StoredCardPaymentMethod let expectedLocalizationParameters = LocalizationParameters(tableName: "AdyenUIHost", keySeparator: nil) XCTAssertEqual(storedCardPaymentMethod.displayInformation, expectedStoredCardPaymentMethodDisplayInfo(method: storedCardPaymentMethod, localizationParameters: nil)) XCTAssertEqual(storedCardPaymentMethod.localizedDisplayInformation(using: expectedLocalizationParameters), expectedStoredCardPaymentMethodDisplayInfo(method: storedCardPaymentMethod, localizationParameters: expectedLocalizationParameters)) XCTAssertTrue(paymentMethods.stored[2] is StoredPayPalPaymentMethod) XCTAssertEqual((paymentMethods.stored[2] as! StoredPayPalPaymentMethod).displayInformation.subtitle, "[email protected]") XCTAssertTrue(paymentMethods.stored[3] is StoredRedirectPaymentMethod) XCTAssertTrue(paymentMethods.stored[4] is StoredBCMCPaymentMethod) XCTAssertTrue(paymentMethods.stored[5] is StoredCardPaymentMethod) XCTAssertEqual((paymentMethods.stored[5] as! StoredCardPaymentMethod).fundingSource!, .debit) XCTAssertTrue(paymentMethods.stored[6] is StoredBLIKPaymentMethod) XCTAssertEqual((paymentMethods.stored[6] as! StoredBLIKPaymentMethod).identifier, "8315892878479934") // Test StoredBCMCPaymentMethod localization let storedBCMCPaymentMethod = paymentMethods.stored[4] as! StoredBCMCPaymentMethod XCTAssertEqual(storedBCMCPaymentMethod.displayInformation, expectedBancontactCardDisplayInfo(method: storedBCMCPaymentMethod, localizationParameters: nil)) XCTAssertEqual(storedBCMCPaymentMethod.localizedDisplayInformation(using: expectedLocalizationParameters), expectedBancontactCardDisplayInfo(method: storedBCMCPaymentMethod, localizationParameters: expectedLocalizationParameters)) XCTAssertEqual(paymentMethods.stored[3].type, "unknown") XCTAssertEqual(paymentMethods.stored[3].name, "Stored Redirect Payment Method") let storedBancontact = paymentMethods.stored[4] as! StoredBCMCPaymentMethod XCTAssertEqual(storedBancontact.type, "bcmc") XCTAssertEqual(storedBancontact.brand, "bcmc") XCTAssertEqual(storedBancontact.name, "Maestro") XCTAssertEqual(storedBancontact.expiryYear, "2020") XCTAssertEqual(storedBancontact.expiryMonth, "10") XCTAssertEqual(storedBancontact.identifier, "8415736344108917") XCTAssertEqual(storedBancontact.holderName, "Checkout Shopper PlaceHolder") XCTAssertEqual(storedBancontact.supportedShopperInteractions, [.shopperPresent]) XCTAssertEqual(storedBancontact.lastFour, "4449") // Regular payment methods XCTAssertEqual(paymentMethods.regular.count, 16) XCTAssertTrue(paymentMethods.regular[0] is CardPaymentMethod) XCTAssertEqual((paymentMethods.regular[0] as! CardPaymentMethod).fundingSource!, .credit) XCTAssertTrue(paymentMethods.regular[1] is IssuerListPaymentMethod) XCTAssertTrue(paymentMethods.regular[2] is SEPADirectDebitPaymentMethod) XCTAssertTrue(paymentMethods.regular[3] is RedirectPaymentMethod) // Uknown redirect XCTAssertEqual(paymentMethods.regular[3].type, "unknown") XCTAssertEqual(paymentMethods.regular[3].name, "Redirect Payment Method") // Bancontact XCTAssertTrue(paymentMethods.regular[4] is BCMCPaymentMethod) XCTAssertEqual(paymentMethods.regular[4].type, "bcmc") XCTAssertEqual(paymentMethods.regular[4].name, "Bancontact card") // Apple Pay XCTAssertTrue(paymentMethods.regular[5] is ApplePayPaymentMethod) XCTAssertEqual(paymentMethods.regular[5].type, "applepay") XCTAssertEqual(paymentMethods.regular[5].name, "Apple Pay") // PayPal XCTAssertTrue(paymentMethods.regular[6] is RedirectPaymentMethod) XCTAssertEqual(paymentMethods.regular[6].type, "paypal") XCTAssertEqual(paymentMethods.regular[6].name, "PayPal") // GiroPay XCTAssertTrue(paymentMethods.regular[7] is RedirectPaymentMethod) XCTAssertEqual(paymentMethods.regular[7].type, "giropay") XCTAssertEqual(paymentMethods.regular[7].name, "GiroPay") // GiroPay with non optional details XCTAssertTrue(paymentMethods.regular[8] is RedirectPaymentMethod) XCTAssertEqual(paymentMethods.regular[8].type, "giropay") XCTAssertEqual(paymentMethods.regular[8].name, "GiroPay with non optional details") // Qiwi Wallet XCTAssertTrue(paymentMethods.regular[9] is QiwiWalletPaymentMethod) let qiwiMethod = paymentMethods.regular[9] as! QiwiWalletPaymentMethod XCTAssertEqual(qiwiMethod.type, "qiwiwallet") XCTAssertEqual(qiwiMethod.name, "Qiwi Wallet") XCTAssertEqual(qiwiMethod.phoneExtensions.count, 3) XCTAssertEqual(qiwiMethod.phoneExtensions[0].value, "+7") XCTAssertEqual(qiwiMethod.phoneExtensions[1].value, "+9955") XCTAssertEqual(qiwiMethod.phoneExtensions[2].value, "+507") XCTAssertEqual(qiwiMethod.phoneExtensions[0].countryCode, "RU") XCTAssertEqual(qiwiMethod.phoneExtensions[1].countryCode, "GE") XCTAssertEqual(qiwiMethod.phoneExtensions[2].countryCode, "PA") XCTAssertTrue(paymentMethods.regular[10] is WeChatPayPaymentMethod) XCTAssertEqual(paymentMethods.regular[10].type, "wechatpaySDK") XCTAssertEqual(paymentMethods.regular[10].name, "WeChat Pay") XCTAssertTrue(paymentMethods.regular[11] is CardPaymentMethod) XCTAssertEqual((paymentMethods.regular[11] as! CardPaymentMethod).fundingSource!, .debit) XCTAssertTrue(paymentMethods.regular[12] is MBWayPaymentMethod) XCTAssertEqual(paymentMethods.regular[12].name, "MB WAY") XCTAssertEqual(paymentMethods.regular[12].type, "mbway") XCTAssertTrue(paymentMethods.regular[13] is BLIKPaymentMethod) XCTAssertEqual(paymentMethods.regular[13].name, "Blik") XCTAssertEqual(paymentMethods.regular[13].type, "blik") XCTAssertTrue(paymentMethods.regular[14] is DokuPaymentMethod) XCTAssertEqual(paymentMethods.regular[14].name, "DOKU wallet") XCTAssertEqual(paymentMethods.regular[14].type, "doku_wallet") XCTAssertTrue(paymentMethods.regular[15] is GiftCardPaymentMethod) XCTAssertEqual(paymentMethods.regular[15].name, "Generic GiftCard") XCTAssertEqual(paymentMethods.regular[15].type, "giftcard") } // MARK: - Card func testDecodingCreditCardPaymentMethod() throws { let paymentMethod = try Coder.decode(creditCardDictionary) as CardPaymentMethod XCTAssertEqual(paymentMethod.type, "scheme") XCTAssertEqual(paymentMethod.name, "Credit Card") XCTAssertEqual(paymentMethod.fundingSource!, .credit) XCTAssertEqual(paymentMethod.brands, ["mc", "visa", "amex"]) } func testDecodingDeditCardPaymentMethod() throws { let paymentMethod = try Coder.decode(debitCardDictionary) as CardPaymentMethod XCTAssertEqual(paymentMethod.type, "scheme") XCTAssertEqual(paymentMethod.name, "Credit Card") XCTAssertEqual(paymentMethod.fundingSource!, .debit) XCTAssertEqual(paymentMethod.brands, ["mc", "visa", "amex"]) } func testDecodingBCMCCardPaymentMethod() throws { let paymentMethod = try Coder.decode(bcmcCardDictionary) as CardPaymentMethod XCTAssertEqual(paymentMethod.type, "bcmc") XCTAssertEqual(paymentMethod.name, "Bancontact card") XCTAssertEqual(paymentMethod.brands, []) } func testDecodingCardPaymentMethodWithoutBrands() throws { var dictionary = creditCardDictionary dictionary.removeValue(forKey: "brands") let paymentMethod = try Coder.decode(dictionary) as CardPaymentMethod XCTAssertEqual(paymentMethod.type, "scheme") XCTAssertEqual(paymentMethod.name, "Credit Card") XCTAssertTrue(paymentMethod.brands.isEmpty) } func testDecodingStoredCreditCardPaymentMethod() throws { let paymentMethod = try Coder.decode(storedCreditCardDictionary) as StoredCardPaymentMethod let expectedLocalizationParameters = LocalizationParameters(tableName: "AdyenUIHost", keySeparator: nil) XCTAssertEqual(paymentMethod.type, "scheme") XCTAssertEqual(paymentMethod.name, "VISA") XCTAssertEqual(paymentMethod.brand, "visa") XCTAssertEqual(paymentMethod.lastFour, "1111") XCTAssertEqual(paymentMethod.expiryMonth, "08") XCTAssertEqual(paymentMethod.expiryYear, "2018") XCTAssertEqual(paymentMethod.holderName, "test") XCTAssertEqual(paymentMethod.fundingSource, .credit) XCTAssertEqual(paymentMethod.supportedShopperInteractions, [.shopperPresent, .shopperNotPresent]) XCTAssertEqual(paymentMethod.displayInformation, expectedStoredCardPaymentMethodDisplayInfo(method: paymentMethod, localizationParameters: nil)) XCTAssertEqual(paymentMethod.localizedDisplayInformation(using: expectedLocalizationParameters), expectedStoredCardPaymentMethodDisplayInfo(method: paymentMethod, localizationParameters: expectedLocalizationParameters)) } func testDecodingStoredDeditCardPaymentMethod() throws { let paymentMethod = try Coder.decode(storedDeditCardDictionary) as StoredCardPaymentMethod let expectedLocalizationParameters = LocalizationParameters(tableName: "AdyenUIHost", keySeparator: nil) XCTAssertEqual(paymentMethod.type, "scheme") XCTAssertEqual(paymentMethod.name, "VISA") XCTAssertEqual(paymentMethod.brand, "visa") XCTAssertEqual(paymentMethod.lastFour, "1111") XCTAssertEqual(paymentMethod.expiryMonth, "08") XCTAssertEqual(paymentMethod.expiryYear, "2018") XCTAssertEqual(paymentMethod.holderName, "test") XCTAssertEqual(paymentMethod.fundingSource, .debit) XCTAssertEqual(paymentMethod.supportedShopperInteractions, [.shopperPresent, .shopperNotPresent]) XCTAssertEqual(paymentMethod.displayInformation, expectedStoredCardPaymentMethodDisplayInfo(method: paymentMethod, localizationParameters: nil)) XCTAssertEqual(paymentMethod.localizedDisplayInformation(using: expectedLocalizationParameters), expectedStoredCardPaymentMethodDisplayInfo(method: paymentMethod, localizationParameters: expectedLocalizationParameters)) } public func expectedStoredCardPaymentMethodDisplayInfo(method: StoredCardPaymentMethod, localizationParameters: LocalizationParameters?) -> DisplayInformation { let expireDate = method.expiryMonth + "/" + method.expiryYear.suffix(2) return DisplayInformation(title: "••••\u{00a0}" + method.lastFour, subtitle: ADYLocalizedString("adyen.card.stored.expires", localizationParameters, expireDate), logoName: method.brand) } // MARK: - Issuer List func testDecodingIssuerListPaymentMethod() throws { let paymentMethod = try Coder.decode(issuerListDictionary) as IssuerListPaymentMethod XCTAssertEqual(paymentMethod.type, "ideal") XCTAssertEqual(paymentMethod.name, "iDEAL") XCTAssertEqual(paymentMethod.issuers.count, 3) XCTAssertEqual(paymentMethod.issuers[0].identifier, "1121") XCTAssertEqual(paymentMethod.issuers[0].name, "Test Issuer 1") XCTAssertEqual(paymentMethod.issuers[1].identifier, "1154") XCTAssertEqual(paymentMethod.issuers[1].name, "Test Issuer 2") XCTAssertEqual(paymentMethod.issuers[2].identifier, "1153") XCTAssertEqual(paymentMethod.issuers[2].name, "Test Issuer 3") } func testDecodingIssuerListPaymentMethodWithoutDetailsObject() throws { let paymentMethod = try Coder.decode(issuerListDictionaryWithoutDetailsObject) as IssuerListPaymentMethod XCTAssertEqual(paymentMethod.type, "ideal_100") XCTAssertEqual(paymentMethod.name, "iDEAL_100") XCTAssertEqual(paymentMethod.issuers.count, 3) XCTAssertEqual(paymentMethod.issuers[0].identifier, "1121") XCTAssertEqual(paymentMethod.issuers[0].name, "Test Issuer 1") XCTAssertEqual(paymentMethod.issuers[1].identifier, "1154") XCTAssertEqual(paymentMethod.issuers[1].name, "Test Issuer 2") XCTAssertEqual(paymentMethod.issuers[2].identifier, "1153") XCTAssertEqual(paymentMethod.issuers[2].name, "Test Issuer 3") } // MARK: - SEPA Direct Debit let sepaDirectDebitDictionary = [ "type": "sepadirectdebit", "name": "SEPA Direct Debit" ] as [String: Any] func testDecodingSEPADirectDebitPaymentMethod() throws { let paymentMethod = try Coder.decode(sepaDirectDebitDictionary) as SEPADirectDebitPaymentMethod XCTAssertEqual(paymentMethod.type, "sepadirectdebit") XCTAssertEqual(paymentMethod.name, "SEPA Direct Debit") } // MARK: - Stored PayPal func testDecodingPayPalPaymentMethod() throws { let paymentMethod = try Coder.decode(storedPayPalDictionary) as StoredPayPalPaymentMethod XCTAssertEqual(paymentMethod.type, "paypal") XCTAssertEqual(paymentMethod.identifier, "9314881977134903") XCTAssertEqual(paymentMethod.name, "PayPal") XCTAssertEqual(paymentMethod.emailAddress, "[email protected]") XCTAssertEqual(paymentMethod.supportedShopperInteractions, [.shopperPresent, .shopperNotPresent]) } // MARK: - Apple Pay func testDecodingApplePayPaymentMethod() throws { let paymentMethod = try Coder.decode(applePayDictionary) as ApplePayPaymentMethod XCTAssertEqual(paymentMethod.type, "applepay") XCTAssertEqual(paymentMethod.name, "Apple Pay") } // MARK: - Bancontact func testDecodingBancontactPaymentMethod() throws { let paymentMethod = try Coder.decode(bcmcCardDictionary) as BCMCPaymentMethod XCTAssertEqual(paymentMethod.type, "bcmc") XCTAssertEqual(paymentMethod.name, "Bancontact card") } // MARK: - GiroPay func testDecodingGiropayPaymentMethod() throws { let paymentMethod = try Coder.decode(giroPayDictionaryWithOptionalDetails) as RedirectPaymentMethod XCTAssertEqual(paymentMethod.type, "giropay") XCTAssertEqual(paymentMethod.name, "GiroPay") } // MARK: - Stored Bancontact func testDecodingStoredBancontactPaymentMethod() throws { let paymentMethod = try Coder.decode(storedBcmcDictionary) as StoredBCMCPaymentMethod let expectedLocalizationParameters = LocalizationParameters(tableName: "AdyenUIHost", keySeparator: nil) XCTAssertEqual(paymentMethod.type, "bcmc") XCTAssertEqual(paymentMethod.brand, "bcmc") XCTAssertEqual(paymentMethod.name, "Maestro") XCTAssertEqual(paymentMethod.expiryYear, "2020") XCTAssertEqual(paymentMethod.expiryMonth, "10") XCTAssertEqual(paymentMethod.identifier, "8415736344108917") XCTAssertEqual(paymentMethod.holderName, "Checkout Shopper PlaceHolder") XCTAssertEqual(paymentMethod.supportedShopperInteractions, [.shopperPresent]) XCTAssertEqual(paymentMethod.lastFour, "4449") let expectedDisplayInfo = expectedBancontactCardDisplayInfo(method: paymentMethod, localizationParameters: nil) XCTAssertEqual(paymentMethod.displayInformation, expectedDisplayInfo) XCTAssertEqual(paymentMethod.localizedDisplayInformation(using: expectedLocalizationParameters), expectedBancontactCardDisplayInfo(method: paymentMethod, localizationParameters: expectedLocalizationParameters)) } // MARK: - MBWay func testDecodingMBWayPaymentMethod() throws { let paymentMethod = try Coder.decode(mbway) as MBWayPaymentMethod XCTAssertEqual(paymentMethod.type, "mbway") XCTAssertEqual(paymentMethod.name, "MB WAY") } // MARK: - Doku wallet func testDecodingDokuWalletPaymentMethod() throws { let paymentMethod = try Coder.decode(dokuWallet) as DokuPaymentMethod XCTAssertEqual(paymentMethod.type, "doku_wallet") XCTAssertEqual(paymentMethod.name, "DOKU wallet") } public func expectedBancontactCardDisplayInfo(method: StoredBCMCPaymentMethod, localizationParameters: LocalizationParameters?) -> DisplayInformation { let expireDate = method.expiryMonth + "/" + method.expiryYear.suffix(2) return DisplayInformation(title: "••••\u{00a0}" + method.lastFour, subtitle: ADYLocalizedString("adyen.card.stored.expires", localizationParameters, expireDate), logoName: method.brand) } } internal extension Coder { static func decode<T: Decodable>(_ dictionary: [String: Any]) throws -> T { let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) return try decode(data) } }
50.178841
227
0.700266
71e1911ce19643785848ad9923a8f94fe0ebc33a
212
let b : [UInt8] = [0x54,0x68,0x65,0x20,0x71,0x75,0x69,0x63, 0x6b,0x20,0x62,0x72,0x6f,0x77,0x6e,0x20, 0x66,0x6f,0x78,0x2e] var md5s1 : Digest = Digest(algorithm:.MD5) md5s1.update(b) let digests1 = md5s1.final()
26.5
43
0.726415
d6f94a083a54651d51f1f53af91dfbb1b58b3dab
781
// // NSTextAttachment.swift // // Created by Sereivoan Yong on 11/23/20. // #if canImport(UIKit) import UIKit extension NSTextAttachment { public convenience init(image: UIImage?) { self.init() self.image = image } } extension NSAttributedString { @inlinable public static func + (lhs: NSAttributedString, rhs: NSTextAttachment) -> NSMutableAttributedString { return lhs + NSAttributedString(attachment: rhs) } public static func attachment(data: Data?, uti: String?) -> NSAttributedString { return NSAttributedString(attachment: NSTextAttachment(data: data, ofType: uti)) } public static func attachment(image: UIImage?) -> NSAttributedString { return NSAttributedString(attachment: NSTextAttachment(image: image)) } } #endif
23.666667
113
0.722151
89df4f558f098a33d17ad3a7d9e5044f39af08f6
612
@objc enum BackgroundFetchTaskFrameworkType: Int { case none case full func create() { switch self { case .none: return case .full: FrameworkHelper.createFramework() } } } extension BackgroundFetchTaskFrameworkType: Equatable { static func ==(lhs: BackgroundFetchTaskFrameworkType, rhs: BackgroundFetchTaskFrameworkType) -> Bool { return lhs.rawValue == rhs.rawValue } } extension BackgroundFetchTaskFrameworkType: Comparable { static func <(lhs: BackgroundFetchTaskFrameworkType, rhs: BackgroundFetchTaskFrameworkType) -> Bool { return lhs.rawValue < rhs.rawValue } }
25.5
104
0.745098
76f7865c39a3629ba957b4d9d524afd3a916839a
1,384
// // PinchVC.swift // PinchVC // // Created by Jacob Trentini on 8/14/21. // import UIKit class PinchVC: UIViewController { @IBOutlet weak var velocityLabel: UILabel! @IBOutlet weak var scaleLabel: UILabel! @IBOutlet weak var stateLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() let gesture: UIPinchGestureRecognizer = { let gesture = UIPinchGestureRecognizer(target: self, action: #selector(didPinch(_:))) return gesture }() view.addGestureRecognizer(gesture) // Do any additional setup after loading the view. } @objc private func didPinch(_ gesture: UIPinchGestureRecognizer) { velocityLabel.text = "Velocity = \(gesture.velocity)" scaleLabel.text = "Scale = \(gesture.scale)" switch gesture.state { case .began: stateLabel.text = "State = Began" case .possible: stateLabel.text = "State = Possible" case .changed: stateLabel.text = "State = Changed" case .ended: stateLabel.text = "State = Ended" case .cancelled: stateLabel.text = "State = Cancelled" case .failed: stateLabel.text = "State = Failed" @unknown default: stateLabel.text = "State = @unknown default!" } } }
30.086957
97
0.59104
d77af8329f8d8d61a66d3a8a30177e4e008118fe
4,739
// // HallOfFame.swift // RedCatTicTacToe // // Created by Markus Pfeifer on 09.05.21. // import SwiftUI import RedCat struct HallOfFame : View { @EnvironmentObject var store : CombineStore<AppState, AppAction> var body : some View { GeometryReader {geo in VStack(spacing: 0) { Text("HALL OF FAME") .font(.largeTitle) .padding() .frame(width: geo.size.width, height: 0.15 * geo.size.height) Divider().padding(.horizontal) items .frame(width: geo.size.width, height: 0.85 * geo.size.height) } } } var items : some View { HStack(spacing: 0) { ForEach(0..<oKeys.count + 1) {colIdx in VStack(spacing: 0) { ForEach(0..<xKeys.count + 1) {rowIdx in ZStack { if colIdx == 0 && rowIdx == 0 { angle.scaledToFit() } else { cellBackground } extendedCell(rowIdx, colIdx) }.frame(minWidth: 100, minHeight: 100) } } } } .padding(30) } @ViewBuilder func extendedCell(_ rowIdx: Int, _ colIdx: Int) -> some View { // swiftlint:disable identifier_name switch (rowIdx, colIdx) { case (0, 0): cornerView case (0, let o): Text(oKeys[o - 1].rawPlayer.rawValue) case (let x, 0): Text(xKeys[x - 1].rawPlayer.rawValue) default: cell(key1: xKeys[rowIdx - 1], key2: oKeys[colIdx - 1]) } // swiftlint:enable identifier_name } var angle : some View { GeometryReader {geo in let rect = geo.frame(in: .local).insetBy(dx: 5, dy: 5) Path {path in path.move(to: CGPoint(x: rect.minX, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) }.stroke(lineWidth: 1) } } var cellBackground : some View { RoundedRectangle(cornerRadius: 10) .foregroundColor(.white) .opacity(0.65) .scaledToFit() .padding(.all, 3) .shadow(radius: 20) } var cornerView : some View { GeometryReader {geo in let textRect = geo.frame(in: .local) Text("X").font(.title).position(textRect.bottom) Text("O").font(.title).position(textRect.right) }.scaledToFit() } func cell(key1: GameStatsKey, key2: GameStatsKey) -> some View { VStack { Text("wins: \(wins(key1: key1, key2: key2))") Text("losses: \(losses(key1: key1, key2: key2))") Text("ties: \(ties(key1: key1, key2: key2))") } } func wins(key1: GameStatsKey, key2: GameStatsKey) -> Int { store.state[gameStatsFor: key1].wins[key2] ?? 0 } func losses(key1: GameStatsKey, key2: GameStatsKey) -> Int { store.state[gameStatsFor: key1].losses[key2] ?? 0 } func ties(key1: GameStatsKey, key2: GameStatsKey) -> Int { store.state[gameStatsFor: key1].ties[key2] ?? 0 } var xKeys : [GameStatsKey] { RawPlayer.allCases.map {raw in GameStatsKey(player: .x, rawPlayer: raw) } } var oKeys : [GameStatsKey] { RawPlayer.allCases.map {raw in GameStatsKey(player: .o, rawPlayer: raw) } } } extension CGRect { var bottom : CGPoint { CGPoint(x: 0.5 * minX + 0.5 * maxX, y: 0.2 * minY + 0.8 * maxY) } var right : CGPoint { CGPoint(x: 0.2 * minX + 0.8 * maxX, y: 0.5 * minY + 0.5 * maxY) } } struct HallOfFamePreview : PreviewProvider { static var previews: some View { HallOfFame() .environmentObject(AppState.makeStore()) } }
27.71345
68
0.436379
203211de9eb7f408d29d4c1b1c2ad7f728312d0f
10,102
// // ViewFactory.swift // // // Created by Enes Karaosman on 27.11.2020. // import SwiftUI internal struct ViewFactory: PresentableProtocol { private let material: ViewMaterial private let date: Date? init(material: ViewMaterial) { self.material = material self.date = nil } init(material: ViewMaterial, date: Date?) { self.material = material self.date = date } func parseFont() -> Font { var font: Font if let fontSize = material.properties?.fontSize { let fontName = material.properties?.fontName ?? "system" let fontDesign = Font.Design.pick[material.properties?.fontDesign ?? "default"] ?? Font.Design.default let fontWight = Font.Weight.pick[material.properties?.fontWeight ?? "regular"] ?? Font.Weight.regular if fontName == "system" { font = Font.system(size: CGFloat(fontSize), weight: fontWight, design: fontDesign) } else { font = Font.custom(fontName, size: CGFloat(fontSize)) } } else { let fontHashValue = material.properties?.font ?? "body" font = Font.pick[fontHashValue] ?? Font.body } if let fontStyle = material.properties?.fontStyle { let fontStyleSegments = fontStyle.components(separatedBy: " ") for style in fontStyleSegments { switch style { case "bold": font = font.bold() case "italic": font = font.italic() case "smallCaps": font = font.smallCaps() case "lowercaseSmallCaps": font = font.lowercaseSmallCaps() case "uppercaseSmallCaps": font = font.uppercaseSmallCaps() case "monospacedDigit": font = font.monospacedDigit() default: break } } } return font } // MARK: - ScrollView @ViewBuilder func scrollView() -> some View { if let subviews = material.subviews { let axisKey = material.properties?.axis ?? "vertical" let axis = Axis.Set.pick[axisKey] ?? .vertical let showsIndicators = material.properties?.showsIndicators ?? true ScrollView(axis, showsIndicators: showsIndicators) { AxisBasedStack(axis: axis) { ForEach(subviews) { subview in ViewFactory(material: subview).toPresentable() } } } } else { Text("Please Add Subview for ScrollView") } } // MARK: - List @ViewBuilder func list() -> some View { if let subviews = material.subviews { List(subviews) { ViewFactory(material: $0).toPresentable() } } else { Text("Please Add Subview for List") } } // MARK: - VStack @ViewBuilder func vstack() -> some View { if let subviews = material.subviews { let spacing = material.properties?.spacing.toCGFloat() ?? 0 let horizontalAlignmentKey = material.properties?.horizontalAlignment ?? "center" let horizontalAlignment = HorizontalAlignment.pick[horizontalAlignmentKey] ?? .center VStack(alignment: horizontalAlignment, spacing: spacing) { ForEach(subviews) { ViewFactory(material: $0).toPresentable() } } } else { Text("Please Add Subview for VStack") } } // MARK: - HStack @ViewBuilder func hstack() -> some View { if let subviews = material.subviews { let spacing = material.properties?.spacing.toCGFloat() ?? 0 let verticalAlignmentKey = material.properties?.verticalAlignment ?? "center" let verticalAlignment = VerticalAlignment.pick[verticalAlignmentKey] ?? .center HStack(alignment: verticalAlignment, spacing: spacing) { ForEach(subviews) { ViewFactory(material: $0).toPresentable() } } } else { Text("Please Add Subview for HStack") } } // MARK: - ZStack @ViewBuilder func zstack() -> some View { if let subviews = material.subviews { ZStack { ForEach(subviews) { ViewFactory(material: $0).toPresentable() } } } else { Text("Please Add Subview for ZStack") } } // MARK: - Text @ViewBuilder func text() -> some View { let font = parseFont() let fontWeightHashValue = material.properties?.fontWeight ?? "regular" let lineLimit = material.properties?.lineLimit let fontWeight = Font.Weight.pick[fontWeightHashValue] Text(material.values?.text ?? "") .font(font) .fontWeight(fontWeight) .conditionalModifier(lineLimit != nil, { $0.lineLimit(lineLimit) }) } // MARK: - Timer @ViewBuilder func timer() -> some View { let font = parseFont() let fontWeightHashValue = material.properties?.fontWeight ?? "regular" let fontWeight = Font.Weight.pick[fontWeightHashValue] Text(date ?? Date(), style: Text.DateStyle.pick[material.values?.dateStyle ?? "timer"] ?? .timer) .font(font) .fontWeight(fontWeight) } // MARK: - Image @ViewBuilder func image() -> some View { if let systemIconName = material.values?.systemIconName { Image(systemName: systemIconName) .resizable() .conditionalModifier(material.properties?.scaleMode == "fill", { $0.scaledToFill() }, { $0.scaledToFit() }) } else if let localIconName = material.values?.localImageName { Image(localIconName) .resizable() .conditionalModifier(material.properties?.scaleMode == "fill", { $0.scaledToFill() }, { $0.scaledToFit() }) } else if let remoteUrl = material.values?.imageUrl { NetworkImage(url: URL(string: remoteUrl), mode: material.properties?.scaleMode) } else { Text("Image value could not read") } } // MARK: - Spacer @ViewBuilder func spacer() -> some View { let minLength = material.properties?.minLength.toCGFloat() Spacer(minLength: minLength) } // MARK: - Chart @ViewBuilder func chart() -> some View { Chart(style: Chart.Style(rawValue: material.properties?.chartStyle ?? ""), data: material.values?.chartData, backgroundColor: material.properties?.backgroundColor.toColor(), foregroundColor: material.properties?.foregroundColor.toColor(), paddingTopPercentage: material.properties?.chartLineChartPaddingTopPercentage, paddingBottomPercentage: material.properties?.chartLineChartPaddingBottomPercentage) } // MARK: - Color @ViewBuilder func color() -> some View { material.values?.hex.toColor() .ignoresSafeArea() } // MARK: - LinearGradient @ViewBuilder func lineargradient() -> some View { let gradient = material.values?.gradient.toGradient() ?? Gradient(colors: [Color.gray, Color.black]) let direction = material.values?.direction.toDirection() ?? (from: .top, to: .bottom) LinearGradient(gradient: gradient, startPoint: direction.from, endPoint: direction.to) .ignoresSafeArea() } // MARK: - Rectangle @ViewBuilder func rectangle() -> some View { Rectangle().fill(material.values?.fill.toColor() ?? .primary) } // MARK: - Circle @ViewBuilder func circle() -> some View { Circle().fill(material.values?.fill.toColor() ?? .primary) } @ViewBuilder func buildDefault() -> some View { switch material.type { case .ScrollView: scrollView() case .List: list() case .VStack: vstack() case .HStack: hstack() case .ZStack: zstack() case .Text: text() case .Timer: timer() case .Image: image() case .Spacer: spacer() case .Chart: chart() case .Color: color() case .LinearGradient: lineargradient() case .Rectangle: rectangle() case .Divider: Divider() case .Circle: circle() default: EmptyView() } } @ViewBuilder func toPresentable() -> some View { let prop = material.properties let uiComponent = buildDefault().embedInAnyView() uiComponent .modifier(ModifierFactory.OpacityModifier(opacity: prop?.opacity)) .modifier(ModifierFactory.CornerRadiusModifier(cornerRadius: prop?.cornerRadius)) .modifier(ModifierFactory.PaddingModifier(padding: prop?.padding.toPaddingEdgeInsets())) .modifier(ModifierFactory.ForegroundModifier(foregroundColor: prop?.foregroundColor.toColor())) .modifier(ModifierFactory.BackgroundModifier(backgroundColor: prop?.backgroundColor.toColor())) .modifier(ModifierFactory.BorderModifier( borderColor: prop?.borderColor.toColor(), borderWidth: prop?.borderWidth.toCGFloat() )) .modifier(ModifierFactory.ShadowModifier( shadow: prop?.shadow.toShadow() )) .modifier(ModifierFactory.FrameModifier( width: prop?.width.toCGFloat(), height: prop?.height.toCGFloat(), clipContent: prop?.clipContent, alignment: Alignment.pick[prop?.alignment ?? "center"] ?? .center )) } }
35.198606
114
0.56375
145f5471143850d43a49cca4c7f717d69bd886f2
1,009
/* Given two integers n and k, return all possible combinations of k numbers out of the range [1, n]. You may return the answer in any order. Example 1: Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] Example 2: Input: n = 1, k = 1 Output: [[1]] Constraints: 1 <= n <= 20 1 <= k <= n */ class Solution { func combine(_ n: Int, _ k: Int) -> [[Int]] { guard k <= n else { return [[Int]]() } var result = [[Int]]() var combination = [Int]() combine(n, k,1, &combination, &result) return result } func combine(_ n: Int, _ k: Int,_ start: Int, _ combination: inout [Int], _ result: inout [[Int]]) { if combination.count == k { result.append(combination) return } if start > n { return } for i in start...n { combination.append(i) combine(n, k, i + 1, &combination, &result) combination.removeLast() } } }
19.403846
104
0.509415
f4d535e96a3836ed14b619554cbaed5bffb86b3f
3,209
//: Playground - noun: a place where people can play /* If you set the usesSignificantDigits property to true, you can configure NSNumberFormatter to display significant digits using the minimumSignificantDigits and maximumSignificantDigits properties. If usesSignificantDigits is false, these properties are ignored. Otherwise, you can configure the minimum and maximum number of integer and fraction digits, or the numbers before and after the decimal separator, respectively, using the minimumIntegerDigits, maximumIntegerDigits, minimumFractionDigits, and maximumFractionDigits properties. */ import UIKit let calculator_formatter = NumberFormatter() calculator_formatter.numberStyle = NumberFormatter.Style.decimal //calculator_formatter.maximumSignificantDigits = 8 calculator_formatter.maximumFractionDigits = 7 //calculator_formatter.maximumIntegerDigits = 6 calculator_formatter.maximum = 9999 print(calculator_formatter.string(from: 568988376078.92) ?? 67) print(calculator_formatter.string(from: 0.568988376078) as Any) //provide default value) let formatter_currency = NumberFormatter() formatter_currency.numberStyle = NumberFormatter.Style.currency formatter_currency.paddingPosition = .afterPrefix formatter_currency.paddingCharacter = "❦"//if string pulls off first char formatter_currency.formatWidth = 17 print(formatter_currency.string(from: 568378.92) ?? 78) //provide default value) let formatter_currency2 = NumberFormatter() formatter_currency2.numberStyle = NumberFormatter.Style.currencyAccounting print(formatter_currency2.string(from: 568378.92)!) //(force unwrap) let formatter_currency3 = NumberFormatter() formatter_currency3.numberStyle = NumberFormatter.Style.currencyISOCode formatter_currency3.locale = Locale.autoupdatingCurrent print(formatter_currency3.string(from: 568378.92) as Any) //cast as Any let formatter_currency4 = NumberFormatter() formatter_currency4.numberStyle = NumberFormatter.Style.currencyPlural print(formatter_currency4.string(from: 568378.92) as Any) //cast as Any let formatter_decimal = NumberFormatter() formatter_decimal.numberStyle = NumberFormatter.Style.decimal print(formatter_decimal.string(from: 568378.0) as Any) //cast as Any let formatter_ordinal = NumberFormatter() formatter_ordinal.numberStyle = NumberFormatter.Style.ordinal print(formatter_ordinal.string(from: 3)!) let formatter_percent = NumberFormatter() formatter_percent.numberStyle = NumberFormatter.Style.percent formatter_percent.minimumFractionDigits = 7 formatter_percent.minimumIntegerDigits = 12 print(formatter_percent.string(from: 0.99)!) let formatter_scientific = NumberFormatter() formatter_scientific.numberStyle = NumberFormatter.Style.scientific print(formatter_scientific.string(from: 0.99)!) let formatter_none = NumberFormatter() formatter_none.numberStyle = NumberFormatter.Style.none print(formatter_none.string(from: 0.99)!) print(formatter_none.string(from: 2.38)!) print(formatter_none.string(from: 2.6)!) let formatter_spell = NumberFormatter() formatter_spell.numberStyle = NumberFormatter.Style.spellOut print(formatter_spell.string(from: 0.99)!) print(formatter_spell.string(from: 2.38)!) print(formatter_spell.string(from: 2.6)!)
41.675325
276
0.832035
61cf6ba280d3893e1bba4e01b3393708e083f603
583
// // HMSAudioSettigs.swift // hmssdk_flutter // // Copyright © 2021 100ms. All rights reserved. // import Foundation import HMSSDK class HMSVideoSettingExtension { static func toDictionary(videoSettings:HMSVideoSettings)-> Dictionary<String,Any?>{ var dict:Dictionary<String, Any?> = [:] dict["bit_rate"]=videoSettings.bitRate dict["codec"] = videoSettings.codec dict["frame_rate"] = videoSettings.frameRate dict["width"] = videoSettings.width dict["height"] = videoSettings.height return dict } }
24.291667
87
0.656947
0a111562faeacbb0a78d309b9cba38f8d0044539
1,810
// // PDFThumbnailView.swift // Pods // // Created by Chris Anderson on 5/6/16. // // import UIKit internal class PDFThumbnailView: UIView { let imageView: UIImageView override init(frame: CGRect) { imageView = UIImageView() imageView.autoresizesSubviews = false imageView.isUserInteractionEnabled = false imageView.autoresizingMask = UIView.AutoresizingMask() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit super.init(frame: frame) imageView.frame = frame addSubview(imageView) autoresizesSubviews = false isUserInteractionEnabled = false contentMode = .redraw autoresizingMask = UIView.AutoresizingMask() backgroundColor = UIColor.clear var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[image]|", options: .alignAllLastBaseline, metrics: nil, views: [ "superview": self, "image": imageView ]) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[image]|", options: .alignAllLastBaseline, metrics: nil, views: [ "superview": self, "image": imageView ])) addConstraints(constraints) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init(frame: CGRect, document: PDFDocument, page: Int) { self.init(frame: frame) showImage(document, page: page) } func showImage(_ document: PDFDocument, page: Int) { imageView.image = nil PDFQueue.sharedQueue.fetchPage(document, page: page, size: frame.size) { (thumbnail) in self.imageView.image = thumbnail.image } } }
32.909091
198
0.659669
2335f6e67d392aefc577d2d6f0d18a5ac0ab8cce
394
// // ViewController.swift // InAppLocalizationDemo // // Created by janlionly on 2020/7/21. // Copyright © 2020 janlionly. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var helloLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() helloLabel.text = NSLocalizedString("Hello", comment: "") } }
18.761905
65
0.664975
7ac2f7283be359abf50028a0f4332d8eff29bb6b
495
// // ContactCell.swift // AddressBook // // Created by Harish Chopra on 2017-11-16. // Copyright © 2017 Harish Chopra. All rights reserved. // import UIKit class ContactCell: UITableViewCell { @IBOutlet weak var nameLbl:UILabel! @IBOutlet weak var phoneLbl:UILabel! func updtateCellUI(contact:Contact) { let fullName = "\(contact.title) \(contact.firstName) \(contact.lastName)" nameLbl.text = fullName phoneLbl.text = contact.phone } }
21.521739
82
0.664646
d93e06ad72daa8df7d275e85779f43ca99b888c5
1,189
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 struct FlutterResetPasswordRequest { var username: String var options: Dictionary<String, Any>? = [:] init(dict: NSMutableDictionary){ self.username = dict["username"] as! String self.options = dict["options"] as! Dictionary<String, Any>? } static func validate(dict: NSMutableDictionary) throws { let validationErrorMessage = "ResetPassword Request malformed." if (dict["username"] == nil && dict["options"] == nil) { throw AmplifyFlutterValidationException(errorDescription: validationErrorMessage, recoverySuggestion: "username is missing.") } } }
37.15625
131
0.727502
e9430e8548518b9c4e7179a53f9f41bf129a93c2
4,266
import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let userDefaults = NSUserDefaults.standardUserDefaults() if userDefaults.integerForKey("accuracy") == 0 { userDefaults.setInteger(63, forKey: "accuracy") } if userDefaults.integerForKey("distance") == 0 { userDefaults.setInteger(28, forKey: "distance") } if userDefaults.integerForKey("refreshRate") == 0 { userDefaults.setInteger(15, forKey: "refreshRate") } let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) var viewController = storyboard.instantiateViewControllerWithIdentifier("main") if NSUserDefaults.standardUserDefaults().stringForKey("username") == nil { viewController = storyboard.instantiateViewControllerWithIdentifier("login") } self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.rootViewController = viewController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { } func applicationWillEnterForeground(application: UIApplication) { } func applicationDidBecomeActive(application: UIApplication) { } func applicationWillTerminate(application: UIApplication) { self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager .defaultManager() .URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource("occupyhdm", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator( managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory .URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType( NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext( concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
35.55
98
0.661744
e46a494113d26ae08ccefa2ad9839b8d118c7727
20,669
// // NaverMapController.swift // naver_map_plugin // // Created by Maximilian on 2020/08/19. // import UIKit import Flutter import NMapsMap protocol NaverMapOptionSink { func setIndoorEnable(_ indoorEnable: Bool) func setNightModeEnable(_ nightModeEnable: Bool) func setLiteModeEnable(_ liteModeEnable: Bool) func setMapType(_ typeIndex: Int) func setBuildingHeight(_ buildingHeight: Float) func setSymbolScale(_ symbolScale: CGFloat) func setSymbolPerspectiveRatio(_ symbolPerspectiveRatio: CGFloat) func setActiveLayers(_ activeLayers: Array<Any>) func setContentPadding(_ paddingData: Array<CGFloat>) func setMaxZoom(_ maxZoom: Double) func setMinZoom(_ minZoom: Double) func setRotationGestureEnable(_ rotationGestureEnable: Bool) func setScrollGestureEnable(_ scrollGestureEnable: Bool) func setTiltGestureEnable(_ tiltGestureEnable: Bool) func setZoomGestureEnable(_ zoomGestureEnable: Bool) func setLocationTrackingMode(_ locationTrackingMode: UInt) func setLocationButtonEnable(_ locationButtonEnable: Bool) } class NaverMapController: NSObject, FlutterPlatformView, NaverMapOptionSink, NMFMapViewTouchDelegate, NMFMapViewCameraDelegate, NMFAuthManagerDelegate { var mapView : NMFMapView var naverMap : NMFNaverMapView let viewId : Int64 var markersController: NaverMarkersController? var pathController: NaverPathController? var circleController: NaverCircleController? var polygonController: NaverPolygonController? var channel : FlutterMethodChannel? var registrar : FlutterPluginRegistrar? init(viewId: Int64, frame: CGRect, registrar: FlutterPluginRegistrar, argument: NSDictionary?) { self.viewId = viewId self.registrar = registrar // need more http connections during getting map tile (default : 4) URLSession.shared.configuration.httpMaximumConnectionsPerHost = 8 // property set naverMap = NMFNaverMapView(frame: frame) mapView = naverMap.mapView channel = FlutterMethodChannel(name: "naver_map_plugin_\(viewId)", binaryMessenger: registrar.messenger()) super.init() markersController = NaverMarkersController(naverMap: naverMap, registrar: registrar, touchHandler: overlayTouchHandler(overlay:)) pathController = NaverPathController(naverMap: naverMap, registrar: registrar, touchHandler: overlayTouchHandler(overlay:)) circleController = NaverCircleController(naverMap: naverMap, touchHandler: overlayTouchHandler(overlay:)) polygonController = NaverPolygonController(naverMap: naverMap, touchHandler: overlayTouchHandler(overlay:)) channel?.setMethodCallHandler(handle(call:result:)) // map view 설정 NMFAuthManager.shared().delegate = self as NMFAuthManagerDelegate // for debug mapView.touchDelegate = self mapView.addCameraDelegate(delegate: self) if let arg = argument { if let initialPositionData = arg["initialCameraPosition"] { if initialPositionData is NSDictionary { mapView.moveCamera(NMFCameraUpdate(position: toCameraPosition(json: initialPositionData))) } } if let options = arg["options"] as? NSDictionary { interpretMapOption(option: options, sink: self) } if let markerData = arg["markers"] as? Array<Any> { markersController?.add(jsonArray: markerData) } if let pathData = arg["paths"] as? Array<Any> { pathController?.set(jsonArray: pathData) } if let circleData = arg["circles"] as? Array<Any> { circleController?.add(jsonArray: circleData) } if let polygonData = arg["polygons"] as? Array<Any> { polygonController?.add(jsonArray: polygonData) } } // 제대로 동작하지 않는 컨트롤러 UI로 원인이 밝혀지기 전까진 강제 비활성화. naverMap.showZoomControls = false naverMap.showIndoorLevelPicker = false } func view() -> UIView { return naverMap } func handle(call: FlutterMethodCall, result: FlutterResult) { switch call.method { case "map#waitForMap": result(nil) break case "map#update": if let arg = call.arguments as! NSDictionary?, let option = arg["options"] as? NSDictionary { interpretMapOption(option: option, sink: self) result(true) } else { result(false) } break case "map#type": if let arg = call.arguments as! NSDictionary?, let type = arg["mapType"] as? Int { setMapType(type) result(nil) } case "map#getVisibleRegion": let bounds = mapView.contentBounds result(latlngBoundToJson(bound: bounds)) break case "map#getPosition": let position = mapView.cameraPosition result(cameraPositionToJson(position: position)) break case "tracking#mode": if let arg = call.arguments as! NSDictionary? { setLocationTrackingMode(arg["locationTrackingMode"] as! UInt) result(true) } else { result(false) } break case "map#getSize" : let width = CGFloat(mapView.mapWidth) let height = CGFloat(mapView.mapHeight) let resolution = UIScreen.main.nativeBounds.width / UIScreen.main.bounds.width let data : Dictionary<String, Int> = [ "width" : Int(round(width * resolution)), "height" : Int(round(height * resolution)) ] result(data) break case "meter#dp" : let meterPerPx = mapView.projection.metersPerPixel().advanced(by: 0.0) let density = Double.init(UIScreen.main.scale) result(meterPerPx*density) break case "meter#px": let meterPerPx = mapView.projection.metersPerPixel().advanced(by: 0.0) result(meterPerPx) break case "camera#move" : if let arg = call.arguments as? NSDictionary { let update = toCameraUpdate(json: arg["cameraUpdate"]!) mapView.moveCamera(update) } result(nil) break case "map#capture" : let dir = NSTemporaryDirectory() let fileName = "\(NSUUID().uuidString).jpg" if let tmpFileUrl = NSURL.fileURL(withPathComponents: [dir, fileName]) { DispatchQueue.main.async { self.naverMap.takeSnapShot({ (image) in if let data = image.jpegData(compressionQuality: 1.0) ?? image.pngData() { do{ try data.write(to: tmpFileUrl) self.channel?.invokeMethod("snapshot#done", arguments: ["path" : tmpFileUrl.path]) }catch { self.channel?.invokeMethod("snapshot#done", arguments: ["path" : nil]) } }else { self.channel?.invokeMethod("snapshot#done", arguments: ["path" : nil]) } }) } } result(nil) break case "map#padding": if let arg = call.arguments as? NSDictionary { if let top = arg["top"] as? CGFloat, let left = arg["left"] as? CGFloat, let right = arg["right"] as? CGFloat, let bottom = arg["bottom"] as? CGFloat { mapView.contentInset = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right) } } result(nil) break case "circleOverlay#update" : if let arg = call.arguments as? NSDictionary { if let dataToAdd = arg["circlesToAdd"] as? Array<Any> { circleController?.add(jsonArray: dataToAdd) } if let dataToModify = arg["circlesToChange"] as? Array<Any> { circleController?.modify(jsonArray: dataToModify) } if let dataToRemove = arg["circleIdsToRemove"] as? Array<Any>{ circleController?.remove(jsonArray: dataToRemove) } } result(nil) break case "pathOverlay#update" : if let arg = call.arguments as? NSDictionary { if let dataToAdd = arg["pathToAddOrUpdate"] as? Array<Any> { pathController?.set(jsonArray: dataToAdd) } if let dataToRemove = arg["pathIdsToRemove"] as? Array<Any>{ pathController?.remove(jsonArray: dataToRemove) } } result(nil) break case "polygonOverlay#update" : if let arg = call.arguments as? NSDictionary { if let dataToAdd = arg["polygonToAdd"] as? Array<Any> { polygonController?.add(jsonArray: dataToAdd) } if let dataToModify = arg["polygonToChange"] as? Array<Any> { polygonController?.modify(jsonArray: dataToModify) } if let dataToRemove = arg["polygonToRemove"] as? Array<Any>{ polygonController?.remove(jsonArray: dataToRemove) } } result(nil) case "markers#update" : if let arg = call.arguments as? NSDictionary { if let dataToAdd = arg["markersToAdd"] as? Array<Any> { markersController?.add(jsonArray: dataToAdd) } if let dataToModify = arg["markersToChange"] as? Array<Any> { markersController?.modify(jsonArray: dataToModify) } if let dataToRemove = arg["markerIdsToRemove"] as? Array<Any>{ markersController?.remove(jsonArray: dataToRemove) } } result(nil) break case "LO#set#position" : if let arg = call.arguments as? NSDictionary, let data = arg["position"] { let latLng = toLatLng(json: data) mapView.locationOverlay.location = latLng } result(nil) break case "LO#set#bearing" : if let arg = call.arguments as? NSDictionary, let bearing = arg["bearing"] as? NSNumber { mapView.locationOverlay.heading = CGFloat(bearing.floatValue) } result(nil) break default: print("지정되지 않은 메서드콜 함수명이 들어왔습니다.\n함수명 : \(call.method)") } } // ==================== naver map camera delegate ================== // onCameraChange func mapView(_ mapView: NMFMapView, cameraDidChangeByReason reason: Int, animated: Bool) { var r = 0; switch reason { case NMFMapChangedByGesture: r = 1 break case NMFMapChangedByControl: r = 2 break case NMFMapChangedByLocation: r = 3 break; default: r = 0; } self.channel?.invokeMethod("camera#move", arguments: ["position" : latlngToJson(latlng: mapView.cameraPosition.target), "reason" : r, "animated" : animated]) } func mapViewCameraIdle(_ mapView: NMFMapView) { self.channel?.invokeMethod("camera#idle" , arguments: nil) } // ========================== About Map Option ============================== func interpretMapOption(option: NSDictionary, sink: NaverMapOptionSink){ if let indoorEnable = option["indoorEnable"] as? Bool { sink.setIndoorEnable(indoorEnable) } if let nightModeEnable = option["nightModeEnable"] as? Bool { sink.setNightModeEnable(nightModeEnable) } if let liteModeEnable = option["liteModeEnable"] as? Bool { sink.setLiteModeEnable(liteModeEnable) } if let mapType = option["mapType"] as? Int { sink.setMapType(mapType) } if let height = option["buildingHeight"] as? Float { sink.setBuildingHeight(height) } if let scale = option["symbolScale"] as? CGFloat { sink.setSymbolScale(scale) } if let ratio = option["symbolPerspectiveRatio"] as? CGFloat{ sink.setSymbolPerspectiveRatio(ratio) } if let layers = option["activeLayers"] as? Array<Any> { sink.setActiveLayers(layers) } if let rotationGestureEnable = option["rotationGestureEnable"] as? Bool { sink.setRotationGestureEnable(rotationGestureEnable) } if let scrollGestureEnable = option["scrollGestureEnable"] as? Bool { sink.setScrollGestureEnable(scrollGestureEnable) } if let tiltGestureEnable = option["tiltGestureEnable"] as? Bool { sink.setTiltGestureEnable(tiltGestureEnable) } if let zoomGestureEnable = option["zoomGestureEnable"] as? Bool{ sink.setZoomGestureEnable(zoomGestureEnable) } if let locationTrackingMode = option["locationTrackingMode"] as? UInt { sink.setLocationTrackingMode(locationTrackingMode) } if let locationButtonEnable = option["locationButtonEnable"] as? Bool{ sink.setLocationButtonEnable(locationButtonEnable) } if let paddingData = option["contentPadding"] as? Array<CGFloat> { sink.setContentPadding(paddingData) } if let maxZoom = option["maxZoom"] as? Double{ sink.setMaxZoom(maxZoom) } if let minZoom = option["minZoom"] as? Double{ sink.setMinZoom(minZoom) } } // Naver touch Delegate method func mapView(_ mapView: NMFMapView, didTapMap latlng: NMGLatLng, point: CGPoint) { channel?.invokeMethod("map#onTap", arguments: ["position" : [latlng.lat, latlng.lng]]) } func mapView(_ mapView: NMFMapView, didTap symbol: NMFSymbol) -> Bool { channel?.invokeMethod("map#onSymbolClick", arguments: ["position" : latlngToJson(latlng: symbol.position), "caption" : symbol.caption!]) return false } // naver overlay touch handler func overlayTouchHandler(overlay: NMFOverlay) -> Bool { if let marker = overlay.userInfo["marker"] as? NMarkerController { channel?.invokeMethod("marker#onTap", arguments: ["markerId" : marker.id, "iconWidth" : pxFromPt(marker.marker.width), "iconHeight" : pxFromPt(marker.marker.height)]) return markersController!.toggleInfoWindow(marker) } else if let path = overlay.userInfo["path"] as? NPathController { channel?.invokeMethod("path#onTap", arguments: ["pathId" : path.id]) return true } else if let circle = overlay.userInfo["circle"] as? NCircleController{ channel?.invokeMethod("circle#onTap", arguments: ["overlayId" : circle.id]) return true } else if let polygon = overlay.userInfo["polygon"] as? NPolygonController { channel?.invokeMethod("polygon#onTap", arguments: ["polygonOverlayId" : polygon.id]) return true } return false } // naver map option sink method func setIndoorEnable(_ indoorEnable: Bool) { mapView.isIndoorMapEnabled = indoorEnable } func setNightModeEnable(_ nightModeEnable: Bool) { mapView.isNightModeEnabled = nightModeEnable } func setLiteModeEnable(_ liteModeEnable: Bool) { mapView.liteModeEnabled = liteModeEnable } func setMapType(_ typeIndex: Int) { let type = NMFMapType(rawValue: typeIndex)! mapView.mapType = type } func setBuildingHeight(_ buildingHeight: Float) { mapView.buildingHeight = buildingHeight } func setSymbolScale(_ symbolScale: CGFloat) { mapView.symbolScale = symbolScale } func setSymbolPerspectiveRatio(_ symbolPerspectiveRatio: CGFloat) { mapView.symbolPerspectiveRatio = symbolPerspectiveRatio } func setActiveLayers(_ activeLayers: Array<Any>) { mapView.setLayerGroup(NMF_LAYER_GROUP_BUILDING, isEnabled: false) mapView.setLayerGroup(NMF_LAYER_GROUP_TRAFFIC, isEnabled: false) mapView.setLayerGroup(NMF_LAYER_GROUP_TRANSIT, isEnabled: false) mapView.setLayerGroup(NMF_LAYER_GROUP_BICYCLE, isEnabled: false) mapView.setLayerGroup(NMF_LAYER_GROUP_MOUNTAIN, isEnabled: false) mapView.setLayerGroup(NMF_LAYER_GROUP_CADASTRAL, isEnabled: false) activeLayers.forEach { (any) in let index = any as! Int switch index { case 0 : mapView.setLayerGroup(NMF_LAYER_GROUP_BUILDING, isEnabled: true) break case 1: mapView.setLayerGroup(NMF_LAYER_GROUP_TRAFFIC, isEnabled: true) break case 2: mapView.setLayerGroup(NMF_LAYER_GROUP_TRANSIT, isEnabled: true) break case 3: mapView.setLayerGroup(NMF_LAYER_GROUP_BICYCLE, isEnabled: true) break case 4: mapView.setLayerGroup(NMF_LAYER_GROUP_MOUNTAIN, isEnabled: true) break case 5: mapView.setLayerGroup(NMF_LAYER_GROUP_CADASTRAL, isEnabled: true) break default: return } } } func setRotationGestureEnable(_ rotationGestureEnable: Bool) { mapView.isRotateGestureEnabled = rotationGestureEnable } func setScrollGestureEnable(_ scrollGestureEnable: Bool) { mapView.isScrollGestureEnabled = scrollGestureEnable } func setTiltGestureEnable(_ tiltGestureEnable: Bool) { mapView.isTiltGestureEnabled = tiltGestureEnable } func setZoomGestureEnable(_ zoomGestureEnable: Bool) { mapView.isZoomGestureEnabled = zoomGestureEnable } func setLocationTrackingMode(_ locationTrackingMode: UInt) { mapView.positionMode = NMFMyPositionMode(rawValue: locationTrackingMode)! } func setContentPadding(_ paddingData: Array<CGFloat>) { mapView.contentInset = UIEdgeInsets(top: paddingData[1], left: paddingData[0], bottom: paddingData[3], right: paddingData[2]) } func setLocationButtonEnable(_ locationButtonEnable: Bool) { naverMap.showLocationButton = locationButtonEnable } func setMaxZoom(_ maxZoom: Double){ mapView.maxZoomLevel = maxZoom } func setMinZoom(_ minZoom: Double){ mapView.minZoomLevel = minZoom } // ===================== authManagerDelegate ======================== func authorized(_ state: NMFAuthState, error: Error?) { switch state { case .authorized: print("네이버 지도 인증 완료") break case .authorizing: print("네이버 지도 인증 진행중") break case .pending: print("네이버 지도 인증 대기중") break case .unauthorized: print("네이버 지도 인증 실패") break default: break } if let e = error { print("네이버 지도 인증 에러 발생 : \(e.localizedDescription)") } } }
40.448141
152
0.56892
4bf3e2b2bfc475f5d0a50e66984a87edb9cddf17
12,602
/* License Agreement for FDA My Studies Copyright © 2017-2019 Harvard Pilgrim Health Care Institute (HPHCI) and its Contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the &quot;Software&quot;), 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. Funding Source: Food and Drug Administration (“Funding Agency”) effective 18 September 2014 as Contract no. HHSF22320140030I/HHSF22301006T (the “Prime Contract”). THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import UIKit //Used to do filter based on Apply and Cancel actions protocol StudyFilterDelegates { func appliedFilter(studyStatus: Array<String>, pariticipationsStatus: Array<String>, categories: Array<String> , searchText: String,bookmarked: Bool) func didCancelFilter(_ cancel: Bool) } enum FilterType: Int { case studyStatus = 0 case bookMark case participantStatus case category } class StudyFilterViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView? @IBOutlet weak var cancelButton: UIButton? @IBOutlet weak var applyButton: UIButton? var delegate: StudyFilterDelegates? var studyStatus: Array<String> = [] var pariticipationsStatus: Array<String> = [] var categories: Array<String> = [] var searchText: String = "" var bookmark = true var previousCollectionData: Array<Array<String>> = [] // MARK:- Viewcontroller lifecycle override func viewDidLoad() { super.viewDidLoad() applyButton?.layer.borderColor = kUicolorForButtonBackground cancelButton?.layer.borderColor = kUicolorForCancelBackground if let layout = collectionView?.collectionViewLayout as? PinterestLayout { layout.delegate = self } if StudyFilterHandler.instance.filterOptions.count == 0 { let appDelegate = (UIApplication.shared.delegate as? AppDelegate)! appDelegate.setDefaultFilters(previousCollectionData: self.previousCollectionData) } self.collectionView?.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } // MARK:- Button Actions /** Navigate to Studylist screen on Apply button clicked @param sender accepts Anyobject in sender */ @IBAction func applyButtonAction(_ sender: AnyObject){ //categories = ["Food Safety","Observational Studies","Cosmetics Safety"] //pariticipationsStatus = ["Food Safety","Observational Studies"] var i: Int = 0 var isbookmarked = false for filterOptions in StudyFilterHandler.instance.filterOptions { let filterType = FilterType.init(rawValue: i) let filterValues = (filterOptions.filterValues.filter({$0.isSelected == true})) for value in filterValues { switch (filterType!) { case .studyStatus: studyStatus.append(value.title) case .participantStatus: pariticipationsStatus.append(value.title) case .bookMark: if User.currentUser.userType == .FDAUser { bookmark = (value.isSelected) isbookmarked = true } else { categories.append(value.title) } case .category: categories.append(value.title) //default: break } } i = i + 1 } previousCollectionData = [] previousCollectionData.append(studyStatus) if User.currentUser.userType == .FDAUser { if isbookmarked { previousCollectionData.append((bookmark == true ? ["Bookmarked"]: [])) } else { previousCollectionData.append([]) bookmark = false } } else { previousCollectionData.append(categories) bookmark = false } previousCollectionData.append(pariticipationsStatus) previousCollectionData.append(categories.count == 0 ? [] : categories) delegate?.appliedFilter(studyStatus: studyStatus, pariticipationsStatus: pariticipationsStatus, categories: categories,searchText: searchText,bookmarked: bookmark) self.dismiss(animated: true, completion: nil) } /** Navigate to Studylist screen on Cancel button clicked @param sender accepts Anyobject in sender */ @IBAction func cancelButtonAction(_ sender: AnyObject) { self.delegate?.didCancelFilter(true) self.dismiss(animated: true, completion: nil) } } //// MARK:- Collection Data source & Delegate extension StudyFilterViewController: UICollectionViewDataSource {//,UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return StudyFilterHandler.instance.filterOptions.count //filterData!.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = (collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? FilterListCollectionViewCell)! let filterOption = StudyFilterHandler.instance.filterOptions[indexPath.row] cell.displayCollectionData(data: filterOption) return cell } } extension StudyFilterViewController:PinterestLayoutDelegate { // 1. Returns the photo height func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath: IndexPath , withWidth width: CGFloat) -> CGFloat { let filterOptions = StudyFilterHandler.instance.filterOptions[indexPath.row] var headerHeight = 0 if filterOptions.title.count > 0 { headerHeight = 40 } let height: CGFloat = CGFloat((filterOptions.filterValues.count * 50) + headerHeight) return height } // 2. Returns the annotation size based on the text func collectionView(_ collectionView: UICollectionView, heightForAnnotationAtIndexPath indexPath: IndexPath, withWidth width: CGFloat) -> CGFloat { return 0 } } class StudyFilterHandler { var filterOptions: Array<FilterOptions> = [] var previousAppliedFilters: Array<Array<String>> = [] var searchText = "" static var instance = StudyFilterHandler() } class FilterOptions{ var title: String! var filterValues: Array<FilterValues> = [] } class FilterValues { var title: String! var isSelected = false } extension AppDelegate{ /** setter method to set the default filter options if none are selected */ func setDefaultFilters(previousCollectionData: Array<Array<String>>) { var filterData: NSMutableArray? var resource = "AnanomousFilterData" if User.currentUser.userType == .FDAUser { resource = "FilterData" } let plistPath = Bundle.main.path(forResource: resource, ofType: ".plist", inDirectory: nil) filterData = NSMutableArray.init(contentsOfFile: plistPath!)! StudyFilterHandler.instance.filterOptions = [] var filterOptionsList: Array<FilterOptions> = [] var i = 0 for options in filterData! { let values = ((options as? Dictionary<String,Any>)!["studyData"] as? Array<Dictionary<String,Any>>)! let filterOptions = FilterOptions() filterOptions.title = ((options as? Dictionary<String,Any>)!["headerText"] as? String)! var selectedValues: Array<String> = [] if previousCollectionData.count > 0 { selectedValues = previousCollectionData[i] } var filterValues: Array<FilterValues> = [] for value in values { var isContained = false let filterValue = FilterValues() filterValue.title = (value["name"] as? String)! if selectedValues.count > 0 { isContained = selectedValues.contains((value["name"] as? String)!) } if isContained == false { if previousCollectionData.count == 0 { // this means that we are first time accessing the filter screen filterValue.isSelected = (value["isEnabled"] as? Bool)! } else { // means that filter is already set filterValue.isSelected = false } } else { filterValue.isSelected = true } filterValues.append(filterValue) } filterOptions.filterValues = filterValues filterOptionsList.append(filterOptions) i = i + 1 } StudyFilterHandler.instance.filterOptions = filterOptionsList } /** returns the array of strings for default filters studyStatus: array of default study status pariticipationsStatus: array of participation status categories: array of categories */ func getDefaultFilterStrings()->(studyStatus: Array<String>,pariticipationsStatus: Array<String>,categories: Array<String>,searchText: String,bookmark: Bool){ var studyStatus: Array<String> = [] var pariticipationsStatus: Array<String> = [] var categories: Array<String> = [] var bookmark = true var i: Int = 0 var isbookmarked = false //Parsing the filter options for filterOptions in StudyFilterHandler.instance.filterOptions { let filterType = FilterType.init(rawValue: i) let filterValues = (filterOptions.filterValues.filter({$0.isSelected == true})) for value in filterValues { switch (filterType!) { case .studyStatus: studyStatus.append(value.title) case .participantStatus: pariticipationsStatus.append(value.title) case .bookMark: if User.currentUser.userType == .FDAUser { bookmark = (value.isSelected) isbookmarked = true } else { categories.append(value.title) } case .category: categories.append(value.title) //default: break } } i = i + 1 } if User.currentUser.userType == .FDAUser { bookmark = false } else { bookmark = false } return(studyStatus: studyStatus,pariticipationsStatus : pariticipationsStatus,categories: categories,searchText: "",bookmark: bookmark) } }
35.801136
171
0.609427
6719cae32a9beec23733d7f317c1f2208804fcde
169
// // Core.swift // // // Created by Yehor Popovych on 20.08.2021. // import Foundation import CCardano public func InitCardanoCore() { cardano_initialize() }
12.071429
44
0.674556
f48d9579a5eff874074e95f7ce62fa047ee434a4
1,338
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Basic final class Person { let name: String init(_ name: String) { self.name = name } } extension Person: ObjectIdentifierProtocol {} class ObjectIdentifierProtocolTests: XCTestCase { func testBasics() { let foo = Person("Foo") let foo2 = Person("Foo2") let foo3 = foo let bar = Person("Bar") let bar2 = bar XCTAssertNotEqual(foo, foo2) XCTAssertNotEqual(foo2, foo3) XCTAssertEqual(foo, foo3) XCTAssertNotEqual(foo, bar) XCTAssertNotEqual(foo, bar2) XCTAssertEqual(bar, bar2) var dict = [Person: String]() dict[foo] = foo.name dict[bar] = bar.name XCTAssertEqual(dict[foo], "Foo") XCTAssertEqual(dict[foo2], nil) XCTAssertEqual(dict[foo3], "Foo") XCTAssertEqual(dict[bar], "Bar") XCTAssertEqual(dict[bar2], "Bar") } static var allTests = [ ("testBasics", testBasics), ] }
23.473684
67
0.630045
ebfbd269fe325f0d2f87c367f688a94c94194e2a
13,164
// // Copyright © 2020 Jakub Kiermasz. All rights reserved. // #if canImport(UIKit) import UIKit #else import AppKit #endif @testable import Neron import XCTest final class LayoutGuideLayout_Layout_YAxis_Tests: XCTestCase { // MARK: - Properties private let view = TestView() // MARK: - Getters var direction: UserInterfaceLayoutDirection { view.direction } // MARK: - Tests // MARK: - Relative to view // MARK: - Top func test_Top_EqualToViewTop() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.equalTo(view, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 0, "Min Y should be equal to view's top anchor position") XCTAssertEqual(constraint.relation, .equal, "Relation should be equal") } func test_Top_LessThanOrEqualToViewTop() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.lessThanOrEqualTo(view, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 0, "Min Y should be less than or equal to the view's top anchor position") XCTAssertEqual(constraint.relation, .lessThanOrEqual, "Relation should be greater than or equal") } func test_Top_GreaterThanOrEqualToViewTop() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.greaterThanOrEqualTo(view, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 0, "Min Y should be greater than or equal to the view's top anchor position") XCTAssertEqual(constraint.relation, .greaterThanOrEqual, "Relation should be greater than or equal") } func test_Top_EqualToViewBottom() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.equalTo(view, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 200, "Min Y should be equal to view's bottom anchor position") XCTAssertEqual(constraint.relation, .equal, "Relation should be equal") } func test_Top_LessThanOrEqualToViewBottom() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.lessThanOrEqualTo(view, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 200, "Min Y should be less than or equal to the view's bottom anchor position") XCTAssertEqual(constraint.relation, .lessThanOrEqual, "Relation should be greater than or equal") } func test_Top_GreaterThanOrEqualToViewBottom() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.greaterThanOrEqualTo(view, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 200, "Min Y should be greater than or equal to the view's bottom anchor position") XCTAssertEqual(constraint.relation, .greaterThanOrEqual, "Relation should be greater than or equal") } // MARK: - Bottom func test_Bottom_EqualToViewBottom() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.equalTo(view, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 200, "Max Y should be equal to view's bottom anchor position") XCTAssertEqual(constraint.relation, .equal, "Relation should be equal") } func test_Bottom_LessThanOrEqualToViewBottom() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.lessThanOrEqualTo(view, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 200, "Max Y should be less than or equal to the view's bottom anchor position") XCTAssertEqual(constraint.relation, .lessThanOrEqual, "Relation should be greater than or equal") } func test_Bottom_GreaterThanOrEqualToViewBottom() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.greaterThanOrEqualTo(view, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 200, "Max Y should be greater than or equal to the view's bottom anchor position") XCTAssertEqual(constraint.relation, .greaterThanOrEqual, "Relation should be greater than or equal") } func test_Bottom_EqualToViewTop() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.equalTo(view, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 0, "Max Y should be equal to view's top anchor position") XCTAssertEqual(constraint.relation, .equal, "Relation should be equal") } func test_Bottom_LessThanOrEqualToViewTop() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.lessThanOrEqualTo(view, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 0, "Max Y should be less than or equal to the view's top anchor position") XCTAssertEqual(constraint.relation, .lessThanOrEqual, "Relation should be greater than or equal") } func test_Bottom_GreaterThanOrEqualToViewTop() { let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.greaterThanOrEqualTo(view, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 0, "Max Y should be greater than or equal to the view's top anchor position") XCTAssertEqual(constraint.relation, .greaterThanOrEqual, "Relation should be greater than or equal") } // MARK: - Relative to layout guide // MARK: - Top func test_Top_EqualToLayoutGuideTop() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.equalTo(siblingGuide, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 0, "Min Y should be equal to sibling guide's top anchor position") XCTAssertEqual(constraint.relation, .equal, "Relation should be equal") } func test_Top_LessThanOrEqualToLayoutGuideTop() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.lessThanOrEqualTo(siblingGuide, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 0, "Min Y should be less than or equal to the sibling guide's top anchor position") XCTAssertEqual(constraint.relation, .lessThanOrEqual, "Relation should be greater than or equal") } func test_Top_GreaterThanOrEqualToLayoutGuideTop() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.greaterThanOrEqualTo(siblingGuide, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 0, "Min Y should be greater than or equal to the sibling guide's top anchor position") XCTAssertEqual(constraint.relation, .greaterThanOrEqual, "Relation should be greater than or equal") } func test_Top_EqualToLayoutGuideBottom() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.equalTo(siblingGuide, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 200, "Min Y should be equal to sibling guide's bottom anchor position") XCTAssertEqual(constraint.relation, .equal, "Relation should be equal") } func test_Top_LessThanOrEqualToLayoutGuideBottom() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.lessThanOrEqualTo(siblingGuide, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 200, "Min Y should be less than or equal to the sibling guide's bottom anchor position") XCTAssertEqual(constraint.relation, .lessThanOrEqual, "Relation should be greater than or equal") } func test_Top_GreaterThanOrEqualToLayoutGuideBottom() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .top.greaterThanOrEqualTo(siblingGuide, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.minY, 200, "Min Y should be greater than or equal to the sibling guide's bottom anchor position") XCTAssertEqual(constraint.relation, .greaterThanOrEqual, "Relation should be greater than or equal") } // MARK: - Bottom func test_Bottom_EqualToLayoutGuideBottom() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.equalTo(siblingGuide, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 200, "Max Y should be equal to sibling guide's bottom anchor position") XCTAssertEqual(constraint.relation, .equal, "Relation should be equal") } func test_Bottom_LessThanOrEqualToLayoutGuideBottom() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.lessThanOrEqualTo(siblingGuide, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 200, "Max Y should be less than or equal to the sibling guide's bottom anchor position") XCTAssertEqual(constraint.relation, .lessThanOrEqual, "Relation should be greater than or equal") } func test_Bottom_GreaterThanOrEqualToLayoutGuideBottom() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.greaterThanOrEqualTo(siblingGuide, .bottom) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 200, "Max Y should be greater than or equal to the sibling guide's bottom anchor position") XCTAssertEqual(constraint.relation, .greaterThanOrEqual, "Relation should be greater than or equal") } func test_Bottom_EqualToLayoutGuideTop() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.equalTo(siblingGuide, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 0, "Max Y should be equal to sibling guide's top anchor position") XCTAssertEqual(constraint.relation, .equal, "Relation should be equal") } func test_Bottom_LessThanOrEqualToLayoutGuideTop() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.lessThanOrEqualTo(siblingGuide, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 0, "Max Y should be less than or equal to the sibling guide's top anchor position") XCTAssertEqual(constraint.relation, .lessThanOrEqual, "Relation should be greater than or equal") } func test_Bottom_GreaterThanOrEqualToLayoutGuideTop() { let siblingGuide = view.layoutGuide let guide = LayoutGuide() let constraint = guide.layout .add(to: view) .bottom.greaterThanOrEqualTo(siblingGuide, .top) .activate() .constraint view.prepare() XCTAssertEqual(guide.frame.maxY, 0, "Max Y should be greater than or equal to the sibling guide's top anchor position") XCTAssertEqual(constraint.relation, .greaterThanOrEqual, "Relation should be greater than or equal") } }
38.717647
132
0.628077
90b8b12a18600b33cbf4d528f2441a3fd2b18ca4
2,883
// // AppDelegate.swift // SafetyBox.Swift // // Created by Assassin on 31/5/20. // Copyright © 2020 Dan Gerchcovich. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: - Core Data stack // lazy var persistentContainer: NSPersistentCloudKitContainer = { // /* // The persistent container for the application. This implementation // creates and returns a container, having loaded the store for the // application to it. This property is optional since there are legitimate // error conditions that could cause the creation of the store to fail. // */ // let container = NSPersistentCloudKitContainer(name: "SafetyBox_Swift") // container.loadPersistentStores(completionHandler: { (storeDescription, error) in // if let error = error as NSError? { // // Replace this implementation with code to handle the error appropriately. // // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // // /* // Typical reasons for an error here include: // * The parent directory does not exist, cannot be created, or disallows writing. // * The persistent store is not accessible, due to permissions or data protection when the device is locked. // * The device is out of space. // * The store could not be migrated to the current model version. // Check the error message to determine what the actual problem was. // */ // fatalError("Unresolved error \(error), \(error.userInfo)") // } // }) // return container // }() // MARK: - Core Data Saving support // func saveContext () { // let context = persistentContainer.viewContext // if context.hasChanges { // do { // try context.save() // } catch { // // Replace this implementation with code to handle the error appropriately. // // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. // let nserror = error as NSError // fatalError("Unresolved error \(nserror), \(nserror.userInfo)") // } // } // } }
41.782609
201
0.628859
7652f1079ddb833de3c4f8f03a89e54f58fefbac
5,715
import Foundation import Socket extension MySQL { public class Connection : Identifiable { public let id : UUID = UUID() var host : String var user : String var password : String var database : String? var port : UInt16 var status : UInt16 = 0 var affectedRows : UInt64 = 0 public var insertId : UInt64 = 0 // Network var socket : Socket var mysql_Handshake: mysql_handshake? public var isConnected = false public init(host : String, user : String, password : String = "", database : String? = nil, port : Int = 3306) throws { self.host = host self.user = user self.password = password self.database = database self.port = UInt16(port) self.socket = try Socket( host: host, port: UInt16(port), addressFamily: AF_INET, socketType: SOCK_STREAM, socketProtocol: 0 ) // Setup options var on : Int32 = 1 try socket.setOption(level: SOL_SOCKET, option: SO_REUSEADDR, value: &on, length: socklen_t(MemoryLayout<Int32>.size)) try socket.setOption(level: SOL_SOCKET, option: SO_KEEPALIVE, value: &on, length: socklen_t(MemoryLayout<Int32>.size)) //try socket.setOption(level: SOL_SOCKET, option: SO_NOSIGPIPE, value: &on, length: socklen_t(MemoryLayout<Int32>.size)) var timeout : timeval = timeval(tv_sec: 120, tv_usec: 0) try socket.setOption(level: SOL_SOCKET, option: SO_RCVTIMEO, value: &timeout, length: socklen_t(MemoryLayout<timeval>.size)) // Setup SIGPIPE handler socket.on(event: SIGPIPE, handler: { signal in print("SIGPIPE \(signal)") /*do { try self.connect() } catch { print("Error trying to reconnect to host") }*/ }) } /// Open MySQL connection. public func open() throws { try self.connect() try self.sendAuth() // MySQL connected self.isConnected = true } /// Close MySQL connection. public func close() throws { try writeCommandPacket(MysqlCommands.COM_QUIT) try self.socket.close() self.isConnected = false } /// Connect socket to server. private func connect() throws { // Connect socket to address matching informations provided in init() try self.socket.connectAll(infos: socket.getAddressInfos()) // MySQL handshake self.mysql_Handshake = try readHandshake() } /// Send authentification data to MySQL server. private func sendAuth() throws { var encodedPass = [UInt8]() var result = [UInt8]() // Setup flags var flags : UInt32 = MysqlClientCaps.CLIENT_PROTOCOL_41 | MysqlClientCaps.CLIENT_LONG_PASSWORD | MysqlClientCaps.CLIENT_TRANSACTIONS | MysqlClientCaps.CLIENT_SECURE_CONN | MysqlClientCaps.CLIENT_LOCAL_FILES | MysqlClientCaps.CLIENT_MULTI_STATEMENTS | MysqlClientCaps.CLIENT_MULTI_RESULTS flags &= UInt32((mysql_Handshake?.cap_flags)!) | 0xffff0000 // Connect without database if database != nil { flags |= MysqlClientCaps.CLIENT_CONNECT_WITH_DB } // Make sure handhsake is received guard mysql_Handshake != nil else { throw ConnectionError.wrongHandshake } guard mysql_Handshake!.scramble != nil else { throw ConnectionError.wrongHandshake } // Encode with scrambles encodedPass = MySQL.Utils.encPasswd(password, scramble: self.mysql_Handshake!.scramble!) // Flags result.append(contentsOf: [UInt8].UInt32Array(UInt32(flags))) // Maximum packet length result.append(contentsOf:[UInt8].UInt32Array(MySQL.maxPackAllowed)) result.append(UInt8(33)) result.append(contentsOf: [UInt8](repeating:0, count: 23)) // Username result.append(contentsOf: user.utf8) result.append(0) // Hashed password result.append(UInt8(encodedPass.count)) result.append(contentsOf: encodedPass) // Database if database != nil { result.append(contentsOf: database!.utf8) } result.append(0) // MARK: Change mysql_native_password to user defined. result.append(contentsOf:"mysql_native_password".utf8) result.append(0) // Send to server try socket.writePacket( Packet( header: Header( length: UInt32(result.count), sequence: 1 ), data: result ) ) // Check is auth is successful try checkAuth() } /// Check if authentification is successful from server response. func checkAuth() throws { let packet : Packet = try socket.readPacket() switch packet.data[0] { case 0x00: successPacket(packet.data) break case 0xfe: break case 0xff: throw errorPacket(packet.data) default: break } } /// Read received MySQL handshake. private func readHandshake() throws -> MySQL.mysql_handshake { let packet : Packet = try socket.readPacket() var handshake = MySQL.mysql_handshake() var pos = 0 handshake.proto_version = packet.data[pos] pos += 1 handshake.server_version = String(cString: packet.data[pos..<packet.data.count].withUnsafeBufferPointer { $0.baseAddress! }) pos += (handshake.server_version?.utf8.count)! + 1 handshake.conn_id = packet.data[pos...pos+4].uInt32() pos += 4 handshake.scramble = Array(packet.data[pos..<pos+8]) pos += 8 + 1 handshake.cap_flags = packet.data[pos...pos+2].uInt16() pos += 2 if packet.data.count > pos { pos += 1 + 2 + 2 + 1 + 10 let c = Array(packet.data[pos..<pos+12]) handshake.scramble?.append(contentsOf:c) } return handshake } enum ConnectionError : Error { case addressNotSet case usernameNotSet case notConnected case statementPrepareError(String) case dataReadingError case queryInProgress case wrongHandshake } } }
26.458333
127
0.674366
18ba25c5364d5e2c2052645f508c02e54dbbdb5a
739
import XCTest import ci class Tests: 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.482759
111
0.596752
56b7224259481e44aeeb7bbace1ebbc6e1db01e9
2,139
import Foundation /// Size of the .ipa archive (not the App Store size!). /// Requirements: .ipa available in the `#{PROJECT_DIR}/build` folder (or in another `PROJECT_DIR` subfolder provided as the `path` argument). public struct IPASizeProvider: InfoProvider { public struct Args { /// The path to the folder containing the .ipa file. public let path: String public init(path: String) { self.path = path } } public typealias Arguments = Args public static let identifier: String = "ipa_size" public let description: String = "📦 Compressed App Size (.ipa)" public let size: Int public init(size: Int) { self.size = size } public static func extract(fromApi api: SwiftInfo, args: Args?) throws -> IPASizeProvider { let fileUtils = api.fileUtils let infofileFolder = try fileUtils.infofileFolder() let buildFolder = infofileFolder + (args?.path ?? "build/") let contents = try fileUtils.fileManager.contentsOfDirectory(atPath: buildFolder) guard let ipa = contents.first(where: { $0.hasSuffix(".ipa") }) else { throw error(".ipa not found! Attempted to find .ipa at: \(buildFolder)") } let attributes = try fileUtils.fileManager.attributesOfItem(atPath: buildFolder + ipa) let fileSize = Int(attributes[.size] as? UInt64 ?? 0) return IPASizeProvider(size: fileSize) } public func summary(comparingWith other: IPASizeProvider?, args _: Args?) -> Summary { let prefix = description let stringFormatter: ((Int) -> String) = { value in let formatter = ByteCountFormatter() formatter.allowsNonnumericFormatting = false formatter.countStyle = .file return formatter.string(fromByteCount: Int64(value)) } return Summary.genericFor(prefix: prefix, now: size, old: other?.size, increaseIsBad: true, stringValueFormatter: stringFormatter) } }
40.358491
142
0.614306
f54a47335bc604e0d15eeece72c44bb9905ccda3
2,312
/* * Copyright (c) 2021, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import Foundation public struct LightLCModeStatus: GenericMessage { public static let opCode: UInt32 = 0x8294 /// Whether the controller is turned on and the binding with the Light Lightness /// state is enabled. let controllerStatus: Bool public var parameters: Data? { return Data() + controllerStatus } /// Creates the Light LC Mode Status message. /// /// - parameter status: The present value of the Light LC Mode state. public init(_ status: Bool) { self.controllerStatus = status } public init?(parameters: Data) { guard parameters.count == 1 else { return nil } self.controllerStatus = parameters[0] == 0x01 } }
39.186441
84
0.729671
d7427cdf928414c673ac57d1389180ce79a486a9
402
// // MatcherServiceTypes.swift // WavesWallet-iOS // // Created by mefilt on 20.07.2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation enum Matcher {} extension Matcher { enum DTO {} enum Service {} } protocol MatcherTargetType: BaseTargetType {} extension MatcherTargetType { var baseURL: URL { return Environments.current.servers.matcherUrl } }
16.75
71
0.71393
d91b45f176e50da604fe5570f2fbc6ddada9f7a3
1,469
// // NavigationController.swift // InnovationApp // // Created by 袁炜杰 on 2018/4/25. // Copyright © 2018年 袁炜杰. All rights reserved. // import UIKit class NavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() setNav() } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if self.childViewControllers.count == 1 { viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } private func setNav() { navigationBar.setBackgroundImage(UIImage.color(kWhiteColor), for: UIBarPosition.any, barMetrics: .default) navigationBar.tintColor = kBlueColor navigationBar.barTintColor = kWhiteColor navigationBar.titleTextAttributes = [ NSAttributedStringKey.foregroundColor : kBlackColor, NSAttributedStringKey.font : boldFont(size: 18)] UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font : Font(size: 15)], for: .normal) UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(-8, -1), for: .default) // 设置导航栏样式 navigationBar.shadowImage = UIImage() navigationBar.backIndicatorImage = UIImage(named: "nav_return") navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "nav_return") } }
35.829268
120
0.696392
29f7f1bc5905b9763970fdb32d006b1ac5e8f77a
1,037
// // StringExtensions.swift // SendToMe // // Created by Chris Jimenez on 1/26/16. // Copyright © 2016 Chris Jimenez. All rights reserved. // import Foundation // MARK: - Util extension for strings extension String { /** Validated if the string is a valid email address - returns: valid email or not */ public func isValidEmail() -> Bool { //Valid email reg expresion let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" //Create the predicate with the expresion let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) //Check the value of the string return emailTest.evaluateWithObject(self) } /// Returns the localized string value public var localized: String { return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "") } }
25.292683
160
0.581485
2f7ab9bbefe867212826b26db0316ae842bdf543
2,553
// // BinarySize.swift // // // Created by Marino Felipe on 03.01.21. // import ArgumentParser import Core import App import Reports extension SwiftPackageInfo { public struct BinarySize: ParsableCommand { static let estimatedSizeNote = """ * Note: The estimated size may not reflect the exact amount since it doesn't account optimizations such as app thinning. Its methodology is inspired by [cocoapods-size](https://github.com/google/cocoapods-size), and thus works by comparing archives with no bitcode and ARM64 arch. Such a strategy has proven to be very consistent with the size added to iOS apps downloaded and installed via TestFlight. """ public static var configuration = CommandConfiguration( abstract: "Estimated binary size of a Swift Package product.", discussion: """ Measures the estimated binary size impact of a Swift Package product, such as "ArgumentParser" declared on `swift-argument-parser`. \(estimatedSizeNote) """, version: "1.0" ) @OptionGroup var allArguments: AllArguments public init() {} public func run() throws { try runArgumentsValidation(arguments: allArguments) var swiftPackage = makeSwiftPackage(from: allArguments) swiftPackage.messages.forEach(Console.default.lineBreakAndWrite) let packageContent = try validate( swiftPackage: &swiftPackage, verbose: allArguments.verbose ) let report = Report(swiftPackage: swiftPackage) try BinarySizeProvider.fetchInformation( for: swiftPackage, packageContent: packageContent, verbose: allArguments.verbose ) .onSuccess { try report.generate( for: $0, format: allArguments.report ) } .onFailure { Console.default.write($0.message) } } } } extension SwiftPackage: CustomConsoleMessagesConvertible { public var messages: [ConsoleMessage] { [ .init( text: "Identified Swift Package:", color: .green, isBold: true, hasLineBreakAfter: false ), .init( text: description, color: .noColor, isBold: false ) ] } }
31.134146
129
0.578927
fb9db16d478b02236d5adfca26d64d5d34f0b525
9,955
// // Authentication.swift // InformME // // Created by Amal Ibrahim on 2/4/16. // Copyright © 2016 King Saud University. All rights reserved. // import UIKit import Foundation class Authentication { func login(email: String, Passoword: String, Type: Int, completionHandler: (login:Bool) -> ()){ struct f { static var flag = false } let MYURL = NSURL(string:"http://bemyeyes.co/API/login.php") let request = NSMutableURLRequest(URL:MYURL!) request.HTTPMethod = "POST"; let postString = "email=\(email)&password=\(Passoword)&type=\(Type)"; request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding); let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print("error=\(error)") return } // var err: NSError? // var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as NSDictionary else { if let urlContent = data { do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) let l = jsonResult["account"]!!["status"] let s = String (l) print (s+"Hi") if( s == "Optional(true)") { let id = jsonResult["account"]!!["ID"] let email = jsonResult["account"]!!["email"] let type = jsonResult["account"]!!["type"] let session = jsonResult["account"]!!["session"] print(id, email, type, session) NSUserDefaults.standardUserDefaults().setObject(id, forKey: "id") NSUserDefaults.standardUserDefaults().setObject(email, forKey: "email") NSUserDefaults.standardUserDefaults().setObject(type, forKey: "type") NSUserDefaults.standardUserDefaults().setObject(session, forKey: "session") NSUserDefaults.standardUserDefaults().synchronize() /* for jawaher to check print(id, email, type, session) print("lol") */ f.flag = true }//end if else if( s == "Optional(false)") { f.flag = false print (s) } //end else } catch { print("JSON serialization failed") } } } // You can print out response object // print("response = \(response)") //completion handler values. completionHandler(login: f.flag) } task.resume() /* var cID = "" var cemail = "" var ctype = "" var csession = "" let current = NSUserDefaults.standardUserDefaults() cID = current.stringForKey("id")! cemail = current.stringForKey("email")! ctype = current.stringForKey("type")! csession = current.stringForKey("session")! print(cID) print(cemail) print(ctype) print(ctype) if (!cID.isEmpty && !cemail.isEmpty && !ctype.isEmpty && !csession.isEmpty) { flag.self = true } */ /* for jawaher to check its save the in defaults let defaults = NSUserDefaults.standardUserDefaults() if let name = defaults.stringForKey("id") { print("reading") print(name) } */ } // end fun login func logout( completionHandler: (login:Bool) -> ()){ struct f { static var flag = false } let session = NSUserDefaults.standardUserDefaults().stringForKey("session")! print("from defult= "+session) let MYURL = NSURL(string:"http://bemyeyes.co/API/logout.php") let request = NSMutableURLRequest(URL:MYURL!) request.HTTPMethod = "POST"; let postString = "&sessionID=\(session)"; request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding); let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print("error=\(error)") return } else{ if let urlContent = data { do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) let l = jsonResult["status"]!! let s = String (l) print (s+"hi this status") if( s == "success") { NSUserDefaults.standardUserDefaults().removeObjectForKey("id") NSUserDefaults.standardUserDefaults().removeObjectForKey("email") NSUserDefaults.standardUserDefaults().removeObjectForKey("type") NSUserDefaults.standardUserDefaults().removeObjectForKey("session") NSUserDefaults.standardUserDefaults().synchronize() f.flag = true print (s+"hi 1111") } //end if else if( s == "unsuccess") { f.flag = false print (s+"hi 222") } //end else } catch { print("JSON serialization failed") } } }//end els // You can print out response object // print("response = \(response)") completionHandler(login: f.flag) } task.resume() } // end log out func forgetPassword(){ } func requestPassword(email: String){} func recoverPassword(email: String , Type: Int, completionHandler: (login:Bool) -> ()){ struct f { static var flag = false } let MYURL = NSURL(string:"http://bemyeyes.co/API/rest.php") let request = NSMutableURLRequest(URL:MYURL!) request.HTTPMethod = "POST"; let postString = "&email=\(email)&type=\(Type)"; request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding); let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print("error=\(error)") return } else{ if let urlContent = data { do { let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) let l = jsonResult["status"]!! let s = String (l) print (s+"hi this status") if( s == "success") { f.flag = true print (s+"hi 1111") } //end if else if( s == "unsuccess") { f.flag = false print (s+"hi 222") } //end else } catch { print("JSON serialization failed") } } }//end els // You can print out response object // print("response = \(response)") completionHandler(login: f.flag) } task.resume() } // end recover password fun }//end class
29.193548
144
0.394977