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
|
---|---|---|---|---|---|
bbcb825db0981a55dd63b74e9b6142bf1be6fb79 | 820 | //
// Copyright © 2019 MBition GmbH. All rights reserved.
//
import XCTest
@testable import Example
class ExampleTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.451613 | 111 | 0.65122 |
7a90fbcbd6e002ec9bd27caa2d919fd973eeb2bc | 3,148 | //
// AlertDialogViewController.swift
// tokenization
//
// Created by AMR on 7/4/18.
// Copyright © 2018 Paysky. All rights reserved.
//
import UIKit
class AlertDialogViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var messageTextView: UILabel!
@IBOutlet weak var okButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var MainImage: UIImageView!
var titleText = ""
var messageText = ""
var okText = "OK"
var cancelText = ""
var imageMainParamter = #imageLiteral(resourceName: "TransactionDeclined")
var showImage = true
var okHandler: (()->Void)? = nil
var cancelHandler: (()->Void)? = nil
@IBOutlet weak var HeaderView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// messageTextView.setTextViewStyle("", title: messageText, textColor: Colors.fontColor, font: Global.setFont(15), borderWidth: 0, borderColor: .clear, backgroundColor: .clear, cornerRadius: 0, placeholderColor: .clear)
titleLabel.text = titleText
titleLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
titleLabel.numberOfLines = 0
titleLabel.font = Global.setFont(15)
titleLabel.textColor = .white
MainImage.image = imageMainParamter
messageTextView.textColor = PaySkySDKColor.fontColor
messageTextView.text = messageText
messageTextView.font = Global.setFont(15, isLight: true)
HeaderView.backgroundColor = PaySkySDKColor.NavColor
// messageTextView.scrollRangeToVisible(NSMakeRange(0, 0))
// messageTextView.setContentOffset(CGPoint.zero, animated: false)
okButton.setButtonStyle(okText, backgroundColor: PaySkySDKColor.mainBtnColor, cornerRadius: 5, borderWidth: 0, borderColor: .clear, font: Global.setFont(15), textColor: .white)
if cancelText != "" {
cancelButton.setButtonStyle(cancelText, backgroundColor: PaySkySDKColor.secondColorBtn, cornerRadius: 5, borderWidth: 0, borderColor: .clear, font: Global.setFont(15), textColor: .white)
}else{
cancelButton.isHidden = true
}
if showImage {
MainImage.isHidden = false
}else{
MainImage.isHidden = true
}
self.view.layer.cornerRadius = PaySkySDKColor.RaduisNumber
// Do any additional setup after loading the view.
}
@IBAction func okAction(_ sender: Any) {
if okHandler == nil {
self.dismiss(animated: true, completion: nil)
} else {
okHandler!()
}
}
@IBAction func cancelAction(_ sender: Any) {
if cancelHandler == nil {
self.dismiss(animated: true, completion: nil)
} else {
cancelHandler!()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 30.269231 | 234 | 0.628971 |
26da5901fb137aad41c57bb3503bc182e406e0c9 | 9,313 | //
// LearningPlanGoalsViewController.swift
// Clark
//
// Created by Vladislav Zagorodnyuk on 9/7/17.
// Copyright © 2017 Clark. All rights reserved.
//
import Popover
import EZSwiftExtensions
enum LearningPlanGoalsCells {
case progress
}
class LearningPlanGoalsViewController: UIViewController, HelpNavigationProtocol, CreationViewControllerProtocol {
/// Student
var student: Student!
/// Title
var navigationTitle: String
/// On next
var nextButtonSuccess: ((String)->())?
/// Params
var progress: String = ""
/// Popover view
lazy var popover: Popover? = self.generatePopover()
/// Progress view
lazy var progressView: UIView = self.generateProgressView()
/// Help copy
var helpCopy: String? {
return "These notes will be shared with students and parents"
}
/// Datasource
var datasource: [LearningPlanGoalsCells] = [.progress]
/// Next Done button
lazy var nextButton: UIButton? = self.generateSkipButton()
/// Help button
lazy var helpButton: UIButton? = self.generateHelpButton()
/// Number of steps
var currentStep: Int = 1
var numberOfSteps: Int = 4
/// First cell - for keyboard
var firstInputCell: FormInputCell? = nil
/// Collection view
lazy var collectionView: UICollectionView = {
/// Layout
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
/// Collection view
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.showsVerticalScrollIndicator = false
collectionView.alwaysBounceVertical = true
collectionView.backgroundColor = UIColor.white
/// Register cells
collectionView.register(FormInputCell.self, forCellWithReuseIdentifier: "\(FormInputCell.self)")
collectionView.register(ClientsTitleHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "\(ClientsTitleHeader.self)")
return collectionView
}()
/// Right button
lazy var rightButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(onCancelButton(_:)))
button.tintColor = UIColor.trinidad
button.setTitleTextAttributes([NSFontAttributeName: UIFont.defaultFont(style: .medium, size: 14)], for: .normal)
return button
}()
// MARK: - Initialization
required init(currentStep: Int, numberOfSteps: Int, title: String) {
self.navigationTitle = title
self.currentStep = currentStep
self.numberOfSteps = numberOfSteps
super.init(nibName: nil, bundle: nil)
/// Layout progress view
layoutProgressView(step: currentStep, total: numberOfSteps)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Controller lifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
/// Controller setup
controllerSetup()
/// Track
Analytics.screen(screenId: .s26)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
/// Right button
navigationItem.rightBarButtonItem = rightButton
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
/// Next button action
nextButton?.addTarget(self, action: #selector(onNextButton(_:)), for: .touchUpInside)
/// Custom init
customInit()
/// Focusing first name
ez.runThisAfterDelay(seconds: 1) {
self.firstInputCell?.formInput.becomeFirstResponder()
}
}
func customInit() {
/// Collection setup
view.addSubview(collectionView)
collectionView.delegate = self
collectionView.dataSource = self
/// Progress view layout
layoutProgressView(step: currentStep, total: numberOfSteps)
/// Buttons setup
nextLayout()
nextButton?.heroID = "nextButton"
nextButton?.heroModifiers = [.cascade()]
helpLayout()
helpButton?.heroID = "helpButton"
helpButton?.heroModifiers = [.cascade()]
helpButton?.addTarget(self, action: #selector(onHelpButton(_:)), for: .touchUpInside)
/// Collectoin layout
collectionView.snp.updateConstraints { maker in
maker.top.equalTo(self.view)
maker.left.equalTo(self.view)
maker.right.equalTo(self.view)
maker.bottom.equalTo(self.view)
}
}
// MARK: - Actions
func onNextButton(_ sender: UIButton) {
nextButtonSuccess?(progress)
}
func onHelpButton(_ sender: UIButton) {
showPopoveView()
}
/// On next button callback
func onNextButtonCallback(_ completion: @escaping ((String)->())) {
nextButtonSuccess = completion
}
// MARK: - Actions
func onCancelButton(_ sender: Any) {
/// Dismiss
navigationController?.heroModalAnimationType = .cover(direction: .down)
navigationController?.hero_dismissViewController()
}
}
// MARK: - CollectionView Datasource
extension LearningPlanGoalsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath)-> CGSize {
return CGSize(width: collectionView.frame.width, height: 250)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 120)
}
/// Header
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
/// Header setup
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "\(ClientsTitleHeader.self)", for: indexPath) as! ClientsTitleHeader
let paragraph = NSMutableParagraphStyle()
paragraph.lineSpacing = 10
headerView.titleLabel.attributedText = NSAttributedString(string: "What are \(student.firstName ?? "")’s goals?", attributes: [NSParagraphStyleAttributeName: paragraph])
return headerView
default:
print("ignore")
return UICollectionReusableView(frame: .zero)
}
}
}
// MARK: - CollectionView Datasource
extension LearningPlanGoalsViewController: UICollectionViewDataSource {
/// Number of sections
func numberOfSections(in collectionView: UICollectionView)-> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)-> Int {
return datasource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)-> UICollectionViewCell {
let inputCell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(FormInputCell.self)", for: indexPath) as! FormInputCell
inputCell.delegate = self
inputCell.titleText = title
inputCell.indexPath = indexPath
inputCell.placeholder = "Describe what you, the student, and the parent want to accomplish. Be as specific as you can."
inputCell.dividerView.isHidden = true
firstInputCell = inputCell
return inputCell
}
}
// MARK: - Text Input delegate
extension LearningPlanGoalsViewController: FormInputCellDelegate {
/// Return button pressed
func textFieldHitReturn(_ textVies: UITextView, indexPath: IndexPath){
onNextButton(nextButton!)
}
func textFieldDidChange(_ textView: UITextView, indexPath: IndexPath) {
progress = textView.text
if textView.text.length > 0 {
nextButton?.setAttributedTitle(NSAttributedString(string: "Next", attributes: [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.defaultFont(style: .medium, size: 19)]), for: .normal)
return
}
nextButton?.setAttributedTitle(NSAttributedString(string: "Skip", attributes: [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.defaultFont(style: .medium, size: 19)]), for: .normal)
}
}
| 33.142349 | 220 | 0.645764 |
9ba2cdbb6d510a9603563bd2e8debdd5cf191ff7 | 3,607 | //
// NearEarthObjects.swift
// NasaExplorer-iOS
//
// Created by Claudio Miraka on 1/27/22.
//
import Foundation
struct NearEarthObjects : Decodable {
var links: Links
var elementCount: Int
var nearEarthObjects: [String: [NearEarthObject]]
enum CodingKeys: String, CodingKey {
case elementCount = "element_count"
case nearEarthObjects = "near_earth_objects"
case links
}
}
/////////////////////////////////////////////////////
struct NearEarthObject : Decodable , Hashable , Identifiable{
var links: Links
var id: String
var name: String
var neoReferenceId: String
var nasaJplUrl: String
var absoluteMagnitudeH: Double
var isPotentiallyHazardousAsteroid: Bool
var estimatedDiameter: EstimatedDiameter
var isSentryObject: Bool
var closeApproachData: [CloseApproach]
enum CodingKeys: String, CodingKey {
case links, id, name
case neoReferenceId = "neo_reference_id"
case nasaJplUrl = "nasa_jpl_url"
case absoluteMagnitudeH = "absolute_magnitude_h"
case isPotentiallyHazardousAsteroid = "is_potentially_hazardous_asteroid"
case estimatedDiameter = "estimated_diameter"
case isSentryObject = "is_sentry_object"
case closeApproachData = "close_approach_data"
}
func getInfoString() -> String{
return "id " + self.id + "\n" + "name " + self.name + "\n"
}
static func == (lhs: NearEarthObject, rhs: NearEarthObject) -> Bool {
return lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
/////////////////////////////////////////////////////
struct Links : Decodable {
var next: String?
var prev: String?
var `self`: String
}
/////////////////////////////////////////////////////
struct EstimatedDiameter : Decodable {
var kilometers: EstimatedDiameterMinMax
var meters: EstimatedDiameterMinMax
var miles: EstimatedDiameterMinMax
var feet: EstimatedDiameterMinMax
}
struct EstimatedDiameterMinMax : Decodable {
var min: Double
var max: Double
enum CodingKeys: String, CodingKey {
case min = "estimated_diameter_min"
case max = "estimated_diameter_max"
}
}
/////////////////////////////////////////////////////
struct CloseApproach : Decodable{
var closeApproachDate: String
var closeApproachDateFull: String
// @SerializedName("epoch_date_close_approach")
// var epochDateCloseApproach: String // where is BigInteger swift?
var relativeVelocity: Velocity
var missDistance: Distance
var orbitingBody: String
enum CodingKeys: String, CodingKey {
case closeApproachDate = "close_approach_date"
case closeApproachDateFull = "close_approach_date_full"
case relativeVelocity = "relative_velocity"
case missDistance = "miss_distance"
case orbitingBody = "orbiting_body"
}
}
struct Velocity :Decodable {
var kilometersPerSecond: String
var kilometersPerHour: String
var milesPerHour: String
enum CodingKeys: String, CodingKey {
case kilometersPerSecond = "kilometers_per_second"
case kilometersPerHour = "kilometers_per_hour"
case milesPerHour = "miles_per_hour"
}
}
struct Distance : Decodable {
var astronomical: String
var lunar: String
var kilometers: String
var miles: String
}
| 22.974522 | 81 | 0.61547 |
e61c58cd766c5f40e877e4a807ad18f17d97f6f2 | 869 | //
// PopoverViewController.swift
// Popover
//
// Created by mefilt on 28/01/2019.
// Copyright © 2019 Mefilt. All rights reserved.
//
import Foundation
import UIKit
protocol ModalPresentationAnimatorContext {
func contentHeight(for size: CGSize) -> CGFloat
func appearingContentHeight(for size: CGSize) -> CGFloat
func disappearingContentHeight(for size: CGSize) -> CGFloat
func hideBoundaries(for size: CGSize) -> CGRect
}
protocol ModalPresentationAnimatorSimpleContext: ModalPresentationAnimatorContext {}
extension ModalPresentationAnimatorSimpleContext {
func appearingContentHeight(for size: CGSize) -> CGFloat {
let contentHeight = self.contentHeight(for: size)
return size.height - contentHeight
}
func disappearingContentHeight(for size: CGSize) -> CGFloat {
return size.height
}
}
| 24.138889 | 84 | 0.730725 |
f73ad870b8847dcc1d86cd4905c93bb9c19966d7 | 10,048 | //
// Copyright (c) 2020 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import Adyen
import AdyenCard
import AdyenDropIn
import UIKit
internal final class ComponentsViewController: UIViewController {
private lazy var componentsView = ComponentsView()
private let payment = Payment(amount: Configuration.amount, countryCode: Configuration.countryCode)
private let environment: Environment = .test
private var paymentMethods: PaymentMethods?
private var currentComponent: PresentableComponent?
private var paymentInProgress: Bool = false
// MARK: - View
internal override func loadView() {
view = componentsView
}
internal override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Components"
componentsView.items = [
[
ComponentsItem(title: "Drop In", selectionHandler: presentDropInComponent)
],
[
ComponentsItem(title: "Card", selectionHandler: presentCardComponent),
ComponentsItem(title: "iDEAL", selectionHandler: presentIdealComponent),
ComponentsItem(title: "SEPA Direct Debit", selectionHandler: presentSEPADirectDebitComponent)
]
]
requestPaymentMethods()
}
// MARK: - Components
private lazy var actionComponent: DropInActionComponent = {
let handler = DropInActionComponent()
handler.presenterViewController = self
handler.redirectComponentStyle = dropInComponentStyle.redirectComponent
handler.delegate = self
return handler
}()
private func present(_ component: PresentableComponent) {
component.environment = environment
component.payment = payment
if let paymentComponent = component as? PaymentComponent {
paymentComponent.delegate = self
}
if let actionComponent = component as? ActionComponent {
actionComponent.delegate = self
}
currentComponent = component
guard component.requiresModalPresentation else {
return present(component.viewController, animated: true)
}
let navigation = UINavigationController(rootViewController: component.viewController)
component.viewController.navigationItem.leftBarButtonItem = .init(barButtonSystemItem: .cancel,
target: self,
action: #selector(cancelDidPress))
present(navigation, animated: true)
}
@objc private func cancelDidPress() {
guard let paymentComponent = self.currentComponent as? PaymentComponent else {
self.dismiss(animated: true, completion: nil)
return
}
paymentComponent.delegate?.didFail(with: ComponentError.cancelled, from: paymentComponent)
}
// MARK: - DropIn Component
private lazy var dropInComponentStyle: DropInComponent.Style = DropInComponent.Style()
private func presentDropInComponent() {
guard let paymentMethods = paymentMethods else { return }
let configuration = DropInComponent.PaymentMethodsConfiguration()
configuration.card.publicKey = Configuration.cardPublicKey
configuration.applePay.merchantIdentifier = Configuration.applePayMerchantIdentifier
configuration.applePay.summaryItems = Configuration.applePaySummaryItems
configuration.localizationParameters = nil
let component = DropInComponent(paymentMethods: paymentMethods,
paymentMethodsConfiguration: configuration,
style: dropInComponentStyle,
title: Configuration.appName)
component.delegate = self
present(component)
}
private func presentCardComponent() {
guard let paymentMethod = paymentMethods?.paymentMethod(ofType: CardPaymentMethod.self) else { return }
let component = CardComponent(paymentMethod: paymentMethod,
publicKey: Configuration.cardPublicKey,
style: dropInComponentStyle.formComponent)
present(component)
}
private func presentIdealComponent() {
guard let paymentMethod = paymentMethods?.paymentMethod(ofType: IssuerListPaymentMethod.self) else { return }
let component = IdealComponent(paymentMethod: paymentMethod,
style: dropInComponentStyle.listComponent)
present(component)
}
private func presentSEPADirectDebitComponent() {
guard let paymentMethod = paymentMethods?.paymentMethod(ofType: SEPADirectDebitPaymentMethod.self) else { return }
let component = SEPADirectDebitComponent(paymentMethod: paymentMethod,
style: dropInComponentStyle.formComponent)
component.delegate = self
present(component)
}
// MARK: - Networking
private lazy var apiClient = RetryAPIClient(apiClient: APIClient(environment: Configuration.environment))
private func requestPaymentMethods() {
let request = PaymentMethodsRequest()
apiClient.perform(request) { result in
switch result {
case let .success(response):
self.paymentMethods = response.paymentMethods
case let .failure(error):
self.presentAlert(with: error, retryHandler: self.requestPaymentMethods)
}
}
}
private func performPayment(with data: PaymentComponentData) {
let request = PaymentsRequest(data: data)
apiClient.perform(request, completionHandler: paymentResponseHandler)
}
private func performPaymentDetails(with data: ActionComponentData) {
let request = PaymentDetailsRequest(details: data.details, paymentData: data.paymentData)
apiClient.perform(request, completionHandler: paymentResponseHandler)
}
private func paymentResponseHandler(result: Result<PaymentsResponse, Error>) {
switch result {
case let .success(response):
if let action = response.action {
handle(action)
} else {
finish(with: response.resultCode)
}
case let .failure(error):
currentComponent?.stopLoading(withSuccess: false) { [weak self] in
self?.presentAlert(with: error)
}
}
}
private func handle(_ action: Action) {
guard paymentInProgress else { return }
if let dropInComponent = currentComponent as? DropInComponent {
return dropInComponent.handle(action)
}
actionComponent.perform(action)
}
private func finish(with resultCode: PaymentsResponse.ResultCode) {
let success = resultCode == .authorised || resultCode == .received || resultCode == .pending
currentComponent?.stopLoading(withSuccess: success) { [weak self] in
self?.dismiss(animated: true) {
self?.presentAlert(withTitle: resultCode.rawValue)
}
}
}
private func finish(with error: Error) {
let isCancelled = ((error as? ComponentError) == .cancelled)
dismiss(animated: true) {
if !isCancelled {
self.presentAlert(with: error)
}
}
}
private func presentAlert(with error: Error, retryHandler: (() -> Void)? = nil) {
let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
if let retryHandler = retryHandler {
alertController.addAction(UIAlertAction(title: "Retry", style: .default, handler: { _ in
retryHandler()
}))
} else {
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
}
adyen.topPresenter.present(alertController, animated: true)
}
private func presentAlert(withTitle title: String) {
let alertController = UIAlertController(title: title, message: nil, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
adyen.topPresenter.present(alertController, animated: true)
}
}
extension ComponentsViewController: DropInComponentDelegate {
internal func didSubmit(_ data: PaymentComponentData, from component: DropInComponent) {
performPayment(with: data)
paymentInProgress = true
}
internal func didProvide(_ data: ActionComponentData, from component: DropInComponent) {
performPaymentDetails(with: data)
}
internal func didFail(with error: Error, from component: DropInComponent) {
paymentInProgress = false
finish(with: error)
}
}
extension ComponentsViewController: PaymentComponentDelegate {
internal func didSubmit(_ data: PaymentComponentData, from component: PaymentComponent) {
paymentInProgress = true
performPayment(with: data)
}
internal func didFail(with error: Error, from component: PaymentComponent) {
paymentInProgress = false
finish(with: error)
}
}
extension ComponentsViewController: ActionComponentDelegate {
internal func didFail(with error: Error, from component: ActionComponent) {
paymentInProgress = false
finish(with: error)
}
internal func didProvide(_ data: ActionComponentData, from component: ActionComponent) {
performPaymentDetails(with: data)
}
}
| 37.774436 | 124 | 0.637341 |
6731c2cb7132e1e24b49a35b1c4bf1767d16c8dd | 1,789 | //
// UIView+LayerAction.swift
// UIAnimationToolbox
//
// Created by WeZZard on 9/14/16.
//
//
import UIKit
import ObjectiveC
//MARK: - Swizzle UIView's CALayerDelegate
internal typealias _CALayerDelegateActionForLayerForKey =
@convention(c) (UIView, Selector, CALayer, String)
-> CAAction?
internal var _originalCALayerDelegateActionForLayerForKey: _CALayerDelegateActionForLayerForKey {
return _originalActionForLayerForKey
}
private var _originalActionForLayerForKey : _CALayerDelegateActionForLayerForKey!
private let _actionForLayerForKey: _CALayerDelegateActionForLayerForKey = {
(aSelf, aSelector, layer, event) -> CAAction? in
if let context = UIView._currentAnimationContext {
if let originalAction = _originalActionForLayerForKey(
aSelf,
aSelector,
layer,
event
)
{
if let timing = context.currentAnimationTiming {
timing._shiftAction(originalAction)
}
return originalAction
} else {
return nil
}
} else {
return _originalActionForLayerForKey(aSelf, aSelector, layer, event)
}
}
internal func _swizzleCALayerDelegateActionForLayerForKey() {
struct Token {
static let once: Bool = {
let sel = #selector(CALayerDelegate.action(for:forKey:))
let method = class_getInstanceMethod(UIView.self, sel)!
let impl = method_getImplementation(method)
_originalActionForLayerForKey = unsafeBitCast(impl, to: _CALayerDelegateActionForLayerForKey.self)
method_setImplementation(method, unsafeBitCast(_actionForLayerForKey, to: IMP.self))
return true
}()
}
_ = Token.once
}
| 29.327869 | 110 | 0.66853 |
72e05cc79fb17b4b28de2ce13f63b3d3132fa1ba | 4,570 | //
// CGColorSpace.swift
//
// The MIT License
// Copyright (c) 2015 - 2021 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if canImport(CoreGraphics)
private let ColorSpaceCacheCGColorSpaceKey = "ColorSpaceCacheCGColorSpaceKey"
extension ColorSpace {
private var _cgColorSpace: CGColorSpace? {
switch AnyColorSpace(self) {
case AnyColorSpace.sRGB: return CGColorSpace(name: CGColorSpace.sRGB)
case AnyColorSpace.genericGamma22Gray: return CGColorSpace(name: CGColorSpace.genericGrayGamma2_2)
case AnyColorSpace.displayP3: return CGColorSpace(name: CGColorSpace.displayP3)
case AnyColorSpace.genericGamma22Gray.linearTone: return CGColorSpace(name: CGColorSpace.linearGray)
case AnyColorSpace.sRGB.linearTone: return CGColorSpace(name: CGColorSpace.linearSRGB)
default: break
}
if #available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) {
switch AnyColorSpace(self) {
case AnyColorSpace.genericXYZ: return CGColorSpace(name: CGColorSpace.genericXYZ)
default: break
}
}
if self is ColorSpace<LabColorModel> {
let white = self.referenceWhite
let black = self.referenceBlack
return CGColorSpace(
labWhitePoint: [CGFloat(white.x), CGFloat(white.y), CGFloat(white.z)],
blackPoint: [CGFloat(black.x), CGFloat(black.y), CGFloat(black.z)],
range: [-128, 128, -128, 128]
)
}
return nil
}
public var cgColorSpace: CGColorSpace? {
if let colorSpace = self._cgColorSpace {
return colorSpace
}
return self.cache.load(for: ColorSpaceCacheCGColorSpaceKey) {
return self.iccData.flatMap { CGColorSpace(iccData: $0 as CFData) }
}
}
}
extension AnyColorSpace {
private static func _init(cgColorSpace: CGColorSpace) -> AnyColorSpace? {
switch cgColorSpace.name {
case CGColorSpace.genericGrayGamma2_2: return AnyColorSpace.genericGamma22Gray
case CGColorSpace.sRGB: return AnyColorSpace.sRGB
case CGColorSpace.displayP3: return AnyColorSpace.displayP3
case CGColorSpace.linearGray: return AnyColorSpace.genericGamma22Gray.linearTone
case CGColorSpace.linearSRGB: return AnyColorSpace.sRGB.linearTone
default: break
}
if #available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) {
switch cgColorSpace.name {
case CGColorSpace.genericXYZ: return AnyColorSpace.genericXYZ
default: break
}
}
return nil
}
public init?(cgColorSpace: CGColorSpace) {
if let colorSpace = AnyColorSpace._init(cgColorSpace: cgColorSpace) {
self = colorSpace
return
}
guard let iccData = cgColorSpace.copyICCData() as Data? else { return nil }
try? self.init(iccData: iccData)
}
}
protocol CGColorSpaceConvertibleProtocol {
var cgColorSpace: CGColorSpace? { get }
}
extension ColorSpace: CGColorSpaceConvertibleProtocol {
}
extension AnyColorSpace {
public var cgColorSpace: CGColorSpace? {
if let base = _base as? CGColorSpaceConvertibleProtocol {
return base.cgColorSpace
}
return nil
}
}
#endif
| 34.885496 | 108 | 0.662801 |
e669100718fb20b98085eddd723b239bbb3413dd | 575 | //
// UsernameViewModel+PasswordViewModel.swift
// Example
//
// Created by Julio Miguel Alorro on 3/27/19.
// Copyright © 2019 Feil, Feil, & Feil GmbH. All rights reserved.
//
import Cyanic
public final class UsernameViewModel: ExampleViewModel<UsernameState> {
public func setUserName(_ userName: String) {
self.setState(with: { $0.userName = userName })
}
}
public final class PasswordViewModel: ExampleViewModel<PasswordState> {
public func setPassword(_ password: String) {
self.setState(with: { $0.password = password })
}
}
| 22.115385 | 71 | 0.693913 |
dbeacf2b78be06139a9b05a05c6d47d47188adc5 | 594 | //
// AssetChartHeaderView.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 5/8/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
class AssetChartHeaderView: UITableViewHeaderFooterView {
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var buttonChangePeriod: UIButton!
override var reuseIdentifier: String? {
return AssetChartHeaderView.identifier()
}
class func identifier() -> String {
return "AssetChartHeaderView"
}
class func viewHeight() -> CGFloat {
return 34
}
}
| 20.482759 | 57 | 0.666667 |
e4b0a48187957ccc6bc35a2649a549e26f959549 | 2,285 | import FirstPartyMocks
import Foundation
import Tagged
public struct FetchTodaysDailyChallengeResponse: Codable, Equatable {
public var dailyChallenge: DailyChallenge
public var yourResult: DailyChallengeResult
public init(
dailyChallenge: DailyChallenge,
yourResult: DailyChallengeResult
) {
self.dailyChallenge = dailyChallenge
self.yourResult = yourResult
}
public struct DailyChallenge: Codable, Equatable {
public var endsAt: Date
public var gameMode: GameMode
public var id: SharedModels.DailyChallenge.Id
public var language: Language
public init(
endsAt: Date,
gameMode: GameMode,
id: SharedModels.DailyChallenge.Id,
language: Language
) {
self.endsAt = endsAt
self.gameMode = gameMode
self.id = id
self.language = language
}
}
}
extension Array where Element == FetchTodaysDailyChallengeResponse {
public var timed: FetchTodaysDailyChallengeResponse? {
self.first(where: { $0.dailyChallenge.gameMode == .timed })
}
public var unlimited: FetchTodaysDailyChallengeResponse? {
self.first(where: { $0.dailyChallenge.gameMode == .unlimited })
}
public var numberOfPlayers: Int {
self.reduce(into: 0) {
$0 += $1.yourResult.outOf
}
}
}
extension FetchTodaysDailyChallengeResponse {
static let started = Self(
dailyChallenge: .init(
endsAt: .init(timeIntervalSinceNow: 1_234_567_890),
gameMode: .unlimited,
id: .init(rawValue: .deadbeef),
language: .en
),
yourResult: .init(
outOf: 1_000,
rank: nil,
score: nil,
started: true
)
)
static let played = Self(
dailyChallenge: .init(
endsAt: .init(timeIntervalSinceNow: 1_234_567_890),
gameMode: .unlimited,
id: .init(rawValue: .deadbeef),
language: .en
),
yourResult: .init(
outOf: 1_000,
rank: 20,
score: 3_000,
started: true
)
)
static let notStarted = Self(
dailyChallenge: .init(
endsAt: .init(timeIntervalSinceNow: 1_234_567_890),
gameMode: .unlimited,
id: .init(rawValue: .deadbeef),
language: .en
),
yourResult: .init(
outOf: 1_000,
rank: nil,
score: nil,
started: false
)
)
}
| 23.080808 | 69 | 0.654705 |
ab7de9f7eb5ec4cbc0ae21691be630bc0060a453 | 1,376 | //
// LabeledGroup.swift
// Clouds
//
// Created by Lukas Romsicki on 2020-03-15.
// Copyright © 2020 Lukas Romsicki. All rights reserved.
//
import SwiftUI
struct LabeledGroup<Content: View>: View {
var label: String?
var content: () -> Content
@inlinable init(label: String? = nil, @ViewBuilder content: @escaping () -> Content) {
self.label = label
self.content = content
}
var body: some View {
Group {
if label == nil {
groupedContent
} else {
VStack(alignment: .leading, spacing: 10.0) {
Text(label!)
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(Color.white.opacity(0.6))
groupedContent
}
}
}
}
private var groupedContent: some View {
Group {
content()
.padding(.horizontal, 16)
.padding(.vertical, 14)
}
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.background(Color.white.opacity(0.07))
.cornerRadius(14)
}
}
struct LabeledGroup_Previews: PreviewProvider {
static var previews: some View {
LabeledGroup(label: "Section") {
Text("Content")
}
}
}
| 24.571429 | 90 | 0.515262 |
ed9de688c77b75a19a5559eacab2522da880595a | 1,036 | //
// LogControllerTests.swift
// EmonCMSiOSTests
//
// Created by Matt Galloway on 23/01/2019.
// Copyright © 2019 Matt Galloway. All rights reserved.
//
@testable import EmonCMSiOS
import Foundation
import Nimble
import Quick
class LogControllerTests: QuickSpec {
override func spec() {
beforeEach {}
describe("logController") {
it("should return log files") {
let controller = LogController.shared
let thingToLog = UUID().uuidString
AppLog.info(thingToLog)
waitUntil { done in
controller.flushFile {
done()
}
}
let logFiles = controller.logFiles
expect(logFiles.count).to(beGreaterThan(0))
if
let logFile = logFiles.first,
let data = try? Data(contentsOf: logFile),
let string = String(data: data, encoding: .utf8)
{
expect(string.contains(thingToLog)).to(equal(true))
} else {
fail("Failed to get log file data")
}
}
}
}
}
| 22.042553 | 61 | 0.596525 |
69e8985a7e82f58c7e08876bfc7c65e47e0e3e11 | 2,130 | //
// MotionAnimationView.swift
// Africa
//
// Created by Alexander Rojas Benavides on 9/29/21.
//
import SwiftUI
struct MotionAnimationView: View {
//MARK: - Properties
@State private var randomCircle = Int.random(in: 12...16)
@State private var isAnimating: Bool = false
//MARK: - Functions
// 1. Random Cordinate
func randomCoordinates(max: CGFloat) -> CGFloat {
return CGFloat.random(in: 0...max)
}
// 2. Random Size
func randomSize() -> CGFloat {
return CGFloat(Int.random(in: 10...300))
}
// 3. Random Scale
func randomScale() -> CGFloat {
return CGFloat(Double.random(in: 0.1...2.0))
}
// 4. Random Speed
func randomSpeed() -> Double {
return Double.random(in: 0.025...1.0)
}
// 5. Random Delay
func randomDelay() -> Double {
return Double.random(in: 0...2)
}
var body: some View {
GeometryReader { geometry in
ZStack {
ForEach(0...randomCircle, id:\.self) { item in
Circle()
.foregroundColor(Color.gray)
.opacity(0.15)
.frame(width: randomSize(), height: randomSize(), alignment: .center)
.scaleEffect(isAnimating ? randomScale(): 1)
.position(x: randomCoordinates(max: geometry.size.width),
y: randomCoordinates(max: geometry.size.height))
.animation(Animation.interpolatingSpring(stiffness: 05, damping: 0.5)
.repeatForever()
.speed(randomSpeed())
.delay(randomDelay()))
.onAppear(perform: {
isAnimating = true
})
}//: Loop
}//: ZStack
.drawingGroup()
}//:Geometry Reader
}
}
struct MotionAnimationView_Previews: PreviewProvider {
static var previews: some View {
MotionAnimationView()
}
}
| 32.272727 | 93 | 0.507981 |
8f0d132e8f8574c73fdca16bea68e8a4b75d2bd6 | 774 | //
// Copyright 2020 Swiftkube Project
//
// 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.
//
///
/// Generated by Swiftkube:ModelGen
/// Kubernetes v1.20.9
///
import Foundation
///
/// Namespace for `coordination.v1`
///
public extension coordination {
enum v1 {}
}
| 25.8 | 75 | 0.72739 |
f5652d3bb14632f5c993b51a0193efdb6e14ce0d | 4,426 | //
// CardBrand+default.swift
// VGSCheckoutSDK
//
// Created by Dima on 10.07.2020.
// Copyright © 2020 VGS. All rights reserved.
//
import Foundation
/// Default CardBrand settings
extension VGSCheckoutPaymentCards.CardBrand {
/// Returns regex for specific card brand detection
var defaultRegex: String {
switch self {
case .amex:
return "^3[47]\\d*$"
case .dinersClub:
return "^3(?:[689]|(?:0[059]+))\\d*$"
case .discover:
return "^(6011|65|64[4-9]|622)\\d*$"
case .unionpay:
return "^62\\d*$"
case .jcb:
return "^35\\d*$"
case .mastercard:
return "^(5[1-5]|677189)\\d*$|^(222[1-9]|2[3-6]\\d{2,}|27[0-1]\\d|2720)([0-9]{2,})\\d*$"
case .visaElectron:
return "^4(026|17500|405|508|844|91[37])\\d*$"
case .visa:
return "^4\\d*$"
case .maestro:
return "^(5018|5020|5038|56|57|58|6304|6390[0-9]{2,}|67[0-9]{4,})\\d*$"
case .forbrugsforeningen:
return "^600\\d*$"
case .dankort:
return "^5019\\d*$"
case .elo:
return "^(4011(78|79)|43(1274|8935)|45(1416|7393|763(1|2))|50(4175|6699|67[0-7][0-9]|9000)|627780|63(6297|6368)|650(03([^4])|04([0-9])|05(0|1)|4(0[5-9]|3[0-9]|8[5-9]|9[0-9])|5([0-2][0-9]|3[0-8])|9([2-6][0-9]|7[0-8])|541|700|720|901)|651652|655000|655021)\\d*$"
case .hipercard:
return "^(384100|384140|384160|606282|637095|637568|60(?!11))\\d*$"
case .unknown:
return "^\\d*$"
// case .custom(brandName: _):
// return ""
}
}
var defaultCardLengths: [Int] {
switch self {
case .amex:
return [15]
case .dinersClub:
return [14, 16]
case .discover:
return [16]
case .unionpay:
return [16, 17, 18, 19]
case .jcb:
return [16, 17, 18, 19]
case .mastercard:
return [16]
case .visaElectron:
return [16]
case .visa:
return [13, 16, 19]
case .maestro:
return [12, 13, 14, 15, 16, 17, 18, 19]
case .elo:
return [16]
case .forbrugsforeningen:
return [16]
case .dankort:
return [16]
case .hipercard:
return [14, 15, 16, 17, 18, 19]
case .unknown:
return [16, 17, 18, 19]
// case .custom(brandName: _):
// return []
}
}
var defaultCVCLengths: [Int] {
switch self {
case .amex:
return [4]
case .unknown:
return [3, 4]
default:
return [3]
}
}
/// Specifies CVC format pattern.
public var cvcFormatPattern: String {
var maxLength = 0
if let cardBrand = VGSCheckoutPaymentCards.availableCardBrands.first(where: { $0.brand == self }) {
maxLength = cardBrand.cvcLengths.max() ?? 0
} else {
maxLength = VGSCheckoutPaymentCards.unknown.cvcLengths.max() ?? 0
}
return String(repeating: "#", count: maxLength)
}
var defaultFormatPattern: String {
switch self {
case .amex:
return "#### ###### #####"
case .dinersClub:
return "#### ###### ######"
default:
return "#### #### #### #### ###"
}
}
var defaultName: String {
switch self {
case .amex:
return "American Express"
case .visa:
return "Visa"
case .visaElectron:
return "Visa Electron"
case .mastercard:
return "Mastercard"
case .discover:
return "Discover"
case .dinersClub:
return "Diners Club"
case .unionpay:
return "UnionPay"
case .jcb:
return "JCB"
case .maestro:
return "Maestro"
case .elo:
return "ELO"
case .forbrugsforeningen:
return "Forbrugsforeningen"
case .dankort:
return "Dankort"
case .hipercard:
return "HiperCard"
case .unknown:
return "Unknown"
// case .custom(brandName: _):
// return ""
}
}
var defaultCheckSumAlgorithm: VGSCheckoutCheckSumAlgorithmType? {
switch self {
case .unionpay:
return nil
default:
return .luhn
}
}
}
| 27.320988 | 268 | 0.496159 |
11a0391cf346e9b04f7ee7b179579ea915ccca69 | 10,695 | // Sources/CodableXPC/XPCKeyedEncodingContainer.swift - KeyedEncodingContainer
// implementation for XPC
//
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// -----------------------------------------------------------------------------
//
// This file contains a KeyedEncodingContainer implementation for xpc_object_t.
// This includes a specialization of the XPCEncoder for handling the super
// class case, as we don't know what container type is going to be needed to
// handle it.
//
// -----------------------------------------------------------------------------//
import XPC
public struct XPCKeyedEncodingContainer<K: CodingKey>: KeyedEncodingContainerProtocol {
public typealias Key = K
// MARK: - Properties
/// A reference to the encoder we're writing to.
private let encoder: XPCEncoder
private let underlyingMesage: xpc_object_t
/// The path of coding keys taken to get to this point in encoding.
public var codingPath: [CodingKey] {
get {
return self.encoder.codingPath
}
}
// MARK: - Initialization
/// Initializes `self` with the given references.
init(referencing encoder: XPCEncoder, wrapping dictionary: xpc_object_t) throws {
self.encoder = encoder
guard xpc_get_type(dictionary) == XPC_TYPE_DICTIONARY else {
throw XPCEncodingHelpers.makeEncodingError(dictionary, encoder.codingPath, "Internal error")
}
self.underlyingMesage = dictionary
}
// MARK: - KeyedEncodingContainerProtocol Methods
public mutating func encodeNil(forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeNil())})
}
public mutating func encode(_ value: Bool, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_bool(self.underlyingMesage, $0, value) })
}
public mutating func encode(_ value: Int, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeSignedInteger(value)) })
}
public mutating func encode(_ value: Int8, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeSignedInteger(value)) })
}
public mutating func encode(_ value: Int16, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeSignedInteger(value)) })
}
public mutating func encode(_ value: Int32, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeSignedInteger(value)) })
}
public mutating func encode(_ value: Int64, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeSignedInteger(value)) })
}
public mutating func encode(_ value: UInt, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeUnsignedInteger(value)) })
}
public mutating func encode(_ value: UInt8, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeUnsignedInteger(value)) })
}
public mutating func encode(_ value: UInt16, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeUnsignedInteger(value)) })
}
public mutating func encode(_ value: UInt32, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeUnsignedInteger(value)) })
}
public mutating func encode(_ value: UInt64, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeUnsignedInteger(value)) })
}
public mutating func encode(_ value: String, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeString(value)) })
}
public mutating func encode(_ value: Float, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeFloat(value)) })
}
public mutating func encode(_ value: Double, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, XPCEncodingHelpers.encodeDouble(value)) })
}
public mutating func encode<T : Encodable>(_ value: T, forKey key: Key) throws {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
do {
let xpcObject = try XPCEncoder.encode(value, at: self.encoder.codingPath)
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, xpcObject) })
} catch let error as EncodingError {
throw error
} catch {
throw XPCEncodingHelpers.makeEncodingError(value, self.codingPath, String(describing: error))
}
}
public mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
let xpcDictionary = xpc_dictionary_create(nil, nil, 0)
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, xpcDictionary) })
// It is OK to force this through because we know we are providing a dictionary
let container = try! XPCKeyedEncodingContainer<NestedKey>(referencing: self.encoder, wrapping: xpcDictionary)
return KeyedEncodingContainer(container)
}
public mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
let xpcArray = xpc_array_create(nil, 0)
key.stringValue.withCString({ xpc_dictionary_set_value(self.underlyingMesage, $0, xpcArray) })
let container = try! XPCUnkeyedEncodingContainer(referencing: self.encoder, wrapping: xpcArray)
return container
}
public mutating func superEncoder() -> Encoder {
self.encoder.codingPath.append(XPCCodingKey.superKey)
defer { self.encoder.codingPath.removeLast() }
return XPCDictionaryReferencingEncoder(at: self.encoder.codingPath, wrapping: self.underlyingMesage, forKey: XPCCodingKey.superKey)
}
public mutating func superEncoder(forKey key: Key) -> Encoder {
self.encoder.codingPath.append(key)
defer { self.encoder.codingPath.removeLast() }
return XPCDictionaryReferencingEncoder(at: self.encoder.codingPath, wrapping: self.underlyingMesage, forKey: key)
}
}
// This is used for encoding super classes, we don't know yet what kind of
// container the caller will request so we can not prepoluate in superEncoder().
// To overcome this we alias the encoder, the underlying dictionary, and the key
// to use, this way we can insert the key-value pair upon request and use the
// encoder to maintain the encoding state
fileprivate class XPCDictionaryReferencingEncoder: XPCEncoder {
let xpcDictionary: xpc_object_t
let key: CodingKey
init(at codingPath: [CodingKey], wrapping dictionary: xpc_object_t, forKey key: CodingKey) {
self.xpcDictionary = dictionary
self.key = key
super.init(at: codingPath)
}
override func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
let newDictionary = xpc_dictionary_create(nil, nil, 0)
self.key.stringValue.withCString({ xpc_dictionary_set_value(self.xpcDictionary, $0, newDictionary) })
// It is OK to force this through because we are explicitly passing a dictionary
let container = try! XPCKeyedEncodingContainer<Key>(referencing: self, wrapping: newDictionary)
return KeyedEncodingContainer(container)
}
override func unkeyedContainer() -> UnkeyedEncodingContainer {
let newArray = xpc_array_create(nil, 0)
self.key.stringValue.withCString({ xpc_dictionary_set_value(self.xpcDictionary, $0, newArray) })
// It is OK to force this through because we are explicitly passing an array
return try! XPCUnkeyedEncodingContainer(referencing: self, wrapping: newArray)
}
override func singleValueContainer() -> SingleValueEncodingContainer {
// It is OK to force this through because we are explicitly passing a dictionary
return XPCSingleValueEncodingContainer(referencing: self, insertionClosure: {
value in
self.key.stringValue.withCString({ xpc_dictionary_set_value(self.xpcDictionary, $0, value)})
})
}
}
| 44.377593 | 141 | 0.704628 |
e50adb95b5a06b318f2faae51cbea4392f3387fc | 64 | extension DomainEvent {
struct EventsChanged {}
}
| 10.666667 | 27 | 0.609375 |
18722ab525a95167fa21b0b94b2e98cd481cd7a0 | 1,432 | //
// SwiftUIDesignsUITests.swift
// SwiftUIDesignsUITests
//
// Created by Rohit Saini on 28/01/21.
//
import XCTest
class SwiftUIDesignsUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.302326 | 182 | 0.659916 |
168cef9e155ae184445c7fb990f76f29c4fefbc4 | 759 | //
// ExpenseItemView.swift
// ExpenseViewer
//
// Created by Gary Chen on 9/9/21.
//
import SwiftUI
struct ExpenseItemView : View {
let item: ExpenseItem
func dateToString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
return dateFormatter.string(from: item.date)
}
var body: some View {
HStack(alignment: .top, spacing: 8) {
Text(item.category.localizedName)
.frame(maxWidth: .infinity)
Text(dateToString())
.frame(maxWidth: .infinity)
Text("$"+String(item.amount))
.frame(maxWidth: .infinity)
}
}
}
| 23 | 52 | 0.555995 |
e8d98e4a104ba5771f852779576daa51bc9c5d9b | 492 | import SwiftUI
import CombineObserver
import Combine
import SwiftObserver
public extension View {
func bind<O: ObservableCache>(_ binding: Binding<O.Message>,
to observable: O) -> some View {
bind(binding, to: observable.publisher())
}
func bind<O: SwiftObserver.ObservableObject>(_ binding: Binding<O.Message>,
to observable: O) -> some View {
bind(binding, to: observable.publisher())
}
}
| 28.941176 | 79 | 0.607724 |
ef625e1295882d32e423b1dd706666033749d306 | 1,318 | //
// TableViewDataSource.swift
// Render
//
// Created by Chris Nevin on 09/03/2019.
// Copyright © 2019 Chris Nevin. All rights reserved.
//
import UIKit
public protocol TableViewCellModel {
func cell(at indexPath: IndexPath, in tableView: UITableView) -> UITableViewCell
func didSelect(at indexPath: IndexPath, in tableView: UITableView)
}
open class TableViewDataSource<T: TableViewCellModel>: AbstractDataSource<T>, UITableViewDataSource, UITableViewDelegate {
open weak var tableView: UITableView? {
didSet {
tableView?.dataSource = self
tableView?.delegate = self
reload()
}
}
open override func reload() {
tableView?.reloadData()
}
public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return items[indexPath.row].cell(at: indexPath, in: tableView)
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
return items[indexPath.row].didSelect(at: indexPath, in: tableView)
}
}
| 29.288889 | 122 | 0.685888 |
6a7b35e8927355e50a0380f34c08c69940e8ae0b | 1,119 | //
// ChallengeDetailViewController.swift
// DevChallenges
//
// Created by Barlow Tucker on 5/6/16.
// Copyright © 2016 Barlow Tucker. All rights reserved.
//
import UIKit
class ChallengeDetailViewController: UIViewController {
@IBOutlet weak var challengeImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var actionButton: UIButton!
var challenge:Challenge?
override func viewDidLoad() {
super.viewDidLoad()
guard let challenge = self.challenge else { return }
self.challengeImageView.image = challenge.image
self.titleLabel.text = challenge.title
self.descriptionLabel.text = challenge.description
self.subtitleLabel.text = challenge.subtitle
self.actionButton.hidden = challenge.appURL == nil
}
@IBAction func actionTapped(sender: AnyObject) {
guard let url = self.challenge?.appURL else { return }
UIApplication.sharedApplication().openURL(url)
}
}
| 30.243243 | 62 | 0.692583 |
08f152fbdc80b83329bc6cdb2178e23a9bcd19e4 | 1,138 | //
// Created by Esteban Torres on 23.04.17.
// Copyright (c) 2017 Esteban Torres. All rights reserved.
//
import Foundation
import XCTest
@testable import MammutAPI
internal class TagTests: XCTestCase {
func test_sameTags_equal() {
let subject1 = TagTests.makeTag()
let subject2 = TagTests.makeTag()
XCTAssertEqual(subject1, subject2)
}
func test_differentTags_notEqual() {
let subject1 = TagTests.makeTag(name: #function + #file)
let subject2 = TagTests.makeTag(name: #file + #function)
XCTAssertNotEqual(subject1, subject2)
}
}
// MARK: - Linux Support
extension TagTests {
static var allTests: [(String, (TagTests) -> () throws -> Void)] {
return [
("test_sameTags_equal", test_sameTags_equal),
("test_differentTags_notEqual", test_differentTags_notEqual)
]
}
}
// MARK: Test Helpers
fileprivate extension TagTests {
static func makeTag(name: String = #file, url: URL = URL(string: "www.example.com")!) -> Tag {
return Tag(
name: name,
url: url
)
}
}
| 25.288889 | 98 | 0.623023 |
210e64fe49a2bb75af036c2b04060255a3799893 | 270 | //
// NotificationStatus.swift
// citizenconnect
//
// Created by Shahzaib Shahid on 26/03/2018.
// Copyright © 2018 cfp. All rights reserved.
//
import Foundation
import RealmSwift
class NotificationStatus: Object {
@objc dynamic var notificationCount = ""
}
| 18 | 46 | 0.722222 |
28bcda3dddb272e820b58a313166a843ab05d533 | 703 | //
// OBActiveOrHistoricCurrencyAndAmount3.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Amount of money associated with the statement benefit type. */
public struct OBActiveOrHistoricCurrencyAndAmount3: Codable {
public var amount: OBActiveCurrencyAndAmountSimpleType
public var currency: ActiveOrHistoricCurrencyCode1
public init(amount: OBActiveCurrencyAndAmountSimpleType, currency: ActiveOrHistoricCurrencyCode1) {
self.amount = amount
self.currency = currency
}
public enum CodingKeys: String, CodingKey {
case amount = "Amount"
case currency = "Currency"
}
}
| 22.677419 | 103 | 0.733997 |
dd0cfbd526a318df93ee526a80e16906834b16e9 | 2,786 | //
// SFCollectionView.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 10/02/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
open class SFCollectionView: UICollectionView, SFViewColorStyle {
// MARK: - Instance Properties
open var automaticallyAdjustsColorStyle: Bool = false
open var useAlternativeColors: Bool = false
// MARK: - Initializers
public init(automaticallyAdjustsColorStyle: Bool = true, useAlternativeColors: Bool = false, frame: CGRect = .zero, collectionViewLayout: UICollectionViewLayout) {
self.automaticallyAdjustsColorStyle = automaticallyAdjustsColorStyle
self.useAlternativeColors = useAlternativeColors
super.init(frame: frame, collectionViewLayout: collectionViewLayout)
if automaticallyAdjustsColorStyle {
updateColors()
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Instance Methods
open func updateColors() {
backgroundColor = useAlternativeColors ? colorStyle.mainColor : colorStyle.alternativeColor
updateSubviewsColors()
if self.numberOfSections >= 0 {
let numberOfSections = self.numberOfSections - 1
if numberOfSections >= 0 {
for i in 0...numberOfSections {
if let header = supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: i)) as? SFViewColorStyle {
header.updateColors()
}
if let footer = supplementaryView(forElementKind: UICollectionView.elementKindSectionFooter, at: IndexPath(row: 0, section: i)) as? SFViewColorStyle {
footer.updateColors()
}
let numberOfItems = self.numberOfItems(inSection: i) - 1
if numberOfItems > 0 {
for j in 0...numberOfItems {
guard let cell = cellForItem(at: IndexPath(row: j, section: i)) as? SFCollectionViewCell else { return }
cell.updateColors()
}
}
}
}
}
}
open override func dequeueReusableCell(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> UICollectionViewCell {
let cell = super.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
if let cell = cell as? SFCollectionViewCell {
cell.updateColors()
}
return cell
}
}
| 38.164384 | 170 | 0.601579 |
11a7a84b864a06e8ff3bf7aa87788c29de6923ce | 717 | //
// YearlyProgressUITests.swift
// YearlyProgressUITests
//
// Created by Mason Phillips on 2/2/18.
// Copyright © 2018 Matrix Studios. All rights reserved.
//
import XCTest
class YearlyProgressUITests: XCTestCase {
override func setUp() {
super.setUp()
let app = XCUIApplication()
setupSnapshot(app)
continueAfterFailure = false
app.launch()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func getSnapshots() {
}
func testUI() {
snapshot("MainInterface")
}
}
| 19.378378 | 111 | 0.592748 |
2881b278a472f846bb7d649ce90d7868263a46a8 | 4,178 | import XCTest
@testable import Curator
class URLExtensionTests: XCTestCase {
let fileURL = URL(string: "file:///file")!
let directoryURL = URL(string: "file:///dir/")!
func testCuratorExtension() {
XCTAssertEqual(fileURL, fileURL.crt.base)
}
func testHasDirectoryPath() {
XCTAssertFalse(fileURL.crt.hasDirectoryPath)
XCTAssertTrue(directoryURL.crt.hasDirectoryPath)
let directoryCurrentDirURL = directoryURL.appendingPathComponent(".", isDirectory: true)
let directoryCurrentDirURL2 = directoryURL.appendingPathComponent(".", isDirectory: false)
XCTAssertTrue(directoryCurrentDirURL.crt.hasDirectoryPath)
XCTAssertTrue(directoryCurrentDirURL2.crt.hasDirectoryPath)
let webURL = URL(string: "https://api.shop.com/category/toy/../phone/./iphone/?json=true")!
XCTAssertTrue(webURL.crt.hasDirectoryPath)
}
func testGetDirectoryURL() {
XCTAssertEqual(directoryURL, directoryURL.crt.getDirectoryURL(greedy: false))
XCTAssertEqual(directoryURL, directoryURL.crt.getDirectoryURL(greedy: true))
let rootURL = URL(string: "file:///")!
XCTAssertEqual(rootURL, fileURL.crt.getDirectoryURL(greedy: false))
let fileDirectoryURL = URL(string: "file:///file/")!
XCTAssertEqual(fileDirectoryURL, fileURL.crt.getDirectoryURL(greedy: true))
}
func testFileExist() {
let tmpDirURL = Curator.SupportedDirectory.tmp.url
let tmpDirExistResult = tmpDirURL.crt.fileExist
XCTAssertTrue(tmpDirExistResult.fileExist)
XCTAssertTrue(tmpDirExistResult.isDirectory)
let notExistFileURL = URL(string: "file:///notExistFile")!
let notExistFileExistResult = notExistFileURL.crt.fileExist
XCTAssertFalse(notExistFileExistResult.fileExist)
XCTAssertFalse(notExistFileExistResult.isDirectory)
let hostsFileURL = URL(string: "file:///etc/hosts")!
let hostsFileExistResult = hostsFileURL.crt.fileExist
XCTAssertTrue(hostsFileExistResult.fileExist)
XCTAssertFalse(hostsFileExistResult.isDirectory)
}
func testCreateDirectory() {
//create testDir first
let uuidString = UUID().uuidString
typealias Location = Curator.KeyLocation
let testDirLocation = Location(key: uuidString, directory: .tmp)
let testDirURL = try! testDirLocation.standardizedFileURL().crt.getDirectoryURL(greedy: true)
XCTAssertFalse(testDirURL.crt.fileExist.fileExist)
try! testDirURL.crt.createDirectory()
XCTAssertTrue(testDirURL.crt.fileExist.isDirectory)
//save a file for test
let data = Data(count: 1)
let fileLocation = Location(key: "\(uuidString)/file", directory: .tmp)
try! Curator.save(data, to: fileLocation)
let fileLocationURL = try! fileLocation.standardizedFileURL()
XCTAssertTrue(fileLocationURL.crt.fileExist.fileExist)
//check locationIsFile
let fileLocationFakeDirURL = fileLocationURL.crt.getDirectoryURL(greedy: true)
do {
try fileLocationFakeDirURL.crt.createDirectory()
XCTFail()
} catch Curator.Error.locationIsFile(let location) {
let url = location as! URL
XCTAssertEqual(url, fileLocationFakeDirURL)
} catch { XCTFail() }
//check parent locationIsFile
let fileLocation2 = Location(key: "\(uuidString)/file/dir/dir/foo", directory: .tmp)
let fileLocation2URL = try! fileLocation2.standardizedFileURL()
XCTAssertFalse(fileLocation2URL.crt.fileExist.fileExist)
do {
try fileLocation2URL.crt.createDirectory()
XCTFail()
} catch Curator.Error.locationIsFile(let location) {
let url = location as! URL
XCTAssertEqual(url, fileLocationFakeDirURL)
} catch { XCTFail() }
//reuse fileExistResult
let testDirExistResult = testDirURL.crt.fileExist
try! testDirURL.crt.createDirectory(fileExistResult: testDirExistResult)
}
}
| 43.072165 | 101 | 0.676879 |
fc1844b092ce76f8b0dc5f749420b7e1604f206a | 2,809 | //
// FSBucketCacheTest.swift
// FlagshipTests
//
// Created by Adel on 01/04/2020.
// Copyright © 2020 FlagShip. All rights reserved.
//
import XCTest
@testable import Flagship
class FSBucketCacheTest: XCTestCase {
var bucketCache: FSBucketCache!
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
bucketCache = FSBucketCache("userId")
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
bucketCache = nil
}
func testGetCampaignnilArray(){
bucketCache.campaigns = nil
XCTAssertTrue(self.bucketCache.getCampaignArray().count == 0)
}
func testGetCampaignEmptyArray(){
bucketCache.campaigns = []
XCTAssertTrue(self.bucketCache.getCampaignArray().count == 0)
}
func testGetCampaignyArray(){
bucketCache.campaigns = [FSCampaignCache("idC", [FSVariationGroupCache("idG", FSVariationCache("idv"))]),
FSCampaignCache("idC", [FSVariationGroupCache("idG", FSVariationCache("idv"))]),
FSCampaignCache("idC", [FSVariationGroupCache("idG", FSVariationCache("idv"))]),
FSCampaignCache("idC", [FSVariationGroupCache("idG", FSVariationCache("idv"))]),
FSCampaignCache("idC", [FSVariationGroupCache("idG", FSVariationCache("idv"))])]
XCTAssertTrue(self.bucketCache.getCampaignArray().count == 5)
}
func testSaveMe(){
self.bucketCache.saveMe()
}
func testFSBucketCache(){
do {
let testBundle = Bundle(for: type(of: self))
guard let path = testBundle.url(forResource: "bucketMock", withExtension: "json") else {
return
}
let data = try Data(contentsOf: path, options:.alwaysMapped)
let bucketCache = try JSONDecoder().decode(FSBucketCache.self, from: data)
XCTAssert(bucketCache.visitorId == "error" )
XCTAssert(bucketCache.campaigns.count == 4 )
print(bucketCache)
}catch{
print("error")
return
}
}
func testFSBucket(){
let bucket = FSBucket()
XCTAssertTrue(bucket.panic == true)
XCTAssertTrue(bucket.campaigns.count == 0)
}
}
| 25.080357 | 113 | 0.544322 |
237517e3341a7bb92ba08c189a40d1ce5a1a6f62 | 1,460 | //
// tipUITests.swift
// tipUITests
//
// Created by StudentGuest on 8/31/20.
// Copyright © 2020 Codepath. All rights reserved.
//
import XCTest
class tipUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 33.181818 | 182 | 0.658219 |
cc1d4a9d925b51d29415989ebdf9d1b2f655ea01 | 165 | //
// File.swift
// SafeAreaViewExample
//
// Created by Janic Duplessis on 2020-05-02.
// Copyright © 2020 Facebook. All rights reserved.
//
import Foundation
| 16.5 | 51 | 0.69697 |
ff149bb6c1c49a5e7f426dd825e4f3ff74bb72f9 | 1,058 | //
// SwiftRPC+Requests.swift
// SwiftRPC
//
// Created by Bruno Philipe on 24/8/17.
// Copyright © 2017 Bruno Philipe. All rights reserved.
//
import Foundation
public extension SwiftRPC
{
func getinfo(completion: @escaping (RPCResult<RPCInfo>) -> Void)
{
invoke(method: "getinfo", completion: completion)
}
public struct RPCInfo: Codable
{
let version: Int
let protocolversion: Int
let walletversion: Int
let balance: Double
let blocks: Int
let timeoffset: Int
let connections: Int
let proxy: String
let difficulty: Double
let testnet: Bool
let keypoololdest: Int
let keypoolsize: Int
let unlocked_until: Int
let paytxfee: Double
let relayfee: Double
let errors: String
}
}
public extension SwiftRPC
{
func getbestblockhash(completion: @escaping (RPCResult<String>) -> Void)
{
invoke(method: "getbestblockhash", completion: completion)
}
}
public extension SwiftRPC
{
func getblockcount(completion: @escaping (RPCResult<Int>) -> Void)
{
invoke(method: "getblockcount", completion: completion)
}
}
| 19.592593 | 73 | 0.723062 |
282787a007fcbd0073aa8f850d13b0c7ba2147a9 | 2,949 | import Foundation
import XCTest
@testable import JustLog
class Dictionary_Flattening: XCTestCase {
func test_merge() {
let d1 = ["k1": "v1", "k2": "v2"]
let d2 = ["k3": "v3", "k4": "v4"]
let merged = d1.merged(with: d2)
let target = ["k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"]
XCTAssertEqual(NSDictionary(dictionary:merged), NSDictionary(dictionary: target))
}
func test_merge_withConflictingDictionies() {
let d1 = ["k1": "v1", "k2": "v2"]
let d2 = ["k1": "v1b", "k3": "v3"]
let merged = d1.merged(with: d2)
let target = ["k1": "v1b", "k2": "v2", "k3": "v3"]
XCTAssertEqual(NSDictionary(dictionary:merged), NSDictionary(dictionary:target))
}
func test_flattened() {
let domain = "com.justeat.dictionary"
let error = NSError(domain: domain, code: 200, userInfo: ["k8": "v8"])
let nestedError = NSError(domain: domain, code: 200, userInfo: [NSUnderlyingErrorKey: NSError(domain: domain, code: 200, userInfo: ["k10": 10])])
let input = ["k1": "v1", "k2": ["k3": "v3"], "k4": 4, "k5": 5.1, "k6": true,
"k7": error, "k9": nestedError, "k11": [1, 2, 3]] as [String : Any]
let flattened = input.flattened()
XCTAssertEqual(flattened.keys.count, 8)
XCTAssertEqual(flattened["k1"] as! String, "v1")
XCTAssertEqual(flattened["k3"] as! String, "v3")
XCTAssertEqual(flattened["k4"] as! Int, 4)
XCTAssertEqual(flattened["k5"] as! Double, 5.1)
XCTAssertEqual(flattened["k6"] as! Bool, true)
XCTAssertEqual(flattened["k8"] as! String, "v8")
XCTAssertEqual(flattened["k10"] as! Int, 10)
XCTAssertEqual(flattened["k11"] as! String, "[1, 2, 3]")
}
func test_flattened_withConflictingDictionies() {
let input = ["k1": "v1", "k2": ["k1": "v3", "k4": "v4"]] as [String : Any]
let flattened = input.flattened()
// can be either ["k1": "v1", "k4": "v4"] or ["k1": "v3", "k4": "v4"]
XCTAssertEqual(flattened.keys.count, 2)
XCTAssertNotNil(flattened["k1"])
XCTAssertEqual(flattened["k4"] as! String, "v4")
}
func test_flattened_recursive() {
let input = ["k1": "v1",
"k2": ["k3": "v3",
"k4": ["k5": "v5"]]] as [String : Any]
let flattened = input.flattened()
// target = ["k1": "v1", "k3": "v3", "k5": "v5"] as [String : Any]
XCTAssertEqual(flattened.keys.count, 3)
XCTAssertEqual(flattened["k1"] as! String, "v1")
XCTAssertNil(flattened["k2"])
XCTAssertNil(flattened["k4"])
XCTAssertEqual(flattened["k3"] as! String, "v3")
XCTAssertEqual(flattened["k5"] as! String, "v5")
}
}
| 36.8625 | 153 | 0.527636 |
d6ded67744d0e84de5ef1d00fca7a5ebd5f22c2c | 3,549 | //: [Previous](@previous)
import UIKit
import _Concurrency
actor Score {
var localLogs: [Int] = []
private(set) var highScore: Int = 0
func update(with score: Int) async {
// requestHighScoreを呼ぶ順番で結果が変わる
highScore = await requestHighScore(with: score)
localLogs.append(score)
}
// サーバーに点数を送るとサーバーが集計した自分の最高得点が得られると想定するメソッド
// 実際は2秒まって引数のscoreを返すだけ
func requestHighScore(with score: Int) async -> Int {
try? await Task.sleep(nanoseconds: 2 * NSEC_PER_SEC) // 2秒待つ
return score
}
}
let score = Score()
Task.detached {
await score.update(with: 100)
print(await score.localLogs)
print(await score.highScore)
}
Task.detached {
await score.update(with: 110)
print(await score.localLogs)
print(await score.highScore)
}
actor ImageDownloader {
private var cached: [String: UIImage] = [:]
func image(from url: String) async -> UIImage {
// キャシュがあればそれを使う
if cached.keys.contains(url) {
return cached[url]!
}
// ダウンロード
let image = await downloadImage(from: url)
if !cached.keys.contains(url) {
// キャッシュに保存
cached[url] = image
}
return cached[url]!
}
// サーバーに画像をリクエストすることを想定するメソッド
// 2秒後に画像をランダムで返す
func downloadImage(from url: String) async -> UIImage {
try? await Task.sleep(nanoseconds: 2 * NSEC_PER_SEC) // 2秒待つ
switch url {
case "monster":
// サーバー側でリソースが変わったことを表すためランダムで画像名をセット
let imageName = Bool.random() ? "cow" : "fox"
return UIImage(named: imageName)!
default:
return UIImage()
}
}
}
let imageDownloader = ImageDownloader()
Task.detached {
let image = await imageDownloader.image(from: "monster")
print(image)
// let image2 = await imageDownloader.image(from: "monster")
// print(image2)
}
Task.detached {
let image = await imageDownloader.image(from: "monster")
print(image)
}
actor ImageDownloader2 {
private enum CacheEntry {
case inProgress(Task<UIImage, Never>)
case ready(UIImage)
}
private var cache: [String: CacheEntry] = [:]
func image(from url: String) async -> UIImage? {
if let cached = cache[url] {
switch cached {
case .ready(let image):
return image
case .inProgress(let task):
return await task.value
}
}
let task = Task {
await downloadImage(from: url)
}
cache[url] = .inProgress(task)
// task.valueでimageを取得
let image = await task.value
cache[url] = .ready(image)
return image
}// NSEC_PER_SEC
func downloadImage(from url: String) async -> UIImage {
print(NSEC_PER_SEC)
try? await Task.sleep(nanoseconds: 2 * NSEC_PER_SEC) // 2秒待つ
switch url {
case "monster":
// サーバー側でリソースが変わったことを表すためランダムで画像名をセット
let imageName = Bool.random() ? "cow" : "fox"
return UIImage(named: imageName)!
default:
return UIImage()
}
}
}
let imageDownloader2 = ImageDownloader2()
Task.detached {
let image = await imageDownloader2.image(from: "monster")
print("image2: \(image.debugDescription)")
}
Task.detached {
let image = await imageDownloader2.image(from: "monster")
print("image2: \(image.debugDescription)")
}
//: [Next](@next)
| 26.288889 | 69 | 0.592561 |
1a1cafda81be44fa87d750b7a0928a99b660b641 | 3,141 | //
// ViewUtil.swift
// MercadoPagoSDK
//
// Created by Maria cristina rodriguez on 21/4/16.
// Copyright © 2016 MercadoPago. All rights reserved.
//
import Foundation
import UIKit
class ViewUtils {
class func getTableCellSeparatorLineView(_ x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> UIView {
let separatorLineView = UIView(frame: CGRect(x: x, y: y, width: width, height: height))
separatorLineView.layer.zPosition = 1
separatorLineView.backgroundColor = UIColor.grayTableSeparator()
return separatorLineView
}
class func addStatusBar(_ view: UIView, color: UIColor) {
let addStatusBar = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 20))
addStatusBar.backgroundColor = color
view.addSubview(addStatusBar)
}
class func addScaledImage(_ image: UIImage, inView view: UIView) {
let imageView = UIImageView()
imageView.frame = view.bounds
imageView.contentMode = .scaleAspectFill
imageView.image = image
view.addSubview(imageView)
}
class func loadImageFromUrl(_ url: String, inView: UIView, loadingBackgroundColor: UIColor = UIColor.primaryColor(), loadingIndicatorColor: UIColor = UIColor.systemFontColor()) {
// LoadingOverlay.shared.showOverlay(inView, backgroundColor: loadingBackgroundColor, indicatorColor: loadingIndicatorColor)
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: {
let url = URL(string: url)
if url != nil {
let data = try? Data(contentsOf: url!)
if data != nil {
DispatchQueue.main.async(execute: {
let image = UIImage(data: data!)
if image != nil {
ViewUtils.addScaledImage(image!, inView: inView)
}
})
}
}
LoadingOverlay.shared.hideOverlayView()
})
}
class func loadImageFromUrl(_ url: String) -> UIImage? {
let url = URL(string: url)
if url != nil {
let data = try? Data(contentsOf: url!)
if data != nil {
let image = UIImage(data: data!)
return image
} else {
return nil
}
} else {
return nil
}
}
func getSeparatorLineForTop(width: Double, y: Float) -> UIView {
let lineFrame = CGRect(origin: CGPoint(x: 0, y :Int(y)), size: CGSize(width: width, height: 0.5))
let line = UIView(frame: lineFrame)
line.alpha = 0.6
line.backgroundColor = UIColor.px_grayLight()
return line
}
class func drawBottomLine(_ x: CGFloat = 0, y: CGFloat, width: CGFloat, inView view: UIView) {
let overLinewView = UIView(frame: CGRect(x: x, y: y, width: width, height: 1))
overLinewView.backgroundColor = UIColor.UIColorFromRGB(0xDEDEDE)
view.addSubview(overLinewView)
}
}
| 36.523256 | 182 | 0.58994 |
8f9de85bbe8717e0304da9716ec149c77d1540f1 | 14,583 | //
// FlagPhoneNumberTextField.swift
// FlagPhoneNumber
//
// Created by Aurélien Grifasi on 06/08/2017.
// Copyright (c) 2017 Aurélien Grifasi. All rights reserved.
//
import UIKit
open class FPNTextField: UITextField {
/// The size of the flag button
@objc open var flagButtonSize: CGSize = CGSize(width: 32, height: 32) {
didSet {
layoutIfNeeded()
}
}
private var flagWidthConstraint: NSLayoutConstraint?
private var flagHeightConstraint: NSLayoutConstraint?
/// The size of the leftView
private var leftViewSize: CGSize {
let width = flagButtonSize.width + getWidth(text: phoneCodeTextField.text!)
let height = bounds.height
return CGSize(width: width, height: height)
}
private var phoneCodeTextField: UITextField = UITextField()
private lazy var phoneUtil: NBPhoneNumberUtil = NBPhoneNumberUtil()
private var nbPhoneNumber: NBPhoneNumber?
private var formatter: NBAsYouTypeFormatter?
open var flagButton: UIButton = UIButton()
open override var font: UIFont? {
didSet {
phoneCodeTextField.font = font
}
}
open var leftTextColor : UIColor? {
didSet {
phoneCodeTextField.textColor = leftTextColor
}
}
/// Present in the placeholder an example of a phone number according to the selected country code.
/// If false, you can set your own placeholder. Set to true by default.
@objc open var hasPhoneNumberExample: Bool = true {
didSet {
if hasPhoneNumberExample == false {
placeholder = nil
}
updatePlaceholder()
}
}
open var countryRepository = FPNCountryRepository()
open var selectedCountry: FPNCountry? {
didSet {
updateUI()
}
}
/// Input Accessory View for the texfield
@objc open var textFieldInputAccessoryView: UIView?
open lazy var pickerView: FPNCountryPicker = FPNCountryPicker()
@objc public enum FPNDisplayMode: Int {
case picker
case list
}
@objc open var displayMode: FPNDisplayMode = .picker
init() {
super.init(frame: .zero)
setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
leftViewMode = .always
setupFlagButton()
setupPhoneCodeTextField()
setupLeftView()
keyboardType = .numberPad
autocorrectionType = .no
addTarget(self, action: #selector(didEditText), for: .editingChanged)
addTarget(self, action: #selector(displayNumberKeyBoard), for: .touchDown)
if let regionCode = Locale.current.regionCode, let countryCode = FPNCountryCode(rawValue: regionCode) {
setFlag(countryCode: countryCode)
} else {
setFlag(countryCode: FPNCountryCode.FR)
}
}
private func setupFlagButton() {
flagButton.imageView?.contentMode = .scaleAspectFit
flagButton.accessibilityLabel = "flagButton"
flagButton.addTarget(self, action: #selector(displayCountries), for: .touchUpInside)
flagButton.translatesAutoresizingMaskIntoConstraints = false
flagButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
private func setupPhoneCodeTextField() {
phoneCodeTextField.font = font
phoneCodeTextField.isUserInteractionEnabled = false
phoneCodeTextField.translatesAutoresizingMaskIntoConstraints = false
}
private func setupLeftView() {
leftView = UIView()
leftViewMode = .always
if #available(iOS 9.0, *) {
phoneCodeTextField.semanticContentAttribute = .forceLeftToRight
} else {
// Fallback on earlier versions
}
leftView?.addSubview(flagButton)
leftView?.addSubview(phoneCodeTextField)
flagWidthConstraint = NSLayoutConstraint(item: flagButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: flagButtonSize.width)
flagHeightConstraint = NSLayoutConstraint(item: flagButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: flagButtonSize.height)
flagWidthConstraint?.isActive = true
flagHeightConstraint?.isActive = true
NSLayoutConstraint(item: flagButton, attribute: .centerY, relatedBy: .equal, toItem: leftView, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: flagButton, attribute: .leading, relatedBy: .equal, toItem: leftView, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: phoneCodeTextField, attribute: .leading, relatedBy: .equal, toItem: flagButton, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: phoneCodeTextField, attribute: .trailing, relatedBy: .equal, toItem: leftView, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: phoneCodeTextField, attribute: .top, relatedBy: .equal, toItem: leftView, attribute: .top, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: phoneCodeTextField, attribute: .bottom, relatedBy: .equal, toItem: leftView, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
}
open override func updateConstraints() {
super.updateConstraints()
flagWidthConstraint?.constant = flagButtonSize.width
flagHeightConstraint?.constant = flagButtonSize.height
}
open override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
let size = leftViewSize
let width: CGFloat = min(bounds.size.width, size.width)
let height: CGFloat = min(bounds.size.height, size.height)
let newRect: CGRect = CGRect(x: bounds.minX, y: bounds.minY, width: width, height: height)
return newRect
}
@objc private func displayNumberKeyBoard() {
switch displayMode {
case .picker:
tintColor = .gray
inputView = nil
inputAccessoryView = textFieldInputAccessoryView
reloadInputViews()
default:
break
}
}
@objc private func displayCountries() {
switch displayMode {
case .picker:
pickerView.setup(repository: countryRepository)
tintColor = .clear
inputView = pickerView
inputAccessoryView = getToolBar(with: getCountryListBarButtonItems())
reloadInputViews()
becomeFirstResponder()
pickerView.didSelect = { [weak self] country in
self?.fpnDidSelect(country: country)
}
if let selectedCountry = selectedCountry {
pickerView.setCountry(selectedCountry.code)
} else if let regionCode = Locale.current.regionCode, let countryCode = FPNCountryCode(rawValue: regionCode) {
pickerView.setCountry(countryCode)
} else if let firstCountry = countryRepository.countries.first {
pickerView.setCountry(firstCountry.code)
}
case .list:
(delegate as? FPNTextFieldDelegate)?.fpnDisplayCountryList()
}
}
@objc private func dismissCountries() {
resignFirstResponder()
inputView = nil
inputAccessoryView = nil
reloadInputViews()
}
private func fpnDidSelect(country: FPNCountry) {
(delegate as? FPNTextFieldDelegate)?.fpnDidSelectCountry(name: country.name, dialCode: country.phoneCode, code: country.code.rawValue)
selectedCountry = country
}
// - Public
/// Get the current formatted phone number
open func getFormattedPhoneNumber(format: FPNFormat) -> String? {
return try? phoneUtil.format(nbPhoneNumber, numberFormat: convert(format: format))
}
/// For Objective-C, Get the current formatted phone number
@objc open func getFormattedPhoneNumber(format: Int) -> String? {
if let formatCase = FPNFormat(rawValue: format) {
return try? phoneUtil.format(nbPhoneNumber, numberFormat: convert(format: formatCase))
}
return nil
}
/// Get the current raw phone number
@objc open func getRawPhoneNumber() -> String? {
let phoneNumber = getFormattedPhoneNumber(format: .E164)
var nationalNumber: NSString?
phoneUtil.extractCountryCode(phoneNumber, nationalNumber: &nationalNumber)
return nationalNumber as String?
}
/// Set directly the phone number. e.g "+33612345678"
@objc open func set(phoneNumber: String) {
let cleanedPhoneNumber: String = clean(string: phoneNumber)
if let validPhoneNumber = getValidNumber(phoneNumber: cleanedPhoneNumber) {
if validPhoneNumber.italianLeadingZero {
text = "0\(validPhoneNumber.nationalNumber.stringValue)"
} else {
text = validPhoneNumber.nationalNumber.stringValue
}
setFlag(countryCode: FPNCountryCode(rawValue: phoneUtil.getRegionCode(for: validPhoneNumber))!)
}
}
/// Set the country image according to country code. Example "FR"
open func setFlag(countryCode: FPNCountryCode) {
let countries = countryRepository.countries
for country in countries {
if country.code == countryCode {
return fpnDidSelect(country: country)
}
}
}
/// Set the country image according to country code. Example "FR"
@objc open func setFlag(key: FPNOBJCCountryKey) {
if let code = FPNOBJCCountryCode[key], let countryCode = FPNCountryCode(rawValue: code) {
setFlag(countryCode: countryCode)
}
}
/// Set the country list excluding the provided countries
open func setCountries(excluding countries: [FPNCountryCode]) {
countryRepository.setup(without: countries)
if let selectedCountry = selectedCountry, countryRepository.countries.contains(selectedCountry) {
fpnDidSelect(country: selectedCountry)
} else if let country = countryRepository.countries.first {
fpnDidSelect(country: country)
}
}
/// Set the country list including the provided countries
open func setCountries(including countries: [FPNCountryCode]) {
countryRepository.setup(with: countries)
if let selectedCountry = selectedCountry, countryRepository.countries.contains(selectedCountry) {
fpnDidSelect(country: selectedCountry)
} else if let country = countryRepository.countries.first {
fpnDidSelect(country: country)
}
}
/// Set the country list excluding the provided countries
@objc open func setCountries(excluding countries: [Int]) {
let countryCodes: [FPNCountryCode] = countries.compactMap({ index in
if let key = FPNOBJCCountryKey(rawValue: index), let code = FPNOBJCCountryCode[key], let countryCode = FPNCountryCode(rawValue: code) {
return countryCode
}
return nil
})
countryRepository.setup(without: countryCodes)
}
/// Set the country list including the provided countries
@objc open func setCountries(including countries: [Int]) {
let countryCodes: [FPNCountryCode] = countries.compactMap({ index in
if let key = FPNOBJCCountryKey(rawValue: index), let code = FPNOBJCCountryCode[key], let countryCode = FPNCountryCode(rawValue: code) {
return countryCode
}
return nil
})
countryRepository.setup(with: countryCodes)
}
// Private
@objc private func didEditText() {
if let phoneCode = selectedCountry?.phoneCode, let number = text {
var cleanedPhoneNumber = clean(string: "\(phoneCode) \(number)")
if let validPhoneNumber = getValidNumber(phoneNumber: cleanedPhoneNumber) {
nbPhoneNumber = validPhoneNumber
cleanedPhoneNumber = "+\(validPhoneNumber.countryCode.stringValue)\(validPhoneNumber.nationalNumber.stringValue)"
if let inputString = formatter?.inputString(cleanedPhoneNumber) {
text = remove(dialCode: phoneCode, in: inputString)
}
(delegate as? FPNTextFieldDelegate)?.fpnDidValidatePhoneNumber(textField: self, isValid: true)
} else {
nbPhoneNumber = nil
if let dialCode = selectedCountry?.phoneCode {
if let inputString = formatter?.inputString(cleanedPhoneNumber) {
text = remove(dialCode: dialCode, in: inputString)
}
}
(delegate as? FPNTextFieldDelegate)?.fpnDidValidatePhoneNumber(textField: self, isValid: false)
}
}
}
private func convert(format: FPNFormat) -> NBEPhoneNumberFormat {
switch format {
case .E164:
return NBEPhoneNumberFormat.E164
case .International:
return NBEPhoneNumberFormat.INTERNATIONAL
case .National:
return NBEPhoneNumberFormat.NATIONAL
case .RFC3966:
return NBEPhoneNumberFormat.RFC3966
}
}
private func updateUI() {
if let countryCode = selectedCountry?.code {
formatter = NBAsYouTypeFormatter(regionCode: countryCode.rawValue)
}
flagButton.setImage(selectedCountry?.flag, for: .normal)
if let phoneCode = selectedCountry?.phoneCode {
phoneCodeTextField.text = phoneCode
}
if hasPhoneNumberExample == true {
updatePlaceholder()
}
didEditText()
}
private func clean(string: String) -> String {
var allowedCharactersSet = CharacterSet.decimalDigits
allowedCharactersSet.insert("+")
return string.components(separatedBy: allowedCharactersSet.inverted).joined(separator: "")
}
private func getWidth(text: String) -> CGFloat {
if let font = phoneCodeTextField.font {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = (text as NSString).size(withAttributes: fontAttributes)
return size.width.rounded(.up)
} else {
phoneCodeTextField.sizeToFit()
return phoneCodeTextField.frame.size.width.rounded(.up)
}
}
private func getValidNumber(phoneNumber: String) -> NBPhoneNumber? {
guard let countryCode = selectedCountry?.code else { return nil }
do {
let parsedPhoneNumber: NBPhoneNumber = try phoneUtil.parse(phoneNumber, defaultRegion: countryCode.rawValue)
let isValid = phoneUtil.isValidNumber(parsedPhoneNumber)
return isValid ? parsedPhoneNumber : nil
} catch _ {
return nil
}
}
private func remove(dialCode: String, in phoneNumber: String) -> String {
return phoneNumber.replacingOccurrences(of: "\(dialCode) ", with: "").replacingOccurrences(of: "\(dialCode)", with: "")
}
private func getToolBar(with items: [UIBarButtonItem]) -> UIToolbar {
let toolbar: UIToolbar = UIToolbar()
toolbar.barStyle = UIBarStyle.default
toolbar.items = items
toolbar.sizeToFit()
return toolbar
}
private func getCountryListBarButtonItems() -> [UIBarButtonItem] {
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissCountries))
doneButton.accessibilityLabel = "doneButton"
return [space, doneButton]
}
private func updatePlaceholder() {
if let countryCode = selectedCountry?.code {
do {
let example = try phoneUtil.getExampleNumber(countryCode.rawValue)
let phoneNumber = "+\(example.countryCode.stringValue)\(example.nationalNumber.stringValue)"
if let inputString = formatter?.inputString(phoneNumber) {
placeholder = remove(dialCode: "+\(example.countryCode.stringValue)", in: inputString)
} else {
placeholder = nil
}
} catch _ {
placeholder = nil
}
} else {
placeholder = nil
}
}
}
| 31.36129 | 189 | 0.744086 |
ff6c8c26f5bbd78ae5ef5260cc4a45855c61834b | 2,491 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift %s -Xfrontend -enable-experimental-keypath-components -o %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
// REQUIRES: objc_interop
import StdlibUnittest
import Foundation
struct NonObjC {
var x: Int
var y: Foo
}
class Foo: NSObject {
@objc var int: Int { fatalError() }
@objc var bar: Bar { fatalError() }
var nonobjc: NonObjC { fatalError() }
@objc(thisIsADifferentName) var differentName: Bar { fatalError() }
@objc subscript(x: Int) -> Foo { return self }
@objc subscript(x: Bar) -> Foo { return self }
dynamic var dynamic: Bar { fatalError() }
}
class Bar: NSObject {
@objc var foo: Foo { fatalError() }
}
var testKVCStrings = TestSuite("KVC strings")
testKVCStrings.test("KVC strings") {
expectEqual((\NonObjC.x)._kvcKeyPathString, nil)
expectEqual((\NonObjC.y)._kvcKeyPathString, nil)
expectEqual((\Foo.int)._kvcKeyPathString, "int")
expectEqual((\Foo.bar)._kvcKeyPathString, "bar")
expectEqual((\Foo.bar.foo)._kvcKeyPathString, "bar.foo")
expectEqual((\Foo.bar.foo.bar)._kvcKeyPathString, "bar.foo.bar")
expectEqual((\Foo.nonobjc)._kvcKeyPathString, nil)
expectEqual((\Foo.bar.foo.nonobjc.y)._kvcKeyPathString, nil)
expectEqual((\Foo.differentName)._kvcKeyPathString, "thisIsADifferentName")
expectEqual((\Bar.foo)._kvcKeyPathString, "foo")
let foo_bar = \Foo.bar
let foo_nonobjc = \Foo.nonobjc
let bar_foo = \Bar.foo
let nonobjc_y = \NonObjC.y
do {
let foo_bar_foo = foo_bar.appending(path: bar_foo)
expectEqual(foo_bar_foo._kvcKeyPathString, "bar.foo")
let foo_bar_foo_bar = foo_bar_foo.appending(path: foo_bar)
expectEqual(foo_bar_foo_bar._kvcKeyPathString, "bar.foo.bar")
}
do {
let bar_foo_bar = bar_foo.appending(path: foo_bar)
expectEqual(bar_foo_bar._kvcKeyPathString, "foo.bar")
}
do {
let bar_foo_nonobjc = bar_foo.appending(path: foo_nonobjc)
expectEqual(bar_foo_nonobjc._kvcKeyPathString, nil)
}
do {
let nonobjc_y_bar = nonobjc_y.appending(path: foo_bar)
expectEqual(nonobjc_y_bar._kvcKeyPathString, nil)
}
do {
let foo_nonobjc_y = foo_nonobjc.appending(path: nonobjc_y)
expectEqual(foo_nonobjc_y._kvcKeyPathString, nil)
}
}
testKVCStrings.test("identification by selector") {
let foo_dynamic = \Foo.dynamic
let bar_foo = \Bar.foo
let foo_dynamic_foo = \Foo.dynamic.foo
expectEqual(foo_dynamic.appending(path: bar_foo), foo_dynamic_foo)
}
runAllTests()
| 29.654762 | 93 | 0.720193 |
4b2eda63b7fc10f1dccc820d497ace821669ee73 | 6,920 | //
// ViewController.swift
// UdacityMap
//
// Created by Mauricio Chirino on 22/7/17.
// Copyright © 2017 3CodeGeeks. All rights reserved.
//
import UIKit
class CredentialsController: UIViewController {
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var loginButton: ButtonStyle!
@IBOutlet weak var waitingVisualEffect: UIVisualEffectView!
override func viewDidLoad() {
super.viewDidLoad()
passwordTextField.enablesReturnKeyAutomatically = true
emailTextField.enablesReturnKeyAutomatically = true
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissKeyboardAction)))
// emailTextField.text = "[email protected]"
// passwordTextField.text = "QnkYyXRu4Z0is2mFFuffgpdQLPR0ssN8jI"
}
@IBAction func loginAction() {
performLogin()
}
@IBAction func signUpAction(_ sender: Any) {
UIApplication.shared.open(URL(string: Constants.URL.SignUp)!, options: [:], completionHandler: nil)
}
// Only when both textfileds are populated will login button be enabled
func enableLogin(_ textField: UITextField) {
textField.returnKeyType = textField == emailTextField && passwordTextField.text!.isEmpty ? .next : .go
loginButton.isEnabled = !passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
func performLogin() {
view.endEditing(true)
setWaitingView(isOn: true, waitingVisualEffect: self.waitingVisualEffect, view: self.view)
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
// Quick question: Is this the proper form to prevent a retain cycle in here? 👉🏽 [unowned self]
[unowned self] in
let jsonPayload = "{\"udacity\": {\"username\": \"\(self.emailTextField.text!)\", \"password\": \"\(self.passwordTextField.text!)\"}}"
Networking.sharedInstance().taskForPOSTMethod(host: true, path: Constants.Path.SignIn, parameters: [:], jsonBody: jsonPayload) {
(results, error) in
if let error = error {
print(error)
DispatchQueue.main.async {
setWaitingView(isOn: false, waitingVisualEffect: self.waitingVisualEffect, view: self.view)
if error.code == 403 {
self.present(UdacityMap.getPopupAlert(message: Constants.ErrorMessages.credentials), animated: true)
} else {
self.present(UdacityMap.getPopupAlert(message: Constants.ErrorMessages.internetConnection), animated: true)
}
}
} else {
guard let JSONresponse = results else { return }
Networking.sharedInstance().sessionID = JSONresponse[Constants.JSONResponseKeys.Session]![Constants.JSONResponseKeys.UserID] as? String
Networking.sharedInstance().userID = Int(JSONresponse[Constants.JSONResponseKeys.Account]![Constants.JSONResponseKeys.Key] as! String)
UserDefaults.standard.set(Networking.sharedInstance().userID ?? 0, forKey: Constants.Session.AccountKey)
UserDefaults.standard.set(Networking.sharedInstance().sessionID ?? "user-token", forKey: Constants.Session.Id)
Networking.sharedInstance().taskForGETMethod(host: false, path: Constants.Path.Students, parameters: ["where": "{\"uniqueKey\":\"\(Networking.sharedInstance().userID ?? 0)\"}" as AnyObject], jsonBody: "") {
(results, error) in
guard let jsonResultArray = results![Constants.JSONResponseKeys.results] as! [[String : AnyObject]]? else { print(error.debugDescription); return }
if !jsonResultArray.isEmpty {
Networking.sharedInstance().name = jsonResultArray[0][Constants.JSONResponseKeys.name] as! String
Networking.sharedInstance().lastName = jsonResultArray[0][Constants.JSONResponseKeys.lastName] as! String
UserDefaults.standard.set(Networking.sharedInstance().name, forKey: Constants.JSONResponseKeys.name)
UserDefaults.standard.set(Networking.sharedInstance().lastName, forKey: Constants.JSONResponseKeys.lastName)
}
}
DispatchQueue.main.async {
self.performSegue(withIdentifier: Constants.Storyboard.loginSegue, sender: nil)
self.passwordTextField.text = ""
self.emailTextField.text = ""
setWaitingView(isOn: false, waitingVisualEffect: self.waitingVisualEffect, view: self.view)
}
}
}
}
}
//# Keyboard events and handling
func keyboardWillShow(_ notification:Notification) {
if view.frame.origin.y >= 0 {
view.frame.origin.y -= getKeyboardHeight(notification)
}
}
func keyboardWillHide(_ notification:Notification) {
if view.frame.origin.y < 0 {
view.frame.origin.y += getKeyboardHeight(notification)
}
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.cgRectValue.height
}
func dismissKeyboardAction() {
view.endEditing(true)
}
}
extension CredentialsController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == emailTextField && passwordTextField.text!.isEmpty {
passwordTextField.becomeFirstResponder()
} else if textField == emailTextField && !passwordTextField.text!.isEmpty {
performLogin()
}
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
enableLogin(textField)
}
func textFieldDidEndEditing(_ textField: UITextField) {
enableLogin(textField)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
enableLogin(textField)
return true
}
}
| 48.732394 | 226 | 0.637861 |
eb28f11815e22ec3a17aab94a548a39c79725b84 | 1,770 | //
// Presenter.swift
//
//
// Created by Franklyn Weber on 20/02/2021.
//
import SwiftUI
class Presenter {
private static var window: UIWindow?
private static var viewController: UIViewController?
private static var presenting: [String: Binding<Bool>] = [:]
static func present<Content>(for id: String, isPresented: Binding<Bool>, style: PopoverStyle<Content>) {
guard let appWindow = UIApplication.window else {
return
}
guard window == nil else {
return
}
UIApplication.endEditing()
presenting[id] = isPresented
let popoverViewController = PopoverViewController(for: id, style: style)
if let windowScene = appWindow.windowScene {
let newWindow = UIWindow(windowScene: windowScene)
newWindow.rootViewController = popoverViewController
window = newWindow
window?.alpha = 0
window?.makeKeyAndVisible()
UIView.animate(withDuration: 0.3) {
window?.alpha = 1
}
viewController = popoverViewController
popoverViewController.present()
}
}
static func dismiss(for id: String) {
guard window != nil, presenting[id] != nil else {
return
}
UIView.animate(withDuration: 0.3) {
window?.alpha = 0
viewController?.view.alpha = 0
} completion: { _ in
window = nil
viewController = nil
presenting[id]?.wrappedValue = false
presenting.removeValue(forKey: id)
}
}
}
| 26.029412 | 108 | 0.538983 |
6936452d231666ba7287384c60f6f99ec5a127a2 | 863 | //
// AgileLifeTableViewCell.swift
// AgileLife
//
// Created by Zachary Gover on 4/12/16.
// Copyright © 2016 Full Sail University. All rights reserved.
//
import UIKit
class AgileLifeTableViewCell: UITableViewCell {
/* ==========================================
*
* MARK: Outlet Connections
*
* =========================================== */
@IBOutlet weak var menuItem: UILabel!
/* ==========================================
*
* MARK: Default Methods
*
* =========================================== */
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
}
}
| 21.575 | 65 | 0.482039 |
bfcdc735ff95add8549f1ee95da88fbb9e7fe4f3 | 113 | import XCTest
import LoStikTests
var tests = [XCTestCaseEntry]()
tests += LoStikTests.allTests()
XCTMain(tests) | 16.142857 | 31 | 0.778761 |
bfbaaca1bf553420b8763a456de36a9b10fe1594 | 853 | //
// BattleResultViewController.swift
// Roshambo
//
// Created by Leonardo Vinicius Kaminski Ferreira on 09/09/17.
// Copyright © 2017 Leonardo Ferreira. All rights reserved.
//
import UIKit
class BattleResultViewController: UIViewController {
@IBOutlet weak var winnerImage: UIImageView!
@IBOutlet weak var winnerLabel: UILabel!
var winnerMessage: String!
var winnerImageName: String!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
winnerLabel.text = winnerMessage
winnerImage.image = UIImage(named: winnerImageName)
}
// MARK: - Actions
@IBAction func playAgainPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
| 21.871795 | 63 | 0.66823 |
db6d6b93023e758ee49b1ca60d1c28d5404bf3f8 | 322 | //
// Service.swift
// SharedFreamwork
//
// Created by Vahagn Gevorgyan on 15/09/2018.
// Copyright © 2018 Vahagn Gevorgyan. All rights reserved.
//
import Foundation
public class Service {
private init() {}
public static func doSomething() -> String {
return "Do some staff"
}
}
| 16.1 | 59 | 0.624224 |
b9a043cb8e344a9edb87d7a6cecf502d4c6b5c80 | 9,912 | // Download.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
dispatch_sync(queue) {
downloadTask = self.session.downloadTaskWithRequest(request)
}
case .ResumeData(let resumeData):
dispatch_sync(queue) {
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
}
}
let request = Request(session: session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
return destination(URL, downloadTask.response as! NSHTTPURLResponse)
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a download request for the specified method, URL string, parameters, parameter encoding, headers
and destination.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter parameters: The parameters. `nil` by default.
- parameter encoding: The parameter encoding. `.URL` by default.
- parameter headers: The HTTP headers. `nil` by default.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The created download request.
*/
public func download(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil,
destination: Request.DownloadFileDestination)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
return download(encodedURLRequest, destination: destination)
}
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for
additional information.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
// MARK: -
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary
file written to during the download process. The closure takes two arguments: the temporary file URL and the URL
response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a
file URL in the first available directory with the specified search path directory and search path domain mask.
- parameter directory: The search path directory. `.DocumentDirectory` by default.
- parameter domain: The search path domain mask. `.UserDomainMask` by default.
- returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(
directory directory: NSSearchPathDirectory = .DocumentDirectory,
domain: NSSearchPathDomainMask = .UserDomainMask)
-> DownloadFileDestination
{
return { temporaryURL, response -> NSURL in
let directoryURLs = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)
if !directoryURLs.isEmpty {
return directoryURLs[0].URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
/// The resume data of the underlying download task if available after a failure.
public var resumeData: NSData? {
var data: NSData?
if let delegate = delegate as? DownloadTaskDelegate {
data = delegate.resumeData
}
return data
}
// MARK: - DownloadTaskDelegate
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return resumeData }
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)?
var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
do {
let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
try NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination)
} catch {
self.error = error as NSError
}
}
}
func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
}
func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
}
| 40.457143 | 121 | 0.666263 |
5d485bbffb421ba13911905d18a0b085a3ffbd7b | 3,658 | // Copyright (C) 2019 Parrot Drones SAS
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// * Neither the name of the Parrot Company nor the names
// of its contributors may be used to endorse or promote products
// derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// PARROT COMPANY 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
import GroundSdk
/// Base class of a device controller delegate that managed one or more components
public class DeviceComponentController: NSObject {
/// Whether or not the managed device is connected.
var connected: Bool {
return deviceController.connectionSession.state == .connected
}
/// Device controller owning this component controller
internal unowned let deviceController: DeviceController
/// Constructor
///
/// - Parameter deviceController: device controller owning this component controller (weak)
init(deviceController: DeviceController) {
self.deviceController = deviceController
super.init()
}
/// Device has been discovered by arsdk
func didAppear() {
}
/// Device has been removed by arsdk
func didDisappear () {
}
/// Device is about to be forgotten
func willForget() {
}
/// Device is about to be connect
func willConnect() {
}
/// Device is connected
func didConnect() {
}
/// Device is about to be disconnected
func willDisconnect() {
}
/// Device is disconnected
func didDisconnect() {
}
/// Link to the device has been lost
func didLoseLink() {
}
/// Preset has been changed
func presetDidChange() {
}
/// Data synchronization allowance changed.
///
/// - Note: this function is only called while the device is connected (i.e. after `didConnect`). If the data sync
/// was allowed, this callback will be called one last time right after the `didDisconnect`.
func dataSyncAllowanceChanged(allowed: Bool) {
}
/// A command has been received
///
/// - Parameter command: received command
func didReceiveCommand(_ command: OpaquePointer) {
}
/// Send a command to the device
///
/// - Parameter encoder: encoder of the command to send
func sendCommand(_ encoder: @escaping ((OpaquePointer) -> Int32)) {
deviceController.sendCommand(encoder)
}
}
| 33.87037 | 118 | 0.688628 |
754e46c6bb365ac4ef950e2e1154f1773646e867 | 521 | //
// ButtonSettingsViewModel.swift
// ButtonMenuPopup
//
// Created by HanJin on 2017. 3. 27..
// Copyright © 2017년 DavidJinHan. All rights reserved.
//
import Foundation
import RxSwift
class ButtonSettingViewModel {
static let shared = ButtonSettingViewModel()
var onSetting: Variable<Bool>!
private let disposeBag = DisposeBag()
private init() {
onSetting = Variable(false)
}
func settingValueChange() {
onSetting.value = !onSetting.value
}
}
| 18.607143 | 55 | 0.650672 |
e2f5b5e0cc01411409765187948bb13afc7e9b20 | 5,112 | import Foundation
internal final class DictionaryUnkeyedDecodingContainer:
UnkeyedDecodingContainer,
DictionaryComponentDecoder {
// MARK: - Instance Properties
internal let components: [Any?]
internal let options: DictionaryDecodingOptions
internal let userInfo: [CodingUserInfoKey: Any]
internal let codingPath: [CodingKey]
internal private(set) var currentIndex = 0
internal var count: Int? {
components.count
}
internal var isAtEnd: Bool {
currentIndex == count
}
// MARK: - Initializers
internal init(
components: [Any?],
options: DictionaryDecodingOptions,
userInfo: [CodingUserInfoKey: Any],
codingPath: [CodingKey]
) {
self.components = components
self.options = options
self.userInfo = userInfo
self.codingPath = codingPath
}
// MARK: - Instance Methods
private func popNextComponent<T>(of type: T.Type = T.self) throws -> T {
guard currentIndex < components.count else {
let errorContext = DecodingError.Context(
codingPath: codingPath.appending(AnyCodingKey(currentIndex)),
debugDescription: "Unkeyed container is at end."
)
throw DecodingError.valueNotFound(type, errorContext)
}
let anyComponent = components[currentIndex]
guard let component = anyComponent as? T else {
throw DecodingError.invalidComponent(
anyComponent,
at: codingPath.appending(AnyCodingKey(currentIndex)),
expectation: type
)
}
currentIndex += 1
return component
}
// MARK: -
internal func decodeNil() throws -> Bool {
decodeNilComponent(try popNextComponent())
}
internal func decode(_ type: Bool.Type) throws -> Bool {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: Int.Type) throws -> Int {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: Int8.Type) throws -> Int8 {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: Int16.Type) throws -> Int16 {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: Int32.Type) throws -> Int32 {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: Int64.Type) throws -> Int64 {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: UInt.Type) throws -> UInt {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: UInt8.Type) throws -> UInt8 {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: UInt16.Type) throws -> UInt16 {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: UInt32.Type) throws -> UInt32 {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: UInt64.Type) throws -> UInt64 {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: Double.Type) throws -> Double {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: Float.Type) throws -> Float {
try decodeComponentValue(try popNextComponent())
}
internal func decode(_ type: String.Type) throws -> String {
try decodeComponentValue(try popNextComponent())
}
internal func decode<T: Decodable>(_ type: T.Type) throws -> T {
try decodeComponentValue(try popNextComponent(), as: type)
}
internal func nestedContainer<NestedKey: CodingKey>(
keyedBy keyType: NestedKey.Type
) throws -> KeyedDecodingContainer<NestedKey> {
return try superDecoder().container(keyedBy: keyType)
}
internal func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
return try superDecoder().unkeyedContainer()
}
internal func superDecoder() throws -> Decoder {
let decoder = DictionarySingleValueDecodingContainer(
component: try popNextComponent(),
options: options,
userInfo: userInfo,
codingPath: codingPath.appending(AnyCodingKey(currentIndex))
)
return decoder
}
}
private extension DecodingError {
// MARK: - Type Methods
static func invalidComponent(
_ component: Any?,
at codingPath: [CodingKey],
expectation: Any.Type
) -> DecodingError {
let typeDescription: String
switch component {
case let component?:
typeDescription = "\(type(of: component))"
case nil:
typeDescription = "nil"
}
let debugDescription = "Expected to decode \(expectation) but found \(typeDescription) instead."
return .typeMismatch(expectation, Context(codingPath: codingPath, debugDescription: debugDescription))
}
}
| 28.881356 | 110 | 0.646127 |
e468cf5e601d358c646c61df29b417d31f775e64 | 1,356 | //
// AppDelegate.swift
// Tip Calculator
//
// Created by Justin Schwartz on 6/12/21.
//
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.648649 | 179 | 0.746313 |
46e369759f624ab36ad76a052ab5103fdd4a399c | 894 | //
// OpenLockCell.swift
// MsdGateLock
//
// Created by ox o on 2017/6/14.
// Copyright © 2017年 xiaoxiao. All rights reserved.
//
import UIKit
class OpenLockCell: UITableViewCell {
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var openStyleLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
//取消选中
self.selectionStyle = .none
userNameLabel.textColor = kRGBColorFromHex(rgbValue: 0x9d9d9d)
openStyleLabel.textColor = kRGBColorFromHex(rgbValue: 0x9d9d9d)
timeLabel.textColor = kRGBColorFromHex(rgbValue: 0x9d9d9d)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 24.833333 | 71 | 0.671141 |
e268981c9bbd8abbdd3fd1173231beea87c2f621 | 429 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "StickySlider",
platforms: [
.iOS(.v10),
],
products: [
.library(name: "StickySlider", targets: ["StickySlider"])
],
targets: [
.target(name: "StickySlider")
],
swiftLanguageVersions: [.v5]
)
| 22.578947 | 96 | 0.631702 |
50b6071062932b0b9ff27cebd9572eedcf69ea65 | 870 | //
// SwifTumblrTests.swift
// SwifTumblr_Tests
//
// Created by Takahashi Yosuke on 2017/10/04.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import XCTest
import SwifTumblr
class SwifTumblrTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testGetBlog() {
let expect = expectation(description: "getBlog")
var blog: Blog?
SwifTumblr.getBlog(
URLString: "http://ysn-blog.tumblr.com/api/read",
success: { b in
blog = b
expect.fulfill() },
failure: { _ in XCTFail() })
wait(for: [expect], timeout: 5.0)
XCTAssertNotNil(blog?.posts)
XCTAssertGreaterThan(blog!.posts!.count, 0)
}
}
| 21.219512 | 61 | 0.541379 |
0a780d453112ee7dca646abd071aed31678ca11b | 2,591 | //
// LXFViewModel.swift
// RxSwiftDemo
//
// Created by 林洵锋 on 2017/9/7.
// Copyright © 2017年 LXF. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
enum LXFRefreshStatus {
case none
case beingHeaderRefresh
case endHeaderRefresh
case beingFooterRefresh
case endFooterRefresh
case noMoreData
}
class LXFViewModel: NSObject {
// 存放着解析完成的模型数组
let models = Variable<[LXFModel]>([])
// 记录当前的索引值
var index: Int = 1
}
extension LXFViewModel: LXFViewModelType {
typealias Input = LXFInput
typealias Output = LXFOutput
struct LXFInput {
// 网络请求类型
let category: LXFNetworkTool.LXFNetworkCategory
init(category: LXFNetworkTool.LXFNetworkCategory) {
self.category = category
}
}
struct LXFOutput {
// tableView的sections数据
let sections: Driver<[LXFSection]>
// 外界通过该属性告诉viewModel加载数据(传入的值是为了标志是否重新加载)
let requestCommond = PublishSubject<Bool>()
// 告诉外界的tableView当前的刷新状态
let refreshStatus = Variable<LXFRefreshStatus>(.none)
init(sections: Driver<[LXFSection]>) {
self.sections = sections
}
}
func transform(input: LXFViewModel.LXFInput) -> LXFViewModel.LXFOutput {
let sections = models.asObservable().map { (models) -> [LXFSection] in
// 当models的值被改变时会调用
return [LXFSection(items: models)]
}.asDriver(onErrorJustReturn: [])
let output = LXFOutput(sections: sections)
output.requestCommond.subscribe(onNext: {[unowned self] isReloadData in
self.index = isReloadData ? 1 : self.index+1
lxfNetTool.rx.request(.data(type: input.category, size: 10, index: self.index))
.asObservable()
.mapArray(LXFModel.self)
.subscribe({ [weak self] (event) in
switch event {
case let .next(modelArr):
self?.models.value = isReloadData ? modelArr : (self?.models.value ?? []) + modelArr
LXFProgressHUD.showSuccess("加载成功")
case let .error(error):
LXFProgressHUD.showError(error.localizedDescription)
case .completed:
output.refreshStatus.value = isReloadData ? .endHeaderRefresh : .endFooterRefresh
}
}).disposed(by: self.rx.disposeBag)
}).disposed(by: rx.disposeBag)
return output
}
}
| 29.781609 | 108 | 0.590892 |
161564e3cb632702b99e0e5a1a67e95d83818e17 | 988 | //
// BTSwift_MacTests.swift
// BTSwift.MacTests
//
// Created by Eric Patey on 12/29/15.
// Copyright © 2015 Eric Patey. All rights reserved.
//
import XCTest
@testable import BTSwift_Mac
class BTSwift_MacTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.702703 | 111 | 0.637652 |
e99d1d61dd98e7c4edd2f52d33ac4870da6d1b9b | 2,591 | import XCTest
import Quick
import Nimble
import Cuckoo
@testable import Bank_Dev_T
class WordsValidatorTests: QuickSpec {
override func spec() {
let words = ["bmw", "audi", "toyota", "mazda"]
let validator = WordsValidator()
describe("not equal indexes and words count") {
let confirmationWords = ["bmw"]
it("throws invalidConfirmation error") {
expect {
try validator.validate(words: words, confirmationIndexes: [1, 2], confirmationWords: confirmationWords)
}.to(throwError(WordsValidator.ValidationError.invalidConfirmation))
}
}
describe("empty words") {
context("without whitespaces") {
let confirmationWords = ["bmw", ""]
it("throws emptyWords error") {
expect { try validator.validate(words: words, confirmationIndexes: [1, 2], confirmationWords: confirmationWords) }.to(throwError(WordsValidator.ValidationError.emptyWords))
}
}
context("with whitespaces") {
let confirmationWords = ["bmw", " "]
it("throws emptyWords error") {
expect { try validator.validate(words: words, confirmationIndexes: [1, 2], confirmationWords: confirmationWords) }.to(throwError(WordsValidator.ValidationError.emptyWords))
}
}
}
describe("invalid words") {
context("invalid word") {
let confirmationWords = ["renault", "audi"]
it("throws invalidConfirmation error") {
expect { try validator.validate(words: words, confirmationIndexes: [1, 2], confirmationWords: confirmationWords) }.to(throwError(WordsValidator.ValidationError.invalidConfirmation))
}
}
context("invalid order") {
let confirmationWords = ["audi", "bmw"]
it("throws invalidConfirmation error") {
expect { try validator.validate(words: words, confirmationIndexes: [1, 2], confirmationWords: confirmationWords) }.to(throwError(WordsValidator.ValidationError.invalidConfirmation))
}
}
}
describe("valid words") {
let confirmationWords = ["bmw", "audi"]
it("does not throw any errors") {
expect { try validator.validate(words: words, confirmationIndexes: [1, 2], confirmationWords: confirmationWords) }.notTo(throwError())
}
}
}
}
| 37.014286 | 201 | 0.582787 |
33b8dce967662ece8d39182f4b3425b8ee1497ad | 1,465 | //
// DeliveryInteractorTests.swift
// LogisticTests
//
// Created by parvind bhatt on 03/06/19.
// Copyright © 2019 parvind bhatt. All rights reserved.
//
import XCTest
import Quick
import Nimble
@testable import Logistic
class DeliveryInteractorTests: XCTestCase {
let expectationTimeout = 1.0
var mockInteractor: DeliveryInteractor?
let mockDeliveryOutput = MockDeliveryOutputInteractor()
let dataManager = MockDeliveryManager()
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
mockInteractor = DeliveryInteractor()
mockInteractor?.presenter = mockDeliveryOutput
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
mockInteractor = nil
super.tearDown()
}
func testLoadDeliveryList() {
dataManager.failedToLoad = false
dataManager.downloadDeliveryItems(0) { (items, messgae) in
XCTAssertNotNil(items)
XCTAssertFalse(items?.isEmpty ?? true)
}
}
func testLoadDeliveryListWithError() {
dataManager.failedToLoad = true
dataManager.downloadDeliveryItems(0) { (items, messgae) in
XCTAssertNil(items)
XCTAssertNotNil(messgae)
XCTAssertTrue(messgae == "Request Failure")
}
}
}
| 28.173077 | 111 | 0.666212 |
d7cac43b92f45eb7dc84c6ec9b85ebe2216cf3c6 | 536 | //
// SortLeastToGreatest.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
extension Hero {
func sortLeastToGreatest(inventory: [UDItem]) -> [UDItem] {
return inventory.sorted(by: { $0 < $1})
}
}
// If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 5"
| 29.777778 | 235 | 0.690299 |
76f94c1441c5ee29e02799beb1325c42e84f8774 | 1,567 | // Wraps the Configuration options for Parse/Encode/Decode
/// The `Config` struct allows for configuring `Parser` and `Serializer`
/// to allow for separators other than comma or string delimiters
/// like quotation marks
public struct Config {
/// The character that separates one cell from another.
public let cellSeparator: UInt8
/// The character that is used to denote the start and end of a cell's contents.
public let cellDelimiter: UInt8?
/// The deault `Config` instance that uses commas for cell separators and double quotes
/// for cell delimiters.
public static let `default`: Config = Config(cellSeparator: 44, cellDelimiter: 34)
/// Creates a new `Config` instance
///
/// - Parameters:
/// - cellSeparator: The character that separates one cell from another.
/// - cellDelimiter: The character that is used to denote the start and end of a cell's contents.
public init(cellSeparator: UInt8, cellDelimiter: UInt8?) {
self.cellSeparator = cellSeparator
self.cellDelimiter = cellDelimiter
}
/// Creates a new `Config` instance from `UnicdeScalar` literals.
///
/// - Parameters:
/// - separator: The `UnicodeScalar` for the separator between cells (`','`).
/// - delimiter: The `UnicdeScalar` for the delimiter that marks the start and end of a cell (`'"'`).
public init(separator: UnicodeScalar, delimiter: UnicodeScalar) {
self.cellSeparator = UInt8(ascii: separator)
self.cellDelimiter = UInt8(ascii: delimiter)
}
}
| 40.179487 | 107 | 0.684748 |
fefe8fd4d10355af34094037e0ae87771aecb12f | 1,708 | //
// Created by Petr Korolev on 26.10.2020.
//
import Foundation
public struct KdfParamsV3: Decodable, Encodable {
var salt: String
var dklen: Int
var n: Int?
var p: Int?
var r: Int?
var c: Int?
var prf: String?
}
public struct CipherParamsV3: Decodable, Encodable {
var iv: String
}
public struct CryptoParamsV3: Decodable, Encodable {
var ciphertext: String
var cipher: String
var cipherparams: CipherParamsV3
var kdf: String
var kdfparams: KdfParamsV3
var mac: String
var version: String?
}
public protocol AbstractKeystoreParams: Codable {
var crypto: CryptoParamsV3 { get }
var id: String? { get }
var version: Int { get }
var isHDWallet: Bool? { get }
}
public struct KeystoreParamsBIP32: AbstractKeystoreParams {
public var crypto: CryptoParamsV3
public var id: String?
public var version: Int
public var isHDWallet: Bool?
var pathToAddress: [String: String]
var rootPath: String?
public init(crypto cr: CryptoParamsV3, id i: String, version ver: Int = 32, rootPath: String? = nil) {
self.crypto = cr
self.id = i
self.version = ver
pathToAddress = [String: String]()
self.rootPath = rootPath
self.isHDWallet = true
}
}
public struct KeystoreParamsV3: AbstractKeystoreParams {
public var crypto: CryptoParamsV3
public var id: String?
public var version: Int
public var isHDWallet: Bool?
var address: String?
public init(address ad: String?, crypto cr: CryptoParamsV3, id i: String, version ver: Int) {
address = ad
self.crypto = cr
self.id = i
self.version = ver
}
}
| 21.620253 | 106 | 0.65281 |
1c9e7acced775670756f4d0dc5fafc5e68bae721 | 57,967 | //
// BleModule.swift
//
// Created by Konrad Rodzik on 7/4/16.
//
import Foundation
import CoreBluetooth
@objc
public protocol BleClientManagerDelegate {
func dispatchEvent(_ name: String, value: Any)
}
@objc
public class BleClientManager : NSObject {
// Delegate is used to send events to
@objc
public var delegate: BleClientManagerDelegate?
// RxBlutoothKit's manager
private let manager : BluetoothManager
// Dispatch queue used for BLE
private let queue : DispatchQueue
// MARK: Caches ----------------------------------------------------------------------------------------------------
// Map of discovered services in any of connected devices.
private var discoveredServices = [Double: Service]()
// Map of discovered characteristics in any of connected devices.
private var discoveredCharacteristics = [Double: Characteristic]()
// Map of discovered descriptors in any of connected devices.
private var discoveredDescriptors = [Double: Descriptor]()
// Map of currently connected peripherals.
private var connectedPeripherals = Dictionary<UUID, Peripheral>()
// Map of monitored characteristics observables. For monitoring sharing.
private var monitoredCharacteristics = Dictionary<Double, Observable<Characteristic>>()
// MARK: Disposables -----------------------------------------------------------------------------------------------
// Disposable for detecting state changes of BleManager
private var stateDisposable = Disposables.create()
// Disposable for detecing state restoration of BleManager.
private var restorationDisposable = Disposables.create()
// Scan disposable which is removed when new scan is created.
private let scanDisposable = SerialDisposable()
// Disposable map for connecting peripherals.
private let connectingPeripherals = DisposableMap<UUID>()
// Disposable map for every transaction.
private let transactions = DisposableMap<String>()
// Map of pending read operations.
private var pendingReads = Dictionary<Double, Int>()
// Constants
static let cccdUUID = CBUUID(string: "2902")
// MARK: Lifecycle -------------------------------------------------------------------------------------------------
@objc
public init(queue: DispatchQueue, restoreIdentifierKey: String?) {
self.queue = queue
if let key = restoreIdentifierKey {
manager = BluetoothManager(queue: queue,
options: [CBCentralManagerOptionRestoreIdentifierKey: key as AnyObject])
} else {
manager = BluetoothManager(queue: queue)
}
super.init()
stateDisposable = manager.rx_state.subscribe(onNext: { [weak self] newState in
self?.onStateChange(newState)
})
if restoreIdentifierKey != nil {
restorationDisposable = Observable<RestoredState?>.amb([
manager.rx_state.skip(1).map { _ in nil },
manager.listenOnRestoredState().map { $0 as RestoredState? }
])
.take(1)
.subscribe(onNext: {[weak self] newRestoredState in
self?.onRestoreState(newRestoredState)
})
}
}
@objc
public func invalidate() {
// Disposables
stateDisposable.dispose()
restorationDisposable.dispose()
scanDisposable.disposable = Disposables.create()
transactions.dispose()
connectingPeripherals.dispose()
// Caches
discoveredServices.removeAll()
discoveredCharacteristics.removeAll()
discoveredDescriptors.removeAll()
monitoredCharacteristics.removeAll()
connectedPeripherals.forEach { (_, device) in
_ = device.cancelConnection().subscribe()
}
connectedPeripherals.removeAll()
pendingReads.removeAll()
}
deinit {
// We don't use deinit to deinitialize BleClientManager. User
// should call invalidate() before destruction of this object.
// In such case observables can call [weak self] closures properly.
}
// Mark: Common ----------------------------------------------------------------------------------------------------
// User is able to cancel any "atomic" operation which is contained in transactions map.
@objc
public func cancelTransaction(_ transactionId: String) {
transactions.removeDisposable(transactionId)
}
// User is able to enable logging of RxBluetoothKit to show how real device responds.
@objc
public func setLogLevel(_ logLevel: String) {
RxBluetoothKitLog.setLogLevel(RxBluetoothKitLog.LogLevel(jsObject: logLevel))
}
// User can retrieve current log level.
@objc
public func logLevel(_ resolve: Resolve, reject: Reject) {
resolve(RxBluetoothKitLog.getLogLevel().asJSObject)
}
// Mark: Monitoring state ------------------------------------------------------------------------------------------
@objc
public func enable(_ transactionId: String, resolve: Resolve, reject: Reject) {
BleError(errorCode: .BluetoothStateChangeFailed).callReject(reject)
}
@objc
public func disable(_ transactionId: String, resolve: Resolve, reject: Reject) {
BleError(errorCode: .BluetoothStateChangeFailed).callReject(reject)
}
// Retrieve current BleManager's state.
@objc
public func state(_ resolve: Resolve, reject: Reject) {
resolve(manager.state.asJSObject)
}
// Dispatch events when state changes.
private func onStateChange(_ state: BluetoothState) {
dispatchEvent(BleEvent.stateChangeEvent, value: state.asJSObject)
}
// Restore internal manager state.
private func onRestoreState(_ restoredState: RestoredState?) {
// When restored state is null then application is run for the first time.
guard let restoredState = restoredState else {
dispatchEvent(BleEvent.restoreStateEvent, value: NSNull())
return
}
// When state is to be restored update all caches.
restoredState.peripherals.forEach { peripheral in
connectedPeripherals[peripheral.identifier] = peripheral
_ = manager.monitorDisconnection(for: peripheral)
.take(1)
.subscribe(
onNext: { [weak self] peripheral in
self?.onPeripheralDisconnected(peripheral)
},
onError: { [weak self] error in
self?.onPeripheralDisconnected(peripheral)
})
peripheral.services?.forEach { service in
discoveredServices[service.jsIdentifier] = service
service.characteristics?.forEach { characteristic in
discoveredCharacteristics[characteristic.jsIdentifier] = characteristic
}
}
}
dispatchEvent(BleEvent.restoreStateEvent, value: restoredState.asJSObject)
}
// Mark: Scanning --------------------------------------------------------------------------------------------------
// Start BLE scanning.
@objc
public func startDeviceScan(_ filteredUUIDs: [String]?, options:[String:AnyObject]?) {
// iOS handles allowDuplicates option to receive more scan records.
var rxOptions = [String:Any]()
if let options = options {
if ((options["allowDuplicates"]?.isEqual(to: NSNumber(value: true as Bool))) ?? false) {
rxOptions[CBCentralManagerScanOptionAllowDuplicatesKey] = true
}
}
// If passed iOS will show only devices with specified service UUIDs.
var uuids: [CBUUID]? = nil
if let filteredUUIDs = filteredUUIDs {
guard let cbuuids = filteredUUIDs.toCBUUIDS() else {
dispatchEvent(BleEvent.scanEvent, value: BleError.invalidIdentifiers(filteredUUIDs).toJSResult)
return
}
uuids = cbuuids
}
// Scanning will emit Scan peripherals as events.
scanDisposable.disposable = manager.scanForPeripherals(withServices: uuids, options: rxOptions)
.subscribe(onNext: { [weak self] scannedPeripheral in
self?.dispatchEvent(BleEvent.scanEvent, value: [NSNull(), scannedPeripheral.asJSObject])
}, onError: { [weak self] errorType in
self?.dispatchEvent(BleEvent.scanEvent, value: errorType.bleError.toJSResult)
})
}
// Stop BLE scanning.
@objc
public func stopDeviceScan() {
scanDisposable.disposable = Disposables.create()
}
// Read peripheral's RSSI.
@objc
public func readRSSIForDevice(_ deviceIdentifier: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier) else {
BleError.invalidIdentifiers(deviceIdentifier).callReject(reject)
return
}
guard let peripheral = connectedPeripherals[deviceId] else {
BleError.peripheralNotConnected(deviceIdentifier).callReject(reject)
return
}
let safePromise = SafePromise(resolve: resolve, reject: reject)
let disposable = peripheral.readRSSI()
.subscribe(
onNext: { (peripheral, rssi) in
safePromise.resolve(peripheral.asJSObject(withRssi: rssi))
},
onError: {error in
error.bleError.callReject(safePromise)
},
onCompleted: nil,
onDisposed: { [weak self] in
self?.transactions.removeDisposable(transactionId)
BleError.cancelled().callReject(safePromise)
})
transactions.replaceDisposable(transactionId, disposable: disposable)
}
@objc
public func requestMTUForDevice(_ deviceIdentifier: String,
mtu: Int,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier) else {
BleError.invalidIdentifiers(deviceIdentifier).callReject(reject)
return
}
guard let peripheral = connectedPeripherals[deviceId] else {
BleError.peripheralNotConnected(deviceIdentifier).callReject(reject)
return
}
resolve(peripheral.asJSObject())
}
@objc
public func requestConnectionPriorityForDevice(_ deviceIdentifier: String,
connectionPriority: Int,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier) else {
BleError.invalidIdentifiers(deviceIdentifier).callReject(reject)
return
}
guard let peripheral = connectedPeripherals[deviceId] else {
BleError.peripheralNotConnected(deviceIdentifier).callReject(reject)
return
}
resolve(peripheral.asJSObject())
}
// Mark: Device management -----------------------------------------------------------------------------------------
@objc
public func devices(_ deviceIdentifiers: [String],
resolve: @escaping Resolve,
reject: @escaping Reject) {
let uuids = deviceIdentifiers.compactMap { UUID(uuidString: $0) }
if (uuids.count != deviceIdentifiers.count) {
BleError.invalidIdentifiers(deviceIdentifiers).callReject(reject)
return
}
_ = manager.retrievePeripherals(withIdentifiers: uuids)
.subscribe(
onNext: { peripherals in
resolve(peripherals.map { $0.asJSObject() })
},
onError: { error in
error.bleError.callReject(reject)
}
);
}
@objc
public func connectedDevices(_ serviceUUIDs: [String],
resolve: @escaping Resolve,
reject: @escaping Reject) {
let uuids = serviceUUIDs.compactMap { $0.toCBUUID() }
if (uuids.count != serviceUUIDs.count) {
BleError.invalidIdentifiers(serviceUUIDs).callReject(reject)
return
}
_ = manager.retrieveConnectedPeripherals(withServices: uuids)
.subscribe(
onNext: { peripherals in
resolve(peripherals.map { $0.asJSObject() })
},
onError: { error in
error.bleError.callReject(reject)
}
);
}
// Mark: Connection management -------------------------------------------------------------------------------------
// Connect to specified device.
@objc
public func connectToDevice(_ deviceIdentifier: String,
options:[String: AnyObject]?,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier) else {
BleError.invalidIdentifiers(deviceIdentifier).callReject(reject)
return
}
var timeout: Int? = nil
if let options = options {
timeout = options["timeout"] as? Int
}
safeConnectToDevice(deviceId, timeout: timeout, promise: SafePromise(resolve: resolve, reject: reject))
}
private func safeConnectToDevice(_ deviceId: UUID,
timeout: Int?,
promise: SafePromise) {
var connectionObservable = manager.retrievePeripherals(withIdentifiers: [deviceId])
.flatMap { devices -> Observable<Peripheral> in
guard let device = devices.first else {
return Observable.error(BleError.peripheralNotFound(deviceId.uuidString))
}
return Observable.just(device)
}
.flatMap { $0.connect() }
if let timeout = timeout {
connectionObservable = connectionObservable.timeout(Double(timeout) / 1000.0, scheduler: ConcurrentDispatchQueueScheduler(queue: queue))
}
var peripheralToConnect : Peripheral? = nil
let connectionDisposable = connectionObservable
.subscribe(
onNext: { [weak self] peripheral in
// When device is connected we save it in dectionary and clear all old cached values.
peripheralToConnect = peripheral
self?.connectedPeripherals[deviceId] = peripheral
self?.clearCacheForPeripheral(peripheral: peripheral)
},
onError: { [weak self] error in
if let rxerror = error as? RxError,
let peripheralToConnect = peripheralToConnect,
let strongSelf = self,
case RxError.timeout = rxerror {
_ = strongSelf.manager.cancelPeripheralConnection(peripheralToConnect).subscribe()
}
error.bleError.callReject(promise)
},
onCompleted: { [weak self] in
if let device = self?.connectedPeripherals[deviceId] {
_ = self?.manager.monitorDisconnection(for: device)
.take(1)
.subscribe(onNext: { peripheral in
// We are monitoring peripheral disconnections to clean up state.
self?.onPeripheralDisconnected(peripheral)
}, onError: { error in
self?.onPeripheralDisconnected(device)
})
promise.resolve(device.asJSObject())
} else {
BleError.peripheralNotFound(deviceId.uuidString).callReject(promise)
}
},
onDisposed: { [weak self] in
self?.connectingPeripherals.removeDisposable(deviceId)
BleError.cancelled().callReject(promise)
}
);
connectingPeripherals.replaceDisposable(deviceId, disposable: connectionDisposable)
}
private func onPeripheralDisconnected(_ peripheral: Peripheral) {
self.connectedPeripherals[peripheral.identifier] = nil
clearCacheForPeripheral(peripheral: peripheral)
dispatchEvent(BleEvent.disconnectionEvent, value: [NSNull(), peripheral.asJSObject()])
}
// User is able to cancel device connection.
@objc
public func cancelDeviceConnection(_ deviceIdentifier: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier) else {
BleError.invalidIdentifiers(deviceIdentifier).callReject(reject)
return
}
if let peripheral = connectedPeripherals[deviceId] {
_ = peripheral
.cancelConnection()
.subscribe(
onNext: nil,
onError: { error in
error.bleError.callReject(reject)
},
onCompleted: { [weak self] in
self?.clearCacheForPeripheral(peripheral: peripheral)
self?.connectedPeripherals[deviceId] = nil
resolve(peripheral.asJSObject())
}
);
} else {
connectingPeripherals.removeDisposable(deviceId)
BleError.cancelled().callReject(reject)
}
}
// Retrieve if device is connected.
@objc
public func isDeviceConnected(_ deviceIdentifier: String, resolve: Resolve, reject: Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier) else {
BleError.invalidIdentifiers(deviceIdentifier).callReject(reject)
return
}
if let device = connectedPeripherals[deviceId] {
resolve(device.isConnected)
} else {
resolve(false)
}
}
// Mark: Discovery -------------------------------------------------------------------------------------------------
// After connection for peripheral to be usable,
// user should discover all services and characteristics for peripheral.
@objc
public func discoverAllServicesAndCharacteristicsForDevice(_ deviceIdentifier: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier) else {
BleError.invalidIdentifiers(deviceIdentifier).callReject(reject)
return
}
guard let peripheral = connectedPeripherals[deviceId] else {
BleError.peripheralNotConnected(deviceIdentifier).callReject(reject)
return
}
safeDiscoverAllServicesAndCharacteristicsForDevice(peripheral, transactionId: transactionId, promise: SafePromise(resolve: resolve, reject: reject))
}
func safeDiscoverAllServicesAndCharacteristicsForDevice(_ peripheral: Peripheral,
transactionId: String,
promise: SafePromise) {
let disposable = peripheral
.discoverServices(nil)
.flatMap { [weak self] services -> Observable<Service> in
for service in services {
self?.discoveredServices[service.jsIdentifier] = service
}
return Observable.from(services)
}
.flatMap { $0.discoverCharacteristics(nil) }
.flatMap { [weak self] characteristics -> Observable<Characteristic> in
for characteristic in characteristics {
self?.discoveredCharacteristics[characteristic.jsIdentifier] = characteristic
}
return Observable.from(characteristics)
}
.flatMap { $0.discoverDescriptors() }
.subscribe(
onNext: { [weak self] descriptors in
for descriptor in descriptors {
self?.discoveredDescriptors[descriptor.jsIdentifier] = descriptor
}
},
onError: { error in error.bleError.callReject(promise) },
onCompleted: { promise.resolve(peripheral.asJSObject()) },
onDisposed: { [weak self] in
self?.transactions.removeDisposable(transactionId)
BleError.cancelled().callReject(promise)
}
)
transactions.replaceDisposable(transactionId, disposable: disposable)
}
// Mark: Service and characteristic getters ------------------------------------------------------------------------
// When fetching services for peripherals we update our cache.
@objc
public func servicesForDevice(_ deviceIdentifier: String, resolve: Resolve, reject: Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier) else {
BleError.invalidIdentifiers(deviceIdentifier).callReject(reject)
return
}
guard let peripheral = connectedPeripherals[deviceId] else {
BleError.peripheralNotConnected(deviceIdentifier).callReject(reject)
return
}
let services = peripheral
.services?.map { [weak self] service in
self?.discoveredServices[service.jsIdentifier] = service
return service.asJSObject
} ?? []
resolve(services)
}
// When fetching characteristics for peripherals we update our cache.
@objc
public func characteristicsForDevice(_ deviceIdentifier: String,
serviceUUID: String,
resolve: Resolve,
reject: Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier),
let serviceId = serviceUUID.toCBUUID() else {
BleError.invalidIdentifiers([deviceIdentifier, serviceUUID]).callReject(reject)
return
}
guard let peripheral = connectedPeripherals[deviceId] else {
BleError.peripheralNotConnected(deviceIdentifier).callReject(reject)
return
}
guard let service = (peripheral.services?.first { serviceId == $0.uuid }) else {
BleError.serviceNotFound(serviceUUID).callReject(reject)
return
}
characteristicForService(service,
resolve: resolve,
reject: reject)
}
@objc
public func characteristicsForService(_ serviceIdentifier: Double,
resolve: Resolve,
reject: Reject) {
guard let service = discoveredServices[serviceIdentifier] else {
BleError.serviceNotFound(serviceIdentifier.description).callReject(reject)
return
}
characteristicForService(service, resolve: resolve, reject: reject)
}
private func characteristicForService(_ service: Service, resolve: Resolve, reject: Reject) {
let characteristics = service.characteristics?
.map { [weak self] characteristic in
self?.discoveredCharacteristics[characteristic.jsIdentifier] = characteristic
return characteristic.asJSObject
} ?? []
resolve(characteristics)
}
@objc
public func descriptorsForDevice(_ deviceIdentifier: String,
serviceUUID: String,
characteristicUUID: String,
resolve: Resolve,
reject: Reject) {
guard let deviceId = UUID(uuidString: deviceIdentifier),
let serviceId = serviceUUID.toCBUUID(),
let characteristicId = characteristicUUID.toCBUUID() else {
BleError.invalidIdentifiers([deviceIdentifier, serviceUUID, characteristicUUID]).callReject(reject)
return
}
guard let peripheral = connectedPeripherals[deviceId] else {
BleError.peripheralNotConnected(deviceIdentifier).callReject(reject)
return
}
guard let service = (peripheral.services?.first { serviceId == $0.uuid }) else {
BleError.serviceNotFound(serviceUUID).callReject(reject)
return
}
guard let characteristic = (service.characteristics?.first { characteristicId == $0.uuid }) else {
BleError.characteristicNotFound(characteristicUUID).callReject(reject)
return
}
descriptorsForCharacteristic(characteristic, resolve: resolve, reject: reject)
}
@objc
public func descriptorsForService(_ serviceIdentifier: Double,
characteristicUUID: String,
resolve: Resolve,
reject: Reject) {
guard let characteristicId = characteristicUUID.toCBUUID() else {
BleError.invalidIdentifiers(characteristicUUID).callReject(reject)
return
}
guard let service = discoveredServices[serviceIdentifier] else {
BleError.serviceNotFound(serviceIdentifier.description).callReject(reject)
return
}
guard let characteristic = (service.characteristics?.first { characteristicId == $0.uuid }) else {
BleError.characteristicNotFound(characteristicUUID).callReject(reject)
return
}
descriptorsForCharacteristic(characteristic, resolve: resolve, reject: reject)
}
@objc
public func descriptorsForCharacteristic(_ characteristicIdentifier: Double,
resolve: Resolve,
reject: Reject) {
guard let characteristic = discoveredCharacteristics[characteristicIdentifier] else {
BleError.characteristicNotFound(characteristicIdentifier.description).callReject(reject)
return
}
descriptorsForCharacteristic(characteristic, resolve: resolve, reject: reject)
}
private func descriptorsForCharacteristic(_ characteristic: Characteristic, resolve: Resolve, reject: Reject) {
let descriptors = characteristic.descriptors?
.map { [weak self] descriptor in
self?.discoveredDescriptors[descriptor.jsIdentifier] = descriptor
return descriptor.asJSObject
} ?? []
resolve(descriptors)
}
// Mark: Reading ---------------------------------------------------------------------------------------------------
@objc
public func readCharacteristicForDevice(_ deviceIdentifier: String,
serviceUUID: String,
characteristicUUID: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
let observable = getCharacteristicForDevice(deviceIdentifier,
serviceUUID: serviceUUID,
characteristicUUID: characteristicUUID)
safeReadCharacteristicForDevice(observable,
transactionId: transactionId,
promise: SafePromise(resolve: resolve, reject: reject))
}
@objc
public func readCharacteristicForService(_ serviceIdentifier: Double,
characteristicUUID: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
let observable = getCharacteristicForService(serviceIdentifier,
characteristicUUID: characteristicUUID)
safeReadCharacteristicForDevice(observable,
transactionId: transactionId,
promise: SafePromise(resolve: resolve, reject: reject))
}
@objc
public func readCharacteristic(_ characteristicIdentifier: Double,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
safeReadCharacteristicForDevice(getCharacteristic(characteristicIdentifier),
transactionId: transactionId,
promise: SafePromise(resolve: resolve, reject: reject))
}
private func safeReadCharacteristicForDevice(_ characteristicObservable: Observable<Characteristic>,
transactionId: String,
promise: SafePromise) {
var characteristicIdentifier: Double? = nil
let disposable = characteristicObservable
.flatMap { [weak self] characteristic -> Observable<Characteristic> in
characteristicIdentifier = characteristic.jsIdentifier
let reads = self?.pendingReads[characteristic.jsIdentifier] ?? 0
self?.pendingReads[characteristic.jsIdentifier] = reads + 1
return characteristic.readValue()
}
.subscribe(
onNext: { characteristic in
promise.resolve(characteristic.asJSObject)
},
onError: { error in
error.bleError.callReject(promise)
},
onCompleted: nil,
onDisposed: { [weak self] in
self?.transactions.removeDisposable(transactionId)
BleError.cancelled().callReject(promise)
if let id = characteristicIdentifier {
let reads = self?.pendingReads[id] ?? 0
if reads > 0 {
self?.pendingReads[id] = reads - 1
}
}
}
)
transactions.replaceDisposable(transactionId, disposable: disposable)
}
// MARK: Writing ---------------------------------------------------------------------------------------------------
@objc
public func writeCharacteristicForDevice( _ deviceIdentifier: String,
serviceUUID: String,
characteristicUUID: String,
valueBase64: String,
response: Bool,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let value = valueBase64.fromBase64 else {
return BleError.invalidWriteDataForCharacteristic(characteristicUUID, data: valueBase64).callReject(reject)
}
let observable = getCharacteristicForDevice(deviceIdentifier,
serviceUUID: serviceUUID,
characteristicUUID: characteristicUUID)
safeWriteCharacteristicForDevice(observable,
value: value,
response: response,
transactionId: transactionId,
promise: SafePromise(resolve: resolve, reject: reject))
}
@objc
public func writeCharacteristicForService( _ serviceIdentifier: Double,
characteristicUUID: String,
valueBase64: String,
response: Bool,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let value = valueBase64.fromBase64 else {
return BleError.invalidWriteDataForCharacteristic(characteristicUUID, data: valueBase64).callReject(reject)
}
let observable = getCharacteristicForService(serviceIdentifier,
characteristicUUID: characteristicUUID)
safeWriteCharacteristicForDevice(observable,
value: value,
response: response,
transactionId: transactionId,
promise: SafePromise(resolve: resolve, reject: reject))
}
@objc
public func writeCharacteristic( _ characteristicIdentifier: Double,
valueBase64: String,
response: Bool,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let value = valueBase64.fromBase64 else {
return BleError.invalidWriteDataForCharacteristic(characteristicIdentifier.description, data: valueBase64)
.callReject(reject)
}
safeWriteCharacteristicForDevice(getCharacteristic(characteristicIdentifier),
value: value,
response: response,
transactionId: transactionId,
promise: SafePromise(resolve: resolve, reject: reject))
}
private func safeWriteCharacteristicForDevice(_ characteristicObservable: Observable<Characteristic>,
value: Data,
response: Bool,
transactionId: String,
promise: SafePromise) {
let disposable = characteristicObservable
.flatMap {
$0.writeValue(value, type: response ? .withResponse : .withoutResponse)
}
.subscribe(
onNext: { characteristic in
promise.resolve(characteristic.asJSObject)
},
onError: { error in
error.bleError.callReject(promise)
},
onCompleted: nil,
onDisposed: { [weak self] in
self?.transactions.removeDisposable(transactionId)
BleError.cancelled().callReject(promise)
}
)
transactions.replaceDisposable(transactionId, disposable: disposable)
}
// MARK: Monitoring ------------------------------------------------------------------------------------------------
@objc
public func monitorCharacteristicForDevice( _ deviceIdentifier: String,
serviceUUID: String,
characteristicUUID: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
let observable = getCharacteristicForDevice(deviceIdentifier,
serviceUUID: serviceUUID,
characteristicUUID: characteristicUUID)
safeMonitorCharacteristicForDevice(observable,
transactionId: transactionId,
promise: SafePromise(resolve: resolve, reject: reject))
}
@objc
public func monitorCharacteristicForService( _ serviceIdentifier: Double,
characteristicUUID: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
let observable = getCharacteristicForService(serviceIdentifier, characteristicUUID: characteristicUUID)
safeMonitorCharacteristicForDevice(observable,
transactionId: transactionId,
promise: SafePromise(resolve: resolve, reject: reject))
}
@objc
public func monitorCharacteristic( _ characteristicIdentifier: Double,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
safeMonitorCharacteristicForDevice(getCharacteristic(characteristicIdentifier),
transactionId: transactionId,
promise: SafePromise(resolve: resolve, reject: reject))
}
private func safeMonitorCharacteristicForDevice(_ characteristicObservable: Observable<Characteristic>,
transactionId: String,
promise: SafePromise) {
let observable: Observable<Characteristic> = characteristicObservable
.flatMap { [weak self] (characteristic: Characteristic) -> Observable<Characteristic> in
let characteristicIdentifier = characteristic.jsIdentifier
if let monitoringObservable = self?.monitoredCharacteristics[characteristicIdentifier] {
return monitoringObservable
} else {
let newObservable: Observable<Characteristic> = characteristic
.setNotificationAndMonitorUpdates()
.do(onNext: nil, onError: nil, onCompleted: nil, onSubscribe: nil, onDispose: {
_ = characteristic.setNotifyValue(false).subscribe()
self?.monitoredCharacteristics[characteristicIdentifier] = nil
})
.share()
self?.monitoredCharacteristics[characteristicIdentifier] = newObservable
return newObservable
}
}
let disposable = observable.subscribe(
onNext: { [weak self] characteristic in
if self?.pendingReads[characteristic.jsIdentifier] ?? 0 == 0 {
self?.dispatchEvent(BleEvent.readEvent, value: [NSNull(), characteristic.asJSObject, transactionId])
}
}, onError: { [weak self] error in
self?.dispatchEvent(BleEvent.readEvent, value: [error.bleError.toJS, NSNull(), transactionId])
}, onCompleted: {
}, onDisposed: { [weak self] in
self?.transactions.removeDisposable(transactionId)
promise.resolve(nil)
})
transactions.replaceDisposable(transactionId, disposable: disposable)
}
// MARK: Getting characteristics -----------------------------------------------------------------------------------
private func getCharacteristicForDevice(_ deviceId: String,
serviceUUID: String,
characteristicUUID: String) -> Observable<Characteristic> {
return Observable.create { [weak self] observer in
guard let peripheralId = UUID(uuidString: deviceId) else {
observer.onError(BleError.peripheralNotFound(deviceId))
return Disposables.create()
}
guard let serviceCBUUID = serviceUUID.toCBUUID() else {
observer.onError(BleError.invalidIdentifiers(serviceUUID))
return Disposables.create()
}
guard let characteristicCBUUID = characteristicUUID.toCBUUID() else {
observer.onError(BleError.invalidIdentifiers(characteristicUUID))
return Disposables.create()
}
guard let peripheral = self?.connectedPeripherals[peripheralId] else {
observer.onError(BleError.peripheralNotConnected(deviceId))
return Disposables.create()
}
guard let characteristic = (peripheral.services?
.first { $0.uuid == serviceCBUUID }?
.characteristics?
.first { $0.uuid == characteristicCBUUID }) else {
observer.onError(BleError.characteristicNotFound(characteristicUUID))
return Disposables.create()
}
observer.onNext(characteristic)
observer.onCompleted()
return Disposables.create()
}
}
private func getCharacteristicForService(_ serviceId: Double,
characteristicUUID: String) -> Observable<Characteristic> {
return Observable.create { [weak self] observer in
guard let characteristicCBUUID = characteristicUUID.toCBUUID() else {
observer.onError(BleError.invalidIdentifiers(characteristicUUID))
return Disposables.create()
}
guard let service = self?.discoveredServices[serviceId] else {
observer.onError(BleError.serviceNotFound(serviceId.description))
return Disposables.create()
}
guard let characteristic = (service
.characteristics?
.first { $0.uuid == characteristicCBUUID }) else {
observer.onError(BleError.characteristicNotFound(characteristicUUID))
return Disposables.create()
}
observer.onNext(characteristic)
observer.onCompleted()
return Disposables.create()
}
}
private func getCharacteristic(_ characteristicId: Double) -> Observable<Characteristic> {
return Observable.create { [weak self] observer in
guard let characteristic = self?.discoveredCharacteristics[characteristicId] else {
observer.onError(BleError.characteristicNotFound(characteristicId.description))
return Disposables.create()
}
observer.onNext(characteristic)
observer.onCompleted()
return Disposables.create()
}
}
// MARK: Descriptors -----------------------------------------------------------------------------------------------
private func getDescriptorForDevice(_ deviceId: String,
serviceUUID: String,
characteristicUUID: String,
descriptorUUID: String) -> Observable<Descriptor> {
return getDescriptorByUUID(descriptorUUID, characteristicObservable: getCharacteristicForDevice(deviceId, serviceUUID: serviceUUID, characteristicUUID: characteristicUUID))
}
private func getDescriptorForService(_ serviceId: Double,
characteristicUUID: String,
descriptorUUID: String) -> Observable<Descriptor> {
return getDescriptorByUUID(descriptorUUID, characteristicObservable: getCharacteristicForService(serviceId, characteristicUUID: characteristicUUID))
}
private func getDescriptorForCharacteristic(_ characteristicId: Double,
descriptorUUID: String) -> Observable<Descriptor> {
return getDescriptorByUUID(descriptorUUID, characteristicObservable: getCharacteristic(characteristicId))
}
private func getDescriptorByUUID(_ descriptorUUID: String, characteristicObservable: Observable<Characteristic>) -> Observable<Descriptor> {
guard let descriptorCBUUID = descriptorUUID.toCBUUID() else {
return Observable.error(BleError.invalidIdentifiers(descriptorUUID))
}
return characteristicObservable.flatMap { characteristic -> Observable<Descriptor> in
guard let descriptor = (characteristic.descriptors?.first { $0.uuid == descriptorCBUUID }) else {
return Observable.error(BleError.descriptorNotFound(descriptorUUID))
}
return Observable.just(descriptor)
}
}
private func getDescriptorByID(_ descriptorId: Double) -> Observable<Descriptor> {
return Observable.create { [weak self] observer in
guard let descriptor = self?.discoveredDescriptors[descriptorId] else {
observer.onError(BleError.descriptorNotFound(descriptorId.description))
return Disposables.create()
}
observer.onNext(descriptor)
observer.onCompleted()
return Disposables.create()
}
}
private func safeReadDescriptor(_ descriptorObservable: Observable<Descriptor>,
transactionId: String,
promise: SafePromise) {
let disposable = descriptorObservable
.flatMap { descriptor -> Observable<Descriptor> in
return descriptor.readValue()
}
.subscribe(
onNext: { descriptor in
promise.resolve(descriptor.asJSObject)
},
onError: { error in
error.bleError.callReject(promise)
},
onCompleted: nil,
onDisposed: { [weak self] in
self?.transactions.removeDisposable(transactionId)
BleError.cancelled().callReject(promise)
}
)
transactions.replaceDisposable(transactionId, disposable: disposable)
}
@objc
public func readDescriptorForDevice(_ deviceIdentifier: String,
serviceUUID: String,
characteristicUUID: String,
descriptorUUID: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
let descriptor = getDescriptorForDevice(deviceIdentifier,
serviceUUID: serviceUUID,
characteristicUUID: characteristicUUID,
descriptorUUID: descriptorUUID)
safeReadDescriptor(descriptor,
transactionId: transactionId,
promise: SafePromise.init(resolve: resolve, reject: reject))
}
@objc
public func readDescriptorForService(_ serviceId: Double,
characteristicUUID: String,
descriptorUUID: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
let descriptor = getDescriptorForService(serviceId,
characteristicUUID: characteristicUUID,
descriptorUUID: descriptorUUID)
safeReadDescriptor(descriptor,
transactionId: transactionId,
promise: SafePromise.init(resolve: resolve, reject: reject))
}
@objc
public func readDescriptorForCharacteristic(_ characteristicID: Double,
descriptorUUID: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
let descriptor = getDescriptorForCharacteristic(characteristicID, descriptorUUID: descriptorUUID)
safeReadDescriptor(descriptor,
transactionId: transactionId,
promise: SafePromise.init(resolve: resolve, reject: reject))
}
@objc
public func readDescriptor(_ descriptorID: Double,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
safeReadDescriptor(getDescriptorByID(descriptorID),
transactionId: transactionId,
promise: SafePromise.init(resolve: resolve, reject: reject))
}
private func safeWriteDescriptor(_ descriptorObservable: Observable<Descriptor>,
transactionId: String,
value: Data,
promise: SafePromise) {
let disposable = descriptorObservable
.flatMap { descriptor -> Observable<Descriptor> in
if descriptor.uuid.isEqual(BleClientManager.cccdUUID) {
return Observable.error(BleError.descriptorWriteNotAllowed(descriptor.uuid.fullUUIDString))
}
return descriptor.writeValue(value)
}
.subscribe(
onNext: { descriptor in
promise.resolve(descriptor.asJSObject)
},
onError: { error in
error.bleError.callReject(promise)
},
onCompleted: nil,
onDisposed: { [weak self] in
self?.transactions.removeDisposable(transactionId)
BleError.cancelled().callReject(promise)
}
)
transactions.replaceDisposable(transactionId, disposable: disposable)
}
@objc
public func writeDescriptorForDevice(_ deviceIdentifier: String,
serviceUUID: String,
characteristicUUID: String,
descriptorUUID: String,
valueBase64: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let value = valueBase64.fromBase64 else {
return BleError.invalidWriteDataForDescriptor(descriptorUUID, data: valueBase64).callReject(reject)
}
let descriptor = getDescriptorForDevice(deviceIdentifier,
serviceUUID: serviceUUID,
characteristicUUID: characteristicUUID,
descriptorUUID: descriptorUUID)
safeWriteDescriptor(descriptor,
transactionId: transactionId,
value: value,
promise: SafePromise(resolve: resolve, reject: reject))
}
@objc
public func writeDescriptorForService(_ serviceID: Double,
characteristicUUID: String,
descriptorUUID: String,
valueBase64: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let value = valueBase64.fromBase64 else {
return BleError.invalidWriteDataForDescriptor(descriptorUUID, data: valueBase64).callReject(reject)
}
let descriptor = getDescriptorForService(serviceID,
characteristicUUID: characteristicUUID,
descriptorUUID: descriptorUUID)
safeWriteDescriptor(descriptor,
transactionId: transactionId,
value: value,
promise: SafePromise(resolve: resolve, reject: reject))
}
@objc
public func writeDescriptorForCharacteristic(_ characteristicID: Double,
descriptorUUID: String,
valueBase64: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let value = valueBase64.fromBase64 else {
return BleError.invalidWriteDataForDescriptor(descriptorUUID, data: valueBase64).callReject(reject)
}
let descriptor = getDescriptorForCharacteristic(characteristicID, descriptorUUID: descriptorUUID)
safeWriteDescriptor(descriptor,
transactionId: transactionId,
value: value,
promise: SafePromise(resolve: resolve, reject: reject))
}
@objc
public func writeDescriptor(_ descriptorID: Double,
valueBase64: String,
transactionId: String,
resolve: @escaping Resolve,
reject: @escaping Reject) {
guard let value = valueBase64.fromBase64 else {
return BleError.invalidWriteDataForDescriptor(descriptorID.description, data: valueBase64).callReject(reject)
}
safeWriteDescriptor(getDescriptorByID(descriptorID),
transactionId: transactionId,
value: value,
promise: SafePromise(resolve: resolve, reject: reject))
}
// MARK: Private interface -----------------------------------------------------------------------------------------
private func clearCacheForPeripheral(peripheral: Peripheral) {
for (key, value) in discoveredDescriptors {
if value.characteristic.service.peripheral == peripheral {
discoveredDescriptors[key] = nil
}
}
for (key, value) in discoveredCharacteristics {
if value.service.peripheral == peripheral {
discoveredCharacteristics[key] = nil
}
}
for (key, value) in discoveredServices {
if value.peripheral == peripheral {
discoveredServices[key] = nil
}
}
}
private func dispatchEvent(_ event: String, value: Any) {
delegate?.dispatchEvent(event, value: value)
}
}
| 45.251366 | 180 | 0.525851 |
db79a521616dff73482079829e326d835f8c081a | 847 | //
// MockData.swift
// LLDB
//
// Created by Clarence Ji on 6/6/19.
// Copyright © 2019 Clarence Ji. All rights reserved.
//
import UIKit
import SwiftUI
import CoreLocation
let lineData: [Line] = load("lineData.json")
func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
| 23.527778 | 79 | 0.599764 |
2869e81ddde412af00f6b1f67651e258219dbc4a | 675 | //
// BlockUnBlockCardRequester.swift
// ChargeBack
//
// Created by Antoine Barrault on 21/03/2017.
// Copyright © 2017 Antoine Barrault. All rights reserved.
//
import Foundation
class BlockUnBlockCardRequester: EndpointRequester {
typealias DataReturnedInRequest = ChargeBackAPI.Actions
var currentTask: URLSessionTask?
var action: ChargeBackAPI.Actions
var completion: ((DataReturnedInRequest?, String?) -> Void)?
var postCompletion: ((Bool, String?) -> Void)?
required init(action: ChargeBackAPI.Actions) {
self.action = action
}
func parseJson(json: [String: Any]) {
//no need of parse because is a post
}
}
| 25 | 64 | 0.697778 |
48b8e14afc064545aede4dd01baea1e5d4138899 | 2,338 | //
// CroucherComponent.swift
// glide
//
// Copyright (c) 2019 cocoatoucher user on github.com (https://github.com/cocoatoucher/)
//
// 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 GameplayKit
/// Component that gives an entity the ability to ignore one way grounds while
/// its entity is above them and pass through below the ground.
/// This component is also used by `PlayableCharacterComponent` which makes
/// it possible to react to crouching via assigning a custom texture animation.
public final class CroucherComponent: GKComponent, GlideComponent {
public static let componentPriority: Int = 670
/// `true` if the entity was crouching in the last frame.
public private(set) var didCrouch: Bool = false
/// `true` if the entity is crouching in the current frame.
public var crouches: Bool = false
public override func update(deltaTime seconds: TimeInterval) {
if crouches {
entity?.component(ofType: ColliderComponent.self)?.pushesDown = true
transform?.proposedPosition = (transform?.currentPosition ?? .zero) - CGPoint(x: 0, y: 1)
}
}
}
extension CroucherComponent: StateResettingComponent {
public func resetStates() {
didCrouch = crouches
crouches = false
}
}
| 41.75 | 101 | 0.725406 |
38ad04745319ab1fc1e51f07ef0b5f267c3c03ef | 3,243 | //
// String+Extensions.swift
// p2p wallet
//
// Created by Chung Tran on 10/23/20.
//
import Foundation
import Down
extension Optional where Wrapped == String {
public var orEmpty: String {
self ?? ""
}
static func + (left: String?, right: String?) -> String {
left.orEmpty + right.orEmpty
}
var double: Double? {
guard let string = self else { return nil }
return string.double
}
}
extension String {
var firstCharacter: String {
String(prefix(1))
}
public var uppercaseFirst: String {
firstCharacter.uppercased() + String(dropFirst())
}
public func onlyUppercaseFirst() -> String {
lowercased().uppercaseFirst
}
subscript(bounds: CountableClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start...end])
}
subscript(bounds: CountableRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start..<end])
}
// swiftlint:disable swiftgen_strings
func localized() -> String {
NSLocalizedString(self, comment: "")
}
// swiftlint:enable swiftgen_strings
func truncatingMiddle(numOfSymbolsRevealed: Int = 4, numOfSymbolsRevealedInSuffix: Int? = nil) -> String {
if count <= numOfSymbolsRevealed + (numOfSymbolsRevealedInSuffix ?? numOfSymbolsRevealed) { return self }
return prefix(numOfSymbolsRevealed) + "..." + suffix(numOfSymbolsRevealedInSuffix ?? numOfSymbolsRevealed)
}
func withNameServiceDomain() -> String {
self + Self.nameServiceDomain
}
static var nameServiceDomain: String {
".p2p.sol"
}
static func secretConfig(_ key: String) -> String? {
Bundle.main.infoDictionary?[key] as? String
}
}
extension String {
var double: Double? {
let formatter = NumberFormatter()
formatter.locale = Locale.current // USA: Locale(identifier: "en_US")
formatter.numberStyle = .decimal
formatter.locale = Locale.current
return formatter.number(from: self)?.doubleValue
}
}
extension String {
func asMarkdown(textSize: CGFloat? = nil, textColor: UIColor? = nil) -> NSAttributedString {
let down = Down(markdownString: self)
let fonts = StaticFontCollection(
body: UIFont.systemFont(ofSize: textSize ?? 15)
)
let colors = StaticColorCollection(
body: textColor ?? UIColor.textBlack
)
var paragraph = StaticParagraphStyleCollection()
paragraph.body = {
let p = NSMutableParagraphStyle()
p.lineSpacing = 0
return p
}()
return (try? down.toAttributedString(styler: DownStyler(
configuration: DownStylerConfiguration(
fonts: fonts,
colors: colors,
paragraphStyles: paragraph
))
)) ?? NSAttributedString()
}
}
| 28.699115 | 114 | 0.610237 |
f5eb79516581f02b5dfe55f3c7346a6f1354b8f4 | 1,530 | //
// Copyright (c) 2018. Uber Technologies
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import os.signpost
fileprivate let perfLog = OSLog(subsystem: "mockolo", category: "PointsOfInterest")
public var minLogLevel = 0
/// Logs status and other messages depending on the level provided
public enum LogLevel: Int {
case verbose
case info
case warning
case error
}
public func log(_ arg: Any..., level: LogLevel = .info) {
guard level.rawValue >= minLogLevel else { return }
switch level {
case .info, .verbose:
print(arg)
case .warning:
print("WARNING: \(arg)")
case .error:
print("ERROR: \(arg)")
}
}
public func signpost_begin(name: StaticString) {
if minLogLevel == LogLevel.verbose.rawValue {
os_signpost(.begin, log: perfLog, name: name)
}
}
public func signpost_end(name: StaticString) {
if minLogLevel == LogLevel.verbose.rawValue {
os_signpost(.end, log: perfLog, name: name)
}
}
| 27.818182 | 83 | 0.687582 |
6ade30ea10e2f5dd2d017050bb98e2288116162b | 175 | //
// AssetsAlbumLayout.swift
// Pods
//
// Created by DragonCherry on 5/18/17.
//
//
import UIKit
open class AssetsAlbumLayout: UICollectionViewFlowLayout {
}
| 11.666667 | 58 | 0.668571 |
7a1edc55ebacc0f17a7c19db53f08a369213e554 | 8,518 | //
// WorkspacesViewController.swift
// MarkDownEditor
//
// Created by Koji Murata on 2018/01/17.
// Copyright © 2018年 Koji Murata. All rights reserved.
//
import Cocoa
import RxSwift
import RealmSwift
final class WorkspacesViewController: NSViewController {
private let bag = DisposeBag()
@IBOutlet private weak var tableView: WorkspacesTableView!
@IBOutlet private var defaultMenu: NSMenu!
private var createOrOpenWorkspaceSegment = CreateOrOpenWorkspaceTabViewController.Segment.create
private var lastSelectionRow: Int?
private var selecteSuppression = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.prepare(defaultMenu: defaultMenu)
tableView.registerForDraggedTypes([.workspaceModel, .nodeModel])
tableView.setDraggingSourceOperationMask([.move], forLocal: true)
WorkspaceModel.observableSpaces.map { $0.map { $0.id } }.distinctUntilChanged().subscribe(onNext: { [weak self] _ in
// reloadするときはworkspace.select()をしない。
// writabletransaction内であるせいで、realm関連クラッシュがおきるため
self?.selecteSuppression = true
self?.tableView.reloadData()
DispatchQueue.main.async {
self?.tableView.selectRowIndexes(IndexSet(integer: WorkspaceModel.selectedIndex), byExtendingSelection: false)
}
}).disposed(by: bag)
}
override func viewWillAppear() {
super.viewWillAppear()
NotificationCenter.default.addObserver(self, selector: #selector(moveFocusToWorkspaces), name: .MoveFocusToWorkspaces, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(openWorkspace(_:)), name: .OpenWorkspace, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(createWorkspace), name: .CreateWorkspace, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(selectNextWorkspace), name: .SelectNextWorkspace, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(selectPreviousWorkspace), name: .SelectPreviousWorkspace, object: nil)
}
override func viewWillDisappear() {
super.viewWillDisappear()
NotificationCenter.default.removeObserver(self, name: .MoveFocusToWorkspaces, object: nil)
NotificationCenter.default.removeObserver(self, name: .OpenWorkspace, object: nil)
NotificationCenter.default.removeObserver(self, name: .CreateWorkspace, object: nil)
NotificationCenter.default.removeObserver(self, name: .SelectNextWorkspace, object: nil)
NotificationCenter.default.removeObserver(self, name: .SelectPreviousWorkspace, object: nil)
}
@objc private func moveFocusToWorkspaces() {
view.window?.makeFirstResponder(tableView)
}
@objc private func openWorkspace(_ notification: Notification) {
createOrOpenWorkspaceURL = (notification.object as? URL)?.deletingLastPathComponent()
createOrOpenWorkspaceSegment = .open
createOrOpenWorkspace()
}
private var createOrOpenWorkspaceURL: URL?
@objc private func createWorkspace() {
createOrOpenWorkspaceSegment = .create
createOrOpenWorkspace()
}
private func createOrOpenWorkspace() {
performSegue(withIdentifier: "createOrOpenWorkspace", sender: nil)
}
@objc private func selectNextWorkspace() {
let row = tableView.selectedRow == WorkspaceModel.spaces.count - 1 ? 0 : tableView.selectedRow + 1
tableView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false)
}
@objc private func selectPreviousWorkspace() {
let row = tableView.selectedRow == 0 ? WorkspaceModel.spaces.count - 1 : tableView.selectedRow - 1
tableView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false)
}
override func viewDidAppear() {
super.viewDidAppear()
WorkspaceModel.selectedObservable.subscribe(onNext: { [weak self] _ in
guard let s = self else { return }
if s.tableView.selectedRow == WorkspaceModel.selectedIndex { return }
self?.tableView.selectRowIndexes(IndexSet(integer: WorkspaceModel.selectedIndex), byExtendingSelection: false)
}).disposed(by: bag)
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
switch segue.destinationController {
case let wc as NSWindowController:
switch wc.contentViewController {
case let vc as MoveWorkspaceViewController:
vc.prepare(workspace: WorkspaceModel.spaces[tableView.selectedRow])
case let vc as CreateOrOpenWorkspaceTabViewController:
vc.prepare(segment: createOrOpenWorkspaceSegment, presetUrl: createOrOpenWorkspaceURL)
default: break
}
default: break
}
super.prepare(for: segue, sender: sender)
}
@IBAction private func showInFinder(_ sender: NSMenuItem) {
guard let row = tableView.rowForMenu else { return }
let url = WorkspaceModel.spaces[row].directoryUrl
NSWorkspace.shared.activateFileViewerSelecting([url])
}
@IBAction private func delete(_ sender: NSMenuItem) {
guard let row = tableView.rowForMenu else { return }
if WorkspaceModel.spaces.count <= 1 {
NSAlert(localizedMessageText: "If there is only one workspace, you can not delete it.").runModal()
return
}
let workspace = WorkspaceModel.spaces[row]
workspace.deleteFromSearchableIndex()
let nodes = [NodeModel](workspace.nodes)
Realm.transaction { (realm) in
for node in nodes { node.prepareDelete() }
realm.delete(workspace)
}
WorkspaceModel.reloadSelected()
// ワークスペース削除よりもタイミングを遅らせるとreloaddata出来るようになる
DispatchQueue.main.async {
Realm.transaction { (realm) in
realm.delete(nodes)
}
}
}
@IBAction private func moveTheWorkspaceFile(_ sender: NSMenuItem) {
performSegue(withIdentifier: "moveWorkspace", sender: nil)
}
}
extension WorkspacesViewController: NSTableViewDataSource, NSTableViewDelegate {
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
if row == WorkspaceModel.spaces.count {
createWorkspace()
return false
}
return true
}
func tableViewSelectionDidChange(_ notification: Notification) {
defer { lastSelectionRow = tableView.selectedRow }
if selecteSuppression {
selecteSuppression = false
return
}
guard let lastSelectionRow = lastSelectionRow else { return }
if lastSelectionRow == tableView.selectedRow { return }
WorkspaceModel.spaces[safe: tableView.selectedRow]?.select()
}
func numberOfRows(in tableView: NSTableView) -> Int {
return WorkspaceModel.spaces.count + 1
}
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
return WorkspacesTableRowView()
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if row == WorkspaceModel.spaces.count {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier("CreateWorkspacesTableCellView"), owner: self)
return cell
}
let workspace = WorkspaceModel.spaces[row]
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier("WorkspacesTableCellView"), owner: self) as! WorkspacesTableCellView
cell.prepare(workspace: workspace)
return cell
}
func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {
if row == WorkspaceModel.spaces.count { return nil }
let item = NSPasteboardItem()
item.setString("\(row)", forType: .workspaceModel)
return item
}
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
let nodes = info.draggingPasteboard.nodes
if nodes.count > 0 {
if dropOperation == .on { WorkspaceModel.spaces[safe: row]?.select() }
return []
}
if dropOperation == .on { return [] }
guard let draggingRow = Int(info.draggingPasteboard.string(forType: .workspaceModel) ?? "") else { return [] }
if draggingRow == row || draggingRow == row - 1 { return [] }
if row == WorkspaceModel.spaces.count + 1 { return [] }
return [.move]
}
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
guard let draggingRow = Int(info.draggingPasteboard.string(forType: .workspaceModel) ?? "") else { return false }
WorkspaceModel.move(from: draggingRow, to: row)
return true
}
}
| 39.99061 | 184 | 0.732919 |
e661aef3ff500363f9891bd9bbcb11b6835843af | 511 | //
// CEFPrintDialogCallback.swift
// CEF.swift
//
// Created by Tamas Lustyik on 2015. 08. 16..
// Copyright © 2015. Tamas Lustyik. All rights reserved.
//
import Foundation
public extension CEFPrintDialogCallback {
/// Continue printing with the specified |settings|.
public func doContinue(settings: CEFPrintSettings) {
cefObject.cont(cefObjectPtr, settings.toCEF())
}
/// Cancel the printing.
public func doCancel() {
cefObject.cancel(cefObjectPtr)
}
}
| 20.44 | 57 | 0.675147 |
ffca33a2e4877dfcce70ea715f09b93e354c7fa1 | 2,086 | //
// AppDelegate.swift
// Yelp
//
// Created by Andrew Duck on 14/3/16.
// Copyright © 2016 Andrew Duck. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
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:.
}
}
| 43.458333 | 285 | 0.747363 |
d53d3fa05c8f7a25718739eb7f3b91734f65f7a9 | 627 | //
// MessageViewController.swift
// WeiboSwift
//
// Created by fenglin on 2016/10/2.
// Copyright © 2016年 fenglin. All rights reserved.
//
import UIKit
class MessageViewController: UIViewController {
@IBOutlet var visitorView: OtherVisitorView!
override func viewDidLoad() {
super.viewDidLoad()
print("MessageViewController");
}
}
//MARK:- VisitorView Login && Register Extension
extension MessageViewController {
override func viewWillAppear(_ animated: Bool) {
if !LoginInteractor.shareInstance.isLogined {
self.view = visitorView;
}
}
}
| 19 | 53 | 0.668262 |
7157cbbc446166bdccf7a7cfa427774e1c923785 | 9,389 |
import UIKit
import AVFoundation
public enum PQButtonLayoutType: Int {
case none = 0
case rightText
case leftText
case topText
case bottomText
}
public enum PQButtonAnimationType: Int {
case none = 0
case textScale
case imageScale
case transformScale
}
public class PQButton: UIButton {
// MARK: 公开
public typealias PQButtonBlock = (_ button: PQButton) -> Void
/// 文字和图片的间距
open var spacing: CGFloat = 0
/// 最短长按时间
open var minLongPressDuration: TimeInterval = 0.5
/// 类型
open var type: PQButtonLayoutType = .none
open var animationType: PQButtonAnimationType = .none
/// disable background color
public var disableColor: UIColor?{
didSet{
if let color = disableColor {
let image = UIImage.pq_drawRect(CGSize(width: 2, height: 2), color: color).stretchableImage(withLeftCapWidth: 1, topCapHeight: 1)
setBackgroundImage(image, for: .disabled)
}
}
}
public func buttonClick(_ block: @escaping PQButtonBlock){
clickBlock = block
listenTouchUpInside()
}
public func longPressBlock(_ block: @escaping PQButtonBlock){
longPressBlock = block
createLongPressGesture()
}
// MARK: 私有
public override init(frame: CGRect) {
super.init(frame: frame)
setupAnimation()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupAnimation()
}
override public func layoutSubviews() {
super.layoutSubviews()
guard let title = self.titleLabel?.text as NSString?, let titleFont = self.titleLabel?.font else { return }
let imageSize = self.imageRect(forContentRect: self.frame)
let titleSize = title.size(withAttributes: [NSAttributedString.Key.font : titleFont])
var titleInsets: UIEdgeInsets = self.titleEdgeInsets
var imageInsets: UIEdgeInsets = self.imageEdgeInsets
switch type {
case .leftText:
titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0,
right: -(titleSize.width * 2 + spacing))
case .topText:
titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing),
left: -(imageSize.width), bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
case .bottomText:
titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing),
left: -(imageSize.width), bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
default:
if pq.width < imageSize.width + titleSize.width + spacing {
self.frame.size.width = imageSize.width + titleSize.width + spacing * 2
}
titleInsets = UIEdgeInsets(top: 0, left: spacing*2, bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: -spacing, bottom: 0,
right: 0)
break
}
self.titleEdgeInsets = titleInsets
self.imageEdgeInsets = imageInsets
}
private var longPressGesture: UILongPressGestureRecognizer?
private var timer: DispatchSourceTimer?
private var responseCount: Int = 0
private var clickBlock: PQButtonBlock!
private var longPressBlock: PQButtonBlock!
private var tempImage: UIImage?
private var tempFont: UIFont!
private(set) var tempBackgroundColor: UIColor?
private func setupAnimation(){
addTarget(self, action: #selector(highlight(_:)), for: .touchDown)
addTarget(self, action: #selector(stopAnimation), for: .touchCancel)
addTarget(self, action: #selector(stopAnimation), for: .touchDragOutside)
}
private func createLongPressGesture(){
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressGestureEvent(_:)))
addGestureRecognizer(longPressGesture!)
}
private func clearTimer(){
self.timer?.cancel()
self.timer = nil
}
private func listenTouchUpInside(){
addTarget(self, action: #selector(touchUpInsideEvent(_:)), for: .touchUpInside)
}
private func callback(){
stopAnimation()
if responseCount >= 1 {
if let block = longPressBlock {
/// 震动一下
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
block(self)
}
}else if responseCount == 0{
if let block = clickBlock{
block(self)
}
}
}
}
extension UIImage {
func imageSize(scale: CGFloat) -> UIImage? {
let newSize = CGSize(width: size.width * scale, height: size.height * scale)
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
self.draw(in: CGRect(origin: .zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
@objc extension PQButton {
@objc private func highlight(_ button: PQButton){
switch animationType {
case .none: break
case .textScale:
guard let size = button.titleLabel?.font else { return }
tempFont = size
UIView.animate(withDuration: 0.25, animations: {
button.titleLabel?.font = UIFont.systemFont(ofSize: size.pointSize * 1.2)
}) { (_) in
self.stopAnimation()
}
case .imageScale:
tempImage = currentImage
UIView.animate(withDuration: 0.25, animations: {
button.setImage(button.currentImage?.imageSize(scale: 1.2), for: .normal)
}) { (_) in
self.stopAnimation()
}
case .transformScale:
UIView.animate(withDuration: 0.25, animations: {
button.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}) { (_) in
self.stopAnimation()
}
}
}
@objc private func stopAnimation(){
switch animationType {
case .none: break
case .textScale:
UIView.animate(withDuration: 0.25, animations: {
self.titleLabel?.font = self.tempFont
})
case .imageScale:
UIView.animate(withDuration: 0.25, animations: {
self.setImage(self.tempImage, for: .normal)
})
case .transformScale:
UIView.animate(withDuration: 0.25, animations: {
self.transform = CGAffineTransform.identity
})
}
}
@objc private func longPressGestureEvent(_ gesture: UILongPressGestureRecognizer){
switch gesture.state {
case .began:
responseCount = 0
clearTimer()
self.timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())
timer?.schedule(deadline: .now(), repeating: minLongPressDuration)
timer?.setEventHandler(handler: {[weak self] in
DispatchQueue.main.async {
self?.responseCount += 1
self?.callback()
self?.clearTimer()
}
})
timer?.resume()
default:
break
}
}
@objc private func touchUpInsideEvent(_ button: PQButton){
responseCount = 0
callback()
}
}
// MARK: - convenience init
public extension PQButton {
convenience init(frame: CGRect, title: String?, titleColor: UIColor? = nil, font: UIFont? = nil, backgroundImage: String? = nil, image: String? = nil) {
self.init(frame: frame)
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
if let font = font {
self.titleLabel?.font = font
}
if let backgroundImage = backgroundImage,
!backgroundImage.isEmpty {
self.setBackgroundImage(UIImage(named: backgroundImage), for: .normal)
}
if let image = image,
!image.isEmpty {
self.setImage(UIImage(named: image), for: .normal)
}
}
convenience init(image: String) {
self.init(frame: .zero)
if !image.isEmpty {
self.setImage(UIImage(named: image), for: .normal)
}
}
convenience init (_ type: PQButtonLayoutType = .none){
self.init(type: type, animationType: .none)
}
convenience init (_ animationType: PQButtonAnimationType = .none){
self.init(type: .none, animationType: animationType)
}
convenience init(type: PQButtonLayoutType = .none, animationType: PQButtonAnimationType = .none){
self.init(frame: .zero)
self.type = type
self.animationType = animationType
}
}
| 33.059859 | 156 | 0.581106 |
6a1a8c2e1cb4097df79d607793cba8c4dcca7f03 | 2,704 | import Cocoa
extension NSRect {
struct Corner: CustomStringConvertible {
var x: Alignment = .leading
var y: Alignment = .leading
enum Alignment: CustomStringConvertible {
case leading
case trailing
static var left = Alignment.leading
static var right = Alignment.trailing
static var bottom = Alignment.leading
static var top = Alignment.trailing
var description: String {
switch self {
case .leading: return "leading"
case .trailing: return "trailing"
}
}
}
struct Insets: CustomStringConvertible {
var x: CGFloat = 0
var y: CGFloat = 0
static let zero = Insets(x: 0, y: 0)
var description: String {
return "(x = \(x), y = \(y))"
}
}
var description: String {
return "(x = \(x), y = \(y))"
}
}
func snappedCorner(of screen: NSScreen, with insets: NSRect.Corner.Insets = .zero) -> NSRect.Corner? {
var corner = NSRect.Corner()
if origin.x == screen.visibleFrame.minX + insets.x {
corner.x = .leading
}
else if origin.x == screen.visibleFrame.maxX - (width + insets.x) {
corner.x = .trailing
}
else {
return nil
}
if origin.y == screen.visibleFrame.minY + insets.y {
corner.y = .leading
}
else if origin.y == screen.visibleFrame.maxY - (height + insets.y) {
corner.y = .trailing
}
else {
return nil
}
return corner
}
func preferredCorner(for screen: NSScreen) -> NSRect.Corner {
var corner = NSRect.Corner()
let left = minX - screen.visibleFrame.minX
let right = screen.visibleFrame.maxX - maxX
corner.x = left < right ? .leading : .trailing
let bottom = minY - screen.visibleFrame.minY
let top = screen.visibleFrame.maxY - maxY
corner.y = bottom > top ? .trailing : .leading
return corner
}
func originForSnappingToPreferredCorner(of screen: NSScreen, with insets: NSRect.Corner.Insets = .zero) -> NSPoint {
return size.originForSnapping(to: preferredCorner(for: screen), of: screen, with: insets)
}
func originForSnapping(to corner: NSRect.Corner, of screen: NSScreen, with insets: NSRect.Corner.Insets = .zero) -> NSPoint {
return size.originForSnapping(to: corner, of: screen, with: insets)
}
}
extension NSSize {
func originForSnapping(to corner: NSRect.Corner, of screen: NSScreen, with insets: NSRect.Corner.Insets = .zero) -> NSPoint {
var origin: NSPoint = .zero
switch corner.x {
case .leading: origin.x = screen.visibleFrame.minX + insets.x
case .trailing: origin.x = screen.visibleFrame.maxX - (width + insets.x)
}
switch corner.y {
case .leading: origin.y = screen.visibleFrame.minY + insets.y
case .trailing: origin.y = screen.visibleFrame.maxY - (height + insets.y)
}
return origin
}
}
| 23.719298 | 126 | 0.675666 |
d6695476584e3959bbbf9baf7171c45318e18180 | 691 | //
// BigIntegerTests.swift
// Whalebird
//
// Created by akirafukushima on 2015/02/24.
// Copyright (c) 2015年 AkiraFukushima. All rights reserved.
//
import XCTest
@testable import Whalebird
class BigIntegerTests: XCTestCase {
func testDecrement() {
let zeroNum: String = "572673378139545600"
let nextZeroID: String = BigInteger(string: zeroNum).decrement()
XCTAssertEqual(nextZeroID, "572673378139545599", "decrement success")
let normalNum: String = "572673378139545605"
let nextNormalID: String = BigInteger(string: normalNum).decrement()
XCTAssertEqual(nextNormalID, "572673378139545604", "decrement success")
}
}
| 28.791667 | 79 | 0.700434 |
69a6c45a4e5602e90eb313b118bb1ea7659f974c | 489 | //: # With a tortoise 🐢
//: [👉 With 2 tortoises 🐢🐢](@next)
import PlaygroundSupport
import TortoiseGraphics
import CoreGraphics
let canvas = PlaygroundCanvas(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
canvas.frameRate = 30
canvas.color = .white
PlaygroundPage.current.liveView = canvas
canvas.drawing { turtle in
// Fill color
turtle.fillColor(.red)
//Draw a square
for _ in 1...4 {
turtle.forward(20)
turtle.right(90)
}
}
| 20.375 | 81 | 0.642127 |
0e545ceb4bf51c4bb1a81e3d96ff90e65c4b1173 | 20,274 | //
// WebViewController.swift
// AlliCrab
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
import OnePasswordExtension
import os
import UIKit
import WaniKaniKit
import WebKit
protocol WebViewControllerDelegate: class {
func webViewControllerDidFinish(_ controller: WebViewController)
}
class WebViewController: UIViewController {
class func wrapped(url: URL, configBlock: ((WebViewController) -> Void)? = nil) -> UINavigationController {
let webViewController = self.init(url: url)
configBlock?(webViewController)
let nc = UINavigationController(rootViewController: webViewController)
nc.hidesBarsOnSwipe = true
nc.hidesBarsWhenVerticallyCompact = true
return nc
}
// MARK: - Properties
weak var delegate: WebViewControllerDelegate?
private(set) var webView: WKWebView!
private var url: URL?
private var webViewConfiguration: WKWebViewConfiguration?
private var shouldIncludeDoneButton = false
private var keyValueObservers: [NSKeyValueObservation]?
private lazy var backButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "ArrowLeft"), style: .plain, target: self, action: #selector(backButtonTouched(_:forEvent:)))
private lazy var forwardButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "ArrowRight"), style: .plain, target: self, action: #selector(forwardButtonTouched(_:forEvent:)))
private lazy var shareButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(share(_:)))
private lazy var openInSafariButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "OpenInSafari"), style: .plain, target: self, action: #selector(openInSafari(_:)))
private lazy var doneButton: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(done(_:)))
private lazy var statusBarView: UIView = {
let view = UIBottomBorderedView(frame: UIApplication.shared.statusBarFrame, color: .lightGray, width: 0.5)
view.autoresizingMask = .flexibleWidth
view.backgroundColor = .globalBarTintColor
return view
}()
private lazy var defaultWebViewConfiguration: WKWebViewConfiguration = {
let config = WKWebViewConfiguration()
registerMessageHandlers(config.userContentController)
config.applicationNameForUserAgent = "Mobile AlliCrab"
let delegate = UIApplication.shared.delegate as! AppDelegate
config.ignoresViewportScaleLimits = true
config.mediaTypesRequiringUserActionForPlayback = [.video]
config.processPool = delegate.webKitProcessPool
return config
}()
// MARK: - Initialisers
required init(url: URL) {
super.init(nibName: nil, bundle: nil)
self.url = url
}
required init(configuration: WKWebViewConfiguration) {
super.init(nibName: nil, bundle: nil)
self.webViewConfiguration = configuration
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
// We nil these references out to unregister KVO on WKWebView
self.navigationItem.titleView = nil
keyValueObservers = nil
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// MARK: - Actions
@objc func backButtonTouched(_ sender: UIBarButtonItem, forEvent event: UIEvent) {
guard let touch = event.allTouches?.first else { return }
switch touch.tapCount {
case 0: // Long press
self.showBackForwardList(webView.backForwardList.backList, sender: sender)
case 1: // Tap
self.webView.goBack()
default: break
}
}
@objc func forwardButtonTouched(_ sender: UIBarButtonItem, forEvent event: UIEvent) {
guard let touch = event.allTouches?.first else { return }
switch touch.tapCount {
case 0: // Long press
self.showBackForwardList(webView.backForwardList.forwardList, sender: sender)
case 1: // Tap
self.webView.goForward()
default: break
}
}
@objc func share(_ sender: UIBarButtonItem) {
guard let absoluteURL = webView.url?.absoluteURL else {
return
}
var activityItems: [AnyObject] = [absoluteURL as NSURL]
activityItems.reserveCapacity(2)
let onePasswordExtension = OnePasswordExtension.shared()
if onePasswordExtension.isAppExtensionAvailable() {
onePasswordExtension.createExtensionItem(forWebView: webView!) { extensionItem, error -> Void in
if let error = error {
os_log("Failed to create 1Password extension item: %@", type: .error, error as NSError)
} else if let extensionItem = extensionItem {
activityItems.append(extensionItem)
}
self.presentActivityViewController(activityItems, title: self.webView.title, sender: sender) {
activityType, completed, returnedItems, activityError in
if let error = activityError {
os_log("Activity failed: %@", type: .error, error as NSError)
DispatchQueue.main.async {
self.showAlert(title: "Activity failed", message: error.localizedDescription)
}
return
}
guard completed else {
return
}
if onePasswordExtension.isOnePasswordExtensionActivityType(activityType?.rawValue) {
onePasswordExtension.fillReturnedItems(returnedItems, intoWebView: self.webView!) { success, error in
if !success {
let errorDescription = error?.localizedDescription ?? "(No error details)"
os_log("Failed to fill password from password manager: %@", type: .error, errorDescription)
DispatchQueue.main.async {
self.showAlert(title: "Password fill failed", message: errorDescription)
}
}
}
}
}
}
} else {
presentActivityViewController(activityItems, title: webView.title, sender: sender)
}
}
@objc func openInSafari(_ sender: UIBarButtonItem) {
guard let URL = webView.url else {
return
}
UIApplication.shared.open(URL)
}
@objc func done(_ sender: UIBarButtonItem) {
finish()
}
func showBackForwardList(_ backForwardList: [WKBackForwardListItem], sender: UIBarButtonItem) {
let vc = WebViewBackForwardListTableViewController()
vc.backForwardList = backForwardList
vc.delegate = self
vc.modalPresentationStyle = .popover
if let popover = vc.popoverPresentationController {
popover.delegate = vc
popover.permittedArrowDirections = [.up, .down]
popover.barButtonItem = sender
}
present(vc, animated: true, completion: nil)
}
func presentActivityViewController(_ activityItems: [AnyObject], title: String?, sender: UIBarButtonItem, completionHandler: UIActivityViewController.CompletionWithItemsHandler? = nil) {
let avc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
avc.popoverPresentationController?.barButtonItem = sender;
avc.completionWithItemsHandler = completionHandler
if let title = title {
avc.setValue(title, forKey: "subject")
}
navigationController?.present(avc, animated: true, completion: nil)
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
webView = makeWebView()
keyValueObservers = registerObservers(webView)
self.view.addSubview(webView)
self.view.addSubview(statusBarView)
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: view.topAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
statusBarView.topAnchor.constraint(equalTo: view.topAnchor),
statusBarView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
statusBarView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
if let nc = self.navigationController {
shouldIncludeDoneButton = nc.viewControllers[0] == self
let addressBarView = WebAddressBarView(frame: nc.navigationBar.bounds, forWebView: webView)
self.navigationItem.titleView = addressBarView
}
configureToolbars(for: self.traitCollection)
if let url = self.url {
let request = URLRequest(url: url)
self.webView.load(request)
}
}
private func makeWebView() -> WKWebView {
let webView = WKWebView(frame: .zero, configuration: webViewConfiguration ?? defaultWebViewConfiguration)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
webView.uiDelegate = self
webView.allowsBackForwardNavigationGestures = true
webView.allowsLinkPreview = true
webView.keyboardDisplayDoesNotRequireUserAction()
return webView
}
private func registerObservers(_ webView: WKWebView) -> [NSKeyValueObservation] {
let keyValueObservers = [
webView.observe(\.canGoBack, options: [.initial]) { [weak self] webView, _ in
self?.backButton.isEnabled = webView.canGoBack
},
webView.observe(\.canGoForward, options: [.initial]) { [weak self] webView, _ in
self?.forwardButton.isEnabled = webView.canGoForward
},
webView.observe(\.isLoading, options: [.initial]) { [weak self] webView, _ in
UIApplication.shared.isNetworkActivityIndicatorVisible = webView.isLoading
self?.shareButton.isEnabled = !webView.isLoading && webView.url != nil
},
webView.observe(\.url, options: [.initial]) { [weak self] webView, _ in
let hasURL = webView.url != nil
self?.shareButton.isEnabled = !webView.isLoading && hasURL
self?.openInSafariButton.isEnabled = hasURL
}
]
return keyValueObservers
}
// MARK: - Size class transitions
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
if newCollection.horizontalSizeClass != traitCollection.horizontalSizeClass || newCollection.verticalSizeClass != traitCollection.verticalSizeClass {
configureToolbars(for: newCollection)
}
}
/// Sets the navigation bar and toolbar items based on the given UITraitCollection
func configureToolbars(for traitCollection: UITraitCollection) {
statusBarView.isHidden = traitCollection.verticalSizeClass == .compact
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
addToolbarItemsForCompactWidthRegularHeight()
} else {
addToolbarItemsForAllOtherTraitCollections()
}
}
/// For phone in portrait
func addToolbarItemsForCompactWidthRegularHeight() {
self.navigationController?.setToolbarHidden(false, animated: true)
navigationItem.leftItemsSupplementBackButton = !shouldIncludeDoneButton
navigationItem.leftBarButtonItems = customLeftBarButtonItems
navigationItem.rightBarButtonItems = customRightBarButtonItems
let flexibleSpace = { UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) }
setToolbarItems([backButton, flexibleSpace(), forwardButton, flexibleSpace(), shareButton, flexibleSpace(), openInSafariButton], animated: true)
}
/// For phone in landscape and pad in any orientation
func addToolbarItemsForAllOtherTraitCollections() {
self.navigationController?.setToolbarHidden(true, animated: true)
setToolbarItems(nil, animated: true)
navigationItem.leftItemsSupplementBackButton = !shouldIncludeDoneButton
navigationItem.leftBarButtonItems = customLeftBarButtonItems + [backButton, forwardButton]
navigationItem.rightBarButtonItems = customRightBarButtonItems + [openInSafariButton, shareButton]
}
var customLeftBarButtonItems: [UIBarButtonItem] {
var buttons: [UIBarButtonItem] = []
buttons.reserveCapacity(1)
if shouldIncludeDoneButton {
buttons.append(doneButton)
}
return buttons
}
var customRightBarButtonItems: [UIBarButtonItem] {
var buttons: [UIBarButtonItem] = []
buttons.reserveCapacity(1)
return buttons
}
// MARK: - Implementation
func showBrowserInterface(_ shouldShowBrowserInterface: Bool, animated: Bool) {
guard let nc = self.navigationController else { return }
nc.setNavigationBarHidden(!shouldShowBrowserInterface, animated: animated)
if self.toolbarItems?.isEmpty == false {
nc.setToolbarHidden(!shouldShowBrowserInterface, animated: animated)
}
}
func finish() {
unregisterMessageHandlers(webView.configuration.userContentController)
delegate?.webViewControllerDidFinish(self)
dismiss(animated: true, completion: nil)
}
func registerMessageHandlers(_ userContentController: WKUserContentController) {
}
func unregisterMessageHandlers(_ userContentController: WKUserContentController) {
}
}
// MARK: - WebViewBackForwardListTableViewControllerDelegate
extension WebViewController: WebViewBackForwardListTableViewControllerDelegate {
func webViewBackForwardListTableViewController(_ controller: WebViewBackForwardListTableViewController, didSelectBackForwardListItem item: WKBackForwardListItem) {
controller.dismiss(animated: true, completion: nil)
self.webView.go(to: item)
}
}
// MARK: - WKNavigationDelegate
extension WebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
if self.toolbarItems?.isEmpty == false {
self.navigationController?.setToolbarHidden(false, animated: true)
}
injectUserScripts(to: webView)
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
injectUserScripts(to: webView)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
os_log("Navigation failed: %@", type: .error, error as NSError)
showErrorDialog(error)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
os_log("Navigation failed: %@", type: .error, error as NSError)
showErrorDialog(error)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let url = webView.url else { return }
switch url {
case WaniKaniURL.lessonSession, WaniKaniURL.reviewSession:
showBrowserInterface(false, animated: true)
default: break
}
}
private func injectUserScripts(to webView: WKWebView) {
webView.configuration.userContentController.removeAllUserScripts()
if let url = webView.url {
_ = injectUserScripts(for: url)
}
}
private func showErrorDialog(_ error: Error) {
switch error {
case let urlError as URLError where urlError.code == .cancelled:
break
case let nsError as NSError where nsError.domain == "WebKitErrorDomain" && nsError.code == 102:
break
default:
showAlert(title: "Failed to load page", message: error.localizedDescription)
}
}
}
// MARK: - WKScriptMessageHandler
extension WebViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
}
}
// MARK: - WKUIDelegate
extension WebViewController: WKUIDelegate {
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
let newVC = type(of: self).init(configuration: configuration)
newVC.url = navigationAction.request.url
self.navigationController?.pushViewController(newVC, animated: true)
return newVC.webView
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
DispatchQueue.main.async {
let host = frame.request.url?.host ?? "web page"
let title = "From \(host):"
os_log("Displaying alert with title %@ and message %@", type: .debug, title, message)
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler() })
self.present(alert, animated: true, completion: nil)
}
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
DispatchQueue.main.async {
let host = frame.request.url?.host ?? "web page"
let title = "From \(host):"
os_log("Displaying alert with title %@ and message %@", type: .debug, title, message)
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler(true) })
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(false) })
self.present(alert, animated: true, completion: nil)
}
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
DispatchQueue.main.async {
let host = frame.request.url?.host ?? "web page"
let title = "From \(host):"
os_log("Displaying input panel with title %@ and message %@", type: .debug, title, prompt)
let alert = UIAlertController(title: title, message: prompt, preferredStyle: .alert)
alert.addTextField { $0.text = defaultText }
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler(alert.textFields?.first?.text) })
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(nil) })
self.present(alert, animated: true, completion: nil)
}
}
}
// MARK: - WebViewUserScriptSupport
extension WebViewController: WebViewUserScriptSupport {
}
| 42.95339 | 201 | 0.653941 |
18aaa90ef6a224f8c8b5593e167a24041cbc9020 | 4,983 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
defer { runAllTests() }
var StringCreateTests = TestSuite("StringCreateTests")
enum SimpleString: String, CaseIterable {
case smallASCII = "abcdefg"
case smallUnicode = "abéÏ𓀀"
case largeASCII = "012345678901234567890"
case largeUnicode = "abéÏ012345678901234567890𓀀"
case emoji = "😀😃🤢🤮👩🏿🎤🧛🏻♂️🧛🏻♂️👩👩👦👦"
case empty = ""
}
extension String {
var utf32: [UInt32] { return unicodeScalars.map { $0.value } }
}
StringCreateTests.test("String(decoding:as:)") {
func validateDecodingAs(_ str: String) {
// Non-contiguous (maybe) storage
expectEqual(str, String(decoding: str.utf8, as: UTF8.self))
expectEqual(str, String(decoding: str.utf16, as: UTF16.self))
expectEqual(str, String(decoding: str.utf32, as: UTF32.self))
// Contiguous storage
expectEqual(str, String(decoding: Array(str.utf8), as: UTF8.self))
expectEqual(str, String(decoding: Array(str.utf16), as: UTF16.self))
expectEqual(str, String(decoding: Array(str.utf32), as: UTF32.self))
}
for simpleString in SimpleString.allCases {
validateDecodingAs(simpleString.rawValue)
}
// Corner-case: UBP with null pointer (https://bugs.swift.org/browse/SR-9869)
expectEqual(
"", String(decoding: UnsafeBufferPointer(_empty: ()), as: UTF8.self))
expectEqual(
"", String(decoding: UnsafeBufferPointer(_empty: ()), as: UTF16.self))
expectEqual(
"", String(decoding: UnsafeBufferPointer(_empty: ()), as: UTF32.self))
}
if #available(SwiftStdlib 5.3, *) {
StringCreateTests.test("String(unsafeUninitializedCapacity:initializingUTF8With:)") {
for simpleString in SimpleString.allCases {
let expected = simpleString.rawValue
let expectedUTF8 = expected.utf8
let actual = String(unsafeUninitializedCapacity: expectedUTF8.count) {
_ = $0.initialize(from: expectedUTF8)
return expectedUTF8.count
}
expectEqual(expected, actual)
}
let validUTF8: [UInt8] = [0x43, 0x61, 0x66, 0xC3, 0xA9]
let invalidUTF8: [UInt8] = [0x43, 0x61, 0x66, 0xC3]
let longerValidUTF8: [UInt8] = [0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x43, 0x61, 0x66, 0xC3, 0xA9]
let longerInvalidUTF8: [UInt8] = [0x21, 0x21, 0x43, 0x61, 0x66, 0xC3, 0x43, 0x61, 0x66, 0xC3, 0x43, 0x61, 0x66, 0xC3]
func test(bufferSize: Int, input: [UInt8], expected: String) {
let strs = (0..<100).map { _ in
String(unsafeUninitializedCapacity: bufferSize) { buffer in
_ = buffer.initialize(from: input)
return input.count
}
}
for str in strs {
expectEqual(expected, str)
}
}
test(bufferSize: validUTF8.count, input: validUTF8, expected: "Café")
test(bufferSize: invalidUTF8.count, input: invalidUTF8, expected: "Caf�")
// Force non-smol strings by using a larger capacity
test(bufferSize: 16, input: validUTF8, expected: "Café")
test(bufferSize: 16, input: invalidUTF8, expected: "Caf�")
test(bufferSize: longerValidUTF8.count, input: longerValidUTF8, expected: "!!!!!!!!!!Café")
test(bufferSize: longerInvalidUTF8.count, input: longerInvalidUTF8, expected: "!!Caf�Caf�Caf�")
test(bufferSize: 16, input: longerValidUTF8, expected: "!!!!!!!!!!Café")
test(bufferSize: 16, input: longerInvalidUTF8, expected: "!!Caf�Caf�Caf�")
let empty = String(unsafeUninitializedCapacity: 16) { _ in
// Can't initialize the buffer (e.g. the capacity is too small).
return 0
}
expectTrue(empty.isEmpty)
}
}
if #available(SwiftStdlib 5.3, *) {
StringCreateTests.test("Small string unsafeUninitializedCapacity") {
let str1 = "42"
let str2 = String(42)
expectEqual(str1, str2)
let str3 = String(unsafeUninitializedCapacity: 2) {
$0[0] = UInt8(ascii: "4")
$0[1] = UInt8(ascii: "2")
return 2
}
expectEqual(str1, str3)
// Write into uninitialized space.
let str4 = String(unsafeUninitializedCapacity: 3) {
$0[0] = UInt8(ascii: "4")
$0[1] = UInt8(ascii: "2")
$0[2] = UInt8(ascii: "X")
// Deinitialize memory used for scratch space before returning.
($0.baseAddress! + 2).deinitialize(count: 1)
return 2
}
expectEqual(str1, str4)
let str5 = String(unsafeUninitializedCapacity: 3) {
$0[1] = UInt8(ascii: "4")
$0[2] = UInt8(ascii: "2")
// Move the initialized UTF-8 code units to the start of the buffer,
// leaving the non-overlapping source memory uninitialized.
$0.baseAddress!.moveInitialize(from: $0.baseAddress! + 1, count: 2)
return 2
}
expectEqual(str1, str5)
// Ensure reasonable behavior despite a deliberate API contract violation.
let str6 = String(unsafeUninitializedCapacity: 3) {
$0[0] = UInt8(ascii: "4")
$0[1] = UInt8(ascii: "2")
$0[2] = UInt8(ascii: "X")
return 2
}
expectEqual(str1, str6)
}
}
| 35.848921 | 125 | 0.657435 |
29f3fb7297f5246ba1a025ea79a77d831d2c22d5 | 852 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A single row to be displayed in a list of landmarks.
*/
import SwiftUI
struct LandmarkRow: View {
var landmark: Landmark
var body: some View {
HStack {
landmark.image(forSize: 50)
Text(landmark.name)
Spacer()
if landmark.isFavorite {
Image(systemName: "star.fill")
.imageScale(.medium)
.foregroundColor(.yellow)
}
}
}
}
#if DEBUG
struct LandmarkRow_Previews: PreviewProvider {
static var previews: some View {
Group {
LandmarkRow(landmark: landmarkData[0])
LandmarkRow(landmark: landmarkData[1])
}
.previewLayout(.fixed(width: 300, height: 70))
}
}
#endif
| 21.3 | 59 | 0.561033 |
e65e8130fd4254cd8acccec4e465eb5733ec8b0d | 975 | //
// MyFrameworkTests.swift
// MyFrameworkTests
//
// Created by Naresh on 04/01/18.
// Copyright © 2018 Naresh. All rights reserved.
//
import XCTest
@testable import MyFramework
class MyFrameworkTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.351351 | 111 | 0.635897 |
dbd1e66b4f2a35cd6abdd09643557166b522fea0 | 1,623 | // web3swift
//
// Created by Alex Vlasov.
// Copyright © 2018 Alex Vlasov. All rights reserved.
//
import Foundation
import BigInt
import PromiseKit
extension web3.Personal {
public func unlockAccountPromise(account: EthereumAddress, password: String = "web3swift", seconds: UInt64 = 300) -> Promise<Bool> {
let addr = account.address
return unlockAccountPromise(account: addr, password: password, seconds: seconds)
}
public func unlockAccountPromise(account: String, password: String = "web3swift", seconds: UInt64 = 300) -> Promise<Bool> {
let queue = web3.requestDispatcher.queue
do {
if self.web3.keystoreManager == nil {
let request = JSONRPCRequestFabric.prepareRequest(.unlockAccount, parameters: [account.lowercased(), password, seconds])
return self.web3.dispatch(request).map(on: queue) {response in
guard let value: Bool = response.getValue() else {
if response.error != nil {
throw Web3Error.nodeError(desc: response.error!.message)
}
throw Web3Error.nodeError(desc: "Invalid value from Ethereum node")
}
return value
}
}
throw Web3Error.inputError(desc: "Can not unlock a local keystore")
} catch {
let returnPromise = Promise<Bool>.pending()
queue.async {
returnPromise.resolver.reject(error)
}
return returnPromise.promise
}
}
}
| 38.642857 | 136 | 0.589649 |
188a20ddb476588388b845829a0e5595ccce7b07 | 894 | //
// ToDoTests.swift
// ToDoTests
//
// Created by Abel Fernandez Pineiro on 31/10/2020.
//
import XCTest
@testable import ToDo
class ToDoTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.294118 | 111 | 0.661074 |
3a4583c606c1ce85d2a01cdcf96eb7e3c51e5041 | 98 | import Cocoa
protocol Playback {
func start() throws
func stop() throws
}
| 9.8 | 23 | 0.571429 |
672a712f90378fe63cc3435cb51bbaffdee7e306 | 2,528 | ///
/// LLVMLexer.swift
/// SavannaKit
///
/// Created by Robert Widmann on 8/3/19.
/// Copyright © 2019 CodaFi. All rights reserved.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
#if os(iOS)
import UIKit
#else
import AppKit
#endif
public struct LLVMToken: UniversalToken {
public enum LLVMTokenType {
case keyword
case plainText
case operand
}
public let type: LLVMTokenType
public let isEditorPlaceholder: Bool
public let isPlain: Bool
public let range: Range<String.Index>
public static func formToken(_ word: String, in range: Range<String.Index>) -> LLVMToken {
let type: LLVMToken.TokenType
if keywordSet.contains(word) { type = .keyword }
else if word.starts(with: "%") || word.starts(with: "!") { type = .operand }
else { type = .plainText }
return LLVMToken(type: type, isEditorPlaceholder: false, isPlain: false, range: range)
}
public func foregroundColor(for type: LLVMTokenType) -> PlatformColor {
switch type {
case .keyword: return PlatformColor.blue
case .operand: return PlatformColor.green
case .plainText:
#if os(macOS)
let appearanceName = NSApp.effectiveAppearance.name
if appearanceName == .darkAqua {
return PlatformColor.white
} else if appearanceName == .aqua {
return PlatformColor.black
} else {
return PlatformColor.white
}
#else
switch UIScreen.main.traitCollection.userInterfaceStyle {
case .dark:
return PlatformColor.white
case .light:
return PlatformColor.black
default:
return PlatformColor.white
}
#endif
}
}
}
private let keywordSet: Set<String> = [
"fneg", "add", "fadd", "sub", "fsub", "mul", "fmul", "udiv", "sdiv", "fdiv", "urem", "srem",
"frem", "shl", "lshr", "ashr", "and", "or", "xor", "icmp", "fcmp", "phi", "call", "trunc", "zext",
"sext", "fptrunc", "fpext", "uitofp", "sitofp", "fptoui", "fptosi", "inttoptr", "ptrtoint",
"bitcast", "addrspacecast", "select", "va_arg", "landingpad", "personality", "cleanup", "catch",
"filter", "ret", "br", "switch", "indirectbr", "invoke", "resume", "unreachable", "cleanupret",
"catchswitch", "catchret", "catchpad", "cleanuppad", "callbr", "alloca", "load", "store", "fence",
"cmpxchg", "atomicrmw", "getelementptr", "extractelement", "insertelement", "shufflevector",
"extractvalue", "insertvalue", "blockaddress",
]
| 33.706667 | 100 | 0.639636 |
2610e3efa6eb0b30c8600e69319e8fa5f42ec489 | 897 | //
// ViewController.swift
// destinySwift
//
// Created by Dulio Denis on 1/3/21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var storyLabel: UILabel!
@IBOutlet weak var choice1Button: UIButton!
@IBOutlet weak var choice2Button: UIButton!
var storyBrain = StoryBrain()
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
@IBAction func choiceMade(_ sender: UIButton) {
storyBrain.nextStory(userChoice: String((sender.titleLabel?.text)!))
updateUI()
}
func updateUI() {
if storyBrain.isMoreStories() {
let storyText = storyBrain.currentStory()
storyLabel.text = storyText.title
choice1Button.setTitle(storyText.choice1, for: .normal)
choice2Button.setTitle(storyText.choice2, for: .normal)
}
}
}
| 24.243243 | 76 | 0.632107 |
dd2269bc91349ae4aa576286e82f8bbd55816ee8 | 1,652 | //
// FloatingPointExtensions.swift
// EZSwiftExtensionsExample
//
// Created by Olexii Pyvovarov on 9/29/16.
// Copyright © 2016 Goktug Yilmaz. All rights reserved.
//
import Foundation
extension FloatingPoint {
/// EZSE: Returns rounded FloatingPoint to specified number of places
public func rounded(toPlaces places: Int) -> Self {
guard places >= 0 else { return self }
var divisor: Self = 1
for _ in 0..<places { divisor *= 10 }
return (self * divisor).rounded() / divisor
}
/// EZSE: Rounds current FloatingPoint to specified number of places
public mutating func round(toPlaces places: Int) {
self = rounded(toPlaces: places)
}
/// EZSE: Returns ceiled FloatingPoint to specified number of places
public func ceiled(toPlaces places: Int) -> Self {
guard places >= 0 else { return self }
var divisor: Self = 1
for _ in 0..<places { divisor *= 10 }
return (self * divisor).rounded(.up) / divisor
}
/// EZSE: Ceils current FloatingPoint to specified number of places
public mutating func ceil(toPlaces places: Int) {
self = ceiled(toPlaces: places)
}
/// EZSE: Returns a random floating point number between 0.0 and 1.0, inclusive.
public static func random() -> Float {
return Float(arc4random()) / 0xFFFFFFFF
}
/// EZSE: Returns a random floating point number in the range min...max, inclusive.
public static func random(within: Range<Float>) -> Float {
return Float.random() * (within.upperBound - within.lowerBound) + within.lowerBound
}
}
| 33.714286 | 91 | 0.644068 |
09c1a1e49fcabf5a6d9fb0dd77c9bf708d5e504a | 726 | // Copyright © 2019 Saleem Abdulrasool <[email protected]>.
// SPDX-License-Identifier: BSD-3-Clause
public class Term {
public let variable: Variable
public let coefficient: Double
public var value: Double {
return self.coefficient * self.variable.value
}
public init(_ variable: Variable, _ coefficient: Double = 1.0) {
self.variable = variable
self.coefficient = coefficient
}
}
extension Term: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(variable)
hasher.combine(coefficient)
}
}
extension Term: Equatable {
public static func == (lhs: Term, rhs: Term) -> Bool {
return lhs.variable == rhs.variable && lhs.coefficient == rhs.coefficient
}
}
| 24.2 | 77 | 0.702479 |
3a1d877c6db60a78b071c87ba70ea05dff723a44 | 429 | //
// CommandModels.swift
// Listr
//
// Created by Guilherme Rambo on 01/03/20.
// Copyright © 2020 Guilherme Rambo. All rights reserved.
//
#if DEBUG
import Foundation
struct ListItemsCommand: Hashable, Codable { }
struct AddItemCommand: Hashable, Codable {
let title: String
}
struct DumpDatabaseCommand: Hashable, Codable {
}
struct ReplaceDatabaseCommand: Hashable, Codable {
let data: Data
}
#endif
| 15.321429 | 58 | 0.713287 |
501f31561c2b451c2cfdf03f318023372f46a1dd | 1,992 | //
// LoginViewController.swift
// Instagram2.0
//
// Created by Victor Li Wang on 2/29/16.
// Copyright © 2016 Victor Li Wang. All rights reserved.
//
import UIKit
import Parse
class LoginViewController: UIViewController {
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSignIn(sender: AnyObject) {
PFUser.logInWithUsernameInBackground(usernameField.text!, password: passwordField.text!) { (user: PFUser?, error: NSError?) -> Void in
if user != nil {
print("logged in")
self.performSegueWithIdentifier("loginSegue", sender: nil)
}
}
}
@IBAction func onSignUp(sender: AnyObject) {
let newUser = PFUser()
newUser.username = usernameField.text
newUser.password = passwordField.text
newUser.signUpInBackgroundWithBlock { (success:Bool, error: NSError?) -> Void in
if success {
print("created a user")
self.performSegueWithIdentifier("loginSegue", sender: nil)
} else {
print(error?.localizedDescription)
if error!.code == 202 {
print("username is taken")
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 30.181818 | 142 | 0.611948 |
16f3e86921c94d751e3a269595d8ab8393084eaf | 10,560 | //
// MainViewController.swift
// MySampleApp
//
//
// Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved.
//
// Code generated by AWS Mobile Hub. Amazon gives unlimited permission to
// copy, distribute and modify it.
//
// Source code generated from template: aws-my-sample-app-ios-swift v0.4
//
// Edited by: Kee Sern Chua
import UIKit
import AWSMobileHubHelper
class MainViewController: UITableViewController {
var demoFeatures: [DemoFeature] = []
var signInObserver: AnyObject!
var signOutObserver: AnyObject!
var willEnterForegroundObserver: AnyObject!
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
//navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .Plain, target: nil, action: nil)
// You need to call `- updateTheme` here in case the sign-in happens before `- viewWillAppear:` is called.
updateTheme()
willEnterForegroundObserver = NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationWillEnterForegroundNotification, object: nil, queue: NSOperationQueue.currentQueue()) { _ in
self.updateTheme()
}
presentSignInViewController()
var demoFeature = DemoFeature.init(
name: NSLocalizedString("Students Profile",
comment: "Label for demo menu option."),
detail: NSLocalizedString("Retrieve user profile.",
comment: "Description for demo menu option."),
icon: "UserIcon", storyboard: "UserProfile")
demoFeatures.append(demoFeature)
/*
demoFeature = DemoFeature.init(
name: NSLocalizedString("Lessons",
comment: "Label for demo menu option."),
detail: NSLocalizedString("Place to start learning English",
comment: "Description for demo menu option."),
icon: "ContentDeliveryIcon", storyboard: "ContentDelivery")
demoFeatures.append(demoFeature)*/
/*
demoFeature = DemoFeature.init(
name: NSLocalizedString("User Files",
comment: "Label for demo menu option."),
detail: NSLocalizedString("Users files in the system.",
comment: "Description for demo menu option."),
icon: "UserFilesIcon", storyboard: "UserFiles")
demoFeatures.append(demoFeature)*/
//App analytic that could be use in the future
/*
demoFeature = DemoFeature.init(
name: NSLocalizedString("App Analytics",
comment: "Label for demo menu option."),
detail: NSLocalizedString("Collect, visualize and export app usage metrics.",
comment: "Description for demo menu option."),
icon: "AppAnalyticsIcon", storyboard: "AppAnalytics")
demoFeatures.append(demoFeature)
*/
//Dynamo Db database could be use in the future
/*
demoFeature = DemoFeature.init(
name: NSLocalizedString("Dynamodb",
comment: "Label for demo menu option."),
detail: NSLocalizedString("Store data in the cloud.",
comment: "Description for demo menu option."),
icon: "NoSQLIcon", storyboard: "NoSQLDatabase")
demoFeatures.append(demoFeature)
*/
demoFeature = DemoFeature.init(
name: NSLocalizedString("Practices",
comment: "Label for demo menu option."),
detail: NSLocalizedString("practice the lessons",
comment: "Description for demo menu option."),
icon: "SpeechBubble", storyboard: "Practices")
demoFeatures.append(demoFeature)
demoFeature = DemoFeature.init(
name: NSLocalizedString("About",
comment: "Label for demo menu option."),
detail: NSLocalizedString("Additional information about the App.",
comment: "Description for demo menu option."),
icon: "About", storyboard: "About")
demoFeatures.append(demoFeature)
/*
demoFeature = DemoFeature.init(
name: NSLocalizedString("Recording",
comment: "Label for demo menu option."),
detail: NSLocalizedString("Recording function.",
comment: "Description for demo menu option."),
icon: "IconFolder", storyboard: "Record")
demoFeatures.append(demoFeature)*/
signInObserver = NSNotificationCenter.defaultCenter().addObserverForName(AWSIdentityManagerDidSignInNotification, object: AWSIdentityManager.defaultIdentityManager(), queue: NSOperationQueue.mainQueue(), usingBlock: {[weak self] (note: NSNotification) -> Void in
guard let strongSelf = self else { return }
print("Sign In Observer observed sign in.")
strongSelf.setupRightBarButtonItem()
// You need to call `updateTheme` here in case the sign-in happens after `- viewWillAppear:` is called.
strongSelf.updateTheme()
})
signOutObserver = NSNotificationCenter.defaultCenter().addObserverForName(AWSIdentityManagerDidSignOutNotification, object: AWSIdentityManager.defaultIdentityManager(), queue: NSOperationQueue.mainQueue(), usingBlock: {[weak self](note: NSNotification) -> Void in
guard let strongSelf = self else { return }
print("Sign Out Observer observed sign out.")
strongSelf.setupRightBarButtonItem()
strongSelf.updateTheme()
})
setupRightBarButtonItem()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(signInObserver)
NSNotificationCenter.defaultCenter().removeObserver(signOutObserver)
NSNotificationCenter.defaultCenter().removeObserver(willEnterForegroundObserver)
}
func setupRightBarButtonItem() {
struct Static {
static var onceToken: dispatch_once_t = 0
}
dispatch_once(&Static.onceToken, {
let loginButton: UIBarButtonItem = UIBarButtonItem(title: nil, style: .Done, target: self, action: nil)
self.navigationItem.rightBarButtonItem = loginButton
})
/*
if (AWSIdentityManager.defaultIdentityManager().loggedIn) {
navigationItem.rightBarButtonItem!.title = NSLocalizedString("Sign-Out", comment: "Label for the logout button.")
navigationItem.rightBarButtonItem!.action = "handleLogout"
}
*/
navigationItem.rightBarButtonItem!.title = NSLocalizedString("Sign-Out", comment: "Label for the logout button.")
navigationItem.rightBarButtonItem!.action = "handleLogout"
}
func presentSignInViewController() {
if !AWSIdentityManager.defaultIdentityManager().loggedIn {
let storyboard = UIStoryboard(name: "SignIn", bundle: nil)
let signInViewController = storyboard.instantiateViewControllerWithIdentifier("SignIn") as! SignInViewController
presentViewController(signInViewController, animated: true, completion: nil)
}
}
// MARK: - UITableViewController delegates
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MainViewCell")!
let demoFeature = demoFeatures[indexPath.row]
cell.imageView!.image = UIImage(named: demoFeature.icon)
cell.textLabel!.text = demoFeature.displayName
cell.detailTextLabel!.text = demoFeature.detailText
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demoFeatures.count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let demoFeature = demoFeatures[indexPath.row]
let storyboard = UIStoryboard(name: demoFeature.storyboard, bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier(demoFeature.storyboard)
self.navigationController!.pushViewController(viewController, animated: true)
}
func updateTheme() {
let settings = ColorThemeSettings.sharedInstance
settings.loadSettings { (themeSettings: ColorThemeSettings?, error: NSError?) -> Void in
guard let themeSettings = themeSettings else {
print("Failed to load color: \(error)")
return
}
dispatch_async(dispatch_get_main_queue(), {
let titleTextColor: UIColor = themeSettings.theme.titleTextColor.UIColorFromARGB()
self.navigationController!.navigationBar.barTintColor = themeSettings.theme.titleBarColor.UIColorFromARGB()
self.view.backgroundColor = themeSettings.theme.backgroundColor.UIColorFromARGB()
self.navigationController!.navigationBar.tintColor = titleTextColor
self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: titleTextColor]
})
}
}
func handleLogout() {
if (AWSIdentityManager.defaultIdentityManager().loggedIn) {
ColorThemeSettings.sharedInstance.wipe()
AWSIdentityManager.defaultIdentityManager().logoutWithCompletionHandler({(result: AnyObject?, error: NSError?) -> Void in
self.navigationController!.popToRootViewControllerAnimated(false)
self.setupRightBarButtonItem()
self.presentSignInViewController()
})
// print("Logout Successful: \(signInProvider.getDisplayName)");
} else {
assert(false)
}
}
}
/*
class FeatureDescriptionViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "Back", style: .Plain, target: nil, action: nil)
}
}*/
| 44.369748 | 279 | 0.635417 |
2694fde755e81cc234caa2a18be0d1d347fce51f | 2,662 | //
// YPHelper.swift
// YPImgePicker
//
// Created by Sacha Durand Saint Omer on 02/11/16.
// Copyright © 2016 Yummypets. All rights reserved.
//
import Foundation
import UIKit
import Photos
internal func ypLocalized(_ str: String) -> String {
return NSLocalizedString(str,
tableName: nil,
bundle: Bundle(for: YPPickerVC.self),
value: "",
comment: "")
}
internal func imageFromBundle(_ named: String) -> UIImage {
return UIImage(named: named, in: Bundle(for: YPPickerVC.self), compatibleWith: nil) ?? UIImage()
}
struct YPHelper {
static func changeBackButtonIcon(_ controller: UIViewController) {
if YPConfig.icons.shouldChangeDefaultBackButtonIcon {
let backButtonIcon = YPConfig.icons.backButtonIcon
controller.navigationController?.navigationBar.backIndicatorImage = backButtonIcon
controller.navigationController?.navigationBar.backIndicatorTransitionMaskImage = backButtonIcon
}
}
static func changeBackButtonTitle(_ controller: UIViewController) {
if YPConfig.icons.hideBackButtonTitle {
controller.navigationItem.backBarButtonItem = UIBarButtonItem(title: "",
style: .plain,
target: nil,
action: nil)
}
}
static func configureFocusView(_ v: UIView) {
v.alpha = 0.0
v.backgroundColor = UIColor.clear
v.layer.borderColor = UIColor(r: 204, g: 204, b: 204).cgColor
v.layer.borderWidth = 1.0
v.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}
static func animateFocusView(_ v: UIView) {
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8,
initialSpringVelocity: 3.0, options: UIView.AnimationOptions.curveEaseIn,
animations: {
v.alpha = 1.0
v.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}, completion: { _ in
v.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
v.removeFromSuperview()
})
}
static func formattedStrigFrom(_ timeInterval: TimeInterval) -> String {
let interval = Int(timeInterval)
let seconds = interval % 60
let minutes = (interval / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
}
| 38.028571 | 108 | 0.564613 |
56f6fc8c4c0b2e5eafd88afc4de3ff48f1acd09d | 1,847 | /*
* --------------------------------------------------------------------------------
* <copyright company="Aspose" file="TableLink.swift">
* Copyright (c) 2020 Aspose.Words for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------
*/
import Foundation
// Table link element.
public class TableLink : NodeLink {
private enum CodingKeys: String, CodingKey {
case invalidCodingKey;
}
public override init() {
super.init();
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder);
}
public override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder);
}
}
| 37.693878 | 83 | 0.649161 |
4b6ab0b0f8d65dd6ca4e14195b6880b9db1b9a98 | 495 | //
// Copyright (c) 2020 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
import Foundation
extension Data {
internal var asBytes: [CUnsignedChar] {
let start = (self as NSData).bytes.bindMemory(to: CUnsignedChar.self, capacity: self.count)
let count = self.count / MemoryLayout<CUnsignedChar>.size
return [CUnsignedChar](UnsafeBufferPointer<CUnsignedChar>(start: start, count: count))
}
}
| 27.5 | 100 | 0.70101 |
7959905c33a2b03b8dbf782ebb730919c64b3533 | 965 | //
// tippyTests.swift
// tippyTests
//
// Created by phil_nachum on 7/16/16.
// Copyright © 2016 phil_nachum. All rights reserved.
//
import XCTest
@testable import tippy
class tippyTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.081081 | 111 | 0.632124 |
71bfcb0916649528a5688611de0c046aa4226676 | 264 | //
// ScrumbleGenerator.swift
// University
//
// Created by Дмитрий Савинов on 03.02.2022.
//
import Foundation
import Combine
// MARK: - ScrumbleGenerator
public protocol ScrumbleGenerator {
func scrumble(lenght: Int) -> AnyPublisher<String, Never>
}
| 16.5 | 62 | 0.719697 |
f5c2af1631bb8e8d1dec5a7cf06a89b13fd3212f | 11,197 | //
// Filter.swift
// SwiftyBeaver
//
// Created by Jeff Roberts on 5/31/16.
// Copyright © 2015 Sebastian Kreutzberger
// Some rights reserved: http://opensource.org/licenses/MIT
//
import Foundation
/// FilterType is a protocol that describes something that determines
/// whether or not a message gets logged. A filter answers a Bool when it
/// is applied to a value. If the filter passes, it shall return true,
/// false otherwise.
///
/// A filter must contain a target, which identifies what it filters against
/// A filter can be required meaning that all required filters against a specific
/// target must pass in order for the message to be logged. At least one non-required
/// filter must pass in order for the message to be logged
public protocol FilterType: class {
/// 判断当前`Filter`是否用于当前log
func apply(_ value: Any) -> Bool
func getTarget() -> Filter.TargetType
/// 在`Destination`包含多个`Filter`的时候,该`Filter`是否是必须的
func isRequired() -> Bool
/// 是否属于排除类型的`Filter`,如:文件名不包含`foo`的文件
func isExcluded() -> Bool
/// 判断`LogLevel`的优先级是否高于该`Filter`的优先级
func reachedMinLevel(_ level: LogLevel) -> Bool
}
/// Filters is syntactic sugar used to easily construct filters
public final class Filters {
/// filter by path or filename
public static let path = PathFilterFactory.self
/// filter by function name
public static let function = FunctionFilterFactory.self
/// filter by log message
public static let message = MessageFilterFactory.self
}
/// Filter is an abstract base class for other filters
public class Filter {
/// `Filter`作用的目标类型
///
/// - path: 基于文件路径或文件名
/// - function: 基于调用函数
/// - message: 基于日志内容
public enum TargetType {
case path(ComparisonType)
case function(ComparisonType)
case message(ComparisonType)
}
/// Filter Matching Functions
///
/// - startsWith: does the filter start with the string?
/// - contains: does the filter contain the string?
/// - excludes: does the filter NOT contain the string?
/// - endsWith: does the filter end with the string?
/// - equals: does the filter equal the string?
public enum ComparisonType {
case startsWith([String], Bool)
case contains([String], Bool)
case excludes([String], Bool)
case endsWith([String], Bool)
case equals([String], Bool)
}
let targetType: TargetType
let required: Bool
let minLevel: LogLevel
public init(_ target: TargetType, required: Bool, minLevel: LogLevel) {
self.targetType = target
self.required = required
self.minLevel = minLevel
}
public func getTarget() -> Filter.TargetType {
return self.targetType
}
/// 在`Destination`包含多个`Filter`的时候,该`Filter`是否是必须的
public func isRequired() -> Bool {
return self.required
}
/// 是否属于排除类型的`Filter`,如:文件名不包含`foo`的文件
public func isExcluded() -> Bool {
return false
}
/// 判断`LogLevel`的优先级是否高于该`Filter`的优先级
public func reachedMinLevel(_ level: LogLevel) -> Bool {
return level.rawValue >= minLevel.rawValue
}
}
/// CompareFilter is a FilterType that can filter based upon whether a target starts with, contains or ends with a specific string.
/// CompareFilters can be case sensitive.
public class CompareFilter: Filter, FilterType {
/// 匹配类型
private let filterComparisonType: ComparisonType
public override init(_ target: TargetType, required: Bool, minLevel: LogLevel) {
switch target {
case let .function(comparison):
self.filterComparisonType = comparison
case let .path(comparison):
self.filterComparisonType = comparison
case let .message(comparison):
self.filterComparisonType = comparison
}
super.init(target, required: required, minLevel: minLevel)
}
public func apply(_ value: Any) -> Bool {
guard let value = value as? String else { return false }
let matches: Bool
switch filterComparisonType {
case let .contains(strings, caseSensitive):
matches = !strings.filter { caseSensitive ? value.contains($0) : value.lowercased().contains($0.lowercased()) }.isEmpty
case let .excludes(strings, caseSensitive):
matches = !strings.filter { caseSensitive ? !value.contains($0) : !value.lowercased().contains($0.lowercased()) }.isEmpty
case let .startsWith(strings, caseSensitive):
matches = !strings.filter { caseSensitive ? value.hasPrefix($0) : value.lowercased().hasPrefix($0.lowercased()) }.isEmpty
case let .endsWith(strings, caseSensitive):
matches = !strings.filter { caseSensitive ? value.hasSuffix($0) : value.lowercased().hasSuffix($0.lowercased()) }.isEmpty
case let .equals(strings, caseSensitive):
matches = !strings.filter { caseSensitive ? value == $0 : value.lowercased() == $0.lowercased() }.isEmpty
}
return matches
}
public override func isExcluded() -> Bool {
if case ComparisonType.excludes = filterComparisonType {
return true
}
return false
}
}
// Syntactic sugar for creating a function comparison filter
public class FunctionFilterFactory {
/// Create Filter
///
/// - Parameters:
/// - prefixes: the string pattern
/// - caseSensitive: case-sensitive must be met, false on default
/// - required: must be met if the destination has multiple filters, false on default
/// - minLevel: the level the filter must at least have, .verbose on default
/// - Returns: Filter
public static func startsWith(_ prefixes: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.function(.startsWith(prefixes, caseSensitive)), required: required, minLevel: minLevel)
}
public static func contains(_ strings: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.function(.contains(strings, caseSensitive)), required: required, minLevel: minLevel)
}
public static func excludes(_ strings: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.function(.excludes(strings, caseSensitive)), required: required, minLevel: minLevel)
}
public static func endsWith(_ suffixes: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.function(.endsWith(suffixes, caseSensitive)), required: required, minLevel: minLevel)
}
public static func equals(_ strings: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.function(.equals(strings, caseSensitive)), required: required, minLevel: minLevel)
}
}
// Syntactic sugar for creating a message comparison filter
public class MessageFilterFactory {
public static func startsWith(_ prefixes: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.message(.startsWith(prefixes, caseSensitive)), required: required, minLevel: minLevel)
}
public static func contains(_ strings: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.message(.contains(strings, caseSensitive)), required: required, minLevel: minLevel)
}
public static func excludes(_ strings: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.message(.excludes(strings, caseSensitive)), required: required, minLevel: minLevel)
}
public static func endsWith(_ suffixes: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.message(.endsWith(suffixes, caseSensitive)), required: required, minLevel: minLevel)
}
public static func equals(_ strings: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.message(.equals(strings, caseSensitive)), required: required, minLevel: minLevel)
}
}
// Syntactic sugar for creating a path comparison filter
public class PathFilterFactory {
public static func startsWith(_ prefixes: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.path(.startsWith(prefixes, caseSensitive)), required: required, minLevel: minLevel)
}
public static func contains(_ strings: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.path(.contains(strings, caseSensitive)), required: required, minLevel: minLevel)
}
public static func excludes(_ strings: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.path(.excludes(strings, caseSensitive)), required: required, minLevel: minLevel)
}
public static func endsWith(_ suffixes: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.path(.endsWith(suffixes, caseSensitive)), required: required, minLevel: minLevel)
}
public static func equals(_ strings: String..., caseSensitive: Bool = false,
required: Bool = false, minLevel: LogLevel = .verbose) -> FilterType {
return CompareFilter(.path(.equals(strings, caseSensitive)), required: required, minLevel: minLevel)
}
}
extension Filter.TargetType: Equatable {
// The == does not compare associated values for each enum. Instead == evaluates to true
// if both enums are the same "types", ignoring the associated values of each enum
public static func == (lhs: Filter.TargetType, rhs: Filter.TargetType) -> Bool {
switch (lhs, rhs) {
case (.path, .path):
return true
case (.function, .function):
return true
case (.message, .message):
return true
default:
return false
}
}
}
| 42.412879 | 133 | 0.643297 |
f4ee7286fa25981692108fb477f263685a9ad8b5 | 1,606 | //
// MenuCustomViewController.swift
// ReactiveCocoaCatalog
//
// Created by Yasuhiro Inami on 2016-04-09.
// Copyright © 2016 Yasuhiro Inami. All rights reserved.
//
import UIKit
import Result
import ReactiveSwift
import FontAwesome
final class MenuCustomViewController: UIViewController, StoryboardSceneProvider
{
static let storyboardScene = StoryboardScene<MenuCustomViewController>(name: "MenuBadge")
@IBOutlet weak var mainLabel: UILabel?
@IBOutlet weak var subLabel: UILabel?
@IBOutlet weak var updateButton: UIButton?
weak var menu: CustomMenu?
override func viewDidLoad()
{
super.viewDidLoad()
guard let menu = self.menu, let mainLabel = self.mainLabel, let subLabel = self.subLabel, let updateButton = self.updateButton else
{
fatalError("Required properties are not set.")
}
mainLabel.font = UIFont.fontAwesome(ofSize: mainLabel.font.pointSize)
mainLabel.reactive.text
<~ menu.title.producer
.map { [unowned menu] title -> String in
let fontAwesome = menu.menuId.fontAwesome
var title2 = String.fontAwesomeIcon(name: fontAwesome)
title2.append(" \(title)")
return title2
}
subLabel.reactive.text
<~ menu.badge.producer
.map { "Badge: \($0)" }
BadgeManager.badges[menu.menuId]
<~ updateButton.reactive.controlEvents(.touchUpInside)
.map { _ in Badge(rawValue: Badge.randomBadgeString()) }
}
}
| 30.301887 | 139 | 0.635741 |
39a92b55fab6fb3b75e58fb16b44bdc65e4074cf | 5,254 | /*
Copyright (c) 2020, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@testable import OTFCareKit
@testable import OTFCareKitStore
import OTFCareKitUI
import Combine
import Foundation
import SwiftUI
import XCTest
class TestLabeledValueTaskViewModel: XCTestCase {
var controller: OCKLabeledValueTaskController!
var cancellables: Set<AnyCancellable> = []
override func setUp() {
super.setUp()
let store = OCKStore(name: "carekit-store", type: .inMemory)
controller = .init(storeManager: .init(wrapping: store))
}
func testViewModelCreation() {
let taskEvents = OCKTaskEvents.mock(underlyingValue: nil, units: nil)
controller.taskEvents = taskEvents
let updated = expectation(description: "updated view model")
controller.$viewModel
.compactMap { $0 }
.sink { viewModel in
XCTAssertEqual("title", viewModel.title)
XCTAssertEqual("Anytime", viewModel.detail)
updated.fulfill()
}
.store(in: &cancellables)
wait(for: [updated], timeout: 1)
}
func testIsComplete() {
let taskEvents = OCKTaskEvents.mock(underlyingValue: 5, units: "BPM")
controller.taskEvents = taskEvents
let updated = expectation(description: "updated view model")
controller.$viewModel
.compactMap { $0 }
.sink { viewModel in
switch viewModel.state {
case let .complete(value, label):
XCTAssertEqual(value, "5")
XCTAssertEqual(label, "BPM")
case .incomplete:
XCTFail("State should be `complete`")
}
updated.fulfill()
}
.store(in: &cancellables)
wait(for: [updated], timeout: 1)
}
func testIsIncomplete() {
let taskEvents = OCKTaskEvents.mock(underlyingValue: nil, units: nil)
controller.taskEvents = taskEvents
let updated = expectation(description: "updated view model")
controller.$viewModel
.compactMap { $0 }
.sink { viewModel in
switch viewModel.state {
case .complete:
XCTFail("State should be `incomplete`")
case .incomplete(let label):
XCTAssertEqual(label, loc("NO_DATA").uppercased())
}
updated.fulfill()
}
.store(in: &cancellables)
wait(for: [updated], timeout: 1)
}
}
private extension OCKTaskEvents {
static func mock(underlyingValue: OCKOutcomeValueUnderlyingType?, units: String?) -> OCKTaskEvents {
let startOfDay = Calendar.current.startOfDay(for: Date())
let element = OCKScheduleElement(start: startOfDay, end: nil, interval: .init(day: 1), text: nil, targetValues: [], duration: .allDay)
var task = OCKTask(id: "task", title: "title", carePlanUUID: nil, schedule: .init(composing: [element]))
task.uuid = UUID()
task.instructions = "instructions"
let outcome = underlyingValue.map { underlyingValue -> OCKOutcome in
var outcomeValue = OCKOutcomeValue(underlyingValue)
outcomeValue.units = units
return OCKOutcome(taskUUID: task.uuid, taskOccurrenceIndex: 0, values: [outcomeValue])
}
let scheduleEvent = task.schedule.event(forOccurrenceIndex: 0)!
let event = OCKAnyEvent(task: task, outcome: outcome, scheduleEvent: scheduleEvent)
var taskEvents = OCKTaskEvents()
taskEvents.append(event: event)
return taskEvents
}
}
| 39.208955 | 142 | 0.664256 |
67bcfe1ecda5d406c5f79e9e40260c8a7741529a | 30,668 | //
// RangeSeekSlider.swift
// RangeSeekSlider
//
// Created by Keisuke Shoji on 2017/03/09.
//
//
import UIKit
@IBDesignable open class RangeSeekSlider: UIControl {
// MARK: - initializers
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public required override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public convenience init(frame: CGRect = .zero, completion: ((RangeSeekSlider) -> Void)? = nil) {
self.init(frame: frame)
completion?(self)
}
// MARK: - open stored properties
open weak var delegate: RangeSeekSliderDelegate?
/// The minimum possible value to select in the range
@IBInspectable open var minValue: CGFloat = 0.0 {
didSet {
refresh()
}
}
/// The maximum possible value to select in the range
@IBInspectable open var maxValue: CGFloat = 100.0 {
didSet {
refresh()
}
}
/// The preselected minumum value
/// (note: This should be less than the selectedMaxValue)
@IBInspectable open var selectedMinValue: CGFloat = 0.0 {
didSet {
if selectedMinValue < minValue {
selectedMinValue = minValue
}
}
}
/// The preselected maximum value
/// (note: This should be greater than the selectedMinValue)
@IBInspectable open var selectedMaxValue: CGFloat = 100.0 {
didSet {
if selectedMaxValue > maxValue {
selectedMaxValue = maxValue
}
}
}
/// The font of the minimum value text label. If not set, the default is system font size 12.0.
open var minLabelFont: UIFont = UIFont.systemFont(ofSize: 12.0) {
didSet {
minLabel.font = minLabelFont as CFTypeRef
minLabel.fontSize = minLabelFont.pointSize
}
}
/// The font of the maximum value text label. If not set, the default is system font size 12.0.
open var maxLabelFont: UIFont = UIFont.systemFont(ofSize: 12.0) {
didSet {
maxLabel.font = maxLabelFont as CFTypeRef
maxLabel.fontSize = maxLabelFont.pointSize
}
}
/// Each handle in the slider has a label above it showing the current selected value. By default, this is displayed as a decimal format.
/// You can update this default here by updating properties of NumberFormatter. For example, you could supply a currency style, or a prefix or suffix.
open var numberFormatter: NumberFormatter = {
let formatter: NumberFormatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 0
return formatter
}()
open var lengthFormatter: LengthFormatter?
/// Hides the labels above the slider controls. true = labels will be hidden. false = labels will be shown. Default is false.
@IBInspectable open var hideLabels: Bool = false {
didSet {
minLabel.isHidden = hideLabels
maxLabel.isHidden = hideLabels
}
}
/// fixes the labels above the slider controls. true: labels will be fixed to both ends. false: labels will move with the handles. Default is false.
@IBInspectable open var labelsFixed: Bool = false
/// The minimum distance the two selected slider values must be apart. Default is 0.
@IBInspectable open var minDistance: CGFloat = 0.0 {
didSet {
if minDistance < 0.0 {
minDistance = 0.0
}
}
}
/// The maximum distance the two selected slider values must be apart. Default is CGFloat.greatestFiniteMagnitude.
@IBInspectable open var maxDistance: CGFloat = .greatestFiniteMagnitude {
didSet {
if maxDistance < 0.0 {
maxDistance = .greatestFiniteMagnitude
}
}
}
/// The color of the minimum value text label. If not set, the default is the tintColor.
@IBInspectable open var minLabelColor: UIColor?
/// The color of the maximum value text label. If not set, the default is the tintColor.
@IBInspectable open var maxLabelColor: UIColor?
/// Handle slider with custom color, you can set custom color for your handle
@IBInspectable open var handleColor: UIColor?
/// Handle slider with custom border color, you can set custom border color for your handle
@IBInspectable open var handleBorderColor: UIColor?
/// Set slider line tint color between handles
@IBInspectable open var colorBetweenHandles: UIColor?
/// The color of the entire slider when the handle is set to the minimum value and the maximum value. Default is nil.
@IBInspectable open var initialColor: UIColor?
/// If true, the control will mimic a normal slider and have only one handle rather than a range.
/// In this case, the selectedMinValue will be not functional anymore. Use selectedMaxValue instead to determine the value the user has selected.
@IBInspectable open var disableRange: Bool = false {
didSet {
leftHandle.isHidden = disableRange
minLabel.isHidden = disableRange
}
}
/// If true the control will snap to point at each step between minValue and maxValue. Default is false.
@IBInspectable open var enableStep: Bool = false
/// The step value, this control the value of each step. If not set the default is 0.0.
/// (note: this is ignored if <= 0.0)
@IBInspectable open var step: CGFloat = 0.0
/// Handle slider with custom image, you can set custom image for your handle
@IBInspectable open var handleImage: UIImage? {
didSet {
guard let image = handleImage else {
return
}
var handleFrame = CGRect.zero
handleFrame.size = image.size
leftHandle.frame = handleFrame
leftHandle.contents = image.cgImage
rightHandle.frame = handleFrame
rightHandle.contents = image.cgImage
}
}
/// Handle diameter (default 16.0)
@IBInspectable open var handleDiameter: CGFloat = 16.0 {
didSet {
leftHandle.cornerRadius = handleDiameter / 2.0
rightHandle.cornerRadius = handleDiameter / 2.0
leftHandle.frame = CGRect(x: 0.0, y: 0.0, width: handleDiameter, height: handleDiameter)
rightHandle.frame = CGRect(x: 0.0, y: 0.0, width: handleDiameter, height: handleDiameter)
}
}
/// Selected handle diameter multiplier (default 1.7)
@IBInspectable open var selectedHandleDiameterMultiplier: CGFloat = 1.7
/// Set the slider line height (default 1.0)
@IBInspectable open var lineHeight: CGFloat = 1.0 {
didSet {
updateLineHeight()
}
}
/// Handle border width (default 0.0)
@IBInspectable open var handleBorderWidth: CGFloat = 0.0 {
didSet {
leftHandle.borderWidth = handleBorderWidth
rightHandle.borderWidth = handleBorderWidth
}
}
/// Set padding between label and handle (default 8.0)
@IBInspectable open var labelPadding: CGFloat = 8.0 {
didSet {
updateLabelPositions()
}
}
/// The label displayed in accessibility mode for minimum value handler. If not set, the default is empty String.
@IBInspectable open var minLabelAccessibilityLabel: String?
/// The label displayed in accessibility mode for maximum value handler. If not set, the default is empty String.
@IBInspectable open var maxLabelAccessibilityLabel: String?
/// The brief description displayed in accessibility mode for minimum value handler. If not set, the default is empty String.
@IBInspectable open var minLabelAccessibilityHint: String?
/// The brief description displayed in accessibility mode for maximum value handler. If not set, the default is empty String.
@IBInspectable open var maxLabelAccessibilityHint: String?
// MARK: - private stored properties
private enum HandleTracking { case none, left, right }
private var handleTracking: HandleTracking = .none
private let sliderLine: CALayer = CALayer()
private let sliderLineBetweenHandles: CALayer = CALayer()
private let leftHandle: CALayer = CALayer()
private let rightHandle: CALayer = CALayer()
fileprivate let minLabel: CATextLayer = CATextLayer()
fileprivate let maxLabel: CATextLayer = CATextLayer()
private var minLabelTextSize: CGSize = .zero
private var maxLabelTextSize: CGSize = .zero
// UIFeedbackGenerator
private var previousStepMinValue: CGFloat?
private var previousStepMaxValue: CGFloat?
// strong reference needed for UIAccessibilityContainer
// see http://stackoverflow.com/questions/13462046/custom-uiview-not-showing-accessibility-on-voice-over
private var accessibleElements: [UIAccessibilityElement] = []
// MARK: - private computed properties
private var leftHandleAccessibilityElement: UIAccessibilityElement {
let element: RangeSeekSliderLeftElement = RangeSeekSliderLeftElement(accessibilityContainer: self)
element.isAccessibilityElement = true
element.accessibilityLabel = minLabelAccessibilityLabel
element.accessibilityHint = minLabelAccessibilityHint
element.accessibilityValue = minLabel.string as? String
element.accessibilityFrame = convert(leftHandle.frame, to: nil)
element.accessibilityTraits = UIAccessibilityTraits.adjustable
return element
}
private var rightHandleAccessibilityElement: UIAccessibilityElement {
let element: RangeSeekSliderRightElement = RangeSeekSliderRightElement(accessibilityContainer: self)
element.isAccessibilityElement = true
element.accessibilityLabel = maxLabelAccessibilityLabel
element.accessibilityHint = maxLabelAccessibilityHint
element.accessibilityValue = maxLabel.string as? String
element.accessibilityFrame = convert(rightHandle.frame, to: nil)
element.accessibilityTraits = UIAccessibilityTraits.adjustable
return element
}
// MARK: - UIView
open override func layoutSubviews() {
super.layoutSubviews()
if handleTracking == .none {
updateLineHeight()
updateLabelValues()
updateColors()
updateHandlePositions()
updateLabelPositions()
}
}
open override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: 65.0)
}
// MARK: - UIControl
open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let touchLocation: CGPoint = touch.location(in: self)
let insetExpansion: CGFloat = -30.0
let isTouchingLeftHandle: Bool = leftHandle.frame.insetBy(dx: insetExpansion, dy: insetExpansion).contains(touchLocation)
let isTouchingRightHandle: Bool = rightHandle.frame.insetBy(dx: insetExpansion, dy: insetExpansion).contains(touchLocation)
guard isTouchingLeftHandle || isTouchingRightHandle else { return false }
// the touch was inside one of the handles so we're definitely going to start movign one of them. But the handles might be quite close to each other, so now we need to find out which handle the touch was closest too, and activate that one.
let distanceFromLeftHandle: CGFloat = touchLocation.distance(to: leftHandle.frame.center)
let distanceFromRightHandle: CGFloat = touchLocation.distance(to: rightHandle.frame.center)
if distanceFromLeftHandle < distanceFromRightHandle && !disableRange {
handleTracking = .left
} else if selectedMaxValue == maxValue && leftHandle.frame.midX == rightHandle.frame.midX {
handleTracking = .left
} else {
handleTracking = .right
}
let handle: CALayer = (handleTracking == .left) ? leftHandle : rightHandle
animate(handle: handle, selected: true)
delegate?.didStartTouches(in: self)
return true
}
open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
guard handleTracking != .none else { return false }
let location: CGPoint = touch.location(in: self)
// find out the percentage along the line we are in x coordinate terms (subtracting half the frames width to account for moving the middle of the handle, not the left hand side)
let percentage: CGFloat = (location.x - sliderLine.frame.minX - handleDiameter / 2.0) / (sliderLine.frame.maxX - sliderLine.frame.minX)
// multiply that percentage by self.maxValue to get the new selected minimum value
let selectedValue: CGFloat = percentage * (maxValue - minValue) + minValue
switch handleTracking {
case .left:
selectedMinValue = min(selectedValue, selectedMaxValue)
case .right:
// don't let the dots cross over, (unless range is disabled, in which case just dont let the dot fall off the end of the screen)
if disableRange && selectedValue >= minValue {
selectedMaxValue = selectedValue
} else {
selectedMaxValue = max(selectedValue, selectedMinValue)
}
case .none:
// no need to refresh the view because it is done as a side-effect of setting the property
break
}
refresh()
return true
}
open override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
let handle: CALayer = (handleTracking == .left) ? leftHandle : rightHandle
animate(handle: handle, selected: false)
handleTracking = .none
delegate?.didEndTouches(in: self)
}
// MARK: - UIAccessibility
open override func accessibilityElementCount() -> Int {
return accessibleElements.count
}
open override func accessibilityElement(at index: Int) -> Any? {
return accessibleElements[index]
}
open override func index(ofAccessibilityElement element: Any) -> Int {
guard let element = element as? UIAccessibilityElement else { return 0 }
return accessibleElements.firstIndex(of: element) ?? 0
}
// MARK: - open methods
/// When subclassing **RangeSeekSlider** and setting each item in **setupStyle()**, the design is reflected in Interface Builder as well.
open func setupStyle() {}
// MARK: - private methods
private func setup() {
isAccessibilityElement = false
accessibleElements = [leftHandleAccessibilityElement, rightHandleAccessibilityElement]
// draw the slider line
layer.addSublayer(sliderLine)
// draw the track distline
layer.addSublayer(sliderLineBetweenHandles)
// draw the minimum slider handle
leftHandle.cornerRadius = handleDiameter / 2.0
leftHandle.borderWidth = handleBorderWidth
layer.addSublayer(leftHandle)
// draw the maximum slider handle
rightHandle.cornerRadius = handleDiameter / 2.0
rightHandle.borderWidth = handleBorderWidth
layer.addSublayer(rightHandle)
let handleFrame: CGRect = CGRect(x: 0.0, y: 0.0, width: handleDiameter, height: handleDiameter)
leftHandle.frame = handleFrame
rightHandle.frame = handleFrame
// draw the text labels
let labelFontSize: CGFloat = 12.0
let labelFrame: CGRect = CGRect(x: 0.0, y: 50.0, width: 75.0, height: 14.0)
minLabelFont = UIFont.systemFont(ofSize: labelFontSize)
minLabel.alignmentMode = CATextLayerAlignmentMode.center
minLabel.frame = labelFrame
minLabel.contentsScale = UIScreen.main.scale
layer.addSublayer(minLabel)
maxLabelFont = UIFont.systemFont(ofSize: labelFontSize)
maxLabel.alignmentMode = CATextLayerAlignmentMode.center
maxLabel.frame = labelFrame
maxLabel.contentsScale = UIScreen.main.scale
layer.addSublayer(maxLabel)
setupStyle()
refresh()
}
private func percentageAlongLine(for value: CGFloat) -> CGFloat {
// stops divide by zero errors where maxMinDif would be zero. If the min and max are the same the percentage has no point.
guard minValue < maxValue else { return 0.0 }
// get the difference between the maximum and minimum values (e.g if max was 100, and min was 50, difference is 50)
let maxMinDif: CGFloat = maxValue - minValue
// now subtract value from the minValue (e.g if value is 75, then 75-50 = 25)
let valueSubtracted: CGFloat = value - minValue
// now divide valueSubtracted by maxMinDif to get the percentage (e.g 25/50 = 0.5)
return valueSubtracted / maxMinDif
}
private func xPositionAlongLine(for value: CGFloat) -> CGFloat {
// first get the percentage along the line for the value
let percentage: CGFloat = percentageAlongLine(for: value)
// get the difference between the maximum and minimum coordinate position x values (e.g if max was x = 310, and min was x=10, difference is 300)
let maxMinDif: CGFloat = sliderLine.frame.maxX - sliderLine.frame.minX
// now multiply the percentage by the minMaxDif to see how far along the line the point should be, and add it onto the minimum x position.
let offset: CGFloat = percentage * maxMinDif
return sliderLine.frame.minX + offset
}
private func updateLineHeight() {
let barSidePadding: CGFloat = 16.0
let yMiddle: CGFloat = frame.height / 2.0
let lineLeftSide: CGPoint = CGPoint(x: barSidePadding, y: yMiddle)
let lineRightSide: CGPoint = CGPoint(x: frame.width - barSidePadding,
y: yMiddle)
sliderLine.frame = CGRect(x: lineLeftSide.x,
y: lineLeftSide.y,
width: lineRightSide.x - lineLeftSide.x,
height: lineHeight)
sliderLine.cornerRadius = lineHeight / 2.0
sliderLineBetweenHandles.cornerRadius = sliderLine.cornerRadius
}
private func updateLabelValues() {
minLabel.isHidden = hideLabels || disableRange
maxLabel.isHidden = hideLabels
if let replacedString = delegate?.rangeSeekSlider(self, stringForMinValue: selectedMinValue) {
minLabel.string = replacedString
} else {
if let lengthFormatter = lengthFormatter {
let heightCentimeters = Measurement(value: Double(selectedMinValue), unit: UnitLength.meters)
let meters = heightCentimeters.converted(to: .meters).value
minLabel.string = lengthFormatter.string(fromMeters: meters)
} else {
minLabel.string = numberFormatter.string(from: selectedMinValue as NSNumber)
}
}
if let replacedString = delegate?.rangeSeekSlider(self, stringForMaxValue: selectedMaxValue) {
maxLabel.string = replacedString
} else {
if let lengthFormatter = lengthFormatter {
let heightCentimeters = Measurement(value: Double(selectedMaxValue), unit: UnitLength.meters)
let meters = heightCentimeters.converted(to: .meters).value
maxLabel.string = lengthFormatter.string(fromMeters: meters)
} else {
maxLabel.string = numberFormatter.string(from: selectedMaxValue as NSNumber)
}
}
if let nsstring = minLabel.string as? NSString {
minLabelTextSize = nsstring.size(withAttributes: [.font: minLabelFont])
}
if let nsstring = maxLabel.string as? NSString {
maxLabelTextSize = nsstring.size(withAttributes: [.font: maxLabelFont])
}
}
private func updateColors() {
let isInitial: Bool = selectedMinValue == minValue && selectedMaxValue == maxValue
if let initialColor = initialColor?.cgColor, isInitial {
minLabel.foregroundColor = initialColor
maxLabel.foregroundColor = initialColor
sliderLineBetweenHandles.backgroundColor = initialColor
sliderLine.backgroundColor = initialColor
let color: CGColor = (handleImage == nil) ? initialColor : UIColor.clear.cgColor
leftHandle.backgroundColor = color
leftHandle.borderColor = color
rightHandle.backgroundColor = color
rightHandle.borderColor = color
} else {
let tintCGColor: CGColor = tintColor.cgColor
minLabel.foregroundColor = minLabelColor?.cgColor ?? tintCGColor
maxLabel.foregroundColor = maxLabelColor?.cgColor ?? tintCGColor
sliderLineBetweenHandles.backgroundColor = colorBetweenHandles?.cgColor ?? tintCGColor
sliderLine.backgroundColor = tintCGColor
let color: CGColor
if let _ = handleImage {
color = UIColor.clear.cgColor
} else {
color = handleColor?.cgColor ?? tintCGColor
}
leftHandle.backgroundColor = color
leftHandle.borderColor = handleBorderColor.map { $0.cgColor }
rightHandle.backgroundColor = color
rightHandle.borderColor = handleBorderColor.map { $0.cgColor }
}
}
private func updateAccessibilityElements() {
accessibleElements = [leftHandleAccessibilityElement, rightHandleAccessibilityElement]
}
private func updateHandlePositions() {
leftHandle.position = CGPoint(x: xPositionAlongLine(for: selectedMinValue),
y: sliderLine.frame.midY)
rightHandle.position = CGPoint(x: xPositionAlongLine(for: selectedMaxValue),
y: sliderLine.frame.midY)
// positioning for the dist slider line
sliderLineBetweenHandles.frame = CGRect(x: leftHandle.position.x,
y: sliderLine.frame.minY,
width: rightHandle.position.x - leftHandle.position.x,
height: lineHeight)
}
private func updateLabelPositions() {
// the center points for the labels are X = the same x position as the relevant handle. Y = the y position of the handle minus half the height of the text label, minus some padding.
minLabel.frame.size = minLabelTextSize
maxLabel.frame.size = maxLabelTextSize
if labelsFixed {
updateFixedLabelPositions()
return
}
let minSpacingBetweenLabels: CGFloat = 8.0
let newMinLabelCenter: CGPoint = CGPoint(x: leftHandle.frame.midX,
y: leftHandle.frame.maxY + (minLabelTextSize.height/2) + labelPadding)
let newMaxLabelCenter: CGPoint = CGPoint(x: rightHandle.frame.midX,
y: rightHandle.frame.maxY + (maxLabelTextSize.height/2) + labelPadding)
let newLeftMostXInMaxLabel: CGFloat = newMaxLabelCenter.x - maxLabelTextSize.width / 2.0
let newRightMostXInMinLabel: CGFloat = newMinLabelCenter.x + minLabelTextSize.width / 2.0
let newSpacingBetweenTextLabels: CGFloat = newLeftMostXInMaxLabel - newRightMostXInMinLabel
if disableRange || newSpacingBetweenTextLabels > minSpacingBetweenLabels {
minLabel.position = newMinLabelCenter
maxLabel.position = newMaxLabelCenter
if minLabel.frame.minX < 0.0 {
minLabel.frame.origin.x = 0.0
}
if maxLabel.frame.maxX > frame.width {
maxLabel.frame.origin.x = frame.width - maxLabel.frame.width
}
} else {
let increaseAmount: CGFloat = minSpacingBetweenLabels - newSpacingBetweenTextLabels
minLabel.position = CGPoint(x: newMinLabelCenter.x - increaseAmount / 2.0, y: newMinLabelCenter.y)
maxLabel.position = CGPoint(x: newMaxLabelCenter.x + increaseAmount / 2.0, y: newMaxLabelCenter.y)
// Update x if they are still in the original position
if minLabel.position.x == maxLabel.position.x {
minLabel.position.x = leftHandle.frame.midX
maxLabel.position.x = leftHandle.frame.midX + minLabel.frame.width / 2.0 + minSpacingBetweenLabels + maxLabel.frame.width / 2.0
}
if minLabel.frame.minX < 0.0 {
minLabel.frame.origin.x = 0.0
maxLabel.frame.origin.x = minSpacingBetweenLabels + minLabel.frame.width
}
if maxLabel.frame.maxX > frame.width {
maxLabel.frame.origin.x = frame.width - maxLabel.frame.width
minLabel.frame.origin.x = maxLabel.frame.origin.x - minSpacingBetweenLabels - minLabel.frame.width
}
}
}
private func updateFixedLabelPositions() {
minLabel.position = CGPoint(x: xPositionAlongLine(for: minValue),
y: sliderLine.frame.minY - (minLabelTextSize.height / 2.0) - (handleDiameter / 2.0) - labelPadding)
maxLabel.position = CGPoint(x: xPositionAlongLine(for: maxValue),
y: sliderLine.frame.minY - (maxLabelTextSize.height / 2.0) - (handleDiameter / 2.0) - labelPadding)
if minLabel.frame.minX < 0.0 {
minLabel.frame.origin.x = 0.0
}
if maxLabel.frame.maxX > frame.width {
maxLabel.frame.origin.x = frame.width - maxLabel.frame.width
}
}
fileprivate func refresh() {
if enableStep && step > 0.0 {
selectedMinValue = CGFloat(roundf(Float(selectedMinValue / step))) * step
if let previousStepMinValue = previousStepMinValue, previousStepMinValue != selectedMinValue {
TapticEngine.selection.feedback()
}
previousStepMinValue = selectedMinValue
selectedMaxValue = CGFloat(roundf(Float(selectedMaxValue / step))) * step
if let previousStepMaxValue = previousStepMaxValue, previousStepMaxValue != selectedMaxValue {
TapticEngine.selection.feedback()
}
previousStepMaxValue = selectedMaxValue
}
let diff: CGFloat = selectedMaxValue - selectedMinValue
if diff < minDistance {
switch handleTracking {
case .left:
selectedMinValue = selectedMaxValue - minDistance
case .right:
selectedMaxValue = selectedMinValue + minDistance
case .none:
break
}
} else if diff > maxDistance {
switch handleTracking {
case .left:
selectedMinValue = selectedMaxValue - maxDistance
case .right:
selectedMaxValue = selectedMinValue + maxDistance
case .none:
break
}
}
// ensure the minimum and maximum selected values are within range. Access the values directly so we don't cause this refresh method to be called again (otherwise changing the properties causes a refresh)
if selectedMinValue < minValue {
selectedMinValue = minValue
}
if selectedMaxValue > maxValue {
selectedMaxValue = maxValue
}
// update the frames in a transaction so that the tracking doesn't continue until the frame has moved.
CATransaction.begin()
CATransaction.setDisableActions(true)
updateHandlePositions()
updateLabelPositions()
CATransaction.commit()
updateLabelValues()
updateColors()
updateAccessibilityElements()
// update the delegate
if let delegate = delegate, handleTracking != .none {
delegate.rangeSeekSlider(self, didChange: selectedMinValue, maxValue: selectedMaxValue)
}
}
private func animate(handle: CALayer, selected: Bool) {
let transform: CATransform3D
if selected {
transform = CATransform3DMakeScale(selectedHandleDiameterMultiplier, selectedHandleDiameterMultiplier, 1.0)
} else {
transform = CATransform3DIdentity
}
CATransaction.begin()
CATransaction.setAnimationDuration(0.3)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut))
handle.transform = transform
// the label above the handle will need to move too if the handle changes size
updateLabelPositions()
CATransaction.commit()
}
}
// MARK: - RangeSeekSliderLeftElement
private final class RangeSeekSliderLeftElement: UIAccessibilityElement {
override func accessibilityIncrement() {
guard let slider = accessibilityContainer as? RangeSeekSlider else { return }
slider.selectedMinValue += slider.step
accessibilityValue = slider.minLabel.string as? String
}
override func accessibilityDecrement() {
guard let slider = accessibilityContainer as? RangeSeekSlider else { return }
slider.selectedMinValue -= slider.step
accessibilityValue = slider.minLabel.string as? String
}
}
// MARK: - RangeSeekSliderRightElement
private final class RangeSeekSliderRightElement: UIAccessibilityElement {
override func accessibilityIncrement() {
guard let slider = accessibilityContainer as? RangeSeekSlider else { return }
slider.selectedMaxValue += slider.step
slider.refresh()
accessibilityValue = slider.maxLabel.string as? String
}
override func accessibilityDecrement() {
guard let slider = accessibilityContainer as? RangeSeekSlider else { return }
slider.selectedMaxValue -= slider.step
slider.refresh()
accessibilityValue = slider.maxLabel.string as? String
}
}
// MARK: - CGRect
private extension CGRect {
var center: CGPoint {
return CGPoint(x: midX, y: midY)
}
}
// MARK: - CGPoint
private extension CGPoint {
func distance(to: CGPoint) -> CGFloat {
let distX: CGFloat = to.x - x
let distY: CGFloat = to.y - y
return sqrt(distX * distX + distY * distY)
}
}
| 39.317949 | 247 | 0.650026 |
4a2eeb118a6ebe30cb0c6d86a42b8678e7264286 | 11,188 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: kava/committee/v1beta1/genesis.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// VoteType enumerates the valid types of a vote.
enum Kava_Committee_V1beta1_VoteType: SwiftProtobuf.Enum {
typealias RawValue = Int
/// VOTE_TYPE_UNSPECIFIED defines a no-op vote option.
case unspecified // = 0
/// VOTE_TYPE_YES defines a yes vote option.
case yes // = 1
/// VOTE_TYPE_NO defines a no vote option.
case no // = 2
/// VOTE_TYPE_ABSTAIN defines an abstain vote option.
case abstain // = 3
case UNRECOGNIZED(Int)
init() {
self = .unspecified
}
init?(rawValue: Int) {
switch rawValue {
case 0: self = .unspecified
case 1: self = .yes
case 2: self = .no
case 3: self = .abstain
default: self = .UNRECOGNIZED(rawValue)
}
}
var rawValue: Int {
switch self {
case .unspecified: return 0
case .yes: return 1
case .no: return 2
case .abstain: return 3
case .UNRECOGNIZED(let i): return i
}
}
}
#if swift(>=4.2)
extension Kava_Committee_V1beta1_VoteType: CaseIterable {
// The compiler won't synthesize support with the UNRECOGNIZED case.
static var allCases: [Kava_Committee_V1beta1_VoteType] = [
.unspecified,
.yes,
.no,
.abstain,
]
}
#endif // swift(>=4.2)
/// GenesisState defines the committee module's genesis state.
struct Kava_Committee_V1beta1_GenesisState {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var nextProposalID: UInt64 = 0
var committees: [Google_Protobuf2_Any] = []
var proposals: [Kava_Committee_V1beta1_Proposal] = []
var votes: [Kava_Committee_V1beta1_Vote] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Proposal is an internal record of a governance proposal submitted to a committee.
struct Kava_Committee_V1beta1_Proposal {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var content: Google_Protobuf2_Any {
get {return _content ?? Google_Protobuf2_Any()}
set {_content = newValue}
}
/// Returns true if `content` has been explicitly set.
var hasContent: Bool {return self._content != nil}
/// Clears the value of `content`. Subsequent reads from it will return its default value.
mutating func clearContent() {self._content = nil}
var id: UInt64 = 0
var committeeID: UInt64 = 0
var deadline: SwiftProtobuf.Google_Protobuf_Timestamp {
get {return _deadline ?? SwiftProtobuf.Google_Protobuf_Timestamp()}
set {_deadline = newValue}
}
/// Returns true if `deadline` has been explicitly set.
var hasDeadline: Bool {return self._deadline != nil}
/// Clears the value of `deadline`. Subsequent reads from it will return its default value.
mutating func clearDeadline() {self._deadline = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _content: Google_Protobuf2_Any? = nil
fileprivate var _deadline: SwiftProtobuf.Google_Protobuf_Timestamp? = nil
}
/// Vote is an internal record of a single governance vote.
struct Kava_Committee_V1beta1_Vote {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var proposalID: UInt64 = 0
var voter: Data = Data()
var voteType: Kava_Committee_V1beta1_VoteType = .unspecified
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "kava.committee.v1beta1"
extension Kava_Committee_V1beta1_VoteType: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "VOTE_TYPE_UNSPECIFIED"),
1: .same(proto: "VOTE_TYPE_YES"),
2: .same(proto: "VOTE_TYPE_NO"),
3: .same(proto: "VOTE_TYPE_ABSTAIN"),
]
}
extension Kava_Committee_V1beta1_GenesisState: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".GenesisState"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "next_proposal_id"),
2: .same(proto: "committees"),
3: .same(proto: "proposals"),
4: .same(proto: "votes"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularUInt64Field(value: &self.nextProposalID) }()
case 2: try { try decoder.decodeRepeatedMessageField(value: &self.committees) }()
case 3: try { try decoder.decodeRepeatedMessageField(value: &self.proposals) }()
case 4: try { try decoder.decodeRepeatedMessageField(value: &self.votes) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.nextProposalID != 0 {
try visitor.visitSingularUInt64Field(value: self.nextProposalID, fieldNumber: 1)
}
if !self.committees.isEmpty {
try visitor.visitRepeatedMessageField(value: self.committees, fieldNumber: 2)
}
if !self.proposals.isEmpty {
try visitor.visitRepeatedMessageField(value: self.proposals, fieldNumber: 3)
}
if !self.votes.isEmpty {
try visitor.visitRepeatedMessageField(value: self.votes, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Kava_Committee_V1beta1_GenesisState, rhs: Kava_Committee_V1beta1_GenesisState) -> Bool {
if lhs.nextProposalID != rhs.nextProposalID {return false}
if lhs.committees != rhs.committees {return false}
if lhs.proposals != rhs.proposals {return false}
if lhs.votes != rhs.votes {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Kava_Committee_V1beta1_Proposal: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Proposal"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "content"),
2: .same(proto: "id"),
3: .standard(proto: "committee_id"),
4: .same(proto: "deadline"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularMessageField(value: &self._content) }()
case 2: try { try decoder.decodeSingularUInt64Field(value: &self.id) }()
case 3: try { try decoder.decodeSingularUInt64Field(value: &self.committeeID) }()
case 4: try { try decoder.decodeSingularMessageField(value: &self._deadline) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._content {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
if self.id != 0 {
try visitor.visitSingularUInt64Field(value: self.id, fieldNumber: 2)
}
if self.committeeID != 0 {
try visitor.visitSingularUInt64Field(value: self.committeeID, fieldNumber: 3)
}
if let v = self._deadline {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Kava_Committee_V1beta1_Proposal, rhs: Kava_Committee_V1beta1_Proposal) -> Bool {
if lhs._content != rhs._content {return false}
if lhs.id != rhs.id {return false}
if lhs.committeeID != rhs.committeeID {return false}
if lhs._deadline != rhs._deadline {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Kava_Committee_V1beta1_Vote: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Vote"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "proposal_id"),
2: .same(proto: "voter"),
3: .standard(proto: "vote_type"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularUInt64Field(value: &self.proposalID) }()
case 2: try { try decoder.decodeSingularBytesField(value: &self.voter) }()
case 3: try { try decoder.decodeSingularEnumField(value: &self.voteType) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.proposalID != 0 {
try visitor.visitSingularUInt64Field(value: self.proposalID, fieldNumber: 1)
}
if !self.voter.isEmpty {
try visitor.visitSingularBytesField(value: self.voter, fieldNumber: 2)
}
if self.voteType != .unspecified {
try visitor.visitSingularEnumField(value: self.voteType, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Kava_Committee_V1beta1_Vote, rhs: Kava_Committee_V1beta1_Vote) -> Bool {
if lhs.proposalID != rhs.proposalID {return false}
if lhs.voter != rhs.voter {return false}
if lhs.voteType != rhs.voteType {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 36.324675 | 147 | 0.718716 |
f746b9469cb74f1297bc1aea731e0a0c06a4ccb7 | 1,399 | //
// BaseTestCase.swift
//
// Copyright 2015-present, Nike, Inc.
// All rights reserved.
//
// This source code is licensed under the BSD-stylelicense found in the LICENSE
// file in the root directory of this source tree.
//
import Foundation
import SQift
import SQLite3
import XCTest
class BaseTestCase: XCTestCase {
// MARK: - Properties
let timeout: TimeInterval = 10.0
let storageLocation: StorageLocation = {
let path = FileManager.cachesDirectory.appending("/sqift_tests.db")
return .onDisk(path)
}()
// MARK: - Setup and Teardown
override func setUp() {
super.setUp()
let dbPath = storageLocation.path
let shmPath = dbPath + "-shm"
let walPath = dbPath + "-wal"
[dbPath, shmPath, walPath].forEach { FileManager.removeItem(atPath: $0) }
}
}
// MARK: -
class BaseConnectionTestCase: BaseTestCase {
// MARK: - Properties
var connection: Connection!
// MARK: - Setup and Teardown
override func setUp() {
super.setUp()
do {
connection = try Connection(storageLocation: storageLocation)
XCTAssertNotNil(connection)
try TestTables.createAndPopulateAgentsTable(using: connection)
} catch {
// No-op
}
}
override func tearDown() {
connection = nil
super.tearDown()
}
}
| 20.880597 | 81 | 0.622588 |
e4f6392f521f48d38e00a4568e65e4ce9018343f | 275 | //
// Created by Brian Coyner on 4/28/18.
// Copyright © 2018 Brian Coyner. All rights reserved.
//
import Foundation
protocol MenuBuilder {
/// The title of the view controller displaying the `[Menu]`.
var title: String { get }
func makeMenu() -> [Menu]
}
| 18.333333 | 65 | 0.654545 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.