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
|
---|---|---|---|---|---|
483ab45a136ba8f6e0f025d9401d843a28bc1d78 | 715 | //
// divide.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
extension AKOperation {
/// Division of parameters
///
/// - returns: AKOperation
/// - parameter parameter: The amount to divide
///
public func dividedBy(parameter: AKParameter) -> AKOperation {
return AKOperation("(\(self) \(parameter) /)")
}
}
/// Helper function for Division
///
/// - returns: AKOperation
/// - parameter left: 1st parameter
/// - parameter right: 2nd parameter
///
public func /(left: AKParameter, right: AKParameter) -> AKOperation {
return left.toMono().dividedBy(right)
}
| 22.34375 | 69 | 0.658741 |
8757c8d84797fb4f90a5ebd9f8d3fe8a72c835d1 | 2,183 | //
// AppDelegate.swift
// ListViewAutoHeightExtention
//
// Created by nothot on 03/31/2021.
// Copyright (c) 2021 nothot. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.446809 | 285 | 0.755841 |
1c59a750fcfded1326c04e3db08d81d6742e5633 | 684 | //
// Copyright © 2019 Artem Novichkov. All rights reserved.
//
import SPMUtility
import CartingCore
extension Format: ArgumentKind {
enum Error: Swift.Error {
case invalid
}
public static let completion: ShellCompletion = .values(Format.allCases.map { ($0.rawValue, $0.rawValue) })
public init(argument: String) throws {
guard let format = Format(rawValue: argument.lowercased()) else {
throw Error.invalid
}
self = format
}
}
extension Format.Error: CustomStringConvertible {
var description: String {
switch self {
case .invalid:
return "Unsupported format."
}
}
}
| 20.727273 | 111 | 0.627193 |
1e27ea792f83607e3a08c44773907d8785c7ffd4 | 380 | //
// User.swift
// PMFramework
//
// Created by Den Andreychuk on 18.03.2022.
//
import Foundation
import SwiftyBeaver
let log = SwiftyBeaver.self
public class User {
let name: String
public init(name: String) {
self.name = name
}
public func sayHello() {
log.info("Hello for \(name)")
print("Hello, \(name)")
}
}
| 14.615385 | 44 | 0.576316 |
e98f753a519ad06c8c30655aa275d09eaae615a1 | 2,160 | //
// AppDelegate.swift
// Worm
//
// Created by wbitos on 01/07/2022.
// Copyright (c) 2022 wbitos. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.957447 | 285 | 0.753241 |
0e65f39eece8698e5b6d1f2b0113f1b060de5db8 | 34,760 | import UIKit
enum CheckoutStep: String {
case START
case ACTION_FINISH
case SCREEN_SECURITY_CODE
case SERVICE_CREATE_CARD_TOKEN
case SERVICE_POST_PAYMENT
case SERVICE_GET_REMEDY
case SCREEN_PAYMENT_RESULT
case SCREEN_ERROR
case SCREEN_PAYMENT_METHOD_PLUGIN_CONFIG
case FLOW_ONE_TAP
}
class MercadoPagoCheckoutViewModel: NSObject, NSCopying {
private var advancedConfig: PXAdvancedConfiguration = PXAdvancedConfiguration()
var trackingConfig: PXTrackingConfiguration?
var publicKey: String
var privateKey: String?
var checkoutType: String?
var lifecycleProtocol: PXLifeCycleProtocol?
// In order to ensure data updated create new instance for every usage
var amountHelper: PXAmountHelper {
guard let paymentData = paymentData.copy() as? PXPaymentData else {
fatalError("Cannot find payment data")
}
return PXAmountHelper(preference: checkoutPreference, paymentData: paymentData, chargeRules: chargeRules, paymentConfigurationService: paymentConfigurationService, splitAccountMoney: splitAccountMoney)
}
var checkoutPreference: PXCheckoutPreference!
let mercadoPagoServices: MercadoPagoServices
// var paymentMethods: [PaymentMethod]?
var cardToken: PXCardToken?
var customerId: String?
// Payment methods disponibles en selección de medio de pago
var paymentMethodOptions: [PaymentMethodOption]?
var paymentOptionSelected: PaymentMethodOption?
// Payment method disponibles correspondientes a las opciones que se muestran en selección de medio de pago
var availablePaymentMethods: [PXPaymentMethod]?
var rootPaymentMethodOptions: [PaymentMethodOption]?
var customPaymentOptions: [CustomerPaymentMethod]?
var customRemedyMessages: PXCustomStringConfiguration?
var remedy: PXRemedy?
var search: PXInitDTO?
var rootVC = true
var paymentData = PXPaymentData()
var splitAccountMoney: PXPaymentData?
var payment: PXPayment?
var paymentResult: PaymentResult?
var disabledOption: PXDisabledOption?
var businessResult: PXBusinessResult?
open var payerCosts: [PXPayerCost]?
@available(*, deprecated, message: "No longer used")
open var issuers: [PXIssuer]?
open var entityTypes: [EntityType]?
open var financialInstitutions: [PXFinancialInstitution]?
open var instructionsInfo: PXInstruction?
open var pointsAndDiscounts: PXPointsAndDiscounts?
static var error: MPSDKError?
var errorCallback: (() -> Void)?
var readyToPay: Bool = false
var initWithPaymentData = false
var savedESCCardToken: PXSavedESCCardToken?
private var checkoutComplete = false
var paymentMethodConfigPluginShowed = false
var invalidESCReason: PXESCDeleteReason?
// Discounts bussines service.
var paymentConfigurationService = PXPaymentConfigurationServices()
// Payment plugin
var paymentPlugin: PXSplitPaymentProcessor?
private(set) var paymentFlow: PXPaymentFlow?
// Discount and charges
var chargeRules: [PXPaymentTypeChargeRule]?
// Init Flow
var initFlow: InitFlow?
weak var initFlowProtocol: InitFlowProtocol?
// OneTap Flow
var onetapFlow: OneTapFlow?
var postPaymentNotificationName: Notification.Name?
lazy var pxNavigationHandler: PXNavigationHandler = PXNavigationHandler.getDefault()
init(checkoutPreference: PXCheckoutPreference, publicKey: String, privateKey: String?, advancedConfig: PXAdvancedConfiguration? = nil, trackingConfig: PXTrackingConfiguration? = nil, checkoutType: String?) {
self.publicKey = publicKey
self.privateKey = privateKey
self.checkoutType = checkoutType
self.checkoutPreference = checkoutPreference
if let advancedConfig = advancedConfig {
self.advancedConfig = advancedConfig
}
self.trackingConfig = trackingConfig
mercadoPagoServices = MercadoPagoServices(publicKey: publicKey, privateKey: privateKey, checkoutType: checkoutType)
super.init()
if String.isNullOrEmpty(checkoutPreference.id), checkoutPreference.payer != nil {
paymentData.updatePaymentDataWith(payer: checkoutPreference.getPayer())
}
PXConfiguratorManager.escConfig = PXESCConfig.createConfig()
PXConfiguratorManager.threeDSConfig = PXThreeDSConfig.createConfig(privateKey: privateKey)
// Create Init Flow
createInitFlow()
}
public func copy(with zone: NSZone? = nil) -> Any {
let copyObj = MercadoPagoCheckoutViewModel(checkoutPreference: self.checkoutPreference, publicKey: publicKey, privateKey: privateKey, checkoutType: checkoutType)
copyObj.setNavigationHandler(handler: pxNavigationHandler)
return copyObj
}
func setNavigationHandler(handler: PXNavigationHandler) {
pxNavigationHandler = handler
}
func setPostPaymentNotification(postPaymentNotificationName: Notification.Name) {
self.postPaymentNotificationName = postPaymentNotificationName
}
func hasError() -> Bool {
return MercadoPagoCheckoutViewModel.error != nil
}
func applyDefaultDiscountOrClear() {
if let defaultDiscountConfiguration = search?.selectedDiscountConfiguration {
attemptToApplyDiscount(defaultDiscountConfiguration)
} else {
clearDiscount()
}
}
func attemptToApplyDiscount(_ discountConfiguration: PXDiscountConfiguration?) {
guard let discountConfiguration = discountConfiguration else {
clearDiscount()
return
}
guard let campaign = discountConfiguration.getDiscountConfiguration().campaign, shouldApplyDiscount() else {
clearDiscount()
return
}
let discount = discountConfiguration.getDiscountConfiguration().discount
let consumedDiscount = !discountConfiguration.getDiscountConfiguration().isAvailable
let discountDescription = discountConfiguration.getDiscountConfiguration().discountDescription
self.paymentData.setDiscount(discount, withCampaign: campaign, consumedDiscount: consumedDiscount, discountDescription: discountDescription)
}
func clearDiscount() {
self.paymentData.clearDiscount()
}
func shouldApplyDiscount() -> Bool {
return paymentPlugin != nil
}
public func getPaymentPreferences() -> PXPaymentPreference? {
return self.checkoutPreference.paymentPreference
}
public func getPaymentMethodsForSelection() -> [PXPaymentMethod] {
let filteredPaymentMethods = search?.availablePaymentMethods.filter {
return $0.conformsPaymentPreferences(self.getPaymentPreferences()) && $0.paymentTypeId == self.paymentOptionSelected?.getId()
}
guard let paymentMethods = filteredPaymentMethods else {
return []
}
return paymentMethods
}
// Returns list with all cards ids with esc
func getCardsIdsWithESC() -> [String] {
guard let customPaymentOptions = customPaymentOptions else { return [] }
let savedCardIds = PXConfiguratorManager.escProtocol.getSavedCardIds(config: PXConfiguratorManager.escConfig)
return customPaymentOptions
.filter { $0.containsSavedId(savedCardIds) }
.filter { PXConfiguratorManager.escProtocol.getESC(config: PXConfiguratorManager.escConfig,
cardId: $0.getCardId(),
firstSixDigits: $0.getFirstSixDigits(),
lastFourDigits: $0.getCardLastForDigits()) != nil
}
.map { $0.getCardId() }
}
public func getPXSecurityCodeViewModel(isCallForAuth: Bool = false) -> PXSecurityCodeViewModel {
let cardInformation: PXCardInformationForm
if let paymentOptionSelected = paymentOptionSelected as? PXCardInformationForm {
cardInformation = paymentOptionSelected
} else if isCallForAuth, let token = paymentData.token {
cardInformation = token
} else {
fatalError("Cannot convert payment option selected to CardInformation")
}
guard let paymentMethod = paymentData.paymentMethod else {
fatalError("Don't have paymentData to open Security View Controller")
}
let reason = PXSecurityCodeViewModel.getSecurityCodeReason(invalidESCReason: invalidESCReason, isCallForAuth: isCallForAuth)
let cardSliderViewModel = onetapFlow?.model.pxOneTapViewModel?.getCardSliderViewModel(cardId: paymentOptionSelected?.getId())
let cardUI = cardSliderViewModel?.cardUI ?? TemplateCard()
let cardData = cardSliderViewModel?.selectedApplication?.cardData ?? PXCardDataFactory()
return PXSecurityCodeViewModel(paymentMethod: paymentMethod, cardInfo: cardInformation, reason: reason, cardUI: cardUI, cardData: cardData, internetProtocol: mercadoPagoServices)
}
func resultViewModel() -> PXResultViewModel {
guard let paymentResult = paymentResult else {
fatalError("paymentResult is nil")
}
var oneTapDto: PXOneTapDto?
if paymentResult.isRejectedWithRemedy(), let oneTap = search?.oneTap, let remedy = remedy {
let paymentMethodId = remedy.suggestedPaymentMethod?.alternativePaymentMethod?.paymentMethodId ?? paymentResult.paymentMethodId
if paymentMethodId == PXPaymentTypes.CONSUMER_CREDITS.rawValue {
oneTapDto = oneTap.first(where: { $0.paymentMethodId == paymentMethodId })
} else {
let cardId = remedy.suggestedPaymentMethod?.alternativePaymentMethod?.customOptionId ?? paymentResult.cardId
oneTapDto = oneTap.first(where: { $0.oneTapCard?.cardId == cardId })
if oneTapDto == nil {
oneTapDto = oneTap.first(where: { $0.paymentMethodId == cardId })
}
}
}
// if it is silver bullet update paymentData with suggestedPaymentMethod
if let suggestedPaymentMethod = remedy?.suggestedPaymentMethod {
updatePaymentData(suggestedPaymentMethod)
}
return PXResultViewModel(amountHelper: amountHelper, paymentResult: paymentResult, instructionsInfo: instructionsInfo, pointsAndDiscounts: pointsAndDiscounts, resultConfiguration: advancedConfig.paymentResultConfiguration, remedy: remedy, oneTapDto: oneTapDto)
}
// SEARCH_PAYMENT_METHODS
public func updateCheckoutModel(paymentMethods: [PXPaymentMethod], cardToken: PXCardToken?) {
self.cleanPayerCostSearch()
self.cleanRemedy()
self.paymentData.updatePaymentDataWith(paymentMethod: paymentMethods[0])
self.cardToken = cardToken
// Sets if esc is enabled to card token
self.cardToken?.setRequireESC(escEnabled: getAdvancedConfiguration().isESCEnabled())
}
// CREDIT_DEBIT
public func updateCheckoutModel(paymentMethod: PXPaymentMethod?) {
if let paymentMethod = paymentMethod {
self.paymentData.updatePaymentDataWith(paymentMethod: paymentMethod)
}
}
public func updateCheckoutModel(financialInstitution: PXFinancialInstitution) {
if let TDs = self.paymentData.transactionDetails {
TDs.financialInstitution = financialInstitution.id
} else {
let transactionDetails = PXTransactionDetails(externalResourceUrl: nil, financialInstitution: financialInstitution.id, installmentAmount: nil, netReivedAmount: nil, overpaidAmount: nil, totalPaidAmount: nil, paymentMethodReferenceId: nil)
self.paymentData.transactionDetails = transactionDetails
}
}
public func updateCheckoutModel(payer: PXPayer) {
self.paymentData.updatePaymentDataWith(payer: payer)
}
public func updateCheckoutModel(remedy: PXRemedy) {
self.remedy = remedy
}
public func updateCheckoutModel(identification: PXIdentification) {
self.paymentData.cleanToken()
self.paymentData.cleanIssuer()
self.paymentData.cleanPayerCost()
self.cleanPayerCostSearch()
if paymentData.hasPaymentMethod() && paymentData.getPaymentMethod()!.isCard {
self.cardToken!.cardholder!.identification = identification
} else {
paymentData.payer?.identification = identification
}
}
public func updateCheckoutModel(payerCost: PXPayerCost) {
self.paymentData.updatePaymentDataWith(payerCost: payerCost)
if let paymentOptionSelected = paymentOptionSelected {
if paymentOptionSelected.isCustomerPaymentMethod() {
self.paymentData.cleanToken()
}
}
}
public func updateCheckoutModel(entityType: EntityType) {
self.paymentData.payer?.entityType = entityType.entityTypeId
}
// MARK: PAYMENT METHOD OPTION SELECTION
public func updateCheckoutModel(paymentOptionSelected: PaymentMethodOption) {
if !self.initWithPaymentData {
resetInFormationOnNewPaymentMethodOptionSelected()
}
resetPaymentOptionSelectedWith(newPaymentOptionSelected: paymentOptionSelected)
}
public func updatePaymentOptionSelectedWithRemedy() {
let alternativePaymentMethod = remedy?.suggestedPaymentMethod?.alternativePaymentMethod
guard let customOptionSearchItem = search?.getPayerPaymentMethod(id: alternativePaymentMethod?.customOptionId, paymentMethodId: alternativePaymentMethod?.paymentMethodId, paymentTypeId: alternativePaymentMethod?.paymentTypeId),
customOptionSearchItem.isCustomerPaymentMethod() else { return }
updateCheckoutModel(paymentOptionSelected: customOptionSearchItem.getCustomerPaymentMethod())
if let payerCosts = paymentConfigurationService.getPayerCostsForPaymentMethod(paymentOptionID: customOptionSearchItem.getId(), paymentMethodId: customOptionSearchItem.paymentMethodId, paymentTypeId: customOptionSearchItem.getPaymentType()) {
self.payerCosts = payerCosts
if let installment = remedy?.suggestedPaymentMethod?.alternativePaymentMethod?.installmentsList?.first,
let payerCost = payerCosts.first(where: { $0.installments == installment.installments }) {
updateCheckoutModel(payerCost: payerCost)
} else if let defaultPayerCost = checkoutPreference.paymentPreference.autoSelectPayerCost(payerCosts) {
updateCheckoutModel(payerCost: defaultPayerCost)
}
} else {
payerCosts = nil
}
if let discountConfiguration = paymentConfigurationService.getDiscountConfigurationForPaymentMethod(paymentOptionID: customOptionSearchItem.getId(), paymentMethodId: customOptionSearchItem.paymentMethodId, paymentTypeId: customOptionSearchItem.getPaymentType()) {
attemptToApplyDiscount(discountConfiguration)
} else {
applyDefaultDiscountOrClear()
}
}
public func resetPaymentOptionSelectedWith(newPaymentOptionSelected: PaymentMethodOption) {
self.paymentOptionSelected = newPaymentOptionSelected
if let targetPlugin = paymentOptionSelected as? PXPaymentMethodPlugin {
self.paymentMethodPluginToPaymentMethod(plugin: targetPlugin)
return
}
if newPaymentOptionSelected.hasChildren() {
self.paymentMethodOptions = newPaymentOptionSelected.getChildren()
}
if self.paymentOptionSelected!.isCustomerPaymentMethod() {
self.findAndCompletePaymentMethodFor(paymentMethodId: newPaymentOptionSelected.getId())
} else if !newPaymentOptionSelected.isCard() && !newPaymentOptionSelected.hasChildren() {
self.paymentData.updatePaymentDataWith(paymentMethod: Utils.findPaymentMethod(self.availablePaymentMethods!, paymentMethodId: newPaymentOptionSelected.getId()), paymentOptionId: newPaymentOptionSelected.getId())
}
}
public func nextStep() -> CheckoutStep {
if needToInitFlow() {
return .START
}
if hasError() {
return .SCREEN_ERROR
}
if shouldExitCheckout() {
return .ACTION_FINISH
}
if needGetRemedy() {
return .SERVICE_GET_REMEDY
}
if shouldShowCongrats() {
return .SCREEN_PAYMENT_RESULT
}
if needOneTapFlow() {
return .FLOW_ONE_TAP
}
if needToShowPaymentMethodConfigPlugin() {
willShowPaymentMethodConfigPlugin()
return .SCREEN_PAYMENT_METHOD_PLUGIN_CONFIG
}
if needToCreatePayment() || shouldSkipReviewAndConfirm() {
readyToPay = false
return .SERVICE_POST_PAYMENT
}
if needSecurityCode() {
return .SCREEN_SECURITY_CODE
}
if needCreateToken() {
return .SERVICE_CREATE_CARD_TOKEN
}
return .ACTION_FINISH
}
fileprivate func autoselectOnlyPaymentMethod() {
guard let search = self.search else {
return
}
var paymentOptionSelected: PaymentMethodOption?
if !Array.isNullOrEmpty(search.payerPaymentMethods) && search.payerPaymentMethods.count == 1 {
paymentOptionSelected = search.payerPaymentMethods.first
}
if let paymentOptionSelected = paymentOptionSelected {
self.updateCheckoutModel(paymentOptionSelected: paymentOptionSelected)
}
}
func getPaymentOptionConfigurations(paymentMethodSearch: PXInitDTO) -> Set<PXPaymentMethodConfiguration> {
let discountConfigurationsKeys = paymentMethodSearch.coupons.keys
var configurations = Set<PXPaymentMethodConfiguration>()
for customOption in paymentMethodSearch.payerPaymentMethods {
var paymentOptionConfigurations = [PXPaymentOptionConfiguration]()
for key in discountConfigurationsKeys {
guard let discountConfiguration = paymentMethodSearch.coupons[key], let payerCostConfiguration = customOption.paymentOptions?[key] else {
continue
}
let paymentOptionConfiguration = PXPaymentOptionConfiguration(id: key, discountConfiguration: discountConfiguration, payerCostConfiguration: payerCostConfiguration)
paymentOptionConfigurations.append(paymentOptionConfiguration)
}
let paymentMethodConfiguration = PXPaymentMethodConfiguration(customOptionSearchItem: customOption, paymentOptionsConfigurations: paymentOptionConfigurations)
configurations.insert(paymentMethodConfiguration)
}
return configurations
}
func updateCustomTexts() {
// If AdditionalInfo has custom texts override the ones set by MercadoPagoCheckoutBuilder
if let customTexts = checkoutPreference.pxAdditionalInfo?.pxCustomTexts {
if let translation = customTexts.payButton {
Localizator.sharedInstance.addCustomTranslation(.pay_button, translation)
}
if let translation = customTexts.payButtonProgress {
Localizator.sharedInstance.addCustomTranslation(.pay_button_progress, translation)
}
if let translation = customTexts.totalDescription {
Localizator.sharedInstance.addCustomTranslation(.total_to_pay_onetap, translation)
}
}
}
public func updateCheckoutModel(paymentMethodSearch: PXInitDTO) {
let configurations = getPaymentOptionConfigurations(paymentMethodSearch: paymentMethodSearch)
self.paymentConfigurationService.setConfigurations(configurations)
self.paymentConfigurationService.setDefaultDiscountConfiguration(paymentMethodSearch.selectedDiscountConfiguration)
self.search = paymentMethodSearch
guard let search = self.search else {
return
}
self.paymentMethodOptions = self.rootPaymentMethodOptions
self.availablePaymentMethods = paymentMethodSearch.availablePaymentMethods
customPaymentOptions?.removeAll()
for pxCustomOptionSearchItem in search.payerPaymentMethods {
let customerPaymentMethod = pxCustomOptionSearchItem.getCustomerPaymentMethod()
customPaymentOptions = Array.safeAppend(customPaymentOptions, customerPaymentMethod)
}
let totalPaymentMethodSearchCount = (search.oneTap?.filter { $0.status.enabled })?.count
if totalPaymentMethodSearchCount == 0 {
self.errorInputs(error: MPSDKError(message: "Hubo un error".localized, errorDetail: "No se ha podido obtener los métodos de pago con esta preferencia".localized, retry: false), errorCallback: { () in
})
} else if totalPaymentMethodSearchCount == 1 {
autoselectOnlyPaymentMethod()
}
// MoneyIn "ChoExpress"
if let defaultPM = getPreferenceDefaultPaymentOption() {
updateCheckoutModel(paymentOptionSelected: defaultPM)
}
}
public func updateCheckoutModel(token: PXToken) {
if let esc = token.esc, !String.isNullOrEmpty(esc) {
PXConfiguratorManager.escProtocol.saveESC(config: PXConfiguratorManager.escConfig, token: token, esc: esc)
} else {
PXConfiguratorManager.escProtocol.deleteESC(config: PXConfiguratorManager.escConfig, token: token, reason: .NO_ESC, detail: nil)
}
self.paymentData.updatePaymentDataWith(token: token)
}
public func updateCheckoutModel(paymentMethodOptions: [PaymentMethodOption]) {
if self.rootPaymentMethodOptions != nil {
self.rootPaymentMethodOptions!.insert(contentsOf: paymentMethodOptions, at: 0)
} else {
self.rootPaymentMethodOptions = paymentMethodOptions
}
self.paymentMethodOptions = self.rootPaymentMethodOptions
}
func updateCheckoutModel(paymentData: PXPaymentData) {
self.paymentData = paymentData
if paymentData.getPaymentMethod() == nil {
prepareForNewSelection()
self.initWithPaymentData = false
} else {
self.readyToPay = !self.needToCompletePayerInfo()
}
}
func needToCompletePayerInfo() -> Bool {
if let paymentMethod = self.paymentData.getPaymentMethod() {
if paymentMethod.isPayerInfoRequired {
return !self.isPayerSetted()
}
}
return false
}
public func updateCheckoutModel(payment: PXPayment) {
self.payment = payment
self.paymentResult = PaymentResult(payment: self.payment!, paymentData: self.paymentData)
}
public func isCheckoutComplete() -> Bool {
return checkoutComplete
}
public func setIsCheckoutComplete(isCheckoutComplete: Bool) {
self.checkoutComplete = isCheckoutComplete
}
func findAndCompletePaymentMethodFor(paymentMethodId: String) {
guard let availablePaymentMethods = availablePaymentMethods else {
fatalError("availablePaymentMethods cannot be nil")
}
if paymentMethodId == PXPaymentTypes.ACCOUNT_MONEY.rawValue {
paymentData.updatePaymentDataWith(paymentMethod: Utils.findPaymentMethod(availablePaymentMethods, paymentMethodId: paymentMethodId), paymentOptionId: paymentOptionSelected?.getId())
} else if let cardInformation = paymentOptionSelected as? PXCardInformation {
if let paymentMethod = Utils.findPaymentMethod(availablePaymentMethods, paymentMethodId: cardInformation.getPaymentMethodId()) {
cardInformation.setupPaymentMethodSettings(paymentMethod.settings)
cardInformation.setupPaymentMethod(paymentMethod)
}
paymentData.updatePaymentDataWith(paymentMethod: cardInformation.getPaymentMethod())
paymentData.updatePaymentDataWith(issuer: cardInformation.getIssuer())
}
}
func hasCustomPaymentOptions() -> Bool {
return !Array.isNullOrEmpty(self.customPaymentOptions)
}
func handleCustomerPaymentMethod() {
guard let availablePaymentMethods = availablePaymentMethods else {
fatalError("availablePaymentMethods cannot be nil")
}
if let paymentMethodId = self.paymentOptionSelected?.getId(), paymentMethodId == PXPaymentTypes.ACCOUNT_MONEY.rawValue {
paymentData.updatePaymentDataWith(paymentMethod: Utils.findPaymentMethod(availablePaymentMethods, paymentMethodId: paymentMethodId))
} else {
// Se necesita completar información faltante de settings y pm para custom payment options
guard let cardInformation = paymentOptionSelected as? PXCardInformation else {
fatalError("Cannot convert paymentOptionSelected to CardInformation")
}
if let paymentMethod = Utils.findPaymentMethod(availablePaymentMethods, paymentMethodId: cardInformation.getPaymentMethodId()) {
cardInformation.setupPaymentMethodSettings(paymentMethod.settings)
cardInformation.setupPaymentMethod(paymentMethod)
}
paymentData.updatePaymentDataWith(paymentMethod: cardInformation.getPaymentMethod())
}
}
func entityTypesFinder(inDict: NSDictionary, forKey: String) -> [EntityType]? {
if let siteETsDictionary = inDict.value(forKey: forKey) as? NSDictionary {
let entityTypesKeys = siteETsDictionary.allKeys
var entityTypes = [EntityType]()
for ET in entityTypesKeys {
let entityType = EntityType()
if let etKey = ET as? String, let etValue = siteETsDictionary.value(forKey: etKey) as? String {
entityType.entityTypeId = etKey
entityType.name = etValue.localized
entityTypes.append(entityType)
}
}
return entityTypes
}
return nil
}
func getEntityTypes() -> [EntityType] {
let dictET = ResourceManager.shared.getDictionaryForResource(named: "EntityTypes")
let site = SiteManager.shared.getSiteId()
if let siteETs = entityTypesFinder(inDict: dictET!, forKey: site) {
return siteETs
} else {
let siteETs = entityTypesFinder(inDict: dictET!, forKey: "default")
return siteETs!
}
}
func errorInputs(error: MPSDKError, errorCallback: (() -> Void)?) {
MercadoPagoCheckoutViewModel.error = error
self.errorCallback = errorCallback
}
func populateCheckoutStore() {
PXCheckoutStore.sharedInstance.paymentDatas = [self.paymentData]
if let splitAccountMoney = amountHelper.splitAccountMoney {
PXCheckoutStore.sharedInstance.paymentDatas.append(splitAccountMoney)
}
PXCheckoutStore.sharedInstance.checkoutPreference = self.checkoutPreference
}
func getResult() -> PXResult? {
if let ourPayment = payment {
return ourPayment
} else {
return getGenericPayment()
}
}
func getGenericPayment() -> PXGenericPayment? {
if let paymentResponse = paymentResult {
return PXGenericPayment(status: paymentResponse.status, statusDetail: paymentResponse.statusDetail, paymentId: paymentResponse.paymentId, paymentMethodId: paymentResponse.paymentMethodId, paymentMethodTypeId: paymentResponse.paymentMethodTypeId)
} else if let businessResultResponse = businessResult {
return PXGenericPayment(status: businessResultResponse.paymentStatus, statusDetail: businessResultResponse.paymentStatusDetail, paymentId: businessResultResponse.getReceiptId(), paymentMethodId: businessResultResponse.getPaymentMethodId(), paymentMethodTypeId: businessResultResponse.getPaymentMethodTypeId())
}
return nil
}
func getOurPayment() -> PXPayment? {
return payment
}
}
extension MercadoPagoCheckoutViewModel {
func resetGroupSelection() {
self.paymentOptionSelected = nil
guard let search = self.search else {
return
}
self.updateCheckoutModel(paymentMethodSearch: search)
}
func resetInFormationOnNewPaymentMethodOptionSelected() {
resetInformation()
}
func resetInformation() {
self.clearCollectedData()
self.cardToken = nil
self.entityTypes = nil
self.financialInstitutions = nil
cleanPayerCostSearch()
resetPaymentMethodConfigPlugin()
}
func clearCollectedData() {
self.paymentData.clearPaymentMethodData()
self.paymentData.clearPayerData()
// Se setea nuevamente el payer que tenemos en la preferencia para no perder los datos
paymentData.updatePaymentDataWith(payer: checkoutPreference.getPayer())
}
func isPayerSetted() -> Bool {
if let payerData = self.paymentData.getPayer(),
let payerIdentification = payerData.identification {
let validPayer = payerIdentification.number != nil
return validPayer
}
return false
}
func cleanPayerCostSearch() {
self.payerCosts = nil
}
func cleanRemedy() {
self.remedy = nil
}
func cleanPaymentResult() {
self.payment = nil
self.paymentResult = nil
self.readyToPay = false
self.setIsCheckoutComplete(isCheckoutComplete: false)
self.paymentFlow?.cleanPayment()
}
func prepareForClone() {
self.cleanPaymentResult()
}
func prepareForNewSelection() {
self.keepDisabledOptionIfNeeded()
self.cleanPaymentResult()
self.cleanRemedy()
self.resetInformation()
self.resetGroupSelection()
self.applyDefaultDiscountOrClear()
self.rootVC = true
}
func isPXSecurityCodeViewControllerLastVC() -> Bool {
return pxNavigationHandler.navigationController.viewControllers.last is PXSecurityCodeViewController
}
func prepareForInvalidPaymentWithESC(reason: PXESCDeleteReason) {
if self.paymentData.isComplete() {
readyToPay = true
if let cardId = paymentData.getToken()?.cardId, cardId.isNotEmpty {
savedESCCardToken = PXSavedESCCardToken(cardId: cardId, esc: nil, requireESC: getAdvancedConfiguration().isESCEnabled())
PXConfiguratorManager.escProtocol.deleteESC(config: PXConfiguratorManager.escConfig, cardId: cardId, reason: reason, detail: nil)
}
}
self.paymentData.cleanToken()
}
static func clearEnviroment() {
MercadoPagoCheckoutViewModel.error = nil
}
func inRootGroupSelection() -> Bool {
guard let root = rootPaymentMethodOptions, let actual = paymentMethodOptions else {
return true
}
if let hashableSet = NSSet(array: actual) as? Set<AnyHashable> {
return NSSet(array: root).isEqual(to: hashableSet)
}
return true
}
}
// MARK: Advanced Config
extension MercadoPagoCheckoutViewModel {
func getAdvancedConfiguration() -> PXAdvancedConfiguration {
return advancedConfig
}
}
// MARK: Payment Flow
extension MercadoPagoCheckoutViewModel {
func createPaymentFlow(paymentErrorHandler: PXPaymentErrorHandlerProtocol) -> PXPaymentFlow {
guard let paymentFlow = paymentFlow else {
return buildPaymentFlow(with: paymentErrorHandler)
}
paymentFlow.model.amountHelper = amountHelper
paymentFlow.model.checkoutPreference = checkoutPreference
return paymentFlow
}
func buildPaymentFlow(with paymentErrorHandler: PXPaymentErrorHandlerProtocol) -> PXPaymentFlow {
let paymentFlow = PXPaymentFlow(
paymentPlugin: paymentPlugin,
mercadoPagoServices: mercadoPagoServices,
paymentErrorHandler: paymentErrorHandler,
navigationHandler: pxNavigationHandler,
amountHelper: amountHelper,
checkoutPreference: checkoutPreference,
ESCBlacklistedStatus: search?.configurations?.ESCBlacklistedStatus
)
if let productId = advancedConfig.productId {
paymentFlow.setProductIdForPayment(productId)
}
paymentFlow.model.postPaymentNotificationName = postPaymentNotificationName
self.paymentFlow = paymentFlow
return paymentFlow
}
}
extension MercadoPagoCheckoutViewModel {
func keepDisabledOptionIfNeeded() {
disabledOption = PXDisabledOption(paymentResult: self.paymentResult)
}
func clean() {
paymentFlow = nil
initFlow = nil
onetapFlow = nil
}
}
// MARK: Remedy
private extension MercadoPagoCheckoutViewModel {
func updatePaymentData(_ suggestedPaymentMethod: PXSuggestedPaymentMethod) {
if let alternativePaymentMethod = suggestedPaymentMethod.alternativePaymentMethod,
let paymentResult = paymentResult,
let sliderViewModel = onetapFlow?.model.pxOneTapViewModel?.getCardSliderViewModel() {
var cardId = alternativePaymentMethod.customOptionId ?? paymentResult.cardId
let paymentMethodId = alternativePaymentMethod.paymentMethodId ?? paymentResult.paymentMethodId
if paymentMethodId == PXPaymentTypes.CONSUMER_CREDITS.rawValue {
cardId = paymentMethodId
}
if let targetModel = sliderViewModel.first(where: { $0.cardId == cardId }) {
guard let selectedApplication = targetModel.selectedApplication else { return }
if let paymentMethods = availablePaymentMethods,
let newPaymentMethod = Utils.findPaymentMethod(paymentMethods, paymentMethodId: selectedApplication.paymentMethodId) {
paymentResult.paymentData?.payerCost = selectedApplication.selectedPayerCost
paymentResult.paymentData?.paymentMethod = newPaymentMethod
paymentResult.paymentData?.issuer = selectedApplication.payerPaymentMethod?.issuer ?? PXIssuer(id: targetModel.issuerId, name: nil)
if let installments = alternativePaymentMethod.installmentsList?.first?.installments,
let newPayerCost = selectedApplication.payerCost.first(where: { $0.installments == installments }) {
paymentResult.paymentData?.payerCost = newPayerCost
}
}
}
}
}
}
| 42.807882 | 321 | 0.696461 |
ff2a4258be9d4e3bdebdb405355fffeb2bb78a9c | 13,319 | //
// AASerializable.swift
// AAChartKit-Swift
//
// Created by An An on 17/4/19.
// Copyright © 2017年 An An . All rights reserved.
//*************** ...... SOURCE CODE ...... ***************
//***...................................................***
//*** https://github.com/AAChartModel/AAChartKit ***
//*** https://github.com/AAChartModel/AAChartKit-Swift ***
//***...................................................***
//*************** ...... SOURCE CODE ...... ***************
/*
* -------------------------------------------------------------------------------
*
* 🌕 🌖 🌗 🌘 ❀❀❀ WARM TIPS!!! ❀❀❀ 🌑 🌒 🌓 🌔
*
* Please contact me on GitHub,if there are any problems encountered in use.
* GitHub Issues : https://github.com/AAChartModel/AAChartKit-Swift/issues
* -------------------------------------------------------------------------------
* And if you want to contribute for this project, please contact me as well
* GitHub : https://github.com/AAChartModel
* StackOverflow : https://stackoverflow.com/users/12302132/codeforu
* JianShu : https://www.jianshu.com/u/f1e6753d4254
* SegmentFault : https://segmentfault.com/u/huanghunbieguan
*
* -------------------------------------------------------------------------------
*/
public class AASeriesElement: AAObject {
public var type: String? //A chart type series. If the type option is not specified, it is inherited from `chart.type`.
public var name: String? //The name of the series as shown in the legend, tooltip etc.
public var data: [Any]? //An array of data points for the series
public var color: Any? //The main color or the series. In line type series it applies to the line and the point markers unless otherwise specified. In bar type series it applies to the bars unless a color is specified per point. The default value is pulled from the options.colors array.
public var colors: [Any]?
public var lineWidth: Float? //The line width, It is only valid for line, spline, area, areaspline, arearange and arearangespline chart types
public var borderWidth: Float? //The border width, It is only valid for column, bar, pie, columnrange, pyramid and funnel chart types
public var borderColor: String? //The border color, It is only valid for column, bar, pie, columnrange, pyramid and funnel chart types
public var fillColor: Any? //The fill color, It is only valid for area, areaspline, arearange and arearangespline chart types
public var fillOpacity: Float? //The fill opacity, It is only valid for area, areaspline, arearange and arearangespline chart types. Note that when you set an explicit fillColor, the fillOpacity is not applied. Instead, you should define the opacity in the fillColor with an rgba color definition. Deafualt value:0.75.
public var threshold: Float? //The threshold, also called zero level or base level. For line type series this is only used in conjunction with negativeColor. default:0.
public var negativeColor: Any? //The color for the parts of the graph or points that are below the threshold
public var negativeFillColor: Any? //A separate color for the negative part of the area.
public var dashStyle: String? //A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, area and scatter in case it has a lineWidth.
public var yAxis: Int?
public var dataLabels: AADataLabels? //Individual data label for each point. The options are the same as the ones for `plotOptions.series.dataLabels`.
public var marker: AAMarker? //Enable or disable the point marker. If null, the markers are hidden when the data is dense, and shown for more widespread data points.
public var step: Any? //Whether to apply steps to the line. Possible values are left, center and right.
public var states: AAStates?
public var colorByPoint: Bool? //When using automatic point colors pulled from the `options.colors` collection, this option determines whether the chart should receive one color per series or one color per point.
public var allowPointSelect: Bool? //Allow this series' points to be selected by clicking on the markers, bars or pie slices
public var zIndex: Int? //Define the visual z index of the series.
public var size: Any? //The innder size for pie chart (String | Number)
public var innerSize: Any? //The innder size for pie chart (String | Number)
public var minSize: Any? //The minimum size for a pie in response to auto margins, Only useful for pie, bubble, funnel, Pyramid (String | Number)
public var shadow: AAShadow?
public var zones: [AAZonesElement]?
public var zoneAxis: String? //Defines the Axis on which the zones are applied. defalut value:y.
public var stack: String?
public var tooltip: AATooltip?
public var pointPlacement: Any?
public var enableMouseTracking: Bool?
public var dataSorting: AADataSorting?
public var reversed: Bool? //Only useful for pyramid chart and funnel chart
@discardableResult
public func type(_ prop: AAChartType) -> AASeriesElement {
type = prop.rawValue
return self
}
@discardableResult
public func name(_ prop: String) -> AASeriesElement {
name = prop
return self
}
@discardableResult
public func data(_ prop: [Any]) -> AASeriesElement {
data = prop
return self
}
@discardableResult
public func lineWidth(_ prop: Float) -> AASeriesElement {
lineWidth = prop
return self
}
@discardableResult
public func borderWidth(_ prop: Float) -> AASeriesElement {
borderWidth = prop
return self
}
@discardableResult
public func borderColor(_ prop: String) -> AASeriesElement {
borderColor = prop
return self
}
@discardableResult
public func fillColor(_ prop: Any) -> AASeriesElement {
fillColor = prop
return self
}
@discardableResult
public func color(_ prop: Any) -> AASeriesElement {
color = prop
return self
}
@discardableResult
public func colors(_ prop: [Any]) -> AASeriesElement {
colors = prop
return self
}
@discardableResult
public func fillOpacity(_ prop: Float) -> AASeriesElement {
fillOpacity = prop
return self
}
@discardableResult
public func threshold(_ prop: Float) -> AASeriesElement {
threshold = prop
return self
}
@discardableResult
public func negativeColor(_ prop: Any) -> AASeriesElement {
negativeColor = prop
return self
}
@discardableResult
public func negativeFillColor(_ prop: Any) -> AASeriesElement {
negativeFillColor = prop
return self
}
@discardableResult
public func dashStyle(_ prop: AAChartLineDashStyleType) -> AASeriesElement {
dashStyle = prop.rawValue
return self
}
@discardableResult
public func yAxis(_ prop: Int) -> AASeriesElement {
yAxis = prop
return self
}
@discardableResult
public func dataLabels(_ prop: AADataLabels) -> AASeriesElement {
dataLabels = prop
return self
}
@discardableResult
public func marker(_ prop: AAMarker) -> AASeriesElement {
marker = prop
return self
}
@discardableResult
public func step(_ prop: Any) -> AASeriesElement {
step = prop
return self
}
@discardableResult
public func states(_ prop: AAStates) -> AASeriesElement {
states = prop
return self
}
@discardableResult
public func colorByPoint(_ prop: Bool) -> AASeriesElement {
colorByPoint = prop
return self
}
@discardableResult
public func allowPointSelect(_ prop: Bool) -> AASeriesElement {
allowPointSelect = prop
return self
}
@discardableResult
public func zIndex(_ prop: Int) -> AASeriesElement {
zIndex = prop
return self
}
@discardableResult
public func size(_ prop: Any) -> AASeriesElement {
size = prop
return self
}
@discardableResult
public func innerSize(_ prop: Any) -> AASeriesElement {
innerSize = prop
return self
}
@discardableResult
public func minSize(_ prop: Any) -> AASeriesElement {
minSize = prop
return self
}
@discardableResult
public func shadow(_ prop: AAShadow) -> AASeriesElement {
shadow = prop
return self
}
@discardableResult
public func zones(_ prop: [AAZonesElement]) -> AASeriesElement {
zones = prop
return self
}
@discardableResult
public func zoneAxis(_ prop: String) -> AASeriesElement {
zoneAxis = prop
return self
}
@discardableResult
public func stack(_ prop: String) -> AASeriesElement {
stack = prop
return self
}
@discardableResult
public func tooltip(_ prop: AATooltip) -> AASeriesElement {
tooltip = prop
return self
}
@discardableResult
public func pointPlacement(_ prop: Any) -> AASeriesElement {
pointPlacement = prop
return self
}
@discardableResult
public func enableMouseTracking(_ prop: Bool) -> AASeriesElement {
enableMouseTracking = prop
return self
}
@discardableResult
public func dataSorting(_ prop: AADataSorting) -> AASeriesElement {
dataSorting = prop
return self
}
@discardableResult
public func reversed(_ prop: Bool) -> AASeriesElement {
reversed = prop
return self
}
public override init() {
}
}
public class AADataElement: AAObject {
public var name: String?
public var x: Float?
public var y: Float?
public var color: Any?
public var dataLabels: AADataLabels?
public var marker: AAMarker?
@discardableResult
public func name(_ prop: String) -> AADataElement {
name = prop
return self
}
@discardableResult
public func x(_ prop: Float) -> AADataElement {
x = prop
return self
}
@discardableResult
public func y(_ prop: Float) -> AADataElement {
y = prop
return self
}
@discardableResult
public func color(_ prop: Any) -> AADataElement {
color = prop
return self
}
@discardableResult
public func dataLabels(_ prop: AADataLabels) -> AADataElement {
dataLabels = prop
return self
}
@discardableResult
public func marker(_ prop: AAMarker) -> AADataElement {
marker = prop
return self
}
public override init() {
}
}
public class AAShadow: AAObject {
public var color: String?
public var offsetX: Float?
public var offsetY: Float?
public var opacity: Float?
public var width: Float?
@discardableResult
public func color(_ prop: String) -> AAShadow {
color = prop
return self
}
@discardableResult
public func offsetX(_ prop: Float) -> AAShadow {
offsetX = prop
return self
}
@discardableResult
public func offsetY(_ prop: Float) -> AAShadow {
offsetY = prop
return self
}
@discardableResult
public func opacity(_ prop: Float) -> AAShadow {
opacity = prop
return self
}
@discardableResult
public func width(_ prop: Float) -> AAShadow {
width = prop
return self
}
public override init() {
}
}
public class AAZonesElement: AAObject {
public var value: Double?
public var color: Any?
public var fillColor: Any?
public var dashStyle: String?
@discardableResult
public func value(_ prop: Double) -> AAZonesElement {
value = prop
return self
}
@discardableResult
public func color(_ prop: Any) -> AAZonesElement {
color = prop
return self
}
@discardableResult
public func fillColor(_ prop: Any) -> AAZonesElement {
fillColor = prop
return self
}
@discardableResult
public func dashStyle(_ prop: AAChartLineDashStyleType) -> AAZonesElement {
dashStyle = prop.rawValue
return self
}
public override init() {
}
}
public class AADataSorting: AAObject {
public var enabled: Bool?
public var matchByName: Bool?
@discardableResult
public func enabled(_ prop: Bool) -> AADataSorting {
enabled = prop
return self
}
@discardableResult
public func matchByName(_ prop: Bool) -> AADataSorting {
matchByName = prop
return self
}
public override init() {
}
}
| 31.192037 | 330 | 0.609355 |
33342b81d12c680eb3db08d34f0936f2746e93ef | 4,237 | //
// ProductsViewController.swift
// CabifyMobileChallenge
//
// Created by Juan Miguel Marqués Morilla on 18/05/2019.
// Copyright © 2019 Míchel Marqués Morilla. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class ProductsViewController: UIViewController, Storyboarded {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var totalValueLabel: UILabel!
@IBOutlet weak var subtotalLabel: UILabel!
@IBOutlet weak var discountLabel: UILabel!
var viewModel: ProductsViewModel?
var cellViewModels: [ProductCellViewModel] = []
let loadingViewController = LoadingViewController()
let errorViewController = ErrorViewController()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configureView()
setupViewModel()
requestData()
}
func configureView () {
self.title = NSLocalizedString("_title_products", comment: "")
configureNavBar()
configureTableView()
}
func configureCalculateView() {
guard let viewModel = viewModel else {return}
self.totalValueLabel.text = viewModel.getTotalString()
self.subtotalLabel.text = viewModel.getSubtotalString()
self.discountLabel.text = viewModel.getDiscountString()
}
func configureNavBar() {
let resetBar = UIBarButtonItem(barButtonSystemItem: .trash ,
target: self,
action: #selector(resetAction))
let reloadBar = UIBarButtonItem(barButtonSystemItem: .refresh,
target: self,
action: #selector(reloadAction))
navigationItem.rightBarButtonItem = reloadBar
navigationItem.leftBarButtonItem = resetBar
}
func configureTableView() {
tableView
.register(UINib(nibName: CellIdentifiers.ProductTableViewCell,
bundle: nil),
forCellReuseIdentifier: CellIdentifiers.ProductTableViewCell)
}
func setupViewModel() {
guard let viewModel = viewModel else {return}
let state = viewModel.state.asObservable()
state.subscribe(onNext: { (state) in
switch state {
case .loaded(let cellViewModels):
self.cellViewModels = cellViewModels
self.tableView.reloadData()
self.configureCalculateView()
self.errorViewController.remove()
self.loadingViewController.remove()
case .loading:
self.errorViewController.remove()
self.add(child: self.loadingViewController)
case .error:
self.loadingViewController.remove()
self.add(child: self.errorViewController)
case .empty:
break
}
}).disposed(by: disposeBag)
}
func requestData () {
guard let viewModel = viewModel else {return}
viewModel.requestData()
}
@objc func resetAction() {
guard let viewModel = viewModel else {return}
viewModel.resetQuantities()
}
@objc func reloadAction() {
viewModel?.requestData()
}
}
extension ProductsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return cellViewModels.count
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView
.dequeueReusableCell(withIdentifier: CellIdentifiers.ProductTableViewCell,
for: indexPath)
if let cell = cell as? ProductTableViewCell {
let rowViewModel = cellViewModels[indexPath.row]
cell.setup(viewModel: rowViewModel)
rowViewModel.unitButtonTapped
.asObserver()
.subscribe(onNext: { (_) in
self.configureCalculateView()
}).disposed(by: disposeBag)
}
return cell
}
}
| 33.362205 | 88 | 0.608685 |
f5d8dd0b878831648d8eeb8365c3d122d4732765 | 3,987 | import Foundation
class UserDefaultsStorage: ILocalStorage {
private let keyIsNewWallet = "is_new_wallet"
private let keyIsBackedUp = "is_backed_up"
private let keyCurrentLanguage = "current_language"
private let keyBaseCurrencyCode = "base_currency_code"
private let keyBaseBitcoinProvider = "base_bitcoin_provider"
private let keyBaseEthereumProvider = "base_ethereum_provider"
private let keyLightMode = "light_mode"
private let iUnderstandKey = "i_understand_key"
private let biometricOnKey = "biometric_on_key"
private let lastExitDateKey = "last_exit_date_key"
private let didLaunchOnceKey = "did_launch_once_key"
private let keySendInputType = "send_input_type_key"
var isNewWallet: Bool {
get { return bool(for: keyIsNewWallet) ?? false }
set { set(newValue, for: keyIsNewWallet) }
}
var isBackedUp: Bool {
get { return bool(for: keyIsBackedUp) ?? false }
set { set(newValue, for: keyIsBackedUp) }
}
var currentLanguage: String? {
get { return getString(keyCurrentLanguage) }
set { setString(keyCurrentLanguage, value: newValue) }
}
var lastExitDate: Double {
get { return double(for: lastExitDateKey) }
set { set(newValue, for: lastExitDateKey) }
}
var didLaunchOnce: Bool {
if bool(for: didLaunchOnceKey) ?? false {
return true
}
set(true, for: didLaunchOnceKey)
return false
}
var baseCurrencyCode: String? {
get { return getString(keyBaseCurrencyCode) }
set { setString(keyBaseCurrencyCode, value: newValue) }
}
var baseBitcoinProvider: String? {
get { return getString(keyBaseBitcoinProvider) }
set { setString(keyBaseBitcoinProvider, value: newValue) }
}
var baseEthereumProvider: String? {
get { return getString(keyBaseEthereumProvider) }
set { setString(keyBaseEthereumProvider, value: newValue) }
}
var lightMode: Bool {
get { return bool(for: keyLightMode) ?? false }
set { set(newValue, for: keyLightMode) }
}
var iUnderstand: Bool {
get { return bool(for: iUnderstandKey) ?? false }
set { set(newValue, for: iUnderstandKey) }
}
var isBiometricOn: Bool {
get { return bool(for: biometricOnKey) ?? false }
set { set(newValue, for: biometricOnKey) }
}
var sendInputType: SendInputType? {
get {
if let rawValue = getString(keySendInputType), let value = SendInputType(rawValue: rawValue) {
return value
}
return nil
}
set {
setString(keySendInputType, value: newValue?.rawValue)
}
}
func clear() {
isNewWallet = false
isBackedUp = false
lightMode = false
iUnderstand = false
isBiometricOn = false
}
private func getString(_ name: String) -> String? {
return UserDefaults.standard.value(forKey: name) as? String
}
private func setString(_ name: String, value: String?) {
if let value = value {
UserDefaults.standard.set(value, forKey: name)
} else {
UserDefaults.standard.removeObject(forKey: name)
}
UserDefaults.standard.synchronize()
}
private func bool(for key: String) -> Bool? {
return UserDefaults.standard.value(forKey: key) as? Bool
}
private func set(_ value: Bool, for key: String) {
UserDefaults.standard.set(value, forKey: key)
UserDefaults.standard.synchronize()
}
private func set(_ value: Double?, for key: String) {
if let value = value {
UserDefaults.standard.set(value, forKey: key)
} else {
UserDefaults.standard.removeObject(forKey: key)
}
}
private func double(for key: String) -> Double {
return UserDefaults.standard.double(forKey: key)
}
}
| 30.669231 | 106 | 0.632305 |
56b861ddf4d5ece08cbfc8a2f7d6f23fd8834ae9 | 4,208 | //----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.7.0.0
//
// Created by Quasar Development
//
//---------------------------------------------------
import Foundation
/**
* Actual content model is non-deterministic, hence wildcard. The following shows intended content model:
*
* <xs:element ref='wst:TokenType' minOccurs='0' />
* <xs:element ref='wst:RequestType' />
* <xs:element ref='wst:SecondaryParameters' minOccurs='0' />
* <xs:element ref='wsp:AppliesTo' minOccurs='0' />
* <xs:element ref='wst:Claims' minOccurs='0' />
* <xs:element ref='wst:Entropy' minOccurs='0' />
* <xs:element ref='wst:Lifetime' minOccurs='0' />
* <xs:element ref='wst:AllowPostdating' minOccurs='0' />
* <xs:element ref='wst:Renewing' minOccurs='0' />
* <xs:element ref='wst:OnBehalfOf' minOccurs='0' />
* <xs:element ref='wst:Issuer' minOccurs='0' />
* <xs:element ref='wst:AuthenticationType' minOccurs='0' />
* <xs:element ref='wst:KeyType' minOccurs='0' />
* <xs:element ref='wst:KeySize' minOccurs='0' />
* <xs:element ref='wst:SignatureAlgorithm' minOccurs='0' />
* <xs:element ref='wst:Encryption' minOccurs='0' />
* <xs:element ref='wst:EncryptionAlgorithm' minOccurs='0' />
* <xs:element ref='wst:CanonicalizationAlgorithm' minOccurs='0' />
* <xs:element ref='wst:ProofEncryption' minOccurs='0' />
* <xs:element ref='wst:UseKey' minOccurs='0' />
* <xs:element ref='wst:SignWith' minOccurs='0' />
* <xs:element ref='wst:EncryptWith' minOccurs='0' />
* <xs:element ref='wst:DelegateTo' minOccurs='0' />
* <xs:element ref='wst:Forwardable' minOccurs='0' />
* <xs:element ref='wst:Delegatable' minOccurs='0' />
* <xs:element ref='wsp:Policy' minOccurs='0' />
* <xs:element ref='wsp:PolicyReference' minOccurs='0' />
* <xs:any namespace='##other' processContents='lax' minOccurs='0' maxOccurs='unbounded' />
*/
public class EPA_FdV_AUTHN_RequestSecurityTokenType : NSObject ,EPA_FdV_AUTHN_ISerializableObject
{
private var __source:DDXMLNode? = nil
var Context:String?
var any=[Any]()
public required override init()
{
super.init()
}
public func loadWithXml(__node: DDXMLElement, __request:EPA_FdV_AUTHN_RequestResultHandler)
{
__source=__node;
for i :UInt in 0 ..< __node.childCount
{
let node=__node.child(at:i)
if node?.kind==UInt(XMLElementKind)
{
let __node=node as! DDXMLElement
if loadProperty(__node:__node, __request:__request) == false
{
self.any.append(__request.getAny(node: __node))
}
}
}
if EPA_FdV_AUTHN_Helper.hasAttribute(node: __node, name:"Context", url:"")
{
self.Context = EPA_FdV_AUTHN_Helper.getAttribute(node: __node, name:"Context", url:"")!.stringValue!
}
}
public func serialize(__parent:DDXMLElement, __request:EPA_FdV_AUTHN_RequestResultHandler)
{
if self.Context != nil
{
let __ContextItemElement=__request.addAttribute(name: "Context", URI:"", stringValue:"", element:__parent)
__ContextItemElement.stringValue = self.Context!;
}
for case let elem as DDXMLNode in self.any
{
elem.detach()
__parent.addChild(elem)
}
}
public func loadProperty(__node: DDXMLElement, __request: EPA_FdV_AUTHN_RequestResultHandler ) -> Bool
{
if __node.localName=="Context"
{
if EPA_FdV_AUTHN_Helper.isValue(node:__node, name: "Context")
{
self.Context = __node.stringValue!
}
return true;
}
return false
}
public func getOriginalXmlSource() ->DDXMLNode?
{
return __source
}
} | 37.238938 | 119 | 0.558935 |
d9c93fdd86918d3fcf11710013716dc702425fee | 560 | import Vapor
// The Droplet is a core class that gives you access to many of Vapor's facilities. It is responsible for registering routes, starting the server, appending middleware, and more.
let drop = Droplet()
// Create a new route to accept GET http method on "listofnutrients"
// registers GET on URL http://localhost:8080/listofnutrients
drop.get("listofnutrients") { req in
return try JSON(node: [ "nutrients" : ["Carbohydrates", "Protein", "Fat", "Vitamins","Minerals", "Water" ]])
}
// After registering routes, now run the droplet
drop.run()
| 37.333333 | 178 | 0.733929 |
d7e9a53f78e6ba2483353a8a2b11674ea7760573 | 1,603 | import Foundation
import XCTest
@testable import ProjectDescription
final class EnvironmentTests: XCTestCase {
func test_booleanTrueValues() throws {
let environment: [String: String] = [
"TUIST_0": "1",
"TUIST_1": "true",
"TUIST_2": "TRUE",
"TUIST_3": "yes",
"TUIST_4": "YES",
]
try environment.enumerated().forEach { index, _ in
let value = try XCTUnwrap(Environment.value(for: String(index), environment: environment))
XCTAssertEqual(value, .boolean(true))
}
}
func test_booleanFalseValues() throws {
let environment: [String: String] = [
"TUIST_0": "0",
"TUIST_1": "false",
"TUIST_2": "FALSE",
"TUIST_3": "no",
"TUIST_4": "NO",
]
try environment.enumerated().forEach { index, _ in
let value = try XCTUnwrap(Environment.value(for: String(index), environment: environment))
XCTAssertEqual(value, .boolean(false))
}
}
func test_stringValue() {
let stringValue = UUID().uuidString
let environment: [String: String] = [
"TUIST_0": stringValue,
]
let value = Environment.value(for: "0", environment: environment)
XCTAssertEqual(value, .string(stringValue))
}
func test_unknownKeysReturnNil() {
let environment: [String: String] = [
"TUIST_0": "0",
]
let value = Environment.value(for: "1", environment: environment)
XCTAssertNil(value)
}
}
| 30.826923 | 102 | 0.563943 |
16d56f805891d6a4b04f012815ab53dfe7ef2f25 | 3,859 | //
// SetGame.swift
// Set
//
// Created by Tiago Lopes on 23/09/21.
//
import Foundation
struct SetGame<Deck: SetDeck> {
// MARK: Typealiases
typealias VacantSpaceIndices = [Int]
// MARK: Properties
private var deck: Deck
private(set) var tableCards = [Deck.Card]()
private(set) var matchedCards = Set<Deck.Card>()
// MARK: Initializer
init(deck: Deck) {
self.deck = deck
let initialCards = self.deck.deal(amount: Constants.initialCardsAmount)
tableCards.append(contentsOf: initialCards)
}
// TODO: Add a property to check if the game is finished.
}
// MARK: - Dealing
extension SetGame {
var canDeal: Bool {
!deck.isEmpty
}
mutating func deal(at vacantSpaces: VacantSpaceIndices? = nil) {
var vacantSpaces = vacantSpaces
if let trio = selectedTrio, trio.isSet {
vacantSpaces = removeMatchedCardsFromTable()
}
var cards = deck.deal()
if let vacantSpaces = vacantSpaces {
for index in vacantSpaces {
guard let card = cards.popLast() else {
return
}
tableCards.insert(card, at: index)
}
} else {
tableCards.append(contentsOf: cards)
}
}
}
// MARK: - Choosing Cards
extension SetGame {
private var selectedTrio: SetTrio<Deck.Card>? {
get {
let selectedCards = tableCards.filter { $0.isSelected }
guard selectedCards.count == 3 else {
return nil
}
return SetTrio(first: selectedCards[0],
second: selectedCards[1],
third: selectedCards[2])
}
set {
tableCards
.filter(\.isSelected)
.compactMap(tableCards.firstIndex(of:))
.forEach {
tableCards[$0].isSelected = false
tableCards[$0].isUnmatched = false
}
}
}
mutating func chooseCard(atIndex index: Int) {
guard index < tableCards.count else {
assertionFailure("Selecting an out of bounds card.")
return
}
if let trio = selectedTrio {
if trio.isSet {
tableCards[index].isSelected = true
let vacantSpaceIndices = removeMatchedCardsFromTable()
deal(at: vacantSpaceIndices)
} else {
selectedTrio = nil
tableCards[index].isSelected = true
}
} else {
tableCards[index].isSelected.toggle()
performMatchIfNeeded()
}
}
}
// MARK: - Matching
private extension SetGame {
mutating func performMatchIfNeeded() {
guard let trio = selectedTrio else {
return
}
let cardIndices = trio
.cards
.compactMap { tableCards.firstIndex(of: $0 ) }
if trio.isSet {
cardIndices.forEach { tableCards[$0].isMatched = true }
} else {
cardIndices.forEach { tableCards[$0].isUnmatched = true }
}
}
private mutating func removeMatchedCardsFromTable() -> VacantSpaceIndices {
tableCards
.filter { $0.isMatched }
.forEach { matchedCards.insert($0) }
let emptySpaceIndices = tableCards
.filter { $0.isMatched }
.compactMap { tableCards.firstIndex(of: $0) }
tableCards.removeAll(where: { $0.isMatched })
return emptySpaceIndices
}
}
// MARK: - Constants
fileprivate enum Constants {
static let initialCardsAmount = 12
}
| 25.899329 | 79 | 0.528116 |
91295382c3d83d6625532991b9b40261dae0449d | 11,386 | //
// SingleValueScheduleTableViewController.swift
// Naterade
//
// Created by Nathan Racklyeft on 2/13/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
import LoopKit
public enum RepeatingScheduleValueResult<T: RawRepresentable> {
case success(scheduleItems: [RepeatingScheduleValue<T>], timeZone: TimeZone)
case failure(Error)
}
public protocol SingleValueScheduleTableViewControllerSyncSource: AnyObject {
func syncScheduleValues(for viewController: SingleValueScheduleTableViewController, completion: @escaping (_ result: RepeatingScheduleValueResult<Double>) -> Void)
func syncButtonTitle(for viewController: SingleValueScheduleTableViewController) -> String
func syncButtonDetailText(for viewController: SingleValueScheduleTableViewController) -> String?
func singleValueScheduleTableViewControllerIsReadOnly(_ viewController: SingleValueScheduleTableViewController) -> Bool
}
open class SingleValueScheduleTableViewController: DailyValueScheduleTableViewController, RepeatingScheduleValueTableViewCellDelegate {
open override func viewDidLoad() {
super.viewDidLoad()
tableView.register(RepeatingScheduleValueTableViewCell.nib(), forCellReuseIdentifier: RepeatingScheduleValueTableViewCell.className)
tableView.register(TextButtonTableViewCell.self, forCellReuseIdentifier: TextButtonTableViewCell.className)
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if syncSource == nil {
delegate?.dailyValueScheduleTableViewControllerWillFinishUpdating(self)
}
}
// MARK: - State
public var scheduleItems: [RepeatingScheduleValue<Double>] = []
override func addScheduleItem(_ sender: Any?) {
guard !isReadOnly && !isSyncInProgress else {
return
}
tableView.endEditing(false)
var startTime = TimeInterval(0)
var value = 0.0
if scheduleItems.count > 0, let cell = tableView.cellForRow(at: IndexPath(row: scheduleItems.count - 1, section: 0)) as? RepeatingScheduleValueTableViewCell {
let lastItem = scheduleItems.last!
let interval = cell.datePickerInterval
startTime = lastItem.startTime + interval
value = lastItem.value
if startTime >= TimeInterval(hours: 24) {
return
}
}
scheduleItems.append(
RepeatingScheduleValue(
startTime: min(TimeInterval(hours: 23.5), startTime),
value: value
)
)
super.addScheduleItem(sender)
}
override func insertableIndiciesByRemovingRow(_ row: Int, withInterval timeInterval: TimeInterval) -> [Bool] {
return insertableIndices(for: scheduleItems, removing: row, with: timeInterval)
}
var preferredValueFractionDigits: Int {
return 1
}
public weak var syncSource: SingleValueScheduleTableViewControllerSyncSource? {
didSet {
isReadOnly = syncSource?.singleValueScheduleTableViewControllerIsReadOnly(self) ?? false
if isViewLoaded {
tableView.reloadData()
}
}
}
private var isSyncInProgress = false {
didSet {
for cell in tableView.visibleCells {
switch cell {
case let cell as TextButtonTableViewCell:
cell.isEnabled = !isSyncInProgress
cell.isLoading = isSyncInProgress
case let cell as RepeatingScheduleValueTableViewCell:
cell.isReadOnly = isReadOnly || isSyncInProgress
default:
break
}
}
for item in navigationItem.rightBarButtonItems ?? [] {
item.isEnabled = !isSyncInProgress
}
navigationItem.hidesBackButton = isSyncInProgress
}
}
// MARK: - UITableViewDataSource
private enum Section: Int {
case schedule
case sync
}
open override func numberOfSections(in tableView: UITableView) -> Int {
if syncSource != nil {
return 2
}
return 1
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .schedule:
return scheduleItems.count
case .sync:
return 1
}
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .schedule:
let cell = tableView.dequeueReusableCell(withIdentifier: RepeatingScheduleValueTableViewCell.className, for: indexPath) as! RepeatingScheduleValueTableViewCell
let item = scheduleItems[indexPath.row]
let interval = cell.datePickerInterval
cell.timeZone = timeZone
cell.date = midnight.addingTimeInterval(item.startTime)
cell.valueNumberFormatter.minimumFractionDigits = preferredValueFractionDigits
cell.value = item.value
cell.unitString = unitDisplayString
cell.isReadOnly = isReadOnly || isSyncInProgress
cell.delegate = self
if indexPath.row > 0 {
let lastItem = scheduleItems[indexPath.row - 1]
cell.datePicker.minimumDate = midnight.addingTimeInterval(lastItem.startTime).addingTimeInterval(interval)
}
if indexPath.row < scheduleItems.endIndex - 1 {
let nextItem = scheduleItems[indexPath.row + 1]
cell.datePicker.maximumDate = midnight.addingTimeInterval(nextItem.startTime).addingTimeInterval(-interval)
} else {
cell.datePicker.maximumDate = midnight.addingTimeInterval(TimeInterval(hours: 24) - interval)
}
return cell
case .sync:
let cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath) as! TextButtonTableViewCell
cell.textLabel?.text = syncSource?.syncButtonTitle(for: self)
cell.isEnabled = !isSyncInProgress
cell.isLoading = isSyncInProgress
return cell
}
}
open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch Section(rawValue: section)! {
case .schedule:
return nil
case .sync:
return syncSource?.syncButtonDetailText(for: self)
}
}
open override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
scheduleItems.remove(at: indexPath.row)
super.tableView(tableView, commit: editingStyle, forRowAt: indexPath)
}
}
open override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if sourceIndexPath != destinationIndexPath {
let item = scheduleItems.remove(at: sourceIndexPath.row)
scheduleItems.insert(item, at: destinationIndexPath.row)
guard destinationIndexPath.row > 0, let cell = tableView.cellForRow(at: destinationIndexPath) as? RepeatingScheduleValueTableViewCell else {
return
}
let interval = cell.datePickerInterval
let startTime = scheduleItems[destinationIndexPath.row - 1].startTime + interval
scheduleItems[destinationIndexPath.row] = RepeatingScheduleValue(startTime: startTime, value: scheduleItems[destinationIndexPath.row].value)
// Since the valid date ranges of neighboring cells are affected, the lazy solution is to just reload the entire table view
DispatchQueue.main.async {
tableView.reloadData()
}
}
}
// MARK: - UITableViewDelegate
open override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return super.tableView(tableView, canEditRowAt: indexPath) && !isSyncInProgress
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
switch Section(rawValue: indexPath.section)! {
case .schedule:
break
case .sync:
if let syncSource = syncSource, !isSyncInProgress {
isSyncInProgress = true
syncSource.syncScheduleValues(for: self) { (result) in
DispatchQueue.main.async {
switch result {
case .success(let items, let timeZone):
self.scheduleItems = items
self.timeZone = timeZone
self.tableView.reloadSections([Section.schedule.rawValue], with: .fade)
self.isSyncInProgress = false
self.delegate?.dailyValueScheduleTableViewControllerWillFinishUpdating(self)
case .failure(let error):
self.present(UIAlertController(with: error), animated: true) {
self.isSyncInProgress = false
}
}
}
}
}
}
}
open override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
guard sourceIndexPath != proposedDestinationIndexPath, let cell = tableView.cellForRow(at: sourceIndexPath) as? RepeatingScheduleValueTableViewCell else {
return proposedDestinationIndexPath
}
let interval = cell.datePickerInterval
let indices = insertableIndices(for: scheduleItems, removing: sourceIndexPath.row, with: interval)
let closestDestinationRow = indices.insertableIndex(closestTo: proposedDestinationIndexPath.row, from: sourceIndexPath.row)
return IndexPath(row: closestDestinationRow, section: proposedDestinationIndexPath.section)
}
// MARK: - RepeatingScheduleValueTableViewCellDelegate
override public func datePickerTableViewCellDidUpdateDate(_ cell: DatePickerTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
let currentItem = scheduleItems[indexPath.row]
scheduleItems[indexPath.row] = RepeatingScheduleValue(
startTime: cell.date.timeIntervalSince(midnight),
value: currentItem.value
)
}
super.datePickerTableViewCellDidUpdateDate(cell)
}
func repeatingScheduleValueTableViewCellDidUpdateValue(_ cell: RepeatingScheduleValueTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
let currentItem = scheduleItems[indexPath.row]
scheduleItems[indexPath.row] = RepeatingScheduleValue(startTime: currentItem.startTime, value: cell.value)
}
}
}
| 37.827243 | 194 | 0.653083 |
204ebfb5b91dce96f9032378fde5ed0ee1cd24a9 | 2,703 | import SwiftUI
import SafariServices
@main
struct HushApp: App {
#if os(macOS)
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#endif
let contentBlockerIdentifier = "\(Bundle.main.bundleIdentifier ?? "se.oblador.Hush").ContentBlocker"
let appState = AppState(initialContentBlockerEnabledState: .undetermined)
init() {
SFContentBlockerManager.reloadContentBlocker(withIdentifier: contentBlockerIdentifier,
completionHandler: { (error) in
if let error = error {
print("Failed to reload content blocker")
print(error)
}
})
}
func refreshEnabledState() {
SFContentBlockerManager.getStateOfContentBlocker(withIdentifier: contentBlockerIdentifier, completionHandler: { (state, error) in
if let error = error {
print("Failed to get content blocker state")
print(error)
DispatchQueue.main.async {
appState.contentBlockerEnabledState = .undetermined
}
}
if let state = state {
DispatchQueue.main.async {
appState.contentBlockerEnabledState = state.isEnabled ? .enabled : .disabled
}
}
})
}
var body: some Scene {
#if os(macOS)
WindowGroup {
ContentView()
.environmentObject(appState)
.onAppear(perform: refreshEnabledState)
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willBecomeActiveNotification)) { _ in
refreshEnabledState()
}
.frame(
minWidth: 320,
idealWidth: 350,
maxWidth: 500,
minHeight: 440,
idealHeight: 460,
maxHeight: 600
)
.background(Color.appBackgroundColor.ignoresSafeArea())
}
.commands {
// Disable "New Window" command
CommandGroup(replacing: CommandGroupPlacement.newItem) {}
}
.windowStyle(HiddenTitleBarWindowStyle())
#else
WindowGroup {
ContentView()
.environmentObject(appState)
.onAppear(perform: refreshEnabledState)
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
refreshEnabledState()
}
.background(Color.appBackgroundColor.ignoresSafeArea())
}
#endif
}
}
| 35.103896 | 137 | 0.557529 |
efd94c1e71696e9ae764de53bfe9e187f9a0e380 | 609 | //
// Cowsay.swift
// Created by Leandro Nunes Fantinatto on 03/09/20.
//
import ArgumentParser
import Foundation
final class Cowsay {
static func create(
named: String,
withEyes eyes: String,
andTongue tongue: String
) throws -> Cow {
guard var cow = getCow(named: named) else {
throw ValidationError("[404] There\'s no cow named '\(named)'\n\t\t\t\t ^")
}
cow.eyes = eyes
cow.tongue = tongue
return cow
}
static func getCow(named: String) -> Cow? {
CowNames.all.first { $0.name == named }
}
}
| 19.645161 | 88 | 0.571429 |
14fac91278088eabb566061e76e9991b453b2a9e | 6,184 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
import XCTest
@testable import Amplify
@testable import AmplifyTestCommon
@testable import AWSDataStoreCategoryPlugin
import AWSPluginsCore
class AWSMutationDatabaseAdapterTests: XCTestCase {
var databaseAdapter: AWSMutationDatabaseAdapter!
let model1 = Post(title: "model1", content: "content1", createdAt: Date())
let post = Post.keys
override func setUp() {
do {
let mockStorageAdapter = MockSQLiteStorageEngineAdapter()
databaseAdapter = try AWSMutationDatabaseAdapter(storageAdapter: mockStorageAdapter)
} catch {
XCTFail("Failed to setup system under test")
}
}
func test_replaceLocal_localCreateCandidateUpdate() throws {
let localCreate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.create)
let candidateUpdate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.update)
let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate])
XCTAssertEqual(disposition, .replaceLocalWithCandidate)
}
func test_saveCandidate_CanadidateUpdateWithCondition() throws {
let anyLocal = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.create)
let queryPredicate = post.title == model1.title
let graphQLFilterJSON = try GraphQLFilterConverter.toJSON(queryPredicate)
let candidateUpdate = try MutationEvent(model: model1,
mutationType: MutationEvent.MutationType.update,
graphQLFilterJSON: graphQLFilterJSON)
let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [anyLocal])
XCTAssertEqual(disposition, .saveCandidate)
}
func test_saveCandidate_CanadidateDeleteWithCondition() throws {
let anyLocal = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.create)
let queryPredicate = post.title == model1.title
let graphQLFilterJSON = try GraphQLFilterConverter.toJSON(queryPredicate)
let candidateUpdate = try MutationEvent(model: model1,
mutationType: MutationEvent.MutationType.delete,
graphQLFilterJSON: graphQLFilterJSON)
let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [anyLocal])
XCTAssertEqual(disposition, .saveCandidate)
}
func test_replaceLocal_BothUpdate() throws {
let localCreate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.update)
let candidateUpdate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.update)
let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate])
XCTAssertEqual(disposition, .replaceLocalWithCandidate)
}
func test_replaceLocal_localUpdateCandidateDelete() throws {
let localCreate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.update)
let candidateUpdate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.delete)
let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate])
XCTAssertEqual(disposition, .replaceLocalWithCandidate)
}
func test_replaceLocal_BothDelete() throws {
let localCreate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.delete)
let candidateUpdate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.delete)
let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate])
XCTAssertEqual(disposition, .replaceLocalWithCandidate)
}
func test_dropCandidate_localCreateCandidateDelete() throws {
let localCreate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.create)
let candidateUpdate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.delete)
let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate])
XCTAssertEqual(disposition, .dropCandidateAndDeleteLocal)
}
func test_dropCandidateWithError_localItemExistsAlreadyCandidateCreates() throws {
let localCreate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.create)
let candidateUpdate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.create)
let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate])
XCTAssertEqual(disposition, .dropCandidateWithError(DataStoreError.unknown("", "", nil)))
}
func test_dropCandidateWithError_updateMutationForItemMarkedDeleted() throws {
let localCreate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.delete)
let candidateUpdate = try MutationEvent(model: model1, mutationType: MutationEvent.MutationType.update)
let disposition = databaseAdapter.disposition(for: candidateUpdate, given: [localCreate])
XCTAssertEqual(disposition, .dropCandidateWithError(DataStoreError.unknown("", "", nil)))
}
}
extension AWSMutationDatabaseAdapter.MutationDisposition: Equatable {
public static func == (lhs: AWSMutationDatabaseAdapter.MutationDisposition,
rhs: AWSMutationDatabaseAdapter.MutationDisposition) -> Bool {
switch (lhs, rhs) {
case (.dropCandidateWithError, .dropCandidateWithError):
return true
case (.saveCandidate, .saveCandidate):
return true
case (.replaceLocalWithCandidate, .replaceLocalWithCandidate):
return true
case (.dropCandidateAndDeleteLocal, .dropCandidateAndDeleteLocal):
return true
default:
return false
}
}
}
| 45.470588 | 111 | 0.721054 |
abee40a1e5217a8115b053132a94014c946d5d4d | 2,243 | import XCTest
@testable import Zonda_Tickers
final class ZondaTickersMainTests: XCTestCase {
// MARK: - Tests
func test_main_forNormalExecution() async {
let zondaTickersMainType = ZondaTickersMain.self
zondaTickersMainType.tickersRepositoryType = TickersRepositoryNormalStub.self
zondaTickersMainType.printer = PrinterMock.self
await zondaTickersMainType.main()
XCTAssertEqual("Ticker: LSK-USD", PrinterMock.displayedTexts.removeLast())
XCTAssertEqual("Ticker: ETH-PLN", PrinterMock.displayedTexts.removeLast())
XCTAssertEqual("Ticker: BTC-PLN", PrinterMock.displayedTexts.removeLast())
}
func test_main_withErroerExecution() async {
let zondaTickersMainType = ZondaTickersMain.self
zondaTickersMainType.tickersRepositoryType = TickersRepositoryErrorStub.self
zondaTickersMainType.printer = PrinterMock.self
await zondaTickersMainType.main()
XCTAssertEqual("Error: Test Error Description", PrinterMock.displayedTexts.last)
}
}
// MARK: - Helpers
private struct PrinterMock: Printer {
static var displayedTexts: [String] = []
static func display(text: String) {
displayedTexts.append(text)
}
}
private struct TickersRepositoryNormalStub: AnyTickersRepository {
func loadTickers(tickerIds: [String], shouldLoadValues: Bool, shouldLoadStatistics: Bool) async throws -> [Ticker] {
[Ticker(id: "btc-pln", apiTickerValuesItem: nil, apiTickerStatisticsItem: nil),
Ticker(id: "eth-pln", apiTickerValuesItem: nil, apiTickerStatisticsItem: nil),
Ticker(id: "lsk-usd", apiTickerValuesItem: nil, apiTickerStatisticsItem: nil)]
}
}
private struct TickersRepositoryErrorStub: AnyTickersRepository {
func loadTickers(tickerIds: [String], shouldLoadValues: Bool, shouldLoadStatistics: Bool) async throws -> [Ticker] {
throw ErrorStub.someError
}
}
private enum ErrorStub: Error, LocalizedError {
case someError
var errorDescription: String? {
switch self {
case .someError:
return "Test Error Description"
}
}
}
| 30.310811 | 120 | 0.688364 |
872a46af2cbaf2284d4df7bc7d25534f5c7be85d | 623 | //
// PostCell.swift
// instakev
//
// Created by Kevin Asistores on 2/18/16.
// Copyright © 2016 Kevin Asistores. All rights reserved.
//
import UIKit
class PostCell: UITableViewCell {
@IBOutlet weak var postImage: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var captionLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 21.482759 | 63 | 0.672552 |
febafdeb3a211c85a199a500345e80c0bc4c5313 | 1,371 | import XCTest
import class Foundation.Bundle
final class loggyTests: XCTestCase {
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.
// Some of the APIs that we use below are available in macOS 10.13 and above.
guard #available(macOS 10.13, *) else {
return
}
let fooBinary = productsDirectory.appendingPathComponent("loggy")
let process = Process()
process.executableURL = fooBinary
let pipe = Pipe()
process.standardOutput = pipe
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
XCTAssertEqual(output, "Hello, world!\n")
}
/// Returns path to the built products directory.
var productsDirectory: URL {
#if os(macOS)
for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") {
return bundle.bundleURL.deletingLastPathComponent()
}
fatalError("couldn't find the products directory")
#else
return Bundle.main.bundleURL
#endif
}
static var allTests = [
("testExample", testExample),
]
}
| 28.5625 | 87 | 0.633844 |
5db58b2872399f026c93dd2678b5806ed12babd3 | 252 | //
// ConfigurationType.swift
// TypographyKit
//
// Created by Ross Butler on 7/15/17.
//
//
public enum ConfigurationType: String {
case plist
case json
static var values: [ConfigurationType] {
return [.json, .plist]
}
}
| 14.823529 | 44 | 0.626984 |
6aab859613070ec3d15fd22ee824c3728882cd0c | 1,411 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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 os(iOS) || os(tvOS)
import UIKit
#endif
@available(iOS 8.0, *)
public extension ConstraintLayoutSupport {
public var snp: ConstraintLayoutSupportDSL {
return ConstraintLayoutSupportDSL(support: self)
}
}
| 41.5 | 81 | 0.742736 |
11890ba8827b5daac22c1be2de5bdf4358f7ff1c | 1,005 | //
// FireliteTestTests.swift
// FireliteTestTests
//
// Created by Alexandre Ménielle on 20/01/2018.
// Copyright © 2018 Alexandre Ménielle. All rights reserved.
//
import XCTest
@testable import FireliteTest
class FireliteTestTests: 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.
}
}
}
| 27.162162 | 111 | 0.644776 |
8f6ba43303e08789c512acb5d6d440076ffd13ba | 1,246 | import GRDB
import SwiftUI
/// The view that edits a player
struct PlayerFormView: View {
@Environment(\.dbQueue) var dbQueue
var player: Player
var body: some View {
Stepper(
"Score: \(player.score)",
onIncrement: { updateScore { $0 += 10 } },
onDecrement: { updateScore { $0 = max(0, $0 - 10) } })
}
private func updateScore(_ transform: (inout Int) -> Void) {
do {
_ = try dbQueue.write { db in
var player = player
try player.updateChanges(db) {
transform(&$0.score)
}
}
} catch PersistenceError.recordNotFound {
// Oops, player does not exist.
// Ignore this error: `PlayerPresenceView` will dismiss.
//
// You can comment out this specific handling of
// `PersistenceError.recordNotFound`, run the preview, change the
// score, and see what happens.
} catch {
fatalError("\(error)")
}
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
PlayerFormView(player: .makeRandom())
.padding()
}
}
| 28.976744 | 77 | 0.533708 |
758a7c8f5245aa3574ef81a61b8feb4d73e0ae1e | 1,290 | //
// InsettableShapes.swift
// SwiftUIDrawing
//
// Created by Mehmet Ateş on 7.05.2022.
//
import SwiftUI
struct InsettableShapes: View {
var body: some View {
VStack{
Circle()
.strokeBorder(.blue, lineWidth: 40)
SecondArc(startAngle: .degrees(-90), endAngle: .degrees(90), clockwise: true)
.strokeBorder(.blue, lineWidth: 40)
}
}
}
struct InsettableShape_Previews: PreviewProvider {
static var previews: some View {
InsettableShapes()
}
}
struct SecondArc: InsettableShape {
var startAngle: Angle
var endAngle: Angle
var clockwise: Bool
var insetAmount = 0.0
func inset(by amount: CGFloat) -> some InsettableShape {
var arc = self
arc.insetAmount += amount
return arc
}
func path(in rect: CGRect) -> Path {
let rotationAdjustment = Angle.degrees(90)
let modifiedStart = startAngle - rotationAdjustment
let modifiedEnd = endAngle - rotationAdjustment
var path = Path()
path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.width / 2 - insetAmount, startAngle: modifiedStart, endAngle: modifiedEnd, clockwise: !clockwise)
return path
}
}
| 25.8 | 175 | 0.617829 |
e5abefec9f7e04665a22b6f5ea1dcbeaaad0e69c | 3,282 | //
// SphereController.swift
// RecognEyes
//
// Created by Matthew Chea on 7/5/21.
// Copyright © 2021 Apple. All rights reserved.
//
import Foundation
import ARKit
import SwiftUI
class ObjectController {
var loadedObjects = [SCNNode]()
var selectedObjects = IndexSet()
var speakDistanceTimer = Timer()
//MARK: -Object Call-outs
func speakObjectName(synthesizer: AVSpeechSynthesizer, label: String) {
let utterance = AVSpeechUtterance(string: String(label) + " detected")
synthesizer.speak(utterance)
}
//MARK: -Distance Call-outs
func speakDistance(from session: ARSession , to object: SCNNode, synthesizer: AVSpeechSynthesizer) {
//check settings
guard UserDefaults.standard.bool(forKey: "distanceCallouts") else {
speakString(synthesizer: synthesizer, words: "Distance callouts disabled in settings")
return
}
speakString(synthesizer: synthesizer, words: "Navigating to " + (object.name ?? "object"))
let timerInterval = UserDefaults.standard.double(forKey: "distanceInterval")
speakDistanceTimer = Timer.scheduledTimer(withTimeInterval: timerInterval, repeats: true) { timer in
let distance = self.getDistance(from: session.currentFrame!.camera, to: object)
let utterance = AVSpeechUtterance(string: String(distance) + "feet")
utterance.volume = UserDefaults.standard.float(forKey: "distanceVolume")
synthesizer.speak(utterance)
}
}
func stopSpeakDistance() {
speakDistanceTimer.invalidate()
}
func speakString(synthesizer: AVSpeechSynthesizer, words: String) {
let utterance = AVSpeechUtterance(string: words)
synthesizer.speak(utterance)
}
// distance in feet to the nearest foot
func getDistance(from camera: ARCamera, to object: SCNNode) -> Int {
return Int(round(simd_distance(object.simdTransform.columns.3, (camera.transform.columns.3)) * 3.21)) //convert meters to feet
}
// MARK: - Positional Audio
func playSound(at object: SCNNode, audioSource: SCNAudioSource) {
// Ensure there is only one audio player
object.removeAllAudioPlayers()
//check settings
guard UserDefaults.standard.bool(forKey: "positionalAudio") else {
return
}
audioSource.volume = UserDefaults.standard.float(forKey: "positionalVolume")
object.addAudioPlayer(SCNAudioPlayer(source: audioSource))
}
func stopSound(at object: SCNNode) {
object.removeAllAudioPlayers()
}
// MARK: - Removing Objects
func removeAllObjects() {
// Reverse the indices so we don't trample over indices as objects are removed.
for index in loadedObjects.indices.reversed() {
removeObject(at: index)
}
}
/// - Tag: RemoveVirtualObject
func removeObject(at index: Int) {
guard loadedObjects.indices.contains(index) else { return }
// Remove the visual node from the scene graph.
loadedObjects[index].removeFromParentNode()
// Recoup resources allocated by the object.
loadedObjects.remove(at: index)
}
}
| 34.914894 | 134 | 0.658135 |
79590e15e4eb2a41be486385f884c7ad0d88f3a5 | 23,935 | //
// ViewController.swift
// 4DSTEM Explorer
//
// Created by James LeBeau on 12/21/17.
// Copyright © 2017 The LeBeau Group. All rights reserved.
//
import Cocoa
import Quartz
protocol ViewControllerDelegate: class {
func averagePatternInRect(_ rect:NSRect?)
}
class ViewController: NSViewController,NSWindowDelegate, ImageViewerDelegate, STEMDataControllerDelegate{
@IBOutlet weak var patternViewer: PatternViewer!
@IBOutlet weak var imageView: ImageViewer!
@IBOutlet weak var innerAngleTextField: NSTextField!
@IBOutlet weak var outerAngleTextField: NSTextField!
@IBOutlet weak var lrud_xySegmented:NSSegmentedControl!
@IBOutlet weak var detectorTypeSegmented:NSSegmentedControl!
@IBOutlet weak var detectorShapeSegmented:NSSegmentedControl!
@IBOutlet weak var viewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var viewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var scrollView: NSScrollView!
@IBOutlet weak var clipView: CenteringClipView!
@IBOutlet weak var displayLogCheckbox: NSButtonCell!
var dataController = STEMDataController()
var patternRect:NSRect? //= NSRect(x: 0, y: 0, width: 0, height: 0)
var selectedDetector:Detector?
let zoomTable = [0.05, 0.10, 0.15, 0.20, 0.30, 0.40, 0.50, 0.75, 1.00, 1.50, 2.00, 3.00, 4.00, 6.00, 8.00, 10.00, 15.00, 20.00, 30.00 ];
@IBOutlet weak var patternSelectionLabel:NSTextField?
var zoomFactor:CGFloat = 1.0 {
didSet {
guard imageView.image != nil else {
return
}
scrollView.magnification = zoomFactor
let winController = self.view.window?.windowController as! WindowController
winController.updateScale(zoomFactor)
}
}
override func awakeFromNib() {
super.awakeFromNib()
imageView.delegate = self
dataController.delegate = self
self.view.window?.makeFirstResponder(patternViewer.detectorView)
selectDetectorType(0)
}
override func viewDidLoad() {
patternViewer.imageScaling = NSImageScaling.scaleProportionallyUpOrDown
patternViewer.bounds = NSRect(x: 0, y: 0, width: 256, height: 256)
let nc = NotificationCenter.default
// nc.addObserver(self, selector: #selector(didFinishLoadingData(note:)), name: Notification.Name("finishedLoadingData"), object: nil)
nc.addObserver(self, selector: #selector(detectorIsMoving(note:)), name: Notification.Name("detectorIsMoving"), object: nil)
nc.addObserver(self, selector: #selector(detectorFinishedMoving(note:)), name: Notification.Name("detectorFinishedMoving"), object: nil)
nc.addObserver(self, selector: #selector(self.pinchZoom(note:)), name: NSScrollView.didEndLiveMagnifyNotification, object: scrollView)
}
@IBAction func open(_sender: Any){
self.openPanel()
}
func loadAndFormatData(_ sender: Any) throws {
let ext = dataController.filePath!.pathExtension
let uti = UTTypeCreatePreferredIdentifierForTag(
kUTTagClassFilenameExtension,
ext as CFString,
nil)
if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeTIFF) {
do{
try dataController.openFile(url: dataController.filePath!)
return
}catch{
throw FileReadError.invalidTiff
}
}
do{
try dataController.openFile(url: dataController.filePath!)
}catch{
throw FileReadError.invalidTiff
}
}
@IBAction func changeLrup_xy(_ sender: Any) {
self.detectImage()
}
@IBAction func changeLog(_ sender: Any){
// need to make sure that a rect has been selected to prevent crash
if patternRect != nil{
averagePatternInRect(patternRect)
}
}
@IBAction func changeImageViewSelectionMode(_ sender: Any){
if let segmented = sender as? NSSegmentedControl{
switch segmented.tag(forSegment: segmented.selectedSegment){
case 0:
imageView.selectMode = .point
case 1:
imageView.selectMode = .marquee
default:
imageView.selectMode = .none
}
}
}
func detectImage(stride:Int = 1){
let lrud_xy = lrud_xySegmented.tag(forSegment: lrud_xySegmented.selectedSegment)
var detectedImage:Matrix? = nil
selectedDetector = patternViewer.detectorView!.detector
switch detectorTypeSegmented.selectedSegment{
case 0:
detectedImage = dataController.integrating(selectedDetector!, strideLength:stride)
case 1:
detectedImage = dataController.dpc(selectedDetector!, strideLength:stride, lrud: lrud_xy )
case 2:
detectedImage = dataController.com(selectedDetector!, strideLength:stride, xy: lrud_xy)
default:
detectedImage = dataController.integrating(selectedDetector!, strideLength:stride)
}
if detectedImage != nil{
self.imageView!.matrix = detectedImage!
}
// self.zoomToFit(nil)
//detectedImage!.imageRepresentation(part: "real", format: MatrixOutput.uint16, nil, nil)
// print("retain count:\(CFGetRetainCount(detectedImage! as CFTypeRef))")
}
@objc func detectorIsMoving(note:Notification) {
// selectedDetector = patternViewer.detectorView!.detector
patternViewer.detectorView?.needsDisplay = true
let stride:Int?
if dataController.imageSize.width % 2 == 0{
var dividor = dataController.imageSize.width
while(dividor > 80){
dividor /= 2
}
stride = dataController.imageSize.width/dividor
}else{
stride = 1
}
self.detectImage(stride: stride!)
innerAngleTextField.floatValue = Float(patternViewer.detectorView!.detector.radii!.inner)
outerAngleTextField.floatValue = Float(patternViewer.detectorView!.detector.radii!.outer)
// let indices = Matrix.init(meshIndicesAlong: 1, empadSize.height-2, empadSize.width)
// let tempMatrix = indices < Float(selectedDetector!.center.x) //.* selectedDetector!.detectorMask()
// patternViewer.detectorView!.detector.detectorMask() .* curPatternMatrix!
//
// patternViewer.image = tempMatrix.imageRepresentation(part: "real", format: MatrixOutput.uint8, nil, nil )
}
@objc func detectorFinishedMoving(note:Notification) {
// selectedDetector = patternViewer.detectorView!.detector
innerAngleTextField.floatValue = Float(patternViewer.detectorView!.detector.radii!.inner)
outerAngleTextField.floatValue = Float(patternViewer.detectorView!.detector.radii!.outer)
self.detectImage()
}
// func selectPatternAt(note:Notification){
//
// let patternPoint = note.object as! NSPoint
//
// let patternIndices = (Int(patternPoint.y), Int(patternPoint.x))
//
// self.selectPatternAt(patternIndices)
//
//
// }
@IBAction func detectorRadiusChanged(_ sender:Any){
if let textField = sender as? NSTextField
{
switch textField.tag{
case 0:
patternViewer.detectorView!.radii!.outer = CGFloat(textField.doubleValue)
case 1:
patternViewer.detectorView!.radii!.inner = CGFloat(textField.doubleValue)
default:
print("radius not changed")
}
patternViewer.detectorView!.needsDisplay = true
self.detectImage()
}else{
}
}
func averagePatternInRect(_ rect:NSRect?){
// print(rect)
patternRect = rect
var avgMatrix = dataController.averagePattern(rect: rect!)
let starti = Int(rect!.origin.y)
let startj = Int(rect!.origin.x)
let endi = starti + Int(rect!.size.height)
let endj = startj + Int(rect!.size.width)
var stringi = String(starti)
var stringj = String(startj)
if starti != endi{
stringi += ":\(endi)"
}
if startj != endj{
stringj += ":\(endj)"
}
let labelString = "(" + stringi + "," + stringj + ")"
patternSelectionLabel?.stringValue = labelString
if(displayLogCheckbox.state == NSButtonCell.StateValue.on){
avgMatrix = avgMatrix.log()
}
patternViewer.matrix = avgMatrix
// patternViewer.matrix = patternViewer.detectorView!.detector.detectorMask()
// patternViewer.needsDisplay = true
}
// Input tuple for (i,j)
func selectPatternAt(_ i: Int, _ j:Int) {
// patternRect = NSRect(x: j, y: i, width: 1, height: 1)
var patternMatrix:Matrix? = dataController.pattern(i, j)
patternSelectionLabel?.stringValue = "(\(j), \(i))"
if patternMatrix != nil{
if(displayLogCheckbox.state == NSButtonCell.StateValue.on){
patternMatrix = patternMatrix!.log()
}
patternViewer.matrix = patternMatrix!
}
}
@IBAction func selectDetectorType(_ sender:Any){
// Update detector type after selecting with keyboard shortcut
var selectedTag:Int = 0
if let menuItem = sender as? NSMenuItem{
selectedTag = menuItem.tag
detectorTypeSegmented.selectSegment(withTag: selectedTag)
} else if let segControl = sender as? NSSegmentedControl{
selectedTag = segControl.selectedSegment
}else{
print("detector not sent by segmented control")
// return
}
let newType:DetectorType
switch selectedTag{
case 0:
newType = DetectorType.integrating
lrud_xySegmented.isEnabled = false
lrud_xySegmented.isHidden = true
case 1:
newType = DetectorType.dpc
lrud_xySegmented.setLabel("L-R", forSegment: 0)
lrud_xySegmented.setLabel("U-D", forSegment: 1)
lrud_xySegmented.isEnabled = true
lrud_xySegmented.isHidden = false
case 2:
newType = DetectorType.com
lrud_xySegmented.setLabel("X", forSegment: 0)
lrud_xySegmented.setLabel("Y", forSegment: 1)
lrud_xySegmented.isEnabled = true
lrud_xySegmented.isHidden = false
default:
newType = DetectorType.integrating
lrud_xySegmented.isEnabled = false
lrud_xySegmented.isHidden = true
}
patternViewer.detectorView?.detectorType = newType
patternViewer.detectorView?.needsDisplay = true
selectedDetector = patternViewer.detectorView!.detector
self.detectImage(stride: 1)
}
@IBAction func showHideDetector(_ sender:Any){
patternViewer.detectorView?.selectionIsHidden = !(patternViewer.detectorView?.selectionIsHidden)!
patternViewer.detectorView?.needsDisplay = true
}
@IBAction func showHideImageSelection(_ sender:Any){
imageView.selectionIsHidden = !(imageView.selectionIsHidden)
imageView.needsDisplay = true
}
@IBAction func selectDetectorShape(_ sender:Any){
var selectedTag:Int
if let menuItem = sender as? NSMenuItem{
selectedTag = menuItem.tag
detectorShapeSegmented.selectSegment(withTag: selectedTag)
} else if let segControl = sender as? NSSegmentedControl{
selectedTag = segControl.selectedSegment
}
else{
print("detector not sent by segmented control")
return
}
let newShape:DetectorShape
switch selectedTag{
case 0:
newShape = DetectorShape.bf
innerAngleTextField.isEnabled = false
outerAngleTextField.isEnabled = true
case 1:
newShape = DetectorShape.adf
innerAngleTextField.isEnabled = true
outerAngleTextField.isEnabled = false
case 2:
newShape = DetectorShape.af
innerAngleTextField.isEnabled = true
outerAngleTextField.isEnabled = true
default:
newShape = DetectorShape.bf
innerAngleTextField.isEnabled = false
outerAngleTextField.isEnabled = true
}
patternViewer.detectorView?.radii = DetectorRadii(inner: CGFloat(innerAngleTextField.floatValue), outer:CGFloat(outerAngleTextField.floatValue))
patternViewer.detectorView?.detectorShape = newShape
patternViewer.detectorView?.needsDisplay = true
selectedDetector = patternViewer.detectorView!.detector
self.detectImage(stride: 1)
}
func openPanel(){
let openPanel = NSOpenPanel()
openPanel.allowedFileTypes = ["raw", "public.tiff", ]
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = true
if (openPanel.runModal() == NSApplication.ModalResponse.OK){
let selectedURL = openPanel.url
if selectedURL != nil{
dataController.filePath = selectedURL
// add to recents menu
let dc = NSDocumentController.shared
dc.noteNewRecentDocumentURL(selectedURL!)
self.displayProbePositionsSelection(openPanel.url!)
}
}
}
@objc func didFinishLoadingData() {
self.view.window?.title = dataController.filePath!.deletingPathExtension().lastPathComponent
if patternViewer.detectorView?.isHidden == true{
let size = NSSize(width: dataController.patternSize.height, height: dataController.patternSize.width)
patternViewer.detectorView!.detector = Detector(shape: DetectorShape.bf, type: DetectorType.integrating, center: NSPoint.init(x: 63, y:63), radii: DetectorRadii(inner: CGFloat(innerAngleTextField.floatValue), outer: CGFloat(outerAngleTextField.floatValue)),size:size)
}
patternViewer.detectorView?.isHidden = false
imageView.isHidden = false
imageView.selectionRect = nil
patternRect = NSRect(x: dataController.imageSize.height/2, y: dataController.imageSize.width/2, width: 0, height: 0)
self.averagePatternInRect(patternRect)
self.detectImage()
imageView.setFrameSize(imageView.image!.size)
viewHeightConstraint.constant = imageView.image!.size.height //* zoomFactor
viewWidthConstraint.constant = imageView.image!.size.width //* zoomFactor
// zoomToActual(nil)
zoomToFit(nil)
}
@IBAction func displayProbePositionsSelection(_ sender: Any){
let sizeSelectionController:ProbeSelectViewController = storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "ProbeSelectViewController")) as! ProbeSelectViewController
self.presentViewControllerAsSheet(sizeSelectionController)
sizeSelectionController.view.window?.makeFirstResponder(sizeSelectionController.loadButton)
sizeSelectionController.dataController = dataController
sizeSelectionController.parentController = self
sizeSelectionController.selectSizeFromURL(sender as! URL)
dataController.progressdelegate = sizeSelectionController
let ext = (sender as! URL).pathExtension
let uti = UTTypeCreatePreferredIdentifierForTag(
kUTTagClassFilenameExtension,
ext as CFString,
nil)
if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeTIFF) {
print("stuff")
sizeSelectionController.loadTiff(self)
}
}
@IBAction func export(_ sender:Any){
var tag = 0
if sender is NSMenuItem{
let menuItem = sender as! NSMenuItem
tag = menuItem.tag
}else if sender is NSPopUpButton{
let popup = sender as! NSPopUpButton
tag = popup.indexOfSelectedItem - 1
}
let savePanel = NSSavePanel()
savePanel.canCreateDirectories = true
savePanel.showsTagField = false
savePanel.isExtensionHidden = false
savePanel.allowedFileTypes = ["tif"]
if tag == 0{
var lrud_xyLabel = ""
let detector = self.patternViewer.detectorView?.detector
if detector?.type == DetectorType.com || detector?.type == DetectorType.dpc{
lrud_xyLabel = "_" + lrud_xySegmented.label(forSegment: lrud_xySegmented.selectedSegment)!
}
let detectorTypeLabel = detectorTypeSegmented.label(forSegment: detectorTypeSegmented.selectedSegment)!
savePanel.nameFieldStringValue = (self.view.window?.title)! + "_" + detectorTypeLabel + lrud_xyLabel
}else if tag == 1{
savePanel.nameFieldStringValue = (self.view.window?.title)!+"_"+(patternSelectionLabel?.stringValue)!
}
savePanel.begin( completionHandler:{(result) in
if result == NSApplication.ModalResponse.OK {
let filename = savePanel.url
var bitmapRep:NSBitmapImageRep?
if(tag == 0){
bitmapRep = self.imageView.matrix.floatImageRep()
}else if tag == 1{
bitmapRep = self.patternViewer.matrix.floatImageRep()
}
// To add metadata, will need to switch to cgimagedestination
var data:Data = Data.init()
let props = [NSBitmapImageRep.PropertyKey:Any]()
// props[NSBitmapImageRep.PropertyKey.compressionFactor] = 1.0
// props[NSBitmapImageRep.PropertyKey.gamma] = 0.5
if bitmapRep != nil{
data = bitmapRep!.representation(using: NSBitmapImageRep.FileType.tiff, properties: props)!
}
var cgProps = [CFString:Any]()
let dest = CGImageDestinationCreateWithURL(filename! as CFURL, "public.tiff" as CFString, 1, nil)
cgProps["{TIFF}" as CFString] = ["ImageDescription" as CFString:"A description" as CFString]
CGImageDestinationAddImage(dest!, bitmapRep!.cgImage!, cgProps as CFDictionary)
CGImageDestinationFinalize(dest!)
} else {
print("save failed")
}
})
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func nearestZoom() -> Int{
var minIndex = 0
var zoomDiff = fabs(Double(zoomFactor)-zoomTable[0])
for (i,_) in zoomTable.enumerated(){
let tempDiff = fabs(Double(zoomFactor)-zoomTable[i])
if zoomDiff > tempDiff {
minIndex += 1
}else if zoomDiff < tempDiff{
break
}
zoomDiff = tempDiff
}
return minIndex
}
@IBAction func zoomIn(_ sender: NSMenuItem?) {
let newZoomIndex = nearestZoom()+1;
if newZoomIndex <= zoomTable.count - 1{
zoomFactor = CGFloat(zoomTable[newZoomIndex])
}
}
@objc func pinchZoom(note:Notification){
zoomFactor = scrollView.magnification
}
@IBAction func zoomInOut(_ sender: Any) {
if sender is NSSegmentedControl{
let zoomButton = sender as! NSSegmentedControl
if zoomButton.selectedSegment == 0{
self.zoomOut(nil)
}else if zoomButton.selectedSegment == 1{
self.zoomIn(nil)
}
} else if sender is NSTextField{
let scaleField = sender as! NSTextField
zoomFactor = CGFloat(scaleField.floatValue)
}
}
@IBAction func zoomOut(_ sender: NSMenuItem?) {
let newZoomIndex = nearestZoom()-1;
if newZoomIndex >= 0{
zoomFactor = CGFloat(zoomTable[newZoomIndex])
}
}
@IBAction func zoomToActual(_ sender: NSMenuItem?) {
zoomFactor = 1.0
}
@IBAction func zoomToFit(_ sender: NSMenuItem?) {
guard imageView!.image != nil else {
return
}
// let imSize = imageView!.image!.size
//
// var clipSize = clipView.bounds.size
//
//
// guard imSize.width > 0 && imSize.height > 0 && clipSize.width > 0 && clipSize.height > 0 else {
//
// return
//
// }
//
// // 20 pixel gutter
//
// let imageMargin:CGFloat = 40
//
// clipSize.width -= imageMargin
// clipSize.height -= imageMargin
//
// let clipAspectRatio = clipSize.width / clipSize.height
// let imAspectRatio = imSize.width / imSize.height
//
// if clipAspectRatio > imAspectRatio {
//
// zoomFactor = clipSize.height / imSize.height
//
// } else {
//
// zoomFactor = clipSize.width / imSize.width
//
// }
scrollView.magnify(toFit: imageView.frame)
zoomFactor = scrollView.magnification
}
}
| 29.404177 | 279 | 0.559014 |
50b9781037813297007b264bcd2d56be30cf2ffa | 4,354 | //
// TabCell.swift
// PagerTab
//
// Created by Suhaib Al Saghir on 14/05/2020.
// Copyright © 2020 Suhaib Al Saghir. All rights reserved.
//
import UIKit
protocol TabCellProtocol: class {
func animate(isShowing: Bool)
}
class TabCell: UIView, TabCellProtocol {
@IBOutlet private weak var tabImageView: UIImageView!
@IBOutlet private weak var tabLabel: UILabel!
@IBOutlet private weak var notificationView: UIView!
@IBOutlet private weak var notificationCounter: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
connectXib()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
connectXib()
}
func configure(with tabType: SPagerModels.TabType) {
switch tabType {
case .soloText(let text):
self.tabImageView.isHidden = true
self.tabLabel.attributedText = text
case .image(let image, let text):
self.tabImageView.image = image
self.tabLabel.attributedText = text
}
self.notificationView.layer.cornerRadius = self.notificationView.bounds.height / 2
}
func setTextColor(_ color: UIColor?) {
self.tabLabel.textColor = color
}
func setBadgeColor(_ color: UIColor?) {
self.notificationView.backgroundColor = color
}
func setTextFont(_ font: UIFont?) {
self.tabLabel.font = font
}
func setImageHeight(_ height: CGFloat?) {
guard let height = height else { return }
self.tabImageView.translatesAutoresizingMaskIntoConstraints = false
self.tabImageView.heightAnchor.constraint(equalToConstant: height).isActive = true
}
func setImageTint(_ color: UIColor?) {
self.tabImageView.tintColor = color
}
func updateCounter(with count: Int) {
self.notificationView.isHidden = count == 0
UIView.animate(withDuration: 0.3) { [weak self] in
self?.notificationCounter.text = count >= 99 ? "+\(99)" : String(count)
if count == 0 {
self?.notificationView.alpha = 0
} else {
let isSelected = self?.notificationView.transform != .identity
self?.notificationView.alpha = isSelected ? 1 : 0.6
}
}
}
func animate(isShowing: Bool) {
UIView.animate(withDuration: 0.3) { [weak self] in
if isShowing {
self?.tabLabel.transform = .init(scaleX: 1.1, y: 1.1)
self?.tabLabel.alpha = 1
self?.tabImageView.transform = .init(scaleX: 1.1, y: 1.1)
self?.tabImageView.alpha = 1
self?.notificationView.transform = .init(scaleX: 1.1, y: 1.1)
self?.notificationView.alpha = self?.notificationCounter.text == "0" ? 0 : 1
} else {
self?.tabLabel.transform = .identity
self?.tabLabel.alpha = 0.6
self?.tabImageView.transform = .identity
self?.tabImageView.alpha = 0.6
self?.notificationView.transform = .identity
self?.notificationView.alpha = self?.notificationCounter.text == "0" ? 0 : 0.6
}
}
}
}
extension TabCell {
func connectXib() {
self.backgroundColor = .clear
let view = self.loadNib()
view.frame = self.bounds
self.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(
[
view.topAnchor.constraint(equalTo: self.topAnchor),
view.bottomAnchor.constraint(equalTo: self.bottomAnchor),
view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.trailingAnchor)
]
)
}
/** Loads instance from nib with the same name. */
func loadNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nibName = String(describing: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as! UIView //swiftlint:disable:this force_cast
}
}
| 32.736842 | 114 | 0.588195 |
f4b390a718741f082d1d0ff3fbf41b8a2d7dd1af | 295 | //
// FloatingPoint+ValuesConversion.swift
// SugarLumpFoundation
//
// Created by Mario Chinchilla on 10/10/18.
//
//
import Foundation
public extension FloatingPoint {
var degreesToRadians: Self { return self * .pi / 180 }
var radiansToDegrees: Self { return self * 180 / .pi }
}
| 19.666667 | 58 | 0.694915 |
e5378d756b7c06519fafb37a43aa290007116cad | 669 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
/** The item type to filter by. Defaults to unspecified. */
public enum ItemType: String, Codable {
case movie = "movie"
case show = "show"
case season = "season"
case episode = "episode"
case program = "program"
case link = "link"
case trailer = "trailer"
case channel = "channel"
public static let cases: [ItemType] = [
.movie,
.show,
.season,
.episode,
.program,
.link,
.trailer,
.channel,
]
}
| 13.38 | 59 | 0.481315 |
0ea04ec248b8ac323d66f768f3a960a40f07cdfd | 4,211 | // MIT License
//
// Copyright (c) 2020 Thales DIS
//
// 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.
// IMPORTANT: This source code is intended to serve training information purposes only.
// Please make sure to review our IdCloud documentation, including security guidelines.
/**
Values needed for Token provisioning.
*/
class ProvisioningConfig {
/**
The URL of the Enrollment API endpoint, e.g: “https://api/provisioning/pp”
@return Provision URL
*/
class func getProvisioningUrl() -> URL {
return URL(string: "")!
}
/**
Identifier for the EPS server’s public RSA key.
@return RSA key ID.
*/
class func getRsaKeyId() -> String {
return ""
}
/**
The RSA modulus of the EPS public key (on provisioning protocol level, not transport level).
@return RSA Key Modulus.
*/
class func getRsaKeyModulus() -> Data {
let raw: [UInt8] = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
]
return Data(raw)
}
/**
The RSA exponent of the EPS public key (on provisioning protocol level, not transport level).
@return RSA Key Exponent.
*/
class func getRsaKeyExponent() -> Data {
let raw: [UInt8] = [0x00, 0x00, 0x00]
return Data(raw)
}
/**
* This configuration will allow to weaken TLS configuration for debug purposes. It’s not allowed to modify in release mode.
*
* @return TLS configuration.
*/
class func getTlsConfiguration() -> EMFastTrackTlsConfiguration {
return EMFastTrackTlsConfiguration(insecureConnectionAllowed: true, selfSignedCertAllowed: true, hostnameMismatchAllowed: true)
}
/**
Gets the custom fingerprint data.
@return Custom fingerprint data.
*/
class func getCustomFingerprintData() -> Data {
return "".data(using: .utf8)!
}
/**
Gets the domain.
@return Domain.
*/
class func getDomain() -> String {
return ""
}
/**
Gets the timestep.
*/
class func getTimeStep() -> Int {
return 30
}
}
| 34.235772 | 135 | 0.611256 |
9b74b6ba983697cb7718d53ca6980d7ec862a493 | 7,370 | //
// ViewController.swift
// AudioTest
//
// Created by hirochin on 08/12/2017.
// Copyright © 2017 Thel. All rights reserved.
//
import AVFoundation
import CoreMedia
import CoreAudio
import Cocoa
class ViewController: NSViewController {
let captureSession = AVCaptureSession()
let audioOutput = AVCaptureAudioDataOutput()
@IBOutlet weak var graphView: GraphView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
audioOutput.audioSettings = [
AVFormatIDKey: kAudioFormatLinearPCM,
AVLinearPCMBitDepthKey: 16,
AVLinearPCMIsFloatKey: false,
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
]
let devices = AVCaptureDevice.devices().filter { $0.hasMediaType(AVMediaType.audio) }
if let captureDevice = devices.first {
try! captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
assert(captureSession.canAddOutput(audioOutput))
captureSession.addOutput(audioOutput)
audioOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global())
}
}
var lastTime: CFAbsoluteTime = 0
override func viewDidAppear() {
super.viewDidAppear()
captureSession.startRunning()
}
override func viewWillDisappear() {
super.viewWillDisappear()
captureSession.stopRunning()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
var data: [[Int16]] = []
let afs = AudioFrequencySpectrum(sampleRate: 44100, sampleCountPerInvoke: 512)
}
extension ViewController: AVCaptureAudioDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// let now = CFAbsoluteTimeGetCurrent()
// print("got sample every \(now - lastTime)")
// lastTime = now
let bufferListSizeNeeded = UnsafeMutablePointer<Int>.allocate(capacity: 1)
var bufferList = AudioBufferList()
let listSize: Int = MemoryLayout<AudioBufferList>.size
var blockBuffer: CMBlockBuffer?
let allocator = kCFAllocatorDefault
let result = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
sampleBuffer,
bufferListSizeNeeded,
&bufferList,
listSize,
allocator,
allocator,
kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
&blockBuffer
)
if (result == kCMSampleBufferError_ArrayTooSmall) {
// Read twice. ref => https://lists.apple.com/archives/quicktime-api/2013/Apr/msg00015.html
let code = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
sampleBuffer,
bufferListSizeNeeded,
&bufferList,
bufferListSizeNeeded.pointee,
allocator,
allocator,
kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
&blockBuffer
)
assert(code == 0 && blockBuffer != nil)
}
assert(blockBuffer != nil)
let buffers = UnsafeBufferPointer<AudioBuffer>(start: &bufferList.mBuffers, count: Int(bufferList.mNumberBuffers))
switch foo(samplebuffer: sampleBuffer) {
case .Float:
for buffer in buffers {
let samplesCount = Int(buffer.mDataByteSize) / MemoryLayout<Float>.size
let samplesPointer = bufferList.mBuffers.mData!.bindMemory(to: Float.self, capacity: samplesCount)
let samples = UnsafeMutableBufferPointer<Float>(start: samplesPointer, count: samplesCount)
let rawValues = samples.compactMap { $0 }
// var rrr = 0 as Float
// for vv in rawValues {
// rrr = rrr + Float(vv)
// }
// let avg = Double(rrr) / Double(rawValues.count)
// print(String(format: "Double: %.4f", avg))
//
// graphView.data = rawValues
graphView.data = afs.fft(xs: rawValues)
DispatchQueue.main.async {
self.graphView.setNeedsDisplay(self.graphView.bounds)
}
// print("rawValues: \(rawValues.count)")
}
case .Integer:
// print("Integer route")
for buffer in buffers {
let samplesCount = Int(buffer.mDataByteSize) / MemoryLayout<Int16>.size
let samplesPointer = bufferList.mBuffers.mData!.bindMemory(to: Int16.self, capacity: samplesCount)
let samples = UnsafeMutableBufferPointer<Int16>(start: samplesPointer, count: samplesCount)
let rawValues = samples.compactMap { $0 }
// data.append(rawValues)
// if data.count == 10 {
// print("")
// }
// var rrr = 0 as Int64
// for vv in rawValues {
// rrr = rrr + Int64(vv)
// }
// let avg = Double(rrr) / Double(rawValues.count)
// print("Sample Size: \(samplesCount) \t Integer: \(avg)")
//
// let rr: [Float] = rawValues.map({ abs(Float($0) / Float(Int16.max)) })
// graphView.data = rr
// DispatchQueue.main.async {
// self.graphView.setNeedsDisplay(self.graphView.bounds)
// }
// let amplitudes = samples.compactMap(ViewController.convertToDouble)
// graphView.data = FFT.fft(amplitudes, sampleRate: 44100)
graphView.data = afs.fft(xs: rawValues)
DispatchQueue.main.async {
self.graphView.setNeedsDisplay(self.graphView.bounds)
}
}
default:
print("Failed")
}
}
func foo(samplebuffer: CMSampleBuffer) -> Format {
let formatDescription = CMSampleBufferGetFormatDescription(samplebuffer)!
let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescription)!.pointee
assert(asbd.mFormatID == kAudioFormatLinearPCM)
// assert((asbd.mFormatFlags & kLinearPCMFormatFlagIsSignedInteger) != 0)
// print(asbd.mFormatFlags)
if (asbd.mFormatFlags & kLinearPCMFormatFlagIsSignedInteger) > 0 {
return .Integer
}
else if (asbd.mFormatFlags & kLinearPCMFormatFlagIsFloat) > 0 {
return .Float
}
else {
assert(false)
}
return .Unknow
}
enum Format {
case Float
case Integer
case Unknow
}
static func convertToDouble(x: Int16) -> Double {
let r = Double(x) / Double(Int16.max)
if r > 1.0 { return 1 }
if r < -1.0 { return -1 }
return r
}
}
| 34.27907 | 129 | 0.567436 |
ed300623e9c0f0dbfef226dd82e9b35ef711fbe5 | 1,010 | //
// AuthCoordinator.swift
// Pixl
//
// Created by Dscyre Scotti on 21/04/2021.
//
import XCoordinator
enum AuthRoute: Route {
case login
case home
}
class AuthCoordinator: NavigationCoordinator<AuthRoute> {
weak var parent: AppCoordinator?
init(_ parent: AppCoordinator? = nil) {
self.parent = parent
super.init(initialRoute: .login)
rootViewController.navigationBar.prefersLargeTitles = false
rootViewController.navigationBar.tintColor = .label
rootViewController.setTransparency()
}
override func prepareTransition(for route: RouteType) -> NavigationTransition {
switch route {
case .login:
let viewModel = LoginViewModel(unownedRouter)
let loginViewController = LoginViewController()
loginViewController.bind(viewModel)
return .push(loginViewController)
case .home:
parent?.trigger(.home)
return .none()
}
}
}
| 24.634146 | 83 | 0.642574 |
233697dfaa57ffce33ed6832b93f287a7453c1b7 | 4,395 | import CocoaAsyncSocket
import XCTest
/**
* A simple test wrapper around GCDAsyncSocket which acts as a server
*/
class TestServer: NSObject {
/**
* Creates a SecIdentity from the bundled SecureSocketServer.p12
*
* For creating a secure connection, we need to start TLS with a valid identity. The one in
* in SecureSocketServer.p12 is a self signed SSL sever cert that was creating following Apple's
* "Creating Certificates for TLS Testing". No root CA is used, however.
*
* https://developer.apple.com/library/content/technotes/tn2326/_index.html
*
* Most of this code in the this method from Apple's examples on reading in the contents of a
* p12.
*
* https://developer.apple.com/documentation/security/certificate_key_and_trust_services/identities/importing_an_identity
*/
static var identity: SecIdentity = {
let bundle = Bundle(for: TestServer.self)
guard let url = bundle.url(forResource: "SecureSocketServer", withExtension: "p12") else {
fatalError("Missing the server cert resource from the bundle")
}
do {
let p12 = try Data(contentsOf: url) as CFData
let options = [kSecImportExportPassphrase as String: "test"] as CFDictionary
var rawItems: CFArray?
guard SecPKCS12Import(p12, options, &rawItems) == errSecSuccess else {
fatalError("Error in p12 import")
}
let items = rawItems as! Array<Dictionary<String,Any>>
let identity = items[0][kSecImportItemIdentity as String] as! SecIdentity
return identity
}
catch {
fatalError("Could not create server certificate")
}
}()
private static func randomValidPort() -> UInt16 {
let minPort = UInt32(1024)
let maxPort = UInt32(UINT16_MAX)
let value = maxPort - minPort + 1
return UInt16(minPort + arc4random_uniform(value))
}
// MARK: Convenience Callbacks
typealias Callback = TestSocket.Callback
var onAccept: Callback = {}
var onDisconnect: Callback = {}
let port: UInt16 = TestServer.randomValidPort()
let queue = DispatchQueue(label: "com.asyncSocket.TestServerDelegate")
let socket: GCDAsyncSocket
var lastAcceptedSocket: TestSocket? = nil
override init() {
self.socket = GCDAsyncSocket()
super.init()
self.socket.delegate = self
self.socket.delegateQueue = self.queue
}
func accept() {
do {
try self.socket.accept(onPort: self.port)
}
catch {
fatalError("Failed to accept on port \(self.port): \(error)")
}
}
func close() {
let waiter = XCTWaiter(delegate: TestSocket.waiterDelegate)
let didDisconnect = XCTestExpectation(description: "Server disconnected")
self.queue.async {
guard self.socket.isConnected else {
didDisconnect.fulfill()
return
}
self.onDisconnect = {
didDisconnect.fulfill()
}
self.socket.disconnect()
}
waiter.wait(for: [didDisconnect], timeout: 0.2)
}
}
// MARK: GCDAsyncSocketDelegate
extension TestServer: GCDAsyncSocketDelegate {
func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
self.lastAcceptedSocket = TestSocket(socket: newSocket)
self.onAccept?()
self.onAccept = nil
}
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
self.onDisconnect?()
self.onDisconnect = nil
}
}
// MARK: Factory
extension TestServer {
func createPair() -> (client: TestSocket, accepted: TestSocket) {
let waiter = XCTWaiter(delegate: TestSocket.waiterDelegate)
let didConnect = XCTestExpectation(description: "Pair connected")
didConnect.expectedFulfillmentCount = 2
let client = TestSocket()
self.onAccept = {
didConnect.fulfill()
}
client.onConnect = {
didConnect.fulfill()
}
self.accept()
client.connect(on: self.port)
let _ = waiter.wait(for: [didConnect], timeout: 2.0)
guard let accepted = self.lastAcceptedSocket else {
fatalError("No socket connected on \(self.port)")
}
return (client, accepted)
}
func createSecurePair() -> (client: TestSocket, accepted: TestSocket) {
let (client, accepted) = self.createPair()
let waiter = XCTWaiter(delegate: TestSocket.waiterDelegate)
let didSecure = XCTestExpectation(description: "Socket did secure")
didSecure.expectedFulfillmentCount = 2
accepted.startTLS(as: .server) {
didSecure.fulfill()
}
client.startTLS(as: .client) {
didSecure.fulfill()
}
waiter.wait(for: [didSecure], timeout: 0.2)
return (client, accepted)
}
}
| 24.830508 | 125 | 0.717179 |
2389eded8f43e0eb6f1ed58569ea4c084e17e6ab | 9,673 | // Copyright 2020 Penguin Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
fileprivate extension MemoryLayout {
/// True iff `T` instances are stored in an existential's inline buffer space.
static var fitsExistentialInlineBuffer: Bool {
MemoryLayout<(T, Any.Type)>.size <= MemoryLayout<Any>.size
&& self.alignment <= MemoryLayout<Any>.alignment
&& _isBitwiseTakable(T.self)
}
}
/// A wrapper for a value of any type, with efficient access and inline storage of bounded size for
/// small values.
///
/// Existential types such as `Any` provide the storage characteristics of `AnyValue`, but many
/// operations on existentials [optimize poorly](https://bugs.swift.org/browse/SR-13438), so
/// `AnyValue` may be needed to achieve efficient access.
///
/// Using `enums` and no existential, it is possible to build such storage for:
/// - types that are trivially copiable (such as Int), or
/// - collections of elements with the inline storage being (roughly) a multiple of the element
/// size.
/// You might consider using the `enum` approach where applicable.
public struct AnyValue {
/// The memory layout of `Any` instances.
private typealias AnyLayout = (inlineStorage: (Int, Int, Int), storedType: Any.Type)
/// The underlying storage of the value.
///
/// Types that fit the inline storage of `Any` are stored directly, by assignment. Although `Any`
/// has its own boxing mechanism for types that don't fit its inline storage, it is apparently
/// incompatible with our needs for mutation (https://bugs.swift.org/browse/SR-13460) and
/// seem to be needlessly reallocated in some cases. Therefore, larger types are stored
/// indirectly in a class instance of static type `BoxBase`. Object references fit the inline
/// storage of `Any`, so the value held *directly* by `storage` is always stored in its inline
/// buffer.
fileprivate var storage: Any
/// Creates an instance that stores `x`.
///
/// - Postcondition: where `a` is the created instance, `a.storedType == T.self`, and `a[T.self]`
/// is equivalent to `x`.
public init<T>(_ x: T) {
if MemoryLayout<T>.fitsExistentialInlineBuffer { storage = x}
else { storage = Box(x) as BoxBase }
}
/// The type of the value held directly by `storage`.
///
/// If the type stored in `self` does not fit the inline storage of an existential,
/// `directlyStoredType` will be `BoxBase.self`.
private var directlyStoredType: Any.Type {
// Note: using withUnsafePointer(to: storage) rather than withUnsafePointer(to: self) produces a
// copy of storage, and thus much worse code (https://bugs.swift.org/browse/SR-13462).
return Swift.withUnsafePointer(to: self) { // https://bugs.swift.org/browse/SR-13462
UnsafeRawPointer($0).assumingMemoryBound(to: AnyLayout.self)[0].storedType
}
}
/// The type of the value stored in `self`.
public var storedType: Any.Type {
let d = directlyStoredType
if d != Self.boxType { return d }
return self[unsafelyAssuming: Type<BoxBase>()].storedType
}
/// Returns a pointer to the `T` which is assumed to be stored in `self`.
private func pointer<T>(toStored _: Type<T>) -> UnsafePointer<T> {
// Note: using withUnsafePointer(to: storage) rather than withUnsafePointer(to: self) produces a
// copy of storage, and thus much worse code (https://bugs.swift.org/browse/SR-13462).
return withUnsafePointer(to: self) {
let address = UnsafeRawPointer($0)
if MemoryLayout<T>.fitsExistentialInlineBuffer {
return address.assumingMemoryBound(to: T.self)
}
else {
let boxBase = address.assumingMemoryBound(to: Self.boxType).pointee
let box = unsafeDowncast(boxBase, to: Box<T>.self)
return withUnsafeMutablePointer(to: &box.value) { .init($0) }
}
}
}
/// A dynamically-allocated box storing a statically-unknown type that doesn't fit in an
/// existential's inline buffer.
private class BoxBase {
/// The type stored in this box.
final let storedType: Any.Type
/// Creates an instance with the given `storedType`
fileprivate init(storedType: Any.Type) {
self.storedType = storedType
}
/// Returns the boxed value.
fileprivate var asAny: Any { fatalError("override me") }
}
/// Cached type metadata (see https://bugs.swift.org/browse/SR-13459)
private static let boxType = BoxBase.self
/// A box holding a value of type `T`, which wouldn't fit in an existential's inline buffer.
///
/// - Note: it's crucial to always cast a `Box` instance to `BoxBase` before assigning it into
/// `storage.`
private final class Box<T>: BoxBase {
/// The boxed value
var value: T
/// Creates an instance storing `value`
///
/// - Requires: !MemoryLayout<T>.fitsExistentialInlineBuffer
init(_ value: T) {
assert(
!MemoryLayout<T>.fitsExistentialInlineBuffer, "Boxing a value that should be stored inline")
assert(!(value is BoxBase), "unexpectedly boxing a box!")
self.value = value
super.init(storedType: T.self)
}
/// Returns the boxed value.
fileprivate override var asAny: Any { value }
}
/// Returns a pointer to the `T` which is assumed to be stored in `self`.
///
/// If the `T` is stored in a shared box, the box is first copied to make it unique.
///
/// - Requires: `storedType == T.self`
private mutating func mutablePointer<T>(toStored _: Type<T>) -> UnsafeMutablePointer<T> {
let address: UnsafeMutableRawPointer = withUnsafeMutablePointer(to: &storage) { .init($0) }
if MemoryLayout<T>.fitsExistentialInlineBuffer {
return address.assumingMemoryBound(to: T.self)
}
if !isKnownUniquelyReferenced(&self[unsafelyAssuming: Type<BoxBase>()]) {
rebox(stored: Type<T>())
}
let boxBase = address.assumingMemoryBound(to: Self.boxType).pointee
let box = unsafeDowncast(boxBase, to: Box<T>.self)
return withUnsafeMutablePointer(to: &box.value) { $0 }
}
/// Copies the boxed `T`.
///
/// - Requires: `storedType == T.self`
/// - Requires: `!MemoryLayout<T>.fitsExistentialInlineBuffer`
// TODO: see if this is really best done out-of-line, considering that `isKnownUniquelyReferenced`
// is already a function call.
@inline(never)
private mutating func rebox<T>(stored _: Type<T>) {
storage = Box(self[unsafelyAssuming: Type<T>()]) as BoxBase
}
/// Iff `storedType != T.self`, traps with an appropriate error message.
private func typeCheck<T>(_: Type<T>) {
if storedType != T.self { typeCheckFailure(T.self) }
}
/// Traps with an appropriate error message assuming that `storedType != T.self`.
@inline(never)
private func typeCheckFailure(_ expectedType: Any.Type) {
fatalError("stored type \(storedType) != \(expectedType)")
}
/// Accesses the `T` stored in `self`.
///
/// - Requires: `storedType == T.self`.
@inline(__always) // Compiler likes to skip inlining this otherwise.
public subscript<T>(_: Type<T>) -> T {
get {
defer { _fixLifetime(self) }
typeCheck(Type<T>())
return pointer(toStored: Type<T>()).pointee
}
_modify {
typeCheck(Type<T>())
defer { _fixLifetime(self) }
yield &mutablePointer(toStored: Type<T>()).pointee
}
}
/// Unsafely accesses the `T` stored in `self`.
///
/// - Requires: `storedType == T.self`.
@inline(__always) // Compiler likes to skip inlining this otherwise.
public subscript<T>(unsafelyAssuming _: Type<T>) -> T {
get {
defer { _fixLifetime(self) }
return pointer(toStored: Type<T>()).pointee
}
_modify {
defer { _fixLifetime(self) }
yield &mutablePointer(toStored: Type<T>()).pointee
}
}
/// Stores `x` in `self`.
///
/// This may be more efficient than `self = AnyValue(x)` because it uses the same allocated buffer
/// when possible for large types.
public mutating func store<T>(_ x: T) {
defer { _fixLifetime(self) }
if storedType == T.self { mutablePointer(toStored: Type<T>()).pointee = x }
else { self = .init(x) }
}
/// The stored value.
///
/// This property can be useful for interoperability with the rest of Swift, especially when you
/// don't know the full dynamic type of the stored value.
public var asAny: Any {
if directlyStoredType != Self.boxType { return storage }
return self[unsafelyAssuming: Type<BoxBase>()].asAny
}
/// If the stored value is boxed or is an object, returns the ID of the box or object; returns
/// `nil` otherwise.
///
/// Used only by tests.
internal var boxOrObjectID_testable: ObjectIdentifier? {
if !(directlyStoredType is AnyObject.Type) { return nil }
return .init(self[unsafelyAssuming: Type<AnyObject>()])
}
}
extension AnyValue: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of this instance.
public var description: String { String(describing: storage) }
/// A string, suitable for debugging, that represents the instance.
public var debugDescription: String { "AnyValue(\(String(reflecting: storage)))" }
}
| 39.481633 | 100 | 0.681795 |
dd697b316a17534342c55f5df6cf2a734e1f8961 | 2,123 | //
// Dictionary+OAuthSwift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
extension Dictionary {
func join(_ other: Dictionary) -> Dictionary {
var joinedDictionary = Dictionary()
for (key, value) in self {
joinedDictionary.updateValue(value, forKey: key)
}
for (key, value) in other {
joinedDictionary.updateValue(value, forKey: key)
}
return joinedDictionary
}
func filter(_ predicate: (_ key: Key, _ value: Value) -> Bool) -> Dictionary {
var filteredDictionary = Dictionary()
for (key, value) in self {
if predicate(key, value) {
filteredDictionary.updateValue(value, forKey: key)
}
}
return filteredDictionary
}
var urlEncodedQuery: String {
var parts = [String]()
for (key, value) in self {
let keyString = "\(key)".urlEncodedString
let valueString = "\(value)".urlEncodedString
let query = "\(keyString)=\(valueString)"
parts.append(query)
}
return parts.joined(separator: "&")
}
mutating func merge<K, V>(_ dictionaries: Dictionary<K, V>...) {
for dict in dictionaries {
for (key, value) in dict {
self.updateValue(value as! Value, forKey: key as! Key)
}
}
}
func map<K: Hashable, V> (_ transform: (Key, Value) -> (K, V)) -> Dictionary<K, V> {
var results: Dictionary<K, V> = [:]
for k in self.keys {
if let value = self[ k ] {
let (u, w) = transform(k, value)
results.updateValue(w, forKey: u)
}
}
return results
}
}
func +=<K, V> (left: inout [K : V], right: [K : V]) { left.merge(right) }
func +<K, V> (left: [K : V], right: [K : V]) -> [K : V] { return left.join(right) }
func +=<K, V> (left: inout [K : V]?, right: [K : V]) {
if let _ = left { left?.merge(right) } else { left = right }
}
| 27.571429 | 88 | 0.534621 |
6a7266f487677070bf4e707db7f0ad631be341a2 | 3,135 | //
// MonochromeFilter.swift
// FlexibleImage
//
// Created by Kawoou on 2017. 5. 12..
// Copyright © 2017년 test. All rights reserved.
//
#if !os(watchOS)
import Metal
#endif
internal class MonochromeFilter: ImageFilter {
// MARK: - Property
internal override var metalName: String {
get {
return "MonochromeFilter"
}
}
internal var threshold: Float = 1.0
// MARK: - Internal
#if !os(watchOS)
@available(OSX 10.11, iOS 8, tvOS 9, *)
internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool {
let factors: [Float] = [self.threshold]
for i in 0..<factors.count {
var factor = factors[i]
let size = max(MemoryLayout<Float>.size, 16)
let options: MTLResourceOptions
if #available(iOS 9.0, *) {
options = [.storageModeShared]
} else {
options = [.cpuCacheModeWriteCombined]
}
let buffer = device.device.makeBuffer(
bytes: &factor,
length: size,
options: options
)
#if swift(>=4.0)
commandEncoder.setBuffer(buffer, offset: 0, index: i)
#else
commandEncoder.setBuffer(buffer, offset: 0, at: i)
#endif
}
return super.processMetal(device, commandBuffer, commandEncoder)
}
#endif
override func processNone(_ device: ImageNoneDevice) -> Bool {
let memoryPool = device.memoryPool!
let width = Int(device.drawRect!.width)
let height = Int(device.drawRect!.height)
func monochrome(_ a: Float, _ l: Float, _ d: Float) -> UInt8 {
var ret: UInt8
if l < 128 {
ret = UInt8(2.0 * l * d)
} else {
let l = 255 - l
let d = 1.0 - d
let first = Int32(255.0 - 2.0 * l * d)
ret = UInt8(max(min(first, 255), 0))
}
return UInt8(a * (1.0 - self.threshold) + Float(ret) * self.threshold)
}
var index = 0
for _ in 0..<height {
for _ in 0..<width {
let r = Float(memoryPool[index + 0])
let g = Float(memoryPool[index + 1])
let b = Float(memoryPool[index + 2])
let luminance = min(255.0, r * 0.2125 + g * 0.7154 + b * 0.0721)
memoryPool[index + 0] = monochrome(r, luminance, 0.6)
memoryPool[index + 1] = monochrome(g, luminance, 0.45)
memoryPool[index + 2] = monochrome(b, luminance, 0.3)
index += 4
}
}
return super.processNone(device)
}
}
| 31.039604 | 160 | 0.470813 |
fbdea2b7b0b3dd561f23cd894f8c61614a8bd112 | 3,381 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// HTTPDecoderTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension HTTPDecoderTest {
static var allTests : [(String, (HTTPDecoderTest) -> () throws -> Void)] {
return [
("testDoesNotDecodeRealHTTP09Request", testDoesNotDecodeRealHTTP09Request),
("testDoesNotDecodeFakeHTTP09Request", testDoesNotDecodeFakeHTTP09Request),
("testDoesNotDecodeHTTP2XRequest", testDoesNotDecodeHTTP2XRequest),
("testToleratesHTTP13Request", testToleratesHTTP13Request),
("testDoesNotDecodeRealHTTP09Response", testDoesNotDecodeRealHTTP09Response),
("testDoesNotDecodeFakeHTTP09Response", testDoesNotDecodeFakeHTTP09Response),
("testDoesNotDecodeHTTP2XResponse", testDoesNotDecodeHTTP2XResponse),
("testToleratesHTTP13Response", testToleratesHTTP13Response),
("testCorrectlyMaintainIndicesWhenDiscardReadBytes", testCorrectlyMaintainIndicesWhenDiscardReadBytes),
("testDropExtraBytes", testDropExtraBytes),
("testDontDropExtraBytesRequest", testDontDropExtraBytesRequest),
("testDontDropExtraBytesResponse", testDontDropExtraBytesResponse),
("testExtraCRLF", testExtraCRLF),
("testSOURCEDoesntExplodeUs", testSOURCEDoesntExplodeUs),
("testExtraCarriageReturnBetweenSubsequentRequests", testExtraCarriageReturnBetweenSubsequentRequests),
("testIllegalHeaderNamesCauseError", testIllegalHeaderNamesCauseError),
("testNonASCIIWorksAsHeaderValue", testNonASCIIWorksAsHeaderValue),
("testDoesNotDeliverLeftoversUnnecessarily", testDoesNotDeliverLeftoversUnnecessarily),
("testHTTPResponseWithoutHeaders", testHTTPResponseWithoutHeaders),
("testBasicVerifications", testBasicVerifications),
("testNothingHappensOnEOFForLeftOversInAllLeftOversModes", testNothingHappensOnEOFForLeftOversInAllLeftOversModes),
("testBytesCanBeForwardedWhenHandlerRemoved", testBytesCanBeForwardedWhenHandlerRemoved),
("testBytesCanBeFiredAsErrorWhenHandlerRemoved", testBytesCanBeFiredAsErrorWhenHandlerRemoved),
("testBytesCanBeDroppedWhenHandlerRemoved", testBytesCanBeDroppedWhenHandlerRemoved),
("testAppropriateErrorWhenReceivingUnsolicitedResponse", testAppropriateErrorWhenReceivingUnsolicitedResponse),
("testAppropriateErrorWhenReceivingUnsolicitedResponseDoesNotRecover", testAppropriateErrorWhenReceivingUnsolicitedResponseDoesNotRecover),
("testOneRequestTwoResponses", testOneRequestTwoResponses),
]
}
}
| 56.35 | 155 | 0.697723 |
235522cb54418bb1a6758eb65b81bf3d5b928838 | 4,626 | //
// BookmarksButton.swift
// DuckDuckGo
//
// Copyright © 2019 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Core
protocol GestureToolbarButtonDelegate: NSObjectProtocol {
func singleTapDetected(in sender: GestureToolbarButton)
func longPressDetected(in sender: GestureToolbarButton)
}
class GestureToolbarButton: UIView {
struct Constants {
static let minLongPressDuration = 0.4
static let maxTouchDeviationPoints = 20.0
static let animationDuration = 0.3
}
// UIToolBarButton size would be 29X44 and its imageview size would be 24X24
struct ToolbarButtonConstants {
static let width = 29.0
static let height = 44.0
static let imageWidth = 24.0
static let imageHeight = 24.0
static let pointerViewWidth = 48.0
static let pointerViewHeight = 36.0
}
weak var delegate: GestureToolbarButtonDelegate?
let iconImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: ToolbarButtonConstants.imageWidth, height: ToolbarButtonConstants.imageHeight))
var image: UIImage? {
didSet {
iconImageView.image = image
}
}
let pointerView: UIView = UIView(frame: CGRect(x: 0,
y: 0,
width: ToolbarButtonConstants.pointerViewWidth,
height: ToolbarButtonConstants.pointerViewHeight))
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(pointerView)
addSubview(iconImageView)
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressHandler(_:)))
longPressRecognizer.minimumPressDuration = Constants.minLongPressDuration
longPressRecognizer.allowableMovement = CGFloat(Constants.maxTouchDeviationPoints)
addGestureRecognizer(longPressRecognizer)
if #available(iOS 13.4, *) {
addInteraction(UIPointerInteraction(delegate: self))
}
}
override func layoutSubviews() {
super.layoutSubviews()
let center = CGPoint(x: bounds.midX, y: bounds.midY)
iconImageView.center = center
pointerView.center = center
}
@objc func longPressHandler(_ sender: UIGestureRecognizer) {
if sender.state == .began {
delegate?.longPressDetected(in: self)
}
}
convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: ToolbarButtonConstants.width, height: ToolbarButtonConstants.height))
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
fileprivate func imposePressAnimation() {
UIView.animate(withDuration: Constants.animationDuration) {
self.iconImageView.alpha = 0.2
}
}
fileprivate func imposeReleaseAnimation() {
UIView.animate(withDuration: Constants.animationDuration) {
self.iconImageView.alpha = 1.0
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
imposePressAnimation()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
imposeReleaseAnimation()
delegate?.singleTapDetected(in: self)
imposeReleaseAnimation()
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
imposeReleaseAnimation()
}
}
extension GestureToolbarButton: Themable {
func decorate(with theme: Theme) {
tintColor = theme.barTintColor
}
}
@available(iOS 13.4, *)
extension GestureToolbarButton: UIPointerInteractionDelegate {
func pointerInteraction(_ interaction: UIPointerInteraction, styleFor region: UIPointerRegion) -> UIPointerStyle? {
return .init(effect: .highlight(.init(view: pointerView)))
}
}
| 31.684932 | 148 | 0.649805 |
d58924d742ed34704e500a437365d855638460d2 | 500 | //
// APIClient.swift
// MyProject
//
// Created by AuthorName
// Copyright © 2019 OrganizationName. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class APIClient: NSObject {
func execute(request apiRequest: APIRequest) -> Observable<Data> {
guard let request = apiRequest.request() else {
print("Invalid request")
return Observable.just(Data())
}
return URLSession.shared.rx.data(request: request)
}
}
| 20.833333 | 70 | 0.64 |
640066b2976d4290e338ca554ac888a946ff8835 | 1,187 | //
// ViewController.swift
// tip
//
// Created by Lisa Fabien on 8/2/20.
// Copyright © 2020 Codepath. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var billAmountTextField: UITextField!
@IBOutlet weak var tipPercentageLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func onTap(_ sender: Any) {
view.endEditing(true)
}
@IBAction func calculateTip(_ sender: Any) {
//Get the bill amount
let bill = Double (billAmountTextField.text!) ?? 0
//Calculate the tip and total
let tipPercentages = [0.15, 0.18, 0.2]
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
//Update the tip and total labels
tipPercentageLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
}
| 24.22449 | 72 | 0.603201 |
7ab451685f4e31410f85ed23fe5184a413d726b9 | 194 | import UIKit
class MapViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("MapViewController loaded its view.")
}
}
| 17.636364 | 51 | 0.634021 |
db146213828dee9df7d1559bea0927d12d04e6de | 398 | //
// TipPercentageChoice.swift
// WeSplit
//
// Created by Brian Sipple on 10/9/19.
// Copyright © 2019 CypherPoet. All rights reserved.
//
import Foundation
enum TipPercentageChoice: Int, CaseIterable {
case zero = 0
case five = 5
case ten = 10
case fifteen = 15
case twenty = 20
case twentyFive = 25
var displayText: String { "\(self.rawValue)%" }
}
| 17.304348 | 53 | 0.633166 |
900183b07b3047b2102c1bbbcd287febb34b9de7 | 3,056 | //
// TablerList.swift
//
// Copyright 2022 FlowAllocator LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
// sourcery: AutoInit
/// List-based table
public struct TablerList<Element, Header, Footer, Row, RowBack, RowOver, Results>: View
where Element: Identifiable,
Header: View,
Footer: View,
Row: View,
RowBack: View,
RowOver: View,
Results: RandomAccessCollection,
Results.Element == Element
{
public typealias Config = TablerListConfig<Element>
public typealias Context = TablerContext<Element>
public typealias HeaderContent = (Binding<Context>) -> Header
public typealias FooterContent = (Binding<Context>) -> Footer
public typealias RowContent = (Element) -> Row
public typealias RowBackground = (Element) -> RowBack
public typealias RowOverlay = (Element) -> RowOver
// MARK: Parameters
private let config: Config
private let headerContent: HeaderContent
private let footerContent: FooterContent
private let rowContent: RowContent
private let rowBackground: RowBackground
private let rowOverlay: RowOverlay
private var results: Results
public init(_ config: Config = .init(),
@ViewBuilder header: @escaping HeaderContent,
@ViewBuilder footer: @escaping FooterContent,
@ViewBuilder row: @escaping RowContent,
@ViewBuilder rowBackground: @escaping RowBackground,
@ViewBuilder rowOverlay: @escaping RowOverlay,
results: Results)
{
self.config = config
headerContent = header
footerContent = footer
rowContent = row
self.rowBackground = rowBackground
self.rowOverlay = rowOverlay
self.results = results
_context = State(initialValue: TablerContext(config))
}
// MARK: Locals
@State private var context: Context
// MARK: Views
public var body: some View {
BaseList(context: $context,
header: headerContent,
footer: footerContent) {
ForEach(results.filter(config.filter ?? { _ in true })) { element in
rowContent(element)
.modifier(ListRowMod(config: config,
element: element))
.listRowBackground(rowBackground(element))
.overlay(rowOverlay(element))
}
.onMove(perform: config.onMove)
}
}
}
| 33.955556 | 87 | 0.641688 |
7a998cce04dfe3bf43188d1075bb814946252f24 | 262 | //
// UserInfoLikeObjectCell.swift
// HotChat
//
// Created by 风起兮 on 2020/9/2.
// Copyright © 2020 风起兮. All rights reserved.
//
import UIKit
class UserInfoLikeObjectCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
}
| 15.411765 | 52 | 0.675573 |
29617c887f6afd8f6cfb129f07295dfd645f3bd2 | 7,868 | // SnapshotTestingExTests/TestSupport/TestHelpers.swift
//
// Created by Jason William Staiert on 7/6/21.
//
// Copyright © 2021 by Jason William Staiert. All Rights Reserved.
import CoreGraphics
#if canImport(AppKit)
import AppKit
#endif
#if canImport(UIKit)
import UIKit
#endif
#if os(iOS) || os(tvOS)
extension CGColor {
static var black: CGColor {
get {
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
let colorComponents = UnsafeMutablePointer<CGFloat>.allocate(capacity: 4)
colorComponents[0] = 0.0
colorComponents[1] = 0.0
colorComponents[2] = 0.0
colorComponents[3] = 1.0
return CGColor(colorSpace: colorSpace, components: colorComponents)!
}
}
static var white: CGColor {
get {
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
let colorComponents = UnsafeMutablePointer<CGFloat>.allocate(capacity: 4)
colorComponents[0] = 1.0
colorComponents[1] = 1.0
colorComponents[2] = 1.0
colorComponents[3] = 1.0
return CGColor(colorSpace: colorSpace, components: colorComponents)!
}
}
}
#endif
#if os(macOS) || os(iOS) || os(tvOS)
private let smallDimension = 256
private let largeDimension = 2048
extension CGPath {
static var arrow: CGPath {
let path = CGMutablePath()
path.move(to: CGPoint(x: 0.0 , y: 0.0))
path.addLine(to: CGPoint(x: 255.0, y: 255.0))
path.addLine(to: CGPoint(x: 0.0, y: 256.0))
path.addLine(to: CGPoint(x: 127.5, y: 127.5))
path.addLine(to: CGPoint(x: 127.5, y: 0.0))
path.addLine(to: CGPoint(x: 0.0, y: 0.0))
path.closeSubpath()
return path
}
}
extension CGImage {
/// Creates an approximation of a arrow at a 45º angle with a circle above.
static var _arrow: CGImage {
let space = CGColorSpace(name: CGColorSpace.sRGB)!
let context = CGContext(
data: nil,
width: smallDimension,
height: smallDimension,
bitsPerComponent: 8,
bytesPerRow: smallDimension * 4,
space: space,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)!
context.setFillColor(CGColor.black)
context.fill(CGRect(x: 0,y: 0,width: smallDimension,height: smallDimension))
context.setFillColor(CGColor.white)
context.addPath(CGPath.arrow)
context.drawPath(using: .fill)
return context.makeImage()!
}
static let arrow: CGImage = _arrow
/// Creates an approximation of a arrow at a 45º angle with a circle above
/// with each component values off-by=one when compared to reference image.
static var _arrowOffByOne: CGImage {
let bytesPerRow = smallDimension * 4
let dataCount = smallDimension * bytesPerRow
let data = UnsafeMutablePointer<UInt8>.allocate(capacity: dataCount)
let space = CGColorSpace(name: CGColorSpace.sRGB)!
let context = CGContext(
data: data,
width: smallDimension,
height: smallDimension,
bitsPerComponent: 8,
bytesPerRow: smallDimension * 4,
space: space,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)!
context.setFillColor(CGColor.black)
context.fill(CGRect(x: 0,y: 0,width: smallDimension,height: smallDimension))
context.setFillColor(CGColor.white)
context.addPath(CGPath.arrow)
context.drawPath(using: .fill)
let medianData = UInt8.max / 2
for i in 0..<dataCount {
if data[i] > medianData {
data[i] = data[i] - 1
}
else {
data[i] = data[i] + 1
}
}
return context.makeImage()!
}
static let arrowOffByOne: CGImage = _arrowOffByOne
/// Creates an approximation of a arrow at a 45º angle with a circle above.
static var _largeArrow: CGImage {
let space = CGColorSpace(name: CGColorSpace.sRGB)!
let context = CGContext(
data: nil,
width: largeDimension,
height: largeDimension,
bitsPerComponent: 8,
bytesPerRow: largeDimension * 4,
space: space,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)!
context.setFillColor(CGColor.black)
context.fill(CGRect(x: 0,y: 0,width: largeDimension,height: largeDimension))
context.setFillColor(CGColor.white)
context.addPath(CGPath.arrow)
context.drawPath(using: .fill)
return context.makeImage()!
}
static let largeArrow: CGImage = _largeArrow
/// Creates an approximation of a arrow at a 45º angle with a circle above
/// with each component values off-by=one when compared to reference image.
static var _largeArrowOffByOne: CGImage {
let bytesPerRow = largeDimension * 4
let dataCount = largeDimension * bytesPerRow
let data = UnsafeMutablePointer<UInt8>.allocate(capacity: dataCount)
let space = CGColorSpace(name: CGColorSpace.sRGB)!
let context = CGContext(
data: data,
width: largeDimension,
height: largeDimension,
bitsPerComponent: 8,
bytesPerRow: largeDimension * 4,
space: space,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)!
context.setFillColor(CGColor.black)
context.fill(CGRect(x: 0,y: 0,width: largeDimension,height: largeDimension))
context.setFillColor(CGColor.white)
context.addPath(CGPath.arrow)
context.drawPath(using: .fill)
let medianData = UInt8.max / 2
for i in 0..<dataCount {
if data[i] > medianData {
data[i] = data[i] - 1
}
else {
data[i] = data[i] + 1
}
}
return context.makeImage()!
}
static let largeArrowOffByOne: CGImage = _largeArrowOffByOne
}
#endif
#if os(macOS)
extension NSImage {
/// Creates an approximation of a arrow at a 45º angle with a circle above.
static var _arrow: NSImage {
return NSImage(cgImage: CGImage.arrow, size: NSZeroSize)
}
static let arrow: NSImage = _arrow
/// Creates an approximation of a arrow at a 45º angle with a circle above
/// with each component values off-by-one when compared to reference image.
static var _arrowOffByOne: NSImage {
return NSImage(cgImage: CGImage.arrowOffByOne, size: NSZeroSize)
}
static let arrowOffByOne: NSImage = _arrowOffByOne
/// Creates an approximation of a arrow at a 45º angle with a circle above.
static var _largeArrow: NSImage {
return NSImage(cgImage: CGImage.largeArrow, size: NSZeroSize)
}
static let largeArrow: NSImage = _largeArrow
/// Creates an approximation of a arrow at a 45º angle with a circle above
/// with each component values off-by-one when compared to reference image.
static var _largeArrowOffByOne: NSImage {
return NSImage(cgImage: CGImage.largeArrowOffByOne, size: NSZeroSize)
}
static let largeArrowOffByOne: NSImage = _largeArrowOffByOne
}
#endif
#if os(iOS) || os(tvOS)
extension UIImage {
/// Creates an approximation of a arrow at a 45º angle with a circle above.
static var arrow: UIImage {
return UIImage(cgImage: CGImage.arrow)
}
/// Creates an approximation of a arrow at a 45º angle with a circle above
/// with each component values off-by-one when compared to reference image.
static var arrowOffByOne: UIImage {
return UIImage(cgImage: CGImage.arrowOffByOne)
}
/// Creates an approximation of a arrow at a 45º angle with a circle above.
static var largeArrow: UIImage {
return UIImage(cgImage: CGImage.largeArrow)
}
/// Creates an approximation of a arrow at a 45º angle with a circle above
/// with each component values off-by-one when compared to reference image.
static var largeArrowOffByOne: UIImage {
return UIImage(cgImage: CGImage.largeArrowOffByOne)
}
}
#endif
| 29.358209 | 80 | 0.668277 |
f901e25ef1089272323aaef0ab715a67db3c029f | 869 | //
// SearchViewModel.swift
// instagramClone
//
// Created by Sinan Özman on 20.01.2021.
//
import Foundation
import SwiftUI
import Combine
final class SearchViewModel: ObservableObject {
@Published var searchCategories: [SearchCategoryModel]? {
willSet {
objectWillChange.send()
}
}
@Published var search: [String] = [] {
willSet {
objectWillChange.send()
}
}
init() {
fetchCategories()
fetchSearch()
}
public func fetchCategories() {
searchCategories = SearchCategoryModel.getSearchCategories()
}
public func fetchSearch() {
search.removeAll()
WebService().getSearch { (response) in
response.forEach { (data) in
self.search.append(data.image ?? "")
}
}
}
}
| 20.209302 | 68 | 0.565017 |
d79babf55c77bb505efe9c7a6d5566ebf4c0597e | 4,627 | //
// FileWriter.swift
// ScoreBoard
//
// Created by Василий Петухов on 10.07.2020.
// Copyright © 2020 Vasily Petuhov. All rights reserved.
//
import Foundation
final class FileWriter {
enum FilesList {
case timer, homeName, awayName, period, homeGoal, awayGoal
}
private let scoreboardData = ScoreBoardData.shared
private let alertWindow = AlertWindow()
func writeToDisk(for files: FilesList...) {
do {
if var userDirectoryUrl = restoreBookmarksPathDirectory() {
userDirectoryUrl = userDirectoryUrl.appendingPathComponent("ScoreBoard Outputs")
// проверка - существование каталога на диске
if !FileManager().fileExists(atPath: userDirectoryUrl.path) {
try FileManager.default.createDirectory(at: userDirectoryUrl, withIntermediateDirectories: true, attributes: nil)
}
var text: String
var fileName: String
for file in files {
switch file {
case .timer:
text = scoreboardData.timerString
fileName = "Timer.txt"
case .homeName:
text = scoreboardData.homeName
fileName = "Home_Name.txt"
case .awayName:
text = scoreboardData.awayName
fileName = "Away_Name.txt"
case .period:
text = scoreboardData.getPeriodCountString()
fileName = "Period.txt"
case .homeGoal:
text = scoreboardData.getCountGoalsString(for: .home)
fileName = "Home_Goal.txt"
case .awayGoal:
text = scoreboardData.getCountGoalsString(for: .away)
fileName = "Away_Goal.txt"
}
try text.write(
to: userDirectoryUrl.appendingPathComponent(fileName),
atomically: false,
encoding: .utf8
)
}
}
} catch {
alertWindow.showAccessToDiskAlert()
}
}
// сохранить закладку
func saveBookmarksPathDirectory(_ userDirectoryUrl:URL) {
// добавить название папки к пути выбранному пользователем
//pathDirectory.url = userDirectoryUrl.appendingPathComponent("ScoreBoard Outputs")
//guard let userDirectoryUrl = pathDirectory.url else { return }
// сохраняем закладку безопасности на будущее
do {
let bookmark = try userDirectoryUrl.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
UserDefaults.standard.set(bookmark, forKey: "bookmarkForDirecory")
// print("закладка сохранилась успешно: \(userDirectoryUrl)")
} catch {
let title = "saveBookmarksPathDirectory"
let message = "Dont saved BookmarksPathDirectory"
// передавать текст ошибки и рекомендации
alertWindow.showAlert(title: title, message: message)
}
}
// восстановить закладку
func restoreBookmarksPathDirectory() -> URL? {
guard let bookmark = UserDefaults.standard.data(forKey: "bookmarkForDirecory") else {
return FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first // каталог downloads по умолчанию
}
var bookmarkDataIsStale: ObjCBool = false
do {
let userDirectoryUrl = try (NSURL(resolvingBookmarkData: bookmark, options: [.withoutUI, .withSecurityScope], relativeTo: nil, bookmarkDataIsStale: &bookmarkDataIsStale) as URL)
if bookmarkDataIsStale.boolValue { return nil }
guard userDirectoryUrl.startAccessingSecurityScopedResource() else { return nil }
// print("закладка открыта успешно: \(userDirectoryUrl)")
return userDirectoryUrl
} catch {
let title = "restoreBookmarksPathDirectory"
let message = "Dont load BookmarksPathDirectory"
// передавать текст ошибки и рекомендации
alertWindow.showAlert(title: title, message: message)
return nil
}
}
}
| 38.239669 | 189 | 0.556084 |
7508e39518d0abc8db30171ac66664d6e5abf1a4 | 2,723 | //
// SceneDelegate.swift
// P18K LayoutAndGeometry
//
// Created by Julian Moorhouse on 13/05/2021.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.546875 | 147 | 0.706941 |
d655f2a6ace3ac729dc7decd6407747a9c1df23a | 20,519 | //
// MedicationRequest.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/MedicationRequest) on 2019-03-01.
// 2019, SMART Health IT.
//
import Foundation
/**
Ordering of medication for patient or group.
An order or request for both supply of the medication and the instructions for administration of the medication to a
patient. The resource is called "MedicationRequest" rather than "MedicationPrescription" or "MedicationOrder" to
generalize the use across inpatient and outpatient settings, including care plans, etc., and to harmonize with workflow
patterns.
*/
open class MedicationRequest: DomainResource {
override open class var resourceType: String {
get { return "MedicationRequest" }
}
/// When request was initially authored.
public var authoredOn: DateTime?
/// What request fulfills.
public var basedOn: [Reference]?
/// Type of medication usage.
public var category: [CodeableConcept]?
/// Overall pattern of medication administration.
public var courseOfTherapyType: CodeableConcept?
/// Clinical Issue with action.
public var detectedIssue: [Reference]?
/// Medication supply authorization.
public var dispenseRequest: MedicationRequestDispenseRequest?
/// True if request is prohibiting action.
public var doNotPerform: FHIRBool?
/// How the medication should be taken.
public var dosageInstruction: [Dosage]?
/// Encounter created as part of encounter/admission/stay.
public var encounter: Reference?
/// A list of events of interest in the lifecycle.
public var eventHistory: [Reference]?
/// Composite request this is part of.
public var groupIdentifier: Identifier?
/// External ids for this request.
public var identifier: [Identifier]?
/// Instantiates FHIR protocol or definition.
public var instantiatesCanonical: [FHIRURL]?
/// Instantiates external protocol or definition.
public var instantiatesUri: [FHIRURL]?
/// Associated insurance coverage.
public var insurance: [Reference]?
/// Whether the request is a proposal, plan, or an original order.
public var intent: MedicationRequestIntent?
/// Medication to be taken.
public var medicationCodeableConcept: CodeableConcept?
/// Medication to be taken.
public var medicationReference: Reference?
/// Information about the prescription.
public var note: [Annotation]?
/// Intended performer of administration.
public var performer: Reference?
/// Desired kind of performer of the medication administration.
public var performerType: CodeableConcept?
/// An order/prescription that is being replaced.
public var priorPrescription: Reference?
/// Indicates how quickly the Medication Request should be addressed with respect to other requests.
public var priority: RequestPriority?
/// Reason or indication for ordering or not ordering the medication.
public var reasonCode: [CodeableConcept]?
/// Condition or observation that supports why the prescription is being written.
public var reasonReference: [Reference]?
/// Person who entered the request.
public var recorder: Reference?
/// Reported rather than primary record.
public var reportedBoolean: FHIRBool?
/// Reported rather than primary record.
public var reportedReference: Reference?
/// Who/What requested the Request.
public var requester: Reference?
/// A code specifying the current state of the order. Generally, this will be active or completed state.
public var status: MedicationrequestStatus?
/// Reason for current status.
public var statusReason: CodeableConcept?
/// Who or group medication request is for.
public var subject: Reference?
/// Any restrictions on medication substitution.
public var substitution: MedicationRequestSubstitution?
/// Information to support ordering of the medication.
public var supportingInformation: [Reference]?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(intent: MedicationRequestIntent, medication: Any, status: MedicationrequestStatus, subject: Reference) {
self.init()
self.intent = intent
if let value = medication as? CodeableConcept {
self.medicationCodeableConcept = value
}
else if let value = medication as? Reference {
self.medicationReference = value
}
else {
fhir_warn("Type “\(Swift.type(of: medication))” for property “\(medication)” is invalid, ignoring")
}
self.status = status
self.subject = subject
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
authoredOn = createInstance(type: DateTime.self, for: "authoredOn", in: json, context: &instCtx, owner: self) ?? authoredOn
basedOn = createInstances(of: Reference.self, for: "basedOn", in: json, context: &instCtx, owner: self) ?? basedOn
category = createInstances(of: CodeableConcept.self, for: "category", in: json, context: &instCtx, owner: self) ?? category
courseOfTherapyType = createInstance(type: CodeableConcept.self, for: "courseOfTherapyType", in: json, context: &instCtx, owner: self) ?? courseOfTherapyType
detectedIssue = createInstances(of: Reference.self, for: "detectedIssue", in: json, context: &instCtx, owner: self) ?? detectedIssue
dispenseRequest = createInstance(type: MedicationRequestDispenseRequest.self, for: "dispenseRequest", in: json, context: &instCtx, owner: self) ?? dispenseRequest
doNotPerform = createInstance(type: FHIRBool.self, for: "doNotPerform", in: json, context: &instCtx, owner: self) ?? doNotPerform
dosageInstruction = createInstances(of: Dosage.self, for: "dosageInstruction", in: json, context: &instCtx, owner: self) ?? dosageInstruction
encounter = createInstance(type: Reference.self, for: "encounter", in: json, context: &instCtx, owner: self) ?? encounter
eventHistory = createInstances(of: Reference.self, for: "eventHistory", in: json, context: &instCtx, owner: self) ?? eventHistory
groupIdentifier = createInstance(type: Identifier.self, for: "groupIdentifier", in: json, context: &instCtx, owner: self) ?? groupIdentifier
identifier = createInstances(of: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier
instantiatesCanonical = createInstances(of: FHIRURL.self, for: "instantiatesCanonical", in: json, context: &instCtx, owner: self) ?? instantiatesCanonical
instantiatesUri = createInstances(of: FHIRURL.self, for: "instantiatesUri", in: json, context: &instCtx, owner: self) ?? instantiatesUri
insurance = createInstances(of: Reference.self, for: "insurance", in: json, context: &instCtx, owner: self) ?? insurance
intent = createEnum(type: MedicationRequestIntent.self, for: "intent", in: json, context: &instCtx) ?? intent
if nil == intent && !instCtx.containsKey("intent") {
instCtx.addError(FHIRValidationError(missing: "intent"))
}
medicationCodeableConcept = createInstance(type: CodeableConcept.self, for: "medicationCodeableConcept", in: json, context: &instCtx, owner: self) ?? medicationCodeableConcept
medicationReference = createInstance(type: Reference.self, for: "medicationReference", in: json, context: &instCtx, owner: self) ?? medicationReference
note = createInstances(of: Annotation.self, for: "note", in: json, context: &instCtx, owner: self) ?? note
performer = createInstance(type: Reference.self, for: "performer", in: json, context: &instCtx, owner: self) ?? performer
performerType = createInstance(type: CodeableConcept.self, for: "performerType", in: json, context: &instCtx, owner: self) ?? performerType
priorPrescription = createInstance(type: Reference.self, for: "priorPrescription", in: json, context: &instCtx, owner: self) ?? priorPrescription
priority = createEnum(type: RequestPriority.self, for: "priority", in: json, context: &instCtx) ?? priority
reasonCode = createInstances(of: CodeableConcept.self, for: "reasonCode", in: json, context: &instCtx, owner: self) ?? reasonCode
reasonReference = createInstances(of: Reference.self, for: "reasonReference", in: json, context: &instCtx, owner: self) ?? reasonReference
recorder = createInstance(type: Reference.self, for: "recorder", in: json, context: &instCtx, owner: self) ?? recorder
reportedBoolean = createInstance(type: FHIRBool.self, for: "reportedBoolean", in: json, context: &instCtx, owner: self) ?? reportedBoolean
reportedReference = createInstance(type: Reference.self, for: "reportedReference", in: json, context: &instCtx, owner: self) ?? reportedReference
requester = createInstance(type: Reference.self, for: "requester", in: json, context: &instCtx, owner: self) ?? requester
status = createEnum(type: MedicationrequestStatus.self, for: "status", in: json, context: &instCtx) ?? status
if nil == status && !instCtx.containsKey("status") {
instCtx.addError(FHIRValidationError(missing: "status"))
}
statusReason = createInstance(type: CodeableConcept.self, for: "statusReason", in: json, context: &instCtx, owner: self) ?? statusReason
subject = createInstance(type: Reference.self, for: "subject", in: json, context: &instCtx, owner: self) ?? subject
if nil == subject && !instCtx.containsKey("subject") {
instCtx.addError(FHIRValidationError(missing: "subject"))
}
substitution = createInstance(type: MedicationRequestSubstitution.self, for: "substitution", in: json, context: &instCtx, owner: self) ?? substitution
supportingInformation = createInstances(of: Reference.self, for: "supportingInformation", in: json, context: &instCtx, owner: self) ?? supportingInformation
// check if nonoptional expanded properties (i.e. at least one "answer" for "answer[x]") are present
if nil == self.medicationCodeableConcept && nil == self.medicationReference {
instCtx.addError(FHIRValidationError(missing: "medication[x]"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.authoredOn?.decorate(json: &json, withKey: "authoredOn", errors: &errors)
arrayDecorate(json: &json, withKey: "basedOn", using: self.basedOn, errors: &errors)
arrayDecorate(json: &json, withKey: "category", using: self.category, errors: &errors)
self.courseOfTherapyType?.decorate(json: &json, withKey: "courseOfTherapyType", errors: &errors)
arrayDecorate(json: &json, withKey: "detectedIssue", using: self.detectedIssue, errors: &errors)
self.dispenseRequest?.decorate(json: &json, withKey: "dispenseRequest", errors: &errors)
self.doNotPerform?.decorate(json: &json, withKey: "doNotPerform", errors: &errors)
arrayDecorate(json: &json, withKey: "dosageInstruction", using: self.dosageInstruction, errors: &errors)
self.encounter?.decorate(json: &json, withKey: "encounter", errors: &errors)
arrayDecorate(json: &json, withKey: "eventHistory", using: self.eventHistory, errors: &errors)
self.groupIdentifier?.decorate(json: &json, withKey: "groupIdentifier", errors: &errors)
arrayDecorate(json: &json, withKey: "identifier", using: self.identifier, errors: &errors)
arrayDecorate(json: &json, withKey: "instantiatesCanonical", using: self.instantiatesCanonical, errors: &errors)
arrayDecorate(json: &json, withKey: "instantiatesUri", using: self.instantiatesUri, errors: &errors)
arrayDecorate(json: &json, withKey: "insurance", using: self.insurance, errors: &errors)
self.intent?.decorate(json: &json, withKey: "intent", errors: &errors)
if nil == self.intent {
errors.append(FHIRValidationError(missing: "intent"))
}
self.medicationCodeableConcept?.decorate(json: &json, withKey: "medicationCodeableConcept", errors: &errors)
self.medicationReference?.decorate(json: &json, withKey: "medicationReference", errors: &errors)
arrayDecorate(json: &json, withKey: "note", using: self.note, errors: &errors)
self.performer?.decorate(json: &json, withKey: "performer", errors: &errors)
self.performerType?.decorate(json: &json, withKey: "performerType", errors: &errors)
self.priorPrescription?.decorate(json: &json, withKey: "priorPrescription", errors: &errors)
self.priority?.decorate(json: &json, withKey: "priority", errors: &errors)
arrayDecorate(json: &json, withKey: "reasonCode", using: self.reasonCode, errors: &errors)
arrayDecorate(json: &json, withKey: "reasonReference", using: self.reasonReference, errors: &errors)
self.recorder?.decorate(json: &json, withKey: "recorder", errors: &errors)
self.reportedBoolean?.decorate(json: &json, withKey: "reportedBoolean", errors: &errors)
self.reportedReference?.decorate(json: &json, withKey: "reportedReference", errors: &errors)
self.requester?.decorate(json: &json, withKey: "requester", errors: &errors)
self.status?.decorate(json: &json, withKey: "status", errors: &errors)
if nil == self.status {
errors.append(FHIRValidationError(missing: "status"))
}
self.statusReason?.decorate(json: &json, withKey: "statusReason", errors: &errors)
self.subject?.decorate(json: &json, withKey: "subject", errors: &errors)
if nil == self.subject {
errors.append(FHIRValidationError(missing: "subject"))
}
self.substitution?.decorate(json: &json, withKey: "substitution", errors: &errors)
arrayDecorate(json: &json, withKey: "supportingInformation", using: self.supportingInformation, errors: &errors)
// check if nonoptional expanded properties (i.e. at least one "value" for "value[x]") are present
if nil == self.medicationCodeableConcept && nil == self.medicationReference {
errors.append(FHIRValidationError(missing: "medication[x]"))
}
}
}
/**
Medication supply authorization.
Indicates the specific details for the dispense or medication supply part of a medication request (also known as a
Medication Prescription or Medication Order). Note that this information is not always sent with the order. There may
be in some settings (e.g. hospitals) institutional or system support for completing the dispense details in the pharmacy
department.
*/
open class MedicationRequestDispenseRequest: BackboneElement {
override open class var resourceType: String {
get { return "MedicationRequestDispenseRequest" }
}
/// Minimum period of time between dispenses.
public var dispenseInterval: Duration?
/// Number of days supply per dispense.
public var expectedSupplyDuration: Duration?
/// First fill details.
public var initialFill: MedicationRequestDispenseRequestInitialFill?
/// Number of refills authorized.
public var numberOfRepeatsAllowed: FHIRInteger?
/// Intended dispenser.
public var performer: Reference?
/// Amount of medication to supply per dispense.
public var quantity: Quantity?
/// Time period supply is authorized for.
public var validityPeriod: Period?
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
dispenseInterval = createInstance(type: Duration.self, for: "dispenseInterval", in: json, context: &instCtx, owner: self) ?? dispenseInterval
expectedSupplyDuration = createInstance(type: Duration.self, for: "expectedSupplyDuration", in: json, context: &instCtx, owner: self) ?? expectedSupplyDuration
initialFill = createInstance(type: MedicationRequestDispenseRequestInitialFill.self, for: "initialFill", in: json, context: &instCtx, owner: self) ?? initialFill
numberOfRepeatsAllowed = createInstance(type: FHIRInteger.self, for: "numberOfRepeatsAllowed", in: json, context: &instCtx, owner: self) ?? numberOfRepeatsAllowed
performer = createInstance(type: Reference.self, for: "performer", in: json, context: &instCtx, owner: self) ?? performer
quantity = createInstance(type: Quantity.self, for: "quantity", in: json, context: &instCtx, owner: self) ?? quantity
validityPeriod = createInstance(type: Period.self, for: "validityPeriod", in: json, context: &instCtx, owner: self) ?? validityPeriod
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.dispenseInterval?.decorate(json: &json, withKey: "dispenseInterval", errors: &errors)
self.expectedSupplyDuration?.decorate(json: &json, withKey: "expectedSupplyDuration", errors: &errors)
self.initialFill?.decorate(json: &json, withKey: "initialFill", errors: &errors)
self.numberOfRepeatsAllowed?.decorate(json: &json, withKey: "numberOfRepeatsAllowed", errors: &errors)
self.performer?.decorate(json: &json, withKey: "performer", errors: &errors)
self.quantity?.decorate(json: &json, withKey: "quantity", errors: &errors)
self.validityPeriod?.decorate(json: &json, withKey: "validityPeriod", errors: &errors)
}
}
/**
First fill details.
Indicates the quantity or duration for the first dispense of the medication.
*/
open class MedicationRequestDispenseRequestInitialFill: BackboneElement {
override open class var resourceType: String {
get { return "MedicationRequestDispenseRequestInitialFill" }
}
/// First fill duration.
public var duration: Duration?
/// First fill quantity.
public var quantity: Quantity?
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
duration = createInstance(type: Duration.self, for: "duration", in: json, context: &instCtx, owner: self) ?? duration
quantity = createInstance(type: Quantity.self, for: "quantity", in: json, context: &instCtx, owner: self) ?? quantity
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.duration?.decorate(json: &json, withKey: "duration", errors: &errors)
self.quantity?.decorate(json: &json, withKey: "quantity", errors: &errors)
}
}
/**
Any restrictions on medication substitution.
Indicates whether or not substitution can or should be part of the dispense. In some cases, substitution must happen, in
other cases substitution must not happen. This block explains the prescriber's intent. If nothing is specified
substitution may be done.
*/
open class MedicationRequestSubstitution: BackboneElement {
override open class var resourceType: String {
get { return "MedicationRequestSubstitution" }
}
/// Whether substitution is allowed or not.
public var allowedBoolean: FHIRBool?
/// Whether substitution is allowed or not.
public var allowedCodeableConcept: CodeableConcept?
/// Why should (not) substitution be made.
public var reason: CodeableConcept?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(allowed: Any) {
self.init()
if let value = allowed as? FHIRBool {
self.allowedBoolean = value
}
else if let value = allowed as? CodeableConcept {
self.allowedCodeableConcept = value
}
else {
fhir_warn("Type “\(Swift.type(of: allowed))” for property “\(allowed)” is invalid, ignoring")
}
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
allowedBoolean = createInstance(type: FHIRBool.self, for: "allowedBoolean", in: json, context: &instCtx, owner: self) ?? allowedBoolean
allowedCodeableConcept = createInstance(type: CodeableConcept.self, for: "allowedCodeableConcept", in: json, context: &instCtx, owner: self) ?? allowedCodeableConcept
reason = createInstance(type: CodeableConcept.self, for: "reason", in: json, context: &instCtx, owner: self) ?? reason
// check if nonoptional expanded properties (i.e. at least one "answer" for "answer[x]") are present
if nil == self.allowedBoolean && nil == self.allowedCodeableConcept {
instCtx.addError(FHIRValidationError(missing: "allowed[x]"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.allowedBoolean?.decorate(json: &json, withKey: "allowedBoolean", errors: &errors)
self.allowedCodeableConcept?.decorate(json: &json, withKey: "allowedCodeableConcept", errors: &errors)
self.reason?.decorate(json: &json, withKey: "reason", errors: &errors)
// check if nonoptional expanded properties (i.e. at least one "value" for "value[x]") are present
if nil == self.allowedBoolean && nil == self.allowedCodeableConcept {
errors.append(FHIRValidationError(missing: "allowed[x]"))
}
}
}
| 49.562802 | 177 | 0.749598 |
335ae47e2f800dc8c0371d79ed09b6176bc705a1 | 2,538 | //: [Previous](@previous)
import UIKit
import PlaygroundSupport
class View: UIView {
let label: UILabel
override init(frame: CGRect) {
label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 20)
label.text = "Do something"
label.numberOfLines = 0
label.textAlignment = .center
super.init(frame: frame)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap(sender:))))
let leftSwipeRecogniser = UISwipeGestureRecognizer(target: self, action: #selector(swipe(sender:)))
leftSwipeRecogniser.direction = UISwipeGestureRecognizerDirection.left
addGestureRecognizer(leftSwipeRecogniser)
let rightSwipeRecogniser = UISwipeGestureRecognizer(target: self, action: #selector(swipe(sender:)))
rightSwipeRecogniser.direction = UISwipeGestureRecognizerDirection.right
addGestureRecognizer(rightSwipeRecogniser)
let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan(sender:)))
panRecognizer.require(toFail: leftSwipeRecogniser)
panRecognizer.require(toFail: rightSwipeRecogniser)
addGestureRecognizer(panRecognizer)
backgroundColor = UIColor.white
addSubview(label)
label.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func tap(sender: UITapGestureRecognizer) {
label.text = "tap"
}
func swipe(sender: UISwipeGestureRecognizer) {
let directionString: String
switch sender.direction {
case UISwipeGestureRecognizerDirection.left:
directionString = "left"
case UISwipeGestureRecognizerDirection.up:
directionString = "up"
case UISwipeGestureRecognizerDirection.right:
directionString = "right"
case UISwipeGestureRecognizerDirection.down:
directionString = "down"
default:
directionString = "w00t?"
}
label.text = "swipe \(directionString)"
}
func pan(sender: UIPanGestureRecognizer) {
label.text = "pan with velocity:\nx: \(sender.velocity(in: self).x)\ny: \(sender.velocity(in: self).y)"
}
}
let view = View(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
PlaygroundPage.current.liveView = view
//: [Next](@next)
| 30.95122 | 107 | 0.722616 |
489031f392f502d2532f9d3a2aefca0406087168 | 852 | //
// ModifierFlagsTests.swift
// HotKey
//
// Created by Sam Soffes on 7/21/17.
// Copyright © 2017 Sam Soffes. All rights reserved.
//
import XCTest
import AppKit
import Carbon
import HotKey
final class ModiferFlagsTests: XCTestCase {
func testCarbonToCocoaConversion() {
var cocoa = NSEvent.ModifierFlags()
cocoa.insert(.command)
XCTAssertEqual(NSEvent.ModifierFlags(carbonFlags: UInt32(cmdKey)), cocoa)
cocoa.insert(.control)
cocoa.insert(.option)
XCTAssertEqual(NSEvent.ModifierFlags(carbonFlags: UInt32(cmdKey|controlKey|optionKey)), cocoa)
}
func testCocoaToCarbonConversion() {
var cocoa = NSEvent.ModifierFlags()
cocoa.insert(.command)
XCTAssertEqual(UInt32(cmdKey), cocoa.carbonFlags)
cocoa.insert(.control)
cocoa.insert(.option)
XCTAssertEqual(UInt32(cmdKey|controlKey|optionKey), cocoa.carbonFlags)
}
}
| 24.342857 | 96 | 0.760563 |
16bb4ecbf6e191fadfa475e4d8a6174d11263811 | 1,535 | //
// Constant.swift
// MyWallpaper
//
// Created by Linsw on 16/3/11.
// Copyright © 2016年 Linsw. All rights reserved.
//
import Foundation
import UIKit
//修改域名后,如果不能加载图片,可能是因为Apple Transport Security,在info.plist里添加白名单即可
let tieTuKuOpenkey = "/key/a5rMlZpnZG6VnpNllmaUkpJon2NrlZVsmGdplGOXamxpmczKm2KVbMObmGSWYpY="
let tieTuKuURL = "http://api.tietuku.cn/v2/api"
let urlGetAlbum = tieTuKuURL + "/getalbum" + tieTuKuOpenkey
let urlGetPicList = tieTuKuURL + "/getpiclist" + tieTuKuOpenkey
//let urlGetRandomRecommandedPhotos = tieTuKuURL + "/getrandrec" + tieTuKuOpenkey
let windowBounds = UIScreen.mainScreen().bounds
struct Theme {
let splitViewBackgroundColor : UIColor
let masterViewBackgroundColor: UIColor
let detailViewBackgroundColor: UIColor
let textColor : UIColor
let lineColor : UIColor
}
let themeBlack = Theme(
splitViewBackgroundColor : UIColor.blackColor(),
masterViewBackgroundColor: UIColor.blackColor(),
detailViewBackgroundColor: UIColor.blackColor(),
textColor : UIColor.whiteColor(),
lineColor : UIColor(white: 0.1, alpha: 1)
)
class Picture {
let name :String
let url :String
let size :CGSize
init(name:String,url:String,size:CGSize){
self.name = name
self.url = url
self.size = size
}
}
class Album {
let name,url,id : String
init(name:String, url:String, id:String){
self.name = name
self.url = url
self.id = id
}
}
| 27.909091 | 92 | 0.678176 |
2129d767f4ae879328302a90866b76e447f2c1e7 | 3,161 | //
// LinkedBuffer.swift
//
// Created by k1x
//
import Foundation
public class LinkedBuffer : WriteExtensions, Reader {
typealias SubbuffersList = LinkedList<LinkedBufferNode>
public struct LinkedBufferNode {
public var data : [Int8]
public var read : Int = 0
public var written : Int = 0
init(capacity : Int) {
data = [Int8](repeating: 0, count: capacity)
}
var leftBytes : Int {
return data.count - written
}
var readLeft : Int {
return written - read
}
}
var subBuffers = SubbuffersList()
var bufferSize : Int
public init(bufferSize : Int) {
self.bufferSize = bufferSize
subBuffers.push(LinkedBufferNode(capacity: bufferSize))
}
public func pop() -> LinkedBufferNode? {
return subBuffers.popFirst()
}
public var headSubbuffer : LinkedList<LinkedBufferNode>.Node? {
return subBuffers.firstNode
}
public func removeSubbufer(subbufer: LinkedList<LinkedBufferNode>.Node) {
subBuffers.remove(node: subbufer)
}
public func read(buffer: UnsafeMutableRawPointer, count: Int) throws -> SocketReadResult {
var node = subBuffers.firstNode
var position = 0
@_transparent func bytesLeft() -> Int {
return count - position
}
while let unode = node, bytesLeft() > 0 {
let bytesToRead = min(bytesLeft(), unode.value.readLeft)
let alreadyRead = unode.value.read
unode.value.data.withUnsafeBytes { src -> Void in
memcpy(buffer.advanced(by: position), src.baseAddress!.advanced(by: alreadyRead), bytesToRead)
}
position += bytesToRead
unode.value.read += bytesToRead
if unode.value.readLeft <= 0 {
node = unode.next
subBuffers.remove(node: unode)
}
}
return SocketReadResult(position, options: subBuffers.firstNode != nil ? [] : .endOfStream)
}
public func write(buffer: UnsafeRawPointer, count: Int) throws -> Int {
guard var node = subBuffers.lastNode else {
throw "Unknown error. No node.".error()
}
var position = 0
@_transparent func bytesLeft() -> Int {
return count - position
}
while bytesLeft() > 0 {
guard node.value.leftBytes > 0 else {
let newNode = SubbuffersList.Node(value: LinkedBufferNode(capacity: bufferSize))
subBuffers.push(newNode)
node = newNode
continue
}
let bytesToWrite = min(bytesLeft(), node.value.leftBytes)
let written = node.value.written
node.value.data.withUnsafeMutableBytes { dst -> Void in
memcpy(dst.baseAddress!.advanced(by: written), buffer.advanced(by: position), bytesToWrite)
}
position += bytesToWrite
node.value.written += bytesToWrite
}
return count
}
}
| 31.29703 | 110 | 0.571971 |
f7db13f0f7b6e92baedef6dd5506f08904faff44 | 233 | #if os(watchOS)
import UIKit
internal struct WatchOSIntegration: SentryIntegration {
public func register(hub: Hub, options _: SentryOptions) {
hub.configure(scope: { s in s.tags["os"] = "watchOS" })
}
}
#endif
| 21.181818 | 62 | 0.665236 |
9112799c0e90866ae002228e5832644baac10092 | 246 | //
// Contact.swift
// CrudCoreData
//
// Created by Francisco José A. C. Souza on 24/12/15.
// Copyright © 2015 Francisco José A. C. Souza. All rights reserved.
//
import Foundation
import CoreData
class Contact: NSManagedObject {
}
| 15.375 | 69 | 0.682927 |
14f98ebb6911686839abe433f6992a7efd4d27ce | 284 | // ___FILEHEADER___
import UIKit
class ___FILEBASENAMEASIDENTIFIER___ {
// TODO: Declare view methods
weak var output: ___VARIABLE_productName:identifier___InteractorOutput!
}
extension ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_productName:identifier___UseCase {
}
| 21.846154 | 88 | 0.81338 |
f86015356c349fc16cdd3eebf38dc8efea78557e | 776 | import Foundation
import ProjectDescription
import TSCBasic
import TuistCore
import TuistGraph
import TuistSupport
extension TuistGraph.DefaultSettings {
/// Maps a ProjectDescription.DefaultSettings instance into a TuistCore.DefaultSettings model.
/// - Parameters:
/// - manifest: Manifest representation of default settings.
/// - generatorPaths: Generator paths.
static func from(manifest: ProjectDescription.DefaultSettings) -> TuistGraph.DefaultSettings {
switch manifest {
case let .recommended(excludedKeys):
return .recommended(excluding: excludedKeys)
case let .essential(excludedKeys):
return .essential(excluding: excludedKeys)
case .none:
return .none
}
}
}
| 32.333333 | 98 | 0.703608 |
38ba064bab2d518ec1b147b80c0c85a8c5e5a44f | 350 | //
// CarParkRealtime.swift
// App
//
// Created by Adrian Schönig on 27.04.18.
//
import Foundation
struct CarParkRealtime: Codable {
let realTimeId: String
let isOpen: Bool
let totalSpaces: Int
let availableSpaces: Int
let opens: String
let closes: String
var source: CarPark.DataSource?
var lastUpdated = Date()
}
| 14.583333 | 42 | 0.685714 |
87b3c55d31e87a8ac6012437d9b892eef62af5c1 | 664 | //
// Core+CALayer.swift
// HXPHPicker
//
// Created by Slience on 2021/7/14.
//
import UIKit
extension CALayer {
func convertedToImage(
size: CGSize = .zero,
scale: CGFloat = UIScreen.main.scale
) -> UIImage? {
var toSize: CGSize
if size.equalTo(.zero) {
toSize = frame.size
}else {
toSize = size
}
UIGraphicsBeginImageContextWithOptions(toSize, false, scale)
let context = UIGraphicsGetCurrentContext()
render(in: context!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| 22.896552 | 68 | 0.60241 |
8fe12ad8858a14e919dedfa5c955a8679efca732 | 3,172 | //
// EndPoint.swift
// SwiftNetworkRouting
//
// Created by Daniyar Kurmanbayev on 4/29/21.
//
import Foundation
import Alamofire
/// `EndPoint` protocol is used to create endpoints to use for HTTP requests.
public protocol EndPoint {
/// Base URL for a group of routes.
/// If the server endpoints have one same part you have to specify it in this field.
///
/// Emample: if the target URLs are "https://google.com/api/some/service/" and "https://google.com/api/other/service/", you can use URL(string: "https://google.com/api") as your base URL.
var baseURL: URL {get}
/// The end of the targer url
///
/// Emample: if the target URLs are "https://google.com/api/some/service/, you can use "/some/service/" as path.
var path: String {get}
/// Parameters that will be incuided in request body
var bodyParameters: [String: Any]? {get}
/// Parameters that will be included as query parameters in the URL of the request.
var urlParameters: [String: Any]? {get}
/// The HTTP method of the request
var httpMethod: HttpMethod {get}
/// HTTP headers which are same for group of routes
///
/// Example: Autorization header
var baseHeaders: [String: String]? {get}
/// HTTP headers which are the same for a group of routes.
var additionalHeaders: [String: String]? {get}
/// The type of request's body (JSON, Multipart Form Data)
var contentType: ContentType {get}
}
public extension EndPoint {
func buildHeaders() -> HTTPHeaders {
var headers = [String: String]()
if let baseHeaders = baseHeaders {
headers.merge(baseHeaders, uniquingKeysWith: { $1 })
}
if let additionalHeaders = additionalHeaders {
headers.merge(additionalHeaders, uniquingKeysWith: { $1 })
}
return HTTPHeaders(headers)
}
func buildURL() -> URL? {
guard let parameters = urlParameters else {
return baseURL.appendingPathComponent(path)
}
let queryItems = parameters.map({ URLQueryItem(name: $0.key, value: "\($0.value)") })
var urlComps = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)
urlComps?.queryItems = queryItems
return urlComps?.url
}
func buildMultipartFormData() -> ((MultipartFormData) -> Void) {
return { multipartFormData in
for (key, value) in bodyParameters ?? Parameters() {
if let url = value as? URL {
multipartFormData.append(url, withName: key)
} else if let image = value as? UploadingFile {
multipartFormData.append(image.data, withName: key, fileName: image.fileName, mimeType: image.mimeType)
} else if let data = value as? Data {
multipartFormData.append(data, withName: key)
} else if let data = "\(value)".data(using: String.Encoding.utf8, allowLossyConversion: false) {
multipartFormData.append(data, withName: key)
}
}
}
}
}
| 36.45977 | 191 | 0.619483 |
e9234784126fd2ce10bb9c7a2fafe3f5def57e02 | 3,289 | //
// MediaGroup.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// 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
/// The <media:group> element is a sub-element of <item>. It allows grouping
/// of <media:content> elements that are effectively the same content,
/// yet different representations. For instance: the same song recorded
/// in both the WAV and MP3 format. It's an optional element that must
/// only be used for this purpose.
public class MediaGroup {
/// <media:content> is a sub-element of either <item> or <media:group>.
/// Media objects that are not the same content should not be included
/// in the same <media:group> element. The sequence of these items implies
/// the order of presentation. While many of the attributes appear to be
/// audio/video specific, this element can be used to publish any type of
/// media. It contains 14 attributes, most of which are optional.
public var mediaContents: [MediaContent]?
/// Notable entity and the contribution to the creation of the media object.
/// Current entities can include people, companies, locations, etc. Specific
/// entities can have multiple roles, and several entities can have the same
/// role. These should appear as distinct <media:credit> elements. It has two
/// optional attributes.
public var mediaCredits: [MediaCredit]?
/// Allows a taxonomy to be set that gives an indication of the type of media
/// content, and its particular contents. It has two optional attributes.
public var mediaCategory: MediaCategory?
/// This allows the permissible audience to be declared. If this element is not
/// included, it assumes that no restrictions are necessary. It has one
/// optional attribute.
public var mediaRating: MediaRating?
public init() { }
}
// MARK: - Equatable
extension MediaGroup: Equatable {
public static func ==(lhs: MediaGroup, rhs: MediaGroup) -> Bool {
return
lhs.mediaContents == rhs.mediaContents &&
lhs.mediaCredits == rhs.mediaCredits &&
lhs.mediaCategory == rhs.mediaCategory &&
lhs.mediaRating == rhs.mediaRating
}
}
| 43.853333 | 83 | 0.710246 |
ef6a272be8e923dbe3f731c1d5bc374617c2ca21 | 2,873 | @inline(__always) public func count(_ source: String?) -> Int {
return length(source)
}
@inline(__always) public func count<T>(_ source: [T]?) -> Int {
if let source = source {
return source.count
} else {
return 0
}
}
@inline(__always) public func count<T>(_ source: T[]?) -> Int {
return length(source)
}
@inline(__always) public func count<T>(_ source: ISequence<T>?) -> Int {
if let s = source {
return s.Count()
}
return 0
}
public func split(_ elements: String, isSeparator: (Char) -> Bool, maxSplit: Int = 0, allowEmptySlices: Bool = false) -> [String] {
let result = [String]()
var currentString = ""
func appendCurrent() -> Bool {
if maxSplit > 0 && result.count >= maxSplit {
return false
}
if allowEmptySlices || currentString.length() > 0 {
result.append(currentString)
}
return true
}
for i in 0 ..< elements.length() {
let ch = elements[i]
if isSeparator(ch) {
if !appendCurrent() {
break
}
currentString = ""
} else {
currentString += ch
}
}
if currentString.length() > 0 {
appendCurrent()
}
return result
}
public func split(_ elements: String, separatorString separator: String) -> [String] {
#if JAVA
return [String](arrayLiteral: (elements as! NativeString).split(java.util.regex.Pattern.quote(separator)))
#elseif CLR
return [String](arrayLiteral: (elements as! NativeString).Split([separator], .None))
#elseif ISLAND
return [String](arrayLiteral: (elements as! NativeString).Split(separator))
#elseif COCOA
return [String]((elements as! NativeString).componentsSeparatedByString(separator))
#endif
}
public func split(_ elements: String, separatorChar separator: Char) -> [String] {
#if JAVA
return [String](arrayLiteral: (elements as! NativeString).split(java.util.regex.Pattern.quote(java.lang.String.valueOf(separator))))
#elseif CLR
return [String](arrayLiteral: (elements as! NativeString).Split([separator], .None))
#elseif ISLAND
return [String](arrayLiteral: (elements as! NativeString).Split(separator))
#elseif COCOA
return [String]((elements as! NativeString).componentsSeparatedByString(NSString.stringWithFormat("%c", separator)))
#endif
}
@inline(__always) public func startsWith(_ s: String, `prefix`: String) -> Bool {
return s.hasPrefix(`prefix`)
}
public func sequence<T>(first: T, next: (T) -> T?) -> ISequence<T> {
var nextResult: T? = first
while nextResult != nil {
__yield nextResult?
nextResult = next(nextResult!)
}
}
//75374: Swift Compatibility: Cannot use `inout` in closure
/*public func sequence<T, State>(state: State, next: (inout State) -> T?) -> ISequence<T> {
var nextResult: T?
repeat {
nextResult = next(&state)
if let nextResult = nextResult {
__yield nextResult
}
} while nextResult != nil
}*/ | 27.893204 | 134 | 0.667247 |
ff4ee655fba2d45e73056cbfb602030daeed6c0a | 2,989 | //
// Runner.swift
// MyMetronome
//
// Created by Marc Rummel on 30.10.20.
// Copyright © 2020 Marc Rummel. All rights reserved.
//
import Foundation
import Combine
import AVFoundation
import SwiftUI
protocol Runable: ObservableObject {
var isRunning:Bool {get}
func start() -> ()
func stop() -> ()
}
protocol Tickable: AnyObject {
var countIn: Bool { get }
var measure: Measure { get set }
var instrument: Instrument { get set }
var bpm: Double { get }
var isRunning: Bool { get set }
func fireBar() -> ()
}
extension AVAudioPlayer {
func trigger() -> () {
self.currentTime = 0
self.play()
}
}
class Runner {
var timer: Timer?
weak var delegate: Tickable?
var sound: Sounds = Sounds.tamborine {
didSet {
accentPlayer = try! AVAudioPlayer(contentsOf: sound.accent!)
normalPlayer = try! AVAudioPlayer(contentsOf: sound.normal!)
subdivPlayer = try! AVAudioPlayer(contentsOf: sound.subdiv!)
beepPlayer = try! AVAudioPlayer(contentsOf: sound.beep!)
}
}
var accentPlayer: AVAudioPlayer!
var subdivPlayer: AVAudioPlayer!
var normalPlayer: AVAudioPlayer!
var beepPlayer: AVAudioPlayer!
init() {
defer {
sound = Sounds.wood
}
}
func start() {
self.timer = Timer(timeInterval: 0.004,
target: self, selector: #selector(fire),
userInfo: nil, repeats: true)
RunLoop.current.add(timer!, forMode: .common)
delegate?.isRunning = true
UIApplication.shared.isIdleTimerDisabled = true
}
func stop() {
guard let timer = timer else { return }
timer.invalidate()
delegate?.isRunning = false
delegate?.measure.reset()
UIApplication.shared.isIdleTimerDisabled = false
}
internal func fireSubdiv() {
guard let delegate = delegate else { return }
if delegate.countIn {
beepPlayer.trigger()
return
}
switch delegate.measure.currentAccent {
case .normal:
normalPlayer.trigger()
case .accent:
accentPlayer.trigger()
case .mute:
break
case .subdiv:
normalPlayer.trigger()
case nil:
break
}
}
var lastFire: TimeInterval = Date.timeIntervalSinceReferenceDate
@objc func fire() {
guard let delegate = delegate else { return }
let now = Date.timeIntervalSinceReferenceDate
let difference = now - lastFire
let interval = 60.0 / (delegate.bpm * delegate.measure.subdiv.rawValue)
if difference > interval {
lastFire = now
delegate.measure.tickSubdiv()
if delegate.measure.isAtStartOfBar {
delegate.fireBar()
}
self.fireSubdiv()
}
}
}
| 26.451327 | 79 | 0.577785 |
fe9bcaa68b000dd235a06c096d171b45d8e4231c | 1,845 | //
// SearchRepositoryModel.swift
// iOSEngineerCodeCheck
//
// Created by Mika Urakawa on 2021/12/18.
// Copyright © 2021 YUMEMI Inc. All rights reserved.
//
import Foundation
protocol SearchRepositoryModelInput {
func fetchRepositories(
searchKeyword: String,
completionHandler: @escaping (Result<[GitHubRepository], GitHubClientError>) -> Void
)
func cancel()
func getImage(
imageURL: String,
completionHandler: @escaping(Data?) -> Void
)
}
final class SearchRepositoryModel: SearchRepositoryModelInput {
private var client = GitHubClient()
/// リポジトリ一覧の取得
func fetchRepositories(
searchKeyword: String,
completionHandler: @escaping (Result<[GitHubRepository], GitHubClientError>) -> Void
) {
let request = GitHubAPI.GitHubSearchRepo(keyword: searchKeyword)
client.send(request: request) { result in
switch result {
case let .success(response):
guard let items = response.items else {
completionHandler(.failure(.noData))
return
}
completionHandler(.success(items))
case let .failure(error):
completionHandler(.failure(error))
}
}
}
/// 取得処理のキャンセル
func cancel() {
client.cancel()
}
/// 画像取得
func getImage(
imageURL: String,
completionHandler: @escaping(Data?) -> Void
) {
guard let url = URL(string: imageURL) else {
return
}
let task = URLSession.shared.dataTask(with: url) { data, _, _ in
guard let data = data else {
completionHandler(nil)
return
}
completionHandler(data)
}
task.resume()
}
}
| 26.357143 | 92 | 0.577236 |
ab6f072dfd2e798f36a1a0bd12c6946841a4c555 | 1,593 | /*
String.ScalarOffset.swift
This source file is part of the SDGSwift open source project.
https://sdggiesbrecht.github.io/SDGSwift
Copyright ©2020–2021 Jeremy David Giesbrecht and the SDGSwift project contributors.
Soli Deo gloria.
Licensed under the Apache Licence, Version 2.0.
See http://www.apache.org/licenses/LICENSE-2.0 for licence information.
*/
import SDGMathematics
extension String {
/// An offset into a String’s scalar view.
///
/// An offset produced by one string is valid in any string instance which contains the same scalars. (The same is not true of a raw string index.)
public struct ScalarOffset: Comparable, OneDimensionalPoint {
// MARK: - Properties
internal var offset: Int
// MARK: - Comparable
public static func < (lhs: String.ScalarOffset, rhs: String.ScalarOffset) -> Bool {
return lhs.offset < rhs.offset
}
// MARK: - OneDimensionalPoint
public typealias Vector = Int
public static func += (precedingValue: inout String.ScalarOffset, followingValue: Vector) {
precedingValue.offset += followingValue
}
public static func − (
precedingValue: String.ScalarOffset,
followingValue: String.ScalarOffset
) -> Int {
precedingValue.offset − followingValue.offset
}
// #workaround(Swift 5.5.1, This is a redundant overload, but it dodges segmentation faults caused by the compiler.)
public static func −= (precedingValue: inout String.ScalarOffset, followingValue: Int) {
precedingValue += -followingValue // @exempt(from: unicode)
}
}
}
| 28.963636 | 149 | 0.711237 |
e2629e515f63b86e536910f076490027f4f413c7 | 992 | // ResultDrivenOperation.swift
// Created by Dmitry Samartcev on 20.11.2020.
import Foundation
#if canImport(UIKit)
/// Asynchronous result-oriented operation
open class ResultDrivenOperation<Success, Failure> : AsynchronousOperation where Failure: Error {
private(set) var result : Result<Success,Failure>? {
didSet {
guard let result = result else { return }
onResult?(result)
}
}
open var onResult: ((_ result: Result<Success,Failure>) -> Void)?
open override func finish() {
fatalError("You should use finish(with:) to ensure a result.")
}
open func finish(with result: Result<Success,Failure>) {
self.result = result
super.finish()
}
open override func cancel() {
fatalError("You should use cancel(with:) to ensure a result.")
}
open func cancel(with error: Failure) {
result = .failure(error)
super.cancel()
}
}
#endif
| 26.105263 | 97 | 0.621976 |
26a9fb5eaeb6047f3f420dfe9a69966e09f5213b | 2,182 | /*
* Copyright (c) 2016-present Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
typealias AnyDict = [String: Any]
class Event {
let repo: String
let name: String
let imageUrl: URL
let action: String
// MARK: - JSON -> Event
init?(dictionary: AnyDict) {
//init를 옵셔널로 선언해 주지 않으면 서버에서 업데이트 하거나 오타 등으로 잘못된 키 이름이 있다면 앱이 중단 된다.
//init?로 작성하면 nil을 반환해 줄 수 있다.
guard let repoDict = dictionary["repo"] as? AnyDict,
let actor = dictionary["actor"] as? AnyDict,
let repoName = repoDict["name"] as? String,
let actorName = actor["display_login"] as? String,
let actorUrlString = actor["avatar_url"] as? String,
let actorUrl = URL(string: actorUrlString),
let actionType = dictionary["type"] as? String
else {
return nil //초기화에 실패하면 nil 반환
}
repo = repoName
name = actorName
imageUrl = actorUrl
action = actionType
}
// MARK: - Event -> JSON
var dictionary: AnyDict {
return [
"repo" : ["name": repo],
"actor": ["display_login": name, "avatar_url": imageUrl.absoluteString],
"type" : action
]
}
}
| 34.634921 | 80 | 0.693859 |
466e6c628bc4675f9834e957940f5f3c2c5aa4fe | 3,129 | //
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Amplify
import Foundation
import AWSPluginsCore
import AWSCore
struct AWSAPIEndpointInterceptors {
// API name
let apiEndpointName: APIEndpointName
let apiAuthProviderFactory: APIAuthProviderFactory
let authService: AWSAuthServiceBehavior?
var interceptors: [URLRequestInterceptor] = []
init(endpointName: APIEndpointName,
apiAuthProviderFactory: APIAuthProviderFactory,
authService: AWSAuthServiceBehavior? = nil) {
self.apiEndpointName = endpointName
self.apiAuthProviderFactory = apiAuthProviderFactory
self.authService = authService
}
/// Registers an interceptor
/// - Parameter interceptor: operation interceptor used to decorate API requests
public mutating func addInterceptor(_ interceptor: URLRequestInterceptor) {
interceptors.append(interceptor)
}
/// Initialize authorization interceptors
mutating func addAuthInterceptorsToEndpoint(endpointType: AWSAPICategoryPluginEndpointType,
authConfiguration: AWSAuthorizationConfiguration) throws {
switch authConfiguration {
case .none:
// No interceptors needed
break
case .apiKey(let apiKeyConfig):
let provider = BasicAPIKeyProvider(apiKey: apiKeyConfig.apiKey)
let interceptor = APIKeyURLRequestInterceptor(apiKeyProvider: provider)
addInterceptor(interceptor)
case .awsIAM(let iamConfig):
guard let authService = authService else {
throw PluginError.pluginConfigurationError("AuthService is not set for IAM",
"")
}
let provider = BasicIAMCredentialsProvider(authService: authService)
let interceptor = IAMURLRequestInterceptor(iamCredentialsProvider: provider,
region: iamConfig.region,
endpointType: endpointType)
addInterceptor(interceptor)
case .amazonCognitoUserPools:
guard let authService = authService else {
throw PluginError.pluginConfigurationError("AuthService not set for cognito user pools",
"")
}
let provider = BasicUserPoolTokenProvider(authService: authService)
let interceptor = UserPoolURLRequestInterceptor(userPoolTokenProvider: provider)
addInterceptor(interceptor)
case .openIDConnect:
guard let oidcAuthProvider = apiAuthProviderFactory.oidcAuthProvider() else {
return
}
let wrappedAuthProvider = AuthTokenProviderWrapper(oidcAuthProvider: oidcAuthProvider)
let interceptor = UserPoolURLRequestInterceptor(userPoolTokenProvider: wrappedAuthProvider)
addInterceptor(interceptor)
}
}
}
| 41.72 | 106 | 0.643337 |
1c2b0f0326044d0a43b6bc30ef57412d88507a7a | 6,059 |
import Foundation
public typealias Completion<T> = (T) -> Void
public protocol QuestAuthDelegate {
func didSignOut(_ questAuth: QuestAuth)
func didAuthorize(_ questAuth: QuestAuth)
func didFailToAuthorize(_ questAuth: QuestAuth, with error: QuestAuth.Error)
}
public class QuestAuth: NSObject, URLRequestCodable {
public enum Error: Swift.Error {
case authInfoMissing, authAttemptsRanOut, urlParsingIssue, missingClientID, missingRedirectURL
}
let baseURL = "https://login.questrade.com/oauth2/"
let clientId: String
let redirectURL: String
private let _tokenStorage: StorageCoder<AuthResponse>
var auth: AuthResponse? {
get { _tokenStorage.value }
set { _tokenStorage.value = newValue }
}
var authURLString: String {
let redirectURI = "redirect_uri=\(redirectURL)"
let responseType = "response_type=token"
let clientID = "client_id=\(clientId)"
return baseURL + "authorize?\(clientID)&\(responseType)&\(redirectURI)"
}
public var requestDelegate: URLRequestCodableDelegate?
public var encoder = JSONEncoder()
public var decoder = JSONDecoder()
public var session = URLSession.shared
public var delegate: QuestAuthDelegate?
public var isAuthorized: Bool {
guard let auth = auth else { return false }
return auth.expiryDate > Date()
}
public init(tokenStore: Storable, clientID: String, redirectURL: String) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
decoder.dateDecodingStrategy = .formatted(formatter)
encoder.dateEncodingStrategy = .formatted(formatter)
self.clientId = clientID
self.redirectURL = redirectURL
self._tokenStorage = StorageCoder<AuthResponse>(storage: tokenStore)
}
private func signOut() {
auth = nil
delegate?.didSignOut(self)
}
public func revokeAccess(completion: (() -> Void)? = nil) {
let _completion: APIRes<Data> = { _ in
self.signOut()
completion?()
}
let endpoint = baseURL + "revoke"
if let req = authorizedTemplateRequest(baseURL: endpoint) {
autoAuth(req, completion: _completion)
}
}
func authorizedTemplateRequest(baseURL: String? = nil) -> URLRequest? {
guard let auth = auth else { return nil }
let u: URL = baseURL != nil ? URL(string: baseURL!)! : auth.api_server
var r = URLRequest(url: u)
r.addValue("\(auth.token_type) \(auth.access_token)", forHTTPHeaderField: "Authorization")
return r
}
// FIXME: Needs logic improvement
func autoAuth<T>(_ request: URLRequest, attempts: Int = 3, completion: @escaping APIRes<T>) {
var executed = false
if attempts == 0 {
completion(.failure(Error.authAttemptsRanOut))
}
let _completion: APIRes<T> = { res in
if executed { return }
if case .failure(let error) = res {
let code = (error as NSError).code
if code == 401 {
self.refreshToken { err in
if err == nil && !executed {
if var newRequest = self.authorizedTemplateRequest(baseURL: request.url?.absoluteString) {
newRequest.httpBody = request.httpBody
newRequest.httpMethod = request.httpMethod
self.autoAuth(newRequest, attempts: attempts - 1, completion: completion)
}
}
}
} else {
completion(res)
executed = true
}
} else {
completion(res)
executed = true
}
}
make(request, completion: _completion)
}
public func refreshToken(completion: Completion<Swift.Error?>? = nil) {
guard let auth = auth else {
completion?(Error.authInfoMissing)
return
}
let _completion: APIRes<AuthResponse> = { res in
switch res {
case .failure(let error):
self.signOut()
completion?(error)
case .success(let _authInfo):
self.auth = _authInfo
completion?(nil)
}
}
let endpoint = baseURL + "token?grant_type=refresh_token&refresh_token=\(auth.refresh_token)"
if let req = authorizedTemplateRequest(baseURL: endpoint) {
autoAuth(req, completion: _completion)
}
}
public func authorize(from url: URL) {
if let auth = parseAuthResponse(from: url) {
self.auth = auth
self.delegate?.didAuthorize(self)
}
}
func parseAuthResponse(from url: URL) -> AuthResponse? {
let u = url.absoluteString.replacingOccurrences(of: "#", with: "?")
guard let items = URLComponents(string: u)?.queryItems else { return nil }
let d = items.reduce(into: [String: String]()) { $0[$1.name] = $1.value }
guard
let accToken = d["access_token"],
let refToken = d["refresh_token"],
let apiURL = URL(string: d["api_server"] ?? ""),
let exp = d["expires_in"],
let type = d["token_type"]
else { return nil }
return AuthResponse(
access_token: accToken,
refresh_token: refToken,
api_server: apiURL,
token_type: type,
expiryDate: Date().addingTimeInterval(Double(exp) ?? 0)
)
}
}
| 34.039326 | 118 | 0.568081 |
6a74a25776a6435481c69870ebb8d9180f96b94e | 786 | //: # Analysis Playgrounds
//:
//: ## Plotting
//:
//: Playgrounds are a very visually compelling interface and you create a few
//: different ways of seeing what is happening to your audio signal.
//:
//: * [Output Waveform Plot](Output%20Waveform%20Plot)
//: * [Rolling Output Plot](Rolling%20Output%20Plot)
//: * [Node Output Plot](Node%20Output%20Plot)
//: * [Node FFT Plot](Node%20FFT%20Plot)
//:
//: ## Audio Analysis
//:
//: * [FFT Analysis](FFT%20Analysis)
//: * [Tracking Amplitude](Tracking%20Amplitude)
//: * [Tracking Frequency](Tracking%20Frequency)
//: * [Tracking Frequency of Audio File](Tracking%20Frequency%20of%20Audio%20File)
//: * Tracking Microphone Input appears in the macOS Development playground since iOS playgrounds don't have access to the micorphone
//:
| 35.727273 | 133 | 0.712468 |
ef18dd91bdd81e20b5265468d777a8261c1dc9cb | 8,283 | //
// ScreenModel.swift
// MetalScope
//
// Created by Jun Tanaka on 2017/01/23.
// Copyright © 2017 eje Inc. All rights reserved.
//
import UIKit
public enum ScreenModel {
case iPhone4
case iPhone5
case iPhone6
case iPhone6Plus
case iPhoneX
case iPhoneXR
case iPhoneXsMax
case iPhone12
case iPhone12mini
case iPhone12ProMax
case custom(parameters: ScreenParametersProtocol)
public static let iPhone4s = ScreenModel.iPhone4
public static let iPhone5s = ScreenModel.iPhone5
public static let iPhone5c = ScreenModel.iPhone5
public static let iPhoneSE = ScreenModel.iPhone5
public static let iPhone6s = ScreenModel.iPhone6
public static let iPhone6sPlus = ScreenModel.iPhone6Plus
public static let iPhone7 = ScreenModel.iPhone6
public static let iPhone7Plus = ScreenModel.iPhone6Plus
public static let iPhone8 = ScreenModel.iPhone6
public static let iPhone8Plus = ScreenModel.iPhone6Plus
public static let iPhoneXs = ScreenModel.iPhoneX
public static let iPhone11Pro = ScreenModel.iPhoneX
public static let iPhone11 = ScreenModel.iPhoneXR
public static let iPhone11ProMax = ScreenModel.iPhoneXsMax
public static let iPhoneSE2 = ScreenModel.iPhone6
public static let iPhone12Pro = ScreenModel.iPhone12
public static let iPodTouch = ScreenModel.iPhone5
public static var `default`: ScreenModel {
return ScreenModel.current ?? .iPhone5
}
public static var current: ScreenModel? {
return ScreenModel(modelIdentifier: currentModelIdentifier) ?? ScreenModel(screen: .main)
}
private static var currentModelIdentifier: String {
var size: size_t = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine: [CChar] = Array(repeating: 0, count: Int(size))
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String(cString: machine)
}
private init?(modelIdentifier identifier: String) {
func match(_ identifier: String, _ prefixes: [String]) -> Bool {
return prefixes.filter({ identifier.hasPrefix($0) }).count > 0
}
switch identifier {
case "iPod7,1": self = .iPodTouch
case "iPhone3,1", "iPhone3,2", "iPhone3,3": self = .iPhone4
case "iPhone4,1": self = .iPhone4s
case "iPhone5,1", "iPhone5,2": self = .iPhone5
case "iPhone5,3", "iPhone5,4": self = .iPhone5c
case "iPhone6,1", "iPhone6,2": self = .iPhone5s
case "iPhone7,2": self = .iPhone6
case "iPhone7,1": self = .iPhone6Plus
case "iPhone8,1": self = .iPhone6s
case "iPhone8,2": self = .iPhone6sPlus
case "iPhone9,1", "iPhone9,3": self = .iPhone7
case "iPhone9,2", "iPhone9,4": self = .iPhone7Plus
case "iPhone8,4": self = .iPhoneSE
case "iPhone10,1", "iPhone10,4": self = .iPhone8
case "iPhone10,2", "iPhone10,5": self = .iPhone8Plus
case "iPhone10,3", "iPhone10,6": self = .iPhoneX
case "iPhone11,2": self = .iPhoneXs
case "iPhone11,4", "iPhone11,6": self = .iPhoneXsMax
case "iPhone11,8": self = .iPhoneXR
case "iPhone12,1": self = .iPhone11
case "iPhone12,3": self = .iPhone11Pro
case "iPhone12,5": self = .iPhone11ProMax
case "iPhone12,8": self = .iPhoneSE2
case "iPhone13,1": self = .iPhone12mini
case "iPhone13,2": self = .iPhone12
case "iPhone13,3", "iPhone13,5": self = .iPhone12Pro
case "iPhone13,4", "iPhone13,7": self = .iPhone12ProMax
// case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":self = "iPad 2"
// case "iPad3,1", "iPad3,2", "iPad3,3": self = "iPad 3"
// case "iPad3,4", "iPad3,5", "iPad3,6": self = "iPad 4"
// case "iPad4,1", "iPad4,2", "iPad4,3": self = "iPad Air"
// case "iPad5,3", "iPad5,4": self = "iPad Air 2"
// case "iPad11,3", "iPad11,4": self = "iPad Air 3"
// case "iPad6,11", "iPad6,12": self = "iPad 5"
// case "iPad7,5", "iPad7,6": self = "iPad 6"
// case "iPad2,5", "iPad2,6", "iPad2,7": self = "iPad Mini"
// case "iPad4,4", "iPad4,5", "iPad4,6": self = "iPad Mini 2"
// case "iPad4,7", "iPad4,8", "iPad4,9": self = "iPad Mini 3"
// case "iPad5,1", "iPad5,2": self = "iPad Mini 4"
// case "iPad11,1", "iPad11,2": self = "iPad Mini 5"
// case "iPad6,3", "iPad6,4": self = "iPad Pro 9.7 Inch"
// case "iPad6,7", "iPad6,8": self = "iPad Pro 12.9 Inch"
// case "iPad7,1", "iPad7,2": self = "iPad Pro 12.9 Inch (2nd Generation)"
// case "iPad7,3", "iPad7,4": self = "iPad Pro 10.5 Inch"
// case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":self = "iPad Pro 11 Inch"
// case "iPad8,9", "iPad8,10": self = "iPad Pro 11 Inch (2nd Generation)"
// case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":self = "iPad Pro 12.9 Inch (3rd Generation)"
// case "iPad8,11", "iPad8,12": self = "iPad Pro 12.9 Inch (4th Generation)"
default:
return nil
}
}
private init?(screen: UIScreen) {
switch screen.fixedCoordinateSpace.bounds.size {
case CGSize(width: 320, height: 480): self = .iPhone4
case CGSize(width: 320, height: 568): self = .iPhone5
case CGSize(width: 375, height: 667): self = .iPhone6
case CGSize(width: 414, height: 768): self = .iPhone6Plus
case CGSize(width: 375, height: 812): self = .iPhoneX
case CGSize(width: 414, height: 896): self = .iPhoneXR
case CGSize(width: 414, height: 896): self = .iPhoneXsMax
case CGSize(width: 390, height: 844): self = .iPhone12
case CGSize(width: 360, height: 780): self = .iPhone12mini
case CGSize(width: 428, height: 926): self = .iPhone12ProMax
default:
return nil
}
}
}
extension ScreenModel: ScreenParametersProtocol {
private var parameters: ScreenParameters {
switch self {
case .iPhone4:
return ScreenParameters(width: 0.075, height: 0.050, border: 0.0045)
case .iPhone5:
return ScreenParameters(width: 0.089, height: 0.050, border: 0.0045)
case .iPhone6:
return ScreenParameters(width: 0.104, height: 0.058, border: 0.005)
case .iPhone6Plus:
return ScreenParameters(width: 0.120, height: 0.065, border: 0.005)
case .iPhoneX:
return ScreenParameters(width: 0.126, height: 0.058, border: 0.005)
case .iPhoneXR:
return ScreenParameters(width: 0.14, height: 0.065, border: 0.005)
case .iPhoneXsMax:
return ScreenParameters(width: 0.14, height: 0.065, border: 0.005)
case .iPhone12:
return ScreenParameters(width: 0.131, height: 0.061, border: 0.005)
case .iPhone12mini:
return ScreenParameters(width: 0.121, height: 0.056, border: 0.005)
case .iPhone12ProMax:
return ScreenParameters(width: 0.144, height: 0.067, border: 0.005)
case .custom(let parameters):
return ScreenParameters(parameters)
}
}
public var width: Float {
return parameters.width
}
public var height: Float {
return parameters.height
}
public var border: Float {
return parameters.border
}
}
| 46.79661 | 102 | 0.545696 |
d70714b92817249c6ac5d5d4b9037022e0f8eecc | 6,519 | //
// DismissCardAnimator.swift
// Kickster
//
// Created by Razvan Chelemen on 06/05/2019.
// Copyright © 2019 appssemble. All rights reserved.
//
import UIKit
final class DismissCardAnimator: NSObject, UIViewControllerAnimatedTransitioning {
struct Params {
let fromCardFrame: CGRect
let fromCardFrameWithoutTransform: CGRect
let fromCell: CardTableViewCell
let settings: TransitionSettings
}
struct Constants {
static let relativeDurationBeforeNonInteractive: TimeInterval = 0.5
static let minimumScaleBeforeNonInteractive: CGFloat = 0.8
}
private let params: Params
init(params: Params) {
self.params = params
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return params.settings.dismissalAnimationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let ctx = transitionContext
let container = ctx.containerView
var toViewController: CardsViewController! = ctx.viewController(forKey: .to)?.cardsViewController()
let screens: (cardDetail: CardDetailViewController, home: CardsViewController) = (
ctx.viewController(forKey: .from)! as! CardDetailViewController,
toViewController
)
let cardDetailView = ctx.view(forKey: .from)!
let animatedContainerView = UIView()
if params.settings.isEnabledDebugAnimatingViews {
animatedContainerView.layer.borderColor = UIColor.yellow.cgColor
animatedContainerView.layer.borderWidth = 4
cardDetailView.layer.borderColor = UIColor.red.cgColor
cardDetailView.layer.borderWidth = 2
}
animatedContainerView.translatesAutoresizingMaskIntoConstraints = false
cardDetailView.translatesAutoresizingMaskIntoConstraints = false
container.removeConstraints(container.constraints)
container.addSubview(animatedContainerView)
animatedContainerView.addSubview(cardDetailView)
// Card fills inside animated container view
cardDetailView.edges(to: animatedContainerView)
animatedContainerView.centerXAnchor.constraint(equalTo: container.centerXAnchor).isActive = true
let animatedContainerTopConstraint = animatedContainerView.topAnchor.constraint(equalTo: container.topAnchor, constant: params.settings.cardContainerInsets.top)
let animatedContainerWidthConstraint = animatedContainerView.widthAnchor.constraint(equalToConstant: cardDetailView.frame.width - (params.settings.cardContainerInsets.left + params.settings.cardContainerInsets.right))
let animatedContainerHeightConstraint = animatedContainerView.heightAnchor.constraint(equalToConstant: cardDetailView.frame.height - (params.settings.cardContainerInsets.top + params.settings.cardContainerInsets.bottom))
NSLayoutConstraint.activate([animatedContainerTopConstraint, animatedContainerWidthConstraint, animatedContainerHeightConstraint])
// Fix weird top inset
let topTemporaryFix = screens.cardDetail.cardContentView.topAnchor.constraint(equalTo: cardDetailView.topAnchor)
topTemporaryFix.isActive = params.settings.isEnabledWeirdTopInsetsFix
container.layoutIfNeeded()
// Force card filling bottom
let stretchCardToFillBottom = screens.cardDetail.cardContentView.bottomAnchor.constraint(equalTo: cardDetailView.bottomAnchor)
// for tableview header required confilcts with autoresizing mask constraints
stretchCardToFillBottom.priority = .defaultHigh
func animateCardViewBackToPlace() {
stretchCardToFillBottom.isActive = true
//screens.cardDetail.isFontStateHighlighted = false
// Back to identity
// NOTE: Animated container view in a way, helps us to not messing up `transform` with `AutoLayout` animation.
cardDetailView.transform = CGAffineTransform.identity
animatedContainerTopConstraint.constant = self.params.fromCardFrameWithoutTransform.minY + params.settings.cardContainerInsets.top
animatedContainerWidthConstraint.constant = self.params.fromCardFrameWithoutTransform.width - (params.settings.cardContainerInsets.left + params.settings.cardContainerInsets.right)
animatedContainerHeightConstraint.constant = self.params.fromCardFrameWithoutTransform.height - (params.settings.cardContainerInsets.top + params.settings.cardContainerInsets.bottom)
container.layoutIfNeeded()
}
func completeEverything() {
let success = !ctx.transitionWasCancelled
animatedContainerView.removeConstraints(animatedContainerView.constraints)
animatedContainerView.removeFromSuperview()
if success {
cardDetailView.removeFromSuperview()
self.params.fromCell.isHidden = false
} else {
//screens.cardDetail.isFontStateHighlighted = true
// Remove temporary fixes if not success!
topTemporaryFix.isActive = false
stretchCardToFillBottom.isActive = false
cardDetailView.removeConstraint(topTemporaryFix)
cardDetailView.removeConstraint(stretchCardToFillBottom)
container.removeConstraints(container.constraints)
container.addSubview(cardDetailView)
cardDetailView.edges(to: container)
}
ctx.completeTransition(success)
}
UIView.animate(withDuration: transitionDuration(using: ctx), delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: [], animations: {
animateCardViewBackToPlace()
}) { (finished) in
completeEverything()
}
UIView.animate(withDuration: transitionDuration(using: ctx) * 0.4) {
//print("godam")
//screens.cardDetail.scrollView.setContentOffset(self.params.settings.dismissalScrollViewContentOffset, animated: true)
screens.cardDetail.scrollView.contentOffset = self.params.settings.dismissalScrollViewContentOffset
}
}
}
| 48.288889 | 228 | 0.698267 |
14f8511a02ba6a4ea4faf6487335f9b099f53b91 | 5,407 | //
// 🦠 Corona-Warn-App
//
import Foundation
import UIKit
struct DiaryInfoViewModel {
init(
presentDisclaimer: @escaping () -> Void
) {
self.presentDisclaimer = presentDisclaimer
}
// MARK: - Internal
var dynamicTableViewModel: DynamicTableViewModel {
DynamicTableViewModel([
// Illustration with information text
.section(
header:
.image(
UIImage(
imageLiteralResourceName: "Illu_ContactDiary-Information"
),
accessibilityLabel: AppStrings.ContactDiary.Information.imageDescription,
accessibilityIdentifier: AccessibilityIdentifiers.ContactDiaryInformation.imageDescription
),
cells: [
.title2(
text: AppStrings.ContactDiary.Information.descriptionTitle,
accessibilityIdentifier: AccessibilityIdentifiers.ContactDiaryInformation.descriptionTitle
),
.subheadline(
text: AppStrings.ContactDiary.Information.descriptionSubHeadline,
accessibilityIdentifier: AccessibilityIdentifiers.ContactDiaryInformation.descriptionSubHeadline
),
.space(
height: 15.0,
color: .enaColor(for: .background)
),
.icon(
UIImage(imageLiteralResourceName: "Icons_Contact"),
text: .string(AppStrings.ContactDiary.Information.itemPersonTitle),
alignment: .top
),
.space(
height: 15.0,
color: .enaColor(for: .background)
),
.icon(
UIImage(imageLiteralResourceName: "Icons_Location"),
text: .string(AppStrings.ContactDiary.Information.itemContactTitle),
alignment: .top
),
.space(
height: 15.0,
color: .enaColor(for: .background)
),
.icon(
UIImage(imageLiteralResourceName: "Icons_Lock"),
text: .string(AppStrings.ContactDiary.Information.itemLockTitle),
alignment: .top
),
.space(
height: 15.0,
color: .enaColor(for: .background)
),
.icon(
UIImage(imageLiteralResourceName: "Icons_Diary_Deleted_Automatically"),
text: .string(AppStrings.ContactDiary.Information.deletedAutomatically),
alignment: .top
),
.space(
height: 15.0,
color: .enaColor(for: .background)
),
.icon(
UIImage(imageLiteralResourceName: "Icons_Diary_Export_Textformat"),
text: .string(AppStrings.ContactDiary.Information.exportTextformat),
alignment: .top
)
]
),
// Legal text
.section(cells: [
.legalExtended(
title: NSAttributedString(string: AppStrings.ContactDiary.Information.legalHeadline_1),
subheadline1: NSAttributedString(string: AppStrings.ContactDiary.Information.legalSubHeadline_1),
bulletPoints1: [
NSAttributedString(string: AppStrings.ContactDiary.Information.legalText_1),
NSAttributedString(string: AppStrings.ContactDiary.Information.legalText_2)
],
subheadline2: NSAttributedString(string: AppStrings.ContactDiary.Information.legalSubHeadline_2),
bulletPoints2: [
NSAttributedString(string: AppStrings.ContactDiary.Information.legalText_3),
NSAttributedString(string: AppStrings.ContactDiary.Information.legalText_4)
],
accessibilityIdentifier: AccessibilityIdentifiers.ExposureSubmissionQRInfo.acknowledgementTitle,
configure: { _, cell, _ in
cell.backgroundColor = .enaColor(for: .background)
}
)
]),
// Disclaimer cell
.section(
separators: .all,
cells: [
.body(
text: AppStrings.ContactDiary.Information.dataPrivacyTitle,
style: DynamicCell.TextCellStyle.label,
accessibilityIdentifier: AccessibilityIdentifiers.ContactDiaryInformation.dataPrivacyTitle,
accessibilityTraits: UIAccessibilityTraits.link,
action: .execute { _, _ in
presentDisclaimer()
},
configure: { _, cell, _ in
cell.accessoryType = .disclosureIndicator
cell.selectionStyle = .default
})
]
)
])
}
// MARK: - Private
private let presentDisclaimer: () -> Void
}
extension DynamicCell {
/// A `DynamicLegalExtendedCell` to display legal text
/// - Parameters:
/// - title: The title/header for the legal foo.
/// - subheadline1: Optional description text.
/// - bulletPoints1: A list of strings to be prefixed with bullet points.
/// - subheadline2: Optional description text.
/// - bulletPoints2: A list of strings to be prefixed with bullet points.
/// - accessibilityIdentifier: Optional, but highly recommended, accessibility identifier.
/// - configure: Optional custom cell configuration
/// - Returns: A `DynamicCell` to display legal texts
static func legalExtended(
title: NSAttributedString,
subheadline1: NSAttributedString?,
bulletPoints1: [NSAttributedString]? = nil,
subheadline2: NSAttributedString?,
bulletPoints2: [NSAttributedString]? = nil,
accessibilityIdentifier: String? = nil,
configure: CellConfigurator? = nil
) -> Self {
.identifier(DiaryInfoViewController.ReuseIdentifiers.legalExtended) { viewController, cell, indexPath in
guard let cell = cell as? DynamicLegalExtendedCell else {
fatalError("could not initialize cell of type `DynamicLegalExtendedCell`")
}
cell.configure(title: title, subheadline1: subheadline1, bulletPoints1: bulletPoints1, subheadline2: subheadline2, bulletPoints2: bulletPoints2, accessibilityIdentifier: accessibilityIdentifier)
configure?(viewController, cell, indexPath)
}
}
}
| 32.572289 | 197 | 0.71019 |
50eca9003c068fda4e59042689c685dbabf4be9a | 1,151 | import Foundation
public extension Double {
/// Rounds to the number of decimal-places specified
func rounded(to places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
/// An interpreted representation of the value, composed of the
/// integral and fraction as needed.
var fractionedString: String {
guard self.isNaN == false && self.isInfinite == false else {
return "0"
}
let decomposedAmount = modf(self)
guard decomposedAmount.1 > 0.0 else {
return "\(Int(decomposedAmount.0))"
}
let integral = Int(decomposedAmount.0)
let fraction = Fraction(proximateValue: decomposedAmount.1)
switch fraction {
case .zero:
return "\(integral)"
case .one:
return "\(Int(integral + 1))"
default:
if integral == 0 {
return "\(fraction.description)"
} else {
return "\(integral)\(fraction.description)"
}
}
}
}
| 28.775 | 68 | 0.537793 |
bb32b257baeb69c303e2df7b5eaa0378918b5f91 | 16,131 | //
// ExchangeViewController.swift
// SwiftWallet
//
// Created by Selin on 2018/4/8.
// Copyright © 2018年 DotC United Group. All rights reserved.
//
import UIKit
import PKHUD
class ExchangeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, FavoritesButtonActionDelegate {//
//MARK: - Declaration attributes
private var exchangeNameDic: Dictionary<String, [String]>?
private var exchangeNameTagList:[String]?
private var exchangeMoreTagList:[String]?
private var exchangeDataArr:[MarketsCoinPairDataModel] = []
private var exchangeSortSelectedKey = MarketsCoinPairsSortParamKey.vo_desc.rawValue
private var exchangeNameTagSelectedKey : String?
private var scrollHeaderView:MarketTitleHeaderView {
let scrollHeader: MarketTitleHeaderView = MarketTitleHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: SWScreen_width, height: 35))
scrollHeader.loadView(titles: self.exchangeNameTagList!, itemWidth: 50)
scrollHeader.itemSelectedActionBlock = { [weak self ](btnTag) in//
SPUserEventsManager.shared.addCount(forEvent: SWUEC_Click_Huobi_ExHomePage)
self?.exchangeNameTagSelectedKey = (self?.exchangeNameTagList![btnTag-100])!
self?.requestNetworkExchangePairsData(exchangeName: (self?.exchangeNameTagSelectedKey)!, sortKey: (self?.exchangeSortSelectedKey)!, offset: 0)
}
scrollHeader.addBtn.addTarget(self, action: #selector(addButtonAction(addBtn:)), for: .touchUpInside)
return scrollHeader
}
private let originY: CGFloat = 35.0
private lazy var exchangeSortingHeaderView : UIView = {
let headView : ExchangeHeaderView = Bundle.main.loadNibNamed("ExchangeHeaderView", owner: self, options: nil)?.last as! ExchangeHeaderView
headView.frame = CGRect.init(x: 0, y: 35, width: SWScreen_width, height: 34)
headView.itemTitles = [SWLocalizedString(key: "ex_vol"),SWLocalizedString(key: "price"),SWLocalizedString(key: "change")]
headView.setDefaultSelectedItem(btnTag: 0)
headView.buttonSelectedBlock = { [weak self] (btnTag, sortKey) in
if btnTag == 0 {
SPUserEventsManager.shared.addCount(forEvent: SWUEC_Click_volRank_ExHomePage)
} else if btnTag == 1 {
SPUserEventsManager.shared.addCount(forEvent: SWUEC_Click_PriceRank_ExHomePage)
} else {
SPUserEventsManager.shared.addCount(forEvent: SWUEC_Click_ChangeRank_ExHomePage)
}
self?.exchangeSortSelectedKey = sortKey
self?.requestNetworkExchangePairsData(exchangeName: (self?.exchangeNameTagSelectedKey)!, sortKey: sortKey, offset: 0)
}
return headView
}()
private lazy var exchangeTableView: UITableView = {
let tab : UITableView = UITableView.init(frame: CGRect.init(x: 0, y: 35+34, width: SWScreen_width, height: SWScreen_height-SafeAreaTopHeight-34-49), style: .plain)
tab.delegate = self
tab.dataSource = self
tab.backgroundColor = UIColor.init(hexColor: "F8F8F8")
tab.register(UINib.init(nibName: "MarketPairCell", bundle: nil), forCellReuseIdentifier: "MarketPairCell")
tab.separatorStyle = .none
tab.rowHeight = 60
tab.showsVerticalScrollIndicator = false
return tab
}()
private lazy var networkFailView: UIView = {
// load_failed
let failView : NetworkFailView = Bundle.main.loadNibNamed("NetworkFailView", owner: nil, options: nil)?.first as! NetworkFailView
failView.tryButton.addTarget(self, action: #selector(touchTryAgain), for: .touchUpInside)
return failView
}()
//MARK: - Life Circle
override func viewDidLoad() {
super.viewDidLoad()
SPUserEventsManager.shared.addCount(forEvent: SWUEC_Show_Exchange_Page)
SPUserEventsManager.shared.addCount(forEvent: SWUEC_Show_ExHomePage)
view.backgroundColor = UIColor.init(hexColor: "F8F8F8")
view.addSubview(exchangeTableView)
getExchangeTagList()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// exchangeSortingHeaderView.frame = CGRect.init(x: 0, y: 35, width: SWScreen_width, height: 34)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - load subView
private func getExchangeTagList() {
if let tagArrayArray = UserDefaults.standard.value(forKey: marketTagKeyPrefix + "exchange") as? [[String]] {
if tagArrayArray.count == 2 {
self.exchangeNameTagList = tagArrayArray[0]
self.exchangeMoreTagList = tagArrayArray[1]
}
}
requestExchangeNameTagsList()
}
func loadFailedView() {
self.exchangeDataArr.removeAll()
self.exchangeTableView.reloadData()
self.exchangeTableView.addSubview(networkFailView)
networkFailView.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.centerY.equalToSuperview().offset(-42)
}
}
func loadDataView() {
if self.exchangeNameTagList?.count == 0 {
loadFailedView()
return
}
view.addSubview(scrollHeaderView)
view.addSubview(exchangeSortingHeaderView)
exchangeSortingHeaderView.snp.makeConstraints { (make) in
make.left.equalTo(0)
make.top.equalTo(originY)
make.width.equalTo(SWScreen_width)
make.height.equalTo(34)
}
// Do any additional setup after loading the view.wan'yi
exchangeTableView.mj_header = SwiftDiyHeader(refreshingBlock: {
SPUserEventsManager.shared.trackEventAction(SWUEC_Show_Refresh_icon, eventPrame: "exchange")
self.requestNetworkExchangePairsData(exchangeName: (self.exchangeNameTagList?.first!)!, sortKey: self.exchangeSortSelectedKey, offset: 0)
})
exchangeTableView.mj_header.lastUpdatedTimeKey = "ExchangeViewController"
exchangeTableView.mj_footer = MJRefreshAutoFooter.init(refreshingBlock: {
self.requestNetworkExchangePairsData(exchangeName: self.exchangeNameTagSelectedKey!, sortKey: self.exchangeSortSelectedKey, offset: self.exchangeDataArr.count)
})
self.requestNetworkExchangePairsData(exchangeName: self.exchangeNameTagSelectedKey!, sortKey: self.exchangeSortSelectedKey, offset: self.exchangeDataArr.count)
}
//MARK: - Action
@objc func touchTryAgain() {
getExchangeTagList()
}
@objc func addButtonAction(addBtn: UIButton) {
SPUserEventsManager.shared.addCount(forEvent: SWUEC_Click_ManagerTag_ExHomePage)
let customVC : TagManageViewController = TagManageViewController()
customVC.type = MarketTagType.exchange
for tag in exchangeNameTagList! {
customVC.myTagArray.append(tag)
}
if exchangeMoreTagList != nil {
for tag in exchangeMoreTagList! {
customVC.moreTagArray.append(tag)
}
}
customVC.hidesBottomBarWhenPushed = true
customVC.reloadHeadTagBlock = { [weak self] (tagList, moreTagList) in
self?.exchangeNameTagList = tagList
self?.exchangeMoreTagList = moreTagList
self?.exchangeNameTagSelectedKey = self?.exchangeNameTagList!.first
self?.scrollHeaderView.removeFromSuperview()
self?.view.addSubview((self?.scrollHeaderView)!)
self?.requestNetworkExchangePairsData(exchangeName: (self?.exchangeNameTagSelectedKey)!, sortKey: (self?.exchangeSortSelectedKey)!, offset: 0)
}
navigationController?.pushViewController(customVC, animated: true)
}
//MARK: - RequestNetwork
func requestExchangeNameTagsList() {
MarketsAPIProvider.request(MarketsAPI.markets_exchangeTags) { [weak self](result) in
if case let .success(response) = result {
let decryptedData:Data = Data.init(decryptionResponseData: response.data)
let json = try? JSONDecoder().decode(MarketsExchangeTagModel.self, from: decryptedData)
if json?.code != 0 {
self?.loadFailedView()
print("markets all response json: \(String(describing: json ?? nil))")
return
}
if json?.data == nil { return }
let tags = json?.data
//每次对比接口与本地是否有新增tag
let tagCount = self?.exchangeNameTagList != nil ? self?.exchangeNameTagList?.count : 0
let moreTagCount = self?.exchangeMoreTagList != nil ? self?.exchangeMoreTagList?.count : 0
if (tagCount == 0) && (moreTagCount == 0) {
self?.exchangeNameTagList = json?.data
} else if (tags?.count)! != tagCount! + moreTagCount! {
for tag in tags! {
if (self?.exchangeNameTagList?.contains(tag))! || (self?.exchangeMoreTagList?.contains(tag))! {
continue
} else {
self?.exchangeNameTagList?.append(tag)
}
}
}
self?.exchangeNameTagSelectedKey = self?.exchangeNameTagList?.first
DispatchQueue.main.async {
self?.loadDataView()
}
} else {
self?.noticeOnlyText(SWLocalizedString(key: "network_error"))
self?.loadFailedView()
}
}
}
func requestNetworkExchangePairsData(exchangeName: String, sortKey:String, offset: Int) {
MarketsAPIProvider.request(MarketsAPI.markets_exchangePairs(exchangeName, sortKey, offset, 20)) { [weak self](result) in
self?.exchangeTableView.mj_header.endRefreshing()
self?.exchangeTableView.mj_footer.endRefreshing()
SPUserEventsManager.shared.trackEventAction(SWUEC_Show_Refresh_completed_icon, eventPrame: "exchange")
self?.networkFailView.removeFromSuperview()
if case let .success(response) = result {
let decryptedData:Data = Data.init(decryptionResponseData: response.data)
if decryptedData.count == 0 {
print("decryptedData is nil")
return
}
let json = try? JSONDecoder().decode(MarketsCoinPairModel.self, from: decryptedData)
if json?.code != 0 {
self?.loadFailedView()
print("json: \(String(describing: json ?? nil))")
return
}
if offset != 0 && json?.data?.count == 0 {
self?.noticeOnlyText(SWLocalizedString(key: "load_end"))
}
DispatchQueue.main.async {
if offset == 0 {
self?.exchangeDataArr.removeAll()
}
for symbol:MarketsCoinPairDataModel in (json?.data)! {
self?.exchangeDataArr.append(symbol)
}
self?.exchangeTableView.reloadData()
if offset == 0 && self?.exchangeDataArr.count != 0 {
self?.exchangeTableView.scrollToRow(at: NSIndexPath.init(row: 0, section: 0) as IndexPath, at: UITableViewScrollPosition.top, animated: true)
}
}
} else {
self?.noticeOnlyText(SWLocalizedString(key: "network_error"))
self?.loadFailedView()
}
}
}
// favorites
func favoritesRequest(symbol: String, exchange: String, pair: String, isFavorite: Bool, arrIndex: Int) {
MarketsAPIProvider.request(MarketsAPI.markets_currencyFavorite(symbol, exchange, pair, isFavorite)) { [weak self] (result) in
if case let .success(response) = result {
let decryptedData = Data.init(decryptionResponseData: response.data)
let json = try? JSONDecoder().decode(SimpleStruct.self, from: decryptedData)
if json?.code != 0 {
let msg = isFavorite ? SWLocalizedString(key: "add_failure") : SWLocalizedString(key: "cancel_failure")
self?.noticeOnlyText(msg)
print("currencyFavorite response json: \(String(describing: json ?? nil))")
return
}
var symbol:MarketsCoinPairDataModel = (self?.exchangeDataArr[arrIndex])!
symbol.favorite_status = isFavorite ? 1 : 2
self?.exchangeDataArr.remove(at: arrIndex)
self?.exchangeDataArr.insert(symbol, at: arrIndex)
self?.exchangeTableView.reloadRows(at: [IndexPath.init(row: arrIndex, section: 0)], with: UITableViewRowAnimation.none)
let msg = isFavorite ? SWLocalizedString(key: "add_success") : SWLocalizedString(key: "cancel_success")
self?.noticeOnlyText(msg)
} else {
self?.noticeOnlyText(SWLocalizedString(key: "cancel_failure"))
}
}
}
//MARK: - TableView Delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.exchangeDataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MarketPairCell = tableView.dequeueReusableCell(withIdentifier: "MarketPairCell") as! MarketPairCell
cell.selectionStyle = .none
let model :MarketsCoinPairDataModel = self.exchangeDataArr[indexPath.row]
cell.setContent(model: model, indexPath: indexPath)
cell.delegate_favor = self
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row < self.exchangeDataArr.count {
let vc:TransactionPairDetailViewController = TransactionPairDetailViewController()
let symbol:MarketsCoinPairDataModel = self.exchangeDataArr[indexPath.row]
vc.reloadFavoriteStatusClosure = { (status:Int) in
print("\(status)")
var symbol = self.exchangeDataArr[indexPath.row]
symbol.favorite_status = status
self.exchangeDataArr[indexPath.row] = symbol
tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none)
}
vc.coinPair = symbol
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
}
//MARK: cell favorites delegate
// func swipeTableCellWillEndSwiping(_ cell: MGSwipeTableCell) {
// let indexPath = self.exchangeTableView.indexPath(for: cell)
// if indexPath == nil {
// return
// }
// let symbol:MarketsCoinPairDataModel = self.exchangeDataArr[indexPath!.row]
// let eventName = symbol.favorite_status == 1 ? SWUEC_Show_AddFavorites_ExHomePage : SWUEC_Show_CancelFavorites_ExHomePage
// SPUserEventsManager.shared.addCount(forEvent: eventName)
// }
func favoritesButtonAction(indexPath: IndexPath) {
let model :MarketsCoinPairDataModel = self.exchangeDataArr[indexPath.row]
let favState = model.favorite_status == 1 ? false : true
self.favoritesRequest(symbol: model.symbol!, exchange: model.exchange!, pair:model.pair!, isFavorite: favState, arrIndex: indexPath.row)
let eventName = model.favorite_status == 1 ? SWUEC_Click_AddFavorites_ExHomePage : SWUEC_Click_CancelFavorites_ExHomePage
SPUserEventsManager.shared.addCount(forEvent: eventName)
}
}
| 46.353448 | 171 | 0.636228 |
f483eae57009ed17a73613b177cb950a25d685ec | 2,626 | //
// MarkupToogleButton.swift
// MacroPepelelipa
//
// Created by Pedro Henrique Guedes Silveira on 24/09/20.
// Copyright © 2020 Pedro Giuliano Farina. All rights reserved.
//
import UIKit
internal class MarkdownToggleButton: UIButton {
// MARK: - Variables and Constants
internal var baseColor: UIColor?
internal var selectedColor: UIColor?
// MARK: - Initializers
internal init(normalStateImage: UIImage?, title: String?, baseColor: UIColor? = UIColor.placeholderColor, selectedColor: UIColor? = UIColor.bodyColor, font: UIFont? = nil) {
super.init(frame: .zero)
self.addTarget(self, action: #selector(toogleButton), for: .touchDown)
self.setTitle(title, for: .normal)
self.setTitle(title, for: .selected)
self.baseColor = baseColor
self.selectedColor = selectedColor
self.tintColor = baseColor
if title != nil {
self.setTitleColor(baseColor, for: .normal)
self.setTitleColor(selectedColor, for: .selected)
setFont(font)
}
self.setBackgroundImage(normalStateImage, for: .normal)
}
internal init(frame: CGRect, color: UIColor) {
super.init(frame: frame)
self.addTarget(self, action: #selector(toogleButton), for: .touchDown)
self.setImage(UIImage(systemName: "checkmark"), for: .selected)
self.tintColor = UIColor.backgroundColor
self.baseColor = self.tintColor
self.selectedColor = self.tintColor
self.backgroundColor = color
self.layer.cornerRadius = frame.height / 2
}
internal required convenience init?(coder: NSCoder) {
guard let frame = coder.decodeObject(forKey: "frame") as? CGRect,
let color = coder.decodeObject(forKey: "color") as? UIColor else {
return nil
}
self.init(frame: frame, color: color)
}
// MARK: - Functions
private func setFont(_ font: UIFont?) {
guard let titleFont = font else {
return
}
self.titleLabel?.font = titleFont
}
internal func setCornerRadius() {
self.layer.cornerRadius = self.frame.height / 2
}
internal func setTintColor() {
if isSelected {
self.tintColor = selectedColor
} else {
self.tintColor = baseColor
}
}
// MARK: - Objective-C functions
@objc internal func toogleButton() {
self.isSelected.toggle()
setTintColor()
}
}
| 28.543478 | 177 | 0.601676 |
e56429d92233d842bb987f527833cc290ec226a4 | 1,278 | //
// SearchRequestTests.swift
// TranslateTests
//
// Created by Stanislav Ivanov on 29.03.2020.
// Copyright © 2020 Stanislav Ivanov. All rights reserved.
//
import XCTest
final class SearchRequestTests: BaseTests {
let networkDataSource = NetworkDataSource.shared
func testSearchRequest() {
let request = NetworkRequest.makeWordSearch(query: "1")
let result = RequestResult<[Word]>()
// Make mock
let requestUrl = request.request()!.url!.absoluteString
let url = URL(string: requestUrl)!
let resultData = self.loadDataFrom(fileName: "RealSearchResponse.json")!
URLProtocolMock.testURLs = [url: resultData]
let config = URLSessionConfiguration.ephemeral
config.protocolClasses = [URLProtocolMock.self]
let session = URLSession(configuration: config)
NetworkDataSource.prepeare(with: session)
// Execute
let expectation = XCTestExpectation(description: "testSearchRequest")
self.networkDataSource.execute(networkRequet: request, result: result) {
XCTAssertEqual(result.result?.isEmpty, false)
expectation.fulfill()
}
wait(for: [expectation], timeout: 10.0)
}
}
| 31.95 | 80 | 0.65493 |
64d37d3af7a3c3717ec5aa3ca4e43aa17d539727 | 507 | import UIKit
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private let flowCoordinator = AppFlowCoordinator()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let appWindow = UIWindow()
window = appWindow
appWindow.makeKeyAndVisible()
flowCoordinator.start(with: appWindow)
return true
}
}
| 29.823529 | 145 | 0.715976 |
dbe1f3d6e7b29b6e767eff9f30cfe3be96d359f3 | 1,787 | /* The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/
contributed by Isaac Gouy
formatDouble fix by Joao Pedrosa
*/
import Glibc
func approximate(n: Int) -> Double {
var u = Array(count: n, repeatedValue: 1.0)
var v = Array(count: n, repeatedValue: 0.0)
for _ in 1...10 {
multiplyAtAv(n,u,&v)
multiplyAtAv(n,v,&u)
}
var vBv = 0.0, vv = 0.0
for i in 0..<n {
vBv += u[i]*v[i]
vv += v[i]*v[i]
}
return sqrt(vBv/vv)
}
func a(i: Int, _ j: Int) -> Double {
let ij = i+j
return 1.0 / Double( ij*(ij+1)/2 + i+1 )
}
func multiplyAv(n: Int, _ v: [Double], inout _ av: [Double]) {
for i in 0..<n {
av[i] = 0.0;
for j in 0..<n {
av[i] += a(i,j)*v[j]
}
}
}
func multiplyAtv(n: Int, _ v: [Double], inout _ atv: [Double]) {
for i in 0..<n {
atv[i] = 0;
for j in 0..<n {
atv[i] += a(j,i)*v[j]
}
}
}
func multiplyAtAv(n: Int, _ v: [Double], inout _ atAv: [Double]) {
var u = Array(count: n, repeatedValue: 0.0)
multiplyAv(n,v,&u)
multiplyAtv(n,u,&atAv)
}
func formatDouble(f: Double, precision: Int = 2) -> String {
var p = 1
for _ in 0..<precision {
p *= 10
}
let neutral = abs(Int(round((f * Double(p)))))
var s = ""
let a = "\(neutral)".characters
let len = a.count
var dot = len - precision
if f < 0 {
s += "-"
}
if dot <= 0 {
dot = 1
}
let pad = precision - len
var i = 0
while i <= pad {
s += i == dot ? ".0" : "0"
i += 1
}
for c in a {
if i == dot {
s += "."
}
s.append(c)
i += 1
}
return s
}
let n: Int = Int(Process.arguments[1])!
print("\(formatDouble(approximate(n), precision: 9))")
| 19.423913 | 66 | 0.501399 |
eb02bbe7fe01bc5fb67a21fc7a28ef3f847a8f6c | 340 | //
// AttributeServiceMock.swift
// MobileConnectSDK
//
// Created by Mircea Grecu on 17/08/2016.
// Copyright © 2016 GSMA. All rights reserved.
//
import Foundation
import Alamofire
@testable import MobileConnectSDK
class AttributeServiceMock: AttributeService {
var error: NSError?
var response: AttributeResponseModel?
} | 17.894737 | 47 | 0.75 |
260098e3bb56b8b2395ff89882f9f1ce0c3de394 | 519 | //
// ViewController.swift
// chating-seminar-ios
//
// Created by Tran Quoc Bao on 4/10/18.
// Copyright © 2018 Tran Quoc Bao. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 19.961538 | 80 | 0.668593 |
1e074766274c3476e0ac11ee565ff69e065898d7 | 4,280 | #if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import Dispatch
import SystemPackage
import FileStreamer
#if swift(>=5.4)
@_implementationOnly import Cinotify
#else
import Cinotify
#endif
@available(*, deprecated, renamed: "Inotifier")
public typealias Inotify = Inotifier
/// The notifier object.
public final class Inotifier { // FIXME: Make struct again once release builds don't crash with SIGSEGV!
/// The callback that is called for read events.
public typealias Callback = (FilePath, Array<InotifyEvent>) -> ()
/// A watch identifier.
@frozen
public struct Watch: Hashable {
/// The callback data.
struct Callback {
/// The observed file path.
let filePath: FilePath
/// The callback queue.
let queue: DispatchQueue
/// The callback closure.
let callback: Inotifier.Callback
func callAsFunction(with events: Array<InotifyEvent>) {
queue.async { callback(filePath, events) }
}
}
/// The internal descriptor.
let descriptor: CInt
}
/// The collection of watches.
final class Watches {
private let lock = DispatchQueue(label: "de.sersoft.inotify.watches.lock")
private var watches = Dictionary<CInt, Array<Watch.Callback>>()
func withWatches<T>(do work: (inout Dictionary<CInt, Array<Watch.Callback>>) throws -> T) rethrows -> T {
dispatchPrecondition(condition: .notOnQueue(lock))
return try lock.sync { try work(&watches) }
}
}
/// The stream of events.
let stream: FileStream<cinotify_event>
/// The watches collection.
let watches: Watches
/// The underlying file descriptor of the stream.
var fileDescriptor: FileDescriptor { stream.fileDescriptor }
/// Creates a new instance.
public init() throws {
guard case let fd = inotify_init1(0), fd != -1 else { throw Errno(rawValue: errno) }
let _watches = Watches()
stream = .init(fileDescriptor: .init(rawValue: fd)) {
// FIXME: Deal with connected events using `event.cookie`.
let grouped = Dictionary(grouping: $0, by: \.wd).mapValues {
$0.map(InotifyEvent.init)
}
_watches.withWatches { watches in
grouped.forEach { (wd, events) in
watches[wd]?.forEach { $0(with: events) }
}
}
}
watches = _watches
}
/// Closes this inotify instance. All further calls to this instance will fail.
public func close() throws {
try watches.withWatches {
try fileDescriptor.close()
$0.removeAll()
}
}
/// Adds a watch for a given file path, calling back on the given queue using the given closure.
/// - Parameters:
/// - filePath: The file path to watch.
/// - queue: The queue on which to call the `callback` closure.
/// - callback: The closure to call with events.
/// - Returns: The added watch. This is needed to later remove it again.
public func addWatch(for filePath: FilePath, on queue: DispatchQueue, calling callback: @escaping Callback) throws -> Watch {
try watches.withWatches {
let wd = filePath.withCString {
inotify_add_watch(fileDescriptor.rawValue, $0, cin_all_events)
}
guard wd != -1 else { throw Errno(rawValue: errno) }
$0[wd, default: []].append(Watch.Callback(filePath: filePath, queue: queue, callback: callback))
stream.beginStreaming()
return Watch(descriptor: wd)
}
}
private func _removeWatch(forDescriptor wd: CInt) throws {
let status = inotify_rm_watch(fileDescriptor.rawValue, wd)
guard status != -1 else { throw Errno(rawValue: errno) }
}
/// Removes a given watch.
/// - Parameter watch: The watch to remove.
public func removeWatch(_ watch: Watch) throws {
try watches.withWatches {
try _removeWatch(forDescriptor: watch.descriptor)
$0.removeValue(forKey: watch.descriptor)
if $0.isEmpty {
stream.endStreaming()
}
}
}
}
| 34.796748 | 129 | 0.609579 |
db5d2f4f3eea1dfcaf7dd6c3b982007191e16824 | 646 | import Foundation
class DeletePostModal{
struct deletePost_SuccessModal:Codable{
var api_status: Int
var action: String
}
struct deletePost_ErrorModal:Codable{
let apiStatus: String
let errors: Errors
enum CodingKeys: String, CodingKey {
case apiStatus = "api_status"
case errors
}
}
// MARK: - Errors
struct Errors: Codable {
let errorID: Int
let errorText: String
enum CodingKeys: String, CodingKey {
case errorID = "error_id"
case errorText = "error_text"
}
}
}
| 21.533333 | 44 | 0.56192 |
db3b03a94e431fd5d17d5dbbcdd2cbf283f90025 | 196 | import ShellClient
// swiftlint:disable:next identifier_name
var Current: World = .init()
// Inspired by: https://vimeo.com/291588126
struct World {
var shellClient: ShellClient = .live()
}
| 19.6 | 43 | 0.729592 |
f994dcaaeef678e4f86a15a1eb0747b6c6bccb15 | 197 | //
// ScreenshotTaker.swift
// ScreenRecorder
//
// Created by Mikayel Aghasyan on 4/7/18.
//
public protocol ScreenshotProcessor {
func processScreenshot(screenshot: UIImage) -> UIImage
}
| 17.909091 | 58 | 0.720812 |
8a0b5a9c9ca864cb714e381948e15f8eec6948f2 | 1,657 | //
// ViewControllerExtension.swift
// MovieBuff
//
// Created by Mac Tester on 11/6/16.
// Copyright © 2016 Lunaria Software LLC. All rights reserved.
//
import Foundation
import UIKit
import MBProgressHUD
extension UIViewController {
func showErrorAlertWithTitle(_ title:String?, message:String) {
let alertController = UIAlertController(title: title ?? "", message: message, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
func showSuccessAlertWithTitle(_ title:String?, message:String) {
let alertController = UIAlertController(title: title ?? "", message: message, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
self.dismiss(animated: true, completion: {
})
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
func showDataLoadingProgressHUD() {
MBProgressHUD.showAdded(to: self.view, animated: true)
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func hideDataLoadingProgressHUD() {
MBProgressHUD.hide(for: self.view, animated: true)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
| 33.816327 | 131 | 0.672903 |
b9d0b534eeb71463c3d9674a035297dc566d4e50 | 893 | import UIKit
import MarkdownView
final class MainViewController: UIViewController {
// MARK: - Injected
var storage: UserStorage!
var windowController: WindowController!
// MARK: - Properties
var isLogged: Bool = false {
didSet {
storage.isLogged = isLogged
}
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
customizeMarkdownView()
}
private func customizeMarkdownView() {
let bundle = Bundle.main
let path = bundle.path(forResource: "README", ofType: "md")
let string = try? String(contentsOfFile: path ?? "")
(view as? MarkdownView)?.load(markdown: string)
}
// MARK: - Actions
@IBAction private func logoutTapped() {
isLogged = false
windowController.performSwitch()
}
}
| 22.325 | 67 | 0.589026 |
182f24eaa3473bbb7bc640c38fb6d47be3d14d07 | 4,676 | //
// RAMViewLineExtension.swift
// RAMSport
//
// Created by rambo on 2020/2/20.
// Copyright © 2020 rambo. All rights reserved.
//
import UIKit
import SnapKit
extension UIView {
private struct RAMViewLineAssociatedKeys {
static var kTopLineKey = "kTopLineKey"
static var kBottomLineKey = "kBottomLineKey"
static var kLeftLineKey = "kLeftLineKey"
static var kRightLineKey = "kRightLineKey"
}
enum LinePosition: Int {
case AtTop
case AtBottom
case AtLeft
case AtRight
}
func ram_line() -> UIView {
let image = UIImage.image(withColor: #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1))
let imageView = UIImageView(image: image)
imageView.frame = CGRect(x: 0, y: 0, width: RAM_SINGLE_LINE_WIDTH, height: RAM_SINGLE_LINE_WIDTH)
return imageView
}
func _ram_getLine(by key: UnsafeRawPointer) -> UIView {
var v = objc_getAssociatedObject(self, key) as? UIView
if v == nil {
v = ram_line()
objc_setAssociatedObject(self, key, v, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return v!
}
func ram_addLine(at position: LinePosition, left leftOffset: CGFloat, right rightOffset: CGFloat) -> UIView {
var v = UIView()
if position == .AtTop {
v = _ram_getLine(by: &RAMViewLineAssociatedKeys.kBottomLineKey)
} else if position == .AtBottom {
v = _ram_getLine(by: &RAMViewLineAssociatedKeys.kTopLineKey);
} else {
return v
}
v.removeFromSuperview()
if let cell = self as? UITableViewCell {
cell.contentView.addSubview(v)
} else {
addSubview(v)
}
v.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(leftOffset)
if position == .AtTop {
make.top.equalToSuperview()
} else if position == .AtBottom {
make.bottom.equalToSuperview()
}
make.width.equalTo(RAMScreenWidth - leftOffset - rightOffset)
make.height.equalTo(RAM_SINGLE_LINE_WIDTH)
}
return v
}
func ram_addLine(at position: LinePosition, top topOffset: CGFloat, bottom bottomOffset: CGFloat) -> UIView {
var v = UIView()
if position == .AtLeft {
v = _ram_getLine(by: &RAMViewLineAssociatedKeys.kLeftLineKey)
} else if position == .AtRight {
v = _ram_getLine(by: &RAMViewLineAssociatedKeys.kRightLineKey);
} else {
return v
}
v.removeFromSuperview()
if let cell = self as? UITableViewCell {
cell.contentView.addSubview(v)
} else {
addSubview(v)
}
v.snp.makeConstraints { (make) in
make.width.equalTo(RAM_SINGLE_LINE_WIDTH)
make.top.equalToSuperview().offset(topOffset)
make.bottom.equalToSuperview().offset(-1 * bottomOffset)
if position == .AtLeft {
make.left.equalToSuperview()
} else if position == .AtRight {
make.right.equalToSuperview()
}
}
return v
}
// MARK: -
func ram_addLine(at position: LinePosition) -> UIView {
switch position {
case .AtBottom, .AtTop:
return ram_addLine(at: position, left: CGFloat.leastNormalMagnitude, right: CGFloat.leastNormalMagnitude)
case .AtLeft, .AtRight:
return ram_addLine(at: position, top: CGFloat.leastNormalMagnitude, bottom: CGFloat.leastNormalMagnitude)
}
}
func ram_addLine(atVertical position: LinePosition, left: CGFloat, right: CGFloat) -> UIView {
return ram_addLine(at: position, left: left, right: right)
}
func ram_addLine(atHorizontal position: LinePosition, top: CGFloat, bottom: CGFloat) -> UIView {
return ram_addLine(at: position, top: top, bottom: bottom)
}
func ram_removeLine(at position: LinePosition) {
switch position {
case .AtBottom:
_ram_getLine(by: RAMViewLineAssociatedKeys.kBottomLineKey).removeFromSuperview()
case .AtTop:
_ram_getLine(by: RAMViewLineAssociatedKeys.kTopLineKey).removeFromSuperview()
case .AtRight:
_ram_getLine(by: RAMViewLineAssociatedKeys.kRightLineKey).removeFromSuperview()
case .AtLeft:
_ram_getLine(by: RAMViewLineAssociatedKeys.kLeftLineKey).removeFromSuperview()
}
}
}
| 34.131387 | 129 | 0.610565 |
5be5b47637d7e51a1a1a55715099d36b35b3364c | 2,037 | //
// ZCashSDKEnvironment.swift
// secant-testnet
//
// Created by Lukáš Korba on 13.04.2022.
//
import Foundation
import ZcashLightClientKit
// swiftlint:disable:next private_over_fileprivate strict_fileprivate
fileprivate enum ZcashSDKConstants {
static let endpointMainnetAddress = "lightwalletd.electriccoin.co"
static let endpointTestnetAddress = "lightwalletd.testnet.electriccoin.co"
static let endpointPort = 9067
static let defaultBlockHeight = 1_629_724
static let mnemonicWordsMaxCount = 24
}
struct ZCashSDKEnvironment {
let defaultBirthday: BlockHeight
let endpoint: LightWalletEndpoint
let lightWalletService: LightWalletService
let network: ZcashNetwork
let mnemonicWordsMaxCount: Int
let isMainnet: () -> Bool
}
extension ZCashSDKEnvironment {
static let mainnet = ZCashSDKEnvironment(
defaultBirthday: BlockHeight(ZcashSDKConstants.defaultBlockHeight),
endpoint: LightWalletEndpoint(address: ZcashSDKConstants.endpointMainnetAddress, port: ZcashSDKConstants.endpointPort),
lightWalletService: LightWalletGRPCService(
endpoint: LightWalletEndpoint(address: ZcashSDKConstants.endpointMainnetAddress, port: ZcashSDKConstants.endpointPort)
),
network: ZcashNetworkBuilder.network(for: .mainnet),
mnemonicWordsMaxCount: ZcashSDKConstants.mnemonicWordsMaxCount,
isMainnet: { true }
)
static let testnet = ZCashSDKEnvironment(
defaultBirthday: BlockHeight(ZcashSDKConstants.defaultBlockHeight),
endpoint: LightWalletEndpoint(address: ZcashSDKConstants.endpointTestnetAddress, port: ZcashSDKConstants.endpointPort),
lightWalletService: LightWalletGRPCService(
endpoint: LightWalletEndpoint(address: ZcashSDKConstants.endpointTestnetAddress, port: ZcashSDKConstants.endpointPort)
),
network: ZcashNetworkBuilder.network(for: .testnet),
mnemonicWordsMaxCount: ZcashSDKConstants.mnemonicWordsMaxCount,
isMainnet: { false }
)
}
| 39.173077 | 130 | 0.76485 |
89d976926c63a96696d8867f5d11737d7ae12510 | 3,353 | // RUN: %target-parse-verify-swift
func foo(a: Int) {
// expected-error @+1 {{invalid character in source file}} {{8-9= }}
foo(<\a\>) // expected-error {{invalid character in source file}} {{10-11= }}
// expected-error @-1 {{'<' is not a prefix unary operator}}
// expected-error @-2 {{'>' is not a postfix unary operator}}
}
// rdar://15946844
func test1(inout var x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{18-22=}}
func test2(inout let x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{18-22=}}
func test3() {
undeclared_func( // expected-error {{use of unresolved identifier 'undeclared_func'}} expected-note {{to match this opening '('}} expected-error {{expected ',' separator}} {{19-19=,}}
} // expected-error {{expected expression in list of expressions}} expected-error {{expected ')' in expression list}}
func runAction() {}
// rdar://16601779
func foo() {
runAction(SKAction.sequence() // expected-error {{use of unresolved identifier 'SKAction'}} expected-note {{to match this opening '('}} expected-error {{expected ',' separator}} {{32-32=,}}
// expected-error @+2 {{expected ',' separator}} {{12-12=,}}
// expected-error @+1 {{expected ',' separator}} {{12-12=,}}
skview!
// expected-error @-1 {{use of unresolved identifier 'skview'}}
} // expected-error {{expected expression in list of expressions}} expected-error {{expected ')' in expression list}}
func test3(a: inout Int) {} // expected-error {{'inout' must appear before the parameter name}}{{12-12=inout }}{{15-21=}}
super.init() // expected-error {{'super' cannot be used outside of class members}}
switch state { // expected-error {{use of unresolved identifier 'state'}}
let duration : Int = 0 // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} \
// expected-error {{expected expression}}
}
// rdar://18926814
func test4() {
let abc = 123
_ = " >> \( abc } ) << " // expected-note {{to match this opening '('}} expected-error {{expected ')' in expression list}} expected-error {{expected ',' separator}} {{18-18=,}} expected-error {{expected ',' separator}} {{18-18=,}} expected-error {{expected expression in list of expressions}} expected-error {{extra tokens after interpolated string expression}}
}
// rdar://problem/18507467
func d(b: String -> <T>() -> T) {} // expected-error {{expected type for function result}}
// expected-error @-1 {{expected ',' separator}} {{20-20=,}}
// expected-error @-2 {{expected parameter name followed by ':'}}
// expected-error @-3 {{expected ',' separator}}
// <rdar://problem/22143680> QoI: terrible diagnostic when trying to form a generic protocol
protocol Animal<Food> { // expected-error {{protocols do not allow generic parameters; use associated types instead}}
func feed(food: Food) // expected-error {{use of undeclared type 'Food'}}
}
// SR-573 - Crash with invalid parameter declaration
class Starfish {}
struct Salmon {}
func f573(s Starfish, // expected-error {{parameter requires an explicit type}}
_ ss: Salmon) -> [Int] {}
func g573() { f573(Starfish(), Salmon()) }
func SR698(a: Int, b: Int) {}
SR698(1, b: 2,) // expected-error {{unexpected ',' separator}}
| 48.594203 | 369 | 0.658515 |
4b420893532b95ab5d72cb127275a3cae8387c07 | 3,963 | import Cocoa
import Defaults
final class TouchBarWindow: NSPanel {
enum Docking: String, Codable {
case floating, dockedToTop, dockedToBottom
func dock(window: TouchBarWindow) {
switch self {
case .floating:
window.addTitlebar()
if let prevPosition = defaults[.lastFloatingPosition] {
window.setFrameOrigin(prevPosition)
}
case .dockedToTop:
window.removeTitlebar()
window.moveTo(x: .center, y: .top)
case .dockedToBottom:
window.removeTitlebar()
window.moveTo(x: .center, y: .bottom)
}
}
}
var docking: Docking? {
didSet {
if oldValue == .floating && docking != .floating {
defaults[.lastFloatingPosition] = frame.origin
}
docking?.dock(window: self)
setIsVisible(true)
orderFront(nil)
}
}
var showOnAllDesktops: Bool = false {
didSet {
if showOnAllDesktops {
collectionBehavior = .canJoinAllSpaces
} else {
collectionBehavior = .moveToActiveSpace
}
}
}
func addTitlebar() {
styleMask.insert(.titled)
title = "Touch Bar Simulator"
guard let toolbarView = self.toolbarView else {
return
}
toolbarView.addSubviews(
makeScreenshotButton(toolbarView),
makeTransparencySlider(toolbarView)
)
}
func removeTitlebar() {
styleMask.remove(.titled)
}
func makeScreenshotButton(_ toolbarView: NSView) -> NSButton {
let button = NSButton()
button.image = NSImage(named: "ScreenshotButton")
button.imageScaling = .scaleProportionallyDown
button.isBordered = false
button.bezelStyle = .shadowlessSquare
button.frame = CGRect(x: toolbarView.frame.width - 19, y: 4, width: 16, height: 11)
button.action = #selector(AppDelegate.captureScreenshot)
return button
}
private var transparencySlider: ToolbarSlider?
func makeTransparencySlider(_ parentView: NSView) -> ToolbarSlider {
let slider = ToolbarSlider().alwaysRedisplayOnValueChanged().bindDoubleValue(to: .windowTransparency)
slider.frame = CGRect(x: parentView.frame.width - 160, y: 4, width: 140, height: 11)
slider.minValue = 0.5
return slider
}
override var canBecomeMain: Bool {
return false
}
override var canBecomeKey: Bool {
return false
}
private var defaultsObservations: [DefaultsObservation] = []
func setUp() {
let view = contentView!
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.black.cgColor
let touchBarView = TouchBarView()
setContentSize(touchBarView.bounds.adding(padding: 5).size)
touchBarView.frame = touchBarView.frame.centered(in: view.bounds)
view.addSubview(touchBarView)
// TODO: These could use the `observe` method with `tiedToLifetimeOf` so we don't have to manually invalidate them.
defaultsObservations.append(defaults.observe(.windowTransparency) { change in
self.alphaValue = CGFloat(change.newValue)
})
defaultsObservations.append(defaults.observe(.windowDocking) { change in
self.docking = change.newValue
})
// TODO: We could maybe simplify this by creating another `Default` extension to bind a default to a KeyPath:
// `defaults.bind(.showOnAllDesktops, to: \.showOnAllDesktop)`
defaultsObservations.append(defaults.observe(.showOnAllDesktops) { change in
self.showOnAllDesktops = change.newValue
})
center()
setFrameOrigin(CGPoint(x: frame.origin.x, y: 100))
setFrameUsingName(Constants.windowAutosaveName)
setFrameAutosaveName(Constants.windowAutosaveName)
orderFront(nil)
}
deinit {
for observation in defaultsObservations {
observation.invalidate()
}
}
convenience init() {
self.init(
contentRect: .zero,
styleMask: [
.titled,
.closable,
.nonactivatingPanel,
.hudWindow,
.utilityWindow
],
backing: .buffered,
defer: false
)
self.level = .assistiveTechHigh
self._setPreventsActivation(true)
self.isRestorable = true
self.hidesOnDeactivate = false
self.worksWhenModal = true
self.acceptsMouseMovedEvents = true
self.isMovableByWindowBackground = false
}
}
| 24.924528 | 117 | 0.726722 |
f77fc6b0c91fee126e1ad042cdfebb61b00474f5 | 5,035 | //
// ViewController.swift
// WLM3U
//
// Created by Willie on 07/15/2019.
// Copyright (c) 2019 Willie. All rights reserved.
//
import UIKit
import WLM3U
class ViewController: UIViewController {
@IBOutlet weak var textView1: UITextView!
@IBOutlet weak var progressView1: UIProgressView!
@IBOutlet weak var speedLabel1: UILabel!
@IBOutlet weak var progressLabel1: UILabel!
@IBOutlet weak var textView2: UITextView!
@IBOutlet weak var progressView2: UIProgressView!
@IBOutlet weak var speedLabel2: UILabel!
@IBOutlet weak var progressLabel2: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let url1 = "http://47.108.143.147/fs/v1/6570255ceb09709311cb152cdc565e12.m3u8"
let url2 = "http://47.108.143.147/fs/v1/6570255ceb09709311cb152cdc565e12.m3u8"
textView1.text = url1
textView2.text = url2
}
@IBAction func onDownloadButton(_ sender: UIButton) {
let url = URL(string: sender.tag == 0 ? textView1.text : textView2.text)!
do {
let workflow = try WLM3U.attach(url: url,
tsURL: { (path, url) -> URL? in
if path.hasSuffix(".ts") {
return url.appendingPathComponent(path)
} else {
return nil
}
},
completion: { (result) in
switch result {
case .success(let model):
print("[Attach Success] " + model.name!)
case .failure(let error):
print("[Attach Failure] " + error.localizedDescription)
}
})
run(workflow: workflow, index: sender.tag)
} catch {
print(error.localizedDescription)
}
}
@IBAction func onPauseButton(_ sender: UIButton) {
WLM3U.cancel(url: URL(string: sender.tag == 0 ? textView1.text : textView2.text)!)
}
@IBAction func onResumeButton(_ sender: UIButton) {
let url = URL(string: sender.tag == 0 ? textView1.text : textView2.text)!
do {
let workflow = try WLM3U.attach(url: url,
completion: { (result) in
switch result {
case .success(let model):
print("[Attach Success] " + model.name!)
case .failure(let error):
print("[Attach Failure] " + error.localizedDescription)
}
})
run(workflow: workflow, index: sender.tag)
} catch {
print(error.localizedDescription)
}
}
func run(workflow: Workflow, index: Int) {
let progressView = (index == 0 ? progressView1 : progressView2)!
let speedLabel = (index == 0 ? speedLabel1 : speedLabel2)!
let progressLabel = (index == 0 ? progressLabel1 : progressLabel2)!
workflow
.download(progress: { (progress, completedCount) in
progressView.progress = Float(progress.fractionCompleted)
var text = ""
let mb = Double(completedCount) / 1024 / 1024
if mb >= 0.1 {
text = String(format: "%.1f", mb) + " M/s"
} else {
text = String(completedCount / 1024) + " K/s"
}
speedLabel.text = text
progressLabel.text = String(format: "%.2f", progress.fractionCompleted * 100) + " %"
}, completion: { (result) in
switch result {
case .success(let url):
print("[Download Success] " + url.path)
case .failure(let error):
print("[Download Failure] " + error.localizedDescription)
}
})
.combine(completion: { (result) in
switch result {
case .success(let url):
print("[Combine Success] " + url.path)
case .failure(let error):
print("[Combine Failure] " + error.localizedDescription)
}
speedLabel.text = "All finished"
progressLabel.text = "All finished"
})
}
}
| 39.645669 | 107 | 0.447865 |
01200240f7d2499bf433663c61c31160cf283b7e | 2,363 | //
// MealCard.swift
// FastFoodOrder
//
// Created by Ha Do on 6/29/20.
// Copyright © 2020 Ha Do. All rights reserved.
//
import SwiftUI
struct MealCard: View {
var meal: Meal
var selectionHandler : (Meal) -> Void
init(_ meal: Meal, onSelected: @escaping (Meal) -> Void) {
self.meal = meal
self.selectionHandler = onSelected
}
var body: some View {
GeometryReader { proxy in
VStack(alignment: .leading, spacing: 4) {
Image(self.meal.photo)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: proxy.size.width - 40, height: proxy.size.width - 40, alignment: .center)
Text(self.meal.title)
.foregroundColor(.darkGray)
.font(.system(size: 12))
.fontWeight(.light)
HStack {
Text("AED: \(self.meal.AED)")
.font(.system(size: 13))
.foregroundColor(.black)
Spacer()
Button(action: {
self.selectionHandler(self.meal)
}) {
Image(systemName: "plus")
.resizable()
.foregroundColor(.darkGray)
.padding(6)
.frame(width: 20, height: 20, alignment: .center)
.background(Color.white)
.cornerRadius(10)
.shadow(color: Color(#colorLiteral(red: 0.8666666667, green: 0.8666666667, blue: 0.8666666667, alpha: 1)), radius: 1, x: 1, y: 1)
}
.buttonStyle(ScaleButtonStyle(step: 0.6))
}
}
.padding(8)
.background(Color(#colorLiteral(red: 0.9921568627, green: 0.9921568627, blue: 0.9921568627, alpha: 1)))
.frame(height: proxy.size.width + 30, alignment: .center)
}
}
}
struct MealCard_Previews: PreviewProvider {
static var previews: some View {
MealCard(RestaurantRepo.getMeals(RestaurantRepo.categories[0])[0], onSelected: { m in })
.previewLayout(.fixed(width: 120, height: 200))
}
}
| 35.268657 | 153 | 0.479898 |
75fa2e4ee7b74b3387351fa440103ee7b05df336 | 261 | import Foundation
public class StorageMapping<T: Decodable> {
open var type: T.Type
open var primaryKey: String?
public init(type: T.Type,
primaryKey: String) {
self.primaryKey = primaryKey
self.type = type
}
}
| 20.076923 | 43 | 0.616858 |
89d92f80caed7ff4af82fe0dfdf17acdbbd7ee80 | 2,193 | //
// AppDelegate.swift
// Testing-Project-ShortCourse
//
// Created by Soeng Saravit on 5/7/18.
// Copyright © 2018 Soeng Saravit. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.659574 | 285 | 0.756498 |
f7e684783c7203feb7754004a70ec96c8807c6aa | 15,390 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import UIKit
// MARK: MSDateTimePickerViewMode
enum MSDateTimePickerViewMode {
case date(startYear: Int, endYear: Int)
case dateTime /// Date hour/minute am/pm
case dayOfMonth /// Week of month / Day of week
static let defaultStartYear: Int = MSCalendarConfiguration.default.referenceStartDate.year
static let defaultEndYear: Int = MSCalendarConfiguration.default.referenceEndDate.year
}
// MARK: - MSDateTimePickerViewDelegate
protocol MSDateTimePickerViewDelegate: class {
func dateTimePickerView(_ dateTimePickerView: MSDateTimePickerView, accessibilityValueOverwriteForDate date: Date, originalValue: String?) -> String?
}
// MARK: - MSDateTimePickerView
/*
* Custom Date picker view
*
* Public
* - init(type: MSDateTimePickerViewMode)
* - property date: Date
* - setDate(date: Date, animated: Bool)
*
* To use:
* - Initialize with the types you want (see MSDateTimePickerViewMode)
* - Set the date you want to show first
* - Listen to UIControlEventChanged to get notified of changes. It is only fired when the change is initiated by the user
* - Query the date property to retrieve a Date
*/
class MSDateTimePickerView: UIControl {
let mode: MSDateTimePickerViewMode
private(set) var date = Date()
private(set) var dayOfMonth = MSDayOfMonth()
weak var delegate: MSDateTimePickerViewDelegate?
private let componentTypes: [MSDateTimePickerViewComponentType]!
private let componentsByType: [MSDateTimePickerViewComponentType: MSDateTimePickerViewComponent]!
private let selectionTopSeparator = MSSeparator()
private let selectionBottomSeparator = MSSeparator()
private let gradientLayer: CAGradientLayer = {
let gradientLayer = CAGradientLayer()
let backgroundColor = MSColors.DateTimePicker.background
let transparentColor = backgroundColor.withAlphaComponent(0)
gradientLayer.colors = [backgroundColor.cgColor, transparentColor.cgColor, transparentColor.cgColor, backgroundColor.cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 0, y: 1)
return gradientLayer
}()
init(mode: MSDateTimePickerViewMode) {
self.mode = mode
componentTypes = MSDateTimePickerViewLayout.componentTypes(fromDatePickerMode: mode)
componentsByType = MSDateTimePickerViewLayout.componentsByType(fromTypes: componentTypes, mode: mode)
super.init(frame: .zero)
for component in componentsByType.values {
component.delegate = self
addSubview(component.view)
}
layer.addSublayer(gradientLayer)
addSubview(selectionTopSeparator)
addSubview(selectionBottomSeparator)
backgroundColor = MSColors.DateTimePicker.background
setDate(date, animated: false)
setDayOfMonth(dayOfMonth, animated: false)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Set the date displayed on the picker. This does not trigger UIControlEventValueChanged
///
/// - Parameters:
/// - date: The new date to be displayed/selected in the picker
/// - animated: Whether to animate the change to the new date
func setDate(_ date: Date, animated: Bool) {
let newDate = date.rounded(toCalendarUnits: [.year, .month, .day, .hour, .minute])
guard newDate != self.date else {
return
}
self.date = newDate
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
let amPM: MSDateTimePickerViewAMPM = dateComponents.hour! > 11 ? .pm : .am
componentsByType[.date]?.select(item: calendar.startOfDay(for: date), animated: animated, userInitiated: false)
componentsByType[.month]?.select(item: dateComponents.month, animated: animated, userInitiated: false)
componentsByType[.day]?.select(item: dateComponents.day, animated: animated, userInitiated: false)
componentsByType[.year]?.select(item: dateComponents.year, animated: animated, userInitiated: false)
componentsByType[.timeAMPM]?.select(item: amPM, animated: animated, userInitiated: false)
componentsByType[.timeHour]?.select(item: dateComponents.hour, animated: animated, userInitiated: false)
componentsByType[.timeMinute]?.select(item: dateComponents.minute, animated: animated, userInitiated: false)
}
func setDayOfMonth(_ dayOfMonth: MSDayOfMonth, animated: Bool) {
self.dayOfMonth = dayOfMonth
componentsByType[.weekOfMonth]?.select(item: dayOfMonth.weekOfMonth, animated: animated, userInitiated: false)
componentsByType[.dayOfWeek]?.select(item: dayOfMonth.dayOfWeek, animated: animated, userInitiated: false)
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return MSDateTimePickerViewLayout.sizeThatFits(size, mode: mode)
}
override func layoutSubviews() {
super.layoutSubviews()
// Compute ratio to ideal width
let idealWidth = sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)).width
let widthRatio = (width - 2 * MSDateTimePickerViewLayout.horizontalPadding) / (idealWidth - 2 * MSDateTimePickerViewLayout.horizontalPadding)
// Compute components width based on the ratio of this width to ideal width
let componentWidths: [CGFloat] = componentTypes.map {
let componentIdealWidth = MSDateTimePickerViewLayout.componentWidths[$0] ?? 0
return floor(componentIdealWidth * widthRatio)
}
// Layout components
var x: CGFloat = MSDateTimePickerViewLayout.horizontalPadding
for (index, type) in componentTypes.enumerated() {
guard let component = componentsByType[type] else {
continue
}
let viewWidth = componentWidths[index]
component.view.frame = CGRect(x: x, y: 0, width: viewWidth, height: height)
// Make sure views are all setup before setting date at the bottom of the function
component.view.layoutIfNeeded()
x += viewWidth
}
let lineOffset = round((height - MSDateTimePickerViewComponentCell.idealHeight - 2 * selectionTopSeparator.height) / 2)
selectionTopSeparator.frame = CGRect(x: 0, y: lineOffset, width: width, height: selectionTopSeparator.height)
selectionBottomSeparator.frame = CGRect(
x: 0,
y: height - lineOffset - selectionBottomSeparator.height,
width: width,
height: selectionBottomSeparator.height
)
gradientLayer.locations = [0, NSNumber(value: Float(lineOffset / height)), NSNumber(value: Float((height - lineOffset) / height)), 1]
gradientLayer.frame = bounds
setDate(date, animated: false)
setDayOfMonth(dayOfMonth, animated: false)
flipSubviewsForRTL()
}
private func type(of component: MSDateTimePickerViewComponent) -> MSDateTimePickerViewComponentType? {
return componentsByType.first(where: { $1 == component })?.key
}
private func updateDate() {
let calendar = Calendar.sharedCalendarWithTimeZone(nil)
var dateComponents = DateComponents()
dateComponents.hour = componentsByType[.timeHour]?.selectedItem as? Int
dateComponents.minute = componentsByType[.timeMinute]?.selectedItem as? Int
if let date = componentsByType[.date]?.selectedItem as? Date {
let components = calendar.dateComponents([.year, .month, .day], from: date)
dateComponents.year = components.year
dateComponents.month = components.month
dateComponents.day = components.day
}
if let year = componentsByType[.year]?.selectedItem as? Int {
dateComponents.year = year
}
if let month = componentsByType[.month]?.selectedItem as? Int {
dateComponents.month = month
}
if let dayComponent = componentsByType[.day], let day = dayComponent.selectedItem as? Int {
// In case the day is greater than the number of days for a given month, create a testDate to find the max. We'll use the max day for that month if current day is greater.
// Ex: Feb 29, 2016 -> Feb 29, 2017 is invalid, so we would instead use Feb 28, 2017
dateComponents.day = 1
if let testDate = calendar.date(from: dateComponents) {
let newDay = min(calendar.range(of: .day, in: .month, for: testDate)?.count ?? 28, day)
dateComponents.day = newDay
// Update date picker in case the number of days for that month has changed
if let dataSource = dayComponent.dataSource as? MSDateTimePickerViewDataSourceWithDate {
dataSource.date = testDate
if let indexPath = dataSource.indexPath(forItem: day) {
dayComponent.reloadData()
dayComponent.view.layoutIfNeeded()
dayComponent.select(indexPath: indexPath, animated: false, userInitiated: false)
}
}
} else {
dateComponents.day = day
}
}
if let amPM = componentsByType[.timeAMPM]?.selectedItem as? MSDateTimePickerViewAMPM {
var hour = dateComponents.hour
switch amPM {
case .am:
hour = hour == 12 ? 0 : hour
case .pm:
hour = hour! == 12 ? hour : hour! + 12
}
dateComponents.hour = hour
}
date = calendar.date(from: dateComponents) ?? date
let weekOfMonth = componentsByType[.weekOfMonth]?.selectedItem as? MSWeekOfMonth ?? dayOfMonth.weekOfMonth
let dayOfWeek = componentsByType[.dayOfWeek]?.selectedItem as? MSDayOfWeek ?? dayOfMonth.dayOfWeek
dayOfMonth = MSDayOfMonth(weekOfMonth: weekOfMonth, dayOfWeek: dayOfWeek)
sendActions(for: .valueChanged)
}
private func updateHourForAMPM() {
guard let amPM = componentsByType[.timeAMPM]?.selectedItem as? MSDateTimePickerViewAMPM else {
return
}
guard var hour = componentsByType[.timeHour]?.selectedItem as? Int else {
fatalError("updateHourForAMPM > hour value not found")
}
switch amPM {
case .am:
hour = hour >= 12 ? hour - 12 : hour
case .pm:
hour = hour >= 12 ? hour : hour + 12
}
componentsByType[.timeHour]?.select(item: hour, animated: false, userInitiated: false)
}
}
// MARK: - MSDateTimePickerView: MSDateTimePickerViewComponentDelegate
extension MSDateTimePickerView: MSDateTimePickerViewComponentDelegate {
func dateTimePickerComponentDidScroll(_ component: MSDateTimePickerViewComponent, userInitiated: Bool) {
guard let type = type(of: component) else {
assertionFailure("dateTimePickerComponent > component not found")
return
}
// Scrolling through hours in 12 hours format
if type == .timeHour {
guard userInitiated, let indexPath = component.tableView.middleIndexPath, componentTypes.contains(.timeAMPM) else {
return
}
guard let amPMComponent = componentsByType[.timeAMPM] else {
fatalError("dateTimePickerComponent > amPM value not found")
}
// Switch between am and pm every cycle
let moduloIsEven = (indexPath.row / 12) % 2 == 0
let newValue: MSDateTimePickerViewAMPM = moduloIsEven ? .am : .pm
amPMComponent.select(item: newValue, animated: true, userInitiated: false)
}
}
func dateTimePickerComponent(_ component: MSDateTimePickerViewComponent, didSelectItemAtIndexPath indexPath: IndexPath, userInitiated: Bool) {
if userInitiated {
if type(of: component) == .timeAMPM {
updateHourForAMPM()
}
updateDate()
}
}
/**
* Getting accessibility value on demand is tricky. Components don't know the full date. They only know their
* components. And the row has not been selected yet when the accessibility value is asked for. Therefore, the
* components send the component info that Cocoa asks the accessibility value for. Then the Picker computes
* the date and sends back the availability accessibility value for it
*
* In summary, this can be used to override the accessibility value for the entire view based on the date rather than individual components.
*/
func dateTimePickerComponent(_ component: MSDateTimePickerViewComponent, accessibilityValueForDateComponents dateComponents: DateComponents?, originalValue: String?) -> String? {
guard let delegate = delegate else {
return originalValue
}
// Create date from received components.
// Accessibility value is asked by Cocoa before the row is selected. So we need another way of knowing the current date
// When is about to change and Cocoa asks the accessibility value for it, we get the date components of this row to compute the new date
let calendar = Calendar.current
var currentDateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
if let dateComponents = dateComponents {
currentDateComponents.year = dateComponents.year ?? currentDateComponents.year
currentDateComponents.month = dateComponents.month ?? currentDateComponents.month
currentDateComponents.day = dateComponents.day ?? currentDateComponents.day
currentDateComponents.hour = dateComponents.hour ?? currentDateComponents.hour
currentDateComponents.minute = dateComponents.minute ?? currentDateComponents.minute
}
// Hours and AM/PM are different components. Therefore they don't know each other and can't compute the 24Hour time by themselves.
// We compute this here.
if var amPM = componentsByType[.timeAMPM]?.selectedItem as? MSDateTimePickerViewAMPM {
guard var hour = currentDateComponents.hour else {
assertionFailure("Invalid date")
return nil
}
if let era = dateComponents?.era {
// Hack for AM/PM. The AM/PM row is stored in "era" of date components
amPM = era == 0 ? .am : .pm
}
// Offset the hour so that it is the correct 24Hour
switch amPM {
case .am:
hour = hour >= 12 ? hour - 12 : hour
case .pm:
hour = hour >= 12 ? hour : hour + 12
}
currentDateComponents.hour = hour
}
guard let date = calendar.date(from: currentDateComponents) else {
assertionFailure("Invalid date")
return nil
}
return delegate.dateTimePickerView(self, accessibilityValueOverwriteForDate: date, originalValue: originalValue)
}
}
| 43.352113 | 183 | 0.664003 |
e566488de7af3d9cd99432c1b6099b7a569433f6 | 1,820 | //
// Shell.swift
// SquirrelToolBox
//
// Created by Filip Klembara on 7/30/17.
//
//
import Foundation
import PathKit
struct ShellResult: CustomStringConvertible {
let output: String
let status: Int32
let description: String
init(status: Int32, output: String) {
self.output = output
self.status = status
self.description = "\(status)\n\(output)"
}
}
/// Shell command with stored stderr and setout to variable
///
/// - Parameters:
/// - launchPath: launchpath
/// - executable: executable name
/// - arguments: arguments
/// - Returns: `ShellResult` containing stderr, stdout and status code of shell command
func shellWithOutput(
launchPath: Path,
executable: String,
arguments: [String] = []) -> ShellResult {
let task = Process()
task.launchPath = launchPath.absolute().description
task.arguments = [executable] + arguments
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
task.waitUntilExit()
let output = String(
data: pipe.fileHandleForReading.readDataToEndOfFile(),
encoding: .utf8) ?? ""
return ShellResult(status: task.terminationStatus, output: output)
}
/// Shell command with classic stderr and stdout
///
/// - Parameters:
/// - launchPath: launchpath
/// - executable: executable name
/// - arguments: arguments
/// - Returns: status code
func shell(launchPath: Path, executable: String, arguments: [String] = []) -> Int32 {
let task = Process()
task.launchPath = launchPath.absolute().description
task.arguments = [executable] + arguments
task.standardOutput = FileHandle.standardOutput
task.standardError = FileHandle.standardError
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
| 27.164179 | 87 | 0.676374 |
f7350253a7eb21d90baa2779f22e3baf56167e36 | 2,268 | //===--- LifetimeTracked.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that tracks the number of live instances.
///
/// To be useful in more contexts, `LifetimeTracked` conforms to various
/// protocols in trivial ways.
///
/// `LifetimeTracked` is useful to check for leaks in algorithms and data
/// structures. `StdlibUnittest` harness automatically checks that after each
/// test has done executing, no `LifetimeTracked` instances exist.
public final class LifetimeTracked {
public init(_ value: Int, identity: Int = 0) {
LifetimeTracked.instances += 1
LifetimeTracked._nextSerialNumber += 1
serialNumber = LifetimeTracked._nextSerialNumber
self.value = value
self.identity = identity
}
deinit {
assert(serialNumber > 0, "double destruction!")
LifetimeTracked.instances -= 1
serialNumber = -serialNumber
}
public static var instances: Int = 0
internal static var _nextSerialNumber = 0
public let value: Int
public var identity: Int
public var serialNumber: Int = 0
}
extension LifetimeTracked : Equatable {
public static func == (x: LifetimeTracked, y: LifetimeTracked) -> Bool {
return x.value == y.value
}
}
extension LifetimeTracked : Hashable {
public var hashValue: Int {
return value
}
}
extension LifetimeTracked : Strideable {
public func distance(to other: LifetimeTracked) -> Int {
return self.value.distance(to: other.value)
}
public func advanced(by n: Int) -> LifetimeTracked {
return LifetimeTracked(self.value.advanced(by: n))
}
}
extension LifetimeTracked : CustomStringConvertible {
public var description: String {
assert(serialNumber > 0, "dead Tracked!")
return value.description
}
}
public func < (x: LifetimeTracked, y: LifetimeTracked) -> Bool {
return x.value < y.value
}
| 29.842105 | 80 | 0.677249 |
e258c6d99aa4cb23b68a5cad92a9691a1edd85f8 | 910 | //
// SelectedUserModelStream.swift
// RIBsReactorKit
//
// Created by Elon on 2020/12/20.
// Copyright © 2020 Elon. All rights reserved.
//
import RxRelay
import RxSwift
// MARK: - SelectedUserModelStream
protocol SelectedUserModelStream {
var userModel: Observable<UserModel> { get }
}
// MARK: - MutableSelectedUserModelStream
protocol MutableSelectedUserModelStream: SelectedUserModelStream {
func updateSelectedUserModel(by userModel: UserModel)
}
// MARK: - SelectedUserModelStreamImpl
final class SelectedUserModelStreamImpl: MutableSelectedUserModelStream {
// MARK: - Properties
var userModel: Observable<UserModel> { self.userModalRelay.asObservable().compactMap { $0 } }
private let userModalRelay = BehaviorRelay<UserModel?>(value: nil)
// MARK: - Internal methods
func updateSelectedUserModel(by userModel: UserModel) {
self.userModalRelay.accept(userModel)
}
}
| 23.333333 | 95 | 0.764835 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.