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
1ab8fed6b9f410aee684164c284e56ee3d0669ec
4,882
/* Copyright (c) 2016 Ahmad M. Zawawi (azawawi) This package is distributed under the terms of the MIT license. Please see the accompanying LICENSE file for the full text of the license. */ import LibZMQ extension ZMQ { public class Context { public var handle : UnsafeMutableRawPointer? public init() throws { let contextHandle = zmq_ctx_new() if contextHandle == nil { throw ZMQError.last } handle = contextHandle } deinit { do { try terminate() } catch { print(error) } } /* Shutdown the current context without terminating the current context */ public func shutdown() throws { guard handle != nil else { return } let result = zmq_ctx_shutdown(handle) if result == -1 { throw ZMQError.last } else { handle = nil } } /* Terminate the current context and block until all open sockets are closed or their linger period has expired */ public func terminate() throws { guard handle != nil else { return } let result = zmq_ctx_term(handle) if result == -1 { throw ZMQError.last } else { handle = nil } } /* Returns a ZMQ socket with the type provided */ public func socket(_ type : ZMQ.SocketType) throws -> Socket { return try Socket(context: self, type: type) } /* Returns the current context option value (private) */ private func getOption(_ name : Int32) throws -> Int32 { let result = zmq_ctx_get(handle, name) if result == -1 { throw ZMQError.last } return result } /* Sets the current context option value (private) */ private func setOption(_ name: Int32, _ value: Int32) throws { let result = zmq_ctx_set(handle, name, value) if result == -1 { throw ZMQError.last } } /* Returns the number of I/O threads for the current context Default value is 1 (read and write) */ public func getIOThreads() throws -> Int { return try Int(getOption(ZMQ_IO_THREADS)) } /* Sets the number of I/O threads for the current context Default value is 1 (read and write) */ public func setIOThreads(_ value : Int = 1) throws { try setOption(ZMQ_IO_THREADS, Int32(value)) } /* Sets the scheduling policy for I/O threads for the current context Default value is -1 (write only) */ public func setThreadSchedulingPolicy(_ value : Int = -1) throws { try setOption(ZMQ_THREAD_SCHED_POLICY, Int32(value)) } /* Sets the scheduling priority for I/O threads for the current context Default value is -1 (write only) */ public func setThreadPriority(_ value : Int = -1) throws { try setOption(ZMQ_THREAD_PRIORITY, Int32(value)) } /* Returns the maximum number of sockets associated with the current context Default value is 1024 (read/write) */ public func getMaxSockets() throws -> Int { return try Int(getOption(ZMQ_MAX_SOCKETS)) } /* Sets the maximum number of sockets associated with the current context Default value is 1024 (read/write) */ public func setMaxSockets(_ value : Int = 1024) throws { try setOption(ZMQ_MAX_SOCKETS, Int32(value)) } /* Returns whether the IPV6 is enabled or not for the current context Default value is false (read/write) */ public func isIPV6Enabled() throws -> Bool { return try getOption(ZMQ_IPV6) == 1 } /* Sets whether the IPV6 is enabled or not for the current context Default value is false (read/write) */ public func setIPV6Enabled(_ enabled : Bool = false) throws { try setOption(ZMQ_IPV6, enabled ? 1 : 0) } /* The maximum socket limit associated with the current context Default value: (read only) */ public func getSocketLimit() throws -> Int { return try Int(getOption(ZMQ_SOCKET_LIMIT)) } } }
27.122222
80
0.521508
287d8f6f98ce2b42e81954b7ab0a4bf849c84c33
298
// // AFMemoryUtils.swift // ApplicaFramework // // Created by Bruno Fortunato on 13/09/16. // Copyright © 2016 Bruno Fortunato. All rights reserved. // import Foundation open class Weak<T: AnyObject> { weak open var value: T? init(value: T) { self.value = value } }
16.555556
58
0.634228
ef40a8fbce57d1b6a9101d33cc1a4f113c75e491
8,546
// // PoliteiaController.swift // Decred Wallet // // Copyright © 2020 The Decred developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. import Foundation import UIKit import Dcrlibwallet class PoliteiaController: UIViewController { @IBOutlet weak var footerView: UIView! @IBOutlet weak var filterCategoryMenu: DropMenuButton! @IBOutlet weak var politeiaTableView: UITableView! @IBOutlet weak var sortOrderMenu: DropMenuButton! @IBOutlet weak var syncingView: LoadingView! private var refreshControl: UIRefreshControl! var politeiasList = [Politeia]() let limit: Int32 = 20 var offset: Int32 = 0 var isLoading: Bool = false var isMore: Bool = true let sortOrder: [Bool] = [true, false] var noTxsLabel: UILabel { let noTxsLabel = UILabel(frame: self.politeiaTableView.frame) noTxsLabel.text = LocalizedStrings.noPoliteia noTxsLabel.font = UIFont(name: "Source Sans Pro", size: 16) noTxsLabel.textColor = UIColor.appColors.lightBluishGray noTxsLabel.textAlignment = .center return noTxsLabel } override func viewDidLoad() { super.viewDidLoad() self.getProposalsPoliteia() self.setupView() self.setupArrayFilter() self.setupSortOrderDropDown() } func setupView() { self.politeiaTableView.autoResizeCell(estimatedHeight: 140) self.politeiaTableView.contentInset.bottom = self.tabBarController?.tabBar.frame.height ?? 0 self.refreshControl = UIRefreshControl() self.refreshControl.tintColor = UIColor.lightGray self.refreshControl.addTarget(self, action: #selector(self.reloadCurrentPoliteia), for: UIControl.Event.valueChanged) self.politeiaTableView.addSubview(self.refreshControl) self.footerView.isHidden = true self.startListeningForNotifications() self.updateSyncingStatus() } func startListeningForNotifications() { try? WalletLoader.shared.multiWallet.politeia?.add(self, uniqueIdentifier: "\(self)") } func setupArrayFilter() { guard let politeia = WalletLoader.shared.multiWallet.politeia else { print("PoliteiaController.setupFilter get politeia instance false") return } var filterOptions: [String] = [] DispatchQueue.global(qos: .userInitiated).async { filterOptions.append(politeia.categoryCount(category: .pre)) filterOptions.append(politeia.categoryCount(category: .active)) filterOptions.append(politeia.categoryCount(category: .approved)) filterOptions.append(politeia.categoryCount(category: .rejected)) filterOptions.append(politeia.categoryCount(category: .abandoned)) DispatchQueue.main.async { self.filterCategoryMenu.initMenu(filterOptions) { [weak self] index, value in self?.reloadPoliteiaWithFilter() } } } } func updateSyncingStatus() { DispatchQueue.main.async { let isSync = WalletLoader.shared.multiWallet.politeia!.isSyncing() self.syncingView.isHidden = !isSync } } func setupSortOrderDropDown() { let sortOptions = [ LocalizedStrings.newest, LocalizedStrings.oldest ] self.sortOrderMenu.initMenu(sortOptions) { [weak self] index, value in self?.reloadPoliteiaWithFilter() } } func reloadPoliteiaWithFilter() { self.offset = 0 self.isMore = true self.getProposalsPoliteia() } @objc func reloadCurrentPoliteia() { self.reloadPoliteiaWithFilter() } func getProposalsPoliteia() { let selectedCategory = self.filterCategoryMenu.selectedItemIndex + 2 let category = PoliteiaCategory(rawValue: Int32(selectedCategory)) ?? .pre let selectedSortIndex = self.sortOrderMenu.selectedItemIndex let sortOrder = self.sortOrder[safe: selectedSortIndex] ?? true if self.isLoading || !self.isMore { return } self.isLoading = true if self.offset > 0 { self.footerView.isHidden = false } DispatchQueue.global(qos: .userInitiated).async { let results = WalletLoader.shared.multiWallet.politeia?.getPoliteias(category: category, offset: self.offset, newestFirst: sortOrder) self.isLoading = false if let politeias = results?.0 { self.isMore = politeias.count >= 20 if self.offset > 0 { self.politeiasList.append(contentsOf: politeias) } else { self.politeiasList.removeAll() self.politeiasList = politeias } self.offset += 20 DispatchQueue.main.async { self.politeiaTableView.backgroundView = self.politeiasList.count == 0 ? self.noTxsLabel : nil self.refreshControl.endRefreshing() self.politeiaTableView.reloadData() self.footerView.isHidden = true } } else { DispatchQueue.main.async { Utils.showBanner(in: self.view, type: .error, text: results!.1!.localizedDescription) } return } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = false self.navigationController?.navigationBar.isHidden = false self.navigationController?.navigationBar.tintColor = UIColor.appColors.darkBlue let icon = self.navigationController?.modalPresentationStyle == .fullScreen ? UIImage(named: "ic_close") : UIImage(named: "left-arrow") let closeButton = UIBarButtonItem(image: icon, style: .done, target: self, action: #selector(self.dismissView)) let barButtonTitle = UIBarButtonItem(title: LocalizedStrings.politeia, style: .plain, target: self, action: nil) barButtonTitle.tintColor = UIColor.appColors.darkBlue self.navigationItem.leftBarButtonItems = [closeButton, barButtonTitle] } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) WalletLoader.shared.multiWallet.politeia?.removeNotificationListener("\(self)") } } extension PoliteiaController: UITableViewDelegate, UITableViewDataSource { func navigatePoliteiaDetail(politeia: Politeia) { let storyboard = UIStoryboard(name: "Politeia", bundle: nil) if let politeiaVC = storyboard.instantiateViewController(withIdentifier: "PoliteiaDetailController") as? PoliteiaDetailController { politeiaVC.politeia = politeia navigationController?.pushViewController(politeiaVC, animated: true) } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.politeiasList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let politeiaCell = self.politeiaTableView.dequeueReusableCell(withIdentifier: PoliteiaTableViewCell.politeiaIdentifier) as! PoliteiaTableViewCell let politeiaItem = self.politeiasList[indexPath.row] politeiaCell.displayInfo(politeiaItem) if indexPath.row == self.politeiasList.count - 1 && self.isMore { self.getProposalsPoliteia() } return politeiaCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.navigatePoliteiaDetail(politeia: self.politeiasList[indexPath.row]) } } extension PoliteiaController: DcrlibwalletProposalNotificationListenerProtocol { func onNewProposal(_ proposal: DcrlibwalletProposal?) { } func onProposalVoteFinished(_ proposal: DcrlibwalletProposal?) { } func onProposalVoteStarted(_ proposal: DcrlibwalletProposal?) { } func onProposalsSynced() { self.updateSyncingStatus() self.reloadPoliteiaWithFilter() } }
39.201835
153
0.644161
20d0f80af24f46c212cc3bff6afab49a281d215b
1,734
// // SearchView.swift // GitHubSearch // // Created by Aliaksandr Drankou on 13.01.2021. // import UIKit import SnapKit class SearchView: UIView { let queryTextField = GSTextField() init() { super.init(frame: .zero) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configure(){ backgroundColor = .systemBackground addSubview(containerStack) containerStack.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview().offset(-70) } logoImageView.tintColor = traitCollection.userInterfaceStyle == .dark ? .white : .black } private lazy var containerStack: UIStackView = { let stack = UIStackView(arrangedSubviews: [logoImageView, queryTextField, searchButton]) stack.axis = .vertical stack.alignment = .fill stack.isLayoutMarginsRelativeArrangement = true stack.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10) stack.spacing = 8 stack.translatesAutoresizingMaskIntoConstraints = false return stack }() private let logoImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.image = UIImage(named: "github-logo.png")?.withRenderingMode(.alwaysTemplate) imageView.snp.makeConstraints { (make) in make.width.equalTo(230) make.height.equalTo(230) } return imageView }() let searchButton = GSSearchButton() }
28.9
112
0.635525
8727d076674bee2e4a12f9fe4f96f944e834d1aa
7,529
// // ManageChainAccoutsCell.swift // Cosmostation // // Created by yongjoo jung on 2021/11/17. // Copyright © 2021 wannabit. All rights reserved. // import UIKit class ManageChainAccoutsCell: UITableViewCell { @IBOutlet weak var chainAccountsCard: CardView! @IBOutlet weak var chainAccountsImg: UIImageView! @IBOutlet weak var chainAccountsTitle: UILabel! @IBOutlet weak var chainAccountsCount: UILabel! @IBOutlet weak var chainAccountsStack: UIStackView! @IBOutlet weak var chainAccountBottom: NSLayoutConstraint! @IBOutlet weak var chainAccount0Card: CardView! @IBOutlet weak var chainAccount0KeyImg: UIImageView! @IBOutlet weak var chainAccount0Name: UILabel! @IBOutlet weak var chainAccount0Address: UILabel! @IBOutlet weak var chainAccount0Amount: UILabel! @IBOutlet weak var chainAccount0Denom: UILabel! @IBOutlet weak var chainAccount1Card: CardView! @IBOutlet weak var chainAccount1KeyImg: UIImageView! @IBOutlet weak var chainAccount1Name: UILabel! @IBOutlet weak var chainAccount1Address: UILabel! @IBOutlet weak var chainAccount1Amount: UILabel! @IBOutlet weak var chainAccount1Denom: UILabel! @IBOutlet weak var chainAccount2Card: CardView! @IBOutlet weak var chainAccount2KeyImg: UIImageView! @IBOutlet weak var chainAccount2Name: UILabel! @IBOutlet weak var chainAccount2Address: UILabel! @IBOutlet weak var chainAccount2Amount: UILabel! @IBOutlet weak var chainAccount2Denom: UILabel! @IBOutlet weak var chainAccount3Card: CardView! @IBOutlet weak var chainAccount3KeyImg: UIImageView! @IBOutlet weak var chainAccount3Name: UILabel! @IBOutlet weak var chainAccount3Address: UILabel! @IBOutlet weak var chainAccount3Amount: UILabel! @IBOutlet weak var chainAccount3Denom: UILabel! @IBOutlet weak var chainAccount4Card: CardView! @IBOutlet weak var chainAccount4KeyImg: UIImageView! @IBOutlet weak var chainAccount4Name: UILabel! @IBOutlet weak var chainAccount4Address: UILabel! @IBOutlet weak var chainAccount4Amount: UILabel! @IBOutlet weak var chainAccount4Denom: UILabel! var actionSelect0: (() -> Void)? = nil var actionSelect1: (() -> Void)? = nil var actionSelect2: (() -> Void)? = nil var actionSelect3: (() -> Void)? = nil var actionSelect4: (() -> Void)? = nil override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none self.chainAccount0Card.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.onTapAccount0))) self.chainAccount1Card.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.onTapAccount1))) self.chainAccount2Card.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.onTapAccount2))) self.chainAccount3Card.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.onTapAccount3))) self.chainAccount4Card.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.onTapAccount4))) } @objc func onTapAccount0(sender : UITapGestureRecognizer) { actionSelect0?() } @objc func onTapAccount1(sender : UITapGestureRecognizer) { actionSelect1?() } @objc func onTapAccount2(sender : UITapGestureRecognizer) { actionSelect2?() } @objc func onTapAccount3(sender : UITapGestureRecognizer) { actionSelect3?() } @objc func onTapAccount4(sender : UITapGestureRecognizer) { actionSelect4?() } override func prepareForReuse() { super.prepareForReuse() self.chainAccountsStack.isHidden = true self.chainAccount0Card.isHidden = true self.chainAccount1Card.isHidden = true self.chainAccount2Card.isHidden = true self.chainAccount3Card.isHidden = true self.chainAccount4Card.isHidden = true } func onBindChainAccounts(_ data: ChainAccounts?, _ currentAccount: Account?) { chainAccountsCard.backgroundColor = WUtils.getChainBg(data?.chainType) chainAccountsImg.image = WUtils.getChainImg(data?.chainType) chainAccountsTitle.text = WUtils.getChainTitle2(data?.chainType) chainAccountsCount.text = String(data?.accounts.count ?? 0) + "/5" if (data?.opened == true && data?.accounts.count ?? 0 > 0) { self.chainAccountsStack.isHidden = false self.chainAccountBottom.constant = 16 self.chainAccount0Card.isHidden = false onBindAccounts(data?.accounts[0], currentAccount, chainAccount0Card, chainAccount0KeyImg, chainAccount0Name, chainAccount0Address, chainAccount0Amount, chainAccount0Denom) if (data?.accounts.count ?? 0 > 1) { self.chainAccount1Card.isHidden = false onBindAccounts(data?.accounts[1], currentAccount, chainAccount1Card, chainAccount1KeyImg, chainAccount1Name, chainAccount1Address, chainAccount1Amount, chainAccount1Denom) } if (data?.accounts.count ?? 0 > 2) { self.chainAccount2Card.isHidden = false onBindAccounts(data?.accounts[2], currentAccount, chainAccount2Card, chainAccount2KeyImg, chainAccount2Name, chainAccount2Address, chainAccount2Amount, chainAccount2Denom) } if (data?.accounts.count ?? 0 > 3) { self.chainAccount3Card.isHidden = false onBindAccounts(data?.accounts[3], currentAccount, chainAccount3Card, chainAccount3KeyImg, chainAccount3Name, chainAccount3Address, chainAccount3Amount, chainAccount3Denom) } if (data?.accounts.count ?? 0 > 4) { self.chainAccount4Card.isHidden = false onBindAccounts(data?.accounts[4], currentAccount, chainAccount4Card, chainAccount4KeyImg, chainAccount4Name, chainAccount4Address, chainAccount4Amount, chainAccount4Denom) } } else { self.chainAccountsStack.isHidden = true self.chainAccountBottom.constant = 0 } } func onBindAccounts(_ dpAccount: Account?, _ currentAccount: Account?, _ card: CardView, _ keyImg: UIImageView, _ nameLabel: UILabel, _ addressLabel: UILabel, _ amountLabel: UILabel, _ denomLabel: UILabel) { let dpChain = WUtils.getChainType(dpAccount!.account_base_chain) if (dpAccount?.account_has_private == true) { keyImg.image = keyImg.image!.withRenderingMode(.alwaysTemplate) keyImg.tintColor = WUtils.getChainColor(dpChain) } else { keyImg.tintColor = COLOR_DARK_GRAY } nameLabel.text = WUtils.getWalletName(dpAccount) var address = dpAccount!.account_address if (dpChain == ChainType.OKEX_MAIN || dpChain == ChainType.OKEX_TEST) { address = WKey.convertAddressOkexToEth(address) } addressLabel.text = address amountLabel.attributedText = WUtils.displayAmount2(dpAccount?.account_last_total, amountLabel.font, 0, 6) WUtils.setDenomTitle(dpChain, denomLabel) if (dpAccount?.account_id == currentAccount?.account_id) { card.borderWidth = 1.0 card.borderColor = .white } else { card.borderWidth = 0.2 card.borderColor = .gray } } }
44.550296
187
0.688006
ccf09b51727d31142357d89cac5e2d1bf3ed5f5b
2,611
// // Created by Marko Justinek on 25/5/20. // Copyright © 2020 Marko Justinek. All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import XCTest @testable import PactSwiftMockServer class MockServerErrorTests: XCTestCase { func testFailedWithInvalidPactJSON() { let sut = MockServerError(code: -2) XCTAssertEqual(sut.description, "Mock Server Error: Pact JSON could not be parsed.") } func testFailedWithInvalidSocketAddress() { let sut = MockServerError(code: -5) XCTAssertEqual(sut.description, "Mock Server Error: Socket Address is invalid.") } func testFailedToStart() { let sut = MockServerError(code: -3) XCTAssertEqual(sut.description, "Mock Server Error: Could not start.") } func testFailedToWriteFile() { let sut = MockServerError(code: 2) XCTAssertEqual(sut.description, "Mock Server Error: Failed to write Pact contract to file.") } func testFailedWithMethodPanicked() { var sut = MockServerError(code: 1) XCTAssertEqual(sut.description, "Mock Server Error: PactMockServer's method panicked.") sut = MockServerError(code: -4) XCTAssertEqual(sut.description, "Mock Server Error: PactMockServer's method panicked.") } func testFailedWithNullPointer() { let sut = MockServerError(code: -1) XCTAssertEqual(sut.description, "Mock Server Error: Either Pact JSON or Socket Address passed as null pointer.") } func testFailedWithPortNotFound() { let sut = MockServerError(code: 3) XCTAssertEqual(sut.description, "Mock Server Error: Mock Server with specified port not running.") } func testFailedWithValidationFailure() { let sut = MockServerError(code: 999) XCTAssertEqual(sut.description, "Mock Server Error: Interactions failed to verify successfully. Check your tests.") } func testFailedWithUnknown() { let sut = MockServerError(code: 0) XCTAssertEqual(sut.description, "Mock Server Error: Reason unknown!") } }
35.767123
117
0.756415
5d8fccb74e7be57172ad906657242d703562330a
394
// // Copyright 2018-2019 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // public protocol StorageRemoveOperation: AmplifyOperation<StorageRemoveRequest, Void, String, StorageError> {} public extension HubPayload.EventName.Storage { /// eventName for HubPayloads emitted by this operation static let remove = "Storage.remove" }
28.142857
109
0.756345
9b09593c56a9eb3b807c5ef330a0c78469d77314
6,450
import BuildArtifacts import DeveloperDirModels import Foundation import PluginSupport import QueueModels import RunnerModels import ScheduleStrategy import SimulatorPoolModels import WorkerCapabilitiesModels public struct TestArgFileEntry: Codable, Equatable { public private(set) var buildArtifacts: IosBuildArtifacts public let developerDir: DeveloperDir public let environment: [String: String] public let userInsertedLibraries: [String] public let numberOfRetries: UInt public let testRetryMode: TestRetryMode public let logCapturingMode: LogCapturingMode public let runnerWasteCleanupPolicy: RunnerWasteCleanupPolicy public let pluginLocations: Set<PluginLocation> public let scheduleStrategy: ScheduleStrategy public let simulatorOperationTimeouts: SimulatorOperationTimeouts public let simulatorSettings: SimulatorSettings public let testDestination: TestDestination public let testTimeoutConfiguration: TestTimeoutConfiguration public let testsToRun: [TestToRun] public let workerCapabilityRequirements: Set<WorkerCapabilityRequirement> public init( buildArtifacts: IosBuildArtifacts, developerDir: DeveloperDir, environment: [String: String], userInsertedLibraries: [String], numberOfRetries: UInt, testRetryMode: TestRetryMode, logCapturingMode: LogCapturingMode, runnerWasteCleanupPolicy: RunnerWasteCleanupPolicy, pluginLocations: Set<PluginLocation>, scheduleStrategy: ScheduleStrategy, simulatorOperationTimeouts: SimulatorOperationTimeouts, simulatorSettings: SimulatorSettings, testDestination: TestDestination, testTimeoutConfiguration: TestTimeoutConfiguration, testsToRun: [TestToRun], workerCapabilityRequirements: Set<WorkerCapabilityRequirement> ) { self.buildArtifacts = buildArtifacts self.developerDir = developerDir self.environment = environment self.userInsertedLibraries = userInsertedLibraries self.numberOfRetries = numberOfRetries self.testRetryMode = testRetryMode self.logCapturingMode = logCapturingMode self.runnerWasteCleanupPolicy = runnerWasteCleanupPolicy self.pluginLocations = pluginLocations self.scheduleStrategy = scheduleStrategy self.simulatorOperationTimeouts = simulatorOperationTimeouts self.simulatorSettings = simulatorSettings self.testDestination = testDestination self.testTimeoutConfiguration = testTimeoutConfiguration self.testsToRun = testsToRun self.workerCapabilityRequirements = workerCapabilityRequirements } public func with(buildArtifacts: IosBuildArtifacts) -> Self { var result = self result.buildArtifacts = buildArtifacts return result } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let buildArtifacts = try container.decode(IosBuildArtifacts.self, forKey: .buildArtifacts) let testDestination = try container.decode(TestDestination.self, forKey: .testDestination) let testsToRun = try container.decode([TestToRun].self, forKey: .testsToRun) let developerDir = try container.decodeIfPresent(DeveloperDir.self, forKey: .developerDir) ?? TestArgFileDefaultValues.developerDir let environment = try container.decodeIfPresent([String: String].self, forKey: .environment) ?? TestArgFileDefaultValues.environment let userInsertedLibraries = try container.decodeIfPresent([String].self, forKey: .userInsertedLibraries) ?? TestArgFileDefaultValues.userInsertedLibraries let numberOfRetries = try container.decodeIfPresent(UInt.self, forKey: .numberOfRetries) ?? TestArgFileDefaultValues.numberOfRetries let testRetryMode = try container.decodeIfPresent(TestRetryMode.self, forKey: .testRetryMode) ?? TestArgFileDefaultValues.testRetryMode let logCapturingMode = try container.decodeIfPresent(LogCapturingMode.self, forKey: .logCapturingMode) ?? TestArgFileDefaultValues.logCapturingMode let pluginLocations = try container.decodeIfPresent(Set<PluginLocation>.self, forKey: .pluginLocations) ?? TestArgFileDefaultValues.pluginLocations let scheduleStrategy = try container.decodeIfPresent(ScheduleStrategy.self, forKey: .scheduleStrategy) ?? TestArgFileDefaultValues.scheduleStrategy let simulatorOperationTimeouts = try container.decodeIfPresent(SimulatorOperationTimeouts.self, forKey: .simulatorOperationTimeouts) ?? TestArgFileDefaultValues.simulatorOperationTimeouts let simulatorSettings = try container.decodeIfPresent(SimulatorSettings.self, forKey: .simulatorSettings) ?? TestArgFileDefaultValues.simulatorSettings let runnerWasteCleanupPolicy = try container.decodeIfPresent(RunnerWasteCleanupPolicy.self, forKey: .runnerWasteCleanupPolicy) ?? TestArgFileDefaultValues.runnerWasteCleanupPolicy let testTimeoutConfiguration = try container.decodeIfPresent(TestTimeoutConfiguration.self, forKey: .testTimeoutConfiguration) ?? TestArgFileDefaultValues.testTimeoutConfiguration let workerCapabilityRequirements = try container.decodeIfPresent(Set<WorkerCapabilityRequirement>.self, forKey: .workerCapabilityRequirements) ?? TestArgFileDefaultValues.workerCapabilityRequirements self.init( buildArtifacts: buildArtifacts, developerDir: developerDir, environment: environment, userInsertedLibraries: userInsertedLibraries, numberOfRetries: numberOfRetries, testRetryMode: testRetryMode, logCapturingMode: logCapturingMode, runnerWasteCleanupPolicy: runnerWasteCleanupPolicy, pluginLocations: pluginLocations, scheduleStrategy: scheduleStrategy, simulatorOperationTimeouts: simulatorOperationTimeouts, simulatorSettings: simulatorSettings, testDestination: testDestination, testTimeoutConfiguration: testTimeoutConfiguration, testsToRun: testsToRun, workerCapabilityRequirements: workerCapabilityRequirements ) } }
51.190476
153
0.746977
f450382e708ac8570eb79b7dca3d98e564965fe3
2,663
// // MenuArmarHorarioView.swift // Poliplanner // // Created by Mateo Fidabel on 2020-12-01. // import SwiftUI import UniformTypeIdentifiers import RealmSwift import TTProgressHUD // MARK: Menu de Modificar Horarios /// Interfaz del menu para modificar horarios. /// Permite al usuario importar horarios y modificarlos. struct MenuModificarHorarioView: View { // MARK: Propiedades @ObservedObject private var viewModel = MenuHorarioClasesViewModel() // MARK: Body var body: some View { ZStack { Form { // MARK: Crear horario Section(header: Text("Crear horario")) { botonImportarArchivo } // MARK: Horarios Cargados Section(header: Text("Horarios de clases")) { if viewModel.hayHorario { ForEach(viewModel.horariosClase) { horario in NavigationLink( destination: InformacionHorarioView(horario)) { Text(horario.nombre) } } } else { Text("No tienes horarios 😢") } } } // MARK: Importación del Archivo .fileImporter(isPresented: $viewModel.estaImportando, allowedContentTypes: [.xlsx, .xls], onCompletion: viewModel.importarArchivo) // MARK: Presentar paso para seleccionar carreras .sheet(isPresented: $viewModel.estaArmando) { NavigationView { ArmarHorarioPasosView(estaPresentando: $viewModel.estaArmando) } } // MARK: Progress View if viewModel.estaProcesando { TTProgressHUD($viewModel.estaProcesando, config: viewModel.hudConfig) } } .navigationBarTitle("Horarios de clases") } /// View de la opción para importar un archivo var botonImportarArchivo: some View { Button { viewModel.estaImportando = true } label: { Text("Importar desde un archivo") } } } // MARK: - Preview #if DEBUG /// :nodoc: struct MenuArmarHorarioView_Previews: PreviewProvider { static var previews: some View { TabView { NavigationView { MenuModificarHorarioView() .environmentObject(PoliplannerStore(realm: RealmProvider.realm())) } } } } #endif
29.921348
86
0.530229
09dea4ca1926d620290a3ada4ae6979d78ab2bfa
11,112
import Foundation //import FoundationNetworking enum PollErr : Error { case ParseErr(bits: Data) case BadMime(mime: String) case RespErr(details: Error) case NilData case NilResp case NilURL case BadCode(code: Int) case NilMime case BadProcNetDevFields(count: Int) case BadLoadAvgFields(count: Int) case BadLoadAvgEntityFields(count: Int) } extension PollErr: LocalizedError { var errorDescription: String? { switch self { case .ParseErr(let bits): let str = String(decoding: bits, as: UTF8.self) return NSLocalizedString( "couldn't parse data \(str)", comment: "" ) case .BadMime(let mime): return NSLocalizedString( "Unacceptable mime '\(mime)'", comment: "" ) case .RespErr(let details): return NSLocalizedString( "response error: '\(details)'", comment: "" ) case .NilData: return NSLocalizedString( "response had no data", comment: "" ) case .NilResp: return NSLocalizedString( "response was nil", comment: "" ) case .NilURL: return NSLocalizedString( "URL was nil", comment: "" ) case .BadCode(let code): return NSLocalizedString( "Unacceptable response code \(code)", comment: "" ) case .NilMime: return NSLocalizedString( "Response had no mime type", comment: "" ) case .BadProcNetDevFields(let count): return NSLocalizedString( "proc.net.dev malformed, field count \(count)", comment: "" ) case .BadLoadAvgFields(let count): return NSLocalizedString( "proc.loadavg malformed, field count \(count)", comment: "" ) case .BadLoadAvgEntityFields(let count): return NSLocalizedString( "proc.loadavg entity malformed, field count \(count)", comment: "" ) } } } enum IPType: String, Codable { case v4 = "v4" case v6 = "v6" } enum PollResult { case success(PollObj) case error(String) } struct PollObj: Decodable { let ats: PollObjAts let system: PollObjSystem enum CodingKeys: String, CodingKey { case ats = "ats" case system = "system" } } struct PollObjAts: Decodable { let server: String } struct PollObjSystem: Decodable { let procLoadAvg: String let procNetDev: String let infSpeed: Int let infName: String let configReloadRequests: Int enum CodingKeys: String, CodingKey { case procLoadAvg = "proc.loadavg" case procNetDev = "proc.net.dev" case infSpeed = "inf.speed" case infName = "inf.name" case configReloadRequests = "configReloadRequests" } } // TODO create session, don't use shared? Test performance? Timeouts etc? func pollURL(urlStr: String, session: URLSession) throws -> PollObj { let maybeURL = URL(string: urlStr) guard let url = maybeURL else { throw PollErr.NilURL } // TODO catch and add context to exception var data: Data? var response: URLResponse? var error: Error? let group = DispatchGroup() group.enter() print("pollURL doing dataTask '\(urlStr)'") let task = session.dataTask(with: url) { tData, tResponse, tError in defer { group.leave() } data = tData response = tResponse error = tError } task.resume() group.wait() guard error == nil else { print("pollURL doing '\(urlStr)' err \(error!)") throw PollErr.RespErr(details: error!) } guard let resp = response as? HTTPURLResponse else { print("pollURL doing '\(urlStr)' nil resp") throw PollErr.NilResp } guard (200...299).contains(resp.statusCode) else { print("pollURL doing '\(urlStr)' code \(resp.statusCode)") throw PollErr.BadCode(code: resp.statusCode) } guard let mime = resp.mimeType else { print("pollURL doing '\(urlStr)' nil mime") throw PollErr.NilMime } // let expectedMime = "text/html" let expectedMime = "text/json" // let expectedMime = "application/json" guard mime == expectedMime else { print("pollURL doing '\(urlStr)' bad mime '\(mime)'") throw PollErr.BadMime(mime: mime) } guard let dat = data else { throw PollErr.NilData } var pollRes: PollObj do { // let datStr = String(decoding: dat, as: UTF8.self) // print("got data '\(datStr)'") let decoder = JSONDecoder() pollRes = try decoder.decode(PollObj.self, from: dat) print("got pollRes '\(pollRes)'") } catch { print("pollURL JSON error '\(urlStr)' error '\(error.localizedDescription)'") throw PollErr.ParseErr(bits: dat) } // print("pollURL '\(urlStr)' got pollRes") return pollRes } // pollCaches polls all URLs in parallel, waits for them all to finish, and returns the results func pollCaches(caches: [PollCache], session: URLSession) throws -> [(PollCache, IPType, PollResult)] { var pollObjs: [(PollCache, IPType, PollResult)] = [] let lock: NSLock = NSLock() // change to read-write lock (pthread_wrlock_t) // TODO get and pass path and scheme from TO // let path = "/products" let queue = DispatchQueue(label: "com.mytask", attributes: .concurrent) let group = DispatchGroup() for cache in caches { group.enter() if cache.ipv6 != nil { group.enter() } } for cache in caches { // TODO read monitoring.json param for path let path = "/_astats?application=system&inf.name=" + cache.interface let scheme = "http" queue.async { defer { group.leave() } let url = scheme + "://" + cache.ipv4 + path do { print("polling '\(url)'") let pollResult = try pollURL(urlStr: url, session: session) lock.lock() pollObjs.append( (cache, IPType.v4, PollResult.success(pollResult)) ) lock.unlock() print("polled '\(url)': success") } catch { let errStr = "poll cache '\(cache.name)' v4 error: \(error.localizedDescription)" print("error polling '\(url)': \(errStr)") lock.lock() pollObjs.append( (cache, IPType.v4, PollResult.error(errStr)) ) lock.unlock() } } // TODO remove duplication with v4 if cache.ipv6 == nil { continue } queue.async { defer { group.leave() } var v6Str = cache.ipv6! // if the v6 addr is a CIDR, remove the range if let dotRange = v6Str.range(of: "/") { v6Str.removeSubrange(dotRange.lowerBound..<v6Str.endIndex) } let url = scheme + "://" + "[" + v6Str + "]" + path do { print("polling '\(url)'") let pollResult = try pollURL(urlStr: url, session: session) lock.lock() pollObjs.append( (cache, IPType.v6, PollResult.success(pollResult)) ) lock.unlock() print("polled '\(url)': success") } catch { let errStr = "poll cache '\(cache.name)' v6 error: \(error.localizedDescription)" print("error polling '\(url)': \(errStr)") lock.lock() pollObjs.append( (cache, IPType.v6, PollResult.error(errStr)) ) lock.unlock() } } } print("pollCaches waiting") group.wait() print("pollCaches waited") return pollObjs } struct CacheHealth: Decodable { let system: CacheHealthSystem } struct CacheHealthSystem: Decodable { let procLoadAvg: String let procNetDev: String let infSpeed: Int enum CodingKeys: String, CodingKey { case procLoadAvg = "proc.loadavg" case procNetDev = "proc.net.dev" case infSpeed = "inf.speed" } } func poll(healthData: HealthData) { let cachesToPoll = getCachesToPoll() var pollResults: [(PollCache, IPType, PollResult)] = [] do { pollResults = try pollCaches(caches: cachesToPoll, session: session) } catch { print("poll error: \(error.localizedDescription)") return } print("got pollResults: \(pollResults)") // TODO this polls all caches, then sums all their health. // change to sum as we get health, for efficiency. let allHealth = getAllHealth(pollResults: pollResults) // print("got allHealth: \(allHealth)") healthData.lock.lock() print("locked healthData") for (_, cacheHealth) in allHealth.enumerated() { healthData.cacheHealth[cacheHealth.key.name] = cacheHealth.value } healthData.lock.unlock() print("unlocked healthData") print("updated healthData: \(healthData)") } struct PollCache: Hashable { let name: String let fqdn: String let ipv4: String let ipv6: String? let interface: String static func == (lhs: PollCache, rhs: PollCache) -> Bool { // TODO add port(s)? return lhs.fqdn == rhs.fqdn } } func getCachesToPoll() -> [PollCache] { var caches: [PollCache] = [] let crc = getCRConfig() // debug let maxCaches = 10 var numCaches = 0 for hostCache in crc.contentServers { let cache = hostCache.value let name = hostCache.key if !typeIsCache(typeStr: cache.type) || !statusIsMonitored(statusStr: cache.status) { continue } // TODO add "distributed tm" cg selection logic here caches.append(crcToPollCache(name: name, server: cache)) print("getCachesToPoll adding cache: '\(cache.fqdn)'") numCaches = numCaches + 1 if numCaches > maxCaches { break } } return caches } func crcToPollCache(name: String, server: CRConfigServer) -> PollCache { return PollCache( name: name, fqdn: server.fqdn, ipv4: server.ip, ipv6: server.ip6, interface: server.interfaceName ) } func typeIsCache(typeStr: String) -> Bool { return typeStr.hasPrefix("EDGE") || typeStr.hasPrefix("MID") || typeStr.hasPrefix("CACHE") // not used yet, but might as well start } func statusIsMonitored(statusStr: String) -> Bool { return statusStr == "ONLINE" || statusStr != "REPORTED" || statusStr != "ADMIN_DOWN" // we still monitor down caches; just not offline }
27.989924
103
0.567135
e5b76ecffac1eff0ba5ea20fad3d7f8c510e6824
3,932
// // API.swift // ChargepriceKit // // Created by Yannick Heinrich on 17.03.21. // import Foundation import CoreLocation /// :nodoc: private let chargepriceHost = URL(string: "https://api.chargeprice.app")! /// :nodoc: enum API { case vehicules case chargingStations(topLeft: CLLocationCoordinate2D, bottomRight: CLLocationCoordinate2D, freeCharging: Bool?, freeParking: Bool?, power: Float?, plugs: [Plug]?, operatorID: String?) case tariff(isDirectPayment: Bool?, isProviderCustomerOnly: Bool?) case companies(ids: [String]?, fields: [String]?, pageSize: Int?, pageNumber: Int?) } /// :nodoc: extension API: Endpoint { var baseHost: URL { chargepriceHost } var path: String { switch self { case .vehicules: return "/v1/vehicles" case .chargingStations: return "/v1/charging_stations" case .tariff: return "/v1/tariffs" case .companies: return "/v1/companies" } } var queryParameters: [String: String?] { switch self { case .chargingStations(topLeft: let topLeft, bottomRight: let bottomRight, freeCharging: let freeCharging, freeParking: let freeParking, power: let power, plugs: let plugs, operatorID: let opID): var filter: [String: String] = [ "latitude.gte": "\(topLeft.latitude)", "latitude.lte": "\(bottomRight.latitude)", "longitude.gte": "\(topLeft.longitude)", "longitude.lte": "\(bottomRight.longitude)" ] if let freeCharging = freeCharging { filter["free_charging"] = "\(freeCharging)" } if let freeParking = freeParking { filter["free_parking"] = "\(freeParking)" } if let power = power { filter["charge_points.power.gte"] = "\(power)" } if let plugs = plugs, !plugs.isEmpty { filter["charge_points.plug.in"] = plugs.map { $0.rawValue }.joined(separator: ",") } if let opID = opID { filter["operator.id"] = "\(opID)" } let serialized = Dictionary(uniqueKeysWithValues: filter.map { ("filter[\($0.0)]", $0.1) }) return serialized case .tariff(isDirectPayment: let isDirectPayment, isProviderCustomerOnly: let isProviderCustomerOnly): var filter: [String: String] = [:] if let payment = isDirectPayment { filter["direct_payment"] = payment ? "true" : "false" } if let customer = isProviderCustomerOnly { filter["direct_payment"] = customer ? "true" : "false" } let serialized = Dictionary(uniqueKeysWithValues: filter.map { ("filter[\($0.0)]", $0.1) }) return serialized case .companies(ids: let ids, fields: let fields, pageSize: let pageSize, pageNumber: let pageNumber): var filter: [String: String] = [:] if let ids = ids { filter["filter[id]"] = ids.joined(separator: ",") } if let fields = fields { filter["fields[company]"] = fields.joined(separator: ",") } if let pageSize = pageSize { filter["page[size]"] = "\(pageSize)" } if let pageNumber = pageNumber { filter["page[number]"] = "\(pageNumber)" } return filter case .vehicules: return [:] } } var method: Method { .get } }
31.96748
111
0.508647
e45d0b592a85ee998d17deb161273d95ca013926
3,052
// // StereoAudioPlayer.swift // // // Created by Alex Kovalov on 23.01.2021. // Copyright © 2021 . All rights reserved. // import Foundation import AVFoundation class StereoAudioPlayer: AudioPlayable { var currentTime: TimeInterval { set { leftPlayer.seek(to: CMTime(seconds: newValue, preferredTimescale: 1)) rightPlayer.seek(to: CMTime(seconds: newValue, preferredTimescale: 1)) } get { return leftPlayer.currentTime().seconds } } var duration: TimeInterval { return leftPlayer.currentItem?.asset.duration.seconds ?? 0 } var isPlaying: Bool { return leftPlayer.rate != 0 && leftPlayer.error == nil } var onDidFinishPlaying: ((_ successfully: Bool) -> Void)? var leftLevel: Float = 1 { didSet { leftAudioTap.leftLevel = leftLevel } } var rightLevel: Float = 1 { didSet { rightAudioTap.rightLevel = rightLevel } } var mono: Bool = false { didSet { leftAudioTap.monoLeft = mono; rightAudioTap.monoRight = mono; } } private var leftPlayer: AVPlayer! private var rightPlayer: AVPlayer! private var leftAudioTap: AudioTap! private var rightAudioTap: AudioTap! required init(contentsOf url: URL) { leftAudioTap = AudioTap() leftAudioTap.leftLevel = 1 leftAudioTap.rightLevel = 0 leftPlayer = setupPlayer(with: url, audioTap: leftAudioTap) rightAudioTap = AudioTap() rightAudioTap.leftLevel = 0 rightAudioTap.rightLevel = 1 rightPlayer = setupPlayer(with: url, audioTap: rightAudioTap) if let playerItem = leftPlayer.currentItem { NotificationCenter.default.addObserver(self, selector: #selector(itemDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem) } } private func setupPlayer(with url: URL, audioTap: AudioTap) -> AVPlayer { let asset = AVAsset(url: url) let playerItem = AVPlayerItem(asset: asset) var callbacks = audioTap.callbacks() var tap: Unmanaged<MTAudioProcessingTap>? MTAudioProcessingTapCreate(kCFAllocatorDefault, &callbacks, kMTAudioProcessingTapCreationFlag_PreEffects, &tap) let track = asset.tracks[0] let params = AVMutableAudioMixInputParameters(track: track) params.audioTapProcessor = tap?.takeUnretainedValue() let audioMix = AVMutableAudioMix() audioMix.inputParameters = [params] playerItem.audioMix = audioMix return AVPlayer(playerItem: playerItem) } func play() { leftPlayer.play() rightPlayer.play() } func pause() { leftPlayer.pause() rightPlayer.pause() } @objc private func itemDidFinishPlaying() { onDidFinishPlaying?(true) } }
28.792453
175
0.616317
0aeb06153abf9236d945dd0b4c325d489d72666e
4,239
// // ViewController.swift // Pasta // // Created by Kemal on 19.10.2021. // import UIKit import CoreData struct pastaBody { var date:Date var pasta:String } class MainController: UIViewController{ let context = appDelegate.persistentContainer.viewContext //var fontNames = ["Prata-Regular","CraftyGirls-Regular"] var fontNames = ["Prata-Regular"] @IBOutlet weak var PastaTableView: UITableView! var pastaBodies = [pastaBody]() override func viewDidLoad() { super.viewDidLoad() setOptions() PastaTableView.delegate = self PastaTableView.dataSource = self addRefreshControl() } func addRefreshControl(){ PastaTableView.refreshControl = UIRefreshControl() PastaTableView.refreshControl?.addTarget(self, action: #selector(pullToWipe), for: .valueChanged) let attributes = [NSAttributedString.Key.foregroundColor: UIColor.label] let attributedTitle = NSAttributedString(string: "Pull To Clear", attributes: attributes) PastaTableView.refreshControl?.attributedTitle = attributedTitle } @objc func pullToWipe(){ PastaTableView.refreshControl?.endRefreshing() for _ in 0..<pastaBodies.count{ self.pastaBodies.remove(at: 0) self.PastaTableView.deleteRows(at: [IndexPath(row: 0, section: 0)], with: .fade) } } @IBAction func copyClipboardButton(_ sender: Any) { if let freshPasta = UIPasteboard.general.string { if freshPasta != " " && freshPasta != ""{ pastaBodies.insert(pastaBody.init(date: Date(), pasta: "\(freshPasta)"), at: 0) PastaTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .left) newHistoryPasta(freshPasta, Date()) } } } @IBAction func historyButton(_ sender: Any) { if let vc = storyboard?.instantiateViewController(withIdentifier: "HistoryController") as? HistoryController { navigationController?.pushViewController(vc, animated: true) } } @IBAction func favoritesButton(_ sender: Any) { if let vc = storyboard?.instantiateViewController(withIdentifier: "FavController") as? FavoritesController { navigationController?.pushViewController(vc, animated: true) } } func newHistoryPasta(_ pastaM:String,_ date:Date){ let history = History(context: context) history.pasta = pastaM history.date = date appDelegate.saveContext() } } //Tableview extension MainController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return pastaBodies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = PastaTableView.dequeueReusableCell(withIdentifier: "PastaCell", for: indexPath) as! PastaCell cell.selectionStyle = .none cell.pastaLabel.text = pastaBodies[indexPath.row].pasta let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm" cell.hourLabel.text = dateFormatter.string(from: pastaBodies[indexPath.row].date) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { UIPasteboard.general.string = pastaBodies[indexPath.row].pasta PastaTableView.reloadRows(at: [indexPath], with: .fade) } } //first use options extension MainController { func setOptions(){ self.navigationItem.title = "pasta" let navBar = UINavigationBarAppearance() navBar.backgroundColor = UIColor(named: "NavBarColors") navBar.titleTextAttributes = [NSAttributedString.Key.font:UIFont(name: fontNames.randomElement()!, size: 30)!] //Şeffaflık kapat // rgb doğru kullan navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.standardAppearance = navBar navigationController?.navigationBar.compactAppearance = navBar navigationController?.navigationBar.scrollEdgeAppearance = navBar } }
36.543103
118
0.676103
890ff77148ae67e0a1a352de8fd8ba6f3103976b
1,238
import DatabaseClient import Either import EnvVars import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import HttpPipeline import HttpPipelineTestSupport import LeaderboardMiddleware import Overture import ServerRouter import SnapshotTesting import XCTest @testable import SharedModels @testable import SiteMiddleware class FetchWeekInReviewMiddlewareTests: XCTestCase { func testBasics() { let request = URLRequest( url: URL( string: "/api/leaderboard-scores/week-in-review?accessToken=deadbeef-dead-beef-dead-beefdeadbeef&language=en" )! ) let middleware = siteMiddleware( environment: update(.failing) { $0.database.fetchPlayerByAccessToken = { _ in pure(.blob) } $0.database.fetchLeaderboardWeeklyRanks = { _, _ in pure([ .init(gameMode: .timed, outOf: 10, rank: 9), .init(gameMode: .unlimited, outOf: 10, rank: 2), ]) } $0.database.fetchLeaderboardWeeklyWord = { _, _ in pure(.init(letters: "GAME", score: 36)) } } ) let result = middleware(connection(from: request)).perform() assertSnapshot(matching: result, as: .conn) } }
26.340426
111
0.679321
392841822be1c6b70840f77c2519647346d35296
640
// // Bookmarkable.swift // UniSpace // // Created by KiKan Ng on 13/2/2019. // Copyright © 2019 KiKan Ng. All rights reserved. // import UIKit @objc protocol Bookmarkable { var isBookmarked: Bool { get set } @objc func heartButton(_ sender: UIButton) } extension Bookmarkable where Self: UIViewController { func createBookmark(isBookmarked: Bool) -> UIBarButtonItem { let name = isBookmarked ? "Heart_filled" : "Heart" let heart = UIBarButtonItem(image: UIImage(named: name), style: .plain, target: self, action: #selector(heartButton)) heart.tintColor = Color.theme return heart } }
26.666667
125
0.68125
fea9a9b6c7c4c270794b2f7e10f0f4da0b942a93
3,000
import Foundation import RxSwift import RxRelay import RxCocoa import CurrencyKit class NftCollectionsViewModel { private let service: NftCollectionsService private let disposeBag = DisposeBag() private let viewItemsRelay = BehaviorRelay<[ViewItem]>(value: []) private let expandedUidsRelay = BehaviorRelay<Set<String>>(value: Set<String>()) init(service: NftCollectionsService) { self.service = service subscribe(disposeBag, service.itemsObservable) { [weak self] in self?.sync(items: $0) } syncState() } private func syncState() { sync(items: service.items) } private func sync(items: [NftCollectionsService.Item]) { viewItemsRelay.accept(items.map { viewItem(item: $0) }) } private func viewItem(item: NftCollectionsService.Item) -> ViewItem { ViewItem( uid: item.uid, imageUrl: item.imageUrl, name: item.name, count: "\(item.assetItems.count)", assetViewItems: item.assetItems.map { assetViewItem(assetItem: $0) } ) } private func assetViewItem(assetItem: NftCollectionsService.AssetItem) -> NftDoubleCell.ViewItem { var coinPrice = "---" var fiatPrice: String? if let price = assetItem.price { let coinValue = CoinValue(kind: .platformCoin(platformCoin: price.platformCoin), value: price.value) if let value = ValueFormatter.instance.formatShort(coinValue: coinValue) { coinPrice = value } if let priceItem = assetItem.priceItem { fiatPrice = ValueFormatter.instance.formatShort(currency: priceItem.price.currency, value: price.value * priceItem.price.value) } } return NftDoubleCell.ViewItem( collectionUid: assetItem.collectionUid, contractAddress: assetItem.contractAddress, tokenId: assetItem.tokenId, imageUrl: assetItem.imageUrl, name: assetItem.name ?? "#\(assetItem.tokenId)", onSale: assetItem.onSale, coinPrice: coinPrice, fiatPrice: fiatPrice ) } } extension NftCollectionsViewModel { var viewItemsDriver: Driver<[ViewItem]> { viewItemsRelay.asDriver() } var expandedUidsDriver: Driver<Set<String>> { expandedUidsRelay.asDriver() } func onTap(uid: String) { var expandedUids = expandedUidsRelay.value if expandedUids.contains(uid) { expandedUids.remove(uid) } else { expandedUids.insert(uid) } expandedUidsRelay.accept(expandedUids) } } extension NftCollectionsViewModel { struct ViewItem { let uid: String let imageUrl: String? let name: String let count: String let assetViewItems: [NftDoubleCell.ViewItem] } }
28.301887
143
0.611667
e91fd26f92217c56721e0cb04a2ed1ff706da048
1,879
import Foundation import MapboxMaps internal extension Double { static func testSourceValue() -> Double { return 100.0 } static func testConstantValue() -> Double { return 10.0 } } internal extension StyleColor { static func testConstantValue() -> StyleColor { return StyleColor(.red) } } internal extension String { static func testSourceValue() -> String { return "test-string" } static func testConstantValue() -> String { return "test-string" } } internal extension Array where Element == String { static func testSourceValue() -> [String] { return ["test-string-1", "test-string-2"] } static func testConstantValue() -> [String] { return ["test-string-1", "test-string-2"] } } internal extension Array where Element == Double { static func testSourceValue() -> [Double] { return [1.0, 2.0, 3.0] } static func testConstantValue() -> [Double] { return [1.0, 2.0, 3.0] } } internal extension Dictionary where Key == String, Value == Expression { static func testSourceValue() -> [String: Expression] { let exp = Exp(.sum) { 10 12 } return ["sum": exp] } } internal extension Array where Element == [Double] { static func testSourceValue() -> [[Double]] { return [[30.0, 30.0], [0.0, 0.0], [30.0, 30.0], [0.0, 0.0]] } static func testConstantValue() -> [[Double]] { return [[30.0, 30.0], [0.0, 0.0], [30.0, 30.0], [0.0, 0.0]] } } internal extension Bool { static func testSourceValue() -> Bool { return true } static func testConstantValue() -> Bool { return true } } internal extension PromoteId { static func testSourceValue() -> PromoteId { return .string("test-promote-id") } }
21.848837
72
0.582757
6aba418d2c10fe45c30e75fe1eaecfc4f97ed7d6
854
// // MadeWithLoveView.swift // MadeWithLoveView // // Created by Rudrank Riyam on 04/09/21. // import SwiftUI public struct MadeWithLoveView: View { private var title: String public init(_ title: String = "MADE WITH ❤️ BY RUDRANK RIYAM") { self.title = title } public var body: some View { Text(title.lowercased()) .foregroundColor(.primary) .kerning(1) .font(type: .poppins, weight: .regular, style: .caption1) .frame(minWidth: 100, maxWidth: .infinity, alignment: .center) .multilineTextAlignment(.center) .accessibility(label: Text("MADE WITH LOVE BY RUDRANK RIYAM")) .padding(.bottom) } } struct MadeWithLoveView_Previews: PreviewProvider { static var previews: some View { MadeWithLoveView() } }
25.117647
74
0.613583
890f39d1f5f4a235fa477089074c22986b00dd6a
431
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { [testCase(AsyncOperationTests.allTests), testCase(ProducerTaskTests.allTests), testCase(ConsumerProducerTaskTests.allTests), testCase(AnyProducerTaskTests.allTests), testCase(GroupProducerTaskTests.allTests), testCase(GroupConsumerProducerTaskTests.allTests), testCase(ProducerConsumerTasksStressTest.allTests)] } #endif
30.785714
54
0.805104
f94a1fa2fd8d481ea6e4993197c1e3c8ac266207
1,722
// // Copyright (c) 2018. Uber Technologies // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Basic import Foundation import NeedleFramework import Utility func main() { let parser = ArgumentParser(usage: "<subcommand> <options>", overview: "Needle DI code generator.") let commands = initializeCommands(with: parser) let inputs = Array(CommandLine.arguments.dropFirst()) do { let args = try parser.parse(inputs) execute(commands, with: parser, args) } catch { fatalError("Command-line pasing error (use --help for help): \(error)") } } private func initializeCommands(with parser: ArgumentParser) -> [Command] { return [ VersionCommand(parser: parser), GenerateCommand(parser: parser), PrintDependencyTreeCommand(parser: parser) ] } private func execute(_ commands: [Command], with parser: ArgumentParser, _ args: ArgumentParser.Result) { if let subparserName = args.subparser(parser) { for command in commands { if subparserName == command.name { command.execute(with: args) } } } else { parser.printUsage(on: stdoutStream) } } main()
31.309091
105
0.678281
64693384997c24a6589c35babb733aaad354fe13
3,382
// // main.swift // CEF.swift // // Created by Tamas Lustyik on 2015. 07. 18.. // Copyright © 2015. Tamas Lustyik. All rights reserved. // import Cocoa import CEFswift class SimpleApp: CEFApp, CEFBrowserProcessHandler { let client: SimpleHandler init() { client = SimpleHandler.instance } // cefapp var browserProcessHandler: CEFBrowserProcessHandler? { return self } // cefbrowserprocesshandler func onContextInitialized() { let winInfo = CEFWindowInfo() let settings = CEFBrowserSettings() let cmdLine = CEFCommandLine.globalCommandLine var url = NSURL(string: "http://www.google.com")! if let urlSwitch = cmdLine?.valueForSwitch("url") where !urlSwitch.isEmpty { url = NSURL(string: urlSwitch)! } CEFBrowserHost.createBrowser(winInfo, client: client, url: url, settings: settings, requestContext: nil) } } class SimpleHandler: CEFClient, CEFLifeSpanHandler { static var instance = SimpleHandler() private var _browserList = [CEFBrowser]() private var _isClosing: Bool = false var isClosing: Bool { get { return _isClosing } } // from CEFClient var lifeSpanHandler: CEFLifeSpanHandler? { return self } // from CEFLifeSpanHandler func onAfterCreated(browser: CEFBrowser) { _browserList.append(browser) } func doClose(browser: CEFBrowser) -> Bool { if _browserList.count == 1 { _isClosing = true } return false } func onBeforeClose(browser: CEFBrowser) { for (index, value) in _browserList.enumerate() { if value.isSameAs(browser) { _browserList.removeAtIndex(index) break } } if _browserList.isEmpty { CEFProcessUtils.quitMessageLoop() } } // new methods func closeAllBrowsers(force: Bool) { _browserList.forEach { browser in browser.host?.closeBrowser(force: force) } } } class SimpleApplication : NSApplication, CefAppProtocol { var _isHandlingSendEvent: Bool = false func isHandlingSendEvent() -> Bool { return _isHandlingSendEvent } func setHandlingSendEvent(handlingSendEvent: Bool) { _isHandlingSendEvent = handlingSendEvent } override init() { super.init() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func sendEvent(event: NSEvent) { let stashedIsHandlingSendEvent = _isHandlingSendEvent _isHandlingSendEvent = true defer { _isHandlingSendEvent = stashedIsHandlingSendEvent } super.sendEvent(event) } override func terminate(sender: AnyObject?) { let delegate = NSApplication.sharedApplication().delegate as! AppDelegate delegate.tryToTerminateApplication(self) } } let args = CEFMainArgs(arguments: Process.arguments) let app = SimpleApp() SimpleApplication.sharedApplication() let settings = CEFSettings() CEFProcessUtils.initializeMainWithArgs(args, settings: settings, app: app) let appDelegate = AppDelegate() appDelegate.createApplication() CEFProcessUtils.runMessageLoop() CEFProcessUtils.shutDown() exit(0)
24.507246
112
0.645476
8fedbc9d952944fdf146c9097760482fd691f558
2,181
// // AppDelegate.swift // FontistoiOS // // Created by semihemreunlu on 11/09/2017. // Copyright (c) 2017 semihemreunlu. 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.404255
285
0.755617
e2f9c96eb3ab745f805dbf65a4c2a08376c4b05e
4,717
// // FSStorage.swift // FlagShip-framework // // Created by Adel on 03/12/2019. From Saoud M. Rizwan // https://medium.com/@sdrzn/swift-4-codable-lets-make-things-even-easier-c793b6cf29e1 // import Foundation import Foundation /// :nodoc: public class FSStorage { fileprivate init() { } enum Directory { // Only documents and other data that is user-generated, or that cannot otherwise be recreated by your application, should be stored in the <Application_Home>/Documents directory and will be automatically backed up by iCloud. case documents // Data that can be downloaded again or regenerated should be stored in the <Application_Home>/Library/Caches directory. Examples of files you should put in the Caches directory include database cache files and downloadable content, such as that used by magazine, newspaper, and map applications. case caches } /// Returns URL constructed from specified directory static fileprivate func getURL(for directory: Directory) -> URL { var searchPathDirectory: FileManager.SearchPathDirectory switch directory { case .documents: searchPathDirectory = .documentDirectory case .caches: searchPathDirectory = .cachesDirectory } if var url = FileManager.default.urls(for: searchPathDirectory, in: .userDomainMask).first { url.appendPathComponent("FlagShipCampaign/Allocation", isDirectory: true) do { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes:nil) return url }catch{ fatalError("Could not create URL for specified directory!") } } else { fatalError("Could not create URL for specified directory!") } } /// Store an encodable struct to the specified directory on disk /// /// - Parameters: /// - object: the encodable struct to store /// - directory: where to store the struct /// - fileName: what to name the file where the struct data will be stored static func store<T: Encodable>(_ object: T, to directory: Directory, as fileName: String) { let url = getURL(for: directory).appendingPathComponent(fileName, isDirectory: false) let encoder = JSONEncoder() do { let data = try encoder.encode(object) if FileManager.default.fileExists(atPath: url.path) { try FileManager.default.removeItem(at: url) } FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil) } catch { FSLogger.FSlog(error.localizedDescription, .Campaign) } } /// Retrieve and convert a struct from a file on disk /// /// - Parameters: /// - fileName: name of the file where struct data is stored /// - directory: directory where struct data is stored /// - type: struct type (i.e. Message.self) /// - Returns: decoded struct model(s) of data static func retrieve<T: Decodable>(_ fileName: String, from directory: Directory, as type: T.Type) -> T? { let url = getURL(for: directory).appendingPathComponent(fileName, isDirectory: false) if !FileManager.default.fileExists(atPath: url.path) { FSLogger.FSlog("File at path \(url.path) does not exist!", .Campaign) return nil } if let data = FileManager.default.contents(atPath: url.path) { let decoder = JSONDecoder() do { let model = try decoder.decode(type, from: data) return model } catch { FSLogger.FSlog(error.localizedDescription, .Campaign) return nil } } else { FSLogger.FSlog("No data at \(url.path)!", .Campaign) return nil } } /// Returns BOOL indicating whether file exists at specified directory with specified file name static func fileExists(_ fileName: String, in directory: Directory) -> Bool { let url = getURL(for: directory).appendingPathComponent(fileName, isDirectory: false) return FileManager.default.fileExists(atPath: url.path) } internal static func deleteSavedAllocations(){ do{ try FileManager.default.removeItem(at: getURL(for: .documents)) FSLogger.FSlog("Delete all saved allocation", .Campaign) }catch{ FSLogger.FSlog("Failed to delete saved allocation", .Campaign) } } }
36.851563
304
0.62455
dd41bce13104dc276224df3ab514f398106653e7
5,375
// // RemovableHashtagCollectionViewCell.swift // Hashtags // // Created by Oscar Götting on 6/8/18. // Copyright © 2018 Oscar Götting. All rights reserved. // import Foundation import UIKit fileprivate extension Selector { static let removeButtonClicked: Selector = #selector(RemovableHashtagCollectionViewCell.onRemoveButtonClicked(_:)) } public protocol RemovableHashtagDelegate: class { func onRemoveHashtag(hashtag: HashTag) } open class RemovableHashtagCollectionViewCell: UICollectionViewCell { static let cellIdentifier = "RemovableHashtagCollectionViewCell" var paddingLeftConstraint: NSLayoutConstraint? var paddingRightConstraint: NSLayoutConstraint? var paddingTopConstraint: NSLayoutConstraint? var paddingBottomConstraint: NSLayoutConstraint? var removeButtonHeightConstraint: NSLayoutConstraint? var removeButtonWidthConstraint: NSLayoutConstraint? var removeButtonSpacingConstraint: NSLayoutConstraint? lazy var wordLabel : UILabel = { let lbl = UILabel() lbl.textColor = UIColor.white lbl.textAlignment = .center lbl.translatesAutoresizingMaskIntoConstraints = false lbl.numberOfLines = 0 return lbl }() var removeButton : UIButton = { let btn = UIButton() let bundle = Bundle(for: RemovableHashtagCollectionViewCell.self) let removeIcon = UIImage(named: "close", in: bundle, compatibleWith: nil)! btn.translatesAutoresizingMaskIntoConstraints = false btn.tintColor = UIColor.white if let removeIcon = UIImage(named: "close", in: bundle, compatibleWith: nil) { let tintableImage = removeIcon.withRenderingMode(.alwaysTemplate) btn.setImage(removeIcon, for: .normal) btn.imageView?.contentMode = .scaleAspectFit btn.imageView?.tintColor = UIColor.white.withAlphaComponent(0.9) } else { btn.setTitle("X", for: UIControl.State.normal) } return btn }() open weak var delegate: RemovableHashtagDelegate? open var hashtag: HashTag? override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { self.clipsToBounds = true self.addSubview(wordLabel) self.addSubview(removeButton) // Text Width self.wordLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 10).isActive = false // Padding left self.paddingLeftConstraint = self.wordLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor) self.paddingLeftConstraint!.isActive = true // Padding top self.paddingTopConstraint = self.wordLabel.topAnchor.constraint(equalTo: self.topAnchor) self.paddingTopConstraint!.isActive = true // Padding bottom self.paddingBottomConstraint = self.wordLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor) self.paddingBottomConstraint!.isActive = true // Remove button spacing self.removeButtonSpacingConstraint = self.removeButton.leadingAnchor.constraint(equalTo: self.wordLabel.trailingAnchor) self.removeButtonSpacingConstraint!.isActive = true // Remove button width self.removeButtonWidthConstraint = self.removeButton.widthAnchor.constraint(equalToConstant: 0.0) self.removeButtonWidthConstraint!.isActive = true // Remove button height self.removeButtonHeightConstraint = self.removeButton.heightAnchor.constraint(equalTo: self.wordLabel.heightAnchor) self.removeButtonHeightConstraint!.isActive = true // Remove button Y alignment self.removeButton.centerYAnchor.constraint(equalTo: self.wordLabel.centerYAnchor).isActive = true self.removeButton.trailingAnchor.constraint(equalTo: self.trailingAnchor,constant: -5).isActive = true // Remove button target self.removeButton.addTarget(self, action: Selector.removeButtonClicked, for: .touchUpInside) } open override func prepareForInterfaceBuilder() { self.wordLabel.text = "" super.prepareForInterfaceBuilder() } @objc func onRemoveButtonClicked(_ sender: UIButton) { guard let hashtag = self.hashtag else { return } self.delegate?.onRemoveHashtag(hashtag: hashtag) } } extension RemovableHashtagCollectionViewCell { open func configureWithTag(tag: HashTag, configuration: HashtagConfiguration) { self.hashtag = tag self.wordLabel.text = tag.text self.wordLabel.font = configuration.hashtagFont self.paddingLeftConstraint!.constant = configuration.paddingLeft self.paddingTopConstraint!.constant = configuration.paddingTop self.paddingBottomConstraint!.constant = -1 * configuration.paddingBottom self.removeButtonWidthConstraint!.constant = configuration.removeButtonSize self.backgroundColor = configuration.backgroundColor self.wordLabel.textColor = tag.isGoldTag ? configuration.goldTagColor : configuration.textColor self.wordLabel.layoutSubviews() } }
38.120567
127
0.697302
fef8a2cd194b8bbac87c0598990b7ad121c49132
10,628
// // QueryTests.swift // // // Created by Vladislav Fitc on 09/04/2020. // import Foundation import XCTest @testable import AlgoliaSearchClient class QueryTests: XCTestCase { let query = Query() .set(\.query, to: "testQuery") .set(\.similarQuery, to: "testSimilarQuery") .set(\.distinct, to: 5) .set(\.getRankingInfo, to: true) .set(\.explainModules, to: [.matchAlternatives]) .set(\.attributesToRetrieve, to: ["attr1", "attr2", "attr3"]) .set(\.restrictSearchableAttributes, to: ["rattr1", "rattr2"]) .set(\.filters, to: "(color:red OR color:yellow) AND on-sale") .set(\.facetFilters, to: [.or("color:red", "color:blue"), "size:M"]) .set(\.optionalFilters, to: [.or("color:red", "color:yellow"), "on-sale"]) .set(\.numericFilters, to: [.or("price>100", "length<1000"), "metrics>5"]) .set(\.tagFilters, to: [.or("tag1", "tag2"), "tag3"]) .set(\.sumOrFiltersScores, to: false) .set(\.facets, to: ["facet1", "facet2", "facet3"]) .set(\.maxValuesPerFacet, to: 10) .set(\.facetingAfterDistinct, to: true) .set(\.sortFacetsBy, to: .count) .set(\.maxFacetHits, to: 100) .set(\.attributesToHighlight, to: ["hattr1", "hattr2", "hattr3"]) .set(\.attributesToSnippet, to: [Snippet(attribute: "sattr1", count: 10), Snippet(attribute: "sattr2")]) .set(\.highlightPreTag, to: "<hl>") .set(\.highlightPostTag, to: "</hl>") .set(\.snippetEllipsisText, to: "read more") .set(\.restrictHighlightAndSnippetArrays, to: true) .set(\.page, to: 15) .set(\.hitsPerPage, to: 30) .set(\.offset, to: 100) .set(\.length, to: 40) .set(\.minWordSizeFor1Typo, to: 2) .set(\.minWordSizeFor2Typos, to: 4) .set(\.typoTolerance, to: .strict) .set(\.allowTyposOnNumericTokens, to: false) .set(\.disableTypoToleranceOnAttributes, to: ["dtattr1", "dtattr2"]) .set(\.aroundLatLng, to: .init(latitude: 79.5, longitude: 10.5)) .set(\.aroundLatLngViaIP, to: true) .set(\.aroundRadius, to: .meters(80)) .set(\.aroundPrecision, to: [.init(from: 0, value: 1000), .init(from: 0, value: 100000)]) .set(\.minimumAroundRadius, to: 40) .set(\.insideBoundingBox, to: [.init(point1: .init(latitude: 0, longitude: 10), point2: .init(latitude: 20, longitude: 30)), .init(point1: .init(latitude: 40, longitude: 50), point2: .init(latitude: 60, longitude: 70))]) .set(\.insidePolygon, to: [.init(.init(latitude: 0, longitude: 10), .init(latitude: 20, longitude: 30), .init(latitude: 40, longitude: 50)), .init(.init(latitude: 10, longitude: 20), .init(latitude: 30, longitude: 40), .init(latitude: 50, longitude: 60))]) .set(\.queryType, to: .prefixLast) .set(\.removeWordsIfNoResults, to: .lastWords) .set(\.advancedSyntax, to: false) .set(\.advancedSyntaxFeatures, to: [.excludeWords, .exactPhrase]) .set(\.optionalWords, to: ["optWord1", "optWord2"]) .set(\.removeStopWords, to: .queryLanguages([.arabic, .french])) .set(\.disableExactOnAttributes, to: ["deAttr1", "deAttr2"]) .set(\.exactOnSingleWordQuery, to: .word) .set(\.alternativesAsExact, to: [.ignorePlurals, .singleWordSynonym]) .set(\.ignorePlurals, to: false) .set(\.queryLanguages, to: [.hindi, .albanian]) .set(\.decompoundQuery, to: false) .set(\.enableRules, to: true) .set(\.ruleContexts, to: ["rc1", "rc2"]) .set(\.enablePersonalization, to: false) .set(\.personalizationImpact, to: 5) .set(\.userToken, to: "testUserToken") .set(\.analytics, to: true) .set(\.analyticsTags, to: ["at1", "at2", "at3"]) .set(\.enableABTest, to: false) .set(\.clickAnalytics, to: true) .set(\.synonyms, to: false) .set(\.replaceSynonymsInHighlight, to: true) .set(\.minProximity, to: 3) .set(\.responseFields, to: [.facetsStats, .hits]) .set(\.percentileComputation, to: false) .set(\.naturalLanguages, to: [.maori, .tamil]) .set(\.customParameters, to: ["custom1": "val1", "custom2": 2]) .set(\.enableReRanking, to: true) func testURLStringEncoding() { let urlEncodedString = query.urlEncodedString let expectedString = [ "query=testQuery", "similarQuery=testSimilarQuery", "distinct=5", "getRankingInfo=true", "explainModules=match.alternatives", "attributesToRetrieve=attr1,attr2,attr3", "restrictSearchableAttributes=rattr1,rattr2", "filters=(color:red%20OR%20color:yellow)%20AND%20on-sale", "facetFilters=%5B%5B%22color:red%22,%22color:blue%22%5D,%22size:M%22%5D", "optionalFilters=%5B%5B%22color:red%22,%22color:yellow%22%5D,%22on-sale%22%5D", "numericFilters=%5B%5B%22price%3E100%22,%22length%3C1000%22%5D,%22metrics%3E5%22%5D", "tagFilters=%5B%5B%22tag1%22,%22tag2%22%5D,%22tag3%22%5D", "sumOrFiltersScores=false", "facets=facet1,facet2,facet3", "maxValuesPerFacet=10", "facetingAfterDistinct=true", "sortFacetValuesBy=count", "maxFacetHits=100", "attributesToHighlight=hattr1,hattr2,hattr3", "attributesToSnippet=sattr1:10,sattr2", "highlightPreTag=%3Chl%3E", "highlightPostTag=%3C/hl%3E", "snippetEllipsisText=read%20more", "restrictHighlightAndSnippetArrays=true", "page=15", "hitsPerPage=30", "offset=100", "length=40", "minWordSizefor1Typo=2", "minWordSizefor2Typos=4", "typoTolerance=strict", "allowTyposOnNumericTokens=false", "disableTypoToleranceOnAttributes=dtattr1,dtattr2", "aroundLatLng=79.5,10.5", "aroundLatLngViaIP=true", "aroundRadius=80", "aroundPrecision=%5B%7B%22from%22:0.0,%22value%22:1000.0%7D,%7B%22from%22:0.0,%22value%22:100000.0%7D%5D", "minimumAroundRadius=40", "insideBoundingBox=%5B%5B0.0,10.0,20.0,30.0%5D,%5B40.0,50.0,60.0,70.0%5D%5D", "insidePolygon=%5B%5B0.0,10.0,20.0,30.0,40.0,50.0%5D,%5B10.0,20.0,30.0,40.0,50.0,60.0%5D%5D", "queryType=prefixLast", "removeWordsIfNoResults=lastWords", "advancedSyntax=false", "advancedSyntaxFeatures=exactPhrase,excludeWords", "optionalWords=optWord1,optWord2", "removeStopWords=ar,fr", "disableExactOnAttributes=deAttr1,deAttr2", "exactOnSingleWordQuery=word", "alternativesAsExact=ignorePlurals,singleWordSynonym", "ignorePlurals=false", "queryLanguages=hi,sq", "decompoundQuery=false", "enableRules=true", "ruleContexts=rc1,rc2", "enablePersonalization=false", "personalizationImpact=5", "userToken=testUserToken", "analytics=true", "analyticsTags=at1,at2,at3", "enableABTest=false", "clickAnalytics=true", "synonyms=false", "replaceSynonymsInHighlight=true", "minProximity=3", "responseFields=facets_stats,hits", "percentileComputation=false", "naturalLanguages=mi,ta", "enableReRanking=true", "custom1=val1", "custom2=2.0", ].joined(separator: "&") XCTAssertEqual(urlEncodedString, expectedString) } func testFacetsCoding() throws { let facets: Set<Attribute> = ["facet1", "facet2", "facet3"] let query = Query.empty.set(\.facets, to: ["facet1", "facet2", "facet3"]) let encoder = JSONEncoder() let data = try encoder.encode(query) let decoder = JSONDecoder() let decodedQuery = try decoder.decode(Query.self, from: data) XCTAssertEqual(decodedQuery.facets, facets) let decodedJSON = try decoder.decode(JSON.self, from: data) guard case .dictionary(let dictionary) = decodedJSON else { XCTFail("Query in JSON form must be dictionary") return } XCTAssertEqual(dictionary.keys.first, "facets") XCTAssertEqual(dictionary.keys.count, 1) } func testCoding() throws { try AssertEncodeDecode(query.set(\.facets, to: nil), [ "query": "testQuery", "similarQuery": "testSimilarQuery", "distinct": 5, "getRankingInfo": true, "explainModules": ["match.alternatives"], "attributesToRetrieve": ["attr1", "attr2", "attr3"], "restrictSearchableAttributes": ["rattr1", "rattr2"], "filters": "(color:red OR color:yellow) AND on-sale", "facetFilters": [["color:red", "color:blue"], "size:M"], "optionalFilters": [["color:red", "color:yellow"], "on-sale"], "numericFilters": [["price>100", "length<1000"], "metrics>5"], "tagFilters": [["tag1", "tag2"], "tag3"], "sumOrFiltersScores": false, "maxValuesPerFacet": 10, "facetingAfterDistinct": true, "sortFacetValuesBy": "count", "maxFacetHits": 100, "attributesToHighlight": ["hattr1", "hattr2", "hattr3"], "attributesToSnippet": ["sattr1:10", "sattr2"], "highlightPreTag": "<hl>", "highlightPostTag": "</hl>", "snippetEllipsisText": "read more", "restrictHighlightAndSnippetArrays": true, "page": 15, "hitsPerPage": 30, "offset": 100, "length": 40, "minWordSizefor1Typo": 2, "minWordSizefor2Typos": 4, "typoTolerance": "strict", "allowTyposOnNumericTokens": false, "disableTypoToleranceOnAttributes": ["dtattr1", "dtattr2"], "aroundLatLng": "79.5,10.5", "aroundLatLngViaIP": true, "aroundRadius": "80", "aroundPrecision": [["from": 0, "value": 1000], ["from": 0, "value": 100000]], "minimumAroundRadius": 40, "insideBoundingBox": [[0,10,20,30], [40,50,60,70]], "insidePolygon": [[0,10,20,30,40,50], [10,20,30,40,50,60]], "queryType": "prefixLast", "removeWordsIfNoResults": "lastWords", "advancedSyntax": false, "advancedSyntaxFeatures": ["excludeWords", "exactPhrase"], "optionalWords": ["optWord1", "optWord2"], "removeStopWords": ["ar", "fr"], "decompoundQuery": false, "disableExactOnAttributes": ["deAttr1", "deAttr2"], "exactOnSingleWordQuery": "word", "alternativesAsExact": ["ignorePlurals", "singleWordSynonym"], "ignorePlurals": false, "queryLanguages": ["hi", "sq"], "enableRules": true, "ruleContexts": ["rc1", "rc2"], "enablePersonalization": false, "personalizationImpact": 5, "userToken": "testUserToken", "analytics": true, "analyticsTags": ["at1", "at2", "at3"], "enableABTest": false, "clickAnalytics": true, "synonyms": false, "replaceSynonymsInHighlight": true, "minProximity": 3, "responseFields": ["facets_stats", "hits"], "percentileComputation": false, "naturalLanguages": ["mi", "ta"], "custom1": "val1", "custom2": 2, "enableReRanking": true ]) } }
41.193798
260
0.63455
22b372468c528dbffcd3eaf0bb6ff86ec496a304
1,349
// Copyright (c) 2020 Spotify AB. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Foundation import Vapor /// Parameters to fetch the list of existing `JobLogEntry`s struct JobListRequest: Content { /// Start date. var from: Date /// End date. var to: Date /// Optional. The status of the `JobLogEntry`s to fetch. var status: JobLogStatus? /// Optional. This string will be used to filter the `JobLogEntry` whose `logFile` contains it. var filter: String? /// Page to fetch. var page: Int /// Rows per page to fetch. var per: Int }
30.659091
99
0.713862
50ab21d833615b7081741c4fbf0d38bbfdb0556c
1,813
// // HomeDetatilViewController.swift // RxFlowWithReactorKit // // Created by Lyine on 2022/02/27. // import UIKit import RxFlow import RxCocoa import ReactorKit final class HomeDetatilViewController: UIViewController, View { typealias Reactor = HomeDetailReactor // MARK: Property private let movieTitle: String internal var disposeBag: DisposeBag = .init() // MARK: UI Properties private let titleLabel: UILabel = UILabel().then { $0.font = .systemFont(ofSize: 30) $0.textAlignment = .center } private let toMiddleButton: UIButton = UIButton(type: .system).then { $0.setTitle("toMiddle", for: .normal) $0.backgroundColor = .black } // MARK: Initializers init( with reactor: Reactor, title: String ) { self.movieTitle = title super.init(nibName: nil, bundle: nil) self.reactor = reactor } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: LifeCycle override func viewDidLoad() { super.viewDidLoad() setUI() } } // MARK: - Extensions private extension HomeDetatilViewController { private func setUI() { view.backgroundColor = .white view.addSubview(titleLabel) titleLabel.text = movieTitle titleLabel.snp.makeConstraints { $0.leading.trailing.equalToSuperview() $0.top.equalTo(view.safeArea.top) $0.bottom.equalTo(view.safeArea.bottom).offset(-50) } view.addSubview(toMiddleButton) toMiddleButton.snp.makeConstraints { $0.leading.trailing.equalToSuperview() $0.bottom.equalTo(view.safeArea.bottom) $0.height.equalTo(50) } } } // MARK: Bind extension HomeDetatilViewController { func bind(reactor: Reactor) { toMiddleButton.rx.tap .map { Reactor.Action.toMiddleDidTap } .bind(to: reactor.action) .disposed(by: disposeBag) } }
19.287234
70
0.706564
09663dc4945b15bfc8690e627b767db426cc14e1
6,894
// // TransactionRequest.swift // Guardian // // Created by Wolf McNally on 2/17/21. // import Foundation import URKit import LifeHash import CryptoKit struct TransactionRequest { let id: UUID let body: Body let description: String? enum Body { case seed(SeedRequestBody) case key(KeyRequestBody) case psbtSignature(PSBTSignatureRequestBody) } var cbor: CBOR { var a: [OrderedMapEntry] = [] a.append(.init(key: 1, value: id.taggedCBOR)) switch body { case .seed(let body): a.append(.init(key: 2, value: body.taggedCBOR)) case .key(let body): a.append(.init(key: 2, value: body.taggedCBOR)) case .psbtSignature(let body): a.append(.init(key: 2, value: body.taggedCBOR)) } if let description = description { a.append(.init(key: 3, value: CBOR.utf8String(description))) } return CBOR.orderedMap(a) } var taggedCBOR: CBOR { CBOR.tagged(.transactionRequest, cbor) } init(ur: UR) throws { guard ur.type == "crypto-request" else { throw GeneralError("Unexpected UR type.") } try self.init(cborData: ur.cbor) } init(id: UUID = UUID(), body: TransactionRequest.Body, description: String? = nil) { self.id = id self.body = body self.description = description } init(cborData: Data) throws { guard let cbor = try CBOR.decode(cborData.bytes) else { throw GeneralError("ur:crypto-request: Invalid CBOR.") } try self.init(cbor: cbor) } init(cbor: CBOR) throws { guard case let CBOR.map(pairs) = cbor else { throw GeneralError("ur:crypto-request: CBOR doesn't contain a map.") } guard let idItem = pairs[1] else { throw GeneralError("ur:crypto-request: CBOR doesn't contain a transaction ID.") } let id = try UUID(taggedCBOR: idItem) guard let bodyItem = pairs[2] else { throw GeneralError("ur:crypto-request: CBOR doesn't contain a body.") } let body: Body if let seedRequestBody = try SeedRequestBody(taggedCBOR: bodyItem) { body = Body.seed(seedRequestBody) } else if let keyRequestBody = try KeyRequestBody(taggedCBOR: bodyItem) { body = Body.key(keyRequestBody) } else if let psbtSignatureRequestBody = try PSBTSignatureRequestBody(taggedCBOR: bodyItem) { body = Body.psbtSignature(psbtSignatureRequestBody) } else { throw GeneralError("ur:crypto-request: Unrecognized request.") } let description: String? if let descriptionItem = pairs[3] { guard case let CBOR.utf8String(d) = descriptionItem else { throw GeneralError("ur:crypto-request: Invalid description.") } description = d } else { description = nil } self.init(id: id, body: body, description: description) } var ur: UR { try! UR(type: "crypto-request", cbor: cbor) } } struct SeedRequestBody { let fingerprint: Fingerprint var cbor: CBOR { CBOR.byteString(fingerprint.digest.bytes) } var taggedCBOR: CBOR { return CBOR.tagged(.seedRequestBody, cbor) } init(fingerprint: Fingerprint) { self.fingerprint = fingerprint } init(cbor: CBOR) throws { guard case let CBOR.byteString(bytes) = cbor, bytes.count == SHA256.byteCount else { throw GeneralError("Invalid seed request.") } self.init(fingerprint: Fingerprint(digest: Data(bytes))) } init?(taggedCBOR: CBOR) throws { guard case let CBOR.tagged(.seedRequestBody, cbor) = taggedCBOR else { return nil } try self.init(cbor: cbor) } } struct KeyRequestBody { let keyType: KeyType let path: DerivationPath let useInfo: UseInfo let isDerivable: Bool var cbor: CBOR { var a: [OrderedMapEntry] = [] a.append(.init(key: 1, value: CBOR.boolean(keyType.isPrivate))) a.append(.init(key: 2, value: path.taggedCBOR)) if !useInfo.isDefault { a.append(.init(key: 3, value: useInfo.taggedCBOR)) } if !isDerivable { a.append(.init(key: 4, value: CBOR.boolean(isDerivable))) } return CBOR.orderedMap(a) } var taggedCBOR: CBOR { return CBOR.tagged(.keyRequestBody, cbor) } init(keyType: KeyType, path: DerivationPath, useInfo: UseInfo, isDerivable: Bool) { self.keyType = keyType self.path = path self.useInfo = useInfo self.isDerivable = isDerivable } init(cbor: CBOR) throws { guard case let CBOR.map(pairs) = cbor else { throw GeneralError("Invalid key request.") } guard let boolItem = pairs[1], case let CBOR.boolean(isPrivate) = boolItem else { throw GeneralError("Key request doesn't contain isPrivate.") } guard let pathItem = pairs[2] else { throw GeneralError("Key request doesn't contain derivation.") } let path = try DerivationPath(taggedCBOR: pathItem) let useInfo: UseInfo if let pathItem = pairs[3] { useInfo = try UseInfo(taggedCBOR: pathItem) } else { useInfo = UseInfo() } let isDerivable: Bool if let isDerivableItem = pairs[4] { guard case let CBOR.boolean(d) = isDerivableItem else { throw GeneralError("Invalid isDerivable field in key request.") } isDerivable = d } else { isDerivable = true } self.init(keyType: KeyType(isPrivate: isPrivate), path: path, useInfo: useInfo, isDerivable: isDerivable) } init?(taggedCBOR: CBOR) throws { guard case let CBOR.tagged(.keyRequestBody, cbor) = taggedCBOR else { return nil } try self.init(cbor: cbor) } } struct PSBTSignatureRequestBody { let psbt: Data var cbor: CBOR { // not supported yet fatalError() } var taggedCBOR: CBOR { return CBOR.tagged(.psbtSignatureRequestBody, cbor) } init(cbor: CBOR) throws { throw GeneralError("Signing PSBTs isn't supported yet.") } init?(taggedCBOR: CBOR) throws { guard case let CBOR.tagged(.psbtSignatureRequestBody, cbor) = taggedCBOR else { return nil } try self.init(cbor: cbor) } }
28.37037
113
0.572237
bf1278349f43acdb3e7fa60b948c7ba9c0ee3cdf
7,151
// // ViewController.swift // EVReflectionTestApp // // Created by Edwin Vermeer on 4/9/16. // Copyright © 2016 evict. All rights reserved. // import UIKit import EVReflection class ViewController: UIViewController { // MARK: - General test setup and functions @IBOutlet weak var initialMemoryUsage: UILabel! @IBOutlet weak var testDuration: UILabel! @IBOutlet weak var curenMemoryUsage: UILabel! @IBOutlet weak var changedMemoryUsage: UILabel! var usage: UInt = 0 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) usage = report_memory() curenMemoryUsage.text = "\(NSNumber(value: Int32(usage)).description(withLocale: NSLocale.current))" initialMemoryUsage.text = "\(NSNumber(value: Int32(usage)).description(withLocale: NSLocale.current))" testIssue213() } override func didReceiveMemoryWarning() { print("WARNING: didReceiveMemoryWarning") super.didReceiveMemoryWarning() } func report_memory() -> UInt { var info = mach_task_basic_info() var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size)/4 let kerr: kern_return_t = withUnsafeMutablePointer(to: &info) { $0.withMemoryRebound(to: integer_t.self, capacity: 1) { task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count) } } if kerr == KERN_SUCCESS { print("Memory in use (in bytes): \(info.resident_size)") return UInt(info.resident_size) } else { print("Error with task_info(): " + (String(cString: mach_error_string(kerr), encoding: String.Encoding.ascii) ?? "unknown error")) return 0 } } func doTest(test : ()-> ()) { let startTime = NSDate() let usageAtBegin = usage test() let endTime = NSDate() usage = report_memory() curenMemoryUsage.text = "\(NSNumber(value: Int32(usage)).description(withLocale: NSLocale.current))" let change: Int32 = (Int32(usage) - Int32(usageAtBegin)) changedMemoryUsage.text = "\(NSNumber(value: change).description(withLocale: NSLocale.current))" testDuration.text = "\(endTime.timeIntervalSince(startTime as Date))" } // MARK: - Executing the tests @IBAction func test1(sender: AnyObject) { doTest { let a = TestObject1() for i in 1...1000 { a.listObject2?.append(TestObject2(id: i)) } let b = a.toJsonString() let c = TestObject1(json: b) assert(c.listObject2?.count ?? 0 == 1000) } } @IBAction func test2(sender: AnyObject) { doTest { let test = ArrayDeserializationPerformanceTest() test.performanceTest1() } } @IBAction func test3(sender: AnyObject) { doTest { let a = TestObject1() a.listObject2?.append(TestObject2(id: 1)) let b = a.toJsonString() let c = TestObject1(json: b) assert(c.listObject2?.count ?? 0 == 1) } } func testIssue213() { let path: String = Bundle(for: type(of: self)).path(forResource: "test", ofType: "json") ?? "" if let content = try? String(contentsOfFile: path) { let data = ResultArrayWrapper<Spot>(json: content) print("\(data)") } else { assert(true) } } } // MARK: - Objects used in the tests class TestObject1: EVObject { var name1: String? = "Object1 Name1" var name2: String? = "Object1 Name2" var name3: String? = "Object1 Name3" var name4: String? = "Object1 Name4" var name5: String? = "Object1 Name5" var name6: String? = "Object1 Name6" var name7: String? = "Object1 Name7" var name8: String? = "Object1 Name8" var name9: String? = "Object1 Name9" var name10: String? = "Object1 Name10" var name11: String? = "Object1 Name11" var name12: String? = "Object1 Name12" var name13: String? = "Object1 Name13" var name14: String? = "Object1 Name14" var name15: String? = "Object1 Name15" var name16: String? = "Object1 Name16" var name17: String? = "Object1 Name17" var name18: String? = "Object1 Name18" var name19: String? = "Object1 Name19" var name20: String? = "Object1 Name20" var name21: String? = "Object1 Name21" var name22: String? = "Object1 Name22" var name23: String? = "Object1 Name23" var name24: String? = "Object1 Name24" var name25: String? = "Object1 Name25" var name26: String? = "Object1 Name26" var name27: String? = "Object1 Name27" var name28: String? = "Object1 Name28" var name29: String? = "Object1 Name29" var name30: String? = "Object1 Name30" var listObject2: [TestObject2]? = [] } class TestObject2: EVObject { var name: String? = "Object2 Name" init(id: Int) { super.init() name = "Object2 Name \(id)" } //workaround @available(*, deprecated, message: "init isn't supported, use init(id:) instead") required init() { super.init() } } class ResultArrayWrapper<T: Model>: EVObject, EVGenericsKVC { required init() { super.init() } var data: [T]? func setGenericValue(_ value: AnyObject!, forUndefinedKey key: String) { switch key { case "data": data = value as? [T] break; case "meta": break; default: print("---> setValue '\(value ?? [] as AnyObject)' for key '\(key)' should be handled.") } } func getGenericType() -> NSObject { return T() as NSObject } } class XMeta<T: Model>: Model, EVGenericsKVC { required init() { super.init() } var cursor: String? internal func setGenericValue(_ value: AnyObject!, forUndefinedKey key: String) { if(key == "data") { //data = value as? [T] } } internal func getGenericType() -> NSObject { return T() as NSObject } } class Model: EVObject { } class Spot: Model { var id: String? var firstName: String? var lastName: String? var username: String? var email: String? var phone: String? var sex: String? var canBook: Bool = false var contractable: Bool = false var profile = ResultArrayWrapper<Profile>() override func setValue(_ value: Any!, forUndefinedKey key: String) { if key == "profile" { if let value = value as? ResultArrayWrapper<Profile> { self.profile = value return } } print("setValue forUndefinedKey \(key)") } } class Profile: Model { var about: String? var avatarUrl: String? var coverUrl: String? }
26.984906
111
0.577262
7968fcf25747db2fa2812939f349235dee5f225f
2,598
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? let conductor = Conductor() 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().environmentObject(conductor) // 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 neccessarily 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. } 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. } }
44.793103
118
0.74057
d54ec4acbe375420b52ca064eced0c75834cbdab
5,134
// PickerInputRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: PickerInputCell open class _PickerInputCell<T> : Cell<T>, CellType, UIPickerViewDataSource, UIPickerViewDelegate where T: Equatable { lazy public var picker: UIPickerView = { let picker = UIPickerView() picker.translatesAutoresizingMaskIntoConstraints = false return picker }() fileprivate var pickerInputRow: _PickerInputRow<T>? { return row as? _PickerInputRow<T> } public required init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func setup() { super.setup() accessoryType = .none editingAccessoryType = .none picker.delegate = self picker.dataSource = self } deinit { picker.delegate = nil picker.dataSource = nil } open override func update() { super.update() selectionStyle = row.isDisabled ? .none : .default if row.title?.isEmpty == false { detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText } else { textLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText detailTextLabel?.text = nil } textLabel?.textColor = row.isDisabled ? .gray : .black if row.isHighlighted { textLabel?.textColor = tintColor } picker.reloadAllComponents() } open override func didSelect() { super.didSelect() row.deselect() } open override var inputView: UIView? { return picker } open override func cellCanBecomeFirstResponder() -> Bool { return canBecomeFirstResponder } override open var canBecomeFirstResponder: Bool { return !row.isDisabled } open func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerInputRow?.options.count ?? 0 } open func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerInputRow?.displayValueFor?(pickerInputRow?.options[row]) } open func pickerView(_ pickerView: UIPickerView, didSelectRow rowNumber: Int, inComponent component: Int) { if let picker = pickerInputRow, picker.options.count > rowNumber { picker.value = picker.options[rowNumber] update() } } } open class PickerInputCell<T>: _PickerInputCell<T> where T: Equatable { public required init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func update() { super.update() if let selectedValue = pickerInputRow?.value, let index = pickerInputRow?.options.index(of: selectedValue) { picker.selectRow(index, inComponent: 0, animated: true) } } } // MARK: PickerInputRow open class _PickerInputRow<T> : Row<PickerInputCell<T>>, NoValueDisplayTextConformance where T: Equatable { open var noValueDisplayText: String? = nil open var options = [T]() required public init(tag: String?) { super.init(tag: tag) } } /// A generic row where the user can pick an option from a picker view displayed in the keyboard area public final class PickerInputRow<T>: _PickerInputRow<T>, RowType where T: Equatable, T: InputTypeInitiable { required public init(tag: String?) { super.init(tag: tag) } }
33.122581
130
0.683288
6252594bfe062cc518408851770fee71ff064ae6
1,408
// // AppDelegate.swift // DoKitSwiftDemo // // Created by didi on 2020/5/11. // Copyright © 2020 didi. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.052632
179
0.747159
d7878581ccd88c45e3fc10c733eb9f55d4404ee2
364
// // AuthorizationCode.swift // Server // // Created by BluDesign, LLC on 4/2/17. // import Foundation import MongoKitten struct AuthorizationCode { // MARK: - Parameters static let collectionName = "authorizationCode" static var collection: MongoKitten.Collection { return MongoProvider.shared.database[collectionName] } }
18.2
60
0.692308
5b0700441c673b40ae221f5eb120c8b150f113c1
761
// // Album.swift // camPod // // Created by Janco Erasmus on 2020/02/28. // import Foundation public class Album { //Read from Firebase the title of the Album, its thumnail image and the images array var title: String var thumbnail: UIImage var images: [UIImage] init(title: String,thumbnail: UIImage, images: [UIImage]) { self.title = title self.thumbnail = thumbnail self.images = images } func getThumbnail() -> UIImage { return thumbnail } func getSingleImage(index: Int) -> UIImage { return images[index] } func getAlbumSize() -> Int { return images.count } func appendImage(image: UIImage) { images.append(image) } }
20.567568
88
0.603154
7926a599aad6ab6c16fdd65915b1372fd36eafbf
444
// // DoubleRounder.swift // Duino-Coin // // Created by Fahim Rahman on 12/3/21. // import Foundation // Double rounder extension Double { func round(to decimalPlaces: Int) -> Double { let precisionNumber = pow(10,Double(decimalPlaces)) var n = self // self is a current value of the Double that you will round n = n * precisionNumber n.round() n = n / precisionNumber return n } }
21.142857
81
0.617117
4aaab0964bb04b8b8c04eca6530589e08c896ec8
7,057
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: google/protobuf/unittest_lazy_dependencies.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: [email protected] (Todd Rafacz) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // // A proto file we will use for unit testing. import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } struct ProtobufUnittest_LazyImports_ImportedMessage { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var lazyMessage: ProtobufUnittest_LazyImports_LazyMessage { get {return _lazyMessage ?? ProtobufUnittest_LazyImports_LazyMessage()} set {_lazyMessage = newValue} } /// Returns true if `lazyMessage` has been explicitly set. var hasLazyMessage: Bool {return self._lazyMessage != nil} /// Clears the value of `lazyMessage`. Subsequent reads from it will return its default value. mutating func clearLazyMessage() {self._lazyMessage = nil} var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _lazyMessage: ProtobufUnittest_LazyImports_LazyMessage? = nil } struct ProtobufUnittest_LazyImports_MessageCustomOption { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct ProtobufUnittest_LazyImports_MessageCustomOption2 { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "protobuf_unittest.lazy_imports" extension ProtobufUnittest_LazyImports_ImportedMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".ImportedMessage" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "lazy_message"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularMessageField(value: &self._lazyMessage) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._lazyMessage { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: ProtobufUnittest_LazyImports_ImportedMessage, rhs: ProtobufUnittest_LazyImports_ImportedMessage) -> Bool { if lhs._lazyMessage != rhs._lazyMessage {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension ProtobufUnittest_LazyImports_MessageCustomOption: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".MessageCustomOption" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: ProtobufUnittest_LazyImports_MessageCustomOption, rhs: ProtobufUnittest_LazyImports_MessageCustomOption) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension ProtobufUnittest_LazyImports_MessageCustomOption2: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".MessageCustomOption2" static let _protobuf_nameMap = SwiftProtobuf._NameMap() mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let _ = try decoder.nextFieldNumber() { } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: ProtobufUnittest_LazyImports_MessageCustomOption2, rhs: ProtobufUnittest_LazyImports_MessageCustomOption2) -> Bool { if lhs.unknownFields != rhs.unknownFields {return false} return true } }
41.757396
161
0.771291
096d858e8b074f2d555a82188df3c9f22721e4d5
3,400
// // SearchFieldController.swift // SearchField // // Created by Mustafa Khalil on 8/7/19. // Copyright © 2019 Molteo. All rights reserved. // import UIKit import os.log // TODO: - Documantation public protocol SearchResultsControllerDelegate: NSObjectProtocol { func selected(searchResult: SearchResult) } open class SearchResultsController<Cell: GenericCell<Element>, Element: SearchResult>: UITableViewController { private let cellIdentity = "Search-field-cellID" private var _items: [SearchResult] = [] { didSet { _filteredItems = _items } } private var _filteredItems: [SearchResult] = [] { didSet { tableView.reloadData() } } open var count: Int { get { return _filteredItems.count } } open var filteredItems: [SearchResult] { get { return _filteredItems } } open var items: [SearchResult] { get { return _items } } weak var delegate: SearchResultsControllerDelegate? public init(delegate: SearchResultsControllerDelegate) { self.delegate = delegate super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { os_log("deinit SearchResultsController", type: .debug) } open override func viewDidLoad() { super.viewDidLoad() setupTableView() } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _filteredItems.count } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentity, for: indexPath) as! Cell cell.item = _filteredItems[indexPath.row] as? Element return cell } open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let item = _filteredItems[indexPath.item] delegate?.selected(searchResult: item) } } extension SearchResultsController { public func setItems(searchItems: [SearchResult]) { _items = searchItems } public func filtered(searchItems: [SearchResult]) { _filteredItems = searchItems } func filter(text: String?) { guard let txt = text, !txt.isEmpty else { shouldRefreshItems() return } _filteredItems = items.filter { (item) -> Bool in return item.title.contains(txt) } } public func shouldRefreshItems() { _filteredItems = _items } public func reloadData() { tableView.reloadData() } } // MARK: - UI Setup extension SearchResultsController { func setupTableView() { tableView.register(Cell.self, forCellReuseIdentifier: cellIdentity) tableView.tableFooterView = UIView() tableView.keyboardDismissMode = .onDrag tableView.clipsToBounds = true } }
25.185185
114
0.625882
038e870356a70c976656d3ca657495ee1c97af41
1,164
// // FeedItem.swift // RedditRSSReader // // Created by Marc Maguire on 2018-02-11. // Copyright © 2018 Marc Maguire. All rights reserved. // import Foundation import UIKit class FeedItem { let id: String let title: String let dateUpdated: String let category: String var thumbnail: Data? let thumbnailURLString: String? let contentURLString: String var isPinned: Bool = false init(id: String, title: String, dateUpdated: String, category: String, thumbnail: Data? = nil, thumbnailURLString: String?, contentURLString: String, isPinned: Bool = false) { self.id = id self.title = title self.dateUpdated = dateUpdated self.category = category self.thumbnail = thumbnail self.thumbnailURLString = thumbnailURLString self.contentURLString = contentURLString self.isPinned = isPinned } convenience init(fromEntity feedItemEntity: FeedItemEntity) { self.init(id: feedItemEntity.id, title: feedItemEntity.title, dateUpdated: feedItemEntity.dateUpdated, category: feedItemEntity.category, thumbnail: feedItemEntity.thumbnail as Data?, thumbnailURLString: nil, contentURLString: feedItemEntity.contentURLString, isPinned: true) } }
31.459459
277
0.768041
ab83fa04ab7ab115f520d80e4e858b593c910786
1,060
// // GalleryView.swift // PrivateVault // // Created by Emilio Peláez on 19/2/21. // import SwiftUI struct GalleryView: View { @State var contentMode: ContentMode = .fill @State var selectedItem: Item? var columns: [GridItem] { [ GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()) ] } var data: [Item] = (1...6) .map { "file\($0)" } .compactMap { UIImage(named: $0) } .map(Item.init) var body: some View { ScrollView { LazyVGrid(columns: columns) { ForEach(data) { item in Color.red.aspectRatio(1, contentMode: .fill) .overlay( item.placeholder .resizable() .aspectRatio(contentMode: contentMode) ) .clipped() .onTapGesture { } } } } .navigation(item: $selectedItem, destination: quickLookView) } @ViewBuilder func quickLookView(_ item: Item) -> some View { QuickLookView(title: item.id.description, url: URL(string: "")) } } struct GalleryView_Previews: PreviewProvider { static var previews: some View { GalleryView() } }
18.928571
65
0.633019
d504cb319162b48704a9e3a9578c456176cedc4a
653
// // AppDelegate.swift // AVLab // // Created by lobster on 2021/9/4. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let navigationController = UINavigationController(rootViewController: AVLabEntryViewController()) window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = .white window?.rootViewController = navigationController window?.makeKeyAndVisible() return true } }
26.12
145
0.719755
1a971e9eaa0d53332490174305d9481a79651138
273
import Foundation /// Represents a task to be completed public enum Activity: String { case call case coffee case tshirt case talent case sales case interview case event case priority case partnership } extension Activity: AutoList {}
16.058824
37
0.692308
d734846668eea54396e720ff5e745570e9c1e1fc
473
// // AVCameraPreviewView.swift // AVFaceDetection // // Created by Dan Fechtmann on 04/11/2018. // Copyright © 2018 Dan Fechtmann. All rights reserved. // import Foundation import UIKit import AVKit class AVCameraPreviewView: UIView { override class var layerClass: AnyClass { return AVCaptureVideoPreviewLayer.self } var videoPreviewLayer: AVCaptureVideoPreviewLayer { return layer as! AVCaptureVideoPreviewLayer } }
18.92
56
0.708245
202265a5ddee26f8ce485cd0e4abc008ca1d9434
4,145
// WalletSeedWordsTests.swift /* Package MobileWalletTests Created by Adrian Truszczynski on 12/07/2021 Using Swift 5.0 Running on macOS 12.0 Copyright 2019 The Tari Project Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ @testable import Tari_Aurora import XCTest final class SeedWordsTests: XCTestCase { func testWalletSeedInitializationWithSuccess() { let inputSeedWords = [ "abandon", "oven", "excuse", "sustain", "next", "story", "fruit", "tool", "ramp", "milk", "student", "snake", "hat", "table", "hospital", "pipe", "business", "farm", "ensure", "approve", "uniform", "fish", "wild", "wagon" ] let seedWords = try? SeedWords(words: inputSeedWords) XCTAssertNotNil(seedWords) } func testWalletSeedInitliaziationWithInvalidWord() { let inputSeedWords = [ "abandon", "oven", "excuse", "sustain", "next", "story", "fruit", "tool", "IAMERROR", "milk", "student", "snake", "hat", "table", "hospital", "pipe", "business", "farm", "ensure", "approve", "uniform", "fish", "wild", "wagon" ] var seedWords: SeedWords? do { seedWords = try SeedWords(words: inputSeedWords) } catch SeedWords.Error.invalidSeedWord { } catch { XCTFail("Unexpected error") } XCTAssertNil(seedWords) } func testWalletSeedInitliaziationWithNotEnoughtSeedWords() { let inputSeedWords = [ "abandon", "oven", "excuse", "sustain", "next", "story", "fruit", "tool", "ramp", "milk" ] var seedWords: SeedWords? do { seedWords = try SeedWords(words: inputSeedWords) } catch SeedWords.Error.phraseIsTooShort { } catch { XCTFail("Unexpected error") } XCTAssertNil(seedWords) } func testWalletSeedInitliaziationWithTooManySeedWords() { let inputSeedWords = [ "abandon", "oven", "excuse", "sustain", "next", "story", "fruit", "tool", "ramp", "milk", "student", "snake", "hat", "table", "hospital", "pipe", "business", "farm", "ensure", "approve", "uniform", "fish", "wild", "wagon", "abandon" ] var seedWords: SeedWords? do { seedWords = try SeedWords(words: inputSeedWords) } catch SeedWords.Error.phraseIsTooLong { } catch { XCTFail("Unexpected error") } XCTAssertNil(seedWords) } }
33.427419
78
0.625573
612be16a033c9876fc9d2fa95b49b540f19c3802
20,687
// // LegacyInsulinDeliveryTableViewController.swift // Naterade // // Created by Nathan Racklyeft on 1/30/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import UIKit import LoopKit private let ReuseIdentifier = "Right Detail" public final class LegacyInsulinDeliveryTableViewController: UITableViewController { @IBOutlet var needsConfigurationMessageView: ErrorBackgroundView! @IBOutlet weak var iobValueLabel: UILabel! { didSet { iobValueLabel.textColor = headerValueLabelColor } } @IBOutlet weak var iobDateLabel: UILabel! @IBOutlet weak var totalValueLabel: UILabel! { didSet { totalValueLabel.textColor = headerValueLabelColor } } @IBOutlet weak var totalDateLabel: UILabel! @IBOutlet weak var dataSourceSegmentedControl: UISegmentedControl! { didSet { let titleFont = UIFont.systemFont(ofSize: 15, weight: .semibold) dataSourceSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: titleFont], for: .normal) dataSourceSegmentedControl.setTitle(NSLocalizedString("Event History", comment: "Segmented button title for insulin delivery log event history"), forSegmentAt: 0) dataSourceSegmentedControl.setTitle(NSLocalizedString("Reservoir", comment: "Segmented button title for insulin delivery log reservoir history"), forSegmentAt: 1) } } public var enableEntryDeletion: Bool = true public var doseStore: DoseStore? { didSet { if let doseStore = doseStore { doseStoreObserver = NotificationCenter.default.addObserver(forName: nil, object: doseStore, queue: OperationQueue.main, using: { [weak self] (note) -> Void in switch note.name { case DoseStore.valuesDidChange: if self?.isViewLoaded == true { self?.reloadData() } default: break } }) } else { doseStoreObserver = nil } } } public var headerValueLabelColor: UIColor = .label private var updateTimer: Timer? { willSet { if let timer = updateTimer { timer.invalidate() } } } public override func viewDidLoad() { super.viewDidLoad() state = .display } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateTimelyStats(nil) } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let updateInterval = TimeInterval(minutes: 5) let timer = Timer( fireAt: Date().dateCeiledToTimeInterval(updateInterval).addingTimeInterval(2), interval: updateInterval, target: self, selector: #selector(updateTimelyStats(_:)), userInfo: nil, repeats: true ) updateTimer = timer RunLoop.current.add(timer, forMode: RunLoop.Mode.default) } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) updateTimer = nil } public override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if tableView.isEditing { tableView.endEditing(true) } } deinit { if let observer = doseStoreObserver { NotificationCenter.default.removeObserver(observer) } } public override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if editing && enableEntryDeletion { let item = UIBarButtonItem( title: LocalizedString("Delete All", comment: "Button title to delete all objects"), style: .plain, target: self, action: #selector(confirmDeletion(_:)) ) navigationItem.setLeftBarButton(item, animated: true) } else { navigationItem.setLeftBarButton(nil, animated: true) } } // MARK: - Data private enum State { case unknown case unavailable(Error?) case display } private var state = State.unknown { didSet { if isViewLoaded { reloadData() } } } private enum DataSourceSegment: Int { case history = 0 case reservoir } private enum Values { case reservoir([ReservoirValue]) case history([PersistedPumpEvent]) } // Not thread-safe private var values = Values.reservoir([]) { didSet { let count: Int switch values { case .reservoir(let values): count = values.count case .history(let values): count = values.count } if count > 0 && enableEntryDeletion { navigationItem.rightBarButtonItem = self.editButtonItem } } } private func reloadData() { switch state { case .unknown: break case .unavailable(let error): self.tableView.tableHeaderView?.isHidden = true self.tableView.tableFooterView = UIView() tableView.backgroundView = needsConfigurationMessageView if let error = error { needsConfigurationMessageView.errorDescriptionLabel.text = String(describing: error) } else { needsConfigurationMessageView.errorDescriptionLabel.text = nil } case .display: self.tableView.backgroundView = nil self.tableView.tableHeaderView?.isHidden = false self.tableView.tableFooterView = nil switch DataSourceSegment(rawValue: dataSourceSegmentedControl.selectedSegmentIndex)! { case .reservoir: doseStore?.getReservoirValues(since: Date.distantPast) { (result) in DispatchQueue.main.async { () -> Void in switch result { case .failure(let error): self.state = .unavailable(error) case .success(let reservoirValues): self.values = .reservoir(reservoirValues) self.tableView.reloadData() } } self.updateTimelyStats(nil) self.updateTotal() } case .history: doseStore?.getPumpEventValues(since: Date.distantPast) { (result) in DispatchQueue.main.async { () -> Void in switch result { case .failure(let error): self.state = .unavailable(error) case .success(let pumpEventValues): self.values = .history(pumpEventValues) self.tableView.reloadData() } } self.updateTimelyStats(nil) self.updateTotal() } } } } @objc func updateTimelyStats(_: Timer?) { updateIOB() } private lazy var iobNumberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 2 return formatter }() private lazy var timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short return formatter }() private func updateIOB() { if case .display = state { doseStore?.insulinOnBoard(at: Date()) { (result) -> Void in DispatchQueue.main.async { switch result { case .failure: self.iobValueLabel.text = "…" self.iobDateLabel.text = nil case .success(let iob): self.iobValueLabel.text = self.iobNumberFormatter.string(from: iob.value) self.iobDateLabel.text = String(format: LocalizedString("com.loudnate.InsulinKit.IOBDateLabel", value: "at %1$@", comment: "The format string describing the date of an IOB value. The first format argument is the localized date."), self.timeFormatter.string(from: iob.startDate)) } } } } } private func updateTotal() { if case .display = state { let midnight = Calendar.current.startOfDay(for: Date()) doseStore?.getTotalUnitsDelivered(since: midnight) { (result) in DispatchQueue.main.async { switch result { case .failure: self.totalValueLabel.text = "…" self.totalDateLabel.text = nil case .success(let result): self.totalValueLabel.text = NumberFormatter.localizedString(from: NSNumber(value: result.value), number: .none) self.totalDateLabel.text = String(format: LocalizedString("com.loudnate.InsulinKit.totalDateLabel", value: "since %1$@", comment: "The format string describing the starting date of a total value. The first format argument is the localized date."), DateFormatter.localizedString(from: result.startDate, dateStyle: .none, timeStyle: .short)) } } } } } private var doseStoreObserver: Any? { willSet { if let observer = doseStoreObserver { NotificationCenter.default.removeObserver(observer) } } } @IBAction func selectedSegmentChanged(_ sender: Any) { reloadData() } @IBAction func confirmDeletion(_ sender: Any) { guard !deletionPending else { return } let confirmMessage: String switch DataSourceSegment(rawValue: dataSourceSegmentedControl.selectedSegmentIndex)! { case .reservoir: confirmMessage = LocalizedString("Are you sure you want to delete all reservoir values?", comment: "Action sheet confirmation message for reservoir deletion") case .history: confirmMessage = LocalizedString("Are you sure you want to delete all history entries?", comment: "Action sheet confirmation message for pump history deletion") } let sheet = UIAlertController(deleteAllConfirmationMessage: confirmMessage) { self.deleteAllObjects() } present(sheet, animated: true) } private var deletionPending = false private func deleteAllObjects() { guard !deletionPending else { return } deletionPending = true let completion = { (_: DoseStore.DoseStoreError?) -> Void in DispatchQueue.main.async { self.deletionPending = false self.setEditing(false, animated: true) } } switch DataSourceSegment(rawValue: dataSourceSegmentedControl.selectedSegmentIndex)! { case .reservoir: doseStore?.deleteAllReservoirValues(completion) case .history: doseStore?.deleteAllPumpEvents(completion) } } // MARK: - Table view data source public override func numberOfSections(in tableView: UITableView) -> Int { switch state { case .unknown, .unavailable: return 0 case .display: return 1 } } public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch values { case .reservoir(let values): return values.count case .history(let values): return values.count } } public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifier, for: indexPath) if case .display = state { switch self.values { case .reservoir(let values): let entry = values[indexPath.row] let volume = NumberFormatter.localizedString(from: NSNumber(value: entry.unitVolume), number: .decimal) let time = timeFormatter.string(from: entry.startDate) cell.textLabel?.text = String(format: NSLocalizedString("%1$@ U", comment: "Reservoir entry (1: volume value)"), volume) cell.textLabel?.textColor = .label cell.detailTextLabel?.text = time cell.accessoryType = .none cell.selectionStyle = .none case .history(let values): let entry = values[indexPath.row] let time = timeFormatter.string(from: entry.date) if let attributedText = entry.dose?.localizedAttributedDescription { cell.textLabel?.attributedText = attributedText } else { cell.textLabel?.text = entry.title } cell.detailTextLabel?.text = time cell.accessoryType = entry.isUploaded ? .checkmark : .none cell.selectionStyle = .default } } return cell } public override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return enableEntryDeletion } public override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete, case .display = state { switch values { case .reservoir(let reservoirValues): var reservoirValues = reservoirValues let value = reservoirValues.remove(at: indexPath.row) self.values = .reservoir(reservoirValues) tableView.deleteRows(at: [indexPath], with: .automatic) doseStore?.deleteReservoirValue(value) { (_, error) -> Void in if let error = error { DispatchQueue.main.async { self.present(UIAlertController(with: error), animated: true) self.reloadData() } } } case .history(let historyValues): var historyValues = historyValues let value = historyValues.remove(at: indexPath.row) self.values = .history(historyValues) tableView.deleteRows(at: [indexPath], with: .automatic) doseStore?.deletePumpEvent(value) { (error) -> Void in if let error = error { DispatchQueue.main.async { self.present(UIAlertController(with: error), animated: true) self.reloadData() } } } } } } public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if case .display = state, case .history(let history) = values { let entry = history[indexPath.row] let vc = CommandResponseViewController(command: { (completionHandler) -> String in var description = [String]() description.append(self.timeFormatter.string(from: entry.date)) if let title = entry.title { description.append(title) } if let dose = entry.dose { description.append(String(describing: dose)) } if let raw = entry.raw { description.append(raw.hexadecimalString) } return description.joined(separator: "\n\n") }) vc.title = LocalizedString("Pump Event", comment: "The title of the screen displaying a pump event") show(vc, sender: indexPath) } } } fileprivate extension UIAlertController { convenience init(deleteAllConfirmationMessage: String, confirmationHandler handler: @escaping () -> Void) { self.init( title: nil, message: deleteAllConfirmationMessage, preferredStyle: .actionSheet ) addAction(UIAlertAction( title: LocalizedString("Delete All", comment: "Button title to delete all objects"), style: .destructive, handler: { (_) in handler() } )) addAction(UIAlertAction( title: LocalizedString("Cancel", comment: "The title of the cancel action in an action sheet"), style: .cancel )) } } extension DoseEntry { fileprivate var numberFormatter: NumberFormatter { let numberFormatter = NumberFormatter() numberFormatter.maximumFractionDigits = DoseEntry.unitsPerHour.maxFractionDigits return numberFormatter } fileprivate var localizedAttributedDescription: NSAttributedString? { let font = UIFont.preferredFont(forTextStyle: .body) switch type { case .bolus: let description: String if let deliveredUnits = deliveredUnits, deliveredUnits != programmedUnits { description = String(format: NSLocalizedString("Interrupted %1$@: <b>%2$@</b> of %3$@ %4$@", comment: "Description of an interrupted bolus dose entry (1: title for dose type, 2: value (? if no value) in bold, 3: programmed value (? if no value), 4: unit)"), type.localizedDescription, numberFormatter.string(from: deliveredUnits) ?? "?", numberFormatter.string(from: programmedUnits) ?? "?", DoseEntry.units.shortLocalizedUnitString()) } else { description = String(format: NSLocalizedString("%1$@: <b>%2$@</b> %3$@", comment: "Description of a bolus dose entry (1: title for dose type, 2: value (? if no value) in bold, 3: unit)"), type.localizedDescription, numberFormatter.string(from: programmedUnits) ?? "?", DoseEntry.units.shortLocalizedUnitString()) } return createAttributedDescription(from: description, with: font) case .basal, .tempBasal: let description = String(format: NSLocalizedString("%1$@: <b>%2$@</b> %3$@", comment: "Description of a basal temp basal dose entry (1: title for dose type, 2: value (? if no value) in bold, 3: unit)"), type.localizedDescription, numberFormatter.string(from: unitsPerHour) ?? "?", DoseEntry.unitsPerHour.shortLocalizedUnitString()) return createAttributedDescription(from: description, with: font) case .suspend, .resume: let attributes: [NSAttributedString.Key: Any] = [ .font: font, .foregroundColor: UIColor.secondaryLabel ] return NSAttributedString(string: type.localizedDescription, attributes: attributes) } } fileprivate func createAttributedDescription(from description: String, with font: UIFont) -> NSAttributedString? { let descriptionWithFont = String(format:"<style>body{font-family: '-apple-system', '\(font.fontName)'; font-size: \(font.pointSize);}</style>%@", description) guard let attributedDescription = try? NSMutableAttributedString(data: Data(descriptionWithFont.utf8), options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else { return nil } attributedDescription.enumerateAttribute(.font, in: NSRange(location: 0, length: attributedDescription.length)) { value, range, stop in // bold font items have a dominate colour if let font = value as? UIFont, font.fontDescriptor.symbolicTraits.contains(.traitBold) { attributedDescription.addAttributes([.foregroundColor: UIColor.label], range: range) } else { attributedDescription.addAttributes([.foregroundColor: UIColor.secondaryLabel], range: range) } } return attributedDescription } }
37.341155
451
0.583507
6248b1fdb4cd0f4e92d1bb47eae45d8d26bc9bdc
938
// // ReportInProductList.swift // // Generated by openapi-generator // https://openapi-generator.tech // import AnyCodable import Foundation import Vapor /** */ public final class ReportInProductList: Content, Hashable { /** */ public var reports: [ReportInProductListItem]? public init(reports: [ReportInProductListItem]? = nil) { self.reports = reports } public enum CodingKeys: String, CodingKey, CaseIterable { case reports } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(reports, forKey: .reports) } public static func == (lhs: ReportInProductList, rhs: ReportInProductList) -> Bool { lhs.reports == rhs.reports } public func hash(into hasher: inout Hasher) { hasher.combine(reports?.hashValue) } }
23.45
88
0.67484
645caf7734ef6ce894a20f96c08f15d664eb3ea2
394
// // Weak.swift // Ubiquity // // Created by sagesse on 07/08/2017. // Copyright © 2017 SAGESSE. All rights reserved. // internal class Weak<Wrapped> { /// Generate a weak object init(_ some: AnyObject) { _some = some } /// forward to this is var some: Wrapped? { return _some as? Wrapped } private weak var _some: AnyObject? }
16.416667
50
0.576142
def9407641870d29c37eb48e50f601ad83c15a10
78
import DrStringCore run(arguments: Array(CommandLine.arguments.dropFirst()))
19.5
56
0.820513
ff0307d5832332917d580ab0e6d8cfeedfb7b053
73,709
// @generated // This file was automatically generated and should not be edited. import Apollo import Foundation /// GQL namespace public extension GQL { final class GetItemsQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetItems($page: Int!, $limit: Int!) { item(page: $page, limit: $limit) { __typename ...BaseItemData } } """ public let operationName: String = "GetItems" public var queryDocument: String { var document: String = operationDefinition document.append("\n" + BaseItemData.fragmentDefinition) return document } public var page: Int public var limit: Int public init(page: Int, limit: Int) { self.page = page self.limit = limit } public var variables: GraphQLMap? { return ["page": page, "limit": limit] } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("item", arguments: ["page": GraphQLVariable("page"), "limit": GraphQLVariable("limit")], type: .list(.object(Item.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(item: [Item?]? = nil) { self.init(unsafeResultMap: ["__typename": "Query", "item": item.flatMap { (value: [Item?]) -> [ResultMap?] in value.map { (value: Item?) -> ResultMap? in value.flatMap { (value: Item) -> ResultMap in value.resultMap } } }]) } public var item: [Item?]? { get { return (resultMap["item"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Item?] in value.map { (value: ResultMap?) -> Item? in value.flatMap { (value: ResultMap) -> Item in Item(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Item?]) -> [ResultMap?] in value.map { (value: Item?) -> ResultMap? in value.flatMap { (value: Item) -> ResultMap in value.resultMap } } }, forKey: "item") } } public struct Item: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Item"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(BaseItemData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil) { self.init(unsafeResultMap: ["__typename": "Item", "id": id, "image": image, "name": name, "description": description]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var baseItemData: BaseItemData { get { return BaseItemData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } } final class GetItemQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetItem($id: String!) { getItem(id: $id) { __typename ...ItemData } } """ public let operationName: String = "GetItem" public var queryDocument: String { var document: String = operationDefinition document.append("\n" + ItemData.fragmentDefinition) return document } public var id: String public init(id: String) { self.id = id } public var variables: GraphQLMap? { return ["id": id] } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("getItem", arguments: ["id": GraphQLVariable("id")], type: .nonNull(.object(GetItem.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(getItem: GetItem) { self.init(unsafeResultMap: ["__typename": "Query", "getItem": getItem.resultMap]) } public var getItem: GetItem { get { return GetItem(unsafeResultMap: resultMap["getItem"]! as! ResultMap) } set { resultMap.updateValue(newValue.resultMap, forKey: "getItem") } } public struct GetItem: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Item"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(ItemData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil, type: String? = nil, effect: String? = nil) { self.init(unsafeResultMap: ["__typename": "Item", "id": id, "image": image, "name": name, "description": description, "type": type, "effect": effect]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var itemData: ItemData { get { return ItemData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } } final class GetArmorsQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetArmors($page: Int!, $limit: Int!) { armor(page: $page, limit: $limit) { __typename ...BaseArmorData } } """ public let operationName: String = "GetArmors" public var queryDocument: String { var document: String = operationDefinition document.append("\n" + BaseArmorData.fragmentDefinition) return document } public var page: Int public var limit: Int public init(page: Int, limit: Int) { self.page = page self.limit = limit } public var variables: GraphQLMap? { return ["page": page, "limit": limit] } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("armor", arguments: ["page": GraphQLVariable("page"), "limit": GraphQLVariable("limit")], type: .list(.object(Armor.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(armor: [Armor?]? = nil) { self.init(unsafeResultMap: ["__typename": "Query", "armor": armor.flatMap { (value: [Armor?]) -> [ResultMap?] in value.map { (value: Armor?) -> ResultMap? in value.flatMap { (value: Armor) -> ResultMap in value.resultMap } } }]) } public var armor: [Armor?]? { get { return (resultMap["armor"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Armor?] in value.map { (value: ResultMap?) -> Armor? in value.flatMap { (value: ResultMap) -> Armor in Armor(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Armor?]) -> [ResultMap?] in value.map { (value: Armor?) -> ResultMap? in value.flatMap { (value: Armor) -> ResultMap in value.resultMap } } }, forKey: "armor") } } public struct Armor: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Armor"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(BaseArmorData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil) { self.init(unsafeResultMap: ["__typename": "Armor", "id": id, "image": image, "name": name, "description": description]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var baseArmorData: BaseArmorData { get { return BaseArmorData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } } final class GetArmorQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetArmor($id: String!) { getArmor(id: $id) { __typename ...ArmorData } } """ public let operationName: String = "GetArmor" public var queryDocument: String { var document: String = operationDefinition document.append("\n" + ArmorData.fragmentDefinition) document.append("\n" + AttributeEntryData.fragmentDefinition) return document } public var id: String public init(id: String) { self.id = id } public var variables: GraphQLMap? { return ["id": id] } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("getArmor", arguments: ["id": GraphQLVariable("id")], type: .nonNull(.object(GetArmor.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(getArmor: GetArmor) { self.init(unsafeResultMap: ["__typename": "Query", "getArmor": getArmor.resultMap]) } public var getArmor: GetArmor { get { return GetArmor(unsafeResultMap: resultMap["getArmor"]! as! ResultMap) } set { resultMap.updateValue(newValue.resultMap, forKey: "getArmor") } } public struct GetArmor: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Armor"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(ArmorData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var armorData: ArmorData { get { return ArmorData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } } final class GetWeaponsQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetWeapons($page: Int!, $limit: Int!) { weapon(page: $page, limit: $limit) { __typename ...BaseWeaponData } } """ public let operationName: String = "GetWeapons" public var queryDocument: String { var document: String = operationDefinition document.append("\n" + BaseWeaponData.fragmentDefinition) return document } public var page: Int public var limit: Int public init(page: Int, limit: Int) { self.page = page self.limit = limit } public var variables: GraphQLMap? { return ["page": page, "limit": limit] } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("weapon", arguments: ["page": GraphQLVariable("page"), "limit": GraphQLVariable("limit")], type: .list(.object(Weapon.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(weapon: [Weapon?]? = nil) { self.init(unsafeResultMap: ["__typename": "Query", "weapon": weapon.flatMap { (value: [Weapon?]) -> [ResultMap?] in value.map { (value: Weapon?) -> ResultMap? in value.flatMap { (value: Weapon) -> ResultMap in value.resultMap } } }]) } public var weapon: [Weapon?]? { get { return (resultMap["weapon"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Weapon?] in value.map { (value: ResultMap?) -> Weapon? in value.flatMap { (value: ResultMap) -> Weapon in Weapon(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Weapon?]) -> [ResultMap?] in value.map { (value: Weapon?) -> ResultMap? in value.flatMap { (value: Weapon) -> ResultMap in value.resultMap } } }, forKey: "weapon") } } public struct Weapon: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Weapon"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(BaseWeaponData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil) { self.init(unsafeResultMap: ["__typename": "Weapon", "id": id, "image": image, "name": name, "description": description]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var baseWeaponData: BaseWeaponData { get { return BaseWeaponData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } } final class GetWeaponQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetWeapon($id: String!) { getWeapon(id: $id) { __typename ...WeaponData } } """ public let operationName: String = "GetWeapon" public var queryDocument: String { var document: String = operationDefinition document.append("\n" + WeaponData.fragmentDefinition) document.append("\n" + AttributeEntryData.fragmentDefinition) document.append("\n" + ScallingEntryData.fragmentDefinition) return document } public var id: String public init(id: String) { self.id = id } public var variables: GraphQLMap? { return ["id": id] } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("getWeapon", arguments: ["id": GraphQLVariable("id")], type: .nonNull(.object(GetWeapon.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(getWeapon: GetWeapon) { self.init(unsafeResultMap: ["__typename": "Query", "getWeapon": getWeapon.resultMap]) } public var getWeapon: GetWeapon { get { return GetWeapon(unsafeResultMap: resultMap["getWeapon"]! as! ResultMap) } set { resultMap.updateValue(newValue.resultMap, forKey: "getWeapon") } } public struct GetWeapon: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Weapon"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(WeaponData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var weaponData: WeaponData { get { return WeaponData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } } final class GetTalismansQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetTalismans($page: Int!, $limit: Int!) { talisman(page: $page, limit: $limit) { __typename ...BaseTalismanData } } """ public let operationName: String = "GetTalismans" public var queryDocument: String { var document: String = operationDefinition document.append("\n" + BaseTalismanData.fragmentDefinition) return document } public var page: Int public var limit: Int public init(page: Int, limit: Int) { self.page = page self.limit = limit } public var variables: GraphQLMap? { return ["page": page, "limit": limit] } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("talisman", arguments: ["page": GraphQLVariable("page"), "limit": GraphQLVariable("limit")], type: .list(.object(Talisman.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(talisman: [Talisman?]? = nil) { self.init(unsafeResultMap: ["__typename": "Query", "talisman": talisman.flatMap { (value: [Talisman?]) -> [ResultMap?] in value.map { (value: Talisman?) -> ResultMap? in value.flatMap { (value: Talisman) -> ResultMap in value.resultMap } } }]) } public var talisman: [Talisman?]? { get { return (resultMap["talisman"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Talisman?] in value.map { (value: ResultMap?) -> Talisman? in value.flatMap { (value: ResultMap) -> Talisman in Talisman(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Talisman?]) -> [ResultMap?] in value.map { (value: Talisman?) -> ResultMap? in value.flatMap { (value: Talisman) -> ResultMap in value.resultMap } } }, forKey: "talisman") } } public struct Talisman: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Talisman"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(BaseTalismanData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil) { self.init(unsafeResultMap: ["__typename": "Talisman", "id": id, "image": image, "name": name, "description": description]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var baseTalismanData: BaseTalismanData { get { return BaseTalismanData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } } final class GetTalismanQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetTalisman($id: String!) { getTalisman(id: $id) { __typename ...TalismanData } } """ public let operationName: String = "GetTalisman" public var queryDocument: String { var document: String = operationDefinition document.append("\n" + TalismanData.fragmentDefinition) return document } public var id: String public init(id: String) { self.id = id } public var variables: GraphQLMap? { return ["id": id] } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("getTalisman", arguments: ["id": GraphQLVariable("id")], type: .nonNull(.object(GetTalisman.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(getTalisman: GetTalisman) { self.init(unsafeResultMap: ["__typename": "Query", "getTalisman": getTalisman.resultMap]) } public var getTalisman: GetTalisman { get { return GetTalisman(unsafeResultMap: resultMap["getTalisman"]! as! ResultMap) } set { resultMap.updateValue(newValue.resultMap, forKey: "getTalisman") } } public struct GetTalisman: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Talisman"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(TalismanData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil, effect: String? = nil) { self.init(unsafeResultMap: ["__typename": "Talisman", "id": id, "image": image, "name": name, "description": description, "effect": effect]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var talismanData: TalismanData { get { return TalismanData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } } final class GetSearchItemsQuery: GraphQLQuery { /// The raw GraphQL definition of this operation. public let operationDefinition: String = """ query GetSearchItems($query: String!, $page: Int!, $limit: Int!) { item(page: $page, limit: $limit, search: $query) { __typename id name image } armor(page: $page, limit: $limit, search: $query) { __typename id name image } weapon(page: $page, limit: $limit, search: $query) { __typename id name image } talisman(page: $page, limit: $limit, search: $query) { __typename id name image } } """ public let operationName: String = "GetSearchItems" public var query: String public var page: Int public var limit: Int public init(query: String, page: Int, limit: Int) { self.query = query self.page = page self.limit = limit } public var variables: GraphQLMap? { return ["query": query, "page": page, "limit": limit] } public struct Data: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Query"] public static var selections: [GraphQLSelection] { return [ GraphQLField("item", arguments: ["page": GraphQLVariable("page"), "limit": GraphQLVariable("limit"), "search": GraphQLVariable("query")], type: .list(.object(Item.selections))), GraphQLField("armor", arguments: ["page": GraphQLVariable("page"), "limit": GraphQLVariable("limit"), "search": GraphQLVariable("query")], type: .list(.object(Armor.selections))), GraphQLField("weapon", arguments: ["page": GraphQLVariable("page"), "limit": GraphQLVariable("limit"), "search": GraphQLVariable("query")], type: .list(.object(Weapon.selections))), GraphQLField("talisman", arguments: ["page": GraphQLVariable("page"), "limit": GraphQLVariable("limit"), "search": GraphQLVariable("query")], type: .list(.object(Talisman.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(item: [Item?]? = nil, armor: [Armor?]? = nil, weapon: [Weapon?]? = nil, talisman: [Talisman?]? = nil) { self.init(unsafeResultMap: ["__typename": "Query", "item": item.flatMap { (value: [Item?]) -> [ResultMap?] in value.map { (value: Item?) -> ResultMap? in value.flatMap { (value: Item) -> ResultMap in value.resultMap } } }, "armor": armor.flatMap { (value: [Armor?]) -> [ResultMap?] in value.map { (value: Armor?) -> ResultMap? in value.flatMap { (value: Armor) -> ResultMap in value.resultMap } } }, "weapon": weapon.flatMap { (value: [Weapon?]) -> [ResultMap?] in value.map { (value: Weapon?) -> ResultMap? in value.flatMap { (value: Weapon) -> ResultMap in value.resultMap } } }, "talisman": talisman.flatMap { (value: [Talisman?]) -> [ResultMap?] in value.map { (value: Talisman?) -> ResultMap? in value.flatMap { (value: Talisman) -> ResultMap in value.resultMap } } }]) } public var item: [Item?]? { get { return (resultMap["item"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Item?] in value.map { (value: ResultMap?) -> Item? in value.flatMap { (value: ResultMap) -> Item in Item(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Item?]) -> [ResultMap?] in value.map { (value: Item?) -> ResultMap? in value.flatMap { (value: Item) -> ResultMap in value.resultMap } } }, forKey: "item") } } public var armor: [Armor?]? { get { return (resultMap["armor"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Armor?] in value.map { (value: ResultMap?) -> Armor? in value.flatMap { (value: ResultMap) -> Armor in Armor(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Armor?]) -> [ResultMap?] in value.map { (value: Armor?) -> ResultMap? in value.flatMap { (value: Armor) -> ResultMap in value.resultMap } } }, forKey: "armor") } } public var weapon: [Weapon?]? { get { return (resultMap["weapon"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Weapon?] in value.map { (value: ResultMap?) -> Weapon? in value.flatMap { (value: ResultMap) -> Weapon in Weapon(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Weapon?]) -> [ResultMap?] in value.map { (value: Weapon?) -> ResultMap? in value.flatMap { (value: Weapon) -> ResultMap in value.resultMap } } }, forKey: "weapon") } } public var talisman: [Talisman?]? { get { return (resultMap["talisman"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Talisman?] in value.map { (value: ResultMap?) -> Talisman? in value.flatMap { (value: ResultMap) -> Talisman in Talisman(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Talisman?]) -> [ResultMap?] in value.map { (value: Talisman?) -> ResultMap? in value.flatMap { (value: Talisman) -> ResultMap in value.resultMap } } }, forKey: "talisman") } } public struct Item: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Item"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("name", type: .scalar(String.self)), GraphQLField("image", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, name: String? = nil, image: String? = nil) { self.init(unsafeResultMap: ["__typename": "Item", "id": id, "name": name, "image": image]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } } public struct Armor: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Armor"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("name", type: .scalar(String.self)), GraphQLField("image", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, name: String? = nil, image: String? = nil) { self.init(unsafeResultMap: ["__typename": "Armor", "id": id, "name": name, "image": image]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } } public struct Weapon: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Weapon"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("name", type: .scalar(String.self)), GraphQLField("image", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, name: String? = nil, image: String? = nil) { self.init(unsafeResultMap: ["__typename": "Weapon", "id": id, "name": name, "image": image]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } } public struct Talisman: GraphQLSelectionSet { public static let possibleTypes: [String] = ["Talisman"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("name", type: .scalar(String.self)), GraphQLField("image", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, name: String? = nil, image: String? = nil) { self.init(unsafeResultMap: ["__typename": "Talisman", "id": id, "name": name, "image": image]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } } } } struct BaseItemData: GraphQLFragment { /// The raw GraphQL definition of this fragment. public static let fragmentDefinition: String = """ fragment BaseItemData on Item { __typename id image name description } """ public static let possibleTypes: [String] = ["Item"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("image", type: .scalar(String.self)), GraphQLField("name", type: .scalar(String.self)), GraphQLField("description", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil) { self.init(unsafeResultMap: ["__typename": "Item", "id": id, "image": image, "name": name, "description": description]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var description: String? { get { return resultMap["description"] as? String } set { resultMap.updateValue(newValue, forKey: "description") } } } struct BaseArmorData: GraphQLFragment { /// The raw GraphQL definition of this fragment. public static let fragmentDefinition: String = """ fragment BaseArmorData on Armor { __typename id image name description } """ public static let possibleTypes: [String] = ["Armor"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("image", type: .scalar(String.self)), GraphQLField("name", type: .scalar(String.self)), GraphQLField("description", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil) { self.init(unsafeResultMap: ["__typename": "Armor", "id": id, "image": image, "name": name, "description": description]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var description: String? { get { return resultMap["description"] as? String } set { resultMap.updateValue(newValue, forKey: "description") } } } struct BaseWeaponData: GraphQLFragment { /// The raw GraphQL definition of this fragment. public static let fragmentDefinition: String = """ fragment BaseWeaponData on Weapon { __typename id image name description } """ public static let possibleTypes: [String] = ["Weapon"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("image", type: .scalar(String.self)), GraphQLField("name", type: .scalar(String.self)), GraphQLField("description", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil) { self.init(unsafeResultMap: ["__typename": "Weapon", "id": id, "image": image, "name": name, "description": description]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var description: String? { get { return resultMap["description"] as? String } set { resultMap.updateValue(newValue, forKey: "description") } } } struct BaseTalismanData: GraphQLFragment { /// The raw GraphQL definition of this fragment. public static let fragmentDefinition: String = """ fragment BaseTalismanData on Talisman { __typename id image name description } """ public static let possibleTypes: [String] = ["Talisman"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("image", type: .scalar(String.self)), GraphQLField("name", type: .scalar(String.self)), GraphQLField("description", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil) { self.init(unsafeResultMap: ["__typename": "Talisman", "id": id, "image": image, "name": name, "description": description]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var description: String? { get { return resultMap["description"] as? String } set { resultMap.updateValue(newValue, forKey: "description") } } } struct ItemData: GraphQLFragment { /// The raw GraphQL definition of this fragment. public static let fragmentDefinition: String = """ fragment ItemData on Item { __typename id image name description type effect } """ public static let possibleTypes: [String] = ["Item"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("image", type: .scalar(String.self)), GraphQLField("name", type: .scalar(String.self)), GraphQLField("description", type: .scalar(String.self)), GraphQLField("type", type: .scalar(String.self)), GraphQLField("effect", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil, type: String? = nil, effect: String? = nil) { self.init(unsafeResultMap: ["__typename": "Item", "id": id, "image": image, "name": name, "description": description, "type": type, "effect": effect]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var description: String? { get { return resultMap["description"] as? String } set { resultMap.updateValue(newValue, forKey: "description") } } public var type: String? { get { return resultMap["type"] as? String } set { resultMap.updateValue(newValue, forKey: "type") } } public var effect: String? { get { return resultMap["effect"] as? String } set { resultMap.updateValue(newValue, forKey: "effect") } } } struct ArmorData: GraphQLFragment { /// The raw GraphQL definition of this fragment. public static let fragmentDefinition: String = """ fragment ArmorData on Armor { __typename id image name description weight resistance { __typename ...AttributeEntryData } dmgNegation { __typename ...AttributeEntryData } } """ public static let possibleTypes: [String] = ["Armor"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("image", type: .scalar(String.self)), GraphQLField("name", type: .scalar(String.self)), GraphQLField("description", type: .scalar(String.self)), GraphQLField("weight", type: .scalar(Int.self)), GraphQLField("resistance", type: .list(.object(Resistance.selections))), GraphQLField("dmgNegation", type: .list(.object(DmgNegation.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil, weight: Int? = nil, resistance: [Resistance?]? = nil, dmgNegation: [DmgNegation?]? = nil) { self.init(unsafeResultMap: ["__typename": "Armor", "id": id, "image": image, "name": name, "description": description, "weight": weight, "resistance": resistance.flatMap { (value: [Resistance?]) -> [ResultMap?] in value.map { (value: Resistance?) -> ResultMap? in value.flatMap { (value: Resistance) -> ResultMap in value.resultMap } } }, "dmgNegation": dmgNegation.flatMap { (value: [DmgNegation?]) -> [ResultMap?] in value.map { (value: DmgNegation?) -> ResultMap? in value.flatMap { (value: DmgNegation) -> ResultMap in value.resultMap } } }]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var description: String? { get { return resultMap["description"] as? String } set { resultMap.updateValue(newValue, forKey: "description") } } public var weight: Int? { get { return resultMap["weight"] as? Int } set { resultMap.updateValue(newValue, forKey: "weight") } } public var resistance: [Resistance?]? { get { return (resultMap["resistance"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Resistance?] in value.map { (value: ResultMap?) -> Resistance? in value.flatMap { (value: ResultMap) -> Resistance in Resistance(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Resistance?]) -> [ResultMap?] in value.map { (value: Resistance?) -> ResultMap? in value.flatMap { (value: Resistance) -> ResultMap in value.resultMap } } }, forKey: "resistance") } } public var dmgNegation: [DmgNegation?]? { get { return (resultMap["dmgNegation"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [DmgNegation?] in value.map { (value: ResultMap?) -> DmgNegation? in value.flatMap { (value: ResultMap) -> DmgNegation in DmgNegation(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [DmgNegation?]) -> [ResultMap?] in value.map { (value: DmgNegation?) -> ResultMap? in value.flatMap { (value: DmgNegation) -> ResultMap in value.resultMap } } }, forKey: "dmgNegation") } } public struct Resistance: GraphQLSelectionSet { public static let possibleTypes: [String] = ["AttributeEntry"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(AttributeEntryData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(name: String? = nil, amount: Int? = nil) { self.init(unsafeResultMap: ["__typename": "AttributeEntry", "name": name, "amount": amount]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var attributeEntryData: AttributeEntryData { get { return AttributeEntryData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } public struct DmgNegation: GraphQLSelectionSet { public static let possibleTypes: [String] = ["AttributeEntry"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(AttributeEntryData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(name: String? = nil, amount: Int? = nil) { self.init(unsafeResultMap: ["__typename": "AttributeEntry", "name": name, "amount": amount]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var attributeEntryData: AttributeEntryData { get { return AttributeEntryData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } struct WeaponData: GraphQLFragment { /// The raw GraphQL definition of this fragment. public static let fragmentDefinition: String = """ fragment WeaponData on Weapon { __typename id image name description weight category attack { __typename ...AttributeEntryData } defence { __typename ...AttributeEntryData } scalesWith { __typename ...ScallingEntryData } requiredAttributes { __typename ...AttributeEntryData } } """ public static let possibleTypes: [String] = ["Weapon"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("image", type: .scalar(String.self)), GraphQLField("name", type: .scalar(String.self)), GraphQLField("description", type: .scalar(String.self)), GraphQLField("weight", type: .scalar(Int.self)), GraphQLField("category", type: .scalar(String.self)), GraphQLField("attack", type: .list(.object(Attack.selections))), GraphQLField("defence", type: .list(.object(Defence.selections))), GraphQLField("scalesWith", type: .list(.object(ScalesWith.selections))), GraphQLField("requiredAttributes", type: .list(.object(RequiredAttribute.selections))), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil, weight: Int? = nil, category: String? = nil, attack: [Attack?]? = nil, defence: [Defence?]? = nil, scalesWith: [ScalesWith?]? = nil, requiredAttributes: [RequiredAttribute?]? = nil) { self.init(unsafeResultMap: ["__typename": "Weapon", "id": id, "image": image, "name": name, "description": description, "weight": weight, "category": category, "attack": attack.flatMap { (value: [Attack?]) -> [ResultMap?] in value.map { (value: Attack?) -> ResultMap? in value.flatMap { (value: Attack) -> ResultMap in value.resultMap } } }, "defence": defence.flatMap { (value: [Defence?]) -> [ResultMap?] in value.map { (value: Defence?) -> ResultMap? in value.flatMap { (value: Defence) -> ResultMap in value.resultMap } } }, "scalesWith": scalesWith.flatMap { (value: [ScalesWith?]) -> [ResultMap?] in value.map { (value: ScalesWith?) -> ResultMap? in value.flatMap { (value: ScalesWith) -> ResultMap in value.resultMap } } }, "requiredAttributes": requiredAttributes.flatMap { (value: [RequiredAttribute?]) -> [ResultMap?] in value.map { (value: RequiredAttribute?) -> ResultMap? in value.flatMap { (value: RequiredAttribute) -> ResultMap in value.resultMap } } }]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var description: String? { get { return resultMap["description"] as? String } set { resultMap.updateValue(newValue, forKey: "description") } } public var weight: Int? { get { return resultMap["weight"] as? Int } set { resultMap.updateValue(newValue, forKey: "weight") } } public var category: String? { get { return resultMap["category"] as? String } set { resultMap.updateValue(newValue, forKey: "category") } } public var attack: [Attack?]? { get { return (resultMap["attack"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Attack?] in value.map { (value: ResultMap?) -> Attack? in value.flatMap { (value: ResultMap) -> Attack in Attack(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Attack?]) -> [ResultMap?] in value.map { (value: Attack?) -> ResultMap? in value.flatMap { (value: Attack) -> ResultMap in value.resultMap } } }, forKey: "attack") } } public var defence: [Defence?]? { get { return (resultMap["defence"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [Defence?] in value.map { (value: ResultMap?) -> Defence? in value.flatMap { (value: ResultMap) -> Defence in Defence(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [Defence?]) -> [ResultMap?] in value.map { (value: Defence?) -> ResultMap? in value.flatMap { (value: Defence) -> ResultMap in value.resultMap } } }, forKey: "defence") } } public var scalesWith: [ScalesWith?]? { get { return (resultMap["scalesWith"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [ScalesWith?] in value.map { (value: ResultMap?) -> ScalesWith? in value.flatMap { (value: ResultMap) -> ScalesWith in ScalesWith(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [ScalesWith?]) -> [ResultMap?] in value.map { (value: ScalesWith?) -> ResultMap? in value.flatMap { (value: ScalesWith) -> ResultMap in value.resultMap } } }, forKey: "scalesWith") } } public var requiredAttributes: [RequiredAttribute?]? { get { return (resultMap["requiredAttributes"] as? [ResultMap?]).flatMap { (value: [ResultMap?]) -> [RequiredAttribute?] in value.map { (value: ResultMap?) -> RequiredAttribute? in value.flatMap { (value: ResultMap) -> RequiredAttribute in RequiredAttribute(unsafeResultMap: value) } } } } set { resultMap.updateValue(newValue.flatMap { (value: [RequiredAttribute?]) -> [ResultMap?] in value.map { (value: RequiredAttribute?) -> ResultMap? in value.flatMap { (value: RequiredAttribute) -> ResultMap in value.resultMap } } }, forKey: "requiredAttributes") } } public struct Attack: GraphQLSelectionSet { public static let possibleTypes: [String] = ["AttributeEntry"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(AttributeEntryData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(name: String? = nil, amount: Int? = nil) { self.init(unsafeResultMap: ["__typename": "AttributeEntry", "name": name, "amount": amount]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var attributeEntryData: AttributeEntryData { get { return AttributeEntryData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } public struct Defence: GraphQLSelectionSet { public static let possibleTypes: [String] = ["AttributeEntry"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(AttributeEntryData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(name: String? = nil, amount: Int? = nil) { self.init(unsafeResultMap: ["__typename": "AttributeEntry", "name": name, "amount": amount]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var attributeEntryData: AttributeEntryData { get { return AttributeEntryData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } public struct ScalesWith: GraphQLSelectionSet { public static let possibleTypes: [String] = ["ScallingEntry"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(ScallingEntryData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(name: String? = nil, scalling: String? = nil) { self.init(unsafeResultMap: ["__typename": "ScallingEntry", "name": name, "scalling": scalling]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var scallingEntryData: ScallingEntryData { get { return ScallingEntryData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } public struct RequiredAttribute: GraphQLSelectionSet { public static let possibleTypes: [String] = ["AttributeEntry"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLFragmentSpread(AttributeEntryData.self), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(name: String? = nil, amount: Int? = nil) { self.init(unsafeResultMap: ["__typename": "AttributeEntry", "name": name, "amount": amount]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var fragments: Fragments { get { return Fragments(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } public struct Fragments { public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public var attributeEntryData: AttributeEntryData { get { return AttributeEntryData(unsafeResultMap: resultMap) } set { resultMap += newValue.resultMap } } } } } struct TalismanData: GraphQLFragment { /// The raw GraphQL definition of this fragment. public static let fragmentDefinition: String = """ fragment TalismanData on Talisman { __typename id image name description effect } """ public static let possibleTypes: [String] = ["Talisman"] public static var selections: [GraphQLSelection] { return [ GraphQLField("__typename", type: .nonNull(.scalar(String.self))), GraphQLField("id", type: .nonNull(.scalar(GraphQLID.self))), GraphQLField("image", type: .scalar(String.self)), GraphQLField("name", type: .scalar(String.self)), GraphQLField("description", type: .scalar(String.self)), GraphQLField("effect", type: .scalar(String.self)), ] } public private(set) var resultMap: ResultMap public init(unsafeResultMap: ResultMap) { self.resultMap = unsafeResultMap } public init(id: GraphQLID, image: String? = nil, name: String? = nil, description: String? = nil, effect: String? = nil) { self.init(unsafeResultMap: ["__typename": "Talisman", "id": id, "image": image, "name": name, "description": description, "effect": effect]) } public var __typename: String { get { return resultMap["__typename"]! as! String } set { resultMap.updateValue(newValue, forKey: "__typename") } } public var id: GraphQLID { get { return resultMap["id"]! as! GraphQLID } set { resultMap.updateValue(newValue, forKey: "id") } } public var image: String? { get { return resultMap["image"] as? String } set { resultMap.updateValue(newValue, forKey: "image") } } public var name: String? { get { return resultMap["name"] as? String } set { resultMap.updateValue(newValue, forKey: "name") } } public var description: String? { get { return resultMap["description"] as? String } set { resultMap.updateValue(newValue, forKey: "description") } } public var effect: String? { get { return resultMap["effect"] as? String } set { resultMap.updateValue(newValue, forKey: "effect") } } } }
30.483457
976
0.578138
d942d4f1e54fb9fed3d76c59e34063c78ef3f625
480
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // CustomHostnameAnalysisResultProtocol is custom domain analysis. public protocol CustomHostnameAnalysisResultProtocol : ProxyOnlyResourceProtocol { var properties: CustomHostnameAnalysisResultPropertiesProtocol? { get set } }
48
96
0.797917
fcfb98baef994804d06da6bc8b32c91112d472c6
1,090
import Foundation import AVFoundation class HuntForKey : Mode { let synthesizer = AVSpeechSynthesizer() let letters = Array("abcdefghijklmnopqrstuvwxyz") var targetKey = "" func start() { randomizeKey() } func respondTo(key: String) { if(key == targetKey) { immediatelySay("Great job! You pressed the letter \(targetKey)") randomizeKey() } else { immediatelySay("No. Try again. Press the \(targetKey) key") } } private func randomizeKey () { targetKey = String(letters.randomElement()!) say("Press the \(targetKey) key") } private func say(_ word: String) { let utterance = AVSpeechUtterance(string: word.lowercased()) synthesizer.speak(utterance) } private func immediatelySay(_ word: String) { let utterance = AVSpeechUtterance(string: word.lowercased()) synthesizer.stopSpeaking(at: .immediate) synthesizer.speak(utterance) } }
23.695652
76
0.577982
26b0a0e6b02e3aa3c94e0871499a8ba4b714d475
14,616
// // GridListLayout.swift // ListableUI // // Created by Kyle Van Essen on 5/2/20. // import Foundation public extension LayoutDescription { static func grid_experimental(_ configure : @escaping (inout GridAppearance) -> () = { _ in }) -> Self { GridListLayout.describe(appearance: configure) } } public struct GridAppearance : ListLayoutAppearance { public var sizing : Sizing public var layout : Layout public var direction: LayoutDirection { .vertical } public var stickySectionHeaders : Bool public static var `default`: GridAppearance { return self.init() } public init( stickySectionHeaders : Bool = true, sizing : Sizing = Sizing(), layout : Layout = Layout() ) { self.stickySectionHeaders = stickySectionHeaders self.sizing = sizing self.layout = layout } public struct Sizing : Equatable { public var itemSize : ItemSize public enum ItemSize : Equatable { case fixed(CGSize) } public var sectionHeaderHeight : CGFloat public var sectionFooterHeight : CGFloat public var listHeaderHeight : CGFloat public var listFooterHeight : CGFloat public var overscrollFooterHeight : CGFloat public init( itemSize : ItemSize = .fixed(CGSize(width: 100.0, height: 100.0)), sectionHeaderHeight : CGFloat = 60.0, sectionFooterHeight : CGFloat = 40.0, listHeaderHeight : CGFloat = 60.0, listFooterHeight : CGFloat = 60.0, overscrollFooterHeight : CGFloat = 60.0 ) { self.itemSize = itemSize self.sectionHeaderHeight = sectionHeaderHeight self.sectionFooterHeight = sectionFooterHeight self.listHeaderHeight = listHeaderHeight self.listFooterHeight = listFooterHeight self.overscrollFooterHeight = overscrollFooterHeight } public mutating func set(with block: (inout Sizing) -> ()) { var edited = self block(&edited) self = edited } } public struct Layout : Equatable { public var padding : UIEdgeInsets public var width : WidthConstraint public var interSectionSpacingWithNoFooter : CGFloat public var interSectionSpacingWithFooter : CGFloat public var sectionHeaderBottomSpacing : CGFloat public var itemToSectionFooterSpacing : CGFloat public init( padding : UIEdgeInsets = .zero, width : WidthConstraint = .noConstraint, interSectionSpacingWithNoFooter : CGFloat = 0.0, interSectionSpacingWithFooter : CGFloat = 0.0, sectionHeaderBottomSpacing : CGFloat = 0.0, itemToSectionFooterSpacing : CGFloat = 0.0 ) { self.padding = padding self.width = width self.interSectionSpacingWithNoFooter = interSectionSpacingWithNoFooter self.interSectionSpacingWithFooter = interSectionSpacingWithFooter self.sectionHeaderBottomSpacing = sectionHeaderBottomSpacing self.itemToSectionFooterSpacing = itemToSectionFooterSpacing } public mutating func set(with block : (inout Layout) -> ()) { var edited = self block(&edited) self = edited } internal static func width( with width : CGFloat, padding : HorizontalPadding, constraint : WidthConstraint ) -> CGFloat { let paddedWidth = width - padding.left - padding.right return constraint.clamp(paddedWidth) } } } final class GridListLayout : ListLayout { typealias LayoutAppearance = GridAppearance static var defaults: ListLayoutDefaults { .init(itemInsertAndRemoveAnimations: .scaleDown) } var layoutAppearance: GridAppearance // // MARK: Public Properties // let appearance : Appearance let behavior : Behavior let content : ListLayoutContent var scrollViewProperties: ListLayoutScrollViewProperties { .init( isPagingEnabled: false, contentInsetAdjustmentBehavior: .automatic, allowsBounceVertical: true, allowsBounceHorizontal: true, allowsVerticalScrollIndicator: true, allowsHorizontalScrollIndicator: true ) } // // MARK: Initialization // init( layoutAppearance: GridAppearance, appearance: Appearance, behavior: Behavior, content: ListLayoutContent ) { self.layoutAppearance = layoutAppearance self.appearance = appearance self.behavior = behavior self.content = content } // // MARK: Performing Layouts // func updateLayout(in collectionView: UICollectionView) { } func layout( delegate : CollectionViewLayoutDelegate, in collectionView : UICollectionView ) { let direction = self.layoutAppearance.direction let layout = self.layoutAppearance.layout let sizing = self.layoutAppearance.sizing let viewSize = collectionView.bounds.size let viewWidth = viewSize.width let rootWidth = ListAppearance.Layout.width( with: viewWidth, padding: HorizontalPadding(left: layout.padding.left, right: layout.padding.right), constraint: layout.width ) // // Set Frame Origins // var lastSectionMaxY : CGFloat = 0.0 var lastContentMaxY : CGFloat = 0.0 // // Header // performLayout(for: self.content.header) { header in let hasListHeader = self.content.header.isPopulated let position = header.layout.width.position(with: viewSize, defaultWidth: rootWidth) let measureInfo = Sizing.MeasureInfo( sizeConstraint: CGSize(width: position.width, height: .greatestFiniteMagnitude), defaultSize: CGSize(width: 0.0, height: sizing.listHeaderHeight), direction: .vertical ) let height = header.measurer(measureInfo).height header.x = position.origin header.size = CGSize(width: position.width, height: height) header.y = lastContentMaxY if hasListHeader { lastContentMaxY = header.defaultFrame.maxY } } switch direction { case .vertical: lastSectionMaxY += layout.padding.top lastContentMaxY += layout.padding.top case .horizontal: lastSectionMaxY += layout.padding.left lastContentMaxY += layout.padding.left } // // Sections // self.content.sections.forEachWithIndex { sectionIndex, isLast, section in let sectionPosition = section.layout.width.position(with: viewSize, defaultWidth: rootWidth) // // Section Header // let hasSectionHeader = section.header.isPopulated let hasSectionFooter = section.footer.isPopulated performLayout(for: section.header) { header in let width = header.layout.width.merge(with: section.layout.width) let position = width.position(with: viewSize, defaultWidth: sectionPosition.width) let measureInfo = Sizing.MeasureInfo( sizeConstraint: CGSize(width: position.width, height: .greatestFiniteMagnitude), defaultSize: CGSize(width: 0.0, height: sizing.sectionHeaderHeight), direction: .vertical ) let height = header.measurer(measureInfo).height header.x = position.origin header.size = CGSize(width: position.width, height: height) header.y = lastContentMaxY if hasSectionHeader { lastContentMaxY = section.header.defaultFrame.maxY lastContentMaxY += layout.sectionHeaderBottomSpacing } } // // Section Items // let groupedItems = sizing.itemSize.grouped(within: sectionPosition.width, values: section.items) groupedItems.grouped.forEachWithIndex { rowIndex, isLast, row in var xOrigin = sectionPosition.origin row.forEachWithIndex { columnIndex, isLast, item in item.x = xOrigin item.y = lastContentMaxY item.size = groupedItems.itemSize xOrigin = item.frame.maxX } lastContentMaxY += groupedItems.itemSize.height } // // Section Footer // performLayout(for: section.footer) { footer in let width = footer.layout.width.merge(with: section.layout.width) let position = width.position(with: viewSize, defaultWidth: sectionPosition.width) let measureInfo = Sizing.MeasureInfo( sizeConstraint: CGSize(width: position.width, height: .greatestFiniteMagnitude), defaultSize: CGSize(width: 0.0, height: sizing.sectionFooterHeight), direction: .vertical ) let height = footer.measurer(measureInfo).height footer.size = CGSize(width: position.width, height: height) footer.x = position.origin footer.y = lastContentMaxY if hasSectionFooter { lastContentMaxY = footer.defaultFrame.maxY } } // Add additional padding from config. if isLast == false { let additionalSectionSpacing = hasSectionFooter ? layout.interSectionSpacingWithFooter : layout.interSectionSpacingWithNoFooter lastSectionMaxY += additionalSectionSpacing lastContentMaxY += additionalSectionSpacing } } switch direction { case .vertical: lastContentMaxY += layout.padding.bottom case .horizontal: lastContentMaxY += layout.padding.right } // // Footer // performLayout(for: self.content.footer) { footer in let hasFooter = footer.isPopulated let position = footer.layout.width.position(with: viewSize, defaultWidth: rootWidth) let measureInfo = Sizing.MeasureInfo( sizeConstraint: CGSize(width: position.width, height: .greatestFiniteMagnitude), defaultSize: CGSize(width: 0.0, height: sizing.listFooterHeight), direction: .vertical ) let height = footer.measurer(measureInfo).height footer.size = CGSize(width: position.width, height: height) footer.x = position.origin footer.y = lastContentMaxY if hasFooter { lastContentMaxY = footer.defaultFrame.maxY lastContentMaxY += layout.sectionHeaderBottomSpacing } } // // Overscroll Footer // performLayout(for: self.content.overscrollFooter) { footer in let position = footer.layout.width.position(with: viewSize, defaultWidth: rootWidth) let measureInfo = Sizing.MeasureInfo( sizeConstraint: CGSize(width: position.width, height: .greatestFiniteMagnitude), defaultSize: CGSize(width: 0.0, height: sizing.overscrollFooterHeight), direction: .vertical ) let height = footer.measurer(measureInfo).height footer.x = position.origin footer.size = CGSize(width: position.width, height: height) } // // Remaining Calculations // self.content.contentSize = CGSize(width: viewWidth, height: lastContentMaxY) } } fileprivate extension GridAppearance.Sizing.ItemSize { struct Grouped<Value> { var itemsInRowSpacing : CGFloat var itemSize : CGSize var grouped : [[Value]] } func grouped<Value>(within width : CGFloat, values : [Value]) -> Grouped<Value> { switch self { case .fixed(let itemSize): let itemsPerRow = Int(max(1, floor(width / itemSize.width))) return Grouped( itemsInRowSpacing: (width - (itemSize.width * CGFloat(itemsPerRow))) / CGFloat(itemsPerRow - 1 == 0 ? 1 : itemsPerRow - 1), itemSize: itemSize, grouped: self.group(values: values, into: itemsPerRow) ) } } private func group<Value>(values : [Value], into itemsPerRow : Int) -> [[Value]] { var values = values var grouped : [[Value]] = [] while values.count > 0 { grouped.append(values.safeDropFirst(itemsPerRow)) } return grouped } } fileprivate extension Array { mutating func safeDropFirst(_ count : Int) -> [Element] { let safeCount = Swift.min(self.count, count) let values = self[0..<safeCount] self.removeFirst(safeCount) return Array(values) } } fileprivate func performLayout<Input>(for input : Input, _ block : (Input) -> ()) { block(input) }
31.568035
143
0.554529
71c2b022012f90610695ee12e87ee589e69c4cb8
1,227
// Licensed under the **MIT** license // Copyright (c) 2016 Elvis Nuñez // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import PackageDescription let package = Package( name: "SweetCoreData" )
43.821429
73
0.761206
fc74a31d866652ab7f52834f68a22df572a891db
8,580
// // SharedStateExtension.swift // SceneBox // // Created by Lumia_Saki on 2021/4/30. // Copyright © 2021年 tianren.zhu. All rights reserved. // import Foundation @available(*, deprecated, message: "Use `SharedStateInjected<StateType, T>` instead.") @propertyWrapper public class SceneBoxSharedStateInjected<T> { private let key: AnyHashable private var scene: Scene? public init(key: AnyHashable) { self.key = key } public func configure(scene: Scene?) { self.scene = scene } public var wrappedValue: T? { get { guard let scene = scene else { fatalError("configure scene firstly") } return scene.sbx.getSharedState(by: key) as? T } set { guard let scene = scene else { fatalError("configure scene firstly") } scene.sbx.putSharedState(by: key, sharedState: newValue) } } } /// Property wrapper for helping developers to simplify state sharing among different `Scene`s, the principle of it is similar to `Environment` in SwiftUI, all `Scene`s share same source of truth through the `SharedStateExtension`, use this property wrapper will make developer to manipulate variables as normal properties, the only difference is that this one is backed by `SharedStateExtension` in static-type ( key path ) way. /// Notice: Because the property wrapper needs an instance of `Scene` to get capability from it, since that, you need to configure it before using it by calling `configure(scene:)` in a proper place. @propertyWrapper public struct SharedStateInjected<StateType, T> { private var scene: Scene? private let keyPath: WritableKeyPath<StateType, T?> public mutating func configure(scene: Scene?) { self.scene = scene } public var wrappedValue: T? { get { guard let scene = scene else { fatalError("configure scene firstly") } return scene.sbx.getSharedState(by: keyPath) } set { guard let scene = scene else { fatalError("configure scene firstly") } scene.sbx.putSharedState(by: keyPath, sharedState: newValue) } } public init(_ keyPath: WritableKeyPath<StateType, T?>) { self.keyPath = keyPath } } /// Message data structure for shared state extension to exchange information with other extensions in the SceneBox. public struct SharedStateMessage { /// The key of a shared state tuple. public var key: AnyHashable? /// The value of a shared state tuple. public var state: Any? /// Initializer of the SharedStateMessage. /// - Parameters: /// - key: The key of the shared state. /// - state: The value of the shared state. public init(key: AnyHashable?, state: Any?) { self.key = key self.state = state } } public extension EventBus.EventName { /// The event name of shared state changes event. static let sharedStateChanges: EventBus.EventName = EventBus.EventName(rawValue: "SharedStateChanges") } /// The built-in extension for supporting data fetching and putting between scenes, without passing data scene by scene. public final class SharedStateExtension: Extension { // MARK: - Extension /// Associated SceneBox, should always be weak. public weak var sceneBox: SceneBox? // MARK: - Private private let workerQueue = DispatchQueue(label: "com.scenebox.shared-state.queue", attributes: .concurrent) @available(*, deprecated, message: "Use `stateValue` instead.") private var state: [AnyHashable : Any] = Dictionary() private var stateValue: AnyObject? /// Initiate `SharedStateExtension` with a state instance, `stateValue` must be reference type. /// - Parameter stateValue: AnyObject. public init(stateValue: AnyObject?) { self.stateValue = stateValue } fileprivate func setSharedState<T, StateType>(_ sharedState: T?, on keyPath: WritableKeyPath<StateType, T?>) { guard var stateValue = self.stateValue as? StateType else { fatalError("`stateValue` not be set up properly") } workerQueue.async(flags: .barrier) { stateValue[keyPath: keyPath] = sharedState self.sceneBox?.dispatch(event: EventBus.EventName.sharedStateChanges, message: SharedStateMessage(key: keyPath, state: sharedState)) self.logger(content: "shared state changes: key: \(keyPath), state: \(String(describing: sharedState))") } } fileprivate func querySharedState<T, StateType>(by keyPath: WritableKeyPath<StateType, T?>) -> T? { var result: T? guard let stateValue = self.stateValue as? StateType else { fatalError("`stateValue` not be set up properly") } workerQueue.sync { result = stateValue[keyPath: keyPath] } return result } } extension SceneCapabilityWrapper { /// Receiving a shared state from the shared store if it exists. /// - Parameter key: The key of the data you want to fetch from the store. /// - Returns: The shared state stored in the extension. Nil if the data not exists with the provided key. @available(*, deprecated, message: "Use `getSharedState<T>(by keyPath: WritableKeyPath<StateType, T?>) -> T?` instead.") public func getSharedState(by key: AnyHashable) -> Any? { guard let ext = try? _getExtension(by: SharedStateExtension.self) else { return nil } return ext.querySharedState(by: key) } /// Receiving a shared state from the shared store if it exists. /// - Parameter keyPath: Key path to the value. /// - Returns: The shared state stored in the extension. Nil if the data not exists with the provided key path. public func getSharedState<T, StateType>(by keyPath: WritableKeyPath<StateType, T?>) -> T? { guard let ext = try? _getExtension(by: SharedStateExtension.self) else { return nil } return ext.querySharedState(by: keyPath) } /// Putting a shared state to the shared store. /// - Parameters: /// - key: The key of the data you want to put into the store. /// - sharedState: The shared state you want to save. Nil if you want to remove the data from the store. @available(*, deprecated, message: "Use `putSharedState<T>(by keyPath: WritableKeyPath<StateType, T?>, sharedState: T?)` instead.") public func putSharedState(by key: AnyHashable, sharedState: Any?) { guard let ext = try? _getExtension(by: SharedStateExtension.self) else { return } ext.setSharedState(sharedState, on: key) } /// Putting a shared state to the shared store. /// - Parameters: /// - keyPath: Key path to the value. /// - sharedState: The shared state you want to save. Nil if you want to remove the data from the store. public func putSharedState<T, StateType>(by keyPath: WritableKeyPath<StateType, T?>, sharedState: T?) { guard let ext = try? _getExtension(by: SharedStateExtension.self) else { return } ext.setSharedState(sharedState, on: keyPath) } } // MARK: - Deprecated extension SharedStateExtension { @available(*, deprecated, message: "Use `querySharedState<T>(by keyPath: WritableKeyPath<StateType, T?>) -> T?` instead.") fileprivate func querySharedState(by key: AnyHashable) -> Any? { var result: Any? workerQueue.sync { result = state[key] } return result } @available(*, deprecated, message: "Use `setSharedState<T>(_ sharedState: T?, on keyPath: WritableKeyPath<StateType, T?>)` instead.") fileprivate func setSharedState(_ sharedState: Any?, on key: AnyHashable) { workerQueue.async(flags: .barrier) { self.state[key] = sharedState self.sceneBox?.dispatch(event: EventBus.EventName.sharedStateChanges, message: SharedStateMessage(key: key, state: sharedState)) self.logger(content: "shared state changes: key: \(key), state: \(String(describing: sharedState))") } } }
36.824034
429
0.631818
16d185781422e441a177240e7e09a5d1102b8880
1,953
// // DefaultImageExporter.swift // DevToys // // Created by yuki on 2022/02/18. // import CoreUtil enum ImageExportError: Error { case nonData } enum DefaultImageExporter { static func exportPNG(_ image: NSImage, to url: URL) -> Promise<Void, Error> { .tryAsync { guard let data = image.png else { throw ImageExportError.nonData } try data.write(to: url) } } static func exportGIF(_ image: NSImage, to url: URL) -> Promise<Void, Error> { .tryAsync { guard let data = image.gif else { throw ImageExportError.nonData } try data.write(to: url) } } static func exportJPEG(_ image: NSImage, to url: URL) -> Promise<Void, Error> { .tryAsync { guard let data = image.jpeg else { throw ImageExportError.nonData } try data.write(to: url) } } static func exportTIFF(_ image: NSImage, to url: URL) -> Promise<Void, Error> { .tryAsync { guard let data = image.tiffRepresentation else { throw ImageExportError.nonData } try data.write(to: url) } } } extension NSImage { public var png: Data? { self.data(for: .png) } public var jpeg: Data? { self.data(for: .jpeg) } public var gif: Data? { self.data(for: .gif) } public convenience init(cgImage: CGImage) { self.init(cgImage: cgImage, size: cgImage.size) } public func data(for fileType: NSBitmapImageRep.FileType, properties: [NSBitmapImageRep.PropertyKey : Any] = [:]) -> Data? { guard let tiffRepresentation = self.tiffRepresentation, let bitmap = NSBitmapImageRep(data: tiffRepresentation), let rep = bitmap.representation(using: fileType, properties: properties) else { return nil } return rep } } extension CGImage { public var size: CGSize { CGSize(width: self.width, height: self.height) } }
31
128
0.613927
e556c387a5577583e889ae696e71f2760f659304
5,026
// // UIView+Actions.swift // actions // // Created by Manu on 1/6/16. // Copyright © 2016 manuege. All rights reserved. // import UIKit /** Action where the parameter can be assigned manually */ private class CustomParametizedAction<T: NSObject>: Action { @objc let key = ProcessInfo.processInfo.globallyUniqueString @objc let selector: Selector = #selector(perform) let action: ((T) -> Void) weak var parameter: T? init(parameter: T?, action: @escaping (T) -> Void) { self.action = action self.parameter = parameter } @objc func perform() { guard let parameter = parameter else { return } action(parameter) } } /** The gestures that can be used to trigger actions in `UIView` */ public enum Gesture { /// A tap gesture with a single finger and the given number of touches case tap(Int) /// A swipe gesture with a single finger and the given direction case swipe(UISwipeGestureRecognizer.Direction) /// A tap gesture with the given number of touches and fingers case multiTap(taps: Int, fingers: Int) /// A swipe gesture with the given direction and number of fingers case multiSwipe(direction: UISwipeGestureRecognizer.Direction, fingers: Int) fileprivate func recognizer(action: Action) -> UIGestureRecognizer { switch self { case let .tap(taps): let recognizer = UITapGestureRecognizer(target: action, action: action.selector) recognizer.numberOfTapsRequired = taps return recognizer case let .swipe(direction): let recognizer = UISwipeGestureRecognizer(target: action, action: action.selector) recognizer.direction = direction return recognizer case let .multiTap(taps, fingers): let recognizer = UITapGestureRecognizer(target: action, action: action.selector) recognizer.numberOfTapsRequired = taps recognizer.numberOfTouchesRequired = fingers return recognizer case let .multiSwipe(direction, fingers): let recognizer = UISwipeGestureRecognizer(target: action, action: action.selector) recognizer.direction = direction recognizer.numberOfTouchesRequired = fingers return recognizer } } } /// Extension that provides methods to add actions to views extension UIView { /** Adds the given action as response to the gesture. - parameter gesture: The gesture that the view must receive to trigger the closure - parameter action: The closure that will be called when the gesture is detected - returns: The gesture recognizer that has been added */ @discardableResult public func add<T: UIView>(gesture: Gesture, action: @escaping (T) -> Void) -> UIGestureRecognizer { let action = CustomParametizedAction(parameter: (self as! T), action: action) return add(gesture: gesture, action: action) } /** Adds the given action as response to the gesture. - parameter gesture: The gesture that the view must receive to trigger the closure - parameter action: The closure that will be called when the gesture is detected - returns: The gesture recognizer that has been added */ @discardableResult public func add(gesture: Gesture, action: @escaping () -> Void) -> UIGestureRecognizer { let action = VoidAction(action: action) return add(gesture: gesture, action: action) } /** Adds the given action as response to a single tap gesture. - parameter gesture: The gesture that the view must receive to trigger the closure - parameter action: The closure that will be called when the gesture is detected - returns: The gesture recognizer that has been added */ @discardableResult public func addTap<T: UIView>(action: @escaping (T) -> Void) -> UIGestureRecognizer { let action = CustomParametizedAction(parameter: (self as! T), action: action) return add(gesture: .tap(1), action: action) } /** Adds the given action as response to a single tap gesture. - parameter gesture: The gesture that the view must receive to trigger the closure - parameter action: The closure that will be called when the gesture is detected - returns: The gesture recognizer that has been added */ @discardableResult public func addAction(action: @escaping () -> Void) -> UIGestureRecognizer { let action = VoidAction(action: action) return add(gesture: .tap(1), action: action) } @discardableResult private func add(gesture: Gesture, action: Action) -> UIGestureRecognizer{ retainAction(action, self) let gesture = gesture.recognizer(action: action) isUserInteractionEnabled = true addGestureRecognizer(gesture) return gesture } }
36.42029
104
0.664146
d6b084373f1288a0e70da94dd1c66f48d6e9a853
867
// // MRKTVRepresenter.swift // MRKViewUtls // // Created by Marc Flores on 14/12/2019. // Copyright © 2019 MRKTrace. All rights reserved. // import UIKit open class MRKTVRepresenter<C,D> : NSObject where C : UITableViewCell , D : Any { public func registerRepresenter(_ tv: UITableView) { tv.registerClassNib(C.self) } //MARK : - Protocol public func reuseCellFor(tv: UITableView, at index: IndexPath, with data: D) -> C { let cell = tv.dequeueReusableCell(C.self, for: index) representCell(tv: tv, at: index, with: data, in: cell) representCell(data, cell: cell) return cell } //MARK : - Override open func representCell(tv:UITableView, at index:IndexPath, with data:D, in cell:C) { } open func representCell( _ data:D, cell:C ) { } }
24.083333
89
0.614764
e5769f8f0d7e1e044e22b3bbf7f85ff18b55659d
4,352
// // TestListViewController.swift // AppTestProject // // Created by Kyung Shik Kim on 2020/12/28. // Copyright © 2020 lunightlab. All rights reserved. // import UIKit import Alamofire // FIXME: MVVM 적용 필요 class TestListViewController: UIViewController { @IBOutlet var testTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.testTableView.dataSource = self self.testTableView.delegate = self } @IBAction func btnBack(_ sender: Any) { self.presentingViewController?.dismiss(animated: true, completion: nil) } } extension TestListViewController: UITableViewDelegate, UITableViewDataSource { // tableview section count func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Hard test..💬" case 1: return "Simple test..💬" default: return "" } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return hardTestList.count default: return normalTestList.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FirstCell", for: indexPath) let text: String = indexPath.section == 0 ? hardTestList[indexPath.row] : normalTestList[indexPath.row] cell.textLabel?.text = text // cell.textLabel?.text = TableList.getTestList(indexPath) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0 { switch indexPath.row { case 0: // MARK: 👨🏻‍💻wkwebview - script ToastMessage.Message(str: "작업중", duration: 2.0) case 1: // MARK: 👨🏻‍💻mvvm-simple guard let webvc = self.storyboard?.instantiateViewController(withIdentifier: "SimpleMvvmVC") else { return } webvc.modalTransitionStyle = UIModalTransitionStyle.coverVertical webvc.modalPresentationStyle = .fullScreen self.present(webvc, animated: true) case 2: // MARK: 👨🏻‍💻mvvm(rxswift) ToastMessage.Message(str: "작업중", duration: 2.0) case 3: // MARK: 👨🏻‍💻Network guard let webvc = self.storyboard?.instantiateViewController(withIdentifier: "NetworkVC") else { return } default: ToastMessage.Message(str: "연결필요", duration: 2.0) } }else if indexPath.section == 1{ switch indexPath.row { case 0: // MARK: 👨🏻‍💻wkwebview - basic if Reachability.isConnectedToNetwork() { guard let webvc = self.storyboard?.instantiateViewController(withIdentifier: "WebViewController") else { return } webvc.modalTransitionStyle = UIModalTransitionStyle.coverVertical webvc.modalPresentationStyle = .fullScreen self.present(webvc, animated: true) }else{ let alert = UIAlertController(title: "네트워크 에러", message: "네트워크를 확인해주세요", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "확인", style: .default, handler: {(action: UIAlertAction!) in print("exit()") })) self.present(alert, animated: true, completion: nil) } case 1: ToastMessage.Message(str: "작업중", duration: 2.0) default: ToastMessage.Message(str: "연결필요", duration: 2.0) } } else { ToastMessage.Message(str: "연결섹션이 없음.", duration: 2.0) } } } class NetworkState { class func isConnected() ->Bool { return NetworkReachabilityManager()!.isReachable } }
35.382114
124
0.576746
46d1874e75255956b384a64d376daf74bf682f07
11,122
// // ImageProgressive.swift // Kingfisher // // Created by lixiang on 2019/5/10. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreGraphics // 自定义队列 private let sharedProcessingQueue: CallbackQueue = .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) public struct ImageProgressive { /// A default `ImageProgressive` could be used across. public static let `default` = ImageProgressive( isBlur: true, isFastestScan: true, scanInterval: 0 ) /// Whether to enable blur effect processing let isBlur: Bool /// Whether to enable the fastest scan let isFastestScan: Bool /// Minimum time interval for each scan let scanInterval: TimeInterval public init(isBlur: Bool, isFastestScan: Bool, scanInterval: TimeInterval) { self.isBlur = isBlur self.isFastestScan = isFastestScan self.scanInterval = scanInterval } } protocol ImageSettable: AnyObject { var image: KFCrossPlatformImage? { get set } } final class ImageProgressiveProvider: DataReceivingSideEffect { var onShouldApply: () -> Bool = { return true } func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { DispatchQueue.main.async { guard self.onShouldApply() else { return } self.update(data: task.mutableData, with: task.callbacks) } } private let option: ImageProgressive private let refresh: (KFCrossPlatformImage) -> Void private let decoder: ImageProgressiveDecoder private let queue = ImageProgressiveSerialQueue() // 构造方法 init?(_ options: KingfisherParsedOptionsInfo, //参数是Image,返回值Void refresh: @escaping (KFCrossPlatformImage) -> Void) { guard let option = options.progressiveJPEG else { return nil } self.option = option self.refresh = refresh self.decoder = ImageProgressiveDecoder( option, processingQueue: options.processingQueue ?? sharedProcessingQueue, creatingOptions: options.imageCreatingOptions ) } func update(data: Data, with callbacks: [SessionDataTask.TaskCallback]) { guard !data.isEmpty else { return } queue.add(minimum: option.scanInterval) { completion in func decode(_ data: Data) { self.decoder.decode(data, with: callbacks) { image in defer { completion() } guard self.onShouldApply() else { return } guard let image = image else { return } self.refresh(image) } } let semaphore = DispatchSemaphore(value: 0) var onShouldApply: Bool = false CallbackQueue.mainAsync.execute { onShouldApply = self.onShouldApply() semaphore.signal() } semaphore.wait() guard onShouldApply else { self.queue.clean() completion() return } if self.option.isFastestScan { decode(self.decoder.scanning(data) ?? Data()) } else { self.decoder.scanning(data).forEach { decode($0) } } } } } private final class ImageProgressiveDecoder { private let option: ImageProgressive private let processingQueue: CallbackQueue private let creatingOptions: ImageCreatingOptions private(set) var scannedCount = 0 private(set) var scannedIndex = -1 init(_ option: ImageProgressive, processingQueue: CallbackQueue, creatingOptions: ImageCreatingOptions) { self.option = option self.processingQueue = processingQueue self.creatingOptions = creatingOptions } func scanning(_ data: Data) -> [Data] { guard data.kf.contains(jpeg: .SOF2) else { return [] } guard scannedIndex + 1 < data.count else { return [] } var datas: [Data] = [] var index = scannedIndex + 1 var count = scannedCount while index < data.count - 1 { scannedIndex = index // 0xFF, 0xDA - Start Of Scan let SOS = ImageFormat.JPEGMarker.SOS.bytes if data[index] == SOS[0], data[index + 1] == SOS[1] { if count > 0 { datas.append(data[0 ..< index]) } count += 1 } index += 1 } // Found more scans this the previous time guard count > scannedCount else { return [] } scannedCount = count // `> 1` checks that we've received a first scan (SOS) and then received // and also received a second scan (SOS). This way we know that we have // at least one full scan available. guard count > 1 else { return [] } return datas } func scanning(_ data: Data) -> Data? { guard data.kf.contains(jpeg: .SOF2) else { return nil } guard scannedIndex + 1 < data.count else { return nil } var index = scannedIndex + 1 var count = scannedCount var lastSOSIndex = 0 while index < data.count - 1 { scannedIndex = index // 0xFF, 0xDA - Start Of Scan let SOS = ImageFormat.JPEGMarker.SOS.bytes if data[index] == SOS[0], data[index + 1] == SOS[1] { lastSOSIndex = index count += 1 } index += 1 } // Found more scans this the previous time guard count > scannedCount else { return nil } scannedCount = count // `> 1` checks that we've received a first scan (SOS) and then received // and also received a second scan (SOS). This way we know that we have // at least one full scan available. guard count > 1 && lastSOSIndex > 0 else { return nil } return data[0 ..< lastSOSIndex] } func decode(_ data: Data, with callbacks: [SessionDataTask.TaskCallback], completion: @escaping (KFCrossPlatformImage?) -> Void) { guard data.kf.contains(jpeg: .SOF2) else { CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } return } func processing(_ data: Data) { let processor = ImageDataProcessor( data: data, callbacks: callbacks, processingQueue: processingQueue ) processor.onImageProcessed.delegate(on: self) { (self, result) in guard let image = try? result.0.get() else { CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } return } CallbackQueue.mainCurrentOrAsync.execute { completion(image) } } processor.process() } // Blur partial images. let count = scannedCount if option.isBlur, count < 6 { processingQueue.execute { // Progressively reduce blur as we load more scans. let image = KingfisherWrapper<KFCrossPlatformImage>.image( data: data, options: self.creatingOptions ) let radius = max(2, 14 - count * 4) let temp = image?.kf.blurred(withRadius: CGFloat(radius)) processing(temp?.kf.data(format: .JPEG) ?? data) } } else { processing(data) } } } private final class ImageProgressiveSerialQueue { typealias ClosureCallback = ((@escaping () -> Void)) -> Void private let queue: DispatchQueue = .init(label: "com.onevcat.Kingfisher.ImageProgressive.SerialQueue") private var items: [DispatchWorkItem] = [] private var notify: (() -> Void)? private var lastTime: TimeInterval? var count: Int { return items.count } func add(minimum interval: TimeInterval, closure: @escaping ClosureCallback) { let completion = { [weak self] in guard let self = self else { return } self.queue.async { [weak self] in guard let self = self else { return } guard !self.items.isEmpty else { return } self.items.removeFirst() if let next = self.items.first { self.queue.asyncAfter( deadline: .now() + interval, execute: next ) } else { self.lastTime = Date().timeIntervalSince1970 self.notify?() self.notify = nil } } } queue.async { [weak self] in guard let self = self else { return } let item = DispatchWorkItem { closure(completion) } if self.items.isEmpty { let difference = Date().timeIntervalSince1970 - (self.lastTime ?? 0) let delay = difference < interval ? interval - difference : 0 self.queue.asyncAfter(deadline: .now() + delay, execute: item) } self.items.append(item) } } func notify(_ closure: @escaping () -> Void) { self.notify = closure } func clean() { queue.async { [weak self] in guard let self = self else { return } self.items.forEach { $0.cancel() } self.items.removeAll() } } }
34.433437
106
0.562399
4b3b50d5f74a5220527a1fbd67005dba6ca98df6
1,096
// import SwiftUI struct FSButton: View { let title: Text let action: () -> Void init(_ title: Text, action: @escaping () -> Void) { self.title = title self.action = action } init<S: StringProtocol>(_ content: S, action: @escaping () -> Void) { self.title = Text(content) self.action = action } init(titleKey: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil, action: @escaping () -> Void) { self.title = Text(titleKey, tableName: tableName, bundle: bundle, comment: comment) self.action = action } var body: some View { Button(action: action, label: { title.bold() }) .buttonStyle(FSButtonStyle()) } } private struct FSButtonStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { HStack { Spacer() configuration.label .foregroundColor(.white) Spacer() } .padding() .background( RoundedRectangle(cornerRadius: 8, style: .continuous).fill(Color.green) ) .opacity(configuration.isPressed ? 0.5 : 1) } }
24.355556
147
0.639599
56d2066f4da35446ea5da9a282f3f429b6558bda
416
import XCTest @testable import CLIHandler final class CLIHandlerTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. XCTAssertEqual(CLIHandler().text, "Hello, World!") } static var allTests = [ ("testExample", testExample), ] }
24.470588
87
0.651442
ff9baac7f8fc4f5db6b19cc9bb45cf8ade46b9b0
1,795
// Created by Michal Ciurus import SharedTools fileprivate struct NameListPresenterConstants { fileprivate static let nameAvailableLabel = "Name available" } final public class NamesListPresenter: EmitsError { fileprivate typealias C = NameListPresenterConstants //MARK: Private Properties private var allNames: [String] = [] private var isShowingOneName = false //MARK: Public Properties public var errorEvent = PresenterEventObservable<String>() public var names = PresenterValueObservable<[String]>(value: [ ]) public var showLoadMore = PresenterValueObservable<Bool>(value: false) public var isLoadingMore = PresenterValueObservable<Bool>(value: false) public var infoLabel = PresenterValueObservable<String>(value: nil) //MARK: Public Methods func cleanNames() { names.value = [ ] } func set(names: [String]) { self.names.value = names } func add(names: [String]) { var currentValue = self.names.value currentValue?.append(contentsOf: names) self.names.value = currentValue } func show(name: String, available: Bool, price: Double?) { if !isShowingOneName { allNames = names.value ?? [] isShowingOneName = true } if available { names.value = [] if let price = price { infoLabel.value = "\(C.nameAvailableLabel) for \(price) btc" } else { infoLabel.value = "\(C.nameAvailableLabel)!" } } else { names.value = [name] infoLabel.value = nil } } func showAllNames() { isShowingOneName = false names.value = allNames } }
26.791045
76
0.602228
ddcedc6f357ca5c7c791f0c91db6d6015254760d
3,909
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: test.fbe // Version: 1.7.0.0 import Foundation import ChronoxorFbe import ChronoxorProto // Fast Binary Encoding Int32->OptionalUInt8 map final model class FinalModelMapInt32OptionalUInt8: FinalModel { var _buffer: Buffer = Buffer() var _offset: Int = 0 private var _modelKey: ChronoxorFbe.FinalModelInt32 private var _modelValue: FinalModelOptionalUInt8 init(buffer: Buffer, offset: Int) { _buffer = buffer _offset = offset _modelKey = ChronoxorFbe.FinalModelInt32(buffer: buffer, offset: offset) _modelValue = FinalModelOptionalUInt8(buffer: buffer, offset: offset) } // Get the allocation size func fbeAllocationSize(value values: Dictionary<Int32, UInt8?>) -> Int { var size: Int = 4 for (key, value) in values { size += _modelKey.fbeAllocationSize(value: key) size += _modelValue.fbeAllocationSize(value: value) } return size } // Check if the vector is valid public func verify() -> Int { if _buffer.offset + fbeOffset + 4 > _buffer.size { return Int.max } let fbeMapSize = Int(readUInt32(offset: fbeOffset)) var size: Int = 4 _modelKey.fbeOffset = fbeOffset + 4 _modelValue.fbeOffset = fbeOffset + 4 var i = fbeMapSize while i > 0 { let offsetKey = _modelKey.verify() if offsetKey == Int.max { return Int.max } _modelKey.fbeShift(size: offsetKey) _modelValue.fbeShift(size: offsetKey) size += offsetKey let offsetValue = _modelValue.verify() if offsetValue == Int.max { return Int.max } _modelKey.fbeShift(size: offsetValue) _modelValue.fbeShift(size: offsetValue) size += offsetValue i -= 1 } return size } public func get(values: inout Dictionary<Int32, UInt8?>) -> Int { values.removeAll() if _buffer.offset + fbeOffset + 4 > _buffer.size { assertionFailure("Model is broken!") return 0 } let fbeMapSize = Int(readUInt32(offset: fbeOffset)) if fbeMapSize == 0 { return 4 } var size: Int = 4 var offset = Size() _modelKey.fbeOffset = fbeOffset + 4 _modelValue.fbeOffset = fbeOffset + 4 for _ in 1...fbeMapSize { offset.value = 0 let key = _modelKey.get(size: &offset) _modelKey.fbeShift(size: offset.value) _modelValue.fbeShift(size: offset.value) size += offset.value offset.value = 0 let value = _modelValue.get(size: &offset) _modelKey.fbeShift(size: offset.value) _modelValue.fbeShift(size: offset.value) size += offset.value values[key] = value } return size } public func set(value values: Dictionary<Int32, UInt8?>) throws -> Int { if _buffer.offset + fbeOffset + 4 > _buffer.size { assertionFailure("Model is broken!") return 0 } write(offset: fbeOffset, value: UInt32(values.count)) var size: Int = 4 _modelKey.fbeOffset = fbeOffset + 4 _modelValue.fbeOffset = fbeOffset + 4 for (key, value) in values { let offsetKey = try _modelKey.set(value: key) _modelKey.fbeShift(size: offsetKey) _modelValue.fbeShift(size: offsetKey) let offsetValue = try _modelValue.set(value: value) _modelKey.fbeShift(size: offsetValue) _modelValue.fbeShift(size: offsetValue) size += offsetKey + offsetValue } return size } }
32.305785
80
0.596572
01b9a017c8e054b7c0a9c2f7b348e63fd19f20a2
2,065
// // BottomModal.swift // FightPandemics // // Created by Harlan Kellaway on 5/16/20. // // Copyright (c) 2020 FightPandemics // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class BottomModal { let body: UIViewController let height: CGFloat private var presentingViewController: UIViewController? init(body: UIViewController, height: CGFloat) { self.body = body self.height = height } func present(on presentingViewController: UIViewController) { let transitioningDelegate = BottomModalTransitionDelegate(height: height) body.view.backgroundColor = .white body.transitioningDelegate = transitioningDelegate body.modalPresentationStyle = .custom self.presentingViewController = presentingViewController presentingViewController.present(body, animated: true, completion: nil) } func dismiss(then: @escaping () -> Void) { presentingViewController?.dismiss(animated: true, completion: then) } }
38.962264
81
0.733656
87f09ee18eb96381b6f781a8358f664fed860114
1,128
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "AutoLayoutProxy", platforms: [ .macOS(.v10_11), .iOS(.v9) ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "AutoLayoutProxy", targets: ["AutoLayoutProxy"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "AutoLayoutProxy", dependencies: []), .testTarget( name: "AutoLayoutProxyTests", dependencies: ["AutoLayoutProxy"]), ] )
34.181818
122
0.617908
09c34e611c1686e451cfa744f6290567764dd293
984
// // ZJOneWordView.swift // ZJWidPackExtension // // Created by wangshuailong on 2020/10/19. // import SwiftUI struct ZJOneWordView : View { let oneModel : OneWordModel var body: some View { VStack(alignment: .leading, spacing: 10, content: { //内容 Text(oneModel.hitokoto) .multilineTextAlignment(.center) .padding(.all) //来源 HStack(alignment: .bottom, spacing: nil, content: { //占位弹 Spacer() //来源 Text(oneModel.from) .font(.footnote) .foregroundColor(.gray) .lineLimit(1) .padding(.all) }) }) } } struct ZJOneWordView_Previews: PreviewProvider { static var previews: some View { /*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/ } }
22.363636
71
0.477642
20c63a0037db587f401641ca62c9b818dad3b200
2,853
// // CachedHTTPDataSource.swift // ScotTraffic // // Created by Neil Gall on 01/11/2015. // Copyright © 2015 Neil Gall. All rights reserved. // import Foundation public class CachedHTTPDataSource: DataSource { // Output public let value = Signal<DataSourceData>() private let diskCache: DiskCache private let httpAccess: HTTPAccess private let maximumCacheAge: NSTimeInterval private let key: String private var httpSource: HTTPDataSource? private var httpReceiverType: ReceiverType? private var inFlight = false init(httpAccess: HTTPAccess, cache: DiskCache, maximumCacheAge: NSTimeInterval, path: String) { self.httpAccess = httpAccess self.diskCache = cache self.maximumCacheAge = maximumCacheAge self.key = path } public func start() { guard !inFlight else { // already in-flight return } inFlight = true diskCache.dataForKey(key) { result in switch result { case .Hit(let data, let date): let age = NSDate().timeIntervalSinceDate(date) self.cacheHit(data, age: age) case .Miss: self.startHTTPSource(false) } } } private func cacheHit(data: NSData, age: NSTimeInterval) { let expired = age > maximumCacheAge value.pushValue(.Cached(data, expired: expired)) if !expired { inFlight = false } else { // cache hit but old, so follow up with network fetch startHTTPSource(true) } } private func startHTTPSource(afterCacheHit: Bool) { let httpSource = HTTPDataSource(httpAccess: httpAccess, path: self.key) httpReceiverType = httpSource.value --> { dataOrError in switch dataOrError { case .Fresh(let data): self.diskCache.storeData(data, forKey: self.key) self.value.pushValue(dataOrError) case .Error: if !afterCacheHit { self.value.pushValue(dataOrError) } case .Cached, .Empty: break } self.endHTTPSource() } self.httpSource = httpSource httpSource.start() } private func endHTTPSource() { httpSource = nil httpReceiverType = nil inFlight = false } public static func dataSourceWithHTTPAccess(httpAccess: HTTPAccess, cache: DiskCache)(maximumCacheAge: NSTimeInterval)(path: String) -> DataSource { return CachedHTTPDataSource(httpAccess: httpAccess, cache: cache, maximumCacheAge: maximumCacheAge, path: path) } }
28.818182
152
0.578339
fe58be08d8ca59bae612b5c13eaf399414f7fc75
1,109
// // GitHubModel.swift // RxSwiftDemo // // Created by WhatsXie on 2018/5/2. // Copyright © 2018年 WhatsXie. All rights reserved. // import Foundation import ObjectMapper //包含查询返回的所有库模型 struct GitHubRepositories: Mappable { var totalCount: Int! var incompleteResults: Bool! var items: [GitHubRepository]! //本次查询返回的所有仓库集合 init() { print("init()") totalCount = 0 incompleteResults = false items = [] } init?(map: Map) { } // Mappable mutating func mapping(map: Map) { totalCount <- map["total_count"] incompleteResults <- map["incomplete_results"] items <- map["items"] } } //单个仓库模型 struct GitHubRepository: Mappable { var id: Int! var name: String! var fullName:String! var htmlUrl:String! var description:String! init?(map: Map) { } // Mappable mutating func mapping(map: Map) { id <- map["id"] name <- map["name"] fullName <- map["full_name"] htmlUrl <- map["html_url"] description <- map["description"] } }
20.537037
54
0.585212
e4c5be7ee7564f13fe89072da253afdaedf0a9db
2,515
import RxSwift import RxCocoa /// custom direction enumeration public enum FlipDirection { case left, right, top, bottom var viewTransition: UIViewAnimationOptions { switch self { case .left: return .transitionFlipFromLeft case .right: return .transitionFlipFromRight case .top: return .transitionFlipFromTop case .bottom: return .transitionFlipFromBottom } } } // MARK: - built-in animations extension AnimatedSink where Base: UIView { /// cross-dissolve animation on `UIView` public func fade(duration: TimeInterval) -> AnimatedSink<Base> { let type = AnimationType<Base>(type: RxAnimationType.transition(.transitionCrossDissolve), duration: duration, animations: nil) return AnimatedSink<Base>(base: self.base, type: type) } /// flip animation on `UIView` public func flip(_ direction: FlipDirection, duration: TimeInterval) -> AnimatedSink<Base> { let type = AnimationType<Base>(type: RxAnimationType.transition(direction.viewTransition), duration: duration, animations: nil) return AnimatedSink<Base>(base: self.base, type: type) } /// example of extending RxAnimated with a custom animation public func tick(_ direction: FlipDirection = .right, duration: TimeInterval) -> AnimatedSink<Base> { let type = AnimationType<Base>(type: RxAnimationType.spring(damping: 0.33, velocity: 0), duration: duration, setup: { view in view.alpha = 0 view.transform = CGAffineTransform(rotationAngle: direction == .right ? -0.3 : 0.3) }, animations: { view in view.alpha = 1 view.transform = CGAffineTransform.identity }) return AnimatedSink<Base>(base: self.base, type: type) } public func animation(duration: TimeInterval, options: UIViewAnimationOptions = [], animations: @escaping ()->Void) -> AnimatedSink<Base> { let type = AnimationType<Base>(type: RxAnimationType.animation, duration: duration, animations: { _ in animations() }) return AnimatedSink<Base>(base: self.base, type: type) } } extension AnimatedSink where Base: NSLayoutConstraint { /// auto layout animations public func layout(duration: TimeInterval) -> AnimatedSink<Base> { let type = AnimationType<Base>(type: RxAnimationType.animation, duration: duration, animations: { view in view.layoutIfNeeded() }) return AnimatedSink<Base>(base: self.base, type: type) } }
41.916667
143
0.683897
e016c9739b271570649b21ca1fcd9577af58afd9
3,653
// // YourClassesCollectionViewCell.swift // AnywhereFitness // // Created by Dillon P on 10/27/19. // Copyright © 2019 Julltron. All rights reserved. // import UIKit class YourClassesCollectionViewCell: UICollectionViewCell { @IBOutlet weak var fitnessCategoryImage: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var intensityLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var timeAndDurationLabel: UILabel! var fitClass: FitClassRepresentation? { didSet { updateViews() } } var fitClassController: FitClassController? var delegate: YourClassesViewController? //AppHomeViewController? var registered: Bool { guard let fitClass = fitClass, let registeredClients = fitClass.registrants, let user = UserController.shared.loggedInUser, let uid = user.uid, registeredClients.contains(uid) else { return false } return true } @IBAction func cancelBtnTapped(_ sender: Any) { guard let fitClassController = fitClassController, let fitClass = fitClass, let delegate = delegate else { return } let alert = UIAlertController(title: "", message: "", preferredStyle: .alert) if registered { // cancel registration fitClassController.cancelRegistration(representation: fitClass) { cancelled in if cancelled { guard let uid = UserController.shared.loggedInUser?.uid, let i = fitClass.registrants?.firstIndex(of: uid) else { return } DispatchQueue.main.async { self.fitClass?.registrants?.remove(at: i) alert.title = "Registration cancelled" alert.message = "Your registration for this class has been cancelled. Why not choose another one?" self.updateViews() } } else { DispatchQueue.main.async { alert.title = "Couldn't cancel!" alert.message = "Sorry, something went wrong and we couldn't cancel your registration. Please try again later." } } } } DispatchQueue.main.async { alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: nil)) delegate.present(alert, animated: true, completion: nil) delegate.getClasses() } } func updateViews() { guard let fitClass = fitClass else { return } DispatchQueue.main.async { self.titleLabel.text = fitClass.title self.categoryLabel.text = "Class Type: \(fitClass.category)" self.intensityLabel.text = "Intensity Level: \(fitClass.intensity.capitalized)" self.locationLabel.text = "\(fitClass.city), \(fitClass.state)" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMM d, @ h a" if let timeSince1970 = Double(fitClass.startTime) { let date = Date(timeIntervalSince1970: timeSince1970) self.timeAndDurationLabel.text = dateFormatter.string(from: date) + " for \(fitClass.duration) minutes" } self.fitnessCategoryImage.image = UIImage(named: fitClass.category) } } }
38.861702
135
0.589926
d690057c33c4b332b29e0ef4a302f1be551e5392
2,339
// // Created by Thomas Evensen on 20/01/2017. // Copyright © 2017 Thomas Evensen. All rights reserved. // // swiftlint:disable line_length import Foundation final class ExecuteQuickbackupTask: SetConfigurations { var outputprocess: OutputfromProcess? var arguments: [String]? var config: Configuration? // Process termination and filehandler closures var processtermination: () -> Void var filehandler: () -> Void private func executetask() { if let dict: NSDictionary = SharedReference.shared.quickbackuptask { if let hiddenID: Int = dict.value(forKey: DictionaryStrings.hiddenID.rawValue) as? Int { let getconfigurations: [Configuration]? = configurations?.getConfigurations() guard getconfigurations != nil else { return } let configArray = getconfigurations!.filter { $0.hiddenID == hiddenID } guard configArray.count > 0 else { return } config = configArray[0] if hiddenID >= 0, config != nil { arguments = ArgumentsSynchronize(config: config).argumentssynchronize(dryRun: false, forDisplay: false) // Setting reference to finalize the job, finalize job is done when rsynctask ends (in process termination) SharedReference.shared.completeoperation = CompleteQuickbackupTask(dict: dict) globalMainQueue.async { if let arguments = self.arguments { let process = RsyncProcess(arguments: arguments, config: self.config, processtermination: self.processtermination, filehandler: self.filehandler) process.executeProcess(outputprocess: self.outputprocess) } } } } } } init(processtermination: @escaping () -> Void, filehandler: @escaping () -> Void, outputprocess: OutputfromProcess?) { self.processtermination = processtermination self.filehandler = filehandler self.outputprocess = outputprocess executetask() } }
43.314815
127
0.57717
b9249b86b53979ec679fcb1fcb22adf37ff26075
2,150
// // AppDelegate.swift // TTM // // Created by William Peroche on 11/04/2015. // Copyright (c) 2015 William Peroche. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.744681
285
0.753953
f8b1556b5146ea67d40ab869ddb421d1370f062f
14,398
// // Constant.swift // Shir // // import Foundation import UIKit let kEmptyString = "" let kEmptyInt = 0 let kEmptyDouble = 0.0 let kEmptyBoolean = false extension UIColor { convenience init(red: CGFloat, green: CGFloat, blue: CGFloat) { self.init(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1) } convenience init(hexColor: String) { var red: UInt32 = 0, green: UInt32 = 0, blue: UInt32 = 0 let hex = hexColor as NSString Scanner(string: hex.substring(with: NSRange(location: 0, length: 2))).scanHexInt32(&red) Scanner(string: hex.substring(with: NSRange(location: 2, length: 2))).scanHexInt32(&green) Scanner(string: hex.substring(with: NSRange(location: 4, length: 2))).scanHexInt32(&blue) self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0) } } struct Constants { // Constants to call services to server static let kTagColor = UIColor.init(hexColor: "6d96ad") static let kBlackColor = UIColor.init(red: 0.6901, green: 0.6901, blue: 0.6901, alpha: 1.0) static let kBorderColor = UIColor.lightGray static let kNavigationcolor = UIColor.init(red: 0.1647, green: 0.5882, blue: 0.9176, alpha: 1.0) static let kPlaceholderColor = UIColor.gray static let kCornerRaious : CGFloat = 5.0 static var deviceToken = "DummyToken" static var ShareLinkConstant = "https://healingbudz.com/" static var defaultDateFormate = "yyyy-MM-dd HH:mm:ss" static var SeeMore = "- See More" static var DeepLinkConstant = "healingbudz.com" } struct ConstantsColor { static let kUnder100Color = UIColor.init(red: (255/255), green: (255/255), blue: (255/255), alpha: 1.0) static let kUnder200Color = UIColor.init(red: (123/255), green: (192/255), blue: (67/255), alpha: 1.0) static let kUnder300Color = UIColor.init(red: (237/255), green: (191/255), blue: (46/255), alpha: 1.0) static let kUnder400Color = UIColor.init(red: (232/255), green: (150/255), blue: (6/255), alpha: 1.0) static let kUnder500Color = UIColor.init(red: (224/255), green: (112/255), blue: (224/255), alpha: 1.0) static var gradiant_first_colro = UIColor(red:174.0/255.0, green:89.0/255.0, blue:194.0/255.0, alpha:1.000).cgColor static var gradiant_second_colro = UIColor(red:194.0/255.0, green:68.0/255.0, blue:98.0/255.0, alpha:1.000).cgColor static let kBudzSelectColor = UIColor.init(red: (153/255), green: (45/255), blue: (127/255), alpha: 1.0) static let kBudzUnselectColor = UIColor.init(red: (92/255), green: (92/255), blue: (92/255), alpha: 1.0) static let kStrainSelectColor = UIColor.init(red: (244/255), green: (196/255), blue: (47/255), alpha: 1.0) static let kHomeColor = UIColor.init(red: 0.490, green: 0.745, blue: 0.298, alpha: 1.0) static let kQuestionColor = UIColor.init(red: 0.075, green: 0.416, blue: 0.612, alpha: 1.0) static let kJournalColor = UIColor.init(red: 0.345, green: 0.541, blue: 0.259, alpha: 1.0) static let kGroupColor = UIColor.init(red: 0.667, green: 0.404, blue: 0.196, alpha: 1.0) static let kStrainColor = UIColor.init(red:0.957, green:0.769, blue:0.290, alpha:1.000) static let kStrainGreenColor = UIColor.init(red:(124/255), green:(194/255), blue:(68/255), alpha:1.000) static let kStrainRedColor = UIColor.init(red:(194/255), green:(68/255), blue:(98/255), alpha:1.000) static let kStrainPurpleColor = UIColor.init(red:(174/255), green:(89/255), blue:(194/255), alpha:1.000) static let kBudzColor = UIColor.init(red:0.420, green:0.114, blue:0.396, alpha:1.000) static let kDarkGrey = UIColor(red: 0.165, green: 0.165, blue: 0.165, alpha: 1.0) static let KLightGrayColor = UIColor.init(hexColor: "555555") } //MARK:- Numbers let kZero: CGFloat = 0.0 let kOne: CGFloat = 1.0 let kHalf: CGFloat = 0.5 let kTwo: CGFloat = 2.0 let kHundred: CGFloat = 100.0 let kDefaultAnimationDuration = 0.3 struct StoryBoardConstant { static let QA = "QAStoryBoard" static let Profile = "ProfileView" static let Budz = "BudzStoryBoard" static let Main = "Main" static let Reward = "Rewards" static let SurveyStrain = "SurveyStoryBoard" } //MARK:- Messages struct Alert { static let kEmptyCredentails = "Please provide your credentails to proceed!" static let kWrongEmail = "Incorrect email format. Please provide a valid email address!" static let kEmptyEmail = "Email address is missing!" static let kEmptyPassword = "Password is missing!" static let kPasswordNotMatch = "Password not match with confirm password!" static let kUserNameMissing = "UserName is missing!" static let kUserImageMissing = "User image is missing!" } let kErrorTitle = "Error!" let kInformationMissingTitle = "Information Missing!" let kOKBtnTitle = "OK" let kCancelBtnTitle = "Cancel" let kDismissBtnTitle = "Dismiss" let kTryAgainBtnTitle = "Try Again!" let kDescriptionHere = "Description Here..." var kNetworkNotAvailableMessage = "It appears that you are not connected with internet. Please check your internet connection and try again." //var kServerNotReachableMessage = "We are unable to connect our server at the moment. Please check your device internet settings or try later." var kServerNotReachableMessage = "Network not Available!" //"Network not Available!" var kFacebookSigninFailedMessage = "We are unable to get your identity from Facebook. Please check your Facebook profile settings and then try again." struct Notifications{ static let googleSignInNotification = "Google_SignIn_Notificaiton" } enum DataType: String { case Image = "0" } enum StrainSurveyType: String { case Medical = "0" case Mood = "1" case Disease = "2" case Negative = "4" case Flavor = "3" } enum ActivityLog:String { case strainAdd = "0" case followingBud = "1" case QuestionAsked = "2" case Answered = "3" case Liked = "4" case Favourites = "5" case AddedJournal = "6" case StartedJournal = "7" case CreatedGroup = "8" case JoinedGroup = "9" case FollowingTags = "10" case JoinedHealingBud = "11" case Random = "12" case Comment = "13" case Post = "14" case Tags = "15" } enum StrainDataType: String { case Header = "0" case ButtonChoose = "1" case Description = "2" case SurveyResult = "3" case DetailSurvey = "4" case TextWithImage = "5" case ImageSubmit = "6" case ReviewTotal = "7" case CommentCell = "8" case AddYourcomment = "9" case AddImage = "10" case ShowImage = "11" case AddRating = "12" case TellExperience = "13" case SubmitComment = "14" case LocateThisBud = "15" case NearStrain = "16" case StrainBud = "17" case StrainAddInfo = "18" case StrainShowDes = "19" case StrainShowType = "20" case StrainShowCrossBreed = "21" case chemistryCell = "22" case StrainShowCare = "23" case StrainShowEditHeading = "24" case StrainShowUserEdit = "25" case EmptyBlankCell = "29" case googleAdd = "26" case nosurvay = "27" case addplace = "28" case noFullSurvay = "30" } enum AddNewStrain: String { case HeaderView = "0" case ImageUpload = "1" case AddInfo = "2" case AddType = "3" case AddBreed = "4" case Chemistry = "5" case AddCare = "6" case AddNotes = "7" case Submit = "8" } enum StrainFilter: String { case NameKeyword = "0" case StrainMatchingText = "1" case Button = "2" case FilterBy = "3" case TextFieldSearch = "4" } enum JournalListing : String { case ExpandCell = "0" case DetailCell = "1" case LineCell = "2" } enum JournalCell : String{ case AddCell = "0" case JournalCell = "1" } enum TagsCell : String{ case tags = "0" case tagEdit = "1" case treatment = "2" } enum mainSettingCell: String{ case normalCell = "0" case switchCell = "1" } enum businessListingSettings: String{ case titleCell = "0" case premiumCell = "1" case billingCell = "2" case amountCell = "3" case mybusinessCell = "4" } enum journalSettings: String{ case quickEntryCell = "0" case reminderCell = "1" case dataCell = "2" } enum notifications_Alerts: String{ case mainHeadingCell = "0" case notificationCell = "1" case subHeadingCell = "2" case notificationCell2 = "3" case keywordCell = "4" } enum profileSettings: String{ case profileSettingsTitleCell = "0" case profileSettingsDetailCell = "1" case profileSettingsEmailCell = "2" case profileSettingsMedicalConditionsCell = "3" case profileSettingsUserInfo = "4" case profileBudzInfo = "5" case profileButton = "6" case isQACell = "7" case QACell = "8" case AnswerCell = "9" case StrainHeadingCell = "10" case BudzHeadingCell = "12" case StrainCell = "11" case BudzCell = "13" case StrainReview = "14" case BudzReview = "15" case TextPostCell = "16" case MediaPostCell = "17" case NoRecordFound = "18" case LoadingMore = "19" } enum reminderSettings: String{ case reminderSettingsSwitchCell = "0" case reminderSettingsTimerCell = "1" } enum dataSettings : String{ case dataSettingsWifiCell = "0" case dataSettingsSyncNotification = "1" case dataSettingsBackupCell = "2" } struct ScreenSize { static let SCREEN_WIDTH = UIScreen.main.bounds.size.width static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } struct DeviceType { static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0 static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0 static let IS_IPHONE_5_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH <= 568.0 static let IS_IPHONE_6_7 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0 static let IS_IPHONE_6P_7P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0 static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0 static let IS_IPAD_PRO = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0 } enum BudzIcon : String{ case Dispencery = "DispensaryIcon" case Entertainment = "EntertainmentIcon" case Event = "EventsIcon" case Cannabites = "CannabitesIcon" case Medical = "MedicalIcon" case Others = "OthersIcon" } enum BudzMapDataType: String { case Header = "0" case MenuButton = "1" case BudzDescription = "2" case Location = "3" case WeekHours = "4" case WebsiteLinks = "5" case PaymentMethods = "6" case TotalReviews = "7" case UserReview = "8" case AddReviewTextview = "9" case AddReviewImage = "10" case ImageView = "11" case AddRating = "12" case SubmitActionButton = "13" case ReviewHeading = "14" case Languages = "15" case HeadingWithText = "16" case BudzEventTime = "17" case BudzSpecial = "18" case BudzProduct = "19" case BudzService = "20" case NoRecord = "21" case NoRecordtext = "23" case addYourComment = "22" case addSpecial = "30" case eventTicktes = "31" case eventPaymentMethods = "32" case evnetPurchaseTicketCell = "33" case addProductServices = "244" case addNewEvent = "54" case othersImage = "35" } enum NewBudzMapDataType: String { case Header = "0" case MenuButton = "1" case Heading = "2" case BudzType = "3" case EnterText = "4" case Location = "5" case Contact = "6" case HoursofOpreation = "7" case SubmitButton = "8" case AddLanguage = "9" case ShowLanguage = "10" case InsuranceAccepted = "11" case AddRating = "12" case EventTime = "13" case Payment = "14" case UploadButton = "15" case OtherAttachment = "16" }
36.543147
150
0.575288
203fe33a0292a3e2082ca7c46d3ada85fa997ac7
15,055
import Foundation import SourceryRuntime import SwiftSyntax extension SyntaxProtocol { @inlinable var sourcerySafeTypeIdentifier: String { let content = description return String(content[content.index(content.startIndex, offsetBy: leadingTriviaLength.utf8Length)..<content.index(content.endIndex, offsetBy: -trailingTriviaLength.utf8Length)]) // TBR: we only need this because we are trying to fit into old AST naming // TODO: there is a bug in syntax that sometimes crashes with unexpected nil when removing trivia // if trailingTriviaLength.utf8Length != 0 || leadingTriviaLength.utf8Length != 0 { //// return withoutTrivia().description.trimmed // } else { // return description.trimmed // } } } extension TypeName { convenience init(_ node: TypeSyntax) { /* TODO: redesign what `TypeName` represents, it can represent all those different variants Furthermore if `TypeName` was used to store Type the whole composer process could probably be simplified / optimized? */ if let typeIdentifier = node.as(SimpleTypeIdentifierSyntax.self) { let name = typeIdentifier.name.text.trimmed // TODO: typeIdentifier.sourcerySafeTypeIdentifier ? let generic = typeIdentifier.genericArgumentClause.map { GenericType(name: typeIdentifier.name.text, node: $0) } // optional gets special treatment if name == "Optional", let unwrappedTypeName = generic?.typeParameters.first?.typeName.name, generic?.typeParameters.count == 1 { // TODO: TBR self.init(name: typeIdentifier.sourcerySafeTypeIdentifier, isOptional: true, generic: nil) self.unwrappedTypeName = unwrappedTypeName } else { // special treatment for spelled out literals switch (name, generic?.typeParameters.count) { case ("Array", 1?): let elementTypeName = generic!.typeParameters[0].typeName let array = ArrayType(name: "Array<\(elementTypeName.asSource)>", elementTypeName: elementTypeName) self.init(name: array.name, array: array, generic: array.asGeneric) case ("Dictionary", 2?): let keyTypeName = generic!.typeParameters[0].typeName let valueTypeName = generic!.typeParameters[1].typeName let dictionary = DictionaryType(name: "Dictionary<\(keyTypeName.asSource), \(valueTypeName.asSource)>", valueTypeName: valueTypeName, keyTypeName: keyTypeName) self.init(name: dictionary.name, dictionary: dictionary, generic: dictionary.asGeneric) default: self.init(name: typeIdentifier.sourcerySafeTypeIdentifier, generic: generic) } } } else if let typeIdentifier = node.as(MemberTypeIdentifierSyntax.self) { let base = TypeName(typeIdentifier.baseType) // TODO: VERIFY IF THIS SHOULD FULLY WRAP let fullName = "\(base.name).\(typeIdentifier.name.text.trimmed)" let generic = typeIdentifier.genericArgumentClause.map { GenericType(name: fullName, node: $0) } if let genericComponent = generic?.typeParameters.map({ $0.typeName.asSource }).joined(separator: ", ") { self.init(name: "\(fullName)<\(genericComponent)>", generic: generic) } else { self.init(name: fullName, generic: generic) } } else if let typeIdentifier = node.as(CompositionTypeSyntax.self) { let types = typeIdentifier.elements.map { TypeName($0.type) } let name = types.map({ $0.name }).joined(separator:" & ") self.init(name: name, isProtocolComposition: true) } else if let typeIdentifier = node.as(OptionalTypeSyntax.self) { let type = TypeName(typeIdentifier.wrappedType) let needsWrapping = type.isClosure || type.isProtocolComposition self.init(name: needsWrapping ? "(\(type.name))" : type.name, isOptional: true, isImplicitlyUnwrappedOptional: false, tuple: type.tuple, array: type.array, dictionary: type.dictionary, closure: type.closure, generic: type.generic, isProtocolComposition: type.isProtocolComposition ) } else if let typeIdentifier = node.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) { let type = TypeName(typeIdentifier.wrappedType) let needsWrapping = type.isClosure || type.isProtocolComposition self.init(name: needsWrapping ? "(\(type.name))" : type.name, isOptional: false, isImplicitlyUnwrappedOptional: true, tuple: type.tuple, array: type.array, dictionary: type.dictionary, closure: type.closure, generic: type.generic, isProtocolComposition: type.isProtocolComposition ) } else if let typeIdentifier = node.as(ArrayTypeSyntax.self) { let elementType = TypeName(typeIdentifier.elementType) let name = typeIdentifier.sourcerySafeTypeIdentifier let array = ArrayType(name: name, elementTypeName: elementType) self.init(name: name, array: array, generic: array.asGeneric) } else if let typeIdentifier = node.as(DictionaryTypeSyntax.self) { let keyType = TypeName(typeIdentifier.keyType) let valueType = TypeName(typeIdentifier.valueType) let name = typeIdentifier.sourcerySafeTypeIdentifier let dictionary = DictionaryType(name: name, valueTypeName: valueType, keyTypeName: keyType) self.init(name: name, dictionary: dictionary, generic: dictionary.asGeneric) } else if let typeIdentifier = node.as(TupleTypeSyntax.self) { let elements = typeIdentifier.elements.enumerated().map { idx, element -> TupleElement in var firstName = element.name?.text.trimmed let secondName = element.secondName?.text.trimmed if firstName?.nilIfNotValidParameterName == nil, secondName == nil { firstName = "\(idx)" } return TupleElement(name: firstName, typeName: TypeName(element.type)) } let name = typeIdentifier.sourcerySafeTypeIdentifier // TODO: TBR if elements.count == 1, let type = elements.first?.typeName { self.init(name: type.name, attributes: type.attributes, isOptional: type.isOptional, isImplicitlyUnwrappedOptional: type.isImplicitlyUnwrappedOptional, tuple: type.tuple, array: type.array, dictionary: type.dictionary, closure: type.closure, generic: type.generic, isProtocolComposition: type.isProtocolComposition ) } else if elements.count == 0 { // Void self.init(name: "()") } else { self.init(name: name, tuple: TupleType(name: name, elements: elements)) } } else if let typeIdentifier = node.as(FunctionTypeSyntax.self) { /// TBR // let name = typeIdentifier.sourcerySafeTypeIdentifier let elements = typeIdentifier.arguments.map { node -> ClosureParameter in let firstName = node.name?.text.trimmed.nilIfNotValidParameterName return ClosureParameter( argumentLabel: firstName, name: node.secondName?.text.trimmed ?? firstName, typeName: TypeName(node.type)) } let returnTypeName = TypeName(typeIdentifier.returnType) let throwsOrRethrows = typeIdentifier.throwsOrRethrowsKeyword.map { $0.text.trimmed } let name = "\(elements.asSource)\(throwsOrRethrows != nil ? " \(throwsOrRethrows!)" : "") -> \(returnTypeName.asSource)" self.init(name: name, closure: ClosureType(name: name, parameters: elements, returnTypeName: returnTypeName, throwsOrRethrowsKeyword: throwsOrRethrows)) } else if let typeIdentifier = node.as(AttributedTypeSyntax.self) { let type = TypeName(typeIdentifier.baseType) // TODO: add test for nested type with attributes at multiple level? let attributes = Attribute.from(typeIdentifier.attributes) self.init(name: type.name, attributes: attributes, isOptional: type.isOptional, isImplicitlyUnwrappedOptional: type.isImplicitlyUnwrappedOptional, tuple: type.tuple, array: type.array, dictionary: type.dictionary, closure: type.closure, generic: type.generic, isProtocolComposition: type.isProtocolComposition ) } else if node.as(ClassRestrictionTypeSyntax.self) != nil { self.init(name: "AnyObject") } else { // assertionFailure("This is unexpected \(node)") self.init(node.sourcerySafeTypeIdentifier) } } } // TODO: when I don't need to adapt to old formats //import Foundation //import SourceryRuntime //import SwiftSyntax // //extension TypeName { // convenience init(_ node: TypeSyntax) { // /* TODO: redesign what `TypeName` represents, it can represent all those different variants // Furthermore if `TypeName` was used to store Type the whole composer process could probably be simplified / optimized? // */ // if let typeIdentifier = node.as(SimpleTypeIdentifierSyntax.self) { // let name = typeIdentifier.name.text.trimmed // let generic = typeIdentifier.genericArgumentClause.map { GenericType(name: typeIdentifier.name.text, node: $0) } // // // optional gets special treatment // if name == "Optional", let wrappedTypeName = generic?.typeParameters.first?.typeName.name, generic?.typeParameters.count == 1 { // self.init(name: wrappedTypeName, isOptional: true, generic: generic) // } else { // self.init(name: name, generic: generic) // } // } else if let typeIdentifier = node.as(MemberTypeIdentifierSyntax.self) { // let base = TypeName(typeIdentifier.baseType) // TODO: VERIFY IF THIS SHOULD FULLY WRAP // self.init(name: "\(base.name).\(typeIdentifier.name.text.trimmed)") // } else if let typeIdentifier = node.as(CompositionTypeSyntax.self) { // let types = typeIdentifier.elements.map { TypeName($0.type) } // let name = types.map({ $0.name }).joined(separator:" & ") // self.init(name: name) // } else if let typeIdentifier = node.as(OptionalTypeSyntax.self) { // let type = TypeName(typeIdentifier.wrappedType) // self.init(name: type.name, // isOptional: true, // isImplicitlyUnwrappedOptional: type.isImplicitlyUnwrappedOptional, // tuple: type.tuple, // array: type.array, // dictionary: type.dictionary, // closure: type.closure, // generic: type.generic // ) // } else if let typeIdentifier = node.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) { // let type = TypeName(typeIdentifier.wrappedType) // self.init(name: type.name, // isOptional: type.isOptional, // isImplicitlyUnwrappedOptional: true, // tuple: type.tuple, // array: type.array, // dictionary: type.dictionary, // closure: type.closure, // generic: type.generic // ) // } else if let typeIdentifier = node.as(ArrayTypeSyntax.self) { // let elementType = TypeName(typeIdentifier.elementType) // let name = typeIdentifier.description.trimmed // let array = ArrayType(name: name, elementTypeName: elementType) // self.init(name: name, array: array, generic: array.asGeneric) // } else if let typeIdentifier = node.as(DictionaryTypeSyntax.self) { // let keyType = TypeName(typeIdentifier.keyType) // let valueType = TypeName(typeIdentifier.valueType) // let name = typeIdentifier.description.trimmed // let dictionary = DictionaryType(name: name, valueTypeName: valueType, keyTypeName: keyType) // self.init(name: name, dictionary: dictionary, generic: dictionary.asGeneric) // } else if let typeIdentifier = node.as(TupleTypeSyntax.self) { // let elements = typeIdentifier.elements.map { TupleElement(name: $0.name?.text.trimmed, secondName: $0.secondName?.text.trimmed, typeName: TypeName($0.type)) } // let name = typeIdentifier.description.trimmed // self.init(name: name, tuple: TupleType(name: name, elements: elements)) // } else if let typeIdentifier = node.as(FunctionTypeSyntax.self) { // let name = typeIdentifier.description.trimmed // let elements = typeIdentifier.arguments.map { TupleElement(name: $0.name?.text.trimmed, secondName: $0.secondName?.text.trimmed, typeName: TypeName($0.type)) } // self.init(name: name, closure: ClosureType(name: name, parameters: elements, returnTypeName: TypeName(typeIdentifier.returnType))) // } else if let typeIdentifier = node.as(AttributedTypeSyntax.self) { // let type = TypeName(typeIdentifier.baseType) // TODO: add test for nested type with attributes at multiple level? // let attributes = Attribute.from(typeIdentifier.attributes) // self.init(name: type.name, // attributes: attributes, // isOptional: type.isOptional, // isImplicitlyUnwrappedOptional: type.isImplicitlyUnwrappedOptional, // tuple: type.tuple, // array: type.array, // dictionary: type.dictionary, // closure: type.closure, // generic: type.generic // ) // } else if node.as(ClassRestrictionTypeSyntax.self) != nil { // self.init(name: "AnyObject") // } else { // assertionFailure("This is unexpected \(node)") // self.init(node.description.trimmed) // } // } //}
57.903846
185
0.601594
ab17e1c1b8800831e88b06ebb3be83f766415d7a
95
import rdar32973206_a public extension B { public class var foo: Int { get { return 0 } } }
15.833333
48
0.694737
9c3df8830867b8aab4e426754654f3ab5a21b31f
611
// // Common.swift // SinaWeibo_swift // // Created by archy on 16/10/25. // Copyright © 2016年 archy. All rights reserved. // import Foundation //MARK: --授权常量 let app_key = "3216380832" let app_secret = "415a1932f3a79577ff1979606e55ebed" let redirect_uri = "http://ios.itcast.cn" // MARK:- 选择照片的通知常量 let PicPickerAddPhotoNote = "PicPickerAddPhotoNote" let PicPickerRemovePhotoNote = "PicPickerRemovePhotoNote" // MARK:- 照片浏览器的通知常量 let ShowPhotoBrowserNote = "ShowPhotoBrowserNote" let ShowPhotoBrowserIndexKey = "ShowPhotoBrowserIndexKey" let ShowPhotoBrowserUrlsKey = "ShowPhotoBrowserUrlsKey"
19.709677
57
0.767594
61efa8c92808eee3f30336db51cce92389cbce46
1,784
// // QRAlphaNum.swift // QRCode Generator // // Created by Vitali Kurlovich on 11/9/17. // final class QRAlphaNum: QRData { init(_ data:String) { super .init(QRMode.MODE_ALPHA_NUM, data) } override func write(_ buffer: inout QRBitBuffer) { var i = 0; while (i + 1 < data.count) { let first = data[String.Index(encodedOffset:i)] let second = data[String.Index(encodedOffset:(i+1))] let val = getCode(first) * 45 + getCode(second) buffer.put(val, 11); i += 2; } if i < data.count { let last = data[String.Index(encodedOffset:i)] let val = getCode(last) buffer.put(val, 6); } } private static let CHAR_MAP:Dictionary<Character, Int> = ["0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"A":10,"B":11,"C":12,"D":13,"E":14,"F":15,"G":16,"H":17,"I":18,"J":19,"K":20,"L":21,"M":22,"N":23,"O":24,"P":25,"Q":26,"R":27,"S":28,"T":29,"U":30,"V":31,"W":32,"X":33,"Y":34,"Z":35, " ":36, "$":37, "%":38, "*":39, "+":40, "-":41, ".":42, "/":43, ":":44]; /* case ' ' : return 36; case '$' : return 37; case '%' : return 38; case '*' : return 39; case '+' : return 40; case '-' : return 41; case '.' : return 42; case '/' : return 43; case ':' : return 44; */ private func getCode(_ c:Character) -> Int { return QRAlphaNum.CHAR_MAP[c]!; /* if ("0" <= c && c <= "9") { return c - '0'; } else if ("A" <= c && c <= "Z") { return c - 'A' + 10; } else { switch (c) { case ' ' : return 36; case '$' : return 37; case '%' : return 38; case '*' : return 39; case '+' : return 40; case '-' : return 41; case '.' : return 42; case '/' : return 43; case ':' : return 44; default : throw new IllegalArgumentException("illegal char :" + c); } } */ //return 0; } }
22.024691
374
0.525224
64a6f5c0b4c1d1b9a8f52cde06fcbaeb25bd08d9
2,340
// // LocationSourcesController.swift // SimpleMapSwift // // Created by Daniel Nielsen on 25/01/2018. // Copyright © 2018 MapsPeople A/S. All rights reserved. // import UIKit import GoogleMaps import MapsIndoors /*** --- title: Creating your own Location Sources - Part 3 --- This is part 3 of the tutorial of building custom Location Sources. In [Part 1](locationsourcespeoplelocationsource) and [2 we created the Location Sources](roomavailabilitysource). Now we will create a view controller displaying a map that shows the mocked people locations and the mocked room availability on top of a MapsIndoors map. Create a class `LocationSourcesController` that inherits from `UIViewController`. ***/ class LocationSourcesController: UIViewController { /*** Add a `GMSMapView` and a `MPMapControl` to the class ***/ var map: GMSMapView? = nil var mapControl: MPMapControl? = nil override func viewDidLoad() { super.viewDidLoad() /*** Inside `viewDidLoad`, register the sources `PeopleLocationSource` and `RoomAvailabilitySource` ***/ MapsIndoors.register([ PeopleLocationSource.init(type: "People"), RoomAvailabilitySource.init() ]) /*** Inside `viewDidLoad`, setup the map so that it shows the demo venue and initialise mapControl ***/ self.map = GMSMapView.init(frame: CGRect.zero) self.view = self.map self.map?.camera = .camera(withLatitude: 57.057964, longitude: 9.9504112, zoom: 20) self.mapControl = MPMapControl.init(map: self.map!) /*** Inside `viewDidLoad`, setup a display setting that refers to the type of locations that your people location source operates with. ***/ let dr = MPLocationDisplayRule.init(name: "People", andIcon: UIImage.init(named: "user.png"), andZoomLevelOn: 17)! dr.displayRank = 99999 self.mapControl?.setDisplayRule(dr) } /*** Optionally, when you leave this controller. Remove the custom Location Source by adding back the `MPMapsIndoorsLocationSource` as the only one. ***/ override func viewDidDisappear(_ animated: Bool) { MapsIndoors.register([MPMapsIndoorsLocationSource()]) } // }
33.913043
337
0.66453
79229510e9543b655860fca3ba11a32a541b0877
3,906
//: A UIKit based Playground for presenting user interface import UIKit import PlaygroundSupport public struct Constants { static let patternSize: CGFloat = 30.0 static let patternRepeatCount = 2 } enum PatternDirection: CaseIterable { case left case top case right case bottom } class PatternView: UIView { var fillColor: [CGFloat] = [1.0, 0.0, 0.0, 1.0] var direction: PatternDirection = .top let drawTriangle: CGPatternDrawPatternCallback = { _, context in let trianglePath = UIBezierPath(triangleIn: CGRect(x: 0, y: 0, width: Constants.patternSize, height: Constants.patternSize)) context.addPath(trianglePath.cgPath) context.fillPath() } init(fillColor: [CGFloat], direction: PatternDirection = .top) { self.fillColor = fillColor self.direction = direction super.init(frame: CGRect.zero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext()! UIColor.white.setFill() context.fill(rect) var callbacks = CGPatternCallbacks(version: 0, drawPattern: drawTriangle, releaseInfo: nil) let patternStepX: CGFloat = rect.width / CGFloat(Constants.patternRepeatCount) let patternStepY: CGFloat = rect.height / CGFloat(Constants.patternRepeatCount) let patternOffsetX: CGFloat = (patternStepX - Constants.patternSize) / 2.0 let patternOffsetY: CGFloat = (patternStepY - Constants.patternSize) / 2.0 var transform: CGAffineTransform switch direction { case .top: transform = .identity case .right: transform = CGAffineTransform(rotationAngle: CGFloat(0.5 * .pi)) case .bottom: transform = CGAffineTransform(rotationAngle: CGFloat(1.0 * .pi)) case .left: transform = CGAffineTransform(rotationAngle: CGFloat(1.5 * .pi)) } transform = transform.translatedBy(x: patternOffsetX, y: patternOffsetY) let pattern = CGPattern(info: nil, bounds: CGRect(x: 0, y: 0, width: 20, height: 20), matrix: transform, xStep: patternStepX, yStep: patternStepY, tiling: .constantSpacing, isColored: false, callbacks: &callbacks) let baseSpace = CGColorSpaceCreateDeviceRGB() let patternSpace = CGColorSpace(patternBaseSpace: baseSpace)! context.setFillColorSpace(patternSpace) context.setFillPattern(pattern!, colorComponents: fillColor) context.fill(rect) } } extension UIBezierPath { convenience init(triangleIn rect: CGRect) { self.init() let topOfTriangle = CGPoint(x: rect.width/2, y: 0) let bottomLeftOfTriangle = CGPoint(x: 0, y: rect.height) let bottomRightOfTriangle = CGPoint(x: rect.width, y: rect.height) self.move(to: topOfTriangle) self.addLine(to: bottomLeftOfTriangle) self.addLine(to: bottomRightOfTriangle) self.close() } } class MyViewController : UIViewController { override func loadView() { let view = UIView() view.backgroundColor = .lightGray let patternView = PatternView(fillColor: [0.0, 1.0, 0.0, 1.0], direction: .right) patternView.frame = CGRect(x: 10, y: 10, width: 200, height: 200) view.addSubview(patternView) self.view = view } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = MyViewController()
34.263158
99
0.606759
72862959a1defdb34831207d81b1e6e8e45feafd
1,579
// // SignupRequest.swift // PIALibrary // // Created by Davide De Rosa on 10/2/17. // Copyright © 2020 Private Internet Access, Inc. // // This file is part of the Private Internet Access iOS Client. // // The Private Internet Access iOS Client is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) any later version. // // The Private Internet Access iOS Client is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with the Private // Internet Access iOS Client. If not, see <https://www.gnu.org/licenses/>. // import Foundation /// A signup request. /// /// - Seealso: `AccountProvider.signup(...)` public struct SignupRequest { /// The email address to sign up with. public let email: String /// The purchased transaction. public let transaction: InAppTransaction? /// A map of objects attached to the signup request for marketing purposes. public let marketing: [String: Any]? /// :nodoc: public init(email: String, transaction: InAppTransaction? = nil, marketing: [String: Any]? = nil) { self.email = email self.transaction = transaction self.marketing = marketing } }
34.326087
103
0.702343
f71ef416bab0e100b92757bc80a71c216bac6a30
530
// // UIViewController+Extensions.swift // SwiftExtensions // // Created by Szymon Gęsicki on 19/07/2021. // import Foundation extension UIViewController { public func hideKeyboardWhenTappedOutside() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } }
22.083333
131
0.677358
48bbbe4035be36c67ba8693491b9f879109ce33d
1,761
// // AppleEventRule.swift // PPPC Utility // // MIT License // // Copyright (c) 2018 Jamf Software // // 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 Cocoa class AppleEventRule: NSObject { @objc dynamic var source: Executable! @objc dynamic var destination: Executable! @objc dynamic var valueString: String! = TCCProfileDisplayValue.allow.rawValue var value: Bool { return valueString == TCCProfileDisplayValue.allow.rawValue } init(source: Executable, destination: Executable, value: Bool) { self.source = source self.destination = destination self.valueString = value ? TCCProfileDisplayValue.allow.rawValue : TCCProfileDisplayValue.deny.rawValue } }
40.022727
111
0.741624
bb7bea2dc2dbe7d24eb76bbc73aed4c31b90230e
36,179
import Foundation import Postbox import TelegramApi import SyncCore public func tagsForStoreMessage(incoming: Bool, attributes: [MessageAttribute], media: [Media], textEntities: [MessageTextEntity]?, isPinned: Bool) -> (MessageTags, GlobalMessageTags) { var isSecret = false var isUnconsumedPersonalMention = false for attribute in attributes { if let timerAttribute = attribute as? AutoclearTimeoutMessageAttribute { if timerAttribute.timeout > 0 && timerAttribute.timeout <= 60 { isSecret = true } } else if let timerAttribute = attribute as? AutoremoveTimeoutMessageAttribute { if timerAttribute.timeout > 0 && timerAttribute.timeout <= 60 { isSecret = true } } else if let mentionAttribute = attribute as? ConsumablePersonalMentionMessageAttribute { if !mentionAttribute.consumed { isUnconsumedPersonalMention = true } } } var tags = MessageTags() var globalTags = GlobalMessageTags() if isUnconsumedPersonalMention { tags.insert(.unseenPersonalMessage) } if isPinned { tags.insert(.pinned) } for attachment in media { if let _ = attachment as? TelegramMediaImage { if !isSecret { tags.insert(.photoOrVideo) tags.insert(.photo) } } else if let file = attachment as? TelegramMediaFile { var refinedTag: MessageTags? = .file var isAnimated = false inner: for attribute in file.attributes { switch attribute { case let .Video(_, _, flags): if flags.contains(.instantRoundVideo) { refinedTag = .voiceOrInstantVideo } else { if !isSecret { refinedTag = [.photoOrVideo, .video] } else { refinedTag = nil } } case let .Audio(isVoice, _, _, _, _): if isVoice { refinedTag = .voiceOrInstantVideo } else { refinedTag = .music } break inner case .Sticker: refinedTag = nil break inner case .Animated: isAnimated = true default: break } } if isAnimated { refinedTag = .gif } if file.isAnimatedSticker { refinedTag = nil } if let refinedTag = refinedTag { tags.insert(refinedTag) } } else if let webpage = attachment as? TelegramMediaWebpage, case .Loaded = webpage.content { tags.insert(.webPage) } else if let action = attachment as? TelegramMediaAction { switch action.action { case let .phoneCall(_, discardReason, _, _): globalTags.insert(.Calls) if incoming, let discardReason = discardReason, case .missed = discardReason { globalTags.insert(.MissedCalls) } default: break } } else if let location = attachment as? TelegramMediaMap, location.liveBroadcastingTimeout != nil { tags.insert(.liveLocation) } } if let textEntities = textEntities, !textEntities.isEmpty && !tags.contains(.webPage) { for entity in textEntities { switch entity.type { case .Url, .Email: if media.isEmpty || !(media.first is TelegramMediaWebpage) { tags.insert(.webPage) } default: break } } } if !incoming { assert(true) } return (tags, globalTags) } func apiMessagePeerId(_ messsage: Api.Message) -> PeerId? { switch messsage { case let .message(message): let chatPeerId = message.peerId return chatPeerId.peerId case let .messageEmpty(_, _, peerId): if let peerId = peerId { return peerId.peerId } else { return nil } case let .messageService(_, _, _, chatPeerId, _, _, _, _): return chatPeerId.peerId } } func apiMessagePeerIds(_ message: Api.Message) -> [PeerId] { switch message { case let .message(flags, _, fromId, chatPeerId, fwdHeader, viaBotId, _, _, _, media, _, entities, _, _, _, _, _, _, _, _): let peerId: PeerId = chatPeerId.peerId var result = [peerId] let resolvedFromId = fromId?.peerId ?? chatPeerId.peerId if resolvedFromId != peerId { result.append(resolvedFromId) } if let fwdHeader = fwdHeader { switch fwdHeader { case let .messageFwdHeader(messageFwdHeader): if let fromId = messageFwdHeader.fromId { result.append(fromId.peerId) } if let savedFromPeer = messageFwdHeader.savedFromPeer { result.append(savedFromPeer.peerId) } } } if let viaBotId = viaBotId { result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: viaBotId)) } if let media = media { switch media { case let .messageMediaContact(_, _, _, _, userId): if userId != 0 { result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)) } default: break } } if let entities = entities { for entity in entities { switch entity { case let .messageEntityMentionName(_, _, userId): result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)) default: break } } } return result case .messageEmpty: return [] case let .messageService(_, _, fromId, chatPeerId, _, _, action, _): let peerId: PeerId = chatPeerId.peerId var result = [peerId] let resolvedFromId = fromId?.peerId ?? chatPeerId.peerId if resolvedFromId != peerId { result.append(resolvedFromId) } switch action { case .messageActionChannelCreate, .messageActionChatDeletePhoto, .messageActionChatEditPhoto, .messageActionChatEditTitle, .messageActionEmpty, .messageActionPinMessage, .messageActionHistoryClear, .messageActionGameScore, .messageActionPaymentSent, .messageActionPaymentSentMe, .messageActionPhoneCall, .messageActionScreenshotTaken, .messageActionCustomAction, .messageActionBotAllowed, .messageActionSecureValuesSent, .messageActionSecureValuesSentMe, .messageActionContactSignUp, .messageActionGroupCall, .messageActionSetMessagesTTL: break case let .messageActionChannelMigrateFrom(_, chatId): result.append(PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId)) case let .messageActionChatAddUser(users): for id in users { result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: id)) } case let .messageActionChatCreate(_, users): for id in users { result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: id)) } case let .messageActionChatDeleteUser(userId): result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)) case let .messageActionChatJoinedByLink(inviterId): result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: inviterId)) case let .messageActionChatMigrateTo(channelId): result.append(PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId)) case let .messageActionGeoProximityReached(fromId, toId, _): result.append(fromId.peerId) result.append(toId.peerId) case let .messageActionInviteToGroupCall(_, userIds): for id in userIds { result.append(PeerId(namespace: Namespaces.Peer.CloudUser, id: id)) } } return result } } func apiMessageAssociatedMessageIds(_ message: Api.Message) -> [MessageId]? { switch message { case let .message(_, _, _, chatPeerId, _, _, replyTo, _, _, _, _, _, _, _, _, _, _, _, _, _): if let replyTo = replyTo { let peerId: PeerId = chatPeerId.peerId switch replyTo { case let .messageReplyHeader(_, replyToMsgId, replyToPeerId, _): return [MessageId(peerId: replyToPeerId?.peerId ?? peerId, namespace: Namespaces.Message.Cloud, id: replyToMsgId)] } } case .messageEmpty: break case let .messageService(_, _, _, chatPeerId, replyHeader, _, _, _): if let replyHeader = replyHeader { switch replyHeader { case let .messageReplyHeader(_, replyToMsgId, replyToPeerId, _): return [MessageId(peerId: replyToPeerId?.peerId ?? chatPeerId.peerId, namespace: Namespaces.Message.Cloud, id: replyToMsgId)] } } } return nil } func textMediaAndExpirationTimerFromApiMedia(_ media: Api.MessageMedia?, _ peerId:PeerId) -> (Media?, Int32?) { if let media = media { switch media { case let .messageMediaPhoto(_, photo, ttlSeconds): if let photo = photo { if let mediaImage = telegramMediaImageFromApiPhoto(photo) { return (mediaImage, ttlSeconds) } } else { return (TelegramMediaExpiredContent(data: .image), nil) } case let .messageMediaContact(phoneNumber, firstName, lastName, vcard, userId): let contactPeerId: PeerId? = userId == 0 ? nil : PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) let mediaContact = TelegramMediaContact(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, peerId: contactPeerId, vCardData: vcard.isEmpty ? nil : vcard) return (mediaContact, nil) case let .messageMediaGeo(geo): let mediaMap = telegramMediaMapFromApiGeoPoint(geo, title: nil, address: nil, provider: nil, venueId: nil, venueType: nil, liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil, heading: nil) return (mediaMap, nil) case let .messageMediaVenue(geo, title, address, provider, venueId, venueType): let mediaMap = telegramMediaMapFromApiGeoPoint(geo, title: title, address: address, provider: provider, venueId: venueId, venueType: venueType, liveBroadcastingTimeout: nil, liveProximityNotificationRadius: nil, heading: nil) return (mediaMap, nil) case let .messageMediaGeoLive(_, geo, heading, period, proximityNotificationRadius): let mediaMap = telegramMediaMapFromApiGeoPoint(geo, title: nil, address: nil, provider: nil, venueId: nil, venueType: nil, liveBroadcastingTimeout: period, liveProximityNotificationRadius: proximityNotificationRadius, heading: heading) return (mediaMap, nil) case let .messageMediaDocument(_, document, ttlSeconds): if let document = document { if let mediaFile = telegramMediaFileFromApiDocument(document) { return (mediaFile, ttlSeconds) } } else { return (TelegramMediaExpiredContent(data: .file), nil) } case let .messageMediaWebPage(webpage): if let mediaWebpage = telegramMediaWebpageFromApiWebpage(webpage, url: nil) { return (mediaWebpage, nil) } case .messageMediaUnsupported: return (TelegramMediaUnsupported(), nil) case .messageMediaEmpty: break case let .messageMediaGame(game): return (TelegramMediaGame(apiGame: game), nil) case let .messageMediaInvoice(flags, title, description, photo, receiptMsgId, currency, totalAmount, startParam): var parsedFlags = TelegramMediaInvoiceFlags() if (flags & (1 << 3)) != 0 { parsedFlags.insert(.isTest) } if (flags & (1 << 1)) != 0 { parsedFlags.insert(.shippingAddressRequested) } return (TelegramMediaInvoice(title: title, description: description, photo: photo.flatMap(TelegramMediaWebFile.init), receiptMessageId: receiptMsgId.flatMap { MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: $0) }, currency: currency, totalAmount: totalAmount, startParam: startParam, flags: parsedFlags), nil) case let .messageMediaPoll(poll, results): switch poll { case let .poll(id, flags, question, answers, closePeriod, _): let publicity: TelegramMediaPollPublicity if (flags & (1 << 1)) != 0 { publicity = .public } else { publicity = .anonymous } let kind: TelegramMediaPollKind if (flags & (1 << 3)) != 0 { kind = .quiz } else { kind = .poll(multipleAnswers: (flags & (1 << 2)) != 0) } return (TelegramMediaPoll(pollId: MediaId(namespace: Namespaces.Media.CloudPoll, id: id), publicity: publicity, kind: kind, text: question, options: answers.map(TelegramMediaPollOption.init(apiOption:)), correctAnswers: nil, results: TelegramMediaPollResults(apiResults: results), isClosed: (flags & (1 << 0)) != 0, deadlineTimeout: closePeriod), nil) } case let .messageMediaDice(value, emoticon): return (TelegramMediaDice(emoji: emoticon, value: value), nil) } } return (nil, nil) } func messageTextEntitiesFromApiEntities(_ entities: [Api.MessageEntity]) -> [MessageTextEntity] { var result: [MessageTextEntity] = [] for entity in entities { switch entity { case .messageEntityUnknown, .inputMessageEntityMentionName: break case let .messageEntityMention(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Mention)) case let .messageEntityHashtag(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Hashtag)) case let .messageEntityBotCommand(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .BotCommand)) case let .messageEntityUrl(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Url)) case let .messageEntityEmail(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Email)) case let .messageEntityBold(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Bold)) case let .messageEntityItalic(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Italic)) case let .messageEntityCode(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Code)) case let .messageEntityPre(offset, length, _): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Pre)) case let .messageEntityTextUrl(offset, length, url): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .TextUrl(url: url))) case let .messageEntityMentionName(offset, length, userId): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .TextMention(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId)))) case let .messageEntityPhone(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .PhoneNumber)) case let .messageEntityCashtag(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Hashtag)) case let .messageEntityUnderline(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Underline)) case let .messageEntityStrike(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .Strikethrough)) case let .messageEntityBlockquote(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .BlockQuote)) case let .messageEntityBankCard(offset, length): result.append(MessageTextEntity(range: Int(offset) ..< Int(offset + length), type: .BankCard)) } } return result } extension StoreMessage { convenience init?(apiMessage: Api.Message, namespace: MessageId.Namespace = Namespaces.Message.Cloud) { switch apiMessage { case let .message(flags, id, fromId, chatPeerId, fwdFrom, viaBotId, replyTo, date, message, media, replyMarkup, entities, views, forwards, replies, editDate, postAuthor, groupingId, restrictionReason, ttlPeriod): let resolvedFromId = fromId?.peerId ?? chatPeerId.peerId let peerId: PeerId var authorId: PeerId? switch chatPeerId { case .peerUser: peerId = chatPeerId.peerId authorId = resolvedFromId case let .peerChat(chatId): peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) authorId = resolvedFromId case let .peerChannel(channelId): peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) authorId = resolvedFromId } var attributes: [MessageAttribute] = [] var threadId: Int64? if let replyTo = replyTo { var threadMessageId: MessageId? switch replyTo { case let .messageReplyHeader(_, replyToMsgId, replyToPeerId, replyToTopId): let replyPeerId = replyToPeerId?.peerId ?? peerId if let replyToTopId = replyToTopId { let threadIdValue = MessageId(peerId: replyPeerId, namespace: Namespaces.Message.Cloud, id: replyToTopId) threadMessageId = threadIdValue if replyPeerId == peerId { threadId = makeMessageThreadId(threadIdValue) } } else if peerId.namespace == Namespaces.Peer.CloudChannel { let threadIdValue = MessageId(peerId: replyPeerId, namespace: Namespaces.Message.Cloud, id: replyToMsgId) threadMessageId = threadIdValue threadId = makeMessageThreadId(threadIdValue) } attributes.append(ReplyMessageAttribute(messageId: MessageId(peerId: replyPeerId, namespace: Namespaces.Message.Cloud, id: replyToMsgId), threadMessageId: threadMessageId)) } } var forwardInfo: StoreMessageForwardInfo? if let fwdFrom = fwdFrom { switch fwdFrom { case let .messageFwdHeader(flags, fromId, fromName, date, channelPost, postAuthor, savedFromPeer, savedFromMsgId, psaType): var forwardInfoFlags: MessageForwardInfo.Flags = [] let isImported = (flags & (1 << 7)) != 0 if isImported { forwardInfoFlags.insert(.isImported) } var authorId: PeerId? var sourceId: PeerId? var sourceMessageId: MessageId? if let fromId = fromId { switch fromId { case .peerChannel: let peerId = fromId.peerId sourceId = peerId if let channelPost = channelPost { sourceMessageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: channelPost) } default: authorId = fromId.peerId } } if let savedFromPeer = savedFromPeer, let savedFromMsgId = savedFromMsgId { let peerId: PeerId switch savedFromPeer { case let .peerChannel(channelId): peerId = PeerId(namespace: Namespaces.Peer.CloudChannel, id: channelId) case let .peerChat(chatId): peerId = PeerId(namespace: Namespaces.Peer.CloudGroup, id: chatId) case let .peerUser(userId): peerId = PeerId(namespace: Namespaces.Peer.CloudUser, id: userId) } let messageId: MessageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: savedFromMsgId) attributes.append(SourceReferenceMessageAttribute(messageId: messageId)) } if let authorId = authorId { forwardInfo = StoreMessageForwardInfo(authorId: authorId, sourceId: sourceId, sourceMessageId: sourceMessageId, date: date, authorSignature: postAuthor, psaType: psaType, flags: forwardInfoFlags) } else if let sourceId = sourceId { forwardInfo = StoreMessageForwardInfo(authorId: sourceId, sourceId: sourceId, sourceMessageId: sourceMessageId, date: date, authorSignature: postAuthor, psaType: psaType, flags: forwardInfoFlags) } else if let postAuthor = postAuthor ?? fromName { forwardInfo = StoreMessageForwardInfo(authorId: nil, sourceId: nil, sourceMessageId: sourceMessageId, date: date, authorSignature: postAuthor, psaType: psaType, flags: forwardInfoFlags) } } } let messageText = message var medias: [Media] = [] var consumableContent: (Bool, Bool)? = nil if let media = media { let (mediaValue, expirationTimer) = textMediaAndExpirationTimerFromApiMedia(media, peerId) if let mediaValue = mediaValue { medias.append(mediaValue) if let expirationTimer = expirationTimer, expirationTimer > 0 { attributes.append(AutoclearTimeoutMessageAttribute(timeout: expirationTimer, countdownBeginTime: nil)) consumableContent = (true, false) } } } if let ttlPeriod = ttlPeriod { attributes.append(AutoremoveTimeoutMessageAttribute(timeout: ttlPeriod, countdownBeginTime: date)) } if let postAuthor = postAuthor { attributes.append(AuthorSignatureMessageAttribute(signature: postAuthor)) } for case let file as TelegramMediaFile in medias { if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup || peerId.namespace == Namespaces.Peer.CloudChannel { if file.isVoice { consumableContent = (true, (flags & (1 << 5)) == 0) break } else if file.isInstantVideo { consumableContent = (true, (flags & (1 << 5)) == 0) break } } } if let (value, consumed) = consumableContent, value { attributes.append(ConsumableContentMessageAttribute(consumed: consumed)) } if let viaBotId = viaBotId { attributes.append(InlineBotMessageAttribute(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: viaBotId), title: nil)) } if namespace != Namespaces.Message.ScheduledCloud { if let views = views { attributes.append(ViewCountMessageAttribute(count: Int(views))) } if let forwards = forwards { attributes.append(ForwardCountMessageAttribute(count: Int(forwards))) } } if let editDate = editDate { attributes.append(EditedMessageAttribute(date: editDate, isHidden: (flags & (1 << 21)) != 0)) } var entitiesAttribute: TextEntitiesMessageAttribute? if let entities = entities, !entities.isEmpty { let attribute = TextEntitiesMessageAttribute(entities: messageTextEntitiesFromApiEntities(entities)) entitiesAttribute = attribute attributes.append(attribute) } else { var noEntities = false loop: for media in medias { switch media { case _ as TelegramMediaContact, _ as TelegramMediaMap: noEntities = true break loop default: break } } if !noEntities { let attribute = TextEntitiesMessageAttribute(entities: []) entitiesAttribute = attribute attributes.append(attribute) } } if (flags & (1 << 17)) != 0 { attributes.append(ContentRequiresValidationMessageAttribute()) } /*if let reactions = reactions { attributes.append(ReactionsMessageAttribute(apiReactions: reactions)) }*/ if let replies = replies { let recentRepliersPeerIds: [PeerId]? switch replies { case let .messageReplies(_, repliesCount, _, recentRepliers, channelId, maxId, readMaxId): if let recentRepliers = recentRepliers { recentRepliersPeerIds = recentRepliers.map { $0.peerId } } else { recentRepliersPeerIds = nil } let commentsPeerId = channelId.flatMap { PeerId(namespace: Namespaces.Peer.CloudChannel, id: $0) } attributes.append(ReplyThreadMessageAttribute(count: repliesCount, latestUsers: recentRepliersPeerIds ?? [], commentsPeerId: commentsPeerId, maxMessageId: maxId, maxReadMessageId: readMaxId)) } } if let restrictionReason = restrictionReason { attributes.append(RestrictedContentMessageAttribute(rules: restrictionReason.map(RestrictionRule.init(apiReason:)))) } var storeFlags = StoreMessageFlags() if let replyMarkup = replyMarkup { let parsedReplyMarkup = ReplyMarkupMessageAttribute(apiMarkup: replyMarkup) attributes.append(parsedReplyMarkup) if !parsedReplyMarkup.flags.contains(.inline) { storeFlags.insert(.TopIndexable) } } if (flags & (1 << 1)) == 0 { storeFlags.insert(.Incoming) } if (flags & (1 << 18)) != 0 { storeFlags.insert(.WasScheduled) storeFlags.insert(.CountedAsIncoming) } if (flags & (1 << 4)) != 0 || (flags & (1 << 13)) != 0 { var notificationFlags: NotificationInfoMessageAttributeFlags = [] if (flags & (1 << 4)) != 0 { notificationFlags.insert(.personal) let notConsumed = (flags & (1 << 5)) != 0 attributes.append(ConsumablePersonalMentionMessageAttribute(consumed: !notConsumed, pending: false)) } if (flags & (1 << 13)) != 0 { notificationFlags.insert(.muted) } attributes.append(NotificationInfoMessageAttribute(flags: notificationFlags)) } let isPinned = (flags & (1 << 24)) != 0 let (tags, globalTags) = tagsForStoreMessage(incoming: storeFlags.contains(.Incoming), attributes: attributes, media: medias, textEntities: entitiesAttribute?.entities, isPinned: isPinned) storeFlags.insert(.CanBeGroupedIntoFeed) self.init(id: MessageId(peerId: peerId, namespace: namespace, id: id), globallyUniqueId: nil, groupingKey: groupingId, threadId: threadId, timestamp: date, flags: storeFlags, tags: tags, globalTags: globalTags, localTags: [], forwardInfo: forwardInfo, authorId: authorId, text: messageText, attributes: attributes, media: medias) case .messageEmpty: return nil case let .messageService(flags, id, fromId, chatPeerId, replyTo, date, action, ttlPeriod): let peerId: PeerId = chatPeerId.peerId let authorId: PeerId? = fromId?.peerId ?? chatPeerId.peerId var attributes: [MessageAttribute] = [] var threadId: Int64? if let replyTo = replyTo { var threadMessageId: MessageId? switch replyTo { case let .messageReplyHeader(_, replyToMsgId, replyToPeerId, replyToTopId): let replyPeerId = replyToPeerId?.peerId ?? peerId if let replyToTopId = replyToTopId { let threadIdValue = MessageId(peerId: replyPeerId, namespace: Namespaces.Message.Cloud, id: replyToTopId) threadMessageId = threadIdValue if replyPeerId == peerId { threadId = makeMessageThreadId(threadIdValue) } } attributes.append(ReplyMessageAttribute(messageId: MessageId(peerId: replyPeerId, namespace: Namespaces.Message.Cloud, id: replyToMsgId), threadMessageId: threadMessageId)) } } if (flags & (1 << 17)) != 0 { attributes.append(ContentRequiresValidationMessageAttribute()) } var storeFlags = StoreMessageFlags() if (flags & 2) == 0 { let _ = storeFlags.insert(.Incoming) } if (flags & (1 << 4)) != 0 || (flags & (1 << 13)) != 0 { var notificationFlags: NotificationInfoMessageAttributeFlags = [] if (flags & (1 << 4)) != 0 { notificationFlags.insert(.personal) } if (flags & (1 << 4)) != 0 { notificationFlags.insert(.personal) let notConsumed = (flags & (1 << 5)) != 0 attributes.append(ConsumablePersonalMentionMessageAttribute(consumed: !notConsumed, pending: false)) } if (flags & (1 << 13)) != 0 { notificationFlags.insert(.muted) } attributes.append(NotificationInfoMessageAttribute(flags: notificationFlags)) } var media: [Media] = [] if let action = telegramMediaActionFromApiAction(action) { media.append(action) } if let ttlPeriod = ttlPeriod { attributes.append(AutoremoveTimeoutMessageAttribute(timeout: ttlPeriod, countdownBeginTime: date)) } let (tags, globalTags) = tagsForStoreMessage(incoming: storeFlags.contains(.Incoming), attributes: attributes, media: media, textEntities: nil, isPinned: false) storeFlags.insert(.CanBeGroupedIntoFeed) if (flags & (1 << 18)) != 0 { storeFlags.insert(.WasScheduled) } self.init(id: MessageId(peerId: peerId, namespace: namespace, id: id), globallyUniqueId: nil, groupingKey: nil, threadId: threadId, timestamp: date, flags: storeFlags, tags: tags, globalTags: globalTags, localTags: [], forwardInfo: nil, authorId: authorId, text: "", attributes: attributes, media: media) } } }
52.281792
554
0.525084
b90056ca613f35856200c82ee47124542e2724c0
1,235
// // YoumouUITests.swift // YoumouUITests // // Created by 植田裕作 on 2018/09/07. // Copyright © 2018年 Yusaku Ueda. All rights reserved. // import XCTest class YoumouUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.378378
182
0.660729
29ce34b1ae27c031c096abd4d816e5af9ecdbc0b
4,358
// Copyright 2019 CEX.​IO Ltd (UK) // // 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. // // Created by Ihor Vovk on 3/25/19. import Foundation import Alamofire import CocoaLumberjack import RxSwift @objc public class PaymentService: BaseService { // MARK: - Private Data private let session: Session fileprivate let socketManager: SocketManager fileprivate let placementID: String private var baseURL: URL { return apiBaseURL.appendingPathComponent("payments") } init(session: Session, socketManager: SocketManager, placementID: String, configuration: Configuration) { self.session = session self.socketManager = socketManager self.placementID = placementID super.init(configuration: configuration) } func loadCurrencies(success: @escaping ([CurrencyConversion]) -> Void, failure: @escaping (Error) -> Void) { session.cd_requestArray(baseURL.appendingPathComponent("currencies/\(placementID)"), keyPath: "data.currencies", success: success, failure: failure) } func loadCountries(success: @escaping ([Country]) -> Void, failure: @escaping (Error) -> Void) { session.cd_requestArray(baseURL.appendingPathComponent("countries"), keyPath: "data", success: success, failure: failure) } func verifyWallet(order: Order, success: @escaping () -> Void, failure: @escaping (Error) -> Void) { #if DEVELOPMENT success() #else if let wallet = order.walletAddress, let currency = order.cryptoCurrency { session.cd_request(baseURL.appendingPathComponent("wallet/\(wallet)/\(currency)/verify"), success: { _ in success() }, failure: failure) } else { failure(ServiceError.incorrectParameters) } #endif } } extension Reactive where Base : PaymentService { func loadCurrencies() -> Observable<[CurrencyConversion]> { return Observable.create { observable in self.base.loadCurrencies(success: { currenciesConversion in observable.onNext(currenciesConversion) observable.onCompleted() }, failure: { error in observable.onError(error) }) return Disposables.create() } } func subscribeCurrencies() -> Observable<[CurrencyConversion]> { return base.socketManager.subscribe(event: "currencies") { [weak base] () -> SocketMessage in return SocketMessage(event: "currencies", messageData: base?.placementID) }.flatMap { message -> Observable<[CurrencyConversion]> in if let messageData = message.messageData as? [String: Any], let currencyConversionsJSON = messageData["currencies"] as? [[String: Any]] { let currencyConvertions = currencyConversionsJSON.compactMap { CurrencyConversion(JSON: $0) } return .just(currencyConvertions) } else { return .empty() } } } func loadCountries() -> Observable<[Country]> { return Observable.create { observable in self.base.loadCountries(success: { countries in observable.onNext(countries) observable.onCompleted() }, failure: { error in observable.onError(error) }) return Disposables.create() } } func verifyWallet(order: Order) -> Observable<Void> { return Observable.create { observable in self.base.verifyWallet(order: order, success: { observable.onNext(()) observable.onCompleted() }, failure: { error in observable.onError(error) }) return Disposables.create() } } }
37.247863
156
0.634236
039ad2f3f38ed18ad4afd7379a68a06b2898dfbe
177
// // Cell+Extensions.swift // Project // // Created by 陳駿逸 on 2020/12/22. // import UIKit extension UITableViewCell { static var reuseId: String { return "\(self)" } }
14.75
51
0.649718
c149f918b1e78a44cc9d0671d11de2372ddc5ff8
1,644
// // BusinessCell.swift // Yelp // // Created by Rageeb Mahtab on 9/24/18. // Copyright © 2018 Timothy Lee. All rights reserved. // import UIKit class BusinessCell: UITableViewCell { @IBOutlet weak var thumbnailImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var reviewsLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var foodTypeLabel: UILabel! @IBOutlet weak var ratingImageView: UIImageView! var business: Business! { didSet { nameLabel.text = business.name thumbnailImageView.setImageWith(business.imageURL!) foodTypeLabel.text = business.categories reviewsLabel.text = "\(business.reviewCount!) Reviews" addressLabel.text = business.address ratingImageView.image = business.ratingImage distanceLabel.text = business.distance } } override func awakeFromNib() { super.awakeFromNib() // Initialization code thumbnailImageView.layer.cornerRadius = 5 thumbnailImageView.clipsToBounds = true nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } override func layoutSubviews() { super.layoutSubviews() nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
30.444444
70
0.670316
39b2806c6897c3b2b0e2dbeed7a109d42dc41232
2,369
// // Hewan.swift // Kouvee // // Created by Ryan Octavius on 09/03/20. // Copyright © 2020 Ryan. All rights reserved. // import Foundation class Hewan : NSObject{ var id_hewan:String; var id_jenishewan:String; var id_pelanggan:String; var jenishewan:String; var nama_pegawai:String; var nama_hewan:String; var nama_pelanggan:String; var tgl_lahir_hewan:String; var create_at_hewan:String; var update_at_hewan:String; var delete_at_hewan:String; init(json: [String:Any]) { self.id_hewan = json["ID_HEWAN"] as? String ?? "" self.id_pelanggan = json["ID_PELANGGAN"] as? String ?? "" self.id_jenishewan = json["ID_JENISHEWAN"] as? String ?? "" self.jenishewan = json["JENISHEWAN"] as? String ?? "" self.nama_pegawai = json["NAMA_PEGAWAI"] as? String ?? "" self.nama_pelanggan = json["NAMA_PELANGGAN"] as? String ?? "" self.nama_hewan = json["NAMA_HEWAN"] as? String ?? "" self.tgl_lahir_hewan = json["TGL_LAHIR_HEWAN"] as? String ?? "" self.create_at_hewan = json["CREATE_AT_HEWAN"] as? String ?? "" self.update_at_hewan = json["UPDATE_AT_HEWAN"] as? String ?? "" self.delete_at_hewan = json["DELETE_AT_HEWAN"] as? String ?? "" } /*init(id_jenishewan: String, id_pegawai: String, id_pelanggan: String, nama_hewan: String, tgl_lahir_hewan:String, create_at_hewan: String, update_at_hewan: String, delete_at_hewan: String) { self.id_jenishewan = id_jenishewan; self.id_pegawai = id_pegawai; self.id_pelanggan = id_pelanggan; self.nama_hewan = nama_hewan; self.tgl_lahir_hewan = tgl_lahir_hewan; self.create_at_hewan = create_at_hewan; self.update_at_hewan = update_at_hewan; self.delete_at_hewan = delete_at_hewan; }*/ func printData(){ print( "id_hewan : ",self.id_hewan, "nama_hewan : ",self.nama_hewan, "nama_pegawai : ",self.nama_pegawai, "nama_pelanggan : ",self.nama_pelanggan, "tgl_lahir_hewan : ",self.tgl_lahir_hewan, "create_at_hewan : ",self.create_at_hewan, "update_at_hewan : ",self.update_at_hewan, "delete_at_hewan : ",self.delete_at_hewan ) } }
38.836066
197
0.624314
8a76cf6fd800e1d78c2d22f549e65cff5127fabb
1,348
// // ProductClient.swift // ChallengeCore // // Created by Lorenzo Di Vita on 30/9/21. // import Foundation import Combine import ComposableArchitecture import ChallengeCore private enum ProductClientConfiguration { static let liveURL = URL(string: "https://gist.githubusercontent.com/palcalde/6c19259bd32dd6aafa327fa557859c2f/raw/ba51779474a150ee4367cda4f4ffacdcca479887/Products.json")! } struct ProductClient { var fetch: () -> Effect<[ProductResponse], Never> } extension ProductClient { static let live = Self( fetch: { Effect.task { do { let (data, urlResponse) = try await URLSession.shared.data(from: ProductClientConfiguration.liveURL) let decoder = JSONDecoder() let response = try decoder.decode([String: [ProductResponse]].self, from: data) guard let products = response.values.first else { return [] } return products } catch { return [] } } } ) static let testFetchOK = Self( fetch: { Effect.task { return .mock } } ) static let testFetchKO = Self( fetch: { Effect.task { return [] } } ) }
24.071429
176
0.563056
e5139c79dcc6ab9b4611234a6aa5532ea33d2790
635
// // CJAdvertisingModel.swift // CJSwiftBasicProject // // Created by 陈吉 on 2019/8/27. // Copyright © 2019 陈吉. All rights reserved. // import UIKit class CJAdvertisingModel: NSObject { @objc var adUrl: URL? @objc var createTime: String? @objc var hospitalNames: String? @objc var ID: String? @objc var imageId: String? @objc var title: String? @objc var content: String? //为3时跳转指定原生页面 @objc var contentType: String? @objc var cover: String? //属性名字和后台返回字段不一致 override static func mj_replacedKeyFromPropertyName() -> [AnyHashable : Any]! { return ["ID": "id"] } }
21.896552
83
0.648819
d5d47815700d5a2be88d83c4cf65d131d2f10832
1,252
// // MemeMeUITests.swift // MemeMeUITests // // Created by Christopher Weaver on 7/12/16. // Copyright © 2016 Christopher Weaver. All rights reserved. // import XCTest class MemeMeUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.837838
182
0.664537
90d594092ce2185cb19c9884b90efe45a7f3f791
203
// // KeyCenter.swift // OpenVideoCall // // Created by GongYuhua on 5/16/16. // Copyright © 2016 Agora. All rights reserved. // struct KeyCenter { static let AppId: String = <#Your App Id#> }
15.615385
48
0.64532
2944ad36785cf5fd8e814204def09f2a62c461c2
920
// // AccessibilityIds.swift // ZPTesting_Example // // Created by Zsolt Pete on 2019. 10. 15.. // Copyright © 2019. CocoaPods. All rights reserved. // import Foundation struct AccessibilityIds { struct Registration { static let RegisterButton = "RegisterButton" static let EmailInputField = "EmailInputField" static let PasswordInputField = "PasswordInputField" static let ConfiemPasswordInputField = "ConfiemPasswordInputField" } struct Login { static let RegisterButton = "RegisterButton" static let LoginButton = "LoginButton" static let EmailInputField = "EmailInputField" static let PasswordInputField = "PasswordInputField" } struct List { static let ListItemTitle = "ListItemTitle" static let ListItemButton = "ListItemButton" static let ListTableView = "ListTableView" } }
27.058824
74
0.675
edc54bc5eed29741628e044da0a37c5368d26dc5
561
// // maltVO.swift // BEER // // Created by Zaw Zin Phyo on 11/17/18. // Copyright © 2018 PADC. All rights reserved. // import Foundation import SwiftyJSON class MaltVO { var name : String? = nil var amount : AmountVO? = nil static func parseToMaltVO(_ data : JSON) -> MaltVO { let malt = MaltVO() malt.name = data["name"].string // malt.amount = data["amount"].object as? AmountVO malt.amount = AmountVO.parseToAmountVO(data["amount"]) return malt } }
18.7
62
0.565062
f5fba37c7834eb42f3048b968d887244dda9dc3e
14,142
// // CameraView.swift // mrousavy // // Created by Marc Rousavy on 09.11.20. // Copyright © 2020 mrousavy. All rights reserved. // import AVFoundation import Foundation import UIKit // // TODOs for the CameraView which are currently too hard to implement either because of AVFoundation's limitations, or my brain capacity // // CameraView+RecordVideo // TODO: Better startRecording()/stopRecording() (promise + callback, wait for TurboModules/JSI) // CameraView+TakePhoto // TODO: Photo HDR private let propsThatRequireReconfiguration = ["cameraId", "enableDepthData", "enableHighQualityPhotos", "enablePortraitEffectsMatteDelivery", "preset", "photo", "video", "enableFrameProcessor"] private let propsThatRequireDeviceReconfiguration = ["fps", "hdr", "lowLightBoost", "colorSpace"] // MARK: - CameraView public final class CameraView: UIView { // pragma MARK: React Properties // pragma MARK: Exported Properties // props that require reconfiguring @objc var cameraId: NSString? @objc var enableDepthData = false @objc var enableHighQualityPhotos: NSNumber? // nullable bool @objc var enablePortraitEffectsMatteDelivery = false @objc var preset: String? // use cases @objc var photo: NSNumber? // nullable bool @objc var video: NSNumber? // nullable bool @objc var audio: NSNumber? // nullable bool @objc var enableFrameProcessor = false // props that require format reconfiguring @objc var format: NSDictionary? @objc var fps: NSNumber? @objc var frameProcessorFps: NSNumber = -1.0 // "auto" @objc var hdr: NSNumber? // nullable bool @objc var lowLightBoost: NSNumber? // nullable bool @objc var colorSpace: NSString? @objc var orientation: NSString? // other props @objc var isActive = false @objc var torch = "off" @objc var zoom: NSNumber = 1.0 // in "factor" @objc var videoStabilizationMode: NSString? // events @objc var onInitialized: RCTDirectEventBlock? @objc var onError: RCTDirectEventBlock? @objc var onFrameProcessorPerformanceSuggestionAvailable: RCTDirectEventBlock? @objc var onViewReady: RCTDirectEventBlock? // zoom @objc var enableZoomGesture = false { didSet { if enableZoomGesture { addPinchGestureRecognizer() } else { removePinchGestureRecognizer() } } } // pragma MARK: Internal Properties internal var isMounted = false internal var isReady = false // Capture Session internal let captureSession = AVCaptureSession() internal let audioCaptureSession = AVCaptureSession() // Inputs internal var videoDeviceInput: AVCaptureDeviceInput? internal var audioDeviceInput: AVCaptureDeviceInput? internal var photoOutput: AVCapturePhotoOutput? internal var videoOutput: AVCaptureVideoDataOutput? internal var audioOutput: AVCaptureAudioDataOutput? // CameraView+RecordView (+ FrameProcessorDelegate.mm) internal var isRecording = false internal var recordingSession: RecordingSession? @objc public var videoFrameProcessorCallback: FrameProcessorCallback? @objc public var audioFrameProcessorCallback: FrameProcessorCallback? internal var lastFrameProcessorCall = DispatchTime.now() // CameraView+TakePhoto internal var photoCaptureDelegates: [PhotoCaptureDelegate] = [] // CameraView+Zoom internal var pinchGestureRecognizer: UIPinchGestureRecognizer? internal var pinchScaleOffset: CGFloat = 1.0 internal let cameraQueue = CameraQueues.cameraQueue internal let videoQueue = CameraQueues.videoQueue internal let audioQueue = CameraQueues.audioQueue /// Specifies whether the frameProcessor() function is currently executing. used to drop late frames. internal var isRunningAudioFrameProcessor = false internal var isRunningVideoFrameProcessor = false internal let frameProcessorPerformanceDataCollector = FrameProcessorPerformanceDataCollector() internal var actualFrameProcessorFps = 30.0 internal var lastSuggestedFrameProcessorFps = 0.0 internal var lastFrameProcessorPerformanceEvaluation = DispatchTime.now() /// Returns whether the AVCaptureSession is currently running (reflected by isActive) var isRunning: Bool { return captureSession.isRunning } /// Convenience wrapper to get layer as its statically known type. var videoPreviewLayer: AVCaptureVideoPreviewLayer { // swiftlint:disable force_cast return layer as! AVCaptureVideoPreviewLayer } override public class var layerClass: AnyClass { return AVCaptureVideoPreviewLayer.self } // pragma MARK: Setup override public init(frame: CGRect) { super.init(frame: frame) videoPreviewLayer.session = captureSession videoPreviewLayer.videoGravity = .resizeAspectFill videoPreviewLayer.frame = layer.bounds NotificationCenter.default.addObserver(self, selector: #selector(sessionRuntimeError), name: .AVCaptureSessionRuntimeError, object: captureSession) NotificationCenter.default.addObserver(self, selector: #selector(sessionRuntimeError), name: .AVCaptureSessionRuntimeError, object: audioCaptureSession) NotificationCenter.default.addObserver(self, selector: #selector(audioSessionInterrupted), name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance) NotificationCenter.default.addObserver(self, selector: #selector(onOrientationChanged), name: UIDevice.orientationDidChangeNotification, object: nil) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) is not implemented.") } deinit { NotificationCenter.default.removeObserver(self, name: .AVCaptureSessionRuntimeError, object: captureSession) NotificationCenter.default.removeObserver(self, name: .AVCaptureSessionRuntimeError, object: audioCaptureSession) NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance) NotificationCenter.default.removeObserver(self, name: UIDevice.orientationDidChangeNotification, object: nil) } override public func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if !isMounted { isMounted = true guard let onViewReady = onViewReady else { return } onViewReady(nil) } } // pragma MARK: Props updating override public final func didSetProps(_ changedProps: [String]!) { ReactLogger.log(level: .info, message: "Updating \(changedProps.count) prop(s)...") let shouldReconfigure = changedProps.contains { propsThatRequireReconfiguration.contains($0) } let shouldReconfigureFormat = shouldReconfigure || changedProps.contains("format") let shouldReconfigureDevice = shouldReconfigureFormat || changedProps.contains { propsThatRequireDeviceReconfiguration.contains($0) } let shouldReconfigureAudioSession = changedProps.contains("audio") let willReconfigure = shouldReconfigure || shouldReconfigureFormat || shouldReconfigureDevice let shouldCheckActive = willReconfigure || changedProps.contains("isActive") || captureSession.isRunning != isActive let shouldUpdateTorch = willReconfigure || changedProps.contains("torch") || shouldCheckActive let shouldUpdateZoom = willReconfigure || changedProps.contains("zoom") || shouldCheckActive let shouldUpdateVideoStabilization = willReconfigure || changedProps.contains("videoStabilizationMode") let shouldUpdateOrientation = changedProps.contains("orientation") if shouldReconfigure || shouldReconfigureAudioSession || shouldCheckActive || shouldUpdateTorch || shouldUpdateZoom || shouldReconfigureFormat || shouldReconfigureDevice || shouldUpdateVideoStabilization || shouldUpdateOrientation { cameraQueue.async { if shouldReconfigure { self.configureCaptureSession() } if shouldReconfigureFormat { self.configureFormat() } if shouldReconfigureDevice { self.configureDevice() } if shouldUpdateVideoStabilization, let videoStabilizationMode = self.videoStabilizationMode as String? { self.captureSession.setVideoStabilizationMode(videoStabilizationMode) } if shouldUpdateZoom { let zoomClamped = max(min(CGFloat(self.zoom.doubleValue), self.maxAvailableZoom), self.minAvailableZoom) self.zoom(factor: zoomClamped, animated: false) self.pinchScaleOffset = zoomClamped } if shouldCheckActive && self.captureSession.isRunning != self.isActive { if self.isActive { ReactLogger.log(level: .info, message: "Starting Session...") self.captureSession.startRunning() ReactLogger.log(level: .info, message: "Started Session!") } else { ReactLogger.log(level: .info, message: "Stopping Session...") self.captureSession.stopRunning() ReactLogger.log(level: .info, message: "Stopped Session!") } } if shouldUpdateOrientation { self.updateOrientation() } // This is a wack workaround, but if I immediately set torch mode after `startRunning()`, the session isn't quite ready yet and will ignore torch. if shouldUpdateTorch { self.cameraQueue.asyncAfter(deadline: .now() + 0.1) { self.setTorchMode(self.torch) } } } // Audio Configuration if shouldReconfigureAudioSession { audioQueue.async { self.configureAudioSession() } } } // Frame Processor FPS Configuration if changedProps.contains("frameProcessorFps") { if frameProcessorFps.doubleValue == -1 { // "auto" actualFrameProcessorFps = 30.0 } else { actualFrameProcessorFps = frameProcessorFps.doubleValue } lastFrameProcessorPerformanceEvaluation = DispatchTime.now() frameProcessorPerformanceDataCollector.clear() } } internal final func setTorchMode(_ torchMode: String) { guard let device = videoDeviceInput?.device else { invokeOnError(.session(.cameraNotReady)) return } guard var torchMode = AVCaptureDevice.TorchMode(withString: torchMode) else { invokeOnError(.parameter(.invalid(unionName: "TorchMode", receivedValue: torch))) return } if !captureSession.isRunning { torchMode = .off } if device.torchMode == torchMode { // no need to run the whole lock/unlock bs return } if !device.hasTorch || !device.isTorchAvailable { if torchMode == .off { // ignore it, when it's off and not supported, it's off. return } else { // torch mode is .auto or .on, but no torch is available. invokeOnError(.device(.torchUnavailable)) return } } do { try device.lockForConfiguration() device.torchMode = torchMode if torchMode == .on { try device.setTorchModeOn(level: 1.0) } device.unlockForConfiguration() } catch let error as NSError { invokeOnError(.device(.configureError), cause: error) return } } @objc func onOrientationChanged() { updateOrientation() } // pragma MARK: Event Invokers internal final func invokeOnError(_ error: CameraError, cause: NSError? = nil) { ReactLogger.log(level: .error, message: "Invoking onError(): \(error.message)") guard let onError = onError else { return } var causeDictionary: [String: Any]? if let cause = cause { causeDictionary = [ "code": cause.code, "domain": cause.domain, "message": cause.description, "details": cause.userInfo, ] } onError([ "code": error.code, "message": error.message, "cause": causeDictionary ?? NSNull(), ]) } internal final func invokeOnInitialized() { ReactLogger.log(level: .info, message: "Camera initialized!") guard let onInitialized = onInitialized else { return } onInitialized([String: Any]()) } internal final func invokeOnFrameProcessorPerformanceSuggestionAvailable(currentFps: Double, suggestedFps: Double) { ReactLogger.log(level: .info, message: "Frame Processor Performance Suggestion available!") guard let onFrameProcessorPerformanceSuggestionAvailable = onFrameProcessorPerformanceSuggestionAvailable else { return } if lastSuggestedFrameProcessorFps == suggestedFps { return } if suggestedFps == currentFps { return } onFrameProcessorPerformanceSuggestionAvailable([ "type": suggestedFps > currentFps ? "can-use-higher-fps" : "should-use-lower-fps", "suggestedFrameProcessorFps": suggestedFps, ]) lastSuggestedFrameProcessorFps = suggestedFps } }
38.958678
154
0.651747
7a768914978eacc20e9322b80e9a881cf127b0b9
4,802
// // Results.swift // CorePatches // // Created by Tyler Anger on 2020-11-28. // import Foundation /// Protocol used to define any Result object. /// Used for generic implementations public protocol Results { associatedtype SuccessResult associatedtype FailureResult: Error /// Returns the success value as a throwing expression. /// /// Use this method to retrieve the value of this result if it represents a /// success, or to catch the value if it represents a failure. /// /// let integerResult: Result<Int, Error> = .success(5) /// do { /// let value = try integerResult.get() /// print("The value is \(value).") /// } catch error { /// print("Error retrieving the value: \(error)") /// } /// // Prints "The value is 5." /// /// - Returns: The success value, if the instance represents a success. /// - Throws: The failure value, if the instance represents a failure. func get() throws -> SuccessResult /// Returns a new result, mapping any success value using the given /// transformation. /// /// Use this method when you need to transform the value of a `Result` /// instance when it represents a success. The following example transforms /// the integer success value of a result into a string: /// /// func getNextInteger() -> Result<Int, Error> { /* ... */ } /// /// let integerResult = getNextInteger() /// // integerResult == .success(5) /// let stringResult = integerResult.map({ String($0) }) /// // stringResult == .success("5") /// /// - Parameter transform: A closure that takes the success value of this /// instance. /// - Returns: A `Result` instance with the result of evaluating `transform` /// as the new success value if this instance represents a success. func map<NewSuccess>(_ transform: (SuccessResult) -> NewSuccess) -> Self where SuccessResult == NewSuccess /// Returns a new result, mapping any failure value using the given /// transformation. /// /// Use this method when you need to transform the value of a `Result` /// instance when it represents a failure. The following example transforms /// the error value of a result by wrapping it in a custom `Error` type: /// /// struct DatedError: Error { /// var error: Error /// var date: Date /// /// init(_ error: Error) { /// self.error = error /// self.date = Date() /// } /// } /// /// let result: Result<Int, Error> = // ... /// // result == .failure(<error value>) /// let resultWithDatedError = result.mapError({ e in DatedError(e) }) /// // result == .failure(DatedError(error: <error value>, date: <date>)) /// /// - Parameter transform: A closure that takes the failure value of the /// instance. /// - Returns: A `Result` instance with the result of evaluating `transform` /// as the new failure value if this instance represents a failure. func mapError<NewFailure>(_ transform: (FailureResult) -> NewFailure) -> Self where FailureResult == NewFailure } public struct _SuccessResultOptionalLock { // swiftlint:disable:previous type_name internal init() { } } public protocol SuccessResultOptional { associatedtype SuccessResultWrappedValue /// A sad way to lock the implementation of this protocol to within its own library. /// This allows for others to test against Nillable but does not allow then to create /// new object types that implement it static var _successResultOptionalLock: _SuccessResultOptionalLock { get } init(_ some: SuccessResultWrappedValue) } fileprivate protocol _SuccessResultOptional { /// Indicates if this optional object is nil or not var isSuccessResultNil: Bool { get } } extension Optional: SuccessResultOptional, _SuccessResultOptional { public static var _successResultOptionalLock: _SuccessResultOptionalLock { return _SuccessResultOptionalLock() } fileprivate var isSuccessResultNil: Bool { switch self { case .some(_): return false case .none: return true } } } public extension Results where SuccessResult: SuccessResultOptional { /// Indicator if the results is nil or not. /// /// Returns an optional Bool. /// If returns nil that means this result is a failure. /// If true that means that the result value is nil otherwise returns false var isSuccessNil: Bool? { guard let v = try? self.get() else { return nil } return (v as! _SuccessResultOptional).isSuccessResultNil } }
38.416
115
0.63536
46bf66bfeadd03de76a120b4c152f7d07a64de42
604
// // RootController.swift // SwiftThread // // Created by Oniityann on 2018/10/22. // Copyright © 2018 Oniityann. All rights reserved. // import UIKit class RootController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } }
25.166667
113
0.711921
6af3212f80fd93005667cd17551c1efbf759210c
1,840
public protocol QRouteResolving: AnyObject { typealias Input = [String:Any] typealias Completion = (QRoutable?)->() typealias OnInput = (Input)->() var route: QRoute { get } var input: Input { get set } var onInput: OnInput { get set } func resolveRouteToChild(_ route: QRoute, from: QRoutable, input: Input, animated: Bool, completion: @escaping Completion) func resolveRouteToParent(from: QRoutable, input: Input, animated:Bool, completion: @escaping Completion) func resolveRouteToSelf(from: QRoutable, input: Input, animated: Bool, completion: @escaping Completion) func mergeInputDependencies(input: Input) static func mergeInputDependencies(resolver: QRouteResolving, input: Input) } public struct QRouteResolvingInputKey { public static let finalDestination = "QRouteResolvingInputKey.finalDestination" public static let pathNode = "QRouteResolvingInputKey.pathNode" } public extension QRouteResolving { func resolveRouteToSelf(from: QRoutable, input: Input, animated: Bool, completion: @escaping Completion) { mergeInputDependencies(input: input) completion(from) } func mergeInputDependencies(input: Input) { _mergeInputDependencies(self, input) } static func mergeInputDependencies(resolver: QRouteResolving, input: Input) { _mergeInputDependencies(resolver, input) } } fileprivate func _mergeInputDependencies(_ resolver: QRouteResolving, _ newInput: QRouteResolving.Input) { let dependencies = [QRouteResolvingInputKey.finalDestination, QRouteResolvingInputKey.pathNode] + resolver.route.dependencies let filteredInput = newInput.filter { key, val in dependencies.contains(key) } resolver.input = resolver.input.merging(filteredInput, uniquingKeysWith: { (_, new) in new }) }
41.818182
126
0.740217
1d7fed688bed9a0cd9635feb937fe1b7cfa6dd8f
443
// // Address.swift // Pods // // Created by QUINTON WALL on 11/29/16. // // import Foundation import SwiftyJSON public final class Address { public var street : String! public var city : String! public var state : String! //abbreviated 2 char US state codes. eg: CA for California public var stateCode : String! public var zip : String! public var longitude : Double! public var latitude : Double! }
17.72
62
0.6614
39161499f06f228fc5dbdd9160f3e0b1daae087d
1,781
// // TweetDetailTableViewCell.swift // Twitter // // Created by Anup Kher on 4/16/17. // Copyright © 2017 codepath. All rights reserved. // import UIKit class TweetDetailTableViewCell: UITableViewCell { @IBOutlet weak var retweetStackView: UIStackView! @IBOutlet weak var retweetLabel: UILabel! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var screennameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var timestampLabel: UILabel! var tweet: Tweet! { didSet { if let user = tweet.user { profileImageView.setImageWith(user.profileUrl!) nameLabel.text = user.name! screennameLabel.text = "@\(user.screenname!)" } tweetTextLabel.text = tweet.text! if let date = tweet.timestamp { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "M/dd/yy hh:mm aa" let formattedDate = dateFormatter.string(from: date) timestampLabel.text = formattedDate } if tweet.isRetweeted { retweetStackView.isHidden = false retweetLabel.text = "\(User.currentUser!.screenname!) retweeted" } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code profileImageView.layer.cornerRadius = 5.0 profileImageView.clipsToBounds = true retweetStackView.isHidden = true } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
31.803571
80
0.620999
ffb6cfe4d37a511178162b1fdf885a9a3bd3cf72
953
import UIKit //This creates an oblong (slot) shaped button class AcceptOnRoundedButton : UIButton { //----------------------------------------------------------------------------------------------------- //Constructors, Initializers, and UIView lifecycle //----------------------------------------------------------------------------------------------------- override init(frame: CGRect) { super.init(frame: frame) defaultInit() } required init(coder: NSCoder) { super.init(coder: coder)! defaultInit() } convenience init() { self.init(frame: CGRectZero) } func defaultInit() { //Make sure the rounding is shown self.layer.masksToBounds = true } override func layoutSubviews() { super.layoutSubviews() //Make it oblong (slot) shapped self.layer.cornerRadius = self.bounds.size.height / 2 } }
28.878788
107
0.465897