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
f79a1ee804dce98c32de06e3e0d247617ddc6b4b
2,565
// // Copyright © 2018-present Amaris Technologies GmbH. All rights reserved. // import Foundation extension MainViewController { /// User pressed the continue (or restart, logout…) button @IBAction func pressedContinueButton(_ sender: AnyObject) { Preferences.sharedInstance.setupDone = true Preferences.sharedInstance.continueAction.pressed(sender) } /// Set the initial state of the view func setupInstalling() { indeterminateProgressIndicator.startAnimation(self) indeterminateProgressIndicator.isHidden = false statusLabel.isHidden = false statusLabel.stringValue = NSLocalizedString("actions.preparing_your_mac") sidebarView.isHidden = Preferences.sharedInstance.sidebar continueButton.isEnabled = false } /// reset the status label to "We are preparing your Mac…" @objc func resetStatusLabel() { statusLabel.stringValue = NSLocalizedString("actions.preparing_your_mac") } /// sets the status label to display an error @objc func errorWhileInstalling() { Preferences.sharedInstance.errorWhileInstalling = true guard let error = SoftwareArray.sharedInstance.localizedErrorStatus else { return } statusLabel.textColor = .red statusLabel.stringValue = error } /// all critical software is installed @objc func canContinue() { Preferences.sharedInstance.criticalDone = true self.continueButton.isEnabled = true } /// all software is installed (failed or success) @objc func doneInstalling() { Preferences.sharedInstance.allInstalled = true indeterminateProgressIndicator.stopAnimation(self) indeterminateProgressIndicator.isHidden = true if Preferences.sharedInstance.labMode { self.sidebarView.isHidden = true if let labComplete = Preferences.sharedInstance.labComplete { self.webView.loadFileURL(labComplete, allowingReadAccessTo: Preferences.sharedInstance.assetPath) } else { let errorMsg = NSLocalizedString("error.create_complete_html_file") self.webView.loadHTMLString(errorMsg, baseURL: nil) } } } /// all software is sucessfully installed @objc func allSuccess() { Preferences.sharedInstance.allSuccessfullyInstalled = true statusLabel.textColor = .labelColor statusLabel.stringValue = Preferences.sharedInstance.continueAction.localizedSuccessStatus } }
34.662162
113
0.694347
e014c3de9a46c5f5616a721efd4639fb312efd06
21,591
// Generated by Lona Compiler 0.5.3 import AppKit import Foundation // MARK: - ColorInspector public class ColorInspector: NSBox { // MARK: Lifecycle public init(_ parameters: Parameters) { self.parameters = parameters super.init(frame: .zero) setUpViews() setUpConstraints() update() } public convenience init( idText: String, nameText: String, valueText: String, descriptionText: String, colorValue: ColorPickerColor) { self .init( Parameters( idText: idText, nameText: nameText, valueText: valueText, descriptionText: descriptionText, colorValue: colorValue)) } public convenience init() { self.init(Parameters()) } public required init?(coder aDecoder: NSCoder) { self.parameters = Parameters() super.init(coder: aDecoder) setUpViews() setUpConstraints() update() } // MARK: Public public var idText: String { get { return parameters.idText } set { if parameters.idText != newValue { parameters.idText = newValue } } } public var nameText: String { get { return parameters.nameText } set { if parameters.nameText != newValue { parameters.nameText = newValue } } } public var valueText: String { get { return parameters.valueText } set { if parameters.valueText != newValue { parameters.valueText = newValue } } } public var descriptionText: String { get { return parameters.descriptionText } set { if parameters.descriptionText != newValue { parameters.descriptionText = newValue } } } public var onChangeIdText: StringHandler { get { return parameters.onChangeIdText } set { parameters.onChangeIdText = newValue } } public var onChangeNameText: StringHandler { get { return parameters.onChangeNameText } set { parameters.onChangeNameText = newValue } } public var onChangeValueText: StringHandler { get { return parameters.onChangeValueText } set { parameters.onChangeValueText = newValue } } public var onChangeDescriptionText: StringHandler { get { return parameters.onChangeDescriptionText } set { parameters.onChangeDescriptionText = newValue } } public var colorValue: ColorPickerColor { get { return parameters.colorValue } set { if parameters.colorValue != newValue { parameters.colorValue = newValue } } } public var onChangeColorValue: ColorPickerHandler { get { return parameters.onChangeColorValue } set { parameters.onChangeColorValue = newValue } } public var parameters: Parameters { didSet { if parameters != oldValue { update() } } } // MARK: Private private var nameLabelView = LNATextField(labelWithString: "") private var nameInputView = TextInput() private var spacer1View = NSBox() private var idLabelView = LNATextField(labelWithString: "") private var idInputView = CoreTextInput() private var spacer2View = NSBox() private var valueLabelView = LNATextField(labelWithString: "") private var fitWidthFixValueContainerView = NSBox() private var coreColorWellPickerView = CoreColorWellPicker() private var smallSpacer1View = NSBox() private var valueInputView = TextInput() private var spacer3View = NSBox() private var descriptionLabelView = LNATextField(labelWithString: "") private var descriptionInputView = TextInput() private var nameLabelViewTextStyle = TextStyles.small private var idLabelViewTextStyle = TextStyles.small private var valueLabelViewTextStyle = TextStyles.small private var descriptionLabelViewTextStyle = TextStyles.small private func setUpViews() { boxType = .custom borderType = .noBorder contentViewMargins = .zero nameLabelView.lineBreakMode = .byWordWrapping spacer1View.boxType = .custom spacer1View.borderType = .noBorder spacer1View.contentViewMargins = .zero idLabelView.lineBreakMode = .byWordWrapping spacer2View.boxType = .custom spacer2View.borderType = .noBorder spacer2View.contentViewMargins = .zero valueLabelView.lineBreakMode = .byWordWrapping fitWidthFixValueContainerView.boxType = .custom fitWidthFixValueContainerView.borderType = .noBorder fitWidthFixValueContainerView.contentViewMargins = .zero spacer3View.boxType = .custom spacer3View.borderType = .noBorder spacer3View.contentViewMargins = .zero descriptionLabelView.lineBreakMode = .byWordWrapping smallSpacer1View.boxType = .custom smallSpacer1View.borderType = .noBorder smallSpacer1View.contentViewMargins = .zero addSubview(nameLabelView) addSubview(nameInputView) addSubview(spacer1View) addSubview(idLabelView) addSubview(idInputView) addSubview(spacer2View) addSubview(valueLabelView) addSubview(fitWidthFixValueContainerView) addSubview(spacer3View) addSubview(descriptionLabelView) addSubview(descriptionInputView) fitWidthFixValueContainerView.addSubview(coreColorWellPickerView) fitWidthFixValueContainerView.addSubview(smallSpacer1View) fitWidthFixValueContainerView.addSubview(valueInputView) nameLabelView.attributedStringValue = nameLabelViewTextStyle.apply(to: "NAME") nameLabelViewTextStyle = TextStyles.small nameLabelView.attributedStringValue = nameLabelViewTextStyle.apply(to: nameLabelView.attributedStringValue) spacer1View.fillColor = #colorLiteral(red: 0.847058823529, green: 0.847058823529, blue: 0.847058823529, alpha: 1) idLabelView.attributedStringValue = idLabelViewTextStyle.apply(to: "ID") idLabelViewTextStyle = TextStyles.small idLabelView.attributedStringValue = idLabelViewTextStyle.apply(to: idLabelView.attributedStringValue) spacer2View.fillColor = #colorLiteral(red: 0.847058823529, green: 0.847058823529, blue: 0.847058823529, alpha: 1) valueLabelView.attributedStringValue = valueLabelViewTextStyle.apply(to: "VALUE") valueLabelViewTextStyle = TextStyles.small valueLabelView.attributedStringValue = valueLabelViewTextStyle.apply(to: valueLabelView.attributedStringValue) spacer3View.fillColor = #colorLiteral(red: 0.847058823529, green: 0.847058823529, blue: 0.847058823529, alpha: 1) descriptionLabelView.attributedStringValue = descriptionLabelViewTextStyle.apply(to: "DESCRIPTION") descriptionLabelViewTextStyle = TextStyles.small descriptionLabelView.attributedStringValue = descriptionLabelViewTextStyle.apply(to: descriptionLabelView.attributedStringValue) } private func setUpConstraints() { translatesAutoresizingMaskIntoConstraints = false nameLabelView.translatesAutoresizingMaskIntoConstraints = false nameInputView.translatesAutoresizingMaskIntoConstraints = false spacer1View.translatesAutoresizingMaskIntoConstraints = false idLabelView.translatesAutoresizingMaskIntoConstraints = false idInputView.translatesAutoresizingMaskIntoConstraints = false spacer2View.translatesAutoresizingMaskIntoConstraints = false valueLabelView.translatesAutoresizingMaskIntoConstraints = false fitWidthFixValueContainerView.translatesAutoresizingMaskIntoConstraints = false spacer3View.translatesAutoresizingMaskIntoConstraints = false descriptionLabelView.translatesAutoresizingMaskIntoConstraints = false descriptionInputView.translatesAutoresizingMaskIntoConstraints = false coreColorWellPickerView.translatesAutoresizingMaskIntoConstraints = false smallSpacer1View.translatesAutoresizingMaskIntoConstraints = false valueInputView.translatesAutoresizingMaskIntoConstraints = false let nameLabelViewTopAnchorConstraint = nameLabelView.topAnchor.constraint(equalTo: topAnchor, constant: 20) let nameLabelViewLeadingAnchorConstraint = nameLabelView.leadingAnchor.constraint(equalTo: leadingAnchor) let nameLabelViewTrailingAnchorConstraint = nameLabelView.trailingAnchor.constraint(equalTo: trailingAnchor) let nameInputViewTopAnchorConstraint = nameInputView .topAnchor .constraint(equalTo: nameLabelView.bottomAnchor, constant: 4) let nameInputViewLeadingAnchorConstraint = nameInputView.leadingAnchor.constraint(equalTo: leadingAnchor) let nameInputViewTrailingAnchorConstraint = nameInputView.trailingAnchor.constraint(equalTo: trailingAnchor) let spacer1ViewTopAnchorConstraint = spacer1View.topAnchor.constraint(equalTo: nameInputView.bottomAnchor) let spacer1ViewLeadingAnchorConstraint = spacer1View.leadingAnchor.constraint(equalTo: leadingAnchor) let idLabelViewTopAnchorConstraint = idLabelView.topAnchor.constraint(equalTo: spacer1View.bottomAnchor) let idLabelViewLeadingAnchorConstraint = idLabelView.leadingAnchor.constraint(equalTo: leadingAnchor) let idLabelViewTrailingAnchorConstraint = idLabelView.trailingAnchor.constraint(equalTo: trailingAnchor) let idInputViewTopAnchorConstraint = idInputView .topAnchor .constraint(equalTo: idLabelView.bottomAnchor, constant: 4) let idInputViewLeadingAnchorConstraint = idInputView.leadingAnchor.constraint(equalTo: leadingAnchor) let idInputViewTrailingAnchorConstraint = idInputView.trailingAnchor.constraint(equalTo: trailingAnchor) let spacer2ViewTopAnchorConstraint = spacer2View.topAnchor.constraint(equalTo: idInputView.bottomAnchor) let spacer2ViewLeadingAnchorConstraint = spacer2View.leadingAnchor.constraint(equalTo: leadingAnchor) let valueLabelViewTopAnchorConstraint = valueLabelView.topAnchor.constraint(equalTo: spacer2View.bottomAnchor) let valueLabelViewLeadingAnchorConstraint = valueLabelView.leadingAnchor.constraint(equalTo: leadingAnchor) let valueLabelViewTrailingAnchorConstraint = valueLabelView.trailingAnchor.constraint(equalTo: trailingAnchor) let fitWidthFixValueContainerViewTopAnchorConstraint = fitWidthFixValueContainerView .topAnchor .constraint(equalTo: valueLabelView.bottomAnchor, constant: 4) let fitWidthFixValueContainerViewLeadingAnchorConstraint = fitWidthFixValueContainerView .leadingAnchor .constraint(equalTo: leadingAnchor) let fitWidthFixValueContainerViewTrailingAnchorConstraint = fitWidthFixValueContainerView .trailingAnchor .constraint(lessThanOrEqualTo: trailingAnchor) let spacer3ViewTopAnchorConstraint = spacer3View .topAnchor .constraint(equalTo: fitWidthFixValueContainerView.bottomAnchor) let spacer3ViewLeadingAnchorConstraint = spacer3View.leadingAnchor.constraint(equalTo: leadingAnchor) let descriptionLabelViewTopAnchorConstraint = descriptionLabelView .topAnchor .constraint(equalTo: spacer3View.bottomAnchor) let descriptionLabelViewLeadingAnchorConstraint = descriptionLabelView .leadingAnchor .constraint(equalTo: leadingAnchor) let descriptionLabelViewTrailingAnchorConstraint = descriptionLabelView .trailingAnchor .constraint(equalTo: trailingAnchor) let descriptionInputViewBottomAnchorConstraint = descriptionInputView.bottomAnchor.constraint(equalTo: bottomAnchor) let descriptionInputViewTopAnchorConstraint = descriptionInputView .topAnchor .constraint(equalTo: descriptionLabelView.bottomAnchor, constant: 4) let descriptionInputViewLeadingAnchorConstraint = descriptionInputView .leadingAnchor .constraint(equalTo: leadingAnchor) let descriptionInputViewTrailingAnchorConstraint = descriptionInputView .trailingAnchor .constraint(equalTo: trailingAnchor) let spacer1ViewHeightAnchorConstraint = spacer1View.heightAnchor.constraint(equalToConstant: 20) let spacer1ViewWidthAnchorConstraint = spacer1View.widthAnchor.constraint(equalToConstant: 0) let idInputViewHeightAnchorConstraint = idInputView.heightAnchor.constraint(equalToConstant: 21) let spacer2ViewHeightAnchorConstraint = spacer2View.heightAnchor.constraint(equalToConstant: 20) let spacer2ViewWidthAnchorConstraint = spacer2View.widthAnchor.constraint(equalToConstant: 0) let coreColorWellPickerViewHeightAnchorParentConstraint = coreColorWellPickerView .heightAnchor .constraint(lessThanOrEqualTo: fitWidthFixValueContainerView.heightAnchor) let smallSpacer1ViewHeightAnchorParentConstraint = smallSpacer1View .heightAnchor .constraint(lessThanOrEqualTo: fitWidthFixValueContainerView.heightAnchor) let valueInputViewHeightAnchorParentConstraint = valueInputView .heightAnchor .constraint(lessThanOrEqualTo: fitWidthFixValueContainerView.heightAnchor) let coreColorWellPickerViewLeadingAnchorConstraint = coreColorWellPickerView .leadingAnchor .constraint(equalTo: fitWidthFixValueContainerView.leadingAnchor) let coreColorWellPickerViewTopAnchorConstraint = coreColorWellPickerView .topAnchor .constraint(equalTo: fitWidthFixValueContainerView.topAnchor) let smallSpacer1ViewLeadingAnchorConstraint = smallSpacer1View .leadingAnchor .constraint(equalTo: coreColorWellPickerView.trailingAnchor) let smallSpacer1ViewTopAnchorConstraint = smallSpacer1View .topAnchor .constraint(equalTo: fitWidthFixValueContainerView.topAnchor) let valueInputViewTrailingAnchorConstraint = valueInputView .trailingAnchor .constraint(equalTo: fitWidthFixValueContainerView.trailingAnchor) let valueInputViewLeadingAnchorConstraint = valueInputView .leadingAnchor .constraint(equalTo: smallSpacer1View.trailingAnchor) let valueInputViewTopAnchorConstraint = valueInputView .topAnchor .constraint(equalTo: fitWidthFixValueContainerView.topAnchor) let valueInputViewBottomAnchorConstraint = valueInputView .bottomAnchor .constraint(equalTo: fitWidthFixValueContainerView.bottomAnchor) let spacer3ViewHeightAnchorConstraint = spacer3View.heightAnchor.constraint(equalToConstant: 20) let spacer3ViewWidthAnchorConstraint = spacer3View.widthAnchor.constraint(equalToConstant: 0) let coreColorWellPickerViewHeightAnchorConstraint = coreColorWellPickerView .heightAnchor .constraint(equalToConstant: 22) let coreColorWellPickerViewWidthAnchorConstraint = coreColorWellPickerView .widthAnchor .constraint(equalToConstant: 34) let smallSpacer1ViewHeightAnchorConstraint = smallSpacer1View.heightAnchor.constraint(equalToConstant: 0) let smallSpacer1ViewWidthAnchorConstraint = smallSpacer1View.widthAnchor.constraint(equalToConstant: 4) coreColorWellPickerViewHeightAnchorParentConstraint.priority = NSLayoutConstraint.Priority.defaultLow smallSpacer1ViewHeightAnchorParentConstraint.priority = NSLayoutConstraint.Priority.defaultLow valueInputViewHeightAnchorParentConstraint.priority = NSLayoutConstraint.Priority.defaultLow NSLayoutConstraint.activate([ nameLabelViewTopAnchorConstraint, nameLabelViewLeadingAnchorConstraint, nameLabelViewTrailingAnchorConstraint, nameInputViewTopAnchorConstraint, nameInputViewLeadingAnchorConstraint, nameInputViewTrailingAnchorConstraint, spacer1ViewTopAnchorConstraint, spacer1ViewLeadingAnchorConstraint, idLabelViewTopAnchorConstraint, idLabelViewLeadingAnchorConstraint, idLabelViewTrailingAnchorConstraint, idInputViewTopAnchorConstraint, idInputViewLeadingAnchorConstraint, idInputViewTrailingAnchorConstraint, spacer2ViewTopAnchorConstraint, spacer2ViewLeadingAnchorConstraint, valueLabelViewTopAnchorConstraint, valueLabelViewLeadingAnchorConstraint, valueLabelViewTrailingAnchorConstraint, fitWidthFixValueContainerViewTopAnchorConstraint, fitWidthFixValueContainerViewLeadingAnchorConstraint, fitWidthFixValueContainerViewTrailingAnchorConstraint, spacer3ViewTopAnchorConstraint, spacer3ViewLeadingAnchorConstraint, descriptionLabelViewTopAnchorConstraint, descriptionLabelViewLeadingAnchorConstraint, descriptionLabelViewTrailingAnchorConstraint, descriptionInputViewBottomAnchorConstraint, descriptionInputViewTopAnchorConstraint, descriptionInputViewLeadingAnchorConstraint, descriptionInputViewTrailingAnchorConstraint, spacer1ViewHeightAnchorConstraint, spacer1ViewWidthAnchorConstraint, idInputViewHeightAnchorConstraint, spacer2ViewHeightAnchorConstraint, spacer2ViewWidthAnchorConstraint, coreColorWellPickerViewHeightAnchorParentConstraint, smallSpacer1ViewHeightAnchorParentConstraint, valueInputViewHeightAnchorParentConstraint, coreColorWellPickerViewLeadingAnchorConstraint, coreColorWellPickerViewTopAnchorConstraint, smallSpacer1ViewLeadingAnchorConstraint, smallSpacer1ViewTopAnchorConstraint, valueInputViewTrailingAnchorConstraint, valueInputViewLeadingAnchorConstraint, valueInputViewTopAnchorConstraint, valueInputViewBottomAnchorConstraint, spacer3ViewHeightAnchorConstraint, spacer3ViewWidthAnchorConstraint, coreColorWellPickerViewHeightAnchorConstraint, coreColorWellPickerViewWidthAnchorConstraint, smallSpacer1ViewHeightAnchorConstraint, smallSpacer1ViewWidthAnchorConstraint ]) } private func update() { idInputView.textValue = idText nameInputView.textValue = nameText valueInputView.textValue = valueText descriptionInputView.textValue = descriptionText idInputView.onChangeTextValue = handleOnChangeIdText nameInputView.onChangeTextValue = handleOnChangeNameText valueInputView.onChangeTextValue = handleOnChangeValueText descriptionInputView.onChangeTextValue = handleOnChangeDescriptionText coreColorWellPickerView.colorValue = colorValue coreColorWellPickerView.onChangeColorValue = handleOnChangeColorValue } private func handleOnChangeIdText(_ arg0: String) { onChangeIdText?(arg0) } private func handleOnChangeNameText(_ arg0: String) { onChangeNameText?(arg0) } private func handleOnChangeValueText(_ arg0: String) { onChangeValueText?(arg0) } private func handleOnChangeDescriptionText(_ arg0: String) { onChangeDescriptionText?(arg0) } private func handleOnChangeColorValue(_ arg0: SwiftColor) { onChangeColorValue?(arg0) } } // MARK: - Parameters extension ColorInspector { public struct Parameters: Equatable { public var idText: String public var nameText: String public var valueText: String public var descriptionText: String public var colorValue: ColorPickerColor public var onChangeIdText: StringHandler public var onChangeNameText: StringHandler public var onChangeValueText: StringHandler public var onChangeDescriptionText: StringHandler public var onChangeColorValue: ColorPickerHandler public init( idText: String, nameText: String, valueText: String, descriptionText: String, colorValue: ColorPickerColor, onChangeIdText: StringHandler = nil, onChangeNameText: StringHandler = nil, onChangeValueText: StringHandler = nil, onChangeDescriptionText: StringHandler = nil, onChangeColorValue: ColorPickerHandler = nil) { self.idText = idText self.nameText = nameText self.valueText = valueText self.descriptionText = descriptionText self.colorValue = colorValue self.onChangeIdText = onChangeIdText self.onChangeNameText = onChangeNameText self.onChangeValueText = onChangeValueText self.onChangeDescriptionText = onChangeDescriptionText self.onChangeColorValue = onChangeColorValue } public init() { self.init(idText: "", nameText: "", valueText: "", descriptionText: "", colorValue: nil) } public static func ==(lhs: Parameters, rhs: Parameters) -> Bool { return lhs.idText == rhs.idText && lhs.nameText == rhs.nameText && lhs.valueText == rhs.valueText && lhs.descriptionText == rhs.descriptionText && lhs.colorValue == rhs.colorValue } } } // MARK: - Model extension ColorInspector { public struct Model: LonaViewModel, Equatable { public var id: String? public var parameters: Parameters public var type: String { return "ColorInspector" } public init(id: String? = nil, parameters: Parameters) { self.id = id self.parameters = parameters } public init(_ parameters: Parameters) { self.parameters = parameters } public init( idText: String, nameText: String, valueText: String, descriptionText: String, colorValue: ColorPickerColor, onChangeIdText: StringHandler = nil, onChangeNameText: StringHandler = nil, onChangeValueText: StringHandler = nil, onChangeDescriptionText: StringHandler = nil, onChangeColorValue: ColorPickerHandler = nil) { self .init( Parameters( idText: idText, nameText: nameText, valueText: valueText, descriptionText: descriptionText, colorValue: colorValue, onChangeIdText: onChangeIdText, onChangeNameText: onChangeNameText, onChangeValueText: onChangeValueText, onChangeDescriptionText: onChangeDescriptionText, onChangeColorValue: onChangeColorValue)) } public init() { self.init(idText: "", nameText: "", valueText: "", descriptionText: "", colorValue: nil) } } }
40.508443
120
0.774026
8acc8b0af3029666ad2a1e7809cbbaf835bcdb5d
1,650
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-swift-frontend -emit-module -module-name Multi -o %t/multi-file.swiftmodule -primary-file %s %S/Inputs/multi-file-nested-types.swift %S/Inputs/multi-file-nested-types-extensions.swift // RUN: %target-swift-frontend -emit-module -module-name Multi -o %t/multi-file-2.swiftmodule %s -primary-file %S/Inputs/multi-file-nested-types.swift %S/Inputs/multi-file-nested-types-extensions.swift // RUN: %target-swift-frontend -emit-module -module-name Multi -o %t/multi-file-3.swiftmodule %s %S/Inputs/multi-file-nested-types.swift -primary-file %S/Inputs/multi-file-nested-types-extensions.swift // RUN: %target-swift-frontend -emit-module -module-name Multi %t/multi-file.swiftmodule %t/multi-file-2.swiftmodule %t/multi-file-3.swiftmodule -o %t -print-stats 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -emit-module -module-name Multi %t/multi-file-2.swiftmodule %t/multi-file.swiftmodule %t/multi-file-3.swiftmodule -o %t -print-stats 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -emit-module -module-name Multi %t/multi-file-2.swiftmodule %t/multi-file-3.swiftmodule %t/multi-file.swiftmodule -o %t -print-stats 2>&1 | %FileCheck %s // CHECK: Statistics // CHECK: 1 Serialization - # of same-module nested types resolved without lookup // Note the Optional here and below; this was once necessary to produce a crash. // Without it, the type of the parameter is initialized "early" enough to not // cause issues. public func useTypes(_: Outer.Callback?) {} extension Outer { public typealias Callback = (Outer.InnerFromExtension) -> Void public func useTypes(_: Outer.Callback?) {} }
75
201
0.744242
d547a4cc6777d7340530c9a72deea526dfc5a73d
4,964
import UIKit final public class NavigationTransitionsHandlerImpl: AnimatingTransitionsHandler { fileprivate weak var navigationController: UINavigationController? public init(navigationController: UINavigationController, transitionsCoordinator: TransitionsCoordinator) { self.navigationController = navigationController super.init(transitionsCoordinator: transitionsCoordinator) } // MARK: - TransitionAnimationsLauncher override public func launchPresentationAnimation(launchingContextBox: inout PresentationAnimationLaunchingContextBox) { switch launchingContextBox { case .modal: super.launchPresentationAnimation(launchingContextBox: &launchingContextBox) case .modalNavigation: super.launchPresentationAnimation(launchingContextBox: &launchingContextBox) case .modalEndpointNavigation: super.launchPresentationAnimation(launchingContextBox: &launchingContextBox) case .modalMasterDetail: super.launchPresentationAnimation(launchingContextBox: &launchingContextBox) case .push(var launchingContext): guard let navigationController = navigationController else { marshrouteDebugPrint("no `UINavigationController` to `pushViewController:animated`"); return } // `Push` could be forwarded to a topmost `UINavigationController`, // so we should pass our navigation controller launchingContext.navigationController = navigationController let pushAnimationContext = PushAnimationContext( pushAnimationLaunchingContext: launchingContext ) if let animationContext = pushAnimationContext { launchingContext.animator.animatePerformingTransition(animationContext: animationContext) } launchingContextBox = .push(launchingContext: launchingContext) case .popover: super.launchPresentationAnimation(launchingContextBox: &launchingContextBox) case .popoverNavigation: super.launchPresentationAnimation(launchingContextBox: &launchingContextBox) } } override public func launchDismissalAnimation(launchingContextBox: DismissalAnimationLaunchingContextBox) { switch launchingContextBox { case .modal: super.launchDismissalAnimation(launchingContextBox: launchingContextBox) case .modalNavigation: super.launchDismissalAnimation(launchingContextBox: launchingContextBox) case .modalEndpointNavigation: super.launchDismissalAnimation(launchingContextBox: launchingContextBox) case .modalMasterDetail: super.launchDismissalAnimation(launchingContextBox: launchingContextBox) case .pop: super.launchDismissalAnimation(launchingContextBox: launchingContextBox) case .popover: super.launchDismissalAnimation(launchingContextBox: launchingContextBox) case .popoverNavigation: super.launchDismissalAnimation(launchingContextBox: launchingContextBox) } } override public func launchResettingAnimation(launchingContextBox: inout ResettingAnimationLaunchingContextBox) { switch launchingContextBox { case .settingNavigationRoot: super.launchResettingAnimation(launchingContextBox: &launchingContextBox) case .resettingNavigationRoot(var launchingContext): guard let navigationController = navigationController else { marshrouteDebugPrint("no `UINavigationController` to `setViewControllers:animated`"); return } // `ResetNavigation` is usually done in place, where the `UINavigationController` is unreachable, // so we should pass our navigation controller launchingContext.navigationController = navigationController let resettingAnimationContext = ResettingNavigationAnimationContext( resettingAnimationLaunchingContext: launchingContext ) if let animationContext = resettingAnimationContext { launchingContext.animator.animateResettingWithTransition(animationContext: animationContext) } launchingContextBox = .resettingNavigationRoot(launchingContext: launchingContext) case .registering: super.launchResettingAnimation(launchingContextBox: &launchingContextBox) case .registeringEndpointNavigation: super.launchResettingAnimation(launchingContextBox: &launchingContextBox) } } }
43.929204
121
0.680298
db78d9aa151de1706656f95810f1e47e2974995f
298
import UIKit internal extension Presenter { internal func addController(presentation:PresentationProtocol) { guard let controller:UIViewController = presentation.controller else { return } self.addChildViewController(controller) } }
22.923077
69
0.657718
f4171cbb6c9800019ecbfee7f604cc5370af0e66
1,351
// // AppDelegate.swift // Swift News // // Created by Chenguo Yan on 2020-10-04. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.513514
179
0.745374
e45b005a64e8ff3bd67dbaa9a64b65819507d615
5,761
/* See LICENSE folder for this sample’s licensing information. Abstract: A view presented to the user once they order a smoothie, and when it's ready to be picked up. */ import SwiftUI struct OrderPlacedView: View { @EnvironmentObject private var model: FrutaModel #if APPCLIP @Binding var presentingAppStoreOverlay: Bool #endif var orderReady: Bool { guard let order = model.order else { return false } return order.isReady } var shouldAnnotate: Bool { #if APPCLIP if presentingAppStoreOverlay { return true } #endif return !model.hasAccount } var blurView: some View { #if os(iOS) return VisualEffectBlur(blurStyle: .systemUltraThinMaterial) #else return VisualEffectBlur() #endif } var signUpButton: some View { SignInWithAppleButton(.signUp, onRequest: { _ in }, onCompletion: model.authorizeUser) .frame(minWidth: 100, maxWidth: 400) .padding(.horizontal, 20) } var body: some View { VStack(spacing: 0) { Spacer() FlipView(visibleSide: orderReady ? .back : .front) { Card( title: "Thank you for your order!".uppercased(), subtitle: "We will notify you when your order is ready." ) } back: { Card( title: "Your smoothie is ready!".uppercased(), subtitle: "\(model.order?.smoothie.title ?? "Your smoothie") is ready to be picked up." ) } .animation(.flipCard, value: orderReady) .padding() Spacer() if shouldAnnotate { VStack { if !model.hasAccount { Text("Sign up to get rewards!") .font(Font.headline.bold()) #if os(iOS) signUpButton .frame(height: 45) #else signUpButton #endif } else { #if APPCLIP if presentingAppStoreOverlay { Text("Get the full smoothie experience!") .font(Font.title2.bold()) .padding(.top, 15) .padding(.bottom, 150) } #endif } } .padding() .frame(maxWidth: .infinity) .background( blurView .opacity(orderReady ? 1 : 0) .padding(.bottom, -100) .edgesIgnoringSafeArea(.all) ) } } .onChange(of: model.hasAccount) { _ in #if APPCLIP if model.hasAccount { presentingAppStoreOverlay = true } #endif } .frame(maxWidth: .infinity, maxHeight: .infinity) .background( ZStack(alignment: .center) { if let order = model.order { order.smoothie.image .resizable() .aspectRatio(contentMode: .fill) } else { Color("order-placed-background") } blurView .opacity(model.order!.isReady ? 0 : 1) } .edgesIgnoringSafeArea(.all) ) .animation(.spring(response: 0.25, dampingFraction: 1), value: orderReady) .animation(.spring(response: 0.25, dampingFraction: 1), value: model.hasAccount) .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 4) { self.model.orderReadyForPickup() } #if APPCLIP if model.hasAccount { presentingAppStoreOverlay = true } #endif } } struct Card: View { var title: String var subtitle: String var body: some View { Circle() .fill(BackgroundStyle()) .overlay( VStack(spacing: 16) { Text(title) .font(Font.title.bold()) .layoutPriority(1) Text(subtitle) .font(.system(.headline, design: .rounded)) .foregroundColor(.secondary) } .multilineTextAlignment(.center) .padding(.horizontal, 36) .frame(maxWidth: .infinity, maxHeight: .infinity) ) .frame(width: 300, height: 300) } } } struct OrderPlacedView_Previews: PreviewProvider { static let orderReady: FrutaModel = { let model = FrutaModel() model.orderSmoothie(Smoothie.berryBlue) model.orderReadyForPickup() return model }() static let orderNotReady: FrutaModel = { let model = FrutaModel() model.orderSmoothie(Smoothie.berryBlue) return model }() static var previews: some View { Group { #if !APPCLIP OrderPlacedView() .environmentObject(orderNotReady) OrderPlacedView() .environmentObject(orderReady) #endif } } }
31.653846
107
0.455997
0172f4bff2598ef002e33e3122ecc5e4d8428c9e
1,792
import Ably import SwiftUI struct ContentView: View { @State var showDeviceDetailsAlert = false @State var deviceDetails: ARTDeviceDetails? @State var deviceDetailsError: ARTErrorInfo? var body: some View { VStack { Spacer() Button("Activate") { AblyHelper.shared.activatePush() } .padding() Button("Dectivate") { AblyHelper.shared.deactivatePush() } .padding() Button("Print Token") { AblyHelper.shared.printIdentityToken() } .padding() Button("Device Details") { AblyHelper.shared.getDeviceDetails { details, error in deviceDetails = details deviceDetailsError = error showDeviceDetailsAlert = true } } .alert(isPresented: $showDeviceDetailsAlert) { if deviceDetails != nil { return Alert(title: Text("Device Details"), message: Text("\(deviceDetails!)")) } else if deviceDetailsError != nil { return Alert(title: Text("Device Details Error"), message: Text("\(deviceDetailsError!)")) } return Alert(title: Text("Device Details Error"), message: Text("Unknown result.")) } .padding() Button("Send Push") { AblyHelper.shared.sendAdminPush(title: "Hello", body: "This push was sent with deviceId") } .padding() Spacer() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
32
110
0.515067
e6cf5f21c98e18da9949873897f2a27cd609c8ec
12,835
// // AnyListController+Cpf.swift // ListController // // Created by Aaron on 2021/5/13. // import UIKit import CPFChain // MARK: - Base public extension Cpf where Base: AnyListController { @discardableResult func sectionCount(_ closour: @escaping () -> Int) -> Self { base.sectionCount(with: closour) return self } @discardableResult func itemList(_ closour: @escaping (Int) -> [Base.Item]) -> Self { base.itemList(with: closour) return self } @discardableResult func itemLists(_ data: [[Base.Item]]) -> Self { base.sectionCount { () -> Int in data.count } base.itemList { (section) -> [Base.Item] in guard 0..<data.endIndex ~= section else { return [] } return data[section] } return self } @discardableResult func itemList(_ data: [Base.Item]) -> Self { base.sectionCount { () -> Int in return 1 } base.itemList { (section) -> [Base.Item] in return data } return self } @discardableResult func cellIdentifier(_ closour: @escaping (IndexPath, Base.Item) -> String) -> Self { base.cellIdentifier(with: closour) return self } @discardableResult func itemDidSelected(_ closour: @escaping (IndexPath, Base.Item) -> Void) -> Self { base.itemDidSelected(with: closour) return self } @discardableResult func scrolled(_ closour: @escaping (UIScrollView) -> Void) -> Self { base.scrolled(with: closour) return self } } // MARK: - Selectable public extension Cpf where Base: AnyListController { @discardableResult func itemShouldHighlight(_ closour: @escaping (IndexPath, Base.Item) -> Bool) -> Self { base.itemShouldHighlight(with: closour) return self } @discardableResult func itemDidHighlight(_ closour: @escaping (IndexPath, Base.Item) -> Void) -> Self { base.itemDidHighlight(with: closour) return self } @discardableResult func itemDidUnHighlight(_ closour: @escaping (IndexPath, Base.Item) -> Void) -> Self { base.itemDidUnHighlight(with: closour) return self } @discardableResult func itemShouldSelect(_ closour: @escaping (IndexPath, Base.Item) -> Bool) -> Self { base.itemShouldSelect(with: closour) return self } func itemShouldDeselect(_ closour: @escaping (IndexPath, Base.Item) -> Bool) -> Self { base.itemShouldDeselect(with: closour) return self } @discardableResult func itemDidDeselected(_ closour: @escaping (IndexPath, Base.Item) -> Void) -> Self { base.itemDidDeselected(with: closour) return self } } // MARK: - Supplementary public extension Cpf where Base: AnyListController { @discardableResult func headerIdentifier(_ closour: @escaping (IndexPath) -> String) -> Self { base.headerIdentifier(with: closour) return self } @discardableResult func footerIdentifier(_ closour: @escaping (IndexPath) -> String) -> Self { base.footerIdentifier(with: closour) return self } } extension AnyListController where ListView: UICollectionView { fileprivate func validateRegisterViews() { configurers.forEach { validateRegisterView(with: $0) } } fileprivate func validateRegisterView(with configurer: AnyListComponentConfigurer) { for configurer in configurers { switch configurer.type { case .cell: listView?.register(configurer.viewClass, forCellWithReuseIdentifier: configurer.id) case .supplementary(let type): switch type { case .header: listView?.register(configurer.viewClass, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: configurer.id) case .footer: listView?.register(configurer.viewClass, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: configurer.id) } } } } } extension AnyListController where ListView: UITableView { fileprivate func validateRegisterViews() { configurers.forEach { validateRegisterView(with: $0) } } fileprivate func validateRegisterView(with configurer: AnyListComponentConfigurer) { switch configurer.type { case .cell: listView?.register(configurer.viewClass, forCellReuseIdentifier: configurer.id) case .supplementary(let type): switch type { case .header: listView?.register(configurer.viewClass, forHeaderFooterViewReuseIdentifier: configurer.id) case .footer: listView?.register(configurer.viewClass, forHeaderFooterViewReuseIdentifier: configurer.id) } } } } public extension Cpf where Base: AnyListController, Base.ListView: UICollectionView { @discardableResult func link(_ listView: Base.ListView) -> Self { base.link(listView) base.validateRegisterViews() return self } @discardableResult func register<Cell: UICollectionViewCell>( cell cellClass: Cell.Type, for identifier: String? = nil, configure: @escaping (Cell, IndexPath, Base.Item) -> Void) -> Self { let configurer = CollectionCellConfigurer<Cell, Base.Item>( id: identifier ?? String(describing: Cell.self), action: configure ) // Note: 注册同一个类型,同一个Id时,仅最后一个生效,前面重复的configurer会被移除 base.configurers.removeAll(where: { $0.id == configurer.id && $0.type == configurer.type }) base.configurers.append(configurer) base.validateRegisterView(with: configurer) base.enableConfiguring(of: .cell) return self } } public extension Cpf where Base: AnyListController, Base.ListView: UICollectionView { @discardableResult func register<View: UICollectionReusableView>( type: ListComponentType.SupplementaryType, view cellClass: View.Type, for identifier: String? = nil, configure: @escaping (View, IndexPath) -> Void) -> Self { let configurer = CollectionSupplementaryConfigurer<View>( type: .supplementary(type), id: identifier ?? String(describing: View.self), action: configure ) // Note: 注册同一个类型,同一个Id时,仅最后一个生效,前面重复的configurer会被移除 base.configurers.removeAll(where: { $0.id == configurer.id && $0.type == configurer.type }) base.configurers.append(configurer) base.validateRegisterView(with: configurer) base.enableConfiguring(of: .supplementary(type)) return self } } public extension Cpf where Base: AnyListController, Base.ListView: UITableView { @discardableResult func link(_ listView: Base.ListView) -> Self { base.link(listView) base.validateRegisterViews() return self } @discardableResult func register<Cell: UITableViewCell>( cell cellClass: Cell.Type, for identifier: String? = nil, config: @escaping (Cell, IndexPath, Base.Item) -> Void) -> Self { let configurer = TableCellConfigurer<Cell, Base.Item>( id: identifier ?? String(describing: Cell.self), action: config ) // Note: 注册同一个类型,同一个Id时,仅最后一个生效,前面重复的configurer会被移除 base.configurers.removeAll(where: { $0.id == configurer.id && $0.type == configurer.type }) base.configurers.append(configurer) base.validateRegisterView(with: configurer) base.enableConfiguring(of: .cell) return self } } public extension Cpf where Base: AnyListController, Base.ListView: UITableView { @discardableResult func register<View: UITableViewHeaderFooterView>( type: ListComponentType.SupplementaryType, view cellClass: View.Type, for identifier: String? = nil, configure: @escaping (View, IndexPath) -> Void) -> Self { let configurer = TableSupplementaryConfigurer<View>( type: .supplementary(type), id: identifier ?? String(describing: View.self), action: configure ) // Note: 注册同一个类型,同一个Id时,仅最后一个生效,前面重复的configurer会被移除 base.configurers.removeAll(where: { $0.id == configurer.id && $0.type == configurer.type }) base.configurers.append(configurer) base.validateRegisterView(with: configurer) base.enableConfiguring(of: .supplementary(type)) return self } } // MARK: - Layout public extension Cpf where Base: AnyListController, Base.ListView: UICollectionView { @discardableResult func cellSize(_ closour: @escaping (IndexPath, Base.Item) -> CGSize) -> Self { base.cellSize(with: closour) return self } @discardableResult func sectionInsets(_ closour: @escaping (Int) -> UIEdgeInsets) -> Self { base.sectionInsets(with: closour) return self } @discardableResult func lineSpacing(_ closour: @escaping (Int) -> CGFloat) -> Self { base.lineSpacing(with: closour) return self } @discardableResult func interitemSpacing(_ closour: @escaping (Int) -> CGFloat) -> Self { base.interitemSpacing(with: closour) return self } @discardableResult func headerSize(_ closour: @escaping (Int) -> CGSize) -> Self { base.headerSize(with: closour) return self } @discardableResult func footerSize(_ closour: @escaping (Int) -> CGSize) -> Self { base.footerSize(with: closour) return self } } public extension Cpf where Base: AnyListController, Base.ListView: UITableView { @discardableResult func rowHeight(_ closour: @escaping (IndexPath, Base.Item) -> CGFloat) -> Self { base.rowHeight(with: closour) return self } @discardableResult func headerHeight(_ closour: @escaping (Int) -> CGFloat) -> Self { base.headerHeight(with: closour) return self } @discardableResult func footerHeight(_ closour: @escaping (Int) -> CGFloat) -> Self { base.footerHeight(with: closour) return self } } // MARK: - Scrollable public extension Cpf where Base: AnyListController, Base.ListView: UIScrollView { @discardableResult func willBeginDecelerating(_ closour: @escaping (UIScrollView) -> Void) -> Self { base.willBeginDecelerating(with: closour) return self } @discardableResult func didEndDecelerating(_ closour: @escaping (UIScrollView) -> Void) -> Self { base.didEndDecelerating(with: closour) return self } @discardableResult func willBeginDragging(_ closour: @escaping (UIScrollView) -> Void) -> Self { base.willBeginDragging(with: closour) return self } @discardableResult func willEndDragging(_ closour: @escaping (UIScrollView, CGPoint, UnsafeMutablePointer<CGPoint>?) -> Void) -> Self { base.willEndDragging(with: closour) return self } @discardableResult func didEndDragging(_ closour: @escaping (UIScrollView, Bool) -> Void) -> Self { base.didEndDragging(with: closour) return self } @discardableResult func didEndScrollingAnimation(_ closour: @escaping (UIScrollView) -> Void) -> Self { base.didEndScrollingAnimation(with: closour) return self } @discardableResult func shouldScrollToTop(_ closour: @escaping (UIScrollView) -> Bool) -> Self { base.shouldScrollToTop(with: closour) return self } @discardableResult func didScrollToTop(_ closour: @escaping (UIScrollView) -> Void) -> Self { base.didScrollToTop(with: closour) return self } @discardableResult func didZoom(_ closour: @escaping (UIScrollView) -> Void) -> Self { base.didZoom(with: closour) return self } @discardableResult func viewForZooming(_ closour: @escaping (UIScrollView) -> UIView?) -> Self { base.viewForZooming(with: closour) return self } @discardableResult func willBeginZooming(_ closour: @escaping (UIScrollView, UIView?) -> Void) -> Self { base.willBeginZooming(with: closour) return self } @discardableResult func didEndZooming(_ closour: @escaping (UIScrollView, UIView?, CGFloat) -> Void) -> Self { base.didEndZooming(with: closour) return self } } extension NSProxy: CpfCompatible {}
32.16792
167
0.638255
d5cb457354cd25c715f6e755cf264b2291d22567
2,154
// // AppDelegate.swift // RPPullDownToRefresh // // Created by Francesco on 08/04/2015. // Copyright (c) 2015 Francesco. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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:. } }
45.829787
285
0.755339
eba12c498a8afc823d3ed4f607ed0d7084f6e51c
1,230
// // IndexPathSet.swift // CollectionView // // Created by Wesley Byrne on 2/27/18. // Copyright © 2018 Noun Project. All rights reserved. // import Foundation struct IndexPathSet: Sequence { typealias Element = IndexPath private var storage = [Int: IndexSet]() typealias Iterator = AnyIterator<IndexPath> func makeIterator() -> Iterator { var s: Int = 0 var data = storage.sorted { (a, b) -> Bool in return a.key < b.key } return AnyIterator { if s >= data.count - 1 { return nil } if let v = data[s].value. if let v = data guard let c = self.storage[s] else { return nil } if let e = c.last return IndexPath() } } mutating func insert(_ indexPath: IndexPath) { if self.storage[indexPath._section] == nil { self.storage[indexPath._item] = IndexSet(integer: indexPath._item) } else { self.storage[indexPath._section]!.insert(indexPath._item) } } func contains(_ indexPath: IndexPath) -> Bool { return storage[indexPath._section]?.contains(indexPath._item) == true } }
26.170213
78
0.566667
163ff995172f6e67785e47f8ddae446630826b30
109
while !isOnClosedSwitch { while isBlocked { turnRight() } moveForward() } toggleSwitch()
13.625
25
0.614679
612eafd29b4a9ed82b93287c126eb8a0d6057064
976
// // ImageViewController.swift // Level // // Created by Ihor Myroniuk on 8/14/18. // Copyright © 2018 Brander. All rights reserved. // import UIKit open class AUIEmptyImageViewController: AUIEmptyViewController, AUIImageViewController { // MARK: ImageView open var imageView: UIImageView? { set { view = newValue } get { return view as? UIImageView } } open override func setupView() { super.setupView() setupImageView() } open func setupImageView() { imageView?.image = image } open override func unsetupView() { super.unsetupView() unsetupImageView() } open func unsetupImageView() { imageView?.image = image } // MARK: State open var image: UIImage? { didSet { didSetImage() } } open func didSetImage() { imageView?.image = image } }
18.074074
88
0.558402
4b841f2ed7d67e1604408da63d01172685249ab1
3,952
// // DeviceUtils.swift // PresentIO // // Created by Gonçalo Borrêga on 01/03/15. // Copyright (c) 2015 Borrega. All rights reserved. // import Foundation import CoreMediaIO import Cocoa import AVKit import AVFoundation enum DeviceType { case iPhone case iPad } enum DeviceOrientation { case Portrait case Landscape } class DeviceUtils { var type: DeviceType var skinSize: NSSize! //video dimensions var skin = "Skin" var orientation = DeviceOrientation.Portrait var videDimensions: CMVideoDimensions = CMVideoDimensions(width: 0,height: 0) { didSet { orientation = videDimensions.width > videDimensions.height ? .Landscape : .Portrait } } init(deviceType:DeviceType) { self.type = deviceType self.skinSize = getSkinSize() switch deviceType { case .iPhone: skin = "Skin" case .iPad: skin = "Skin_iPad" } } class func initWithDimensions(dimensions:CMVideoDimensions) -> DeviceUtils { var device : DeviceUtils if((dimensions.width == 1024 && dimensions.height == 768) || (dimensions.width == 768 && dimensions.height == 1024) || (dimensions.width == 900 && dimensions.height == 1200) || (dimensions.width == 1200 && dimensions.height == 900) || (dimensions.width == 1200 && dimensions.height == 1600) || (dimensions.width == 1600 && dimensions.height == 1200)) { device = DeviceUtils(deviceType: .iPad) } else { device = DeviceUtils(deviceType: .iPhone) } device.videDimensions = dimensions return device } func getSkinDeviceImage() -> String { let imgLandscape = self.orientation == .Landscape ? "_landscape" : "" let imgtype = self.type == .iPad ? "iPad" : "iphone6" return "\(imgtype)_white\(imgLandscape)" } func getSkinSize() -> NSSize { var size : NSSize switch self.type { case .iPhone: size = NSSize(width: 350,height: 700) //640x1136 (iPhone5) case .iPad: size = NSSize(width: 435,height: 646) // 768x1024 (ipad mini) } return self.orientation == .Portrait ? NSSize(width: size.width, height: size.height) : NSSize(width: size.height, height: size.width) } func getFrame() -> CGRect { return CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: skinSize.width, height: skinSize.height)) } func getWindowSize() -> NSSize { //return NSSize(width: max(skinSize.width, skinSize.height), height: max(skinSize.width, skinSize.height)) if(self.orientation == .Portrait) { return NSSize(width: skinSize.width, height: skinSize.height) } else { return NSSize(width: skinSize.height, height: skinSize.width) } } class func getCenteredRect(windowSize : NSSize, screenFrame: NSRect) -> NSRect{ let origin = NSPoint( x: screenFrame.width / 2 - windowSize.width / 2, y: screenFrame.height / 2 - windowSize.height / 2 ) return NSRect(origin: origin, size: windowSize) } class func registerForScreenCaptureDevices() { var prop : CMIOObjectPropertyAddress = CMIOObjectPropertyAddress( mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices), mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal), mElement: CMIOObjectPropertyElement(kCMIOObjectPropertyElementMaster)) var allow:UInt32 = 1 CMIOObjectSetPropertyData( CMIOObjectID(kCMIOObjectSystemObject), &prop, 0, nil, UInt32(MemoryLayout.size(ofValue:allow)), &allow) } }
31.11811
114
0.601721
8fe82dcbe42f40bb00076d74022bc87b565744b9
415
// // TransactionFeeRequest+Encoding.swift // ZKSync // // Created by Eugene Belyakov on 08/01/2021. // import Foundation extension TransactionFeeRequest: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(transactionType) try container.encode(address) try container.encode(tokenIdentifier) } }
21.842105
52
0.703614
14d003e2c286d67bea07623351f5ea13d57c8ed6
2,040
// // RewriteRule+Matches.swift // StubPlay // // Created by Yoo-Jin Lee on 8/5/21. // Copyright © 2021 Mokten Pty Ltd. All rights reserved. // import Foundation extension RewriteRule { static func doesNotMatch(key: String?, matcher: String?) -> Bool { guard let key = key else { return false } if key.contains("*") { if let matcher = matcher, matcher.range(of: key, options: .regularExpression) == nil { return true } } else { if let matcher = matcher, matcher != key { return true } } return false } public func matches(_ request: Request) -> Bool { let requestUrl = request.url var isMatch = false if let method = method { guard request.method == method else { return false } isMatch = true } if let host = host { if RewriteRule.doesNotMatch(key: host, matcher: requestUrl.host) { return false } isMatch = true } if let path = path { if RewriteRule.doesNotMatch(key: path, matcher: requestUrl.path) { return false } isMatch = true } if let params = params { if RewriteRule.doesNotMatch(key: params, matcher: requestUrl.query) { return false } isMatch = true } if let body = body { if RewriteRule.doesNotMatch(key: body, matcher: request.body) { return false } isMatch = true } if let headers = headers, let requestHeaders = request.headers, !requestHeaders.isEmpty { for (key, value) in headers { guard let requestValue = requestHeaders[key] else { return false } if RewriteRule.doesNotMatch(key: value, matcher: requestValue) { return false } } isMatch = true } return isMatch } }
30
113
0.527941
3a6b1a12b18df0056a32f01be7ed2070fe296e89
42,516
// // ZLCustomCamera.swift // ZLPhotoBrowser // // Created by long on 2020/8/11. // // Copyright (c) 2020 Long Zhang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import AVFoundation import CoreMotion open class ZLCustomCamera: UIViewController, CAAnimationDelegate { struct Layout { static let bottomViewH: CGFloat = 150 static let largeCircleRadius: CGFloat = 85 static let smallCircleRadius: CGFloat = 62 static let largeCircleRecordScale: CGFloat = 1.2 static let smallCircleRecordScale: CGFloat = 0.7 } @objc public var takeDoneBlock: ( (UIImage?, URL?) -> Void )? @objc public var cancelBlock: ( () -> Void )? public lazy var tipsLabel = UILabel() public lazy var bottomView = UIView() public lazy var largeCircleView: UIVisualEffectView = { if #available(iOS 13.0, *) { return UIVisualEffectView(effect: UIBlurEffect(style: .systemThinMaterialLight)) } else { return UIVisualEffectView(effect: UIBlurEffect(style: .light)) } }() public lazy var smallCircleView = UIView() public lazy var animateLayer = CAShapeLayer() public lazy var retakeBtn = UIButton(type: .custom) public lazy var doneBtn = UIButton(type: .custom) public lazy var dismissBtn = UIButton(type: .custom) public lazy var switchCameraBtn = UIButton(type: .custom) public lazy var focusCursorView = UIImageView(image: getImage("zl_focus")) public lazy var takedImageView = UIImageView() var hideTipsTimer: Timer? var takedImage: UIImage? var videoUrl: URL? var motionManager: CMMotionManager? var orientation: AVCaptureVideoOrientation = .portrait let sessionQueue = DispatchQueue(label: "com.zl.camera.sessionQueue") let session = AVCaptureSession() var videoInput: AVCaptureDeviceInput? var imageOutput: AVCapturePhotoOutput! var movieFileOutput: AVCaptureMovieFileOutput! var previewLayer: AVCaptureVideoPreviewLayer? var recordVideoPlayerLayer: AVPlayerLayer? var cameraConfigureFinish = false var layoutOK = false var dragStart = false var viewDidAppearCount = 0 var restartRecordAfterSwitchCamera = false var cacheVideoOrientation: AVCaptureVideoOrientation = .portrait var recordUrls: [URL] = [] var microPhontIsAvailable = true var focusCursorTapGes = UITapGestureRecognizer() var cameraFocusPanGes: UIPanGestureRecognizer? var recordLongGes: UILongPressGestureRecognizer? // 仅支持竖屏 public override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } public override var prefersStatusBarHidden: Bool { return true } deinit { zl_debugPrint("ZLCustomCamera deinit") self.cleanTimer() try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) } @objc public init() { super.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .fullScreen } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() self.setupUI() if !UIImagePickerController.isSourceTypeAvailable(.camera) { return } self.observerDeviceMotion() AVCaptureDevice.requestAccess(for: .video) { (videoGranted) in guard videoGranted else { ZLMainAsync(after: 1) { self.showAlertAndDismissAfterDoneAction(message: String(format: localLanguageTextValue(.noCameraAuthority), getAppName()), type: .camera) } return } guard ZLPhotoConfiguration.default().allowRecordVideo else { self.addNotification() return } AVCaptureDevice.requestAccess(for: .audio) { (audioGranted) in self.addNotification() if !audioGranted { ZLMainAsync(after: 1) { self.showNoMicrophoneAuthorityAlert() } } } } if ZLPhotoConfiguration.default().allowRecordVideo { do { try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .videoRecording, options: .mixWithOthers) try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation) } catch { let err = error as NSError if err.code == AVAudioSession.ErrorCode.insufficientPriority.rawValue || err.code == AVAudioSession.ErrorCode.isBusy.rawValue { self.microPhontIsAvailable = false } } } self.setupCamera() self.sessionQueue.async { self.session.startRunning() } } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !UIImagePickerController.isSourceTypeAvailable(.camera) { showAlertAndDismissAfterDoneAction(message: localLanguageTextValue(.cameraUnavailable), type: .camera) } else if !ZLPhotoConfiguration.default().allowTakePhoto, !ZLPhotoConfiguration.default().allowRecordVideo { #if DEBUG fatalError("Error configuration of camera") #else showAlertAndDismissAfterDoneAction(message: "Error configuration of camera", type: nil) #endif } else if self.cameraConfigureFinish, self.viewDidAppearCount == 0 { self.showTipsLabel(animate: true) let animation = CABasicAnimation(keyPath: "opacity") animation.toValue = 1 animation.duration = 0.15 animation.fillMode = .forwards animation.isRemovedOnCompletion = false self.previewLayer?.add(animation, forKey: nil) self.setFocusCusor(point: self.view.center) } self.viewDidAppearCount += 1 } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.motionManager?.stopDeviceMotionUpdates() self.motionManager = nil } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if self.session.isRunning { self.session.stopRunning() } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard !self.layoutOK else { return } self.layoutOK = true var insets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0) if #available(iOS 11.0, *) { insets = self.view.safeAreaInsets } let previewLayerY: CGFloat = deviceSafeAreaInsets().top > 0 ? 20 : 0 self.previewLayer?.frame = CGRect(x: 0, y: previewLayerY, width: self.view.bounds.width, height: self.view.bounds.height) self.recordVideoPlayerLayer?.frame = self.view.bounds self.takedImageView.frame = self.view.bounds self.bottomView.frame = CGRect(x: 0, y: self.view.bounds.height-insets.bottom-ZLCustomCamera.Layout.bottomViewH-50, width: self.view.bounds.width, height: ZLCustomCamera.Layout.bottomViewH) let largeCircleH = ZLCustomCamera.Layout.largeCircleRadius self.largeCircleView.frame = CGRect(x: (self.view.bounds.width-largeCircleH)/2, y: (ZLCustomCamera.Layout.bottomViewH-largeCircleH)/2, width: largeCircleH, height: largeCircleH) let smallCircleH = ZLCustomCamera.Layout.smallCircleRadius self.smallCircleView.frame = CGRect(x: (self.view.bounds.width-smallCircleH)/2, y: (ZLCustomCamera.Layout.bottomViewH-smallCircleH)/2, width: smallCircleH, height: smallCircleH) self.dismissBtn.frame = CGRect(x: 60, y: (ZLCustomCamera.Layout.bottomViewH-25)/2, width: 25, height: 25) let tipsTextHeight = (self.tipsLabel.text ?? " ").boundingRect(font: getFont(14), limitSize: CGSize(width: self.view.bounds.width - 20, height: .greatestFiniteMagnitude)).height self.tipsLabel.frame = CGRect(x: 10, y: self.bottomView.frame.minY - tipsTextHeight, width: self.view.bounds.width - 20, height: tipsTextHeight) self.retakeBtn.frame = CGRect(x: 30, y: insets.top+10, width: 28, height: 28) self.switchCameraBtn.frame = CGRect(x: self.view.bounds.width-30-28, y: insets.top+10, width: 28, height: 28) let doneBtnW = localLanguageTextValue(.done).boundingRect(font: ZLLayout.bottomToolTitleFont, limitSize: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 40)).width + 20 let doneBtnY = self.view.bounds.height - 57 - insets.bottom self.doneBtn.frame = CGRect(x: self.view.bounds.width - doneBtnW - 20, y: doneBtnY, width: doneBtnW, height: ZLLayout.bottomToolBtnH) } func setupUI() { view.backgroundColor = .black takedImageView.backgroundColor = .black takedImageView.isHidden = true takedImageView.contentMode = .scaleAspectFit view.addSubview(takedImageView) focusCursorView.contentMode = .scaleAspectFit focusCursorView.clipsToBounds = true focusCursorView.frame = CGRect(x: 0, y: 0, width: 70, height: 70) focusCursorView.alpha = 0 view.addSubview(focusCursorView) tipsLabel.font = getFont(14) tipsLabel.textColor = .white tipsLabel.textAlignment = .center tipsLabel.numberOfLines = 2 tipsLabel.lineBreakMode = .byWordWrapping tipsLabel.alpha = 0 if ZLPhotoConfiguration.default().allowTakePhoto, ZLPhotoConfiguration.default().allowRecordVideo { tipsLabel.text = localLanguageTextValue(.customCameraTips) } else if ZLPhotoConfiguration.default().allowTakePhoto { tipsLabel.text = localLanguageTextValue(.customCameraTakePhotoTips) } else if ZLPhotoConfiguration.default().allowRecordVideo { tipsLabel.text = localLanguageTextValue(.customCameraRecordVideoTips) } view.addSubview(tipsLabel) view.addSubview(bottomView) dismissBtn.setImage(getImage("zl_arrow_down"), for: .normal) dismissBtn.addTarget(self, action: #selector(dismissBtnClick), for: .touchUpInside) dismissBtn.adjustsImageWhenHighlighted = false dismissBtn.zl_enlargeValidTouchArea(inset: 30) bottomView.addSubview(self.dismissBtn) largeCircleView.layer.masksToBounds = true largeCircleView.layer.cornerRadius = ZLCustomCamera.Layout.largeCircleRadius / 2 bottomView.addSubview(self.largeCircleView) smallCircleView.layer.masksToBounds = true smallCircleView.layer.cornerRadius = ZLCustomCamera.Layout.smallCircleRadius / 2 smallCircleView.isUserInteractionEnabled = false smallCircleView.backgroundColor = .white bottomView.addSubview(self.smallCircleView) let animateLayerRadius = ZLCustomCamera.Layout.largeCircleRadius let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: animateLayerRadius, height: animateLayerRadius), cornerRadius: animateLayerRadius/2) animateLayer.path = path.cgPath animateLayer.strokeColor = UIColor.cameraRecodeProgressColor.cgColor animateLayer.fillColor = UIColor.clear.cgColor animateLayer.lineWidth = 8 var takePictureTap: UITapGestureRecognizer? if ZLPhotoConfiguration.default().allowTakePhoto { takePictureTap = UITapGestureRecognizer(target: self, action: #selector(takePicture)) largeCircleView.addGestureRecognizer(takePictureTap!) } if ZLPhotoConfiguration.default().allowRecordVideo { let longGes = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(_:))) longGes.minimumPressDuration = 0.3 longGes.delegate = self largeCircleView.addGestureRecognizer(longGes) takePictureTap?.require(toFail: longGes) recordLongGes = longGes let panGes = UIPanGestureRecognizer(target: self, action: #selector(adjustCameraFocus(_:))) panGes.delegate = self panGes.maximumNumberOfTouches = 1 largeCircleView.addGestureRecognizer(panGes) cameraFocusPanGes = panGes recordVideoPlayerLayer = AVPlayerLayer() recordVideoPlayerLayer?.backgroundColor = UIColor.black.cgColor recordVideoPlayerLayer?.videoGravity = .resizeAspect recordVideoPlayerLayer?.isHidden = true view.layer.insertSublayer(recordVideoPlayerLayer!, at: 0) NotificationCenter.default.addObserver(self, selector: #selector(recordVideoPlayFinished), name: .AVPlayerItemDidPlayToEndTime, object: nil) } retakeBtn.setImage(getImage("zl_retake"), for: .normal) retakeBtn.addTarget(self, action: #selector(retakeBtnClick), for: .touchUpInside) retakeBtn.isHidden = true retakeBtn.adjustsImageWhenHighlighted = false retakeBtn.zl_enlargeValidTouchArea(inset: 30) view.addSubview(retakeBtn) let cameraCount = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .unspecified).devices.count switchCameraBtn.setImage(getImage("zl_toggle_camera"), for: .normal) switchCameraBtn.addTarget(self, action: #selector(switchCameraBtnClick), for: .touchUpInside) switchCameraBtn.adjustsImageWhenHighlighted = false switchCameraBtn.zl_enlargeValidTouchArea(inset: 30) switchCameraBtn.isHidden = cameraCount <= 1 view.addSubview(switchCameraBtn) doneBtn.titleLabel?.font = ZLLayout.bottomToolTitleFont doneBtn.setTitle(localLanguageTextValue(.done), for: .normal) doneBtn.setTitleColor(.bottomToolViewBtnNormalTitleColor, for: .normal) doneBtn.backgroundColor = .bottomToolViewBtnNormalBgColor doneBtn.addTarget(self, action: #selector(doneBtnClick), for: .touchUpInside) doneBtn.isHidden = true doneBtn.layer.masksToBounds = true doneBtn.layer.cornerRadius = ZLLayout.bottomToolBtnCornerRadius view.addSubview(doneBtn) focusCursorTapGes.addTarget(self, action: #selector(adjustFocusPoint)) focusCursorTapGes.delegate = self view.addGestureRecognizer(focusCursorTapGes) let pinchGes = UIPinchGestureRecognizer(target: self, action: #selector(pinchToAdjustCameraFocus(_:))) view.addGestureRecognizer(pinchGes) } func observerDeviceMotion() { if !Thread.isMainThread { ZLMainAsync { self.observerDeviceMotion() } return } self.motionManager = CMMotionManager() self.motionManager?.deviceMotionUpdateInterval = 0.5 if self.motionManager?.isDeviceMotionAvailable == true { self.motionManager?.startDeviceMotionUpdates(to: OperationQueue.main, withHandler: { (motion, error) in if let _ = motion { self.handleDeviceMotion(motion!) } }) } else { self.motionManager = nil } } func handleDeviceMotion(_ motion: CMDeviceMotion) { let x = motion.gravity.x let y = motion.gravity.y if abs(y) >= abs(x) { if y >= 0 { self.orientation = .portraitUpsideDown } else { self.orientation = .portrait } } else { if x >= 0 { self.orientation = .landscapeLeft } else { self.orientation = .landscapeRight } } } func setupCamera() { guard let backCamera = self.getCamera(position: .back) else { return } guard let input = try? AVCaptureDeviceInput(device: backCamera) else { return } self.session.beginConfiguration() // 相机画面输入流 self.videoInput = input // 照片输出流 self.imageOutput = AVCapturePhotoOutput() let preset = ZLPhotoConfiguration.default().cameraConfiguration.sessionPreset.avSessionPreset if self.session.canSetSessionPreset(preset) { self.session.sessionPreset = preset } else { self.session.sessionPreset = .hd1280x720 } self.movieFileOutput = AVCaptureMovieFileOutput() // 解决视频录制超过10s没有声音的bug self.movieFileOutput.movieFragmentInterval = .invalid // 添加视频输入 if let vi = self.videoInput, self.session.canAddInput(vi) { self.session.addInput(vi) } // 添加音频输入 self.addAudioInput() // 将输出流添加到session if self.session.canAddOutput(self.imageOutput) { self.session.addOutput(self.imageOutput) } if self.session.canAddOutput(self.movieFileOutput) { self.session.addOutput(self.movieFileOutput) } self.session.commitConfiguration() // 预览layer self.previewLayer = AVCaptureVideoPreviewLayer(session: self.session) self.previewLayer?.videoGravity = .resizeAspect self.previewLayer?.opacity = 0 self.view.layer.masksToBounds = true self.view.layer.insertSublayer(self.previewLayer!, at: 0) self.cameraConfigureFinish = true } func getCamera(position: AVCaptureDevice.Position) -> AVCaptureDevice? { let devices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: position).devices for device in devices { if device.position == position { return device } } return nil } func getMicrophone() -> AVCaptureDevice? { return AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone], mediaType: .audio, position: .unspecified).devices.first } func addAudioInput() { guard ZLPhotoConfiguration.default().allowRecordVideo else { return } // 音频输入流 var audioInput: AVCaptureDeviceInput? if let microphone = self.getMicrophone() { audioInput = try? AVCaptureDeviceInput(device: microphone) } guard self.microPhontIsAvailable, let ai = audioInput else { return } self.removeAudioInput() if self.session.isRunning { self.session.beginConfiguration() } if self.session.canAddInput(ai) { self.session.addInput(ai) } if self.session.isRunning { self.session.commitConfiguration() } } func removeAudioInput() { var audioInput: AVCaptureInput? for input in self.session.inputs { if (input as? AVCaptureDeviceInput)?.device.deviceType == .builtInMicrophone { audioInput = input } } guard let ai = audioInput else { return } if self.session.isRunning { self.session.beginConfiguration() } self.session.removeInput(ai) if self.session.isRunning { self.session.commitConfiguration() } } func addNotification() { NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) if ZLPhotoConfiguration.default().allowRecordVideo { NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleAudioSessionInterruption), name: AVAudioSession.interruptionNotification, object: nil) } } func showNoMicrophoneAuthorityAlert() { let alert = UIAlertController(title: nil, message: String(format: localLanguageTextValue(.noMicrophoneAuthority), getAppName()), preferredStyle: .alert) let continueAction = UIAlertAction(title: localLanguageTextValue(.keepRecording), style: .default, handler: nil) let gotoSettingsAction = UIAlertAction(title: localLanguageTextValue(.gotoSettings), style: .default) { (_) in guard let url = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } alert.addAction(continueAction) alert.addAction(gotoSettingsAction) showAlertController(alert) } func showAlertAndDismissAfterDoneAction(message: String, type: ZLNoAuthorityType?) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) let action = UIAlertAction(title: localLanguageTextValue(.done), style: .default) { (_) in self.dismiss(animated: true) { if let t = type { ZLPhotoConfiguration.default().noAuthorityCallback?(t) } } } alert.addAction(action) showAlertController(alert) } func showTipsLabel(animate: Bool) { self.tipsLabel.layer.removeAllAnimations() if animate { UIView.animate(withDuration: 0.25) { self.tipsLabel.alpha = 1 } } else { self.tipsLabel.alpha = 1 } self.startHideTipsLabelTimer() } func hideTipsLabel(animate: Bool) { self.tipsLabel.layer.removeAllAnimations() if animate { UIView.animate(withDuration: 0.25) { self.tipsLabel.alpha = 0 } } else { self.tipsLabel.alpha = 0 } } @objc func hideTipsLabel_timerFunc() { self.cleanTimer() self.hideTipsLabel(animate: true) } func startHideTipsLabelTimer() { self.cleanTimer() self.hideTipsTimer = Timer.scheduledTimer(timeInterval: 3, target: ZLWeakProxy(target: self), selector: #selector(hideTipsLabel_timerFunc), userInfo: nil, repeats: false) RunLoop.current.add(self.hideTipsTimer!, forMode: .common) } func cleanTimer() { self.hideTipsTimer?.invalidate() self.hideTipsTimer = nil } @objc func appWillResignActive() { if self.session.isRunning { self.dismiss(animated: true, completion: nil) } if self.videoUrl != nil, let player = self.recordVideoPlayerLayer?.player { player.pause() } } @objc func appDidBecomeActive() { if self.videoUrl != nil, let player = self.recordVideoPlayerLayer?.player { player.play() } } @objc func handleAudioSessionInterruption(_ notify: Notification) { guard self.recordVideoPlayerLayer?.isHidden == false, let player = self.recordVideoPlayerLayer?.player else { return } guard player.rate == 0 else { return } let type = notify.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt let option = notify.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt if type == AVAudioSession.InterruptionType.ended.rawValue, option == AVAudioSession.InterruptionOptions.shouldResume.rawValue { player.play() } } @objc func dismissBtnClick() { self.dismiss(animated: true) { self.cancelBlock?() } } @objc func retakeBtnClick() { self.session.startRunning() self.resetSubViewStatus() self.takedImage = nil self.stopRecordAnimation() if let url = self.videoUrl { self.recordVideoPlayerLayer?.player?.pause() self.recordVideoPlayerLayer?.player = nil self.recordVideoPlayerLayer?.isHidden = true self.videoUrl = nil try? FileManager.default.removeItem(at: url) } } @objc func switchCameraBtnClick() { do { guard !restartRecordAfterSwitchCamera else { return } guard let currInput = videoInput else { return } var newVideoInput: AVCaptureDeviceInput? if currInput.device.position == .back, let front = getCamera(position: .front) { newVideoInput = try AVCaptureDeviceInput(device: front) } else if currInput.device.position == .front, let back = getCamera(position: .back) { newVideoInput = try AVCaptureDeviceInput(device: back) } else { return } if let ni = newVideoInput { session.beginConfiguration() session.removeInput(currInput) if session.canAddInput(ni) { session.addInput(ni) videoInput = ni } else { session.addInput(currInput) } session.commitConfiguration() if movieFileOutput.isRecording { let pauseTime = animateLayer.convertTime(CACurrentMediaTime(), from: nil) animateLayer.speed = 0 animateLayer.timeOffset = pauseTime restartRecordAfterSwitchCamera = true } } } catch { zl_debugPrint("切换摄像头失败 \(error.localizedDescription)") } } @objc func editImage() { guard ZLPhotoConfiguration.default().allowEditImage, let image = self.takedImage else { return } ZLEditImageViewController.showEditImageVC(parentVC: self, image: image) { [weak self] in self?.retakeBtnClick() } completion: { [weak self] (editImage, _) in self?.takedImage = editImage self?.takedImageView.image = editImage self?.doneBtnClick() } } @objc func doneBtnClick() { self.recordVideoPlayerLayer?.player?.pause() // 置为nil会导致卡顿,先注释,不影响内存释放 // self.recordVideoPlayerLayer?.player = nil self.dismiss(animated: true) { self.takeDoneBlock?(self.takedImage, self.videoUrl) } } // 点击拍照 @objc func takePicture() { guard ZLPhotoManager.hasCameraAuthority() else { return } let connection = self.imageOutput.connection(with: .video) connection?.videoOrientation = self.orientation if self.videoInput?.device.position == .front, connection?.isVideoMirroringSupported == true { connection?.isVideoMirrored = true } let setting = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecJPEG]) if self.videoInput?.device.hasFlash == true { setting.flashMode = ZLPhotoConfiguration.default().cameraConfiguration.flashMode.avFlashMode } self.imageOutput.capturePhoto(with: setting, delegate: self) } // 长按录像 @objc func longPressAction(_ longGes: UILongPressGestureRecognizer) { if longGes.state == .began { guard ZLPhotoManager.hasCameraAuthority(), ZLPhotoManager.hasMicrophoneAuthority() else { return } self.startRecord() } else if longGes.state == .cancelled || longGes.state == .ended { self.finishRecord() } } // 调整焦点 @objc func adjustFocusPoint(_ tap: UITapGestureRecognizer) { guard self.session.isRunning else { return } let point = tap.location(in: self.view) if point.y > self.bottomView.frame.minY - 30 { return } self.setFocusCusor(point: point) } func setFocusCusor(point: CGPoint) { self.focusCursorView.center = point self.focusCursorView.layer.removeAllAnimations() self.focusCursorView.alpha = 1 self.focusCursorView.layer.transform = CATransform3DMakeScale(1.2, 1.2, 1) UIView.animate(withDuration: 0.5, animations: { self.focusCursorView.layer.transform = CATransform3DIdentity }) { (_) in self.focusCursorView.alpha = 0 } // ui坐标转换为摄像头坐标 let cameraPoint = self.previewLayer?.captureDevicePointConverted(fromLayerPoint: point) ?? self.view.center self.focusCamera( mode: ZLPhotoConfiguration.default().cameraConfiguration.focusMode.avFocusMode, exposureMode: ZLPhotoConfiguration.default().cameraConfiguration.exposureMode.avFocusMode, point: cameraPoint ) } // 调整焦距 @objc func adjustCameraFocus(_ pan: UIPanGestureRecognizer) { let convertRect = bottomView.convert(largeCircleView.frame, to: view) let point = pan.location(in: view) if pan.state == .began { dragStart = true startRecord() } else if pan.state == .changed { guard dragStart else { return } let maxZoomFactor = getMaxZoomFactor() var zoomFactor = (convertRect.midY - point.y) / convertRect.midY * maxZoomFactor zoomFactor = max(1, min(zoomFactor, maxZoomFactor)) setVideoZoomFactor(zoomFactor) } else if pan.state == .cancelled || pan.state == .ended { guard dragStart else { return } dragStart = false finishRecord() } } @objc func pinchToAdjustCameraFocus(_ pinch: UIPinchGestureRecognizer) { guard let device = self.videoInput?.device else { return } var zoomFactor = device.videoZoomFactor * pinch.scale zoomFactor = max(1, min(zoomFactor, self.getMaxZoomFactor())) self.setVideoZoomFactor(zoomFactor) pinch.scale = 1 } func getMaxZoomFactor() -> CGFloat { guard let device = videoInput?.device else { return 1 } if #available(iOS 11.0, *) { return device.maxAvailableVideoZoomFactor / 2 } else { return device.activeFormat.videoMaxZoomFactor / 2 } } func setVideoZoomFactor(_ zoomFactor: CGFloat) { guard let device = self.videoInput?.device else { return } do { try device.lockForConfiguration() device.videoZoomFactor = zoomFactor device.unlockForConfiguration() } catch { zl_debugPrint("调整焦距失败 \(error.localizedDescription)") } } func focusCamera(mode: AVCaptureDevice.FocusMode, exposureMode: AVCaptureDevice.ExposureMode, point: CGPoint) { do { guard let device = self.videoInput?.device else { return } try device.lockForConfiguration() if device.isFocusModeSupported(mode) { device.focusMode = mode } if device.isFocusPointOfInterestSupported { device.focusPointOfInterest = point } if device.isExposureModeSupported(exposureMode) { device.exposureMode = exposureMode } if device.isExposurePointOfInterestSupported { device.exposurePointOfInterest = point } device.unlockForConfiguration() } catch { zl_debugPrint("相机聚焦设置失败 \(error.localizedDescription)") } } func startRecord() { guard !self.movieFileOutput.isRecording else { return } self.dismissBtn.isHidden = true let connection = self.movieFileOutput.connection(with: .video) connection?.videoScaleAndCropFactor = 1 if !self.restartRecordAfterSwitchCamera { connection?.videoOrientation = self.orientation self.cacheVideoOrientation = self.orientation } else { connection?.videoOrientation = self.cacheVideoOrientation } // 解决前置摄像头录制视频时候左右颠倒的问题 if self.videoInput?.device.position == .front, connection?.isVideoMirroringSupported == true { // 镜像设置 connection?.isVideoMirrored = true } let url = URL(fileURLWithPath: ZLVideoManager.getVideoExportFilePath()) self.movieFileOutput.startRecording(to: url, recordingDelegate: self) } func finishRecord() { guard self.movieFileOutput.isRecording else { return } try? AVAudioSession.sharedInstance().setCategory(.playback) self.movieFileOutput.stopRecording() self.stopRecordAnimation() } func startRecordAnimation() { UIView.animate(withDuration: 0.1, animations: { self.largeCircleView.layer.transform = CATransform3DScale(CATransform3DIdentity, ZLCustomCamera.Layout.largeCircleRecordScale, ZLCustomCamera.Layout.largeCircleRecordScale, 1) self.smallCircleView.layer.transform = CATransform3DScale(CATransform3DIdentity, ZLCustomCamera.Layout.smallCircleRecordScale, ZLCustomCamera.Layout.smallCircleRecordScale, 1) }) { (_) in self.largeCircleView.layer.addSublayer(self.animateLayer) let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = 0 animation.toValue = 1 animation.duration = Double(ZLPhotoConfiguration.default().maxRecordDuration) animation.delegate = self self.animateLayer.add(animation, forKey: nil) } } func stopRecordAnimation() { self.animateLayer.removeFromSuperlayer() self.animateLayer.removeAllAnimations() self.largeCircleView.transform = .identity self.smallCircleView.transform = .identity } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { self.finishRecord() } func resetSubViewStatus() { if self.session.isRunning { self.showTipsLabel(animate: true) self.bottomView.isHidden = false self.dismissBtn.isHidden = false self.switchCameraBtn.isHidden = false self.retakeBtn.isHidden = true self.doneBtn.isHidden = true self.takedImageView.isHidden = true self.takedImage = nil } else { self.hideTipsLabel(animate: false) self.bottomView.isHidden = true self.dismissBtn.isHidden = true self.switchCameraBtn.isHidden = true self.retakeBtn.isHidden = false self.doneBtn.isHidden = false } } func playRecordVideo(fileUrl: URL) { self.recordVideoPlayerLayer?.isHidden = false let player = AVPlayer(url: fileUrl) player.automaticallyWaitsToMinimizeStalling = false self.recordVideoPlayerLayer?.player = player player.play() } @objc func recordVideoPlayFinished() { self.recordVideoPlayerLayer?.player?.seek(to: .zero) self.recordVideoPlayerLayer?.player?.play() } } extension ZLCustomCamera: AVCapturePhotoCaptureDelegate { public func photoOutput(_ output: AVCapturePhotoOutput, willCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings) { DispatchQueue.main.async { self.previewLayer?.opacity = 0 UIView.animate(withDuration: 0.25) { self.previewLayer?.opacity = 1 } } } public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) { ZLMainAsync { if photoSampleBuffer == nil || error != nil { zl_debugPrint("拍照失败 \(error?.localizedDescription ?? "")") return } if let data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: photoSampleBuffer!, previewPhotoSampleBuffer: previewPhotoSampleBuffer) { self.session.stopRunning() self.takedImage = UIImage(data: data)?.fixOrientation() self.takedImageView.image = self.takedImage self.takedImageView.isHidden = false self.resetSubViewStatus() self.editImage() } else { zl_debugPrint("拍照失败,data为空") } } } } extension ZLCustomCamera: AVCaptureFileOutputRecordingDelegate { public func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { if self.restartRecordAfterSwitchCamera { self.restartRecordAfterSwitchCamera = false // 稍微加一个延时,否则切换摄像头后拍摄时间会略小于设置的最大值 ZLMainAsync(after: 0.1) { let pauseTime = self.animateLayer.timeOffset self.animateLayer.speed = 1 self.animateLayer.timeOffset = 0 self.animateLayer.beginTime = 0 let timeSincePause = self.animateLayer.convertTime(CACurrentMediaTime(), from: nil) - pauseTime self.animateLayer.beginTime = timeSincePause } } else { ZLMainAsync { self.startRecordAnimation() } } } public func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { ZLMainAsync { if self.restartRecordAfterSwitchCamera { self.recordUrls.append(outputFileURL) self.startRecord() return } self.recordUrls.append(outputFileURL) var duration: Double = 0 if self.recordUrls.count == 1 { duration = output.recordedDuration.seconds } else { for url in self.recordUrls { let temp = AVAsset(url: url) duration += temp.duration.seconds } } // 重置焦距 self.setVideoZoomFactor(1) if duration < Double(ZLPhotoConfiguration.default().minRecordDuration) { showAlertView(String(format: localLanguageTextValue(.minRecordTimeTips), ZLPhotoConfiguration.default().minRecordDuration), self) self.resetSubViewStatus() self.recordUrls.forEach { try? FileManager.default.removeItem(at: $0) } self.recordUrls.removeAll() return } // 拼接视频 self.session.stopRunning() self.resetSubViewStatus() if self.recordUrls.count > 1 { ZLVideoManager.mergeVideos(fileUrls: self.recordUrls) { [weak self] (url, error) in if let url = url, error == nil { self?.videoUrl = url self?.playRecordVideo(fileUrl: url) } else if let error = error { self?.videoUrl = nil showAlertView(error.localizedDescription, self) } self?.recordUrls.forEach { try? FileManager.default.removeItem(at: $0) } self?.recordUrls.removeAll() } } else { self.videoUrl = outputFileURL self.playRecordVideo(fileUrl: outputFileURL) self.recordUrls.removeAll() } } } } extension ZLCustomCamera: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { let gesTuples: [(UIGestureRecognizer?, UIGestureRecognizer?)] = [(recordLongGes, cameraFocusPanGes), (recordLongGes, focusCursorTapGes), (cameraFocusPanGes, focusCursorTapGes)] let result = gesTuples.map { (ges1, ges2) in return (ges1 == gestureRecognizer && ges2 == otherGestureRecognizer) || (ges2 == otherGestureRecognizer && ges1 == gestureRecognizer) }.filter { $0 == true} return result.count > 0 } }
39.257618
299
0.623295
562398e48b17f49cca1728da22c970d1cedb627d
2,952
// // APModeTableViewController.swift // TuyaAppSDKSample-iOS-Swift // // Copyright (c) 2014-2021 Tuya Inc. (https://developer.tuya.com/) import UIKit import TuyaSmartActivatorKit class APModeTableViewController: UITableViewController { // MARK: - IBOutlet @IBOutlet weak var ssidTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! // MARK: - Property var token: String = "" private var isSuccess = false // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() requestToken() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) stopConfigWifi() } // MARK: - IBAction @IBAction func searchTapped(_ sender: UIBarButtonItem) { startConfiguration() } // MARK: - Private Method private func requestToken() { guard let homeID = Home.current?.homeId else { return } SVProgressHUD.show(withStatus: NSLocalizedString("Requesting for Token", comment: "")) TuyaSmartActivator.sharedInstance()?.getTokenWithHomeId(homeID, success: { [weak self] (token) in guard let self = self else { return } self.token = token ?? "" SVProgressHUD.dismiss() }, failure: { (error) in let errorMessage = error?.localizedDescription ?? "" SVProgressHUD.showError(withStatus: errorMessage) }) } private func startConfiguration() { SVProgressHUD.show(withStatus: NSLocalizedString("Configuring", comment: "")) let ssid = ssidTextField.text ?? "" let password = passwordTextField.text ?? "" TuyaSmartActivator.sharedInstance()?.delegate = self TuyaSmartActivator.sharedInstance()?.startConfigWiFi(TYActivatorModeAP, ssid: ssid, password: password, token: token, timeout: 100) } private func stopConfigWifi() { if !isSuccess { SVProgressHUD.dismiss() } TuyaSmartActivator.sharedInstance()?.delegate = nil TuyaSmartActivator.sharedInstance()?.stopConfigWiFi() } } extension APModeTableViewController: TuyaSmartActivatorDelegate { func activator(_ activator: TuyaSmartActivator!, didReceiveDevice deviceModel: TuyaSmartDeviceModel!, error: Error!) { if deviceModel != nil && error == nil { // Success let name = deviceModel.name ?? NSLocalizedString("Unknown Name", comment: "Unknown name device.") SVProgressHUD.showSuccess(withStatus: NSLocalizedString("Successfully Added \(name)", comment: "Successfully added one device.")) isSuccess = true navigationController?.popViewController(animated: true) } if let error = error { // Error SVProgressHUD.showError(withStatus: error.localizedDescription) } } }
34.325581
141
0.641599
f8c6d968f461a50151bfc2f4b93e4aaf8cce12e9
2,763
// // VerticalViewController.swift // CNChart_Example // // Created by CNOO on 2021/07/27. // Copyright © 2021 CocoaPods. All rights reserved. // import UIKit import CNChart class DetailViewController: UIViewController, CNChartDelegate { @IBOutlet weak var chartView: CNChart! @IBOutlet weak var controlView: UIView! @IBOutlet weak var cellHeightStepper: UIStepper! @IBOutlet var valueLabels: [UILabel]! override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() controlView.layer.cornerRadius = 16 } override func viewDidLoad() { super.viewDidLoad() cellHeightStepper.value = 10 chartView.delegate = self onLoadMore() let chart = CNChart(axis: .horizontal) self.view.addSubview(chart) } @IBAction func onRefresh(_ sender: UIBarButtonItem) { chartView.setClear() count = 1 onLoadMore() } // MARK: - Control properties @IBAction func stepperValueChanged(_ sender: UIStepper) { switch sender.tag { case 0: chartView.cellThickness = CGFloat(sender.value) case 1: chartView.chartDuration = sender.value case 2: chartView.showDuration = sender.value default: chartView.spacing = CGFloat(sender.value) } valueLabels[sender.tag].text = String(format: "%.2f", sender.value) } // MARK: - Text Alignment @IBAction func textAlignmentChanged(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: chartView.labelAlignment = .left case 1: chartView.labelAlignment = .center default: chartView.labelAlignment = .right } } // MARK: - CNChartDelegate private var colors: [UIColor?] = [.red, .green, .blue, .brown, .cyan, .orange, .yellow, .gray] private var count = 1 func onLoadMore() { var data: [ChartData] = [] DispatchQueue.main.asyncAfter(deadline: .now()+1, execute: { self.count += 1 for i in 0...10 { let value = self.count == 1 ? Float.random(in: 0..<80) : Float.random(in: 0..<100) let chart = ChartData(value: value, label: self.chartView.axis == .vertical ? "Data_\(i*i*self.count*self.count)" : "\(i*i*self.count*self.count)", color: self.colors.randomElement() ?? nil) data.append(chart) } self.chartView.addData(data: data, isEnd: self.count > 5) }) } }
30.7
98
0.564604
dd54d404a60b0c8f350542fdf0f4d7bec0de8090
6,972
// // CountersListViewController.swift // Counters // // Created by Me on 20/01/21. // import UIKit protocol CountersListViewControllerProtocol: class { func displayLoading(_ visible: Bool) func displayError(_ viewModel: ErrorMessageViewModel) func displayList(_ viewModel: [CountersCellViewModel]) func displayListToolBar(title: String) func displayEditToolbar() func displayEditButton(enabled: Bool) func switchDisplayMode(editing: Bool) func displayAddCounterScene() } class CountersListViewController: BaseViewController, CountersListViewControllerProtocol { var interactor: CountersListInteractorProtocol? var router: CountersRouterProtocol? lazy var errorMessageView: ErrorMessageView = { let view = ErrorMessageView.initFromNib() return view }() lazy var activityIndicatorView: UIActivityIndicatorView = { let view = UIActivityIndicatorView(style: .large) return view }() private var customToolBar: CounterBottomToolbar = { let toolbar = CounterBottomToolbar(frame: .zero) toolbar.toolbarTitle = "4 items · Counted 16 times" return toolbar }() private lazy var listView: CountersListTableView = { let listView = CountersListTableView() listView.delegate = self return listView }() private lazy var contentStackView: UIStackView = { let stack = UIStackView() stack.axis = .horizontal stack.spacing = 0 stack.alignment = .fill stack.distribution = .fill return stack }() //MARK: - Lifecycle e Setup override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Colors.countersBackground title = "Counters" setupNavBars() setupView() setupSearch() interactor?.start() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isToolbarHidden = false navigationController?.navigationBar.prefersLargeTitles = true navigationItem.largeTitleDisplayMode = .always DispatchQueue.main.async { [weak self] in self?.navigationController?.navigationBar.sizeToFit() } } override func setupNavBars() { super.setupNavBars() navigationItem.leftBarButtonItem = editButtonItem toolbarItems = customToolBar.items } private func setupView() { view.addSubview(contentStackView) contentStackView.pin(to: view) } private func showView(_ view: UIView) { cleanView() contentStackView.addArrangedSubview(view) } private func cleanView() { contentStackView.subviews.forEach { (subview) in contentStackView.removeArrangedSubview(subview) subview.removeFromSuperview() } } //MARK: - Edit Feature override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) interactor?.didSwitchEditMode(editing: editing) } @objc func selectAllPressed(_ sender: Any?) { interactor?.selectAllCounters() } //MARK: - Search Feature private func setupSearch() { let searchController = UISearchController(searchResultsController: nil) self.navigationItem.searchController = searchController searchController.searchResultsUpdater = self searchController.obscuresBackgroundDuringPresentation = false definesPresentationContext = true } //MARK: - Add Feature func displayAddCounterScene() { router?.showAddCountersScene(with: self) } // MARK: - CountersListViewControllerProtocol // MARK: - Loading func displayLoading(_ visible: Bool) { if visible { showView(activityIndicatorView) activityIndicatorView.startAnimating() } else { activityIndicatorView.stopAnimating() cleanView() } } // MARK: - Error func displayError(_ viewModel: ErrorMessageViewModel) { errorMessageView.errorMessageState = .action(viewModel: viewModel, action: { [weak self] in self?.interactor?.didPressErrorButton() }) showView(errorMessageView) } // MARK: - Listing Feature var viewModel: [CountersCellViewModel] = [] func displayList(_ viewModel: [CountersCellViewModel]) { self.viewModel = viewModel listView.viewModel = viewModel showView(listView) } // MARK: - Edit Mode Feature func displayEditButton(enabled: Bool) { navigationItem.leftBarButtonItem?.isEnabled = enabled } func switchDisplayMode(editing: Bool) { if editing == true { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Select All", style: .plain, target: self, action: #selector(selectAllPressed(_:))) listView.tableView.setEditing(true, animated: true) } else { navigationItem.rightBarButtonItem = nil listView.tableView.setEditing(false, animated: true) } } // MARK: - Toolbar func displayListToolBar(title: String) { customToolBar.toolbarState = .add(viewModel: ToolBarViewModel(toolbarTitle: title, leftAction: nil, righttAction: { [self] in interactor?.didPressAddButton() })) } func displayEditToolbar() { customToolBar.toolbarState = .edit(viewModel: ToolBarViewModel(toolbarTitle: nil, leftAction: { [weak self] in self?.interactor?.deleteSelectedCounters() }, righttAction: { // not enough time to implement print("Share") })) } } extension CountersListViewController: CountersListDelegate { func didStartRefreshing() { interactor?.didPullToRefresh() } func didChangeCounterValue(_ value: Int, at item: Int) { interactor?.didChangeCounter(value, at: item) } func didSelectCounter(_ at: Int) { interactor?.didSelectCounter(at) } } extension CountersListViewController: AddCounterInteractorDelegate { func didCreateNew(_ counter: Counter) { interactor?.didCreateNew(counter) } } extension CountersListViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { if let text = searchController.searchBar.text, !text.isEmpty { filterContentForSearchText(text) } else { listView.viewModel = viewModel } } func filterContentForSearchText(_ searchText: String) { let filteredResults = viewModel.filter { (viewModel) -> Bool in return viewModel.title.lowercased().contains(searchText.lowercased()) } listView.viewModel = filteredResults } }
30.713656
154
0.655049
d5ca28da3d21937fd8e4a95d3f13c0c5916ca651
1,000
// // GetInterestingnessResponse.swift // Foxy // // Created by Леонид Хабибуллин on 31.12.2021. // import Foundation import CoreData struct GetInterestingnessResponse: Codable { let photos: GetInterestingnessResponseInternal let extra: GetInterestingnessResponseExtra let stat: String } struct GetInterestingnessResponseInternal: Codable { let page: Int let pages: Int let perpage: Int let total: Int let photo: [GetInterestingnessResponsePhoto] } struct GetInterestingnessResponseExtra: Codable { let exploreDate: String let nextPreludeInterval: Int enum CodingKeys: String, CodingKey { case exploreDate = "explore_date" case nextPreludeInterval = "next_prelude_interval" } } struct GetInterestingnessResponsePhoto: Codable { let id: String let owner: String let secret: String let server: String let farm: Int let title: String let ispublic: Int let isfriend: Int let isfamily: Int }
21.73913
58
0.719
4bbf19bbde1a5fb3981318ea440488bc71cfa824
407
// Copyright © 2021 Andreas Link. All rights reserved. enum WindowContentViewAction { case didAppear case didDisappear case updateIsOnboardingCompleted(Bool) case onboarding(action: OnboardingViewAction) case fileDropArea(action: FileDropAreaViewAction) case toolbar(action: ToolbarItemsAction) case master(action: MasterViewAction) case detail(action: DetailViewAction) }
31.307692
55
0.773956
f4e6feb5638312c644e92503215015216043261d
1,143
// // NovelSearchService.swift // EBook // // Created by SPARK-Daniel on 2021/8/20. // import Foundation import RxSwift struct NovelSearchService: NovelSearchServiceType { private let book: NetworkProvider init(book: NetworkProvider = NetworkProvider.shared) { self.book = book } func searchHeat(withAppId id: String) -> Observable<[SearchHeat]> { let path = Constants.staticDomain.value + "/static/book/heat/\(id)/heat.json" return book.rx.request(.bookHeatPath(path)).subscribe(on: ConcurrentDispatchQueueScheduler(qos: .userInitiated)).observe(on: MainScheduler.instance).map([SearchHeat].self, atKeyPath: "data").asObservable() } func searchNovel(withKeyword keyword: String, pageIndex: Int, pageSize: Int, reader: ReaderType) -> Observable<SearchResult> { return book.rx.request(.bookSearch(keyword, UIDevice.current.uniqueID, pageIndex, pageSize, Constants.pkgName.value, reader.rawValue)).subscribe(on: ConcurrentDispatchQueueScheduler(qos: .userInitiated)).observe(on: MainScheduler.instance).map(SearchResult.self, atKeyPath: "data").asObservable() } }
40.821429
304
0.730534
2f7d27dba872f9f80952d2db025e20ad113183b1
162
import Foundation struct OCRModel: Codable { let ocrText: [[String]] enum CodingKeys: String, CodingKey { case ocrText = "OCRText" } }
14.727273
40
0.617284
72038e21f453121dfdbb1e09082851f66659dc05
2,071
// // FormElement.swift // StripeiOS // // Created by Yuki Tokuhiro on 6/7/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import Foundation import UIKit /** A simple container of Elements. Displays its views in a vertical stack. Coordinates focus between its child Elements. */ class FormElement { weak var delegate: ElementDelegate? lazy var formView: FormView = { return FormView(viewModel: viewModel) }() let elements: [Element] let paramsUpdater: (IntentConfirmParams) -> IntentConfirmParams // MARK: - ViewModel struct ViewModel { let elements: [UIView] } var viewModel: ViewModel { return ViewModel(elements: elements.map({ $0.view })) } // MARK: - Initializer init(elements: [Element], paramsUpdater: @escaping (IntentConfirmParams) -> IntentConfirmParams) { self.elements = elements self.paramsUpdater = paramsUpdater defer { elements.forEach { $0.delegate = self } } } } // MARK: - Element extension FormElement: Element { func updateParams(params: IntentConfirmParams) -> IntentConfirmParams? { let params = paramsUpdater(params) return elements.reduce(params) { (params: IntentConfirmParams?, element: Element) in guard let params = params else { return nil } return element.updateParams(params: params) } } var validationState: ElementValidationState { // Return the first invalid element's validation state. return elements.reduce(ElementValidationState.valid) { validationState, element in guard case .valid = validationState else { return validationState } return element.validationState } } var view: UIView { return formView } } // MARK: - ElementDelegate extension FormElement: ElementDelegate { func didUpdate(element: Element) { delegate?.didUpdate(element: self) } }
25.567901
102
0.63013
7922c237a9a98d6307cd3bc63b67d4a61ff4aafe
188
// // main.swift // FloodFillAssignment // // Created by Kaden Kim on 2020-02-29. // Copyright © 2020 CICCC. All rights reserved. // import Foundation _ = tomatoFarm() _ = bridges()
14.461538
48
0.664894
e9a750f91a9eaf16cc99b17fd8083d11413abdc1
495
// // HomePictureCell.swift // Instagram // // Created by brad.wu on 2017/4/14. // Copyright © 2017年 bradwoo8621. All rights reserved. // import UIKit class HomePictureCell: UICollectionViewCell { @IBOutlet weak var picImg: UIImageView! override func awakeFromNib() { super.awakeFromNib() let width = UIScreen.main.bounds.width picImg.frame = CGRect(x: 0, y: 0, width: width / 3, height: width / 3) } }
20.625
55
0.593939
feccb069a64303592d6043bad56e6515b8d032bc
9,518
// // profileTBC.swift // SnapInterview // // Created by JT Smrdel on 1/24/17. // Copyright © 2017 SmrdelJT. All rights reserved. // import UIKit class ProfileTBC: UITabBarController, UITabBarControllerDelegate { var profile = (UIApplication.shared.delegate as! AppDelegate).profile var profileTVC: ProfileTVC! var interviewsTVC: InterviewsTVC! var businessSearchVC: BusinessSearchVC! var spotlightsTVC: SpotlightsTVC! var interviewTemplateTVC: InterviewTemplateTVC! var individualSearchVC: IndividualSearchVC! var newInterviewCount: Int! var profileNavController: UINavigationController! var interviewTemplateNavController: UINavigationController! var interviewsNavController: UINavigationController! var individualSearchNavController: UINavigationController! var spotlightNavController: UINavigationController! var businessSearchNavController: UINavigationController! override func viewDidLoad() { super.viewDidLoad() newInterviewCount = 0 tabBar.tintColor = Global.greenColor NotificationCenter.default.addObserver(self, selector: #selector(fetchUpdates), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) profileTVC = ProfileTVC(nibName: "ProfileTVC", bundle: nil) profileTVC.viewType = ViewType.Edit let profileTabBarItem = UITabBarItem(title: "Profile", image: UIImage(named: "profile_icon"), selectedImage: UIImage(named: "profile_icon")) profileTVC.tabBarItem = profileTabBarItem profileNavController = UINavigationController() profileNavController.navigationBar.isTranslucent = false profileNavController.viewControllers = [profileTVC] interviewTemplateTVC = InterviewTemplateTVC(nibName: "InterviewTemplateTVC", bundle: nil) let interviewTemplateTabBarItem = UITabBarItem(title: "InterviewTypes", image: UIImage(named: "template_icon"), selectedImage: UIImage(named: "template_icon")) interviewTemplateTVC.tabBarItem = interviewTemplateTabBarItem interviewTemplateNavController = UINavigationController() interviewTemplateNavController.navigationBar.isTranslucent = false interviewTemplateNavController.viewControllers = [interviewTemplateTVC] interviewsTVC = InterviewsTVC(nibName: "InterviewsTVC", bundle: nil) let interviewsTabBarItem = UITabBarItem(title: "Interviews", image: UIImage(named: "interview_icon"), selectedImage: UIImage(named: "interview_icon")) interviewsTVC.tabBarItem = interviewsTabBarItem interviewsNavController = UINavigationController() interviewsNavController.navigationBar.isTranslucent = false interviewsNavController.viewControllers = [interviewsTVC] individualSearchVC = IndividualSearchVC(nibName: "IndividualSearchVC", bundle: nil) let individualSearchTabBarItem = UITabBarItem(title: "Search", image: UIImage(named: "search_icon"), selectedImage: UIImage(named: "search_icon")) individualSearchVC.tabBarItem = individualSearchTabBarItem individualSearchNavController = UINavigationController() individualSearchNavController.navigationBar.isTranslucent = false individualSearchNavController.viewControllers = [individualSearchVC] spotlightsTVC = SpotlightsTVC(nibName: "SpotlightsTVC", bundle: nil) let spotlightTabBarItem = UITabBarItem(title: "Spotlight", image: UIImage(named: "spotlight_icon"), selectedImage: UIImage(named: "spotlight_icon")) spotlightsTVC.tabBarItem = spotlightTabBarItem spotlightNavController = UINavigationController() spotlightNavController.navigationBar.isTranslucent = false spotlightNavController.viewControllers = [spotlightsTVC] businessSearchVC = BusinessSearchVC(nibName: "BusinessSearchVC", bundle: nil) let businessSearchTabBarItem = UITabBarItem(title: "Search", image: UIImage(named: "search_icon"), selectedImage: UIImage(named: "search_icon")) businessSearchVC.tabBarItem = businessSearchTabBarItem businessSearchNavController = UINavigationController() businessSearchNavController.navigationBar.isTranslucent = false businessSearchNavController.viewControllers = [businessSearchVC] } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) switch profile.profileType! { case .Business: viewControllers = [interviewsNavController, interviewTemplateNavController, individualSearchNavController, spotlightNavController, profileNavController] case .Individual: viewControllers = [interviewsNavController, businessSearchNavController, spotlightNavController, profileNavController] } if !profile.exists { // Set to profile tab self.selectedViewController = profileNavController } } @objc func fetchUpdates() { if profile.exists { switch profile.profileType! { case .Business: profile.businessProfile?.interviewCollection.fetchAllInterviews(with: profile.cKRecordName!, profileType: .Business, completion: { let newInterviewCount = self.profile.businessProfile?.interviewCollection.interviews.filter({ (interview) -> Bool in interview.businessNewFlag == true }).count if let count = newInterviewCount { if count > 0 { DispatchQueue.main.async { self.interviewsTVC.tabBarItem.badgeValue = "\(count)" self.interviewsTVC.sortAndRefreshInterviews() } } else { DispatchQueue.main.async { self.interviewsTVC.tabBarItem.badgeValue = nil } } } }) profile.businessProfile?.spotlightCollection.fetchAllSpotlights(with: profile.cKRecordName!, profileType: .Business, completion: { let newSpotlightCount = self.profile.businessProfile?.spotlightCollection.spotlights.filter({ (spotlight) -> Bool in spotlight.businessNewFlag == true }).count if let count = newSpotlightCount { if count > 0 { DispatchQueue.main.async { self.spotlightsTVC.tabBarItem.badgeValue = "\(count)" } } else { DispatchQueue.main.async { self.spotlightsTVC.tabBarItem.badgeValue = nil } } } }) case .Individual: profile.individualProfile?.interviewCollection.fetchAllInterviews(with: profile.cKRecordName!, profileType: .Individual, completion: { let newInterviewCount = self.profile.individualProfile?.interviewCollection.interviews.filter({ (interview) -> Bool in interview.individualNewFlag == true }).count if let count = newInterviewCount { if count > 0 { DispatchQueue.main.async { self.interviewsTVC.tabBarItem.badgeValue = "\(count)" self.interviewsTVC.sortAndRefreshInterviews() } } else { DispatchQueue.main.async { self.interviewsTVC.tabBarItem.badgeValue = nil } } } }) profile.individualProfile?.spotlightCollection.fetchAllSpotlights(with: profile.cKRecordName!, profileType: .Individual, completion: { let newSpotlightCount = self.profile.individualProfile?.spotlightCollection.spotlights.filter({ (spotlight) -> Bool in spotlight.individualNewFlag == true }).count if let count = newSpotlightCount { if count > 0 { DispatchQueue.main.async { self.spotlightsTVC.tabBarItem.badgeValue = "\(count)" } } else { DispatchQueue.main.async { self.spotlightsTVC.tabBarItem.badgeValue = nil } } } }) } } } }
46.203883
167
0.581215
3a9754dd3af5b085195bd128ac245a4f6a8b322e
2,701
#if os(watchOS) && canImport(SwiftUI) import SwiftUI public class TimeComponent: ObservableObject { @Published public var hour: Double @Published public var minute: Double public init(h: Double, m: Double) { hour = h minute = m } public init(_ t: TimeInterval) { hour = trunc(t) minute = (t - trunc(t)) * 60 } public func update(_ t: TimeInterval) { hour = trunc(t) minute = (t - trunc(t)) * 60 } public var wholeHour: Int { Int(hour.rounded(.toNearestOrAwayFromZero)) } public var wholeMinute: Int { Int(minute.rounded(.toNearestOrAwayFromZero)) } public var time: TimeInterval { hour + minute / 60 } } @available(watchOS 7, *) public struct TimePicker: View { @ObservedObject public var timeComponent: TimeComponent @State private var hourFocused: Bool = false @State private var minuteFocused: Bool = false @State private var curfewEnabled: Bool = true static let formatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.allowedUnits = [.hour, .minute] return formatter }() public var body: some View { HStack { Text("\(timeComponent.wholeHour, specifier: "%02d")") .font(.title3) .focusable(true, onFocusChange: { focused in hourFocused = focused }) .digitalCrownRotation( $timeComponent.hour, from: 0, through: 24, by: 1, sensitivity: .medium, isContinuous: false, isHapticFeedbackEnabled: true ) .padding(.horizontal, 4) .border(Color.accentColor, width: hourFocused ? 2 : 0) .cornerRadius(3) Text(":") Text("\(timeComponent.wholeMinute, specifier: "%02d")") .font(.title3) .focusable(true, onFocusChange: { focused in minuteFocused = focused }) .digitalCrownRotation( $timeComponent.minute, from: 0, through: 59, by: 1, sensitivity: .medium, isContinuous: false, isHapticFeedbackEnabled: true ) .padding(.horizontal, 4) .border(Color.accentColor, width: minuteFocused ? 2 : 0) .cornerRadius(3) } } } #endif
29.043011
72
0.509071
14c393182750f21ed683d62ce57e261954beb729
701
// // UnregisterWampMessage.swift // // // Created by Jordan Anders on 2020-09-21. // import Foundation /// [UNREGISTER, requestId|number, registration|number] class UnregisterWampMessage: WampMessage { let requestId: Int let registration: Int init(requestId: Int, registration: Int) { self.requestId = requestId self.registration = registration } // MARK: WampMessage protocol required init(payload: [Any]) { self.requestId = payload[0] as! Int self.registration = payload[1] as! Int } func marshal() -> [Any] { return [WampMessages.unregister.rawValue, self.requestId, self.registration] } }
21.90625
84
0.636234
223a84ce49c6e4bc94d37323d12ffd92e992900e
2,198
// // UniversalTextField.swift // SwiftUI Test // // Created by Alex Golub on 23.11.2021. // import SwiftUI struct UniversalTextField: UIViewRepresentable { class Coordinator: NSObject, UITextFieldDelegate { @Binding var text: String @Binding var inEditing: Bool @Binding var isFirstResponder: Bool var onSubmit: () -> Void init( text: Binding<String>, inEditing: Binding<Bool>, isFirstResponder: Binding<Bool>, onSubmit: @escaping () -> Void ) { _text = text _inEditing = inEditing _isFirstResponder = isFirstResponder self.onSubmit = onSubmit } func textFieldDidChangeSelection(_ textField: UITextField) { text = textField.text ?? "" } func textFieldShouldReturn(_ textField: UITextField) -> Bool { isFirstResponder = false self.onSubmit() return true } } @Binding var text: String @Binding var inEditing: Bool @Binding var isFirstResponder: Bool var onSubmit: () -> Void func makeUIView(context: UIViewRepresentableContext<UniversalTextField>) -> UITextField { let textField = UITextField(frame: .zero) textField.delegate = context.coordinator textField.autocapitalizationType = .words textField.textColor = UIColor(.white) textField.attributedPlaceholder = NSAttributedString( string: "Name", attributes: [NSAttributedString.Key.foregroundColor: UIColor(Color("lightBlue").opacity(0.5))] ) return textField } func makeCoordinator() -> UniversalTextField.Coordinator { return Coordinator( text: $text, inEditing: $inEditing, isFirstResponder: $isFirstResponder, onSubmit: onSubmit ) } func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<UniversalTextField>) { uiView.text = text if isFirstResponder { uiView.becomeFirstResponder() } else { uiView.resignFirstResponder() } } }
28.545455
106
0.608735
26eaf953b4a10b5417b1fa9c2b61648ee95593ff
2,156
// // AppDelegate.swift // DouYuZB // // Created by 郭小洪 on 2018/3/1. // Copyright © 2018年 郭小洪. 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 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:. } }
45.87234
285
0.754174
56fbc59fce7952d29a637713de9031f2e625404c
2,159
// // FieldSceneCheckCanMove.swift // DQ3 // // Created by aship on 2021/01/12. // import SpriteKit extension FieldScene { func checkCanMove(tileMapNode: SKTileMapNode, newPositionX: Int, newPositionY: Int) -> Bool { if self.scene.fieldMoveMode == .walk { // 船がある場合は行ける if DataManager.adventureLog.hasShip { let shipNode = self.shipNode if shipNode?.positionX == newPositionX && shipNode?.positionY == newPositionY { return true } } let tileGroup = tileMapNode.tileGroup(atColumn: newPositionX, row: newPositionY) let name = tileGroup?.name if name == "tile0" || name == "tile1" || name == "tile2" || name == "tile4" || name == "tile6" || name == "tile7" || name == "tile12" || name == "tile13" || name == "tile14" || name == "tile15" || name == "tile16" || name == "tile18" || name == "tile19" || name == "tile21" || name == "tile22" || name == "tile23" || name == "tile24" || name == "tile37" || name == "tile39" || name == "tile40" || name == "tile42" || name == "tile43" || name == "tile44" { return false } } else if self.scene.fieldMoveMode == .ship { let tileGroup = tileMapNode.tileGroup(atColumn: newPositionX, row: newPositionY) let name = tileGroup?.name if name == "tile16" || name == "tile18" || name == "tile40" { return false } } return true } }
30.842857
73
0.380269
097820b9a490e91575ec9d26b393fcb8085089eb
899
// // BookingModelVM.swift // Xe TQT // // Created by Admin on 5/11/20. // Copyright © 2020 eagle. All rights reserved. // import UIKit import RxCocoa import RxSwift class BookingModelVM: BaseViewModel { let viewModel = BehaviorRelay<BookingModel>(value: BookingModel()) let address_go = BehaviorRelay<String>(value: "") let address_deliver = BehaviorRelay<String>(value: "") let phone_passenger = BehaviorRelay<String>(value: "") let phone_driver = BehaviorRelay<String>(value: "") let name_passenger = BehaviorRelay<String>(value: "") let name_driver = BehaviorRelay<String>(value: "") let date = BehaviorRelay<String>(value: "") let time = BehaviorRelay<String>(value: "") let note_passenger = BehaviorRelay<String>(value: "") override init() { super.init() setupRx() } func setupRx() { } }
26.441176
70
0.649611
010698a216869cddfd5e1b85a12a38a3c3364175
1,259
// // Copyright © 2019 Essential Developer. All rights reserved. // import CoreData public final class CoreDataFeedStore { private static let modelName = "FeedStore" private static let model = NSManagedObjectModel.with(name: modelName, in: Bundle(for: CoreDataFeedStore.self)) private let container: NSPersistentContainer private let context: NSManagedObjectContext enum StoreError: Error { case modelNotFound case failedToLoadPersistentContainer(Error) } public init(storeURL: URL) throws { guard let model = CoreDataFeedStore.model else { throw StoreError.modelNotFound } do { container = try NSPersistentContainer.load(name: CoreDataFeedStore.modelName, model: model, url: storeURL) context = container.newBackgroundContext() } catch { throw StoreError.failedToLoadPersistentContainer(error) } } func perform(_ action: @escaping (NSManagedObjectContext) -> Void) { let context = self.context context.perform { action(context) } } private func cleanUpReferencesToPersistentStores() { context.performAndWait { let coordinator = self.container.persistentStoreCoordinator try? coordinator.persistentStores.forEach(coordinator.remove) } } deinit { cleanUpReferencesToPersistentStores() } }
26.229167
111
0.766481
031304ce88a4628846a2d6d26b550819eddec93f
4,390
import Foundation import Capacitor import GoogleSignIn /** * Please read the Capacitor iOS Plugin Development Guide * here: https://capacitor.ionicframework.com/docs/plugins/ios */ @objc(GoogleAuth) public class GoogleAuth: CAPPlugin { var signInCall: CAPPluginCall? let googleSignIn: GIDSignIn = GIDSignIn.sharedInstance(); var forceAuthCode: Bool = false; public override func load() { guard let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist") else { print("GoogleService-Info.plist not found"); return; } guard let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] else {return} guard let clientId = dict["CLIENT_ID"] as? String else {return} googleSignIn.clientID = clientId; googleSignIn.delegate = self; googleSignIn.presentingViewController = bridge?.viewController; if let serverClientId = getConfigValue("serverClientId") as? String { googleSignIn.serverClientID = serverClientId; } if let scopes = getConfigValue("scopes") as? [String] { googleSignIn.scopes = scopes; } if let forceAuthCodeConfig = getConfigValue("forceCodeForRefreshToken") as? Bool { forceAuthCode = forceAuthCodeConfig; } NotificationCenter.default.addObserver(self, selector: #selector(handleOpenUrl(_ :)), name: Notification.Name(CAPNotifications.URLOpen.name()), object: nil); } @objc func signIn(_ call: CAPPluginCall) { signInCall = call; DispatchQueue.main.async { if self.googleSignIn.hasPreviousSignIn() && !self.forceAuthCode { self.googleSignIn.restorePreviousSignIn(); } else { self.googleSignIn.signIn(); } } } @objc func refresh(_ call: CAPPluginCall) { DispatchQueue.main.async { if self.googleSignIn.currentUser == nil { call.error("User not logged in."); return } self.googleSignIn.currentUser.authentication.getTokensWithHandler { (authentication, error) in guard let authentication = authentication else { call.error(error?.localizedDescription ?? "Something went wrong."); return; } let authenticationData: [String: Any] = [ "accessToken": authentication.accessToken, "idToken": authentication.idToken, "refreshToken": authentication.refreshToken ] call.success(authenticationData); } } } @objc func signOut(_ call: CAPPluginCall) { DispatchQueue.main.async { self.googleSignIn.signOut(); } call.success(); } @objc func handleOpenUrl(_ notification: Notification) { guard let object = notification.object as? [String: Any] else { print("There is no object on handleOpenUrl"); return; } guard let url = object["url"] as? URL else { print("There is no url on handleOpenUrl"); return; } googleSignIn.handle(url); } func processCallback(user: GIDGoogleUser) { var userData: [String: Any] = [ "authentication": [ "accessToken": user.authentication.accessToken, "idToken": user.authentication.idToken, "refreshToken": user.authentication.refreshToken ], "serverAuthCode": user.serverAuthCode, "email": user.profile.email, "familyName": user.profile.familyName, "givenName": user.profile.givenName, "id": user.userID, "name": user.profile.name ]; if let imageUrl = user.profile.imageURL(withDimension: 100)?.absoluteString { userData["imageUrl"] = imageUrl; } signInCall?.success(userData); } } extension GoogleAuth: GIDSignInDelegate { public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if let error = error { signInCall?.error(error.localizedDescription); return; } processCallback(user: user); } }
35.983607
165
0.5959
5d39dafad498c7ca1af9cbe644c72a94d97fb927
3,199
// // PlatformFactory.swift // Runner // // Created by mac on 2017/9/6. // Copyright © 2017年 CoderZNBmm. All rights reserved. // import SpriteKit class PlatformFactory: SKNode { // 定义平台左边纹理 let textureLeft = SKTexture(imageNamed: "platform_l") //定义平台中间纹理 let textureMid = SKTexture(imageNamed: "platform_m") //定义平台右边纹理 let textureRight = SKTexture(imageNamed: "platform_r") //定义一个数组来储存组装后的平台 var platforms = [Platform]() //游戏场景的宽度 var sceneWidth:CGFloat = 0 //ProtocolMainScene代理 var delegate:ProtocolMainScene? //生成自定义位置的平台 func createPlatform(midNum:UInt32,x:CGFloat,y:CGFloat){ let platform = self.createPlatform(isRandom: false, midNum: midNum, x: x, y: y) delegate?.onGetData(dist: platform.width - sceneWidth) } //生成随机位置的平台的方法 func createPlatformRandom(){ //随机平台的长度 let midNum:UInt32 = arc4random()%4 + 1 //随机间隔 let gap:CGFloat = CGFloat(arc4random()%8 + 1) //随机x坐标 let x:CGFloat = self.sceneWidth + CGFloat( midNum*50 ) + gap + 80 //随机y坐标 let y:CGFloat = CGFloat(arc4random()%40 + 100) let platform = self.createPlatform(isRandom: true, midNum: midNum, x: x, y: y) //回传距离用于判断什么时候生成新的平台 delegate?.onGetData(dist: platform.width + x - sceneWidth) } func createPlatform(isRandom:Bool,midNum:UInt32,x:CGFloat,y:CGFloat)->Platform{ //声明一个平台类,用来组装平台。 let platform = Platform() //生成平台的左边零件 let platform_left = SKSpriteNode(texture: textureLeft) //设置中心点 platform_left.anchorPoint = CGPoint(x: 0, y: 1.0) //生成平台的右边零件 let platform_right = SKSpriteNode(texture: textureRight) //设置中心点 platform_right.anchorPoint = CGPoint(x: 0, y: 1.0) //声明一个数组来存放平台的零件 var arrPlatform = [SKSpriteNode]() //将左边零件加入零件数组 arrPlatform.append(platform_left) //根据传入的参数来决定要组装几个平台的中间零件 //然后将中间的零件加入零件数组 for _ in 1...midNum { let platform_mid = SKSpriteNode(texture: textureMid) platform_mid.anchorPoint = CGPoint(x: 0, y: 1.0) arrPlatform.append(platform_mid) } //将右边零件加入零件数组 arrPlatform.append(platform_right) //将零件数组传入 platform.onCreate(arrSprite: arrPlatform) platform.name="platform" //设置平台的位置 platform.position = CGPoint(x: x, y: y) //放到当前实例中 self.addChild(platform) //将平台加入平台数组 platforms.append(platform) return platform } func move(speed:CGFloat){ //遍历所有 for p in platforms{ //x坐标的变化长生水平移动的动画 p.position.x -= speed } //移除平台 if platforms[0].position.x < -platforms[0].width { platforms[0].removeFromParent() platforms.remove(at: 0) } } //重置方法 func reSet(){ //清除所有子对象 self.removeAllChildren() //清空平台数组 platforms.removeAll(keepingCapacity: false) } } //定义一个协议,用来接收数据 protocol ProtocolMainScene { func onGetData(dist:CGFloat) }
28.061404
87
0.595499
502367ea54bb8558279a86df765c4a61af4d6a9f
508
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -emit-ir protocol a protocol P protocol A}}guard let c class T:Range<T>:A protocolass B struct D:A{iB let f=nil a(){{ gu
31.75
79
0.746063
e67c629d8c8ddbe5d18340a4b133e379650d1c3d
3,145
// // CGGeometryModel.swift // ViewBuilder // // Created by Abel Sanchez on 6/15/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import CoreGraphics import Foundation // MARK: - CGRect extension CGRect: NSValueConvertible { public func convertToNSValue() -> NSValue? { return NSValue(cgRect: self) } } open class Rect: Object, TextDeserializer { public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? { guard let value = text, value.count > 0 else { return NSValue(cgRect: CGRect.zero) } guard let array = service.parseValidDoubleArray(from: value), array.count == 4 else { return nil } return CGRect(x: CGFloat(array[0]), y: CGFloat(array[1]), width: CGFloat(array[2]), height: CGFloat(array[3])) } } extension CGRect: TextDeserializer { public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? { return Rect.deserialize(text: text, service: service) } } // MARK: - CGPoint extension CGPoint: NSValueConvertible { public func convertToNSValue() -> NSValue? { return NSValue(cgPoint: self) } } open class Point: Object, TextDeserializer { public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? { guard let value = text, value.count > 0 else { return NSValue(cgRect: CGRect.zero) } guard let array = service.parseValidDoubleArray(from: value), array.count == 2 else { return nil } return CGPoint(x: CGFloat(array[0]), y: CGFloat(array[1])) } } extension CGPoint: TextDeserializer { public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? { return Point.deserialize(text: text, service: service) } } // MARK: - CGSize extension CGSize: NSValueConvertible { public func convertToNSValue() -> NSValue? { return NSValue(cgSize: self) } } open class Size: Object, TextDeserializer { public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? { guard let value = text, value.count > 0 else { return NSValue(cgRect: CGRect.zero) } guard let array = service.parseValidDoubleArray(from: value), array.count == 2 else { return nil } return CGSize(width: CGFloat(array[0]), height: CGFloat(array[1])) } } // MARK: - CGVector extension CGVector: NSValueConvertible { public func convertToNSValue() -> NSValue? { return NSValue(cgVector: self) } } open class Vector: Object, TextDeserializer { public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? { guard let value = text, value.count > 0 else { return NSValue(cgRect: CGRect.zero) } guard let array = service.parseValidDoubleArray(from: value), array.count == 2 else { return nil } return CGVector(dx: CGFloat(array[0]), dy: CGFloat(array[1])) } }
29.952381
118
0.651828
fbc9b93c68026efa59c56a0da3e923d3130406c2
394
// // Created by Yaroslav Zhurakovskiy // Copyright © 2019-2020 Yaroslav Zhurakovskiy. All rights reserved. // public struct FavoriteQuestionID { public let favoriteIDHash: String public let questionID: Int public init( favoriteIDHash: String, questionID: Int ) { self.favoriteIDHash = favoriteIDHash self.questionID = questionID } }
21.888889
69
0.667513
bb8b7b2c6966fe6c0a16fe71fdd7b9bb3b85e82f
408
// // Copyright © 2020 NHSX. All rights reserved. // import XCTest struct SimulatedCameraAuthorizationScreen { typealias Text = Sandbox.Text.CameraManager var app: XCUIApplication var allowButton: XCUIElement { app.buttons[key: Text.authorizationAlertAllow] } var dontAllowButton: XCUIElement { app.buttons[key: Text.authorizationAlertDoNotAllow] } }
20.4
59
0.693627
d967e45f458428b47540be74c6ea3a4ba892f914
674
// // MeasureType.swift // DEMO_Swift_Protocols // // Created by Robert L. Jones on 2/4/16. // Copyright © 2016 Synthelytics LLC. All rights reserved. // // INSPIRATIONS: // 1. http://nshipster.com/swift-comparison-protocols/ // 2. http://stackoverflow.com/questions/31491638/swift-2-add-protocol-conformance-to-protocols // import HealthKit protocol MeasureType { var unit: String { get set } // var quantity: HKQuantity { get set } // Equivalent to quantity.doubleValueForUnit(unit) var value: Double { get set } // Equivalent to quantity.doubleValueForUnit(unit) // var string: String { get } // Equivalent to quantity.description }
29.304348
96
0.698813
18692b7547ed510d0e62f232542e84dfd63a4b0c
527
// // MenuCell.swift // hamburgerDemo // // Created by Rajat Bhargava on 10/3/17. // Copyright © 2017 Rajat Bhargava. All rights reserved. // import UIKit class MenuCell: UITableViewCell { @IBOutlet weak var colorLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
20.269231
65
0.666034
8a75f432a94821b20c140a12eb519837ca74f7ce
3,538
/* 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 */ /// Check if the given code unit needs shell escaping. // /// - Parameters: /// - codeUnit: The code unit to be checked. /// /// - Returns: True if shell escaping is not needed. private func inShellWhitelist(_ codeUnit: UInt8) -> Bool { switch codeUnit { case UInt8(ascii: "a")...UInt8(ascii: "z"), UInt8(ascii: "A")...UInt8(ascii: "Z"), UInt8(ascii: "0")...UInt8(ascii: "9"), UInt8(ascii: "-"), UInt8(ascii: "_"), UInt8(ascii: "/"), UInt8(ascii: ":"), UInt8(ascii: "@"), UInt8(ascii: "%"), UInt8(ascii: "+"), UInt8(ascii: "="), UInt8(ascii: "."), UInt8(ascii: ","): return true default: return false } } extension String { /// Creates a shell escaped string. If the string does not need escaping, returns the original string. /// Otherwise escapes using single quotes. For example: /// hello -> hello, hello$world -> 'hello$world', input A -> 'input A' /// /// - Returns: Shell escaped string. public func spm_shellEscaped() -> String { // If all the characters in the string are in whitelist then no need to escape. guard let pos = utf8.index(where: { !inShellWhitelist($0) }) else { return self } // If there are no single quotes then we can just wrap the string around single quotes. guard let singleQuotePos = utf8[pos...].index(of: UInt8(ascii: "'")) else { return "'" + self + "'" } // Otherwise iterate and escape all the single quotes. var newString = "'" + String(self[..<singleQuotePos]) for char in self[singleQuotePos...] { if char == "'" { newString += "'\\''" } else { newString += String(char) } } newString += "'" return newString } /// Shell escapes the current string. This method is mutating version of shellEscaped(). public mutating func spm_shellEscape() { self = spm_shellEscaped() } } /// Type of localized join operator. public enum LocalizedJoinType: String { /// A conjunction join operator (ie: blue, white, and red) case conjunction = "and" /// A disjunction join operator (ie: blue, white, or red) case disjunction = "or" } //FIXME: Migrate to DiagnosticFragmentBuilder public extension Array where Element == String { /// Returns a localized list of terms representing a conjunction or disjunction. func spm_localizedJoin(type: LocalizedJoinType) -> String { var result = "" for (i, item) in enumerated() { // Add the separator, if necessary. if i == count - 1 { switch count { case 1: break case 2: result += " \(type.rawValue) " default: result += ", \(type.rawValue) " } } else if i != 0 { result += ", " } result += item } return result } }
30.765217
106
0.547767
765686f83aa94126cc60aac6afd54e98e917a629
983
// // SwiftUIView.swift // // // Created by O'Brien, Patrick on 2/4/21. // import SwiftUI internal struct MarkerContainer<Label: View>: View { var _state: MarkerControl.State var _icon: Image? var _screenPosition: CGPoint var _isMarkerVisible: Bool let _label: (MarkerControl.State, Image?) -> Label internal init(state: MarkerControl.State, icon: Image?, screenPosition: CGPoint, isMarkerVisible: Bool, @ViewBuilder label: @escaping (MarkerControl.State, Image?) -> Label) { self._state = state self._icon = icon self._screenPosition = screenPosition self._isMarkerVisible = isMarkerVisible self._label = label } internal var label_: some View { _label(_state, _icon) } } extension MarkerContainer { var body: some View { Group { if _isMarkerVisible { label_ .position(_screenPosition) } } } }
23.97561
179
0.614446
6281aa0ef0452bfc768722548e9994bd96acc627
3,535
// // ConversationVCNavBarSnapshotTests.swift // Kommunicate_Tests // // Created by Shivam Pokhriyal on 20/11/18. // Copyright © 2018 CocoaPods. All rights reserved. // import Quick import Nimble import Nimble_Snapshots import Applozic @testable import Kommunicate class ConversationVCNavBarSnapshotTests: QuickSpec, NavigationBarCallbacks { func backButtonPressed() { } let mockContact: ALContact = { let alContact = ALContact() alContact.userId = "demoUserId" alContact.displayName = "Demo Display Name" return alContact }() let mockChannel: ALChannel = { let channel = ALChannel() channel.key = 1244444 channel.name = "Demo Display Name" channel.type = Int16(SUPPORT_GROUP.rawValue) return channel }() override func spec() { describe ("conversationVC NavBar") { var navigationController: UINavigationController! var customNavigationView: ConversationVCNavBar! var viewController: UIViewController! beforeEach { customNavigationView = ConversationVCNavBar( delegate: self, localizationFileName: "Localizable", configuration: KMConversationViewConfiguration()) viewController = UIViewController(nibName: nil, bundle: nil) viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: customNavigationView) navigationController = UINavigationController(rootViewController: viewController) self.applyColor(navigationController: navigationController) customNavigationView.setupAppearance(navigationController.navigationBar) } it ("show agent online") { self.mockContact.connected = true customNavigationView.updateView(assignee: self.mockContact,channel:self.mockChannel ) navigationController.navigationBar.snapshotView(afterScreenUpdates: true) expect(navigationController.navigationBar).to(haveValidSnapshot()) } it ("show agent offline") { self.mockContact.connected = false customNavigationView.updateView(assignee: self.mockContact,channel: self.mockChannel) navigationController.navigationBar.snapshotView(afterScreenUpdates: true) expect(navigationController.navigationBar).to(haveValidSnapshot()) } } } func applyColor(navigationController : UINavigationController) { navigationController.navigationBar.isTranslucent = false navigationController.navigationBar.tintColor = UIColor.red navigationController.navigationBar.barTintColor = UIColor(236, green: 239, blue: 241) navigationController.navigationBar.titleTextAttributes = [ .foregroundColor: UIColor.blue, .font: UIFont.boldSystemFont(ofSize: 16), .subtitleFont: UIFont.systemFont(ofSize: 8) ] if #available(iOS 13.0, *) { let appearance = UINavigationBarAppearance() appearance.backgroundColor = UIColor(red:0.93, green:0.94, blue:0.95, alpha:1.0) navigationController.navigationBar.standardAppearance = appearance }else{ navigationController.navigationBar.barTintColor = UIColor(red:0.93, green:0.94, blue:0.95, alpha:1.0) } } }
39.277778
115
0.655446
9c07e1841f8146c8b73e5aa1ba20418d66491c6e
3,752
// // AppDetailsScreen.swift // MetricsViewer // // Created by Kamaal M Farah on 08/07/2021. // import SwiftUI import MetricsLocale import ConsoleSwift struct AppDetailsScreen: View { @EnvironmentObject private var coreAppManager: CoreAppManager @StateObject private var editViewModel = EditViewModel() @StateObject private var viewModel = ViewModel() private let preview: Bool init(preview: Bool = false) { self.preview = preview } var body: some View { VStack(alignment: .leading) { if editViewModel.editScreenIsActive { ModifyApp( appName: $editViewModel.editingAppName, appIdentifier: $editViewModel.editingAppIdentifier, accessToken: $editViewModel.editingAccessToken, selectedHost: $editViewModel.editingSelectedHost, preview: preview) } else { AppDetailsMetrics( loadingMetrics: $viewModel.loadingMetrics, metricsLastUpdated: viewModel.metricsLastUpdated, last7FirstLaunchMetrics: viewModel.last7FirstLaunchMetrics, last7LaunchFromBackgroundMetrics: viewModel.last7LaunchFromBackgroundMetrics) } } .padding(24) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .background(Color.Background) .alert(isPresented: $viewModel.showAlert, content: { handledAlert(with: viewModel.alertMessage) }) .onAppear(perform: onViewAppear) #if os(macOS) .navigationTitle(Text(coreAppManager.selectedApp?.name ?? "")) .toolbar(content: { if editViewModel.editScreenIsActive { Button(action: editViewModel.onCancelPress) { // - TODO: LOCALIZE THIS Text("Cancel") } } Button(action: onEditPress) { Text(localized: editViewModel.editScreenIsActive ? .DONE : .EDIT) .animation(nil) } Button(action: viewModel.getMetrics) { Label(MetricsLocale.Keys.REFRESH_METRICS.localized, systemImage: "arrow.triangle.2.circlepath") } .disabled(viewModel.loadingMetrics || editViewModel.editScreenIsActive) }) #endif } private func onEditPress() { let argsResult = editViewModel.onEditPress() let args: CoreApp.Args switch argsResult { case .failure(let failure): viewModel.setAlertMessage(with: failure.alertMessage) return case .success(let success): guard let success = success else { return } args = success } guard let selectedApp = coreAppManager.selectedApp else { console.error(Date(), "app not found") return } let editedApp: CoreApp do { editedApp = try selectedApp.editApp(with: args) } catch { console.error(Date(), error.localizedDescription, error) return } viewModel.setApp(editedApp) editViewModel.setApp(editedApp) coreAppManager.selectApp(editedApp) coreAppManager.replaceApp(with: editedApp) } private func onViewAppear() { if let selectedApp = coreAppManager.selectedApp { viewModel.setApp(selectedApp) editViewModel.setApp(selectedApp) } } } struct AppDetailsScreen_Previews: PreviewProvider { static var previews: some View { AppDetailsScreen() .environmentObject(CoreAppManager(preview: true)) } }
33.5
111
0.602079
bf639608f861e7141090f1e24b84c3a385cff9df
6,771
/* See LICENSE folder for this sample’s licensing information. Abstract: View controller that reads NFC fish tag. */ import UIKit import CoreNFC import os /* NFCNDEFReaderSession:用于检测NFC数据交换格式(NDEF)标签的读取器会话 NFCTagReaderSession:用于检测ISO7816,ISO15693,FeliCa和MIFARE标签的读取器会话 */ class ScanViewController: UITableViewController, NFCTagReaderSessionDelegate { // MARK: - Properties var readerSession: NFCTagReaderSession? @IBOutlet weak var kindText: UITextField! @IBOutlet weak var dateText: UITextField! @IBOutlet weak var priceText: UITextField! @IBOutlet weak var infoText: UITextField! override func viewDidLoad() { super.viewDidLoad() } // MARK: - Actions @IBAction func scanTag(_ sender: Any) { guard NFCNDEFReaderSession.readingAvailable else { let alertController = UIAlertController( title: "不支持扫描", message: "这个设备不支持标签扫描", preferredStyle: .alert ) alertController.addAction(UIAlertAction(title: "确定", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) return } readerSession = NFCTagReaderSession(pollingOption: [.iso14443, .iso15693, .iso18092], delegate: self, queue: nil) readerSession?.alertMessage = "Hold your iPhone near an NFC fish tag." readerSession?.begin() } // MARK: - Private helper functions func tagRemovalDetect(_ tag: NFCTag) { self.readerSession?.connect(to: tag) { (error: Error?) in if error != nil || !tag.isAvailable { os_log("重新启动轮询") self.readerSession?.restartPolling() return } DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + .milliseconds(500), execute: { self.tagRemovalDetect(tag) }) } } func getDate(from value: String?) -> String? { guard let dateString = value else { return nil } let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.dateFormat = "yyyyMMdd" dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) let outputDateFormatter = DateFormatter() outputDateFormatter.dateStyle = .medium outputDateFormatter.timeStyle = .none outputDateFormatter.locale = Locale.current return outputDateFormatter.string(from: dateFormatter.date(from: dateString)!) } func getPrice(from value: String?) -> String? { guard let priceString = value else { return nil } return String("$\(priceString.prefix(priceString.count - 2)).\(priceString.suffix(2))") } // UI元素根据接收到的NDEF消息进行更新 func updateWithNDEFMessage(_ message: NFCNDEFMessage) -> Bool { let urls: [URLComponents] = message.records.compactMap { (payload: NFCNDEFPayload) -> URLComponents? in // 使用匹配的域主机和方案搜索URL记录 if let url = payload.wellKnownTypeURIPayload() { let components = URLComponents(url: url, resolvingAgainstBaseURL: false) if components?.host == "www.baidu.com" && components?.scheme == "https" { return components } } return nil } // 有效标签应该只包含一个URL和多个查询项 guard urls.count == 1, let items = urls.first?.queryItems else { return false } // 从有效负载中获取可选信息文本 var additionInfo: String? = nil for payload in message.records { (additionInfo, _) = payload.wellKnownTypeTextPayload() if additionInfo != nil { break } } DispatchQueue.main.async { self.infoText.text = additionInfo for item in items { switch item.name { case "date": self.dateText.text = self.getDate(from: item.value) case "price": self.priceText.text = self.getPrice(from: item.value) case "kind": self.kindText.text = item.value default: break } } } return true } // MARK: - NFCTagReaderSessionDelegate func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) { // 如果需要,您可以在会话启动时执行其他操作 // 此时启用了RF轮询 print("BecomeActive"); } func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) { // 如果有必要,您可以处理错误。注:会话不再有效 // 您必须创建一个新会话来重新启动RF轮询 print("error=\(error)"); } func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) { if tags.count > 1 { session.alertMessage = "发现了1个以上的标签。请只展示1个标签" self.tagRemovalDetect(tags.first!) return } var ndefTag: NFCNDEFTag switch tags.first! { case let .iso7816(tag): ndefTag = tag case let .feliCa(tag): ndefTag = tag case let .iso15693(tag): ndefTag = tag case let .miFare(tag): ndefTag = tag @unknown default: session.invalidate(errorMessage: "标签无效") return } session.connect(to: tags.first!) { (error: Error?) in if error != nil { session.invalidate(errorMessage: "连接错误 请再试一次") return } ndefTag.queryNDEFStatus() { (status: NFCNDEFStatus, _, error: Error?) in if status == .notSupported { session.invalidate(errorMessage: "标签无效") return } ndefTag.readNDEF() { (message: NFCNDEFMessage?, error: Error?) in if error != nil { session.invalidate(errorMessage: "读取错误 请再试一次") return } if message == nil { session.invalidate(errorMessage: "没有读取到任何信息") return } if self.updateWithNDEFMessage(message!) { session.invalidate() } // session.invalidate(errorMessage: "标签无效") } } } } }
32.242857
121
0.537439
4a9ffee983e3c885e64d2c11f05c2d07c447782c
439
// // RemoteImageServiceProtocol.swift // RemoteImage // // Created by Christian Elies on 15.12.19. // #if canImport(UIKit) import Combine protocol RemoteImageServiceProtocol where Self: ObservableObject { static var cache: RemoteImageCache { get set } static var cacheKeyProvider: RemoteImageCacheKeyProvider { get set } var state: RemoteImageState { get set } func fetchImage(ofType type: RemoteImageType) } #endif
23.105263
72
0.749431
c1e62a504c97c40242cc1487fa9746c595e517b7
2,190
// // LayoutYTarget.swift // FlexibleLayout // // Created by Kacper Harasim on 14/07/2017. // Copyright © 2017 Harasim. All rights reserved. // import Foundation #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif public struct LayoutYTarget { let view: FlexibleView let kind: Kind enum Kind { case top case bottom case centerY case topMargin case bottomMargin case centerYWithinMargins case firstBaseline case lastBaseline } init(kind: Kind, view: FlexibleView) { self.kind = kind self.view = view } var attribute: FlexibleLayoutAttribute { switch kind { case .top: return .top case .bottom: return .bottom case .centerY: return .centerY case .firstBaseline: return .firstBaseline case .lastBaseline: return .lastBaseline default: break } #if os(iOS) || os(tvOS) switch kind { case .topMargin: return .topMargin case .bottomMargin: return .bottomMargin case .centerYWithinMargins: return .centerYWithinMargins default: break } #endif fatalError("Should never happen") } @available(iOS 9.0, *) @available(OSX 10.11, *) var anchor: NSLayoutYAxisAnchor { switch kind { case .top: return view.topAnchor case .bottom: return view.bottomAnchor case .centerY: return view.centerYAnchor case .firstBaseline: return view.firstBaselineAnchor case .lastBaseline: return view.lastBaselineAnchor default: break } #if os(iOS) || os(tvOS) switch kind { case .topMargin: return view.layoutMarginsGuide.topAnchor case .bottomMargin: return view.layoutMarginsGuide.bottomAnchor case .centerYWithinMargins: return view.layoutMarginsGuide.centerYAnchor default: break } #endif fatalError("Should never happen") } public func to(_ other: LayoutYTarget) -> VerticalFlexibleSpaceConstructable { return VerticalFlexibleSpaceConstructable(from: self, to: other) } }
26.385542
82
0.62968
1c544f486100969ec79388c202762a1130ae7bf3
3,962
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module -o %t %S/sil_witness_tables_external_conformance.swift // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -I %t -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 import sil_witness_tables_external_conformance // FIXME: This should be a SIL test, but we can't parse sil_witness_tables // yet. protocol A {} protocol P { associatedtype Assoc: A static func staticMethod() func instanceMethod() } protocol Q : P { func qMethod() } protocol QQ { func qMethod() } struct AssocConformer: A {} struct Conformer: Q, QQ { typealias Assoc = AssocConformer static func staticMethod() {} func instanceMethod() {} func qMethod() {} } // CHECK: [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE:@"\$s39sil_witness_tables_external_conformance17ExternalConformerVAA0F1PAAWP"]] = external{{( dllimport)?}} global i8*, align 8 // CHECK: [[CONFORMER_Q_WITNESS_TABLE:@"\$s18sil_witness_tables9ConformerVAA1QAAWP"]] = hidden constant [3 x i8*] [ // CHECK: i8* bitcast ([5 x i8*]* [[CONFORMER_P_WITNESS_TABLE:@"\$s18sil_witness_tables9ConformerVAA1PAAWP"]] to i8*), // CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @"$s18sil_witness_tables9ConformerVAA1QA2aDP7qMethod{{[_0-9a-zA-Z]*}}FTW" to i8*) // CHECK: ] // CHECK: [[CONFORMER_P_WITNESS_TABLE]] = hidden constant [5 x i8*] [ // CHECK: i8* bitcast (i8** ()* @"$s18sil_witness_tables14AssocConformerVAA1AAAWa" to i8*) // CHECK: i8* bitcast (%swift.metadata_response (i64)* @"$s18sil_witness_tables14AssocConformerVMa" to i8*) // CHECK: i8* bitcast (void (%swift.type*, %swift.type*, i8**)* @"$s18sil_witness_tables9ConformerVAA1PA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW" to i8*), // CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @"$s18sil_witness_tables9ConformerVAA1PA2aDP14instanceMethod{{[_0-9a-zA-Z]*}}FTW" to i8*) // CHECK: ] // CHECK: [[CONFORMER2_P_WITNESS_TABLE:@"\$s18sil_witness_tables10Conformer2VAA1PAAWP"]] = hidden constant [5 x i8*] struct Conformer2: Q { typealias Assoc = AssocConformer static func staticMethod() {} func instanceMethod() {} func qMethod() {} } // CHECK-LABEL: define hidden swiftcc void @"$s18sil_witness_tables7erasure1cAA2QQ_pAA9ConformerV_tF"(%T18sil_witness_tables2QQP* noalias nocapture sret) // CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T18sil_witness_tables2QQP, %T18sil_witness_tables2QQP* %0, i32 0, i32 2 // CHECK-NEXT: store i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* [[CONFORMER_QQ_WITNESS_TABLE:@"\$s.*WP"]], i32 0, i32 0), i8*** [[WITNESS_TABLE_ADDR]], align 8 func erasure(c: Conformer) -> QQ { return c } // CHECK-LABEL: define hidden swiftcc void @"$s18sil_witness_tables15externalErasure1c0a1_b1_c1_D12_conformance9ExternalP_pAD0G9ConformerV_tF"(%T39sil_witness_tables_external_conformance9ExternalPP* noalias nocapture sret) // CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T39sil_witness_tables_external_conformance9ExternalPP, %T39sil_witness_tables_external_conformance9ExternalPP* %0, i32 0, i32 2 // CHECK-NEXT: store i8** [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE]], i8*** %2, align 8 func externalErasure(c: ExternalConformer) -> ExternalP { return c } // FIXME: why do these have different linkages? // CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s18sil_witness_tables14AssocConformerVMa"(i64) // CHECK: ret %swift.metadata_response { %swift.type* bitcast (i64* getelementptr inbounds {{.*}} @"$s18sil_witness_tables14AssocConformerVMf", i32 0, i32 1) to %swift.type*), i64 0 } // CHECK-LABEL: define hidden i8** @"$s18sil_witness_tables9ConformerVAA1PAAWa"() // CHECK: ret i8** getelementptr inbounds ([5 x i8*], [5 x i8*]* @"$s18sil_witness_tables9ConformerVAA1PAAWP", i32 0, i32 0)
48.91358
222
0.740283
09d681974386046917217e5d0e3b37c5fc01f617
2,047
import SwiftUI struct ContentView: View { @State private var stateString: String = "" @State private var emailString: String = "" @State private var password: String = "" var body: some View { VStack { Text("Playing with TextField") .font(.largeTitle) .foregroundColor(.black) TextField("Place holder text", text: $stateString) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding(.init(top: 40, leading: 20, bottom: 100, trailing: 20)) Text("This text has just been updated: \n \(stateString)") .font(.custom("serif", fixedSize: 24)) .foregroundColor(.black) .lineLimit(nil) .multilineTextAlignment(.center) TextField("Enter an email adderess", text: $emailString, onEditingChanged: { status in print("Keyboard tapped status - \(status)") print(self.$emailString.wrappedValue) }) { print("The return key has been pressed") } .textContentType(.emailAddress) .textFieldStyle(RoundedBorderTextFieldStyle()) .font(.subheadline) .fixedSize() .padding() Text("A secure text field") .font(.largeTitle) .padding(.init(top: 40, leading: 20, bottom: 100, trailing: 20)) SecureField("Enter your password", text: $password, onCommit: { print(self.password) print("Returned pressed - done!") }) .foregroundColor(.red) .frame(height: 40) .textFieldStyle(RoundedBorderTextFieldStyle()) .border(Color.black, width: 1) .padding() Spacer() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
34.116667
98
0.522716
e0ef19e47ffc4c3e9ae0f9740f5e8612a50b5fde
2,180
// RUN: %target-typecheck-verify-swift -enable-objc-interop -import-objc-header %S/../Inputs/objc_direct.h // REQUIRES: objc_interop class BarSubclass: Bar { override func directMethod() -> String! { // expected-error@-1 {{instance method overrides a 'final' instance method}} // expected-error@-2 {{overriding non-open instance method outside of its defining module}} "" } override func directMethod2() -> String! { // expected-error@-1 {{instance method overrides a 'final' instance method}} // expected-error@-2 {{overriding non-open instance method outside of its defining module}} "" } override static func directClassMethod() -> String! { // expected-error@-1 {{static method overrides a 'final' class method}} // expected-error@-2 {{overriding non-open static method outside of its defining module}} "" } override static func directClassMethod2() -> String! { // expected-error@-1 {{static method overrides a 'final' class method}} // expected-error@-2 {{overriding non-open static method outside of its defining module}} "" } override func directProtocolMethod() -> String! { // expected-error@-1 {{instance method overrides a 'final' instance method}} // expected-error@-2 {{overriding non-open instance method outside of its defining module}} "" } override var directProperty: Int32 { // expected-error@-1 {{property overrides a 'final' property}} // expected-error@-2 {{overriding non-open property outside of its defining module}} get {0} set(value) {} } override var directProperty2: Int32 { // expected-error@-1 {{property overrides a 'final' property}} // expected-error@-2 {{overriding non-open property outside of its defining module}} get {0} set(value) {} } override subscript(index: Int32) -> Int32 { // expected-error@-1 {{subscript overrides a 'final' subscript}} // expected-error@-2 {{overriding non-open subscript outside of its defining module}} get {0} set(value) {} } }
43.6
106
0.637615
e00d8f06ed93630979b770347381b64c43c9f912
37,379
// RUN: %target-swift-emit-silgen -module-name function_conversion -primary-file %s | %FileCheck %s // RUN: %target-swift-emit-ir -module-name function_conversion -primary-file %s // Check SILGen against various FunctionConversionExprs emitted by Sema. // ==== Representation conversions // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion7cToFuncyS2icS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_guaranteed (Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @$sS2iIetCyd_S2iIegyd_TR // CHECK: [[FUNC:%.*]] = partial_apply [callee_guaranteed] [[THUNK]](%0) // CHECK: return [[FUNC]] func cToFunc(_ arg: @escaping @convention(c) (Int) -> Int) -> (Int) -> Int { return arg } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion8cToBlockyS2iXBS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] // CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) (Int) -> Int // CHECK: return [[COPY]] func cToBlock(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(block) (Int) -> Int { return arg } // ==== Throws variance // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToThrowsyyyKcyycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @owned @callee_guaranteed () -> @error Error // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> ()): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> () to $@callee_guaranteed () -> @error Error // CHECK: return [[FUNC]] // CHECK: } // end sil function '$s19function_conversion12funcToThrowsyyyKcyycF' func funcToThrows(_ x: @escaping () -> ()) -> () throws -> () { return x } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12thinToThrowsyyyKXfyyXfF : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error Error // CHECK: [[FUNC:%.*]] = convert_function %0 : $@convention(thin) () -> () to $@convention(thin) () -> @error Error // CHECK: return [[FUNC]] : $@convention(thin) () -> @error Error func thinToThrows(_ x: @escaping @convention(thin) () -> ()) -> @convention(thin) () throws -> () { return x } // FIXME: triggers an assert because we always do a thin to thick conversion on DeclRefExprs /* func thinFunc() {} func thinToThrows() { let _: @convention(thin) () -> () = thinFunc } */ // ==== Class downcasts and upcasts class Feral {} class Domesticated : Feral {} // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> @owned Domesticated) -> @owned @callee_guaranteed () -> @owned Feral { // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> @owned Domesticated): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> @owned Domesticated to $@callee_guaranteed () -> @owned Feral // CHECK: return [[FUNC]] // CHECK: } // end sil function '$s19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF' func funcToUpcast(_ x: @escaping () -> Domesticated) -> () -> Feral { return x } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToUpcastyyAA12DomesticatedCcyAA5FeralCcF : $@convention(thin) (@guaranteed @callee_guaranteed (@guaranteed Feral) -> ()) -> @owned @callee_guaranteed (@guaranteed Domesticated) -> () // CHECK: bb0([[ARG:%.*]] : // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed (@guaranteed Feral) -> () to $@callee_guaranteed (@guaranteed Domesticated) -> (){{.*}} // CHECK: return [[FUNC]] func funcToUpcast(_ x: @escaping (Feral) -> ()) -> (Domesticated) -> () { return x } // ==== Optionals struct Trivial { let n: Int8 } class C { let n: Int8 init(n: Int8) { self.n = n } } struct Loadable { let c: C var n: Int8 { return c.n } init(n: Int8) { c = C(n: n) } } struct AddrOnly { let a: Any var n: Int8 { return a as! Int8 } init(n: Int8) { a = n } } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion19convOptionalTrivialyyAA0E0VADSgcF func convOptionalTrivial(_ t1: @escaping (Trivial?) -> Trivial) { // CHECK: function_ref @$s19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR // CHECK: partial_apply let _: (Trivial) -> Trivial? = t1 // CHECK: function_ref @$s19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR // CHECK: partial_apply let _: (Trivial?) -> Trivial? = t1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial> // CHECK: [[ENUM:%.*]] = enum $Optional<Trivial> // CHECK-NEXT: apply %1([[ENUM]]) // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR : $@convention(thin) (Optional<Trivial>, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial> // CHECK: apply %1(%0) // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: return // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion20convOptionalLoadableyyAA0E0VADSgcF func convOptionalLoadable(_ l1: @escaping (Loadable?) -> Loadable) { // CHECK: function_ref @$s19function_conversion8LoadableVSgACIeggo_AcDIeggo_TR // CHECK: partial_apply let _: (Loadable) -> Loadable? = l1 // CHECK: function_ref @$s19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR // CHECK: partial_apply let _: (Loadable?) -> Loadable? = l1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR : $@convention(thin) (@guaranteed Optional<Loadable>, @guaranteed @callee_guaranteed (@guaranteed Optional<Loadable>) -> @owned Loadable) -> @owned Optional<Loadable> // CHECK: apply %1(%0) // CHECK-NEXT: enum $Optional<Loadable> // CHECK-NEXT: return // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion20convOptionalAddrOnlyyyAA0eF0VADSgcF func convOptionalAddrOnly(_ a1: @escaping (AddrOnly?) -> AddrOnly) { // CHECK: function_ref @$s19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR // CHECK: partial_apply let _: (AddrOnly?) -> AddrOnly? = a1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR : $@convention(thin) (@in_guaranteed Optional<AddrOnly>, @guaranteed @callee_guaranteed (@in_guaranteed Optional<AddrOnly>) -> @out AddrOnly) -> @out Optional<AddrOnly> // CHECK: [[TEMP:%.*]] = alloc_stack $AddrOnly // CHECK-NEXT: apply %2([[TEMP]], %1) // CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly> // CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*AddrOnly // CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly> // CHECK-NEXT: tuple () // CHECK-NEXT: dealloc_stack {{.*}} : $*AddrOnly // CHECK-NEXT: return // ==== Existentials protocol Q { var n: Int8 { get } } protocol P : Q {} extension Trivial : P {} extension Loadable : P {} extension AddrOnly : P {} // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion22convExistentialTrivial_2t3yAA0E0VAA1Q_pc_AeaF_pSgctF func convExistentialTrivial(_ t2: @escaping (Q) -> Trivial, t3: @escaping (Q?) -> Trivial) { // CHECK: function_ref @$s19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR // CHECK: partial_apply let _: (Trivial) -> P = t2 // CHECK: function_ref @$s19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR // CHECK: partial_apply let _: (Trivial?) -> P = t3 // CHECK: function_ref @$s19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR // CHECK: partial_apply let _: (P) -> P = t2 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> Trivial) -> @out P // CHECK: alloc_stack $Q // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK-NEXT: apply // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR // CHECK: switch_enum // CHECK: bb1([[TRIVIAL:%.*]] : $Trivial): // CHECK: init_existential_addr // CHECK: init_enum_data_addr // CHECK: copy_addr // CHECK: inject_enum_addr // CHECK: bb2: // CHECK: inject_enum_addr // CHECK: bb3: // CHECK: apply // CHECK: init_existential_addr // CHECK: store // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> Trivial) -> @out P // CHECK: [[TMP:%.*]] = alloc_stack $Q // CHECK-NEXT: open_existential_addr immutable_access %1 : $*P // CHECK-NEXT: init_existential_addr [[TMP]] : $*Q // CHECK-NEXT: copy_addr {{.*}} to [initialization] {{.*}} // CHECK-NEXT: apply // CHECK-NEXT: init_existential_addr // CHECK-NEXT: store // CHECK: destroy_addr // CHECK: return // ==== Existential metatypes // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion23convExistentialMetatypeyyAA7TrivialVmAA1Q_pXpSgcF func convExistentialMetatype(_ em: @escaping (Q.Type?) -> Trivial.Type) { // CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR // CHECK: partial_apply let _: (Trivial.Type) -> P.Type = em // CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR // CHECK: partial_apply let _: (Trivial.Type?) -> P.Type = em // CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR // CHECK: partial_apply let _: (P.Type) -> P.Type = em } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR : $@convention(thin) (@thin Trivial.Type, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: [[META:%.*]] = metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype [[META]] : $@thick Trivial.Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK-NEXT: apply // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR : $@convention(thin) (Optional<@thin Trivial.Type>, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: switch_enum %0 : $Optional<@thin Trivial.Type> // CHECK: bb1([[META:%.*]] : $@thin Trivial.Type): // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK: bb2: // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK: bb3({{.*}}): // CHECK-NEXT: apply // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR : $@convention(thin) (@thick P.Type, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type // CHECK: open_existential_metatype %0 : $@thick P.Type to $@thick (@opened({{.*}}) P).Type // CHECK-NEXT: init_existential_metatype %2 : $@thick (@opened({{.*}}) P).Type, $@thick Q.Type // CHECK-NEXT: enum $Optional<@thick Q.Type> // CHECK-NEXT: apply %1 // CHECK-NEXT: metatype $@thick Trivial.Type // CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type // CHECK-NEXT: return // ==== Class metatype upcasts class Parent {} class Child : Parent {} // Note: we add a Trivial => Trivial? conversion here to force a thunk // to be generated // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion18convUpcastMetatype_2c5yAA5ChildCmAA6ParentCm_AA7TrivialVSgtc_AEmAGmSg_AJtctF func convUpcastMetatype(_ c4: @escaping (Parent.Type, Trivial?) -> Child.Type, c5: @escaping (Parent.Type?, Trivial?) -> Child.Type) { // CHECK: function_ref @$s19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR // CHECK: partial_apply let _: (Child.Type, Trivial) -> Parent.Type = c4 // CHECK: function_ref @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR // CHECK: partial_apply let _: (Child.Type, Trivial) -> Parent.Type = c5 // CHECK: function_ref @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR // CHECK: partial_apply let _: (Child.Type?, Trivial) -> Parent.Type? = c5 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (@thick Parent.Type, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type // CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type // CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type // CHECK: enum $Optional<@thick Parent.Type> // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR : $@convention(thin) (Optional<@thick Child.Type>, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> Optional<@thick Parent.Type> // CHECK: unchecked_trivial_bit_cast %0 : $Optional<@thick Child.Type> to $Optional<@thick Parent.Type> // CHECK: apply // CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type // CHECK: enum $Optional<@thick Parent.Type> // CHECK: return // ==== Function to existential -- make sure we maximally abstract it // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion19convFuncExistentialyyS2icypcF : $@convention(thin) (@guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> () // CHECK: bb0([[ARG:%.*]] : // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @$sypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR : // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_THUNK]]([[ARG_COPY]]) // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '$s19function_conversion19convFuncExistentialyyS2icypcF' func convFuncExistential(_ f1: @escaping (Any) -> (Int) -> Int) { let _: (@escaping (Int) -> Int) -> Any = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> @out Any { // CHECK: [[EXISTENTIAL:%.*]] = alloc_stack $Any // CHECK: [[COPIED_VAL:%.*]] = copy_value // CHECK: function_ref @$sS2iIegyd_S2iIegnr_TR // CHECK-NEXT: [[PA:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[COPIED_VAL]]) // CHECK-NEXT: [[CF:%.*]] = convert_function [[PA]] // CHECK-NEXT: init_existential_addr [[EXISTENTIAL]] : $*Any, $(Int) -> Int // CHECK-NEXT: store [[CF]] // CHECK-NEXT: apply // CHECK: function_ref @$sS2iIegyd_S2iIegnr_TR // CHECK-NEXT: partial_apply // CHECK-NEXT: convert_function // CHECK-NEXT: init_existential_addr %0 : $*Any, $(Int) -> Int // CHECK-NEXT: store {{.*}} to {{.*}} : $*@callee_guaranteed <τ_0_0, τ_0_1> in (@in_guaranteed τ_0_0) -> @out τ_0_1 for <Int, Int> // CHECK: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS2iIegyd_S2iIegnr_TR : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> Int) -> @out Int // CHECK: [[LOADED:%.*]] = load [trivial] %1 : $*Int // CHECK-NEXT: apply %2([[LOADED]]) // CHECK-NEXT: store {{.*}} to [trivial] %0 // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK: return [[VOID]] // ==== Class-bound archetype upcast // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion29convClassBoundArchetypeUpcast{{[_0-9a-zA-Z]*}}F func convClassBoundArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent) -> (T, Trivial)) { // CHECK: function_ref @$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR // CHECK: partial_apply let _: (T) -> (Parent, Trivial?) = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR : $@convention(thin) <T where T : Parent> (@guaranteed T, @guaranteed @callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)) -> (@owned Parent, Optional<Trivial>) // CHECK: bb0([[ARG:%.*]] : @guaranteed $T, [[CLOSURE:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)): // CHECK: [[CASTED_ARG:%.*]] = upcast [[ARG]] : $T to $Parent // CHECK: [[RESULT:%.*]] = apply %1([[CASTED_ARG]]) // CHECK: ([[LHS:%.*]], [[RHS:%.*]]) = destructure_tuple [[RESULT]] // CHECK: [[LHS_CAST:%.*]] = upcast [[LHS]] : $T to $Parent // CHECK: [[RHS_OPT:%.*]] = enum $Optional<Trivial>, #Optional.some!enumelt.1, [[RHS]] // CHECK: [[RESULT:%.*]] = tuple ([[LHS_CAST]] : $Parent, [[RHS_OPT]] : $Optional<Trivial>) // CHECK: return [[RESULT]] // CHECK: } // end sil function '$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR' // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion37convClassBoundMetatypeArchetypeUpcast{{[_0-9a-zA-Z]*}}F func convClassBoundMetatypeArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent.Type) -> (T.Type, Trivial)) { // CHECK: function_ref @$s19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR // CHECK: partial_apply let _: (T.Type) -> (Parent.Type, Trivial?) = f1 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR : $@convention(thin) <T where T : Parent> (@thick T.Type, @guaranteed @callee_guaranteed (@thick Parent.Type) -> (@thick T.Type, Trivial)) -> (@thick Parent.Type, Optional<Trivial>) // CHECK: bb0([[META:%.*]] : // CHECK: upcast %0 : $@thick T.Type // CHECK-NEXT: apply // CHECK-NEXT: destructure_tuple // CHECK-NEXT: upcast {{.*}} : $@thick T.Type to $@thick Parent.Type // CHECK-NEXT: enum $Optional<Trivial> // CHECK-NEXT: tuple // CHECK-NEXT: return // ==== Make sure we destructure one-element tuples // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion15convTupleScalar_2f22f3yyAA1Q_pc_yAaE_pcySi_SitSgctF // CHECK: function_ref @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR // CHECK: function_ref @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR // CHECK: function_ref @$sSi_SitSgIegy_S2iIegyy_TR // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> ()) -> () // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sSi_SitSgIegy_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (Optional<(Int, Int)>) -> ()) -> () func convTupleScalar(_ f1: @escaping (Q) -> (), f2: @escaping (_ parent: Q) -> (), f3: @escaping (_ tuple: (Int, Int)?) -> ()) { let _: (P) -> () = f1 let _: (P) -> () = f2 let _: ((Int, Int)) -> () = f3 } func convTupleScalarOpaque<T>(_ f: @escaping (T...) -> ()) -> ((_ args: T...) -> ())? { return f } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> @owned @callee_guaranteed (Int) -> Optional<(Int, Int)> // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)): // CHECK: [[FN:%.*]] = copy_value [[ARG]] // CHECK: [[THUNK_FN:%.*]] = function_ref @$sS3iIegydd_S2i_SitSgIegyd_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[FN]]) // CHECK-NEXT: return [[THUNK]] // CHECK-NEXT: } // end sil function '$s19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF' // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS3iIegydd_S2i_SitSgIegyd_TR : $@convention(thin) (Int, @guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> Optional<(Int, Int)> // CHECK: bb0(%0 : $Int, %1 : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)): // CHECK: [[RESULT:%.*]] = apply %1(%0) // CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Int) // CHECK-NEXT: [[OPTIONAL:%.*]] = enum $Optional<(Int, Int)>, #Optional.some!enumelt.1, [[RESULT]] // CHECK-NEXT: return [[OPTIONAL]] // CHECK-NEXT: } // end sil function '$sS3iIegydd_S2i_SitSgIegyd_TR' func convTupleToOptionalDirect(_ f: @escaping (Int) -> (Int, Int)) -> (Int) -> (Int, Int)? { return f } // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF : $@convention(thin) <T> (@guaranteed @callee_guaranteed <τ_0_0, τ_0_1, τ_0_2> in (@in_guaranteed τ_0_0) -> (@out τ_0_1, @out τ_0_2) for <T, T, T>) -> @owned @callee_guaranteed <τ_0_0, τ_0_1, τ_0_2> in (@in_guaranteed τ_0_0) -> @out Optional<(τ_0_1, τ_0_2)> for <T, T, T> // CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed <τ_0_0, τ_0_1, τ_0_2> in (@in_guaranteed τ_0_0) -> (@out τ_0_1, @out τ_0_2) for <T, T, T>): // CHECK: [[FN:%.*]] = copy_value [[ARG]] // CHECK-NEXT: [[FN_CONV:%.*]] = convert_function [[FN]] // CHECK: [[THUNK_FN:%.*]] = function_ref @$sxxxIegnrr_xx_xtSgIegnr_lTR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<T>([[FN_CONV]]) // CHECK-NEXT: [[THUNK_CONV:%.*]] = convert_function [[THUNK]] // CHECK-NEXT: return [[THUNK_CONV]] // CHECK-NEXT: } // end sil function '$s19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF' // CHECK: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sxxxIegnrr_xx_xtSgIegnr_lTR : $@convention(thin) <T> (@in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)) -> @out Optional<(T, T)> // CHECK: bb0(%0 : $*Optional<(T, T)>, %1 : $*T, %2 : @guaranteed $@callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)): // CHECK: [[OPTIONAL:%.*]] = init_enum_data_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt.1 // CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 0 // CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 1 // CHECK-NEXT: apply %2([[LEFT]], [[RIGHT]], %1) // CHECK-NEXT: inject_enum_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt.1 // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK: return [[VOID]] func convTupleToOptionalIndirect<T>(_ f: @escaping (T) -> (T, T)) -> (T) -> (T, T)? { return f } // ==== Make sure we support AnyHashable erasure // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion15convAnyHashable1tyx_tSHRzlF // CHECK: function_ref @$s19function_conversion15convAnyHashable1tyx_tSHRzlFSbs0dE0V_AEtcfU_ // CHECK: function_ref @$ss11AnyHashableVABSbIegnnd_xxSbIegnnd_SHRzlTR // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$ss11AnyHashableVABSbIegnnd_xxSbIegnnd_SHRzlTR : $@convention(thin) <T where T : Hashable> (@in_guaranteed T, @in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed AnyHashable, @in_guaranteed AnyHashable) -> Bool) -> Bool // CHECK: alloc_stack $AnyHashable // CHECK: function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF // CHECK: apply {{.*}}<T> // CHECK: alloc_stack $AnyHashable // CHECK: function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF // CHECK: apply {{.*}}<T> // CHECK: return func convAnyHashable<T : Hashable>(t: T) { let fn: (T, T) -> Bool = { (x: AnyHashable, y: AnyHashable) in x == y } } // ==== Convert exploded tuples to Any or Optional<Any> // CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12convTupleAnyyyyyc_Si_SitycyypcyypSgctF // CHECK: function_ref @$sIeg_ypIegr_TR // CHECK: partial_apply // CHECK: function_ref @$sIeg_ypSgIegr_TR // CHECK: partial_apply // CHECK: function_ref @$sS2iIegdd_ypIegr_TR // CHECK: partial_apply // CHECK: function_ref @$sS2iIegdd_ypSgIegr_TR // CHECK: partial_apply // CHECK: function_ref @$sypIegn_S2iIegyy_TR // CHECK: partial_apply // CHECK: function_ref @$sypSgIegn_S2iIegyy_TR // CHECK: partial_apply func convTupleAny(_ f1: @escaping () -> (), _ f2: @escaping () -> (Int, Int), _ f3: @escaping (Any) -> (), _ f4: @escaping (Any?) -> ()) { let _: () -> Any = f1 let _: () -> Any? = f1 let _: () -> Any = f2 let _: () -> Any? = f2 let _: ((Int, Int)) -> () = f3 let _: ((Int, Int)) -> () = f4 } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sIeg_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Any // CHECK: init_existential_addr %0 : $*Any, $() // CHECK-NEXT: apply %1() // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sIeg_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Optional<Any> // CHECK: [[ENUM_PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Optional<Any>, #Optional.some!enumelt.1 // CHECK-NEXT: init_existential_addr [[ENUM_PAYLOAD]] : $*Any, $() // CHECK-NEXT: apply %1() // CHECK-NEXT: inject_enum_addr %0 : $*Optional<Any>, #Optional.some!enumelt.1 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS2iIegdd_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Any // CHECK: [[ANY_PAYLOAD:%.*]] = init_existential_addr %0 // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RESULT:%.*]] = apply %1() // CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]] // CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sS2iIegdd_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Optional<Any> { // CHECK: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr %0 // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[OPTIONAL_PAYLOAD]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: [[RESULT:%.*]] = apply %1() // CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]] // CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: inject_enum_addr %0 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sypIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> ()) -> () // CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: apply %2([[ANY_VALUE]]) // CHECK-NEXT: tuple () // CHECK-NEXT: destroy_addr [[ANY_VALUE]] // CHECK-NEXT: dealloc_stack [[ANY_VALUE]] // CHECK-NEXT: return // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] [ossa] @$sypSgIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Optional<Any>) -> ()) -> () // CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any // CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]] // CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]] // CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]] // CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]] // CHECK-NEXT: [[OPTIONAL_VALUE:%.*]] = alloc_stack $Optional<Any> // CHECK-NEXT: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: copy_addr [take] [[ANY_VALUE]] to [initialization] [[OPTIONAL_PAYLOAD]] // CHECK-NEXT: inject_enum_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: apply %2([[OPTIONAL_VALUE]]) // CHECK-NEXT: tuple () // CHECK-NEXT: destroy_addr [[OPTIONAL_VALUE]] // CHECK-NEXT: dealloc_stack [[OPTIONAL_VALUE]] // CHECK-NEXT: dealloc_stack [[ANY_VALUE]] // CHECK-NEXT: return // ==== Support collection subtyping in function argument position protocol Z {} class A: Z {} func foo_arr<T: Z>(type: T.Type, _ fn: ([T]?) -> Void) {} func foo_map<T: Z>(type: T.Type, _ fn: ([Int: T]) -> Void) {} func rdar35702810() { let fn_arr: ([Z]?) -> Void = { _ in } let fn_map: ([Int: Z]) -> Void = { _ in } // CHECK: function_ref @$ss15_arrayForceCastySayq_GSayxGr0_lF : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1> // CHECK: apply %5<A, Z>(%4) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1> foo_arr(type: A.self, fn_arr) // CHECK: function_ref @$ss17_dictionaryUpCastySDyq0_q1_GSDyxq_GSHRzSHR0_r2_lF : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> // CHECK: apply %2<Int, A, Int, Z>(%0) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> // CHECK: apply %1(%4) : $@callee_guaranteed (@guaranteed Dictionary<Int, Z>) -> () foo_map(type: A.self, fn_map) } protocol X: Hashable {} class B: X { func hash(into hasher: inout Hasher) {} static func == (lhs: B, rhs: B) -> Bool { return true } } func bar_arr<T: X>(type: T.Type, _ fn: ([T]?) -> Void) {} func bar_map<T: X>(type: T.Type, _ fn: ([T: Int]) -> Void) {} func bar_set<T: X>(type: T.Type, _ fn: (Set<T>) -> Void) {} func rdar35702810_anyhashable() { let fn_arr: ([AnyHashable]?) -> Void = { _ in } let fn_map: ([AnyHashable: Int]) -> Void = { _ in } let fn_set: (Set<AnyHashable>) -> Void = { _ in } // CHECK: [[FN:%.*]] = function_ref @$sSays11AnyHashableVGSgIegg_Say19function_conversion1BCGSgIegg_TR : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> () // CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Optional<Array<B>>) -> () to $@noescape @callee_guaranteed (@guaranteed Optional<Array<B>>) -> () bar_arr(type: B.self, fn_arr) // CHECK: [[FN:%.*]] = function_ref @$sSDys11AnyHashableVSiGIegg_SDy19function_conversion1BCSiGIegg_TR : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> () // CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Dictionary<B, Int>) -> () to $@noescape @callee_guaranteed (@guaranteed Dictionary<B, Int>) -> () bar_map(type: B.self, fn_map) // CHECK: [[FN:%.*]] = function_ref @$sShys11AnyHashableVGIegg_Shy19function_conversion1BCGIegg_TR : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> () // CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> () // CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Set<B>) -> () to $@noescape @callee_guaranteed (@guaranteed Set<B>) -> () bar_set(type: B.self, fn_set) } // ==== Function conversion with parameter substToOrig reabstraction. struct FunctionConversionParameterSubstToOrigReabstractionTest { typealias SelfTy = FunctionConversionParameterSubstToOrigReabstractionTest class Klass: Error {} struct Foo<T> { static func enum1Func(_ : (T) -> Foo<Error>) -> Foo<Error> { // Just to make it compile. return Optional<Foo<Error>>.none! } } static func bar<T>(t: T) -> Foo<T> { // Just to make it compile. return Optional<Foo<T>>.none! } static func testFunc() -> Foo<Error> { return Foo<Klass>.enum1Func(SelfTy.bar) } } // CHECK: sil {{.*}} [ossa] @$sS4SIgggoo_S2Ss11AnyHashableVyps5Error_pIegggrrzo_TR // CHECK: [[TUPLE:%.*]] = apply %4(%2, %3) : $@noescape @callee_guaranteed (@guaranteed String, @guaranteed String) -> (@owned String, @owned String) // CHECK: ([[LHS:%.*]], [[RHS:%.*]]) = destructure_tuple [[TUPLE]] // CHECK: [[ADDR:%.*]] = alloc_stack $String // CHECK: store [[LHS]] to [init] [[ADDR]] : $*String // CHECK: [[CVT:%.*]] = function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF : $@convention(thin) <τ_0_0 where τ_0_0 : Hashable> (@in_guaranteed τ_0_0) -> @out AnyHashable // CHECK: apply [[CVT]]<String>(%0, [[ADDR]]) // CHECK: } // end sil function '$sS4SIgggoo_S2Ss11AnyHashableVyps5Error_pIegggrrzo_TR' func dontCrash() { let userInfo = ["hello": "world"] let d = [AnyHashable: Any](uniqueKeysWithValues: userInfo.map { ($0.key, $0.value) }) } struct Butt<T> { var foo: () throws -> T } @_silgen_name("butt") func butt() -> Butt<Any> func foo() throws -> Any { return try butt().foo() }
54.172464
376
0.666069
75f5313acf99e2978a41961314c26b6c14f61a4e
3,997
// // UIView+Wave.swift // GlowEffect // // Created by Vigneshuvi on 14/07/17. // Copyright © 2017 Uvi. All rights reserved. // import UIKit @IBDesignable extension UIView { @IBInspectable public var enableWaveEffect:Bool { set { if newValue { self.startWaving() } } get { return self.enableWaveEffect; } } public func startWavingWithRepeatCount(repeatCount:Float) { self.startWavingWithColor(color: UIColor.lightGray, repeatCount: repeatCount); } // Create a pulsing, Waving view based on this one. public func startWaving() { self.isOpaque = false; self.clipsToBounds = false; self.startWavingWithColor(color: UIColor.lightGray, repeatCount: 1); } // Stop Waving by removing the animation from the superview public func stopWaving() { self.layer.removeAllAnimations(); } public func startWavingWithColor(color:UIColor, repeatCount:Float) { // Add Wave effect let borderLayer = CAShapeLayer() borderLayer.frame = self.bounds; let circlePath = UIBezierPath.init(roundedRect: self.bounds, cornerRadius: 5.0) borderLayer.path = circlePath.cgPath borderLayer.fillColor = color.cgColor borderLayer.strokeColor = UIColor.clear.cgColor borderLayer.opacity = 0.3 borderLayer.lineWidth = 20.0; // Start Transaction CATransaction.begin() // Scale Animation let scaleAnimation = CABasicAnimation(keyPath: "transform.scale") scaleAnimation.fromValue = NSValue.init(caTransform3D: CATransform3DIdentity) scaleAnimation.toValue = NSValue.init(caTransform3D: CATransform3DMakeScale(2.0, 2.0, 1)); scaleAnimation.repeatCount = 2 // Alpha Animation let alphaAnimation = CABasicAnimation(keyPath: "opacity") alphaAnimation.fromValue = [0.5]; alphaAnimation.toValue = [0]; alphaAnimation.repeatCount = 2 // Group Animations let animation:CAAnimationGroup = CAAnimationGroup.init(); animation.animations = [scaleAnimation, alphaAnimation]; animation.duration = 2.0; animation.repeatCount = repeatCount; // Set the Timing function. animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut); // Callback function CATransaction.setCompletionBlock { self.layer.removeAllAnimations(); borderLayer.backgroundColor = UIColor.clear.cgColor borderLayer.removeAllAnimations(); borderLayer.removeFromSuperlayer(); } borderLayer.add(animation, forKey: nil) self.layer.addSublayer(borderLayer); CATransaction.commit() } public func rippleEffect() { self.isOpaque = true; self.clipsToBounds = true; // Start Transaction CATransaction.begin() // Ripple Effect let rippleAnimation = CATransition(); rippleAnimation.delegate = self as? CAAnimationDelegate; rippleAnimation.duration = 1.5; rippleAnimation.fillMode = kCAFillModeRemoved; rippleAnimation.repeatCount = 1.0 rippleAnimation.startProgress = 0.0; rippleAnimation.endProgress = 0.99; rippleAnimation.isRemovedOnCompletion = true; rippleAnimation.type = "rippleEffect"; // Set the Timing function. rippleAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut); // Callback function CATransaction.setCompletionBlock { self.layer.removeAllAnimations(); } self.layer.add(rippleAnimation, forKey: nil) CATransaction.commit() } }
31.722222
105
0.624468
5d67d1ab1d1045022d5313e78e89caa263228b5d
8,946
public struct Tagged<Tag, RawValue> { public var rawValue: RawValue public init(rawValue: RawValue) { self.rawValue = rawValue } public func map<B>(_ f: (RawValue) -> B) -> Tagged<Tag, B> { return .init(rawValue: f(self.rawValue)) } } extension Tagged: CustomStringConvertible { public var description: String { return String(describing: self.rawValue) } } extension Tagged: RawRepresentable {} extension Tagged: CustomPlaygroundDisplayConvertible { public var playgroundDescription: Any { return self.rawValue } } // MARK: - Conditional Conformances extension Tagged: Collection where RawValue: Collection { public typealias Element = RawValue.Element public typealias Index = RawValue.Index public func index(after i: RawValue.Index) -> RawValue.Index { return rawValue.index(after: i) } public subscript(position: RawValue.Index) -> RawValue.Element { return rawValue[position] } public var startIndex: RawValue.Index { return rawValue.startIndex } public var endIndex: RawValue.Index { return rawValue.endIndex } public __consuming func makeIterator() -> RawValue.Iterator { return rawValue.makeIterator() } } extension Tagged: Comparable where RawValue: Comparable { public static func < (lhs: Tagged, rhs: Tagged) -> Bool { return lhs.rawValue < rhs.rawValue } } extension Tagged: Decodable where RawValue: Decodable { public init(from decoder: Decoder) throws { do { self.init(rawValue: try decoder.singleValueContainer().decode(RawValue.self)) } catch { self.init(rawValue: try .init(from: decoder)) } } } extension Tagged: Encodable where RawValue: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.rawValue) } } extension Tagged: Equatable where RawValue: Equatable {} extension Tagged: Error where RawValue: Error {} #if canImport(Foundation) import Foundation extension Tagged: LocalizedError where RawValue: Error { public var errorDescription: String? { return rawValue.localizedDescription } public var failureReason: String? { return (rawValue as? LocalizedError)?.failureReason } public var helpAnchor: String? { return (rawValue as? LocalizedError)?.helpAnchor } public var recoverySuggestion: String? { return (rawValue as? LocalizedError)?.recoverySuggestion } } #endif extension Tagged: ExpressibleByBooleanLiteral where RawValue: ExpressibleByBooleanLiteral { public typealias BooleanLiteralType = RawValue.BooleanLiteralType public init(booleanLiteral value: RawValue.BooleanLiteralType) { self.init(rawValue: RawValue(booleanLiteral: value)) } } extension Tagged: ExpressibleByExtendedGraphemeClusterLiteral where RawValue: ExpressibleByExtendedGraphemeClusterLiteral { public typealias ExtendedGraphemeClusterLiteralType = RawValue.ExtendedGraphemeClusterLiteralType public init(extendedGraphemeClusterLiteral: ExtendedGraphemeClusterLiteralType) { self.init(rawValue: RawValue(extendedGraphemeClusterLiteral: extendedGraphemeClusterLiteral)) } } extension Tagged: ExpressibleByFloatLiteral where RawValue: ExpressibleByFloatLiteral { public typealias FloatLiteralType = RawValue.FloatLiteralType public init(floatLiteral: FloatLiteralType) { self.init(rawValue: RawValue(floatLiteral: floatLiteral)) } } extension Tagged: ExpressibleByIntegerLiteral where RawValue: ExpressibleByIntegerLiteral { public typealias IntegerLiteralType = RawValue.IntegerLiteralType public init(integerLiteral: IntegerLiteralType) { self.init(rawValue: RawValue(integerLiteral: integerLiteral)) } } extension Tagged: ExpressibleByStringLiteral where RawValue: ExpressibleByStringLiteral { public typealias StringLiteralType = RawValue.StringLiteralType public init(stringLiteral: StringLiteralType) { self.init(rawValue: RawValue(stringLiteral: stringLiteral)) } } extension Tagged: ExpressibleByStringInterpolation where RawValue: ExpressibleByStringInterpolation { public typealias StringInterpolation = RawValue.StringInterpolation public init(stringInterpolation: Self.StringInterpolation) { self.init(rawValue: RawValue(stringInterpolation: stringInterpolation)) } } extension Tagged: ExpressibleByUnicodeScalarLiteral where RawValue: ExpressibleByUnicodeScalarLiteral { public typealias UnicodeScalarLiteralType = RawValue.UnicodeScalarLiteralType public init(unicodeScalarLiteral: UnicodeScalarLiteralType) { self.init(rawValue: RawValue(unicodeScalarLiteral: unicodeScalarLiteral)) } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) extension Tagged: Identifiable where RawValue: Identifiable { public typealias ID = RawValue.ID public var id: ID { return rawValue.id } } extension Tagged: LosslessStringConvertible where RawValue: LosslessStringConvertible { public init?(_ description: String) { guard let rawValue = RawValue(description) else { return nil } self.init(rawValue: rawValue) } } #if compiler(>=5) extension Tagged: AdditiveArithmetic where RawValue: AdditiveArithmetic { public static var zero: Tagged { return self.init(rawValue: .zero) } public static func + (lhs: Tagged, rhs: Tagged) -> Tagged { return self.init(rawValue: lhs.rawValue + rhs.rawValue) } public static func += (lhs: inout Tagged, rhs: Tagged) { lhs.rawValue += rhs.rawValue } public static func - (lhs: Tagged, rhs: Tagged) -> Tagged { return self.init(rawValue: lhs.rawValue - rhs.rawValue) } public static func -= (lhs: inout Tagged, rhs: Tagged) { lhs.rawValue -= rhs.rawValue } } extension Tagged: Numeric where RawValue: Numeric { public init?<T>(exactly source: T) where T: BinaryInteger { guard let rawValue = RawValue(exactly: source) else { return nil } self.init(rawValue: rawValue) } public var magnitude: RawValue.Magnitude { return self.rawValue.magnitude } public static func * (lhs: Tagged, rhs: Tagged) -> Tagged { return self.init(rawValue: lhs.rawValue * rhs.rawValue) } public static func *= (lhs: inout Tagged, rhs: Tagged) { lhs.rawValue *= rhs.rawValue } } #else extension Tagged: Numeric where RawValue: Numeric { public typealias Magnitude = RawValue.Magnitude public init?<T>(exactly source: T) where T: BinaryInteger { guard let rawValue = RawValue(exactly: source) else { return nil } self.init(rawValue: rawValue) } public var magnitude: RawValue.Magnitude { return self.rawValue.magnitude } public static func + (lhs: Tagged<Tag, RawValue>, rhs: Tagged<Tag, RawValue>) -> Tagged<Tag, RawValue> { return self.init(rawValue: lhs.rawValue + rhs.rawValue) } public static func += (lhs: inout Tagged<Tag, RawValue>, rhs: Tagged<Tag, RawValue>) { lhs.rawValue += rhs.rawValue } public static func * (lhs: Tagged, rhs: Tagged) -> Tagged { return self.init(rawValue: lhs.rawValue * rhs.rawValue) } public static func *= (lhs: inout Tagged, rhs: Tagged) { lhs.rawValue *= rhs.rawValue } public static func - (lhs: Tagged, rhs: Tagged) -> Tagged<Tag, RawValue> { return self.init(rawValue: lhs.rawValue - rhs.rawValue) } public static func -= (lhs: inout Tagged<Tag, RawValue>, rhs: Tagged<Tag, RawValue>) { lhs.rawValue -= rhs.rawValue } } #endif extension Tagged: Hashable where RawValue: Hashable {} extension Tagged: SignedNumeric where RawValue: SignedNumeric {} extension Tagged: Sequence where RawValue: Sequence { public typealias Iterator = RawValue.Iterator public __consuming func makeIterator() -> RawValue.Iterator { return rawValue.makeIterator() } } // Commenting these out for Joe. // // https://twitter.com/jckarter/status/985375396601282560 // //extension Tagged: ExpressibleByArrayLiteral where RawValue: ExpressibleByArrayLiteral { // public typealias ArrayLiteralElement = RawValue.ArrayLiteralElement // // public init(arrayLiteral elements: ArrayLiteralElement...) { // let f = unsafeBitCast( // RawValue.init(arrayLiteral:) as (ArrayLiteralElement...) -> RawValue, // to: (([ArrayLiteralElement]) -> RawValue).self // ) // // self.init(rawValue: f(elements)) // } //} // //extension Tagged: ExpressibleByDictionaryLiteral where RawValue: ExpressibleByDictionaryLiteral { // public typealias Key = RawValue.Key // public typealias Value = RawValue.Value // // public init(dictionaryLiteral elements: (Key, Value)...) { // let f = unsafeBitCast( // RawValue.init(dictionaryLiteral:) as ((Key, Value)...) -> RawValue, // to: (([(Key, Value)]) -> RawValue).self // ) // // self.init(rawValue: f(elements)) // } //} // MARK: - Coerce extension Tagged { public func coerced<Tag2>(to type: Tag2.Type) -> Tagged<Tag2, RawValue> { return unsafeBitCast(self, to: Tagged<Tag2, RawValue>.self) } }
29.919732
123
0.735971
2303528d749bd85ac502f72c9abf92164307e7c0
267
// // XALG_Visit.swift // XALG // // Created by Juguang Xiao on 17/03/2017. // import Swift class XALG_Visit<ObjectType> { var object : ObjectType? } class XALG_Visit_Vertex<VertexType> { var vertex : VertexType? var depth : Int? }
12.136364
42
0.621723
e458c38e60f7f65fc13c85cd719d4d340322bd8e
4,771
// // SettingsDataManager.swift // goSellSDK // // Copyright © 2019 Tap Payments. All rights reserved. // import func TapSwiftFixesV2.synchronized /// Settings data manager. import UIKit internal final class SettingsDataManager { // MARK: - Internal - internal typealias OptionalErrorClosure = (TapSDKError?) -> Void // MARK: Properties /// SDK settings. internal private(set) var settings: SDKSettingsData? { didSet { if let deviceID = self.settings?.deviceID { KeychainManager.deviceID = deviceID } } } // MARK: Methods internal func checkInitializationStatus(_ completion: @escaping OptionalErrorClosure) { synchronized(self) { [unowned self] in switch self.status { case .notInitiated: self.append(completion) self.callInitializationAPI() case .initiated: self.append(completion) case .succeed: guard self.settings != nil else { completion(TapSDKUnknownError(dataTask: nil)) return } completion(nil) } } } internal static func resetAllSettings() { self.storages?.values.forEach { $0.reset() } } // MARK: - Private - // MARK: Properties private var status: InitializationStatus = .notInitiated private var pendingCompletions: [OptionalErrorClosure] = [] private static var storages: [SDKMode: SettingsDataManager]? = [:] // MARK: Methods private init() {} private func append(_ completion: @escaping OptionalErrorClosure) { self.pendingCompletions.append(completion) } private func callInitializationAPI() { self.status = .initiated APIClient.shared.initSDK { [unowned self] (settings, error) in self.update(settings: settings, error: error) } } private func update(settings updatedSettings: SDKSettings?, error: TapSDKError?) { let unVerifiedApplicationError = (SettingsDataManager.shared.settings?.verifiedApplication ?? true) ? nil : TapSDKError(type: .unVerifiedApplication) var finalError:TapSDKError? if let nonnullError = error { finalError = nonnullError }else if let nonnullError = unVerifiedApplicationError { finalError = nonnullError print(nonnullError.description) } if let nonnullError = finalError { self.status = .notInitiated if self.pendingCompletions.count > 0 { self.callAllPendingCompletionsAndEmptyStack(nonnullError) } else { ErrorDataManager.handle(nonnullError, retryAction: { self.callInitializationAPI() }, alertDismissButtonClickHandler: nil) } } else { self.settings = updatedSettings?.data self.status = .succeed self.callAllPendingCompletionsAndEmptyStack(nil) } } private func callAllPendingCompletionsAndEmptyStack(_ error: TapSDKError?) { synchronized(self) { [unowned self] in for completion in self.pendingCompletions { completion(error) } self.pendingCompletions.removeAll() } } private func reset() { let userInfo: [String: String] = [ NSLocalizedDescriptionKey: "Merchant account data is missing." ] let underlyingError = NSError(domain: ErrorConstants.internalErrorDomain, code: InternalError.noMerchantData.rawValue, userInfo: userInfo) let error = TapSDKKnownError(type: .internal, error: underlyingError, response: nil, body: nil) self.update(settings: nil, error: error) } } // MARK: - Singleton extension SettingsDataManager: Singleton { internal static var shared: SettingsDataManager { if let existing = self.storages?[GoSellSDK.mode] { return existing } let instance = SettingsDataManager() var stores = self.storages ?? [:] stores[GoSellSDK.mode] = instance self.storages = stores return instance } } // MARK: - ImmediatelyDestroyable extension SettingsDataManager: ImmediatelyDestroyable { internal static func destroyInstance() { self.storages = nil } internal static var hasAliveInstance: Bool { return !(self.storages?.isEmpty ?? true) } }
24.848958
158
0.590652
79fad24a4e57aa979a3c97fa973a8c5f3e6d084a
2,498
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../Inputs/custom-modules -import-objc-header %S/Inputs/mixed-target/header.h -typecheck -primary-file %s %S/Inputs/mixed-target/other-file.swift -disable-objc-attr-requires-foundation-module -verify // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../Inputs/custom-modules -import-objc-header %S/Inputs/mixed-target/header.h -emit-sil -primary-file %s %S/Inputs/mixed-target/other-file.swift -disable-objc-attr-requires-foundation-module -o /dev/null -D SILGEN // REQUIRES: objc_interop func test(_ foo : FooProto) { _ = foo.bar as CInt _ = ExternIntX.x as CInt } @objc class ForwardClass : NSObject { } @objc protocol ForwardProto : NSObjectProtocol { } @objc class ForwardProtoAdopter : NSObject, ForwardProto { } @objc class PartialBaseClass { } @objc class PartialSubClass : NSObject { } func testCFunction() { doSomething(ForwardClass()) doSomethingProto(ForwardProtoAdopter()) doSomethingPartialBase(PartialBaseClass()) doSomethingPartialSub(PartialSubClass()) } class ProtoConformer : ForwardClassUser { @objc func consumeForwardClass(_ arg: ForwardClass) {} @objc var forward = ForwardClass() } func testProtocolWrapper(_ conformer: ForwardClassUser) { conformer.consumeForwardClass(conformer.forward) } func useProtocolWrapper() { testProtocolWrapper(ProtoConformer()) } func testStruct(_ p: Point2D) -> Point2D { var result = p result.y += 5 return result } #if !SILGEN func testSuppressed() { let _: __int128_t? = nil // expected-error{{use of undeclared type '__int128_t'}} } #endif func testMacro() { _ = CONSTANT as CInt } func testFoundationOverlay() { _ = NSUTF8StringEncoding // no ambiguity _ = NSUTF8StringEncoding as UInt // and we should get the overlay version } #if !SILGEN func testProtocolNamingConflict() { let a: ConflictingName1? var b: ConflictingName1Protocol? b = a // expected-error {{cannot assign value of type 'ConflictingName1?' to type 'ConflictingName1Protocol?'}} _ = b let c: ConflictingName2? var d: ConflictingName2Protocol? d = c // expected-error {{cannot assign value of type 'ConflictingName2?' to type 'ConflictingName2Protocol?'}} _ = d } #endif func testDeclsNestedInObjCContainers() { let _: NameInInterface = 0 let _: NameInProtocol = 0 let _: NameInCategory = 0 } func testReleaseClassWhoseMembersAreNeverLoaded( obj: ClassThatHasAProtocolTypedPropertyButMembersAreNeverLoaded) {}
28.386364
280
0.747398
abe3f792a0efcbf2078706b323ba94b582f1a1a0
1,549
// swift-tools-version:5.0 // // Package.swift // // Copyright (c) 2017 Abdullah Selek // 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 PackageDescription let package = Package( name: "Swifty360Player", platforms: [ .iOS(.v11), ], products: [ .library( name: "Swifty360Player", targets: ["Swifty360Player"]) ], targets: [ .target( name: "Swifty360Player", path: "Swifty360Player") ], swiftLanguageVersions: [.v5] )
35.204545
81
0.703034
763edb792d65adda73007eeb3de9424038eb53b1
1,461
/* * Copyright (c) 2011-2020 HERE Europe B.V. * All rights reserved. */ import UIKit import NMAKit class PlaceDetailViewController: UIViewController { @IBOutlet weak var placeNameLabel: UILabel! @IBOutlet weak var placeLocationLabel: UILabel! var placeLink: NMAPlaceLink? = nil override func viewDidLoad() { super.viewDidLoad() Helper.showIndicator(onView: self.view) // Fire a PlaceDetail request on the NMAPlaceLink passed from the previous controller. self.placeLink?.detailsRequest().start ( { request, data, inError in Helper.hideIndicator() guard inError == nil else { print("Place request returns error with error code:\((inError! as NSError).code)") return } if request is NMAPlaceRequest { // Display the name and the location of the place.Additional place details info ca also // be // retrieved at this moment as well.Please refer to the HERE Mobile SDK for iOS API doc for // details. if let place = data as? NMAPlace { self.placeNameLabel.text = place.name; } if let position = (data as? NMAPlace)?.location?.position { self.placeLocationLabel.text = "Position: \(position.latitude), \(position.longitude)" } } }) } }
33.976744
107
0.589322
388f59071a2452df1d6f2ec0efa04c1ac940ae83
8,502
/* file: variable.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY variable ABSTRACT SUPERTYPE OF ( ONEOF ( numeric_variable, boolean_variable, string_variable ) ) SUBTYPE OF ( generic_variable ); END_ENTITY; -- variable (line:33430 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) generic_expression (no local attributes) SUPER- ENTITY(2) simple_generic_expression (no local attributes) SUPER- ENTITY(3) generic_variable ATTR: interpretation, TYPE: environment -- INVERSE FOR syntactic_representation; ENTITY(SELF) variable (no local attributes) SUB- ENTITY(5) maths_real_variable (no local attributes) SUB- ENTITY(6) real_numeric_variable (no local attributes) SUB- ENTITY(7) maths_integer_variable (no local attributes) SUB- ENTITY(8) int_numeric_variable (no local attributes) SUB- ENTITY(9) numeric_variable (no local attributes) SUB- ENTITY(10) maths_boolean_variable (no local attributes) SUB- ENTITY(11) boolean_variable (no local attributes) SUB- ENTITY(12) maths_string_variable (no local attributes) SUB- ENTITY(13) string_variable (no local attributes) */ //MARK: - Partial Entity public final class _variable : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eVARIABLE.self } //ATTRIBUTES // (no local attributes) public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init() { super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 0 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } self.init( ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY variable ABSTRACT SUPERTYPE OF ( ONEOF ( numeric_variable, boolean_variable, string_variable ) ) SUBTYPE OF ( generic_variable ); END_ENTITY; -- variable (line:33430 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eVARIABLE : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _variable.self } public let partialEntity: _variable //MARK: SUPERTYPES public let super_eGENERIC_EXPRESSION: eGENERIC_EXPRESSION // [1] public let super_eSIMPLE_GENERIC_EXPRESSION: eSIMPLE_GENERIC_EXPRESSION // [2] public let super_eGENERIC_VARIABLE: eGENERIC_VARIABLE // [3] public var super_eVARIABLE: eVARIABLE { return self } // [4] //MARK: SUBTYPES public var sub_eMATHS_REAL_VARIABLE: eMATHS_REAL_VARIABLE? { // [5] return self.complexEntity.entityReference(eMATHS_REAL_VARIABLE.self) } public var sub_eREAL_NUMERIC_VARIABLE: eREAL_NUMERIC_VARIABLE? { // [6] return self.complexEntity.entityReference(eREAL_NUMERIC_VARIABLE.self) } public var sub_eMATHS_INTEGER_VARIABLE: eMATHS_INTEGER_VARIABLE? { // [7] return self.complexEntity.entityReference(eMATHS_INTEGER_VARIABLE.self) } public var sub_eINT_NUMERIC_VARIABLE: eINT_NUMERIC_VARIABLE? { // [8] return self.complexEntity.entityReference(eINT_NUMERIC_VARIABLE.self) } public var sub_eNUMERIC_VARIABLE: eNUMERIC_VARIABLE? { // [9] return self.complexEntity.entityReference(eNUMERIC_VARIABLE.self) } public var sub_eMATHS_BOOLEAN_VARIABLE: eMATHS_BOOLEAN_VARIABLE? { // [10] return self.complexEntity.entityReference(eMATHS_BOOLEAN_VARIABLE.self) } public var sub_eBOOLEAN_VARIABLE: eBOOLEAN_VARIABLE? { // [11] return self.complexEntity.entityReference(eBOOLEAN_VARIABLE.self) } public var sub_eMATHS_STRING_VARIABLE: eMATHS_STRING_VARIABLE? { // [12] return self.complexEntity.entityReference(eMATHS_STRING_VARIABLE.self) } public var sub_eSTRING_VARIABLE: eSTRING_VARIABLE? { // [13] return self.complexEntity.entityReference(eSTRING_VARIABLE.self) } //MARK: ATTRIBUTES /// __INVERSE__ attribute /// observing eENVIRONMENT .SYNTACTIC_REPRESENTATION /// - origin: SUPER( ``eGENERIC_VARIABLE`` ) public var INTERPRETATION: eENVIRONMENT? { get { return super_eGENERIC_VARIABLE.partialEntity._interpretation } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_variable.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(eGENERIC_EXPRESSION.self) else { return nil } self.super_eGENERIC_EXPRESSION = super1 guard let super2 = complexEntity?.entityReference(eSIMPLE_GENERIC_EXPRESSION.self) else { return nil } self.super_eSIMPLE_GENERIC_EXPRESSION = super2 guard let super3 = complexEntity?.entityReference(eGENERIC_VARIABLE.self) else { return nil } self.super_eGENERIC_VARIABLE = super3 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "VARIABLE", type: self, explicitAttributeCount: 0) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: eGENERIC_EXPRESSION.self) entityDef.add(supertype: eSIMPLE_GENERIC_EXPRESSION.self) entityDef.add(supertype: eGENERIC_VARIABLE.self) entityDef.add(supertype: eVARIABLE.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "INTERPRETATION", keyPath: \eVARIABLE.INTERPRETATION, kind: .inverse, source: .superEntity, mayYieldEntityReference: true) return entityDef } } }
32.450382
185
0.715479
28bbd29e764e965b74a006df5fe34e8ab92583c9
950
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var closure = { () -> Void in print("hello") } closure() var anotherClosure: () -> Void = { print("Hello") } anotherClosure() func runClousure(_ aClosure: () -> Void) { aClosure() } runClousure(anotherClosure ) runClousure { print("hello") } var yetAnotherClosure:(String, Int) -> Void = { (message: String, times: Int) -> Void in for _ in 0..<times { print(message) } } yetAnotherClosure("Hello world", 5) //var multiply:(Int, Int) -> Int = { (a: Int, b: Int) -> Int in // return a * b //} //var multiply:(Int, Int) -> Int = { // return $0 * $1 //} var multiply:(Int, Int) -> Int = { $0 * $1 } multiply(5, 5) var counter = 0 var counterClosure = { counter += 1 } counterClosure() counterClosure() counterClosure() counterClosure() counterClosure() counterClosure() counter counter = 0 counterClosure() counter //: [Next](@next)
14.84375
88
0.638947
acb08bc736857770774a1fb517e67f1dc5cb73a6
7,551
import XCTest import GRDB import SQLite import CoreData import RealmSwift private let expectedRowCount = 100_000 /// Here we test the extraction of models from rows class FetchRecordTests: XCTestCase { func testSQLite() { let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")! var connection: COpaquePointer = nil sqlite3_open_v2(databasePath, &connection, 0x00000004 /*SQLITE_OPEN_CREATE*/ | 0x00000002 /*SQLITE_OPEN_READWRITE*/, nil) self.measureBlock { var statement: COpaquePointer = nil sqlite3_prepare_v2(connection, "SELECT * FROM items", -1, &statement, nil) let columnNames = (Int32(0)..<10).map { String.fromCString(sqlite3_column_name(statement, $0))! } let index0 = Int32(columnNames.indexOf("i0")!) let index1 = Int32(columnNames.indexOf("i1")!) let index2 = Int32(columnNames.indexOf("i2")!) let index3 = Int32(columnNames.indexOf("i3")!) let index4 = Int32(columnNames.indexOf("i4")!) let index5 = Int32(columnNames.indexOf("i5")!) let index6 = Int32(columnNames.indexOf("i6")!) let index7 = Int32(columnNames.indexOf("i7")!) let index8 = Int32(columnNames.indexOf("i8")!) let index9 = Int32(columnNames.indexOf("i9")!) var items = [Item]() loop: while true { switch sqlite3_step(statement) { case 101 /*SQLITE_DONE*/: break loop case 100 /*SQLITE_ROW*/: let item = Item( i0: Int(sqlite3_column_int64(statement, index0)), i1: Int(sqlite3_column_int64(statement, index1)), i2: Int(sqlite3_column_int64(statement, index2)), i3: Int(sqlite3_column_int64(statement, index3)), i4: Int(sqlite3_column_int64(statement, index4)), i5: Int(sqlite3_column_int64(statement, index5)), i6: Int(sqlite3_column_int64(statement, index6)), i7: Int(sqlite3_column_int64(statement, index7)), i8: Int(sqlite3_column_int64(statement, index8)), i9: Int(sqlite3_column_int64(statement, index9))) items.append(item) break default: XCTFail() } } sqlite3_finalize(statement) XCTAssertEqual(items.count, expectedRowCount) XCTAssertEqual(items[0].i0, 0) XCTAssertEqual(items[1].i1, 1) XCTAssertEqual(items[expectedRowCount-1].i9, expectedRowCount-1) } sqlite3_close(connection) } func testFMDB() { // Here we test the loading of an array of Records. let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")! let dbQueue = FMDatabaseQueue(path: databasePath) self.measureBlock { var items = [Item]() dbQueue.inDatabase { db in if let rs = db.executeQuery("SELECT * FROM items", withArgumentsInArray: nil) { while rs.next() { let item = Item(dictionary: rs.resultDictionary()) items.append(item) } } } XCTAssertEqual(items.count, expectedRowCount) XCTAssertEqual(items[0].i0, 0) XCTAssertEqual(items[1].i1, 1) XCTAssertEqual(items[expectedRowCount-1].i9, expectedRowCount-1) } } func testGRDB() { let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")! let dbQueue = try! DatabaseQueue(path: databasePath) measureBlock { let items = dbQueue.inDatabase { db in Item.fetchAll(db, "SELECT * FROM items") } XCTAssertEqual(items.count, expectedRowCount) XCTAssertEqual(items[0].i0, 0) XCTAssertEqual(items[1].i1, 1) XCTAssertEqual(items[expectedRowCount-1].i9, expectedRowCount-1) } } func testSQLiteSwift() { let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceTests", ofType: "sqlite")! let db = try! Connection(databasePath) self.measureBlock { var items = [Item]() for row in try! db.prepare(itemsTable) { let item = Item( i0: row[i0Column], i1: row[i1Column], i2: row[i2Column], i3: row[i3Column], i4: row[i4Column], i5: row[i5Column], i6: row[i6Column], i7: row[i7Column], i8: row[i8Column], i9: row[i9Column]) items.append(item) } XCTAssertEqual(items.count, expectedRowCount) XCTAssertEqual(items[0].i0, 0) XCTAssertEqual(items[1].i1, 1) XCTAssertEqual(items[expectedRowCount-1].i9, expectedRowCount-1) } } func testCoreData() { let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceCoreDataTests", ofType: "sqlite")! let modelURL = NSBundle(forClass: self.dynamicType).URLForResource("PerformanceModel", withExtension: "momd")! let mom = NSManagedObjectModel(contentsOfURL: modelURL)! let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) try! psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: NSURL(fileURLWithPath: databasePath), options: nil) let moc = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) moc.persistentStoreCoordinator = psc measureBlock { let request = NSFetchRequest(entityName: "Item") let items = try! moc.executeFetchRequest(request) for item in items { item.valueForKey("i0") item.valueForKey("i1") item.valueForKey("i2") item.valueForKey("i3") item.valueForKey("i4") item.valueForKey("i5") item.valueForKey("i6") item.valueForKey("i7") item.valueForKey("i8") item.valueForKey("i9") } XCTAssertEqual(items.count, expectedRowCount) } } func testRealm() { let databasePath = NSBundle(forClass: self.dynamicType).pathForResource("PerformanceRealmTests", ofType: "realm")! let realm = try! Realm(path: databasePath) measureBlock { let items = realm.objects(RealmItem) var count = 0 for item in items { count += 1 _ = item.i0 _ = item.i1 _ = item.i2 _ = item.i3 _ = item.i4 _ = item.i5 _ = item.i6 _ = item.i7 _ = item.i8 _ = item.i9 } XCTAssertEqual(count, expectedRowCount) } } }
40.816216
139
0.545888
64a4542d7c59ca66a6f1afe3e148c70769b3f2c6
4,900
// // CNLSearchController.swift // CNLUIKitTools // // Created by Igor Smirnov on 01/12/2016. // Copyright © 2016 Complex Numbers. All rights reserved. // import UIKit public protocol CNLSearchControllerDelegate: class { func searchControllerNeedRefresh(_ controller: CNLSearchController) func searchControllerCancelled(_ controller: CNLSearchController) } open class CNLSearchController: NSObject, UISearchBarDelegate { weak var delegate: CNLSearchControllerDelegate? open var searchQueryText: String? open var searchBar = UISearchBar() open var searchBarButtonItem: UIBarButtonItem! open var searchButton: UIButton! open var navigationItem: UINavigationItem! open var isActive = false open func setupWithDelegate(_ delegate: CNLSearchControllerDelegate, navigationItem: UINavigationItem, buttonImage: UIImage?, searchQueryText: String? = nil) { self.delegate = delegate searchButton = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 30.0, height: 30.0)) searchButton.setImage(buttonImage, for: UIControlState()) searchButton.imageEdgeInsets = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0) searchButton.addTarget(self, action: #selector(searchButtonAction(_:)), for: .touchUpInside) searchBarButtonItem = UIBarButtonItem(customView: searchButton) self.navigationItem = navigationItem self.searchQueryText = searchQueryText searchBar.text = searchQueryText ?? "" searchBar.delegate = self searchBar.setShowsCancelButton(true, animated: false) updateState() } open func updateState() { if isActive { // remove the search button navigationItem.rightBarButtonItem = nil // add the search bar navigationItem.titleView = searchBar searchBar.becomeFirstResponder() } else { searchBar.resignFirstResponder() navigationItem.rightBarButtonItem = searchBarButtonItem navigationItem.titleView = nil } } open func activate(animated: Bool) { isActive = true updateState() if animated { searchBar.alpha = 0.0 UIView.animate( withDuration: 0.5, animations: { self.searchBar.alpha = 1.0 }, completion: { _ in self.searchBar.becomeFirstResponder() } ) } else { searchBar.alpha = 1.0 searchBar.becomeFirstResponder() } } open func deactivate(animated: Bool) { searchBar.resignFirstResponder() hideSearchBar(animated) isActive = false } open func hideSearchBar(_ animated: Bool) { searchBar.resignFirstResponder() //searchBar.setShowsCancelButton(false, animated: true) delegate?.searchControllerCancelled(self) if animated { UIView.animate( withDuration: 0.5, animations: { self.searchBar.alpha = 0.0 }, completion: { _ in self.navigationItem.titleView = nil self.navigationItem.rightBarButtonItem = self.searchBarButtonItem self.searchButton.alpha = 0.0 // set this *after* adding it back UIView.animate( withDuration: 0.5, animations: { self.searchButton.alpha = 1.0 } ) } ) } else { navigationItem.titleView = nil navigationItem.rightBarButtonItem = self.searchBarButtonItem searchButton.alpha = 1.0 } } @objc open func searchButtonAction(_ sender: AnyObject) { UIView.animate( withDuration: 0.5, animations: { self.searchButton.alpha = 0.0 }, completion: { _ in self.activate(animated: true) } ) } open func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchQueryText = searchBar.text delegate?.searchControllerNeedRefresh(self) //searchBar.setShowsCancelButton(false, animated: true) } open func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { //searchBar.setShowsCancelButton(true, animated: true) } open func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.text = nil if (searchQueryText ?? "") != "" { searchBarSearchButtonClicked(searchBar) } deactivate(animated: true) } }
32.885906
163
0.585714
461b32c6d942d266108e5b61f571f51a50e0d443
338
// // ListItemResponse.swift // // // Created by alexis on 2022/3/28. // import Foundation public struct ListItemResponse: Codable { enum CodingKeys: String, CodingKey { case items = "Items" case totalRecordCount = "TotalRecordCount" } public let items: [EmbyItem] public let totalRecordCount: Int }
18.777778
50
0.66568
113bb7a71b43c98f9b49e72b759caedf1ff30235
2,092
// // Notification.swift // ReactKit // // Created by Yasuhiro Inami on 2014/09/11. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import Foundation public extension NSNotificationCenter { /// creates new Stream public func stream(notificationName notificationName: String, object: AnyObject? = nil, queue: NSOperationQueue? = nil) -> Stream<NSNotification?> { return Stream { [weak self] progress, fulfill, reject, configure in var observer: NSObjectProtocol? configure.pause = { if let self_ = self { if let observer_ = observer { self_.removeObserver(observer_) observer = nil } } } configure.resume = { if let self_ = self { if observer == nil { observer = self_.addObserverForName(notificationName, object: object, queue: queue) { notification in progress(notification) } } } } configure.cancel = { if let self_ = self { if let observer_ = observer { self_.removeObserver(observer_) observer = nil } } } configure.resume?() }.name("NSNotification.stream(\(notificationName))") |> takeUntil(self.deinitStream) } } /// NSNotificationCenter helper public struct Notification { public static func stream(notificationName: String, _ object: AnyObject?) -> Stream<NSNotification?> { return NSNotificationCenter.defaultCenter().stream(notificationName: notificationName, object: object) } public static func post(notificationName: String, _ object: AnyObject?) { NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: object) } }
32.6875
150
0.538241
916bb7bb8d456ea060ae852dbb47de84dfec0b37
13,694
// // QRView.swift // flutter_qr // // Created by Julius Canute on 21/12/18. // import Foundation import MTBBarcodeScanner public class QRView:NSObject,FlutterPlatformView { @IBOutlet var previewView: UIView! var scanner: MTBBarcodeScanner? var registrar: FlutterPluginRegistrar var channel: FlutterMethodChannel var cameraFacing: MTBCamera // Codabar, maxicode, rss14 & rssexpanded not supported. Replaced with qr. // UPCa uses ean13 object. var QRCodeTypes = [ 0: AVMetadataObject.ObjectType.aztec, 1: AVMetadataObject.ObjectType.qr, 2: AVMetadataObject.ObjectType.code39, 3: AVMetadataObject.ObjectType.code93, 4: AVMetadataObject.ObjectType.code128, 5: AVMetadataObject.ObjectType.dataMatrix, 6: AVMetadataObject.ObjectType.ean8, 7: AVMetadataObject.ObjectType.ean13, 8: AVMetadataObject.ObjectType.interleaved2of5, 9: AVMetadataObject.ObjectType.qr, 10: AVMetadataObject.ObjectType.pdf417, 11: AVMetadataObject.ObjectType.qr, 12: AVMetadataObject.ObjectType.qr, 13: AVMetadataObject.ObjectType.qr, 14: AVMetadataObject.ObjectType.ean13, 15: AVMetadataObject.ObjectType.upce ] public init(withFrame frame: CGRect, withRegistrar registrar: FlutterPluginRegistrar, withId id: Int64, params: Dictionary<String, Any>){ self.registrar = registrar previewView = UIView(frame: frame) cameraFacing = MTBCamera.init(rawValue: UInt(Int(params["cameraFacing"] as! Double))) ?? MTBCamera.back channel = FlutterMethodChannel(name: "net.touchcapture.qr.flutterqr/qrview_\(id)", binaryMessenger: registrar.messenger()) } deinit { scanner?.stopScanning() } public func view() -> UIView { channel.setMethodCallHandler({ [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in switch(call.method){ case "setDimensions": let arguments = call.arguments as! Dictionary<String, Double> self?.setDimensions(result, width: arguments["width"] ?? 0, height: arguments["height"] ?? 0, scanAreaWidth: arguments["scanAreaWidth"] ?? 0, scanAreaHeight: arguments["scanAreaHeight"] ?? 0, scanAreaOffset: arguments["scanAreaOffset"] ?? 0) case "startScan": self?.startScan(call.arguments as! Array<Int>, result) case "flipCamera": self?.flipCamera(result) case "toggleFlash": self?.toggleFlash(result) case "pauseCamera": self?.pauseCamera(result) case "stopCamera": self?.stopCamera(result) case "resumeCamera": self?.resumeCamera(result) case "getCameraInfo": self?.getCameraInfo(result) case "getFlashInfo": self?.getFlashInfo(result) case "getSystemFeatures": self?.getSystemFeatures(result) default: result(FlutterMethodNotImplemented) return } }) return previewView } func setDimensions(_ result: @escaping FlutterResult, width: Double, height: Double, scanAreaWidth: Double, scanAreaHeight: Double, scanAreaOffset: Double) { // Then set the size of the preview area. previewView.frame = CGRect(x: 0, y: 0, width: width, height: height) // Then set the size of the scan area. let midX = self.view().bounds.midX let midY = self.view().bounds.midY if let sc: MTBBarcodeScanner = scanner { // Set the size of the preview if preview is already created. if let previewLayer = sc.previewLayer { previewLayer.frame = self.previewView.bounds } } else { // Create new preview. scanner = MTBBarcodeScanner(previewView: previewView) } // Set scanArea if provided. if (scanAreaWidth != 0 && scanAreaHeight != 0) { scanner?.didStartScanningBlock = { self.scanner?.scanRect = CGRect(x: Double(midX) - (scanAreaWidth / 2), y: Double(midY) - (scanAreaHeight / 2), width: scanAreaWidth, height: scanAreaHeight) self.channel.invokeMethod("onCameraStarted", arguments: nil) // Set offset if provided. if (scanAreaOffset != 0) { let reversedOffset = -scanAreaOffset self.scanner?.scanRect = (self.scanner?.scanRect.offsetBy(dx: 0, dy: CGFloat(reversedOffset)))! } } } return result(width) } func startScan(_ arguments: Array<Int>, _ result: @escaping FlutterResult) { // Check for allowed barcodes var allowedBarcodeTypes: Array<AVMetadataObject.ObjectType> = [] arguments.forEach { arg in allowedBarcodeTypes.append( QRCodeTypes[arg]!) } MTBBarcodeScanner.requestCameraPermission(success: { [weak self] permissionGranted in guard let self = self else { return } self.channel.invokeMethod("onPermissionSet", arguments: permissionGranted) if permissionGranted { do { try self.scanner?.startScanning(with: self.cameraFacing, resultBlock: { [weak self] codes in if let codes = codes { for code in codes { var typeString: String; switch(code.type) { case AVMetadataObject.ObjectType.aztec: typeString = "AZTEC" case AVMetadataObject.ObjectType.code39: typeString = "CODE_39" case AVMetadataObject.ObjectType.code93: typeString = "CODE_93" case AVMetadataObject.ObjectType.code128: typeString = "CODE_128" case AVMetadataObject.ObjectType.dataMatrix: typeString = "DATA_MATRIX" case AVMetadataObject.ObjectType.ean8: typeString = "EAN_8" case AVMetadataObject.ObjectType.ean13: typeString = "EAN_13" case AVMetadataObject.ObjectType.itf14, AVMetadataObject.ObjectType.interleaved2of5: typeString = "ITF" case AVMetadataObject.ObjectType.pdf417: typeString = "PDF_417" case AVMetadataObject.ObjectType.qr: typeString = "QR_CODE" case AVMetadataObject.ObjectType.upce: typeString = "UPC_E" default: return } let bytes = { () -> Data? in if #available(iOS 11.0, *) { switch (code.descriptor) { case let qrDescriptor as CIQRCodeDescriptor: return qrDescriptor.errorCorrectedPayload case let aztecDescriptor as CIAztecCodeDescriptor: return aztecDescriptor.errorCorrectedPayload case let pdf417Descriptor as CIPDF417CodeDescriptor: return pdf417Descriptor.errorCorrectedPayload case let dataMatrixDescriptor as CIDataMatrixCodeDescriptor: return dataMatrixDescriptor.errorCorrectedPayload default: return nil } } else { return nil } }() let result = { () -> [String : Any]? in guard let stringValue = code.stringValue else { guard let safeBytes = bytes else { return nil } return ["type": typeString, "rawBytes": safeBytes] } guard let safeBytes = bytes else { return ["code": stringValue, "type": typeString] } return ["code": stringValue, "type": typeString, "rawBytes": safeBytes] }() guard result != nil else { continue } if allowedBarcodeTypes.count == 0 || allowedBarcodeTypes.contains(code.type) { self?.channel.invokeMethod("onRecognizeQR", arguments: result) } } } }) } catch { let scanError = FlutterError(code: "unknown-error", message: "Unable to start scanning", details: error) result(scanError) } } }) } func stopCamera(_ result: @escaping FlutterResult) { if let sc: MTBBarcodeScanner = self.scanner { if sc.isScanning() { sc.stopScanning() } } } func getCameraInfo(_ result: @escaping FlutterResult) { result(self.cameraFacing.rawValue) } func flipCamera(_ result: @escaping FlutterResult) { if let sc: MTBBarcodeScanner = self.scanner { if sc.hasOppositeCamera() { sc.flipCamera() self.cameraFacing = sc.camera } return result(sc.camera.rawValue) } return result(FlutterError(code: "404", message: "No barcode scanner found", details: nil)) } func getFlashInfo(_ result: @escaping FlutterResult) { if let sc: MTBBarcodeScanner = self.scanner { result(sc.torchMode.rawValue != 0) } else { let error = FlutterError(code: "cameraInformationError", message: "Could not get flash information", details: nil) result(error) } } func toggleFlash(_ result: @escaping FlutterResult){ if let sc: MTBBarcodeScanner = self.scanner { if sc.hasTorch() { sc.toggleTorch() return result(sc.torchMode == MTBTorchMode(rawValue: 1)) } return result(FlutterError(code: "404", message: "This device doesn\'t support flash", details: nil)) } return result(FlutterError(code: "404", message: "No barcode scanner found", details: nil)) } func pauseCamera(_ result: @escaping FlutterResult) { if let sc: MTBBarcodeScanner = self.scanner { if sc.isScanning() { sc.freezeCapture() } return result(true) } return result(FlutterError(code: "404", message: "No barcode scanner found", details: nil)) } func resumeCamera(_ result: @escaping FlutterResult) { if let sc: MTBBarcodeScanner = self.scanner { if !sc.isScanning() { sc.unfreezeCapture() } return result(true) } return result(FlutterError(code: "404", message: "No barcode scanner found", details: nil)) } func getSystemFeatures(_ result: @escaping FlutterResult) { if let sc: MTBBarcodeScanner = scanner { var hasBackCameraVar = false var hasFrontCameraVar = false let camera = sc.camera if(camera == MTBCamera(rawValue: 0)){ hasBackCameraVar = true if sc.hasOppositeCamera() { hasFrontCameraVar = true } }else{ hasFrontCameraVar = true if sc.hasOppositeCamera() { hasBackCameraVar = true } } return result([ "hasFrontCamera": hasFrontCameraVar, "hasBackCamera": hasBackCameraVar, "hasFlash": sc.hasTorch(), "activeCamera": camera.rawValue ]) } return result(FlutterError(code: "404", message: nil, details: nil)) } }
44.751634
172
0.493793
9ce42091e6062000e09a3a9323f7e7cae49425e7
3,627
// // JSONCollectionViewController.swift // SnapKitchen // // Created by Graham Perks on 3/1/16. // Copyright © 2016 Snap Kitchen. All rights reserved. // import UIKit import SwiftyJSON public protocol JSONCollectionCellConfigurer { func configureInCollectionViewController(_ collectionViewController: UICollectionViewController, cellDefinition: JSON) } open class JSONCollectionViewController: UICollectionViewController { open var sections: JSON! var cellConfigurers = [String: JSONCollectionCellConfigurer]() @objc override open func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false } open func setJSON(_ url:URL) { if let data = try? Data(contentsOf: url) { sections = try? JSON(data: data, options:.allowFragments) registerConfigurers() } } // Iterate through all the rows ensuring each cell's NIB and class is registered with the table open func registerConfigurers() { for section in sections.arrayValue { for row in section["rows"].arrayValue { if let rowClass = row["class"].string { let clazz:AnyClass = rowClass.classFromClassName() collectionView!.register(clazz, forCellWithReuseIdentifier: rowClass) } else if let rowNib = row["nib"].string { let nib = UINib(nibName: rowNib, bundle: nil) collectionView!.register(nib, forCellWithReuseIdentifier: rowNib) } } } } open func cellForIndexPath(_ indexPath : IndexPath) -> JSON { let section = sections.arrayValue[indexPath.section] let rows = section["rows"] let row = rows[indexPath.row] return row } // MARK: UICollectionViewDataSource @objc override open func numberOfSections(in collectionView: UICollectionView) -> Int { return sections.count } @objc override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let section = sections.arrayValue[section] let rows = section["rows"] return rows.count } @objc override open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let row = cellForIndexPath(indexPath) let reuseId = row["class"].string ?? row["nib"].stringValue let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseId, for: indexPath) // Configure the cell... if let configurer = cell as? JSONCollectionCellConfigurer { configurer.configureInCollectionViewController(self, cellDefinition: row) } return cell } // MARK: UICollectionViewDelegate @objc override open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let row = cellForIndexPath(indexPath) if let action = row["action"].string { if action.hasSuffix(":") { self.perform(Selector(action), with: row.dictionaryObject!) } else { self .perform(Selector(action)) } } } @objc override open func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { } }
30.478992
171
0.646816
d9b148081bc3d7621aae2b5bc1105ddc0e018e17
805
// // JMTrackingPermissionManager.swift // // // Created by Jevon Mao on 2/2/21. // import Foundation import AppTrackingTransparency import AdSupport @available(iOS 14, *) struct JMTrackingPermissionManager { static var shared = JMTrackingPermissionManager() public static var advertisingIdentifier:UUID{ ASIdentifierManager.shared().advertisingIdentifier } func requestPermission(completion: @escaping (Bool) -> Void) { ATTrackingManager.requestTrackingAuthorization { status in switch status { case .authorized: completion(true) case .notDetermined: break default: completion(false) } } } }
25.967742
66
0.58882
5b1aa91671e97d4929b1a890e7a5fa06b6a3601f
347
// // TabBarViewController.swift // Sport With You ! // // Created by Dany Jean-Charles on 09/05/2019. // Copyright © 2019 Dany Jean-Charles. All rights reserved. // import UIKit class TabBarViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() self.selectedIndex = 1 } }
15.772727
60
0.654179
0aaa97467454c7495cabd7a1c3aeeac56de7de2c
7,681
/// /// Copyright (c) 2018 Tjek. All rights reserved. /// import UIKit import Verso // MARK: - Verso DataSource extension PagedPublicationView: VersoViewDataSource { // Return how many pages are on each spread public func spreadConfiguration(with size: CGSize, for verso: VersoView) -> VersoSpreadConfiguration { let pageCount = self.pageCount let lastPageIndex = max(0, pageCount - 1) var totalPageCount = pageCount // there is an outro, and we have some pages, so add outro to the pages list if self.outroPageIndex != nil { totalPageCount += 1 } // how far between the page spreads let spreadSpacing: CGFloat = 20 // TODO: compare verso aspect ratio to publication aspect ratio let isLandscape: Bool = size.width > size.height return VersoSpreadConfiguration.buildPageSpreadConfiguration(pageCount: totalPageCount, spreadSpacing: spreadSpacing, spreadPropertyConstructor: { (_, nextPageIndex) in // it's the outro (has an outro, we have some real pages, and next page is after the last pageIndex if let outroProperties = self.outroViewProperties, nextPageIndex == self.outroPageIndex { return (1, outroProperties.maxZoom, outroProperties.width) } let spreadPageCount: Int if nextPageIndex == 0 || nextPageIndex == lastPageIndex || isLandscape == false { spreadPageCount = 1 } else { spreadPageCount = 2 } return (spreadPageCount, 3.0, 1.0) }) } public func pageViewClass(on pageIndex: Int, for verso: VersoView) -> VersoPageViewClass { if let outroProperties = self.outroViewProperties, pageIndex == self.outroPageIndex { return outroProperties.viewClass } else { return PagedPublicationView.PageView.self } } public func configure(pageView: VersoPageView, for verso: VersoView) { if let pubPageView = pageView as? PagedPublicationView.PageView { pubPageView.imageLoader = self.imageLoader pubPageView.delegate = self let pageProperties = self.pageViewProperties(forPageIndex: pubPageView.pageIndex) pubPageView.configure(with: pageProperties) } else if type(of: pageView) === self.outroViewProperties?.viewClass { dataSourceWithDefaults.configure(outroView: pageView, for: self) } } public func spreadOverlayView(overlaySize: CGSize, pageFrames: [Int: CGRect], for verso: VersoView) -> UIView? { // we have an outro and it is one of the pages we are being asked to add an overlay for if let outroPageIndex = self.outroPageIndex, pageFrames[outroPageIndex] != nil { return nil } let spreadHotspots = self.hotspotModels(onPageIndexes: IndexSet(pageFrames.keys)) // configure the overlay self.hotspotOverlayView.isHidden = self.pageCount == 0 self.hotspotOverlayView.delegate = self self.hotspotOverlayView.frame.size = overlaySize self.hotspotOverlayView.updateWithHotspots(spreadHotspots, pageFrames: pageFrames) // disable tap when double-tapping if let doubleTap = contentsView.versoView.zoomDoubleTapGestureRecognizer { self.hotspotOverlayView.tapGesture?.require(toFail: doubleTap) } return self.hotspotOverlayView } public func adjustPreloadPageIndexes(_ preloadPageIndexes: IndexSet, visiblePageIndexes: IndexSet, for verso: VersoView) -> IndexSet? { guard let outroPageIndex = self.outroPageIndex, let lastIndex = visiblePageIndexes.last, outroPageIndex - lastIndex < 10 else { return nil } // add outro to preload page indexes if we have scrolled close to it var adjustedPreloadPages = preloadPageIndexes adjustedPreloadPages.insert(outroPageIndex) return adjustedPreloadPages } } // MARK: - Verso Delegate extension PagedPublicationView: VersoViewDelegate { public func currentPageIndexesChanged(current currentPageIndexes: IndexSet, previous oldPageIndexes: IndexSet, in verso: VersoView) { // this is a bit of a hack to cancel the touch-gesture when we start scrolling self.hotspotOverlayView.touchGesture?.isEnabled = false self.hotspotOverlayView.touchGesture?.isEnabled = true // remove the outro index when refering to page indexes outside of PagedPub var currentExOutro = currentPageIndexes var oldExOutro = oldPageIndexes if let outroIndex = self.outroPageIndex { currentExOutro.remove(outroIndex) oldExOutro.remove(outroIndex) } delegate?.pageIndexesChanged(current: currentExOutro, previous: oldExOutro, in: self) // check if the outro has newly appeared or disappeared (not if it's in both old & current) if let outroIndex = outroPageIndex, let outroView = verso.getPageViewIfLoaded(outroIndex) { let addedIndexes = currentPageIndexes.subtracting(oldPageIndexes) let removedIndexes = oldPageIndexes.subtracting(currentPageIndexes) if addedIndexes.contains(outroIndex) { delegate?.outroDidAppear(outroView, in: self) outroOutsideTapGesture.isEnabled = true } else if removedIndexes.contains(outroIndex) { delegate?.outroDidDisappear(outroView, in: self) outroOutsideTapGesture.isEnabled = false } } updateContentsViewLabels(pageIndexes: currentPageIndexes, additionalLoading: contentsView.properties.showAdditionalLoading) } public func currentPageIndexesFinishedChanging(current currentPageIndexes: IndexSet, previous oldPageIndexes: IndexSet, in verso: VersoView) { // make a new spreadEventHandler (unless it's the outro) if self.isOutroPage(inPageIndexes: currentPageIndexes) == false { self.eventHandler?.didOpenPublicationPages(currentPageIndexes) } // remove the outro index when refering to page indexes outside of PagedPub var currentExOutro = currentPageIndexes var oldExOutro = oldPageIndexes if let outroIndex = self.outroPageIndex { currentExOutro.remove(outroIndex) oldExOutro.remove(outroIndex) } delegate?.pageIndexesFinishedChanging(current: currentExOutro, previous: oldExOutro, in: self) // cancel the loading of the zoomimage after a page disappears oldPageIndexes.subtracting(currentPageIndexes).forEach { if let pageView = verso.getPageViewIfLoaded($0) as? PagedPublicationView.PageView { pageView.clearZoomImage(animated: false) } } } public func didStartZooming(pages pageIndexes: IndexSet, zoomScale: CGFloat, in verso: VersoView) { hotspotOverlayView.isZooming = true } public func didEndZooming(pages pageIndexes: IndexSet, zoomScale: CGFloat, in verso: VersoView) { delegate?.didEndZooming(zoomScale: zoomScale) pageIndexes.forEach { if let pageView = verso.getPageViewIfLoaded($0) as? PagedPublicationView.PageView { pageView.startLoadingZoomImageIfNotLoaded() } } hotspotOverlayView.isZooming = false } }
44.143678
176
0.660331
1835859201d3aed933aaf6cafeecf09ff14a95f9
3,968
// // Copyright © 2018 PhonePe. All rights reserved. // import Foundation import Swift public struct ErrorLocation { public let file: StaticString public let function: StaticString public let line: Int public init(file: StaticString, function: StaticString, line: Int) { self.file = file self.function = function self.line = line } public var description: String { return "file: \(file), function: \(function), line: \(line)" } } public struct ErrorAccumulator { private var locations: [ErrorLocation] private var errors: [Error] public init() { self.locations = [] self.errors = [] } public mutating func add(_ error: Error, file: StaticString = #function, function: StaticString = #function, line: Int = #line) { if let error = error as? AccumulatedErrors { locations += error.locations errors += error.errors } else { errors.append(error) } } public mutating func silence<T>(_ expr: @autoclosure () throws -> T, file: StaticString = #function, function: StaticString = #function, line: Int = #line) -> T? { do { return try expr() } catch { add(error, file: file, function: function, line: line) return nil } } public func accumulated(file: StaticString = #file, function: StaticString = #function, line: Int = #line) -> AccumulatedErrors { return .init(locations: locations, errors: errors, file: file, function: function, line: line) } } public struct AccumulatedErrors: CustomStringConvertible, Error { fileprivate let locations: [ErrorLocation] fileprivate let errors: [Error] fileprivate let file: StaticString fileprivate let function: StaticString fileprivate let line: Int public init(locations: [ErrorLocation], errors: [Error], file: StaticString = #file, function: StaticString = #function, line: Int = #line) { self.locations = locations self.errors = errors self.file = file self.function = function self.line = line } public init(errors: [Error], file: StaticString = #file, function: StaticString = #function, line: Int = #line) { self.locations = errors.map({ _ in ErrorLocation(file: file, function: function, line: line) }) self.errors = errors self.file = file self.function = function self.line = line } public var description: String { return "Error in file: \(file), line: \(line), function: \(function): \(errors.description)" } public var name: String { if let first = errors.first { return String(describing: first) } else { return "Empty error in file: \(file), line: \(line), function: \(function)" } } public var traceDescription: String { var description: String = "" var indent: String = "" for (location, error) in zip(locations.reversed(), errors.reversed()) { description += indent + "From \(location.description):\n" description += indent + error.localizedDescription indent += "\t" } return description } } public enum JSONRuntimeError: Error { case noContainer case irrepresentableNumber(NSNumber) case invalidTypeCast(from: Any.Type, to: Any.Type) case noFallbackCovariantForSupertype(Any.Type) case stringEncodingError case unexpectedlyFoundNil(file: StaticString, function: StaticString, line: UInt) case isNotEmpty } extension Optional { public func unwrapOrThrowJSONRuntimeError(file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> Wrapped { return try unwrapOrThrow(JSONRuntimeError.unexpectedlyFoundNil(file: file, function: function, line: line)) } }
33.066667
167
0.62752
f7ad882e8a0251f8c9651403d0b7d38670cd0d78
772
// // LTTheme.swift // VPNOn // // Created by Lex on 1/15/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit public protocol LTTheme { var name : String { get set } var defaultBackgroundColor : UIColor { get set } var navigationBarColor : UIColor { get set } var tintColor : UIColor { get set } var textColor : UIColor { get set } var placeholderColor : UIColor { get set } var textFieldColor : UIColor { get set } var tableViewBackgroundColor : UIColor { get set } var tableViewLineColor : UIColor { get set } var tableViewCellColor : UIColor { get set } var switchBorderColor : UIColor { get set } }
32.166667
56
0.586788
1e0ff13c59a4b8545631e2bcced98f02bfa86bef
2,517
import Core import HTTP import Transport import AWSSignatureV4 import Vapor @_exported import enum AWSSignatureV4.AWSError @_exported import enum AWSSignatureV4.AccessControlList public struct S3 { public enum Error: Swift.Error { case unimplemented case invalidResponse(Status) } let signer: AWSSignatureV4 public var host: String public init( host: String, accessKey: String, secretKey: String, region: Region ) { self.host = host signer = AWSSignatureV4( service: "s3", host: host, region: region, accessKey: accessKey, secretKey: secretKey ) } public func upload(bytes: Bytes, path: String, access: AccessControlList) throws { let url = generateURL(for: path) let headers = try signer.sign( payload: .bytes(bytes), method: .put, path: path, headers: ["x-amz-acl": access.rawValue] ) let response = try EngineClient.factory.put(url, headers, Body.data(bytes)) guard response.status == .ok else { guard let bytes = response.body.bytes else { throw Error.invalidResponse(response.status) } throw try ErrorParser.parse(bytes) } } public func get(path: String) throws -> Bytes { let url = generateURL(for: path) let headers = try signer.sign(path: path) let response = try EngineClient.factory.get(url, headers) guard response.status == .ok else { guard let bytes = response.body.bytes else { throw Error.invalidResponse(response.status) } throw try ErrorParser.parse(bytes) } guard let bytes = response.body.bytes else { throw Error.invalidResponse(.internalServerError) } return bytes } public func delete(file: String) throws { throw Error.unimplemented } } extension S3 { func generateURL(for path: String) -> String { //FIXME(Brett): return "https://\(host)\(path)" } } extension Dictionary where Key: CustomStringConvertible, Value: CustomStringConvertible { var vaporHeaders: [HeaderKey: String] { var result: [HeaderKey: String] = [:] self.forEach { result.updateValue($0.value.description, forKey: HeaderKey($0.key.description)) } return result } }
26.21875
91
0.595153
09a639c081ecc1c768bad1dd43419fdc0bffdfb4
345
import Foundation enum SendTransactionError: Error { case noFee case wrongAmount } extension SendTransactionError: LocalizedError { public var errorDescription: String? { switch self { case .wrongAmount: return "alert.wrong_amount".localized case .noFee: return "alert.no_fee".localized } } }
19.166667
64
0.681159
16dc21d844cafc43848cb1bb13c1894738781003
1,323
import Foundation public func test() -> Void { // if let let isFlag:Bool? = false if let tempFlag = isFlag { print( (tempFlag)) } // ? ! // let name : String? // name!.hashValue // 逻辑判断和区间 // ... 表示闭区间/ ..< 表示开区间, == 表示值相等/=== 表示引用相同, + 可以直接加字符串或数组 for i in 1...100 { print( (i)) } // ?? var a:Int? print(a ?? 2) //2 // 闭包test var doubleFun : (Int) -> Int doubleFun = { num in return num * 2 } doubleFun(5) typealias Type = (Int) -> Int var b : Type b = { num in return num * 2 } b(6) // 运算符重载 // func - (t1 : Int,t2: Int) -> Int { // return t1 + t2 // } // // var a = 20 // var b = 23 // // var c = b - a // c // // let tupe1 = ("xiaoming",16) // let tupe2 = ("xiaoming",18) // // func == (t1:(String,Int) , t2:(String,Int)) -> Bool { // return (t1.0 == t2.0 && t1.1 == t2.1) // } // // let flag = (tupe1 == tupe2) // flag } /// 普通交互方法定义 func swapTwoIntValue (inout a:Int ,inout b:Int) { let tempV = a a = b b = tempV } /// 泛型定义 func swapTwoValue<T> (inout a:T , inout b:T) { let tempValue = a a = b b = tempValue }
15.383721
62
0.427816
edab603b1eaed5512e163bf083351478e601e452
1,429
import PMKOMGHTTPURLRQ import OHHTTPStubs import PromiseKit import XCTest class NSURLSessionTests: XCTestCase { func test1() { let json: NSDictionary = ["key1": "value1", "key2": ["value2A", "value2B"]] OHHTTPStubs.stubRequests(passingTest: { $0.url!.host == "example.com" }) { _ in return OHHTTPStubsResponse(jsonObject: json, statusCode: 200, headers: nil) } let ex = expectation(description: "") URLSession.shared.GET("http://example.com").asDictionary().then { rsp -> Void in XCTAssertEqual(json, rsp) ex.fulfill() } waitForExpectations(timeout: 1) } func test2() { // test that URLDataPromise chains thens // this test because I don’t trust the Swift compiler let dummy = ("fred" as NSString).data(using: String.Encoding.utf8.rawValue)! OHHTTPStubs.stubRequests(passingTest: { $0.url!.host == "example.com" }) { _ in return OHHTTPStubsResponse(data: dummy, statusCode: 200, headers: [:]) } let ex = expectation(description: "") after(interval: 0.1).then { URLSession.shared.GET("http://example.com") }.then { x -> Void in XCTAssertEqual(x, dummy) }.then(execute: ex.fulfill) waitForExpectations(timeout: 1) } override func tearDown() { OHHTTPStubs.removeAllStubs() } }
29.770833
88
0.604619
232e49dd15495417040223947f5c776f7cac39d5
19,152
// // UnitKitTests.swift // UnitKitTests // // Created by Bo Gosmer on 20/01/2016. // Copyright © 2016 Deadlock Baby. All rights reserved. // import XCTest @testable import UnitKit class MassUnitTests: XCTestCase { override func setUp() { super.setUp() MassUnit.sharedDecimalNumberHandler = nil } override func tearDown() { super.tearDown() } // MARK: - MassUnit func testDecimalNumberInitializationUsingBaseUnitType() { let decimalValue = NSDecimalNumber.double(1) let massUnitValue = NSDecimalNumber(decimal: MassUnit(value: decimalValue, type: .Gram).baseUnitTypeValue) XCTAssert(massUnitValue == decimalValue, "expected \(decimalValue) - got \(massUnitValue)") } func testDoubleInitializationUsingBaseUnitType() { let value: Double = 1 let decimalValue = NSDecimalNumber.double(value) let massUnitValue = NSDecimalNumber(decimal: MassUnit(value: value, type: .Gram).baseUnitTypeValue) XCTAssert(massUnitValue == decimalValue, "expected \(decimalValue) - got \(massUnitValue)") } func testIntInitializationUsingBaseUnitType() { let value: Int = 1 let decimalValue = NSDecimalNumber.integer(value) let massUnitValue = NSDecimalNumber(decimal: MassUnit(value: value, type: .Gram).baseUnitTypeValue) XCTAssert(massUnitValue == decimalValue, "expected \(decimalValue) - got \(massUnitValue)") } func testIntInitializationUsingOtherUnitType() { let value: Int = 1 let decimalValue = NSDecimalNumber.integer(value).decimalNumberByMultiplyingBy(MassUnitType.Kilo.baseUnitTypePerUnit()) let massUnitValue = NSDecimalNumber(decimal: MassUnit(value: value, type: .Kilo).baseUnitTypeValue) XCTAssert(massUnitValue == decimalValue, "expected \(decimalValue) - got \(massUnitValue)") } func testDecimalNumberInitializationOthergBaseUnitType() { let value: Int = 1 let decimalValue = NSDecimalNumber.double(1).decimalNumberByMultiplyingBy(MassUnitType.Pound.baseUnitTypePerUnit()) let massUnitValue = NSDecimalNumber(decimal: MassUnit(value: value, type: .Pound).baseUnitTypeValue) XCTAssert(massUnitValue == decimalValue, "expected \(decimalValue) - got \(massUnitValue)") } func testDoubleInitializationUsingOtherUnitType() { let value: Double = 1 let decimalValue = NSDecimalNumber.double(value).decimalNumberByMultiplyingBy(MassUnitType.ShortTon.baseUnitTypePerUnit()) let massUnitValue = NSDecimalNumber(decimal: MassUnit(value: value, type: .ShortTon).baseUnitTypeValue) XCTAssert(massUnitValue == decimalValue, "expected \(decimalValue) - got \(massUnitValue)") } func testMilligramValue() { let value: Double = 1 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.Milligram.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).milligramValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testKiloValue() { let value: Double = 2 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.Kilo.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).kiloValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testTonneValue() { let value: Double = 3 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.Tonne.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).tonneValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testGrainValue() { let value: Double = 4 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.Grain.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).grainValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testDramValue() { let value: Double = 5 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.Dram.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).dramValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testOunceValue() { let value: Double = 6 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.Ounce.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).ounceValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testPoundValue() { let value: Double = 7 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.Pound.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).poundValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testStoneValue() { let value: Double = 8 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.Stone.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).stoneValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testQuarterValue() { let value: Double = 9 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.Quarter.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).quarterValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testLongHundredWeightValue() { let value: Double = 10 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.LongHundredweight.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).longHundredweightValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testLongTonValue() { let value: Double = 11 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.LongTon.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).longTonValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testShortHundredWeightValue() { let value: Double = 12 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.ShortHundredweight.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).shortHundredweightValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testShortTonValue() { let value: Double = 13 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(MassUnitType.ShortTon.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .Gram).shortTonValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testConversionExample() { let value: Double = 1 let decimalValue = NSDecimalNumber.double(value).decimalNumberByMultiplyingBy(MassUnitType.ShortTon.baseUnitTypePerUnit()).decimalNumberByDividingBy(MassUnitType.LongTon.baseUnitTypePerUnit()) let massUnit = MassUnit(value: value, type: .ShortTon).longTonValue XCTAssert(massUnit == decimalValue, "expected \(decimalValue) - got \(massUnit)") } func testSharedDecimalNumberHandler() { MassUnit.sharedDecimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) let value = 1.2345 let massUnitValue = MassUnit(value: value, type: .Gram) XCTAssert(NSDecimalNumber(decimal: massUnitValue.baseUnitTypeValue) == NSDecimalNumber.double(1.23), "expected 1.23 - got \(NSDecimalNumber(decimal: massUnitValue.baseUnitTypeValue))") } func testInstanceDecimalNumberHandler() { let instanceNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) let value = 9.8765 var massUnit = MassUnit(value: value, type: .Gram) massUnit.decimalNumberHandler = instanceNumberHandler let baseUnitTypeValue = NSDecimalNumber(decimal: massUnit.baseUnitTypeValue) XCTAssert(NSDecimalNumber.double(value) == baseUnitTypeValue, "expected \(value) - got \(baseUnitTypeValue)") XCTAssert(massUnit.gramValue == NSDecimalNumber.double(value).decimalNumberByRoundingAccordingToBehavior(instanceNumberHandler), "expected \(value) - got \(baseUnitTypeValue)") MassUnit.sharedDecimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundUp, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) XCTAssert(massUnit.gramValue == NSDecimalNumber.double(value).decimalNumberByRoundingAccordingToBehavior(instanceNumberHandler), "expected \(value) - got \(baseUnitTypeValue)") } // MARK: - CustomStringConvertible func testDescription() { let unit = MassUnit(value: -1, type: .Kilo) XCTAssert(unit.description == "-1 kilo", "got \(unit.description)") } // MARK: - Localization func testLocalizedName() { let unitSingle = MassUnit(value: -1, type: .Pound) XCTAssert(unitSingle.localizedNameOfUnitType(NSLocale(localeIdentifier: "en")) == "pound") XCTAssert(unitSingle.localizedNameOfUnitType(NSLocale(localeIdentifier: "da")) == "pund") let unitPlural = MassUnit(value: -2, type: .Pound) XCTAssert(unitPlural.localizedNameOfUnitType(NSLocale(localeIdentifier: "en")) == "pounds") XCTAssert(unitPlural.localizedNameOfUnitType(NSLocale(localeIdentifier: "da")) == "pund") } func testLocalizedAbbreviation() { let unitSingle = MassUnit(value: -1, type: .Pound) XCTAssert(unitSingle.localizedAbbreviationOfUnitType(nil) == "lb") XCTAssert(unitSingle.localizedAbbreviationOfUnitType(NSLocale(localeIdentifier: "en")) == "lb") XCTAssert(unitSingle.localizedAbbreviationOfUnitType(NSLocale(localeIdentifier: "da")) == "lb") let unitPlural = MassUnit(value: -2, type: .Pound) XCTAssert(unitPlural.localizedAbbreviationOfUnitType(nil) == "lbs") XCTAssert(unitPlural.localizedAbbreviationOfUnitType(NSLocale(localeIdentifier: "en")) == "lbs") XCTAssert(unitPlural.localizedAbbreviationOfUnitType(NSLocale(localeIdentifier: "da")) == "lbs") } // MARK: - Arithmetic func testAdditionOfMassUnits() { let kgs = MassUnit(value: 1, type: .Kilo) let grams = MassUnit(value: 1, type: .Gram) let addition = kgs + grams let number = addition.kiloValue XCTAssert(addition.unitType == MassUnitType.Kilo, "expected \(MassUnitType.Kilo) - got \(addition.unitType)") XCTAssert(number == NSDecimalNumber.double(1.001), "expected 1.001, got \(number)") } func testAdditionWithDouble() { let initialValue:Double = 1245 let additionValue = 2.5 let pound = MassUnit(value: initialValue, type: .Pound) let addition = pound + additionValue let number = addition.poundValue XCTAssert(number == NSDecimalNumber.double(initialValue + additionValue), "expected \(initialValue + additionValue) - got \(number)") } func testAdditionWithInteger() { let initialValue:Int = 967235 let additionValue = 254 let pound = MassUnit(value: initialValue, type: .Pound) let addition = pound + additionValue let number = addition.poundValue XCTAssert(number == NSDecimalNumber.integer(initialValue + additionValue), "expected \(initialValue + additionValue) - got \(number)") } func testSubtractionOfMassUnits() { let m2 = MassUnit(value: 1, type: .Kilo) let cm2 = MassUnit(value: 1, type: .Gram) var subtraction = m2 - cm2 var number = subtraction.kiloValue XCTAssert(subtraction.unitType == MassUnitType.Kilo, "expected \(MassUnitType.Kilo) - got \(subtraction.unitType)") XCTAssert(number == NSDecimalNumber.double(0.999), "expected 0.999, got \(number)") subtraction = cm2 - m2 number = subtraction.gramValue XCTAssert(subtraction.unitType == MassUnitType.Gram, "expected \(MassUnitType.Gram) - got \(subtraction.unitType)") XCTAssert(number == NSDecimalNumber.double(-999), "expected -999, got \(number)") } func testSubtractionWithDouble() { let initialValue:Double = 1245 let subtractionValue = 2.5 let acre = MassUnit(value: initialValue, type: .Pound) let subtraction = acre - subtractionValue let number = subtraction.poundValue XCTAssert(number == NSDecimalNumber.double(initialValue - subtractionValue), "expected \(initialValue - subtractionValue) - got \(number)") } func testSubtractionWithInteger() { let initialValue:Int = 967235 let subtractionValue = 254 let hectare = MassUnit(value: initialValue, type: .Pound) let subtraction = hectare - subtractionValue let number = subtraction.poundValue XCTAssert(number == NSDecimalNumber.integer(initialValue - subtractionValue), "expected \(initialValue - subtractionValue) - got \(number)") } func testMultiplicationWithDouble() { let initialValue:Double = 1000 let factor = 2.5 let acre = MassUnit(value: initialValue, type: .Pound) let mult = acre * factor let number = mult.poundValue XCTAssert(number == NSDecimalNumber.double(initialValue * factor), "expected \(initialValue * factor) - got \(number)") } func testMultiplicationWithInteger() { let initialValue:Int = 1000 let multiplicationValue = 3 let hectare = MassUnit(value: initialValue, type: .Pound) let mult = hectare * multiplicationValue let number = mult.poundValue XCTAssert(number == NSDecimalNumber.integer(initialValue * multiplicationValue), "expected \(initialValue * multiplicationValue) - got \(number)") } func testDivisionWithDouble() { let initialValue:Double = 1000 let divValue = 2.5 let acre = MassUnit(value: initialValue, type: .Pound) let div = acre / divValue let number = div.poundValue XCTAssert(number == NSDecimalNumber.double(initialValue / divValue), "expected \(initialValue / divValue) - got \(number)") } func testDivisionWithInteger() { let initialValue:Int = 2000 let divValue = 4 let hectare = MassUnit(value: initialValue, type: .Pound) let div = hectare / divValue let number = div.poundValue XCTAssert(number == NSDecimalNumber.integer(initialValue / divValue), "expected \(initialValue / divValue) - got \(number)") } // MARK: - Double and Int extensions func testMilligramExtension() { XCTAssert(1.0.milligrams().milligramValue == MassUnit(value: 1.0, type: .Milligram).milligramValue) XCTAssert(1.milligrams().milligramValue == MassUnit(value: 1, type: .Milligram).milligramValue) } func testGramExtension() { XCTAssert(1.0.grams().gramValue == MassUnit(value: 1.0, type: .Gram).gramValue) XCTAssert(1.grams().gramValue == MassUnit(value: 1, type: .Gram).gramValue) } func testKiloExtension() { XCTAssert(1.0.kilos().kiloValue == MassUnit(value: 1.0, type: .Kilo).kiloValue) XCTAssert(1.kilos().kiloValue == MassUnit(value: 1, type: .Kilo).kiloValue) } func testTonneExtension() { XCTAssert(1.0.tonnes().tonneValue == MassUnit(value: 1.0, type: .Tonne).tonneValue) XCTAssert(1.tonnes().tonneValue == MassUnit(value: 1, type: .Tonne).tonneValue) } func testGrainExtension() { XCTAssert(1.0.grains().grainValue == MassUnit(value: 1.0, type: .Grain).grainValue) XCTAssert(1.grains().grainValue == MassUnit(value: 1, type: .Grain).grainValue) } func testDramExtension() { XCTAssert(1.0.drams().dramValue == MassUnit(value: 1.0, type: .Dram).dramValue) XCTAssert(1.drams().dramValue == MassUnit(value: 1, type: .Dram).dramValue) } func testOunceExtension() { XCTAssert(1.0.ounces().ounceValue == MassUnit(value: 1.0, type: .Ounce).ounceValue) XCTAssert(1.ounces().ounceValue == MassUnit(value: 1, type: .Ounce).ounceValue) } func testPoundExtension() { XCTAssert(1.0.pounds().poundValue == MassUnit(value: 1.0, type: .Pound).poundValue) XCTAssert(1.pounds().poundValue == MassUnit(value: 1, type: .Pound).poundValue) } func testStoneExtension() { XCTAssert(1.0.stones().stoneValue == MassUnit(value: 1.0, type: .Stone).stoneValue) XCTAssert(1.stones().stoneValue == MassUnit(value: 1, type: .Stone).stoneValue) } func testQuarterExtension() { XCTAssert(1.0.quarters().quarterValue == MassUnit(value: 1.0, type: .Quarter).quarterValue) XCTAssert(1.quarters().quarterValue == MassUnit(value: 1, type: .Quarter).quarterValue) } func testLongHundredWeightExtension() { XCTAssert(1.0.longHundredweights().longHundredweightValue == MassUnit(value: 1.0, type: .LongHundredweight).longHundredweightValue) XCTAssert(1.longHundredweights().longHundredweightValue == MassUnit(value: 1, type: .LongHundredweight).longHundredweightValue) } func testLongTonExtension() { XCTAssert(1.0.longTons().longTonValue == MassUnit(value: 1.0, type: .LongTon).longTonValue) XCTAssert(1.longTons().longTonValue == MassUnit(value: 1, type: .LongTon).longTonValue) } func testShortHundredWeightExtension() { XCTAssert(1.0.shortHundredweights().shortHundredweightValue == MassUnit(value: 1.0, type: .ShortHundredweight).shortHundredweightValue) XCTAssert(1.shortHundredweights().shortHundredweightValue == MassUnit(value: 1, type: .ShortHundredweight).shortHundredweightValue) } func testShortTonExtension() { XCTAssert(1.0.shortTons().shortTonValue == MassUnit(value: 1.0, type: .ShortTon).shortTonValue) XCTAssert(1.shortTons().shortTonValue == MassUnit(value: 1, type: .ShortTon).shortTonValue) } }
49.875
207
0.685359
22000015e1435ee6ce98cbc103593d32e8cff4cd
2,108
// // FaresandReservedViewController.swift // fastbnb // // Created by wonsik on 20/12/2018. // Copyright © 2018 fastcampus. All rights reserved. // import UIKit class FaresandReserved2ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.rowHeight = 80 self.tableView.tableFooterView = UIView(frame: .zero) } let data = FaresandReserved2Data() } extension FaresandReserved2ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.data.list.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FaresandReserved2Cell let list = self.data.list[indexPath.row] cell.title?.text = list.title return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.row { case 0: self.performSegue(withIdentifier: "1line", sender: nil) case 1: self.performSegue(withIdentifier: "2line", sender: nil) case 2: self.performSegue(withIdentifier: "3line", sender: nil) case 3: self.performSegue(withIdentifier: "4line", sender: nil) case 4: self.performSegue(withIdentifier: "5line", sender: nil) case 5: self.performSegue(withIdentifier: "6line", sender: nil) case 6: self.performSegue(withIdentifier: "7line", sender: nil) case 7: self.performSegue(withIdentifier: "8line", sender: nil) case 8: self.performSegue(withIdentifier: "9line", sender: nil) case 9: self.performSegue(withIdentifier: "10line", sender: nil) default: return } } }
35.728814
114
0.669355
90062b8b662a8238de806db0aa40ab8d9760d0e5
398
// // Dealer.swift // Blackjack // // Created by Jack Munkonge on 03/12/2019. // Copyright © 2019 MobileDev. All rights reserved. // import Foundation final class Dealer: Player { var id = "Dealer" var hand: Hand? init(withHand hand: Hand?) { self.hand = hand } public func hit(fromDeck deck: Deck) { hand?.add(card: deck.getNext()) } }
16.583333
52
0.585427
1d29f8703e0af207c3d10449088dbf34a27493ee
862
import Combine import DataLayer public extension Domain.Usecase.Course { struct FetchByRockId: PassthroughUsecaseProtocol { public typealias Repository = Repositories.Course.FetchByRockId public typealias Mapper = Domain.Mapper.Course var repository: Repository var mapper: Mapper public init(repository: Repository = .init(), mapper: Mapper = .init()) { self.repository = repository self.mapper = mapper } public func fetch(by rockId: String) -> AnyPublisher<[Domain.Entity.Course], Error> { self.repository.request( parameters: .init(rockId: rockId) ) .map { responses -> [Domain.Entity.Course] in responses.map { mapper.map(from: $0) } } .eraseToAnyPublisher() } } }
30.785714
93
0.600928
abb8cd241b1c409a40a5df99205bdb789cb10323
4,230
import CTLS public struct TLSError: Error { public let functionName: String public let returnCode: Int32? public let reason: String public init( functionName: String, returnCode: Int32?, reason: String ) { self.functionName = functionName self.returnCode = returnCode self.reason = reason } } // MARK: Convenience extension Socket { func assert( _ returnCode: Int32, functionName: String ) throws { if returnCode != 1 { throw makeError( functionName: functionName, returnCode: returnCode ) } } func makeError( functionName: String, returnCode: Int32? = nil ) -> TLSError { let reason: String? if let cSSL = cSSL, let returnCode = returnCode { let res = SSL_get_error(cSSL, returnCode) switch res { case SSL_ERROR_ZERO_RETURN: reason = "The TLS/SSL connection has been closed." case SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: reason = "The operation did not complete; the same TLS/SSL I/O function should be called again later." case SSL_ERROR_WANT_X509_LOOKUP: reason = "The operation did not complete because an application callback set by SSL_CTX_set_client_cert_cb() has asked to be called again." case SSL_ERROR_SYSCALL: reason = String(validatingUTF8: strerror(errno)) ?? "System call error" case SSL_ERROR_SSL: let bio = BIO_new(BIO_s_mem()) defer { BIO_free(bio) } ERR_print_errors(bio) let written = BIO_number_written(bio) var buffer: [Int8] = Array(repeating: 0, count: Int(written) + 1) reason = buffer.withUnsafeMutableBufferPointer { buf in BIO_read(bio, buf.baseAddress, Int32(written)) return String(validatingUTF8: buf.baseAddress!) } default: reason = "A failure in the SSL library occurred." } } else { reason = nil } return context.makeError( functionName: functionName, returnCode: returnCode, reason: reason ) } } extension Context { private var errorReason: String? { let err = ERR_get_error() if err == 0 { return nil } if let errorStr = ERR_reason_error_string(err) { return String(validatingUTF8: errorStr) } else { return nil } } func assert( _ returnCode: Int32, functionName: String, reason: String? = nil ) throws { if returnCode != 1 { throw makeError( functionName: functionName, returnCode: returnCode, reason: reason ) } } func makeError( functionName: String, returnCode: Int32? = nil, reason otherReason: String? = nil ) -> TLSError { let reason: String if let error = errorReason { reason = error } else if let otherReason = otherReason { reason = otherReason } else { reason = "Unknown" } return TLSError( functionName: functionName, returnCode: returnCode, reason: reason ) } } // MARK: Debuggable import Debugging extension TLSError: Debuggable { public static var readableName: String { return "Transport Layer Security Error" } public var identifier: String { if let returnCode = returnCode { return "\(functionName) (\(returnCode))" } else { return functionName } } public var possibleCauses: [String] { return [] } public var suggestedFixes: [String] { return [] } }
26.4375
155
0.532861
f48ba3063b1001e7c764de5f1e59943ed5831ad3
1,302
// // VersionUtility.swift // RemoteConfigForceUpdate // // Created by 伊賀裕展 on 2019/12/12. // Copyright © 2019 Iganin. All rights reserved. // import Foundation struct VersionUtility { // 現在のバージョンと比較対象のバージョンを比べ強制アラートの表示が必要かを判定します func isForceAlertRequired(currentVersion: String, criteriaVersion: String) -> Bool { var currentVersionNumbers = currentVersion.components(separatedBy: ".").map { Int($0) ?? 0 } var criteriaVersionNumbers = criteriaVersion.components(separatedBy: ".").map { Int($0) ?? 0 } let countDifference = currentVersionNumbers.count - criteriaVersionNumbers.count switch countDifference { case 0..<Int.max: criteriaVersionNumbers.append(contentsOf: Array(repeating: 0, count:abs(countDifference))) case Int.min..<0: currentVersionNumbers.append(contentsOf: Array(repeating: 0, count:abs(countDifference))) default: break // 個数同じ } // major versionから順に比較していき、同値でなくなった時に大小比較結果を返す for (current, criteria) in zip(currentVersionNumbers, criteriaVersionNumbers) { if current > criteria { return false } else if current < criteria { return true } } // 同値 return false } }
35.189189
116
0.647465
1120211220967208b77f18191a62b2c1fb0310b6
1,938
import SwiftUI struct ContentView: View { // MARK: - Propertiers @State private var email = "" @State private var password = "" var body: some View { ZStack { // Background Color.purple .opacity(0.5) .edgesIgnoringSafeArea(.all) VStack() { Text("SIMPLE LOGIN SCREEN") .font(.largeTitle) .fontWeight(.heavy) .foregroundColor(Color.white) .padding([.top, .bottom], 40) Image("admin") .resizable() .frame(width: 250, height: 250) .clipShape(Circle()) .overlay(Circle().stroke(Color.white, lineWidth: 4)) .shadow(radius: 10) .padding(.bottom, 50) VStack(alignment: .leading, spacing: 15) { TextField("Email", text: self.$email) .padding() .background(Color.white) .cornerRadius(20.0) SecureField("Password", text: self.$password) .padding() .background(Color.white) .cornerRadius(20.0) } .padding([.leading, .trailing], 27.5) Button(action: { print("Button Pressed!") }, label: { Text("Sign In") .font(.title) .fontWeight(.bold) .foregroundColor(.white) }) .padding(.all) } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
31.258065
72
0.395769
1dfdc3c33914f1edd068f09ace3e35840f0721c9
3,365
// // ViewController.swift // Demo // // Created by Charles on 2021/11/15. // import UIKit import TLSerializable struct Cat { let name : String let age : Int let list : [String] } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() test1() test2() test3() let kitten = Cat(name: "kitten", age: 2, list : ["篮球","排球","乒乓球"]) let mirror = Mirror(reflecting: kitten) for child in mirror.children { print("\(child.label!) - \(child.value)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK:- 编码使用的 结构体 struct Person : TLSerializable { // enum CodingKeys: String, CodingKey { // case name = "_name" // case age = "_age" // } let name: String let age: Int let pet: Pet } struct Pet: TLSerializable { let name: String let desc: String } // MARK: - 测试 decode /// 只有状态值和提示信息的模型转化 struct ModelObjet: TLSerializable { /// 状态值 var status:Int? = nil /// 提示信息 var message:String? = nil } /// 转换成数组模型 struct ModelObjetT<T: TLSerializable>: TLSerializable { /// 状态值 var status:Int? = nil /// 提示信息 var message:String? = nil /// 嵌套模型 var data:T? = nil } // 转换成数组模型 struct ModelArrayT<T: TLSerializable>: TLSerializable { /// 状态值 var status:Int? = nil /// 提示信息 var message:String? = nil /// 嵌套模型 var data:[T]? = nil } struct Test1: TLSerializable { lazy var name: Double? = { return (Double(test ?? "0.00") ?? 0.00) * 100 }() /// 测试文字 var test:String? var jsonStr : String? } struct Test2: TLSerializable { lazy var name: String? = { return "我是test_name转换之后的\(test_name ?? "")" }() /// 测试文字 var test_name:String? var detial:[Detial]? } struct Detial: TLSerializable { var detial_name: String? } // json字符串一键转模型 func test1(){ let jsonString = "{\"status\":1000,\"message\":\"操作成功\",\"data\":{\"test\":\"0.05\",\"jsonStr\":\"{\\\"orderid\\\":1000,\\\"ordername\\\":\\\"hello kity\\\"}\"}}" // let model = jsonString.jsonStringMapModel(ModelObjetT<Test1>.self) var model = ModelObjetT<Test1>.deserialize(from: jsonString) print(model?.data?.test ?? "test无值") print(model?.data?.name ?? 0.00) print("============华丽的分割线==============") } func test2(){ let jsonString = "{\"status\":1000,\"message\":\"操作成功\",\"data\":{\"test_name\":\"Decodable\",\"detial\":[{\"detial_name\":\"看吧嵌套毫无压力\"}]}}" // let model = jsonString.jsonStringMapModel(ModelObjetT<Test2>.self) var model = ModelObjetT<Test2>.deserialize(from: jsonString) print(model?.data?.test_name ?? "test无值") print(model?.data?.name ?? "name无值") print(model?.data?.detial?.first?.detial_name ?? "detial_name无值") } func test3() { let jsonString = """ { "status":1000, "message":"操作成功", "data":[ {"name":"Pet1","desc": "pet1 desc"},{"name":"Pet2","desc": "pet2 desc"},{"name":"Pet3","desc": "pet3 desc"},{"name":"Pet4","desc": "pet4 desc"}, ] } """ let model = ModelArrayT<Pet>.deserialize(from: jsonString) print(model) }
24.742647
166
0.570282
483b65dd573a903f5a75251ff1cffcaf41e7dcb5
2,129
// // AppDelegate.swift // AwaitKitExample // // Created by Yannick LORIOT on 18/05/16. // Copyright © 2016 Yannick Loriot. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private 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 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.282609
281
0.77783
e9d8078c0a61d2aa50f4eeabc8f283581ced5f57
2,237
// // AirWatch-SDK-iOS-Swift-Sample // // Copyright © 2017 VMware, Inc. All rights reserved // // The BSD-2 license (the ìLicenseî) set forth below applies to all parts of the AirWatch-SDK-iOS-Swift // project. You may not use this file except in compliance with the License. // // BSD-2 License // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit class TutorialViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var topLabel: UILabel! var pageIndex: Int! var titleText: String! var imageFile: String! //Setting the title and the image override func viewDidLoad() { super.viewDidLoad() self.imageView.image = UIImage(named: self.imageFile) self.topLabel.text = self.titleText } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
41.425926
153
0.729996
dd781f11b6cbea4ac9be6b61c7efb901af285934
3,511
// // ScanListVC.swift // BT-Tracking // // Created by Tomas Svoboda on 18/03/2020. // Copyright © 2020 Covid19CZ. All rights reserved. // import RxSwift import RxCocoa import RxDataSources import FirebaseAuth final class ScanListVC: UIViewController, UITableViewDelegate { @IBOutlet private weak var tableView: UITableView! private var dataSource: RxTableViewSectionedAnimatedDataSource<ScanListVM.SectionModel>! private let viewModel = ScanListVM(scannerStore: AppDelegate.shared.scannerStore) private let bag = DisposeBag() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() if #available(iOS 13, *) { navigationController?.tabBarItem.image = UIImage(systemName: "wifi") } else { navigationController?.tabBarItem.image = UIImage(named: "wifi")?.resize(toWidth: 30) } navigationItem.largeTitleDisplayMode = .never setupTableView() } // MARK: - Actions @IBAction func signOutAction(_ sender: Any) { do { try Auth.auth().signOut() UserDefaults.resetStandardUserDefaults() let storyboard = UIStoryboard(name: "Signup", bundle: nil) view.window?.rootViewController = storyboard.instantiateInitialViewController() } catch { show(error: error) } } @IBAction func clearAction(_ sender: Any) { viewModel.clear() } @IBAction func closeAction(_ sender: Any) { dismiss(animated: true, completion: nil) } // MARK: - TableView private func setupTableView() { tableView.tableFooterView = UIView() tableView.allowsSelection = false tableView.rowHeight = UITableView.automaticDimension dataSource = RxTableViewSectionedAnimatedDataSource<ScanListVM.SectionModel>(configureCell: { datasource, tableView, indexPath, row in let cell: UITableViewCell? switch row { case .info(let buid): let infoCell = tableView.dequeueReusableCell(withIdentifier: InfoCell.identifier, for: indexPath) as? InfoCell infoCell?.configure(for: buid) cell = infoCell case .scan(let scan): let scanCell = tableView.dequeueReusableCell(withIdentifier: ScanCell.identifier, for: indexPath) as? ScanCell scanCell?.configure(for: scan) cell = scanCell } return cell ?? UITableViewCell() }) viewModel.sections .drive(tableView.rx.items(dataSource: dataSource)) .disposed(by: bag) tableView.rx.setDelegate(self) .disposed(by: bag) dataSource.animationConfiguration = AnimationConfiguration(insertAnimation: .fade, reloadAnimation: .none, deleteAnimation: .fade) } // MARK: - TableView section header func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 29 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let datasourceSection = dataSource.sectionModels[section] let cell = tableView.dequeueReusableCell(withIdentifier: SectionTitleCell.identifier, for: IndexPath(row: 0, section: section)) as? SectionTitleCell cell?.configure(for: datasourceSection.model.identity) return cell?.contentView ?? UIView() } }
32.211009
156
0.648248
4b189eb0b4b3f95748a5883cf6c886b442fd124b
2,157
// // NavigationController.swift // FritzAIStudio // // Created by Andrew Barba on 12/14/17. // Copyright © 2017 Fritz Labs, Inc. All rights reserved. // import UIKit class NavigationController: UINavigationController { override var preferredStatusBarStyle: UIStatusBarStyle { return .default } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidLoad() { super.viewDidLoad() navigationBar.tintColor = .white navigationBar.shadowImage = UIImage() navigationBar.isTranslucent = true navigationBar.setBackgroundImage(UIImage(), for: .default) let blurView = createBlurView() navigationBar.addSubview(blurView) let titleFont = UIFont.systemFont(ofSize: 17, weight: .bold) navigationBar.titleTextAttributes = [ .font: titleFont, .foregroundColor: UIColor.white ] let buttonFont = UIFont.systemFont(ofSize: 14, weight: .semibold) UIBarButtonItem.appearance(whenContainedInInstancesOf: [NavigationController.self]) .setTitleTextAttributes([ .font: buttonFont], for: .normal) UIBarButtonItem.appearance(whenContainedInInstancesOf: [NavigationController.self]) .setTitleTextAttributes([ .font: buttonFont], for: .highlighted) UIBarButtonItem.appearance(whenContainedInInstancesOf: [NavigationController.self]) .setTitleTextAttributes([ .font: buttonFont], for: .disabled) UIBarButtonItem.appearance(whenContainedInInstancesOf: [NavigationController.self]) .setTitleTextAttributes([ .font: buttonFont], for: .selected) } private func createBlurView() -> UIVisualEffectView { let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) var bounds = navigationBar.bounds let notchHeight: CGFloat = UIDevice.hasNotch ? 30.0 : 0.0 bounds.size.height += 20 + notchHeight bounds.origin.y -= 20 + notchHeight visualEffectView.isUserInteractionEnabled = false visualEffectView.frame = bounds visualEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] visualEffectView.layer.zPosition = -1 return visualEffectView } }
34.238095
87
0.741771
09b89d3b2f0f69e42d96d855892859e1f8dbf0d0
793
// // PreworkUITestsLaunchTests.swift // PreworkUITests // // Created by Jiaqi Li on 12/29/21. // import XCTest class PreworkUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
24.030303
88
0.67087
de7045a74df8610af0b363e92afb6a8c6de9d5bb
2,427
// // WelcomeViewController.swift // Kiretan0 // // Copyright (c) 2017 Hironori Ichimiya <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import RxCocoa import RxSwift public class WelcomeViewController: UIViewController { public var viewModel: WelcomeViewModel? @IBOutlet private weak var newAnonymousUserButton: UIButton! private var _disposeBag: DisposeBag? public override func viewDidLoad() { super.viewDidLoad() bindViewModel() } private func bindViewModel() { _disposeBag = nil guard let viewModel = viewModel else { return } let disposeBag = DisposeBag() viewModel.newAnonymousUserEnabled .bind(to: newAnonymousUserButton.rx.isEnabled) .disposed(by: disposeBag) newAnonymousUserButton.rx.tap .bind(to: viewModel.onNewAnonymousUser) .disposed(by: disposeBag) _disposeBag = disposeBag } } extension DefaultWelcomeViewModel: ViewControllerCreatable { public func createViewController() -> UIViewController { let storyboard = UIStoryboard(name: "Welcome", bundle: Bundle.main) let viewController = storyboard.instantiateInitialViewController() as! WelcomeViewController viewController.viewModel = self return viewController } }
35.691176
100
0.71611
762b0f8c78d5f81305c5dad5dfeda69b9d57f11c
504
// // File.swift // // // Created by neutralradiance on 12/2/20. // import Foundation /// A wrapper to build a rule-based syntax. public struct Syntax: Codable, Hashable, Equatable { public var elements: [Rule] } extension Syntax { public init(@SyntaxBuilder _ elements: () -> [Rule]) { self.elements = elements() } } @_functionBuilder public struct SyntaxBuilder { public static func buildBlock(_ elements: Rule...) -> Syntax { Syntax(elements: elements) } }
18.666667
66
0.652778
edea32cdde04273e24ee27a37feebdffe350f562
6,205
import Foundation import UIKit import CoreML class YOLO { public static let inputWidth = 416 public static let inputHeight = 416 public static let maxBoundingBoxes = 10 // Tweak these values to get more or fewer predictions. let confidenceThreshold: Float = 0.3 let iouThreshold: Float = 0.5 struct Prediction { let classIndex: Int let score: Float let rect: CGRect let ocr: String } let model = TinyYOLO() public init() { } public func predict(image: CVPixelBuffer) throws -> [Prediction] { if let output = try? model.prediction(image: image) { return computeBoundingBoxes(features: output.grid) } else { return [] } } public func computeBoundingBoxes(features: MLMultiArray) -> [Prediction] { assert(features.count == 125*13*13) var predictions = [Prediction]() let blockSize: Float = 32 let gridHeight = 13 let gridWidth = 13 let boxesPerCell = 5 let numClasses = 20 // The 416x416 image is divided into a 13x13 grid. Each of these grid cells // will predict 5 bounding boxes (boxesPerCell). A bounding box consists of // five data items: x, y, width, height, and a confidence score. Each grid // cell also predicts which class each bounding box belongs to. // // The "features" array therefore contains (numClasses + 5)*boxesPerCell // values for each grid cell, i.e. 125 channels. The total features array // contains 125x13x13 elements. // NOTE: It turns out that accessing the elements in the multi-array as // `features[[channel, cy, cx] as [NSNumber]].floatValue` is kinda slow. // It's much faster to use direct memory access to the features. let featurePointer = UnsafeMutablePointer<Double>(OpaquePointer(features.dataPointer)) let channelStride = features.strides[0].intValue let yStride = features.strides[1].intValue let xStride = features.strides[2].intValue func offset(_ channel: Int, _ x: Int, _ y: Int) -> Int { return channel*channelStride + y*yStride + x*xStride } for cy in 0..<gridHeight { for cx in 0..<gridWidth { for b in 0..<boxesPerCell { // For the first bounding box (b=0) we have to read channels 0-24, // for b=1 we have to read channels 25-49, and so on. let channel = b*(numClasses + 5) // The slow way: /* let tx = features[[channel , cy, cx] as [NSNumber]].floatValue let ty = features[[channel + 1, cy, cx] as [NSNumber]].floatValue let tw = features[[channel + 2, cy, cx] as [NSNumber]].floatValue let th = features[[channel + 3, cy, cx] as [NSNumber]].floatValue let tc = features[[channel + 4, cy, cx] as [NSNumber]].floatValue */ // The fast way: let tx = Float(featurePointer[offset(channel , cx, cy)]) let ty = Float(featurePointer[offset(channel + 1, cx, cy)]) let tw = Float(featurePointer[offset(channel + 2, cx, cy)]) let th = Float(featurePointer[offset(channel + 3, cx, cy)]) let tc = Float(featurePointer[offset(channel + 4, cx, cy)]) // The predicted tx and ty coordinates are relative to the location // of the grid cell; we use the logistic sigmoid to constrain these // coordinates to the range 0 - 1. Then we add the cell coordinates // (0-12) and multiply by the number of pixels per grid cell (32). // Now x and y represent center of the bounding box in the original // 416x416 image space. let x = (Float(cx) + sigmoid(tx)) * blockSize let y = (Float(cy) + sigmoid(ty)) * blockSize // The size of the bounding box, tw and th, is predicted relative to // the size of an "anchor" box. Here we also transform the width and // height into the original 416x416 image space. let w = exp(tw) * anchors[2*b ] * blockSize let h = exp(th) * anchors[2*b + 1] * blockSize // The confidence value for the bounding box is given by tc. We use // the logistic sigmoid to turn this into a percentage. let confidence = sigmoid(tc) // Gather the predicted classes for this anchor box and softmax them, // so we can interpret these numbers as percentages. var classes = [Float](repeating: 0, count: numClasses) for c in 0..<numClasses { // The slow way: //classes[c] = features[[channel + 5 + c, cy, cx] as [NSNumber]].floatValue // The fast way: classes[c] = Float(featurePointer[offset(channel + 5 + c, cx, cy)]) } classes = softmax(classes) // Find the index of the class with the largest score. let (detectedClass, bestClassScore) = classes.argmax() // Combine the confidence score for the bounding box, which tells us // how likely it is that there is an object in this box (but not what // kind of object it is), with the largest class prediction, which // tells us what kind of object it detected (but not where). let confidenceInClass = bestClassScore * confidence // Since we compute 13x13x5 = 845 bounding boxes, we only want to // keep the ones whose combined score is over a certain threshold. if confidenceInClass > confidenceThreshold { let rect = CGRect(x: CGFloat(x - w/2), y: CGFloat(y - h/2), width: CGFloat(w), height: CGFloat(h)) let prediction = Prediction(classIndex: detectedClass, score: confidenceInClass, rect: rect, ocr: "") predictions.append(prediction) } } } } // We already filtered out any bounding boxes that have very low scores, // but there still may be boxes that overlap too much with others. We'll // use "non-maximum suppression" to prune those duplicate bounding boxes. return nonMaxSuppression(boxes: predictions, limit: YOLO.maxBoundingBoxes, threshold: iouThreshold) } }
41.366667
103
0.621918
e8fecf40b0ef48a0dc194e40f170517a876d4b35
9,006
/** * Copyright © 2019 Aga Khan Foundation * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import Foundation enum AKFCausesEndPoint { case healthcheck case participant(fbId: String) case participants case team(teamId: Int) case teams case event(eventId: Int) case events case record(recordId: Int) case records case leaderboard(eventId: Int) case source(sourceId: Int) case sources case commitment case commitments(id: Int) // swiftlint:disable:this identifier_name case achievement } extension AKFCausesEndPoint { public var rawValue: String { switch self { case .healthcheck: return "/" case .participant(let fbid): return "/participants/\(fbid)" case .participants: return "/participants" case .team(let teamId): return "/teams/\(teamId)" case .teams: return "/teams" case .event(let eventId): return "/events/\(eventId)" case .events: return "/events" case .record(let recordId): return "/records/\(recordId)" case .records: return "/records" case .leaderboard(let eventId): return "/teams/stats/\(eventId)" case .source(let sourceId): return "/sources/\(sourceId)" case .sources: return "/sources" case .commitment: return "/commitments" case .commitments(let cid): return "/commitments/\(cid)" case .achievement: return "/achievement" } } } class AKFCausesService: Service { public static var shared: AKFCausesService = AKFCausesService(server: AppConfig.server) init(server: URLComponents) { let config = URLSessionConfiguration.default config.httpAdditionalHeaders = ["Authorization": "Basic \(AppConfig.serverPassword)"] super.init(server: server, session: URLSession(configuration: config)) } private func request(_ method: HTTPMethod = .get, endpoint: AKFCausesEndPoint, query: JSON? = nil, parameters: JSON? = nil, completion: ServiceRequestCompletion?) { guard let url = buildURL(endpoint.rawValue, query) else { self.callback(completion, result: .failed(nil)) return } request(method, url: url, parameters: parameters, completion: completion) } static func createParticipant(fbid: String, completion: ServiceRequestCompletion? = nil) { shared.request(.post, endpoint: .participants, parameters: JSON(["fbid": fbid]), completion: completion) } static func getParticipant(fbid: String, completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .participant(fbId: fbid), completion: completion) } static func deleteParticipant(fbid: String, completion: ServiceRequestCompletion? = nil) { shared.request(.delete, endpoint: .participant(fbId: fbid), completion: completion) } static func createTeam(name: String, imageName: String = "", lead fbid: String, hidden: Bool = false, completion: ServiceRequestCompletion? = nil) { shared.request(.post, endpoint: .teams, parameters: JSON([ "name": name, "image": imageName, "creator_id": fbid, "hidden": hidden ]), completion: completion) } static func deleteTeam(team: Int, completion: ServiceRequestCompletion? = nil) { shared.request(.delete, endpoint: .team(teamId: team), completion: completion) } static func getTeams(completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .teams, completion: completion) } static func getTeam(team: Int, completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .team(teamId: team), completion: completion) } static func getAchievement(completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .achievement, completion: completion) } static func joinTeam(fbid: String, team: Int, completion: ServiceRequestCompletion? = nil) { shared.request(.patch, endpoint: .participant(fbId: fbid), parameters: JSON(["team_id": team]), completion: completion) } static func leaveTeam(fbid: String, completion: ServiceRequestCompletion? = nil) { shared.request(.patch, endpoint: .participant(fbId: fbid), parameters: JSON(["team_id": "null"]), completion: completion) } static func editTeamName(teamId: Int, name: String, completion: ServiceRequestCompletion? = nil) { shared.request(.patch, endpoint: .team(teamId: teamId), parameters: JSON(["name": name]), completion: completion) } static func performAPIHealthCheck(completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .healthcheck, completion: completion) } static func getEvent(event: Int, completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .event(eventId: event), completion: completion) } static func getEvents(completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .events, completion: completion) } static func getRecord(record: Int, completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .record(recordId: record), completion: completion) } static func getLeaderboard(eventId: Int, completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .leaderboard(eventId: eventId), completion: completion) } static func createRecord(for participantID: Int, dated: Date = Date.init(timeIntervalSinceNow: 0), steps: Int, sourceID: Int, completion: ServiceRequestCompletion? = nil) { shared.request(.post, endpoint: .records, parameters: JSON([ "date": Date.formatter.string(from: dated), "distance": steps, "participant_id": participantID, "source_id": sourceID ]), completion: completion) } static func getSource(source: Int, completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .source(sourceId: source), completion: completion) } static func getSources(completion: ServiceRequestCompletion? = nil) { shared.request(endpoint: .sources, completion: completion) } static func joinEvent(fbid: String, eventID: Int, steps: Int, commpletion: ServiceRequestCompletion? = nil) { shared.request(.post, endpoint: .commitment, parameters: JSON(["fbid": fbid, "event_id": eventID, "commitment": steps]), completion: commpletion) } static func setCommitment(_ commitment: Int, toSteps steps: Int, completion: ServiceRequestCompletion? = nil) { shared.request(.patch, endpoint: .commitments(id: commitment), parameters: JSON(["commitment": steps]), completion: completion) } } extension AKFCausesService { static func getSourceByName(source: String, completion: ServiceRequestCompletion? = nil) { getSources { result in switch result { case .failed(let error): shared.callback(completion, result: .failed(error)) case .success(let status, let response): let source: JSON? = response?.arrayValue?.filter { Source(json: $0)?.name == source }.first shared.callback(completion, result: .success(statusCode: status, response: source)) } } } }
38
103
0.666778
cc34ea33aa7ea3777698a3b2928a8392526212c2
1,768
// // BrowseStationCell.swift // SailboatRadio // // Created by Dmitry Mazo on 1/3/21. // Copyright © 2021 SailboatDevelopment, Inc. All rights reserved. // import SwiftUI import SailboatMedia struct BrowseStationCell: View { private struct Constants { static let size: CGFloat = 60 } @ObservedObject private var service = ImageLoader() private var favoriteButton = Image(systemName: "star") private var mainView: some View { HStack(spacing: 10) { stationImage .frame(width: Constants.size, height: Constants.size) VStack(alignment: .leading, spacing: 2) { Text("\(station.name)") Text("\(station.homepage ?? "")") } Spacer() favoriteButton } .padding(5) .background(Color.gray.opacity(0.3)) .cornerRadius(3) } private var stationImage: some View { Group { if let image = service.image { Image(uiImage: image) .resizable() } else { Image("music-note", bundle: Bundle(for: SailboatMedia.self)) .resizable() } } } let station: BrowseStationViewModel var body: some View { mainView .padding(.horizontal, 10) } init(station: BrowseStationViewModel) { self.station = station guard let iconUrl = station.iconUrl else { return } try? service.load(url: iconUrl) } } struct BrowseStationViewModel { var id: String var name: String var homepage: String? var country: String? var audioUrl: URL var iconUrl: URL? }
23.573333
76
0.548643
fe49fd3375f9ed1bb0a639c946c319d2c6f9df1b
21,693
/* Abstract: The file contains the input elements. The html-element 'input' only allows these elements to be its descendants. Authors: - Mats Moll (https://github.com/matsmoll) Contributors: - Mattes Mohr (https://github.com/mattesmohr) Note: If you about to add something to the file, stick to the official documentation to keep the code consistent. */ import OrderedCollections /// The alias for the element OptionGroup. /// /// Optgroup is the official tag and can be used instead of OptionGroup. /// /// ```html /// <optgroup></optgroup> /// ``` public typealias Optgroup = OptionGroup /// The element represents a group of options. /// /// ```html /// <optgroup></optgroup> /// ``` public struct OptionGroup: ContentNode, InputElement { internal var name: String { "optgroup" } internal var attributes: OrderedDictionary<String, Any>? internal var content: [AnyContent] public init(@ContentBuilder<AnyContent> content: () -> [AnyContent]) { self.content = content() } internal init(attributes: OrderedDictionary<String, Any>?, content: [AnyContent]) { self.attributes = attributes self.content = content } } extension OptionGroup: GlobalAttributes, DisabledAttribute, LabelAttribute { public func accessKey(_ value: Character) -> OptionGroup { return mutate(accesskey: value) } public func autocapitalize(_ type: Capitalization) -> OptionGroup { return mutate(autocapitalize: type.rawValue) } public func autofocus() -> OptionGroup { return mutate(autofocus: "autofocus") } public func `class`(_ value: String) -> OptionGroup { return mutate(class: value) } public func isEditable(_ condition: Bool) -> OptionGroup { return mutate(contenteditable: condition) } public func direction(_ type: Direction) -> OptionGroup { return mutate(dir: type.rawValue) } public func isDraggable(_ condition: Bool) -> OptionGroup { return mutate(draggable: condition) } public func enterKeyHint(_ type: Hint) -> OptionGroup { return mutate(enterkeyhint: type.rawValue) } public func hidden() -> OptionGroup { return mutate(hidden: "hidden") } public func inputMode(_ value: String) -> OptionGroup { return mutate(inputmode: value) } public func `is`(_ value: String) -> OptionGroup { return mutate(is: value) } public func itemId(_ value: String) -> OptionGroup { return mutate(itemid: value) } public func itemProperty(_ value: String) -> OptionGroup { return mutate(itemprop: value) } public func itemReference(_ value: String) -> OptionGroup { return mutate(itemref: value) } public func itemScope(_ value: String) -> OptionGroup { return mutate(itemscope: value) } public func itemType(_ value: String) -> OptionGroup { return mutate(itemtype: value) } public func id(_ value: String) -> OptionGroup { return mutate(id: value) } public func id(_ value: TemplateValue<String>) -> OptionGroup { return mutate(id: value.rawValue) } public func language(_ type: Language) -> OptionGroup { return mutate(lang: type.rawValue) } public func nonce(_ value: String) -> OptionGroup { return mutate(nonce: value) } @available(*, deprecated, message: "use role(_ value: Roles) instead") public func role(_ value: String) -> OptionGroup { return mutate(role: value) } public func role(_ value: Roles) -> OptionGroup { return mutate(role: value.rawValue) } public func hasSpellCheck(_ condition: Bool) -> OptionGroup { return mutate(spellcheck: condition) } public func style(_ value: String) -> OptionGroup { return mutate(style: value) } public func tabIndex(_ value: Int) -> OptionGroup { return mutate(tabindex: value) } public func title(_ value: String) -> OptionGroup { return mutate(title: value) } @available(*, deprecated, message: "use translate(_ type: Decision) instead") public func translate(_ value: String) -> OptionGroup { return mutate(translate: value) } public func translate(_ type: Decision) -> OptionGroup { return mutate(translate: type.rawValue) } public func disabled() -> OptionGroup { return mutate(disabled: "disabled") } public func label(_ value: String) -> OptionGroup { return mutate(label: value) } public func custom(key: String, value: Any) -> OptionGroup { return mutate(key: key, value: value) } } extension OptionGroup: AnyContent { public func prerender(_ formula: Renderer.Formula) throws { try self.build(formula) } public func render<T>(with manager: Renderer.ContextManager<T>) throws -> String { try self.build(with: manager) } } extension OptionGroup: Modifiable { public func modify(if condition: Bool, element: (Self) -> Self) -> Self { if condition { return modify(element(self)) } return self } public func modify<T>(unwrap value: TemplateValue<T?>, element: (Self, TemplateValue<T>) -> Self) -> Self { switch value { case .constant(let optional): guard let value = optional else { return self } return modify(element(self, .constant(value))) case .dynamic(let context): if context.isMascadingOptional { return modify(element(self, .dynamic(context.unsafeCast(to: T.self)))) } else { return modify(element(self, .dynamic(context.unsafelyUnwrapped))) } } } } /// The element represents an option. /// /// ```html /// <option></option> /// ``` public struct Option: ContentNode, InputElement { internal var name: String { "option" } internal var attributes: OrderedDictionary<String, Any>? internal var content: [String] public init(@ContentBuilder<String> content: () -> [String]) { self.content = content() } internal init(attributes: OrderedDictionary<String, Any>?, content: [String]) { self.attributes = attributes self.content = content } } extension Option: GlobalAttributes, DisabledAttribute, LabelAttribute, ValueAttribute, SelectedAttribute { public func accessKey(_ value: Character) -> Option { return mutate(accesskey: value) } public func autocapitalize(_ type: Capitalization) -> Option { return mutate(autocapitalize: type.rawValue) } public func autofocus() -> Option { return mutate(autofocus: "autofocus") } public func `class`(_ value: String) -> Option { return mutate(class: value) } public func isEditable(_ condition: Bool) -> Option { return mutate(contenteditable: condition) } public func direction(_ type: Direction) -> Option { return mutate(dir: type.rawValue) } public func isDraggable(_ condition: Bool) -> Option { return mutate(draggable: condition) } public func enterKeyHint(_ type: Hint) -> Option { return mutate(enterkeyhint: type.rawValue) } public func hidden() -> Option { return mutate(hidden: "hidden") } public func inputMode(_ value: String) -> Option { return mutate(inputmode: value) } public func `is`(_ value: String) -> Option { return mutate(is: value) } public func itemId(_ value: String) -> Option { return mutate(itemid: value) } public func itemProperty(_ value: String) -> Option { return mutate(itemprop: value) } public func itemReference(_ value: String) -> Option { return mutate(itemref: value) } public func itemScope(_ value: String) -> Option { return mutate(itemscope: value) } public func itemType(_ value: String) -> Option { return mutate(itemtype: value) } public func id(_ value: String) -> Option { return mutate(id: value) } public func id(_ value: TemplateValue<String>) -> Option { return mutate(id: value.rawValue) } public func language(_ type: Language) -> Option { return mutate(lang: type.rawValue) } public func nonce(_ value: String) -> Option { return mutate(nonce: value) } @available(*, deprecated, message: "use role(_ value: Roles) instead") public func role(_ value: String) -> Option { return mutate(role: value) } public func role(_ value: Roles) -> Option { return mutate(role: value.rawValue) } public func hasSpellCheck(_ condition: Bool) -> Option { return mutate(spellcheck: condition) } public func style(_ value: String) -> Option { return mutate(style: value) } public func tabIndex(_ value: Int) -> Option { return mutate(tabindex: value) } public func title(_ value: String) -> Option { return mutate(title: value) } @available(*, deprecated, message: "use translate(_ type: Decision) instead") public func translate(_ value: String) -> Option { return mutate(translate: value) } public func translate(_ type: Decision) -> Option { return mutate(translate: type.rawValue) } public func disabled() -> Option { return mutate(disabled: "disabled") } public func label(_ value: String) -> Option { return mutate(label: value) } public func value(_ value: String) -> Option { return mutate(value: value) } public func value(_ value: TemplateValue<String>) -> Option { return mutate(value: value.rawValue) } public func selected() -> Option { return mutate(selected: "selected") } public func custom(key: String, value: Any) -> Option { return mutate(key: key, value: value) } } extension Option: AnyContent { public func prerender(_ formula: Renderer.Formula) throws { try self.build(formula) } public func render<T>(with manager: Renderer.ContextManager<T>) throws -> String { try self.build(with: manager) } } extension Option: Modifiable { public func modify(if condition: Bool, element: (Self) -> Self) -> Self { if condition { return modify(element(self)) } return self } public func modify<T>(unwrap value: TemplateValue<T?>, element: (Self, TemplateValue<T>) -> Self) -> Self { switch value { case .constant(let optional): guard let value = optional else { return self } return modify(element(self, .constant(value))) case .dynamic(let context): if context.isMascadingOptional { return modify(element(self, .dynamic(context.unsafeCast(to: T.self)))) } else { return modify(element(self, .dynamic(context.unsafelyUnwrapped))) } } } } /// The element represents a caption for the rest of the contents of a fieldset. /// /// ```html /// <legend></legend> /// ``` public struct Legend: ContentNode, InputElement { internal var name: String { "legend" } internal var attributes: OrderedDictionary<String, Any>? internal var content: [AnyContent] public init(@ContentBuilder<AnyContent> content: () -> [AnyContent]) { self.content = content() } internal init(attributes: OrderedDictionary<String, Any>?, content: [AnyContent]) { self.attributes = attributes self.content = content } } extension Legend: GlobalAttributes { public func accessKey(_ value: Character) -> Legend { return mutate(accesskey: value) } public func autocapitalize(_ type: Capitalization) -> Legend { return mutate(autocapitalize: type.rawValue) } public func autofocus() -> Legend { return mutate(autofocus: "autofocus") } public func `class`(_ value: String) -> Legend { return mutate(class: value) } public func isEditable(_ condition: Bool) -> Legend { return mutate(contenteditable: condition) } public func direction(_ type: Direction) -> Legend { return mutate(dir: type.rawValue) } public func isDraggable(_ condition: Bool) -> Legend { return mutate(draggable: condition) } public func enterKeyHint(_ type: Hint) -> Legend { return mutate(enterkeyhint: type.rawValue) } public func hidden() -> Legend { return mutate(hidden: "hidden") } public func inputMode(_ value: String) -> Legend { return mutate(inputmode: value) } public func `is`(_ value: String) -> Legend { return mutate(is: value) } public func itemId(_ value: String) -> Legend { return mutate(itemid: value) } public func itemProperty(_ value: String) -> Legend { return mutate(itemprop: value) } public func itemReference(_ value: String) -> Legend { return mutate(itemref: value) } public func itemScope(_ value: String) -> Legend { return mutate(itemscope: value) } public func itemType(_ value: String) -> Legend { return mutate(itemtype: value) } public func id(_ value: String) -> Legend { return mutate(id: value) } public func id(_ value: TemplateValue<String>) -> Legend { return mutate(id: value.rawValue) } public func language(_ type: Language) -> Legend { return mutate(lang: type.rawValue) } public func nonce(_ value: String) -> Legend { return mutate(nonce: value) } @available(*, deprecated, message: "use role(_ value: Roles) instead") public func role(_ value: String) -> Legend { return mutate(role: value) } public func role(_ value: Roles) -> Legend { return mutate(role: value.rawValue) } public func hasSpellCheck(_ condition: Bool) -> Legend { return mutate(spellcheck: condition) } public func style(_ value: String) -> Legend { return mutate(style: value) } public func tabIndex(_ value: Int) -> Legend { return mutate(tabindex: value) } public func title(_ value: String) -> Legend { return mutate(title: value) } @available(*, deprecated, message: "use translate(_ type: Decision) instead") public func translate(_ value: String) -> Legend { return mutate(translate: value) } public func translate(_ type: Decision) -> Legend { return mutate(translate: type.rawValue) } public func custom(key: String, value: Any) -> Legend { return mutate(key: key, value: value) } } extension Legend: AnyContent { public func prerender(_ formula: Renderer.Formula) throws { try self.build(formula) } public func render<T>(with manager: Renderer.ContextManager<T>) throws -> String { try self.build(with: manager) } } extension Legend: Modifiable { public func modify(if condition: Bool, element: (Self) -> Self) -> Self { if condition { return modify(element(self)) } return self } public func modify<T>(unwrap value: TemplateValue<T?>, element: (Self, TemplateValue<T>) -> Self) -> Self { switch value { case .constant(let optional): guard let value = optional else { return self } return modify(element(self, .constant(value))) case .dynamic(let context): if context.isMascadingOptional { return modify(element(self, .dynamic(context.unsafeCast(to: T.self)))) } else { return modify(element(self, .dynamic(context.unsafelyUnwrapped))) } } } } /// The element represents a summary, caption, or legend for the rest of the content. /// /// ```html /// <summary></summary> /// ``` public struct Summary: ContentNode, InputElement { internal var name: String { "summary" } internal var attributes: OrderedDictionary<String, Any>? internal var content: [AnyContent] public init(@ContentBuilder<AnyContent> content: () -> [AnyContent]) { self.content = content() } internal init(attributes: OrderedDictionary<String, Any>?, content: [AnyContent]) { self.attributes = attributes self.content = content } } extension Summary: GlobalAttributes { public func accessKey(_ value: Character) -> Summary { return mutate(accesskey: value) } public func autocapitalize(_ type: Capitalization) -> Summary { return mutate(autocapitalize: type.rawValue) } public func autofocus() -> Summary { return mutate(autofocus: "autofocus") } public func `class`(_ value: String) -> Summary { return mutate(class: value) } public func isEditable(_ condition: Bool) -> Summary { return mutate(contenteditable: condition) } public func direction(_ type: Direction) -> Summary { return mutate(dir: type.rawValue) } public func isDraggable(_ condition: Bool) -> Summary { return mutate(draggable: condition) } public func enterKeyHint(_ type: Hint) -> Summary { return mutate(enterkeyhint: type.rawValue) } public func hidden() -> Summary { return mutate(hidden: "hidden") } public func inputMode(_ value: String) -> Summary { return mutate(inputmode: value) } public func `is`(_ value: String) -> Summary { return mutate(is: value) } public func itemId(_ value: String) -> Summary { return mutate(itemid: value) } public func itemProperty(_ value: String) -> Summary { return mutate(itemprop: value) } public func itemReference(_ value: String) -> Summary { return mutate(itemref: value) } public func itemScope(_ value: String) -> Summary { return mutate(itemscope: value) } public func itemType(_ value: String) -> Summary { return mutate(itemtype: value) } public func id(_ value: String) -> Summary { return mutate(id: value) } public func id(_ value: TemplateValue<String>) -> Summary { return mutate(id: value.rawValue) } public func language(_ type: Language) -> Summary { return mutate(lang: type.rawValue) } public func nonce(_ value: String) -> Summary { return mutate(nonce: value) } @available(*, deprecated, message: "use role(_ value: Roles) instead") public func role(_ value: String) -> Summary { return mutate(role: value) } public func role(_ value: Roles) -> Summary { return mutate(role: value.rawValue) } public func hasSpellCheck(_ condition: Bool) -> Summary { return mutate(spellcheck: condition) } public func style(_ value: String) -> Summary { return mutate(style: value) } public func tabIndex(_ value: Int) -> Summary { return mutate(tabindex: value) } public func title(_ value: String) -> Summary { return mutate(title: value) } @available(*, deprecated, message: "use translate(_ type: Decision) instead") public func translate(_ value: String) -> Summary { return mutate(translate: value) } public func translate(_ type: Decision) -> Summary { return mutate(translate: type.rawValue) } public func custom(key: String, value: Any) -> Summary { return mutate(key: key, value: value) } } extension Summary: AnyContent { public func prerender(_ formula: Renderer.Formula) throws { try self.build(formula) } public func render<T>(with manager: Renderer.ContextManager<T>) throws -> String { try self.build(with: manager) } } extension Summary: Modifiable { public func modify(if condition: Bool, element: (Self) -> Self) -> Self { if condition { return modify(element(self)) } return self } public func modify<T>(unwrap value: TemplateValue<T?>, element: (Self, TemplateValue<T>) -> Self) -> Self { switch value { case .constant(let optional): guard let value = optional else { return self } return modify(element(self, .constant(value))) case .dynamic(let context): if context.isMascadingOptional { return modify(element(self, .dynamic(context.unsafeCast(to: T.self)))) } else { return modify(element(self, .dynamic(context.unsafelyUnwrapped))) } } } }
26.487179
113
0.600378
29c9a7011159a250406bd49f6d6cad017b72b277
16,930
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 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 // //===----------------------------------------------------------------------===// @testable import NIO import XCTest class ChannelNotificationTest: XCTestCase { private static func assertFulfilled(promise: EventLoopPromise<Void>?, promiseName: String, trigger: String, setter: String, file: StaticString = #file, line: UInt = #line) { if let promise = promise { XCTAssertTrue(promise.futureResult.isFulfilled, "\(promiseName) not fulfilled before \(trigger) was called", file: (file), line: line) } else { XCTFail("\(setter) not called before \(trigger)", file: (file), line: line) } } // Handler that verifies the notification order of the different promises + the inbound events that are fired. class SocketChannelLifecycleVerificationHandler: ChannelDuplexHandler { typealias InboundIn = Any typealias OutboundIn = Any private var registerPromise: EventLoopPromise<Void>? private var connectPromise: EventLoopPromise<Void>? private var closePromise: EventLoopPromise<Void>? public func channelActive(context: ChannelHandlerContext) { XCTAssertTrue(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelActive", setter: "register") assertFulfilled(promise: self.connectPromise, promiseName: "connectPromise", trigger: "channelActive", setter: "connect") XCTAssertNil(self.closePromise) XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func channelInactive(context: ChannelHandlerContext) { XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register") assertFulfilled(promise: self.connectPromise, promiseName: "connectPromise", trigger: "channelInactive", setter: "connect") assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close") XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func channelRegistered(context: ChannelHandlerContext) { XCTAssertFalse(context.channel.isActive) XCTAssertNil(self.connectPromise) XCTAssertNil(self.closePromise) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelRegistered", setter: "register") XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func channelUnregistered(context: ChannelHandlerContext) { XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register") assertFulfilled(promise: self.connectPromise, promiseName: "connectPromise", trigger: "channelInactive", setter: "connect") assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close") XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func register(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) { XCTAssertNil(self.registerPromise) XCTAssertNil(self.connectPromise) XCTAssertNil(self.closePromise) promise!.futureResult.whenSuccess { XCTAssertFalse(context.channel.isActive) } self.registerPromise = promise context.register(promise: promise) } public func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) { XCTFail("bind(...) should not be called") context.bind(to: address, promise: promise) } public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) { XCTAssertNotNil(self.registerPromise) XCTAssertNil(self.connectPromise) XCTAssertNil(self.closePromise) promise!.futureResult.whenSuccess { XCTAssertTrue(context.channel.isActive) } self.connectPromise = promise context.connect(to: address, promise: promise) } public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) { XCTAssertNotNil(self.registerPromise) XCTAssertNotNil(self.connectPromise) XCTAssertNil(self.closePromise) promise!.futureResult.whenSuccess { XCTAssertFalse(context.channel.isActive) } self.closePromise = promise context.close(mode: mode, promise: promise) } } class AcceptedSocketChannelLifecycleVerificationHandler: ChannelDuplexHandler { typealias InboundIn = Any typealias OutboundIn = Any private var registerPromise: EventLoopPromise<Void>? private let activeChannelPromise: EventLoopPromise<Channel> init(_ activeChannelPromise: EventLoopPromise<Channel>) { self.activeChannelPromise = activeChannelPromise } public func channelActive(context: ChannelHandlerContext) { XCTAssertTrue(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelActive", setter: "register") XCTAssertFalse(context.channel.closeFuture.isFulfilled) XCTAssertFalse(self.activeChannelPromise.futureResult.isFulfilled) self.activeChannelPromise.succeed(context.channel) } public func channelInactive(context: ChannelHandlerContext) { XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register") XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func channelRegistered(context: ChannelHandlerContext) { XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelRegistered", setter: "register") XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func channelUnregistered(context: ChannelHandlerContext) { XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelUnregistered", setter: "register") XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func register(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) { XCTAssertNil(self.registerPromise) let p = promise ?? context.eventLoop.makePromise() p.futureResult.whenSuccess { XCTAssertFalse(context.channel.isActive) } self.registerPromise = p context.register(promise: p) } public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) { XCTFail("connect(...) should not be called") context.connect(to: address, promise: promise) } public func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) { XCTFail("bind(...) should not be called") context.bind(to: address, promise: promise) } public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) { XCTFail("close(...) should not be called") context.close(mode: mode, promise: promise) } } class ServerSocketChannelLifecycleVerificationHandler: ChannelDuplexHandler { typealias InboundIn = Any typealias OutboundIn = Any private var registerPromise: EventLoopPromise<Void>? private var bindPromise: EventLoopPromise<Void>? private var closePromise: EventLoopPromise<Void>? public func channelActive(context: ChannelHandlerContext) { XCTAssertTrue(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelActive", setter: "register") XCTAssertNil(self.closePromise) XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func channelInactive(context: ChannelHandlerContext) { XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register") assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close") XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func channelRegistered(context: ChannelHandlerContext) { XCTAssertFalse(context.channel.isActive) XCTAssertNil(closePromise) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelRegistered", setter: "register") XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func channelUnregistered(context: ChannelHandlerContext) { XCTAssertFalse(context.channel.isActive) assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelUnregistered", setter: "register") assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close") XCTAssertFalse(context.channel.closeFuture.isFulfilled) } public func register(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) { XCTAssertNil(self.registerPromise) XCTAssertNil(self.bindPromise) XCTAssertNil(self.closePromise) let p = promise ?? context.eventLoop.makePromise() p.futureResult.whenSuccess { XCTAssertFalse(context.channel.isActive) } self.registerPromise = p context.register(promise: p) } public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) { XCTFail("connect(...) should not be called") context.connect(to: address, promise: promise) } public func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) { XCTAssertNotNil(self.registerPromise) XCTAssertNil(self.bindPromise) XCTAssertNil(self.closePromise) promise?.futureResult.whenSuccess { XCTAssertTrue(context.channel.isActive) } self.bindPromise = promise context.bind(to: address, promise: promise) } public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) { XCTAssertNotNil(self.registerPromise) XCTAssertNotNil(self.bindPromise) XCTAssertNil(self.closePromise) let p = promise ?? context.eventLoop.makePromise() p.futureResult.whenSuccess { XCTAssertFalse(context.channel.isActive) } self.closePromise = p context.close(mode: mode, promise: p) } } func testNotificationOrder() throws { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } let acceptedChannelPromise = group.next().makePromise(of: Channel.self) let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .serverChannelInitializer { channel in channel.pipeline.addHandler(ServerSocketChannelLifecycleVerificationHandler()) } .childChannelOption(ChannelOptions.autoRead, value: false) .childChannelInitializer { channel in channel.pipeline.addHandler(AcceptedSocketChannelLifecycleVerificationHandler(acceptedChannelPromise)) } .bind(host: "127.0.0.1", port: 0).wait()) let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group) .channelInitializer { channel in channel.pipeline.addHandler(SocketChannelLifecycleVerificationHandler()) } .connect(to: serverChannel.localAddress!).wait()) XCTAssertNoThrow(try clientChannel.close().wait()) XCTAssertNoThrow(try clientChannel.closeFuture.wait()) let channel = try acceptedChannelPromise.futureResult.wait() var buffer = channel.allocator.buffer(capacity: 8) buffer.writeString("test") while (try? channel.writeAndFlush(buffer).wait()) != nil { // Just write in a loop until it fails to ensure we detect the closed connection in a timely manner. } XCTAssertNoThrow(try channel.closeFuture.wait()) XCTAssertNoThrow(try serverChannel.close().wait()) XCTAssertNoThrow(try serverChannel.closeFuture.wait()) } func testActiveBeforeChannelRead() throws { // Use two EventLoops to ensure the ServerSocketChannel and the SocketChannel are on different threads. let group = MultiThreadedEventLoopGroup(numberOfThreads: 2) defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) } class OrderVerificationHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer private enum State { case `init` case active case read case readComplete case inactive } private var state = State.`init` private let promise: EventLoopPromise<Void> init(_ promise: EventLoopPromise<Void>) { self.promise = promise } public func channelActive(context: ChannelHandlerContext) { XCTAssertEqual(.`init`, state) state = .active } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { XCTAssertEqual(.active, state) state = .read } public func channelReadComplete(context: ChannelHandlerContext) { XCTAssertTrue(.read == state || .readComplete == state, "State should either be .read or .readComplete but was \(state)") state = .readComplete } public func channelInactive(context: ChannelHandlerContext) { XCTAssertEqual(.readComplete, state) state = .inactive promise.succeed(()) } } let promise = group.next().makePromise(of: Void.self) let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .childChannelOption(ChannelOptions.autoRead, value: true) .childChannelInitializer { channel in channel.pipeline.addHandler(OrderVerificationHandler(promise)) } .bind(host: "127.0.0.1", port: 0).wait()) let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group) .connect(to: serverChannel.localAddress!).wait()) var buffer = clientChannel.allocator.buffer(capacity: 2) buffer.writeString("X") XCTAssertNoThrow(try clientChannel.writeAndFlush(buffer).flatMap { clientChannel.close() }.wait()) XCTAssertNoThrow(try promise.futureResult.wait()) XCTAssertNoThrow(try clientChannel.closeFuture.wait()) XCTAssertNoThrow(try serverChannel.close().wait()) XCTAssertNoThrow(try serverChannel.closeFuture.wait()) } }
42.219451
177
0.658004
f785ff577ac1d47d8b0923dc2d12cb3d30c85252
1,714
// Copyright 2018 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Transport.swift // EspressifProvision // import Foundation enum TransportError: Error { case deviceUnreachableError(String) case communicationError(Int) } /** * Transport interface which abstracts the * transport layer to send messages to the Device. */ protocol Transport { var utility: Utility { get } /// Send message data relating to session establishment. /// /// - Parameters: /// - data: data to be sent /// - completionHandler: handler called when data is successfully sent and response is received func SendSessionData(data: Data, completionHandler: @escaping (Data?, Error?) -> Swift.Void) /// Send data relating to device configurations /// /// - Parameters: /// - path: path of the config endpoint /// - data: config data to be sent /// - completionHandler: handler called when data is successfully sent and response is recieved func SendConfigData(path: String, data: Data, completionHandler: @escaping (Data?, Error?) -> Swift.Void) func isDeviceConfigured() -> Bool func disconnect() }
32.961538
109
0.705368
bfa9770d4b4ed2afe4195cfd33403cea316c2b76
503
// // ViewController.swift // xxHash-Swift // // Created by Daisuke T on 2019/02/14. // Copyright © 2019 xxHash-Swift. All rights reserved. // import UIKit import xxHash_Swift class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() Common.oneshotXXH32() Common.oneshotXXH64() Common.oneshotXXH3_64() Common.oneshotXXH3_128() Common.streamingXXH32() Common.streamingXXH64() } }
17.964286
55
0.632207