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
48ea91ac02f1a3f7bcde79c9ad28e046ff6706bf
3,199
// // HeaderView.swift // Emotions // // Created by Witek Bobrowski on 10/05/2020. // Copyright © 2020 Witek Bobrowski. All rights reserved. // import SwiftUI struct HeaderView: View { @State var title: String @State var showsCloseButton: Bool = true @EnvironmentObject var router: Router @EnvironmentObject var store: Store var body: some View { ZStack { HStack { if router.current == .dashboard() { profile } Spacer() if router.current == .dashboard() { knowledge } if showsCloseButton { close } } text }.fillHorizontally() } } // MARK: - Subviews extension HeaderView { private var text: some View { Text(title) .font(Style.Font.font(size: 44)) .foregroundColor(Style.Color.black) .kerning(0.5) .multilineTextAlignment(.center) } private var profile: some View { Button(action: { self.router.current = .profile }) { ZStack { if store.user.avatar == nil { placeholder } else { avatar } } .clipShape(Circle()) .shadow(color: Style.Color.lightGray, radius: 4) } } private var knowledge: some View { Button(action: { self.router.current = .knowledge }) { Image(systemName: "info.circle") .resizable() .padding(.all, 13) .foregroundColor(Style.Color.black) .frame(width: 50, height: 50, alignment: .center) .background(Style.Color.lightGray) .clipShape(Circle()) .shadow(color: Style.Color.lightGray, radius: 4) } } private var close: some View { Button(action: { self.router.current = .dashboard() }) { Image(systemName: "xmark") .resizable() .padding(.all, 15) .foregroundColor(Style.Color.black) .frame(width: 50, height: 50, alignment: .center) .background(Style.Color.lightGray) .clipShape(Circle()) .shadow(color: Style.Color.lightGray, radius: 4) } } private var placeholder: some View { Image(systemName: "person.fill") .resizable() .foregroundColor(Style.Color.black) .padding(.all, 15) .background(Style.Color.lightGray) .frame(width: 50, height: 50, alignment: .center) } private var avatar: some View { store.user.avatar.map { avatar in Text(avatar) .font(.system(size: 30)) .frame(width: 50, height: 50, alignment: .center) .background(Style.Color.lightGray) } } } struct HeaderView_Previews: PreviewProvider { static var previews: some View { let store: Store = .mock return HeaderView(title: "Hello, \(store.user.name)!", showsCloseButton: true) .environmentObject(Router(initial: .dashboard())) .environmentObject(store) .padding(.all, 24) } }
31.362745
86
0.539544
080b05937e817137f1eeb7111addf6fe1e5d0fa8
1,319
// // Runtime.swift // iSimulator // // Created by 靳朋 on 2017/8/23. // Copyright © 2017年 niels.jin. All rights reserved. // import Foundation import ObjectMapper enum Availability: String { case available = "(available)" case unavailable = "(unavailable, runtime profile not found)" } class Runtime: Mappable { enum OSType: String { case iOS, tvOS, watchOS, None } var buildversion = "" var availability = Availability.unavailable var name = "" var identifier = "" var version = "" var devices: [Device] = [] var devicetypes: [DeviceType] = [] var osType: OSType{ if name.contains("iOS"){ return .iOS }else if name.contains("tvOS"){ return .tvOS }else if name.contains("watchOS"){ return .watchOS }else{ return .None } } required init?(map: Map) { } func mapping(map: Map) { buildversion <- map["buildversion"] availability <- (map["availability"], EnumTransform()) name <- map["name"] identifier <- map["identifier"] version <- map["version"] } var dataReportDic: [String: String] { return ["n": name, "b": buildversion, "v": version, "id": identifier] } }
22.741379
77
0.559515
6ab84da691b0180bb84d8e676fc0ee597f7ca1db
6,538
// // DiskManager.swift // Vinyl Piano // // Created by Jeff Cooper on 5/5/20. // Copyright © 2020 Vinyl Piano. All rights reserved. // import Disk import Foundation class DiskManager { var directory: Disk.Directory { return .sharedContainer(appGroupName: FileConstants.sharedContainer) } func exists(relativePath: String) -> Bool { return Disk.exists(relativePath, in: directory) } func saveTemporaryPreset(preset: InstrumentPreset) -> URL? { let presetLocation = "temp/\(preset.filename)" try? Disk.save(preset, to: .caches, as: presetLocation) guard let url = try? Disk.url(for: presetLocation, in: .caches) else { deboog("Save temporary preset failed - no file found at \(presetLocation)") return nil } return url } func saveTemporaryBank(bank: PresetBank) -> URL? { let bankLocation = "temp/\(bank.filename)" try? Disk.save(bank, to: .caches, as: bankLocation) guard let url = try? Disk.url(for: bankLocation, in: .caches) else { deboog("Save temporary bank failed - no file found at \(bankLocation)") return nil } return url } @discardableResult func removeFile(url: URL) -> Bool { do { try Disk.remove(url) } catch { deboog("error removing \(url.path): \(error)") return false } return true } func removeFile(path: String) { do { try Disk.remove(path, from: directory) } catch { deboog("error removing \(path): \(error)") } } @discardableResult func save(presetBank: PresetBank) -> Bool { do { try Disk.save(presetBank, to: directory, as: presetBank.pathOnDisk) } catch { deboog("error saving preset \(presetBank.name): \(error)") return false } return true } func get(presetBankName: String) -> PresetBank? { do { let presetBank = try Disk.retrieve(PresetBank.pathFor(name: presetBankName), from: directory, as: PresetBank.self) return presetBank } catch { deboog("error retrieving preset \(presetBankName): \(error)") return nil } } func get(presetBankPath: String) -> PresetBank? { do { let presetBank = try Disk.retrieve(presetBankPath, from: directory, as: PresetBank.self) return presetBank } catch { deboog("error retrieving preset path \(presetBankPath): \(error)") return nil } } func getFilesNames(inDirectory subdir: String) -> [String]? { guard let path = FileConstants.appGroupPath else { return nil } let subPath = path + "/" + subdir return FileManager.default.subpaths(atPath: subPath) } func getAllPresetBanks() -> [PresetBank]? { guard let presetBankFiles = getFilesNames(inDirectory: PresetConstants.presetBanksFolder) else { return nil } var banks = [PresetBank]() for file in presetBankFiles { if let preset = try? Disk.retrieve(PresetConstants.presetBanksFolder + "/" + file, from: directory, as: PresetBank.self) { banks.append(preset) } } return banks.count > 0 ? banks : nil } /* the following much simpler function fails with "The file “PresetLists” couldn’t be opened because you don’t have permission to view it." func getAllPresetBanks() -> [PresetBank]? { do { let presetBanks = try Disk.retrieve(AudioConstants.presetListsFolder, from: directory, as: [PresetBank].self) return presetBanks } catch { deboog("error retrieving presetBanks from \(AudioConstants.presetListsFolder): \(error)") return nil } } */ func getAllPresets() -> [InstrumentPreset]? { guard let presetFileNames = getFilesNames(inDirectory: PresetConstants.presetsFolder) else { return nil } var presets = [InstrumentPreset]() for file in presetFileNames { if let preset = try? Disk.retrieve(PresetConstants.presetsFolder + "/" + file, from: directory, as: InstrumentPreset.self) { presets.append(preset) } } return presets.count > 0 ? presets : nil } func save(preset: InstrumentPreset) { let path = (PresetConstants.presetsFolder + "/" + preset.name + "." + PresetConstants.presetsSuffix).trimmingCharacters(in: .whitespacesAndNewlines) do { var presetToSave = preset presetToSave.pathOnDisk = path try Disk.save(presetToSave, to: directory, as: path) } catch { deboog("error saving preset \(preset.name): \(error)") } } func remove(preset: InstrumentPreset) { remove(presetName: preset.name) } func remove(presetName: String) { let path = (PresetConstants.presetsFolder + "/" + presetName + "." + PresetConstants.presetsSuffix).trimmingCharacters(in: .whitespacesAndNewlines) do { try Disk.remove(path, from: directory) } catch { deboog("error removing preset \(presetName): \(error)") } } func deleteAllPresets() { deleteFile(path: PresetConstants.presetsFolder) } func deleteAllPresetBanks() { deleteFile(path: PresetConstants.presetBanksFolder) } @discardableResult func deleteURL(url: URL) -> Bool { do { try Disk.remove(url) } catch { deboog("error removing all presets at \(url.path) : \(error)") return false } return true } @discardableResult func deleteFile(path: String) -> Bool { let fileManager = FileManager.default if let directory = fileManager.containerURL(forSecurityApplicationGroupIdentifier: FileConstants.sharedContainer) { do { try fileManager.removeItem(atPath: directory.path + "/" + path) return true } catch { deboog("error removing all presets at \(path) : \(error)") return false } } return false } }
34.592593
155
0.575558
56f18e49af647474857ccfb979095dca3c1abe61
1,666
// // ReduxProtocols.swift // FitnessTrackerReSwift // // Created by Swain Molster on 7/30/18. // Copyright © 2018 Swain Molster. All rights reserved. // import RxSwift public protocol Action { } public typealias Reducer<State> = (Action, State) -> State public typealias GetState<State> = () -> State public typealias Middleware<State> = (Action, GetState<State>) -> Void public class Store<State> { private let queue: DispatchQueue private let _publishSubject: PublishSubject<State> private var _state: State private let reducer: Reducer<State> private let middlewares: [Middleware<State>] public var observable: Observable<State> { return _publishSubject.asObservable() } public var state: State { return self._state } public init( initialValue: State, queueLabel: String = "Store Queue", reducer: @escaping Reducer<State>, middlewares: [Middleware<State>] ) { self.queue = DispatchQueue(label: queueLabel) self._publishSubject = PublishSubject<State>() self._state = initialValue self.reducer = reducer self.middlewares = middlewares } /// Dispatches an `action` to the store. public func dispatch(_ action: Action) { queue.async { [unowned self] in let getState: GetState<State> = { [unowned self] in return self.reducer(action, self._state) } self.middlewares.forEach { $0(action, getState) } self._state = self.reducer(action, self._state) self._publishSubject.onNext(self._state) } } }
29.22807
86
0.636855
9ccd4294c90d94af5f6efa905afee6e72c3c3203
5,502
import UIKit extension WMFAppViewController { // MARK: - Language Variant Migration Alerts @objc internal func presentLanguageVariantAlerts(completion: @escaping () -> Void) { guard shouldPresentLanguageVariantAlerts else { completion() return } let savedLibraryVersion = UserDefaults.standard.integer(forKey: WMFLanguageVariantAlertsLibraryVersion) guard savedLibraryVersion < MWKDataStore.currentLibraryVersion else { completion() return } let languageCodesNeedingAlerts = self.dataStore.languageCodesNeedingVariantAlerts(since: savedLibraryVersion) guard let firstCode = languageCodesNeedingAlerts.first else { completion() return } self.presentVariantAlert(for: firstCode, remainingCodes: Array(languageCodesNeedingAlerts.dropFirst()), completion: completion) UserDefaults.standard.set(MWKDataStore.currentLibraryVersion, forKey: WMFLanguageVariantAlertsLibraryVersion) } private func presentVariantAlert(for languageCode: String, remainingCodes: [String], completion: @escaping () -> Void) { let primaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler let secondaryButtonTapHandler: ScrollableEducationPanelButtonTapHandler? // If there are remaining codes if let nextCode = remainingCodes.first { // If more to show, primary button shows next variant alert primaryButtonTapHandler = { _ in self.dismiss(animated: true) { self.presentVariantAlert(for: nextCode, remainingCodes: Array(remainingCodes.dropFirst()), completion: completion) } } // And no secondary button secondaryButtonTapHandler = nil } else { // If no more to show, primary button navigates to languge settings primaryButtonTapHandler = { _ in self.displayPreferredLanguageSettings(completion: completion) } // And secondary button dismisses secondaryButtonTapHandler = { _ in self.dismiss(animated: true, completion: completion) } } let alert = LanguageVariantEducationalPanelViewController(primaryButtonTapHandler: primaryButtonTapHandler, secondaryButtonTapHandler: secondaryButtonTapHandler, dismissHandler: nil, theme: self.theme, languageCode: languageCode) self.present(alert, animated: true, completion: nil) } // Don't present over modals or navigation stacks // The user is deep linking in these states and we don't want to interrupt them private var shouldPresentLanguageVariantAlerts: Bool { guard presentedViewController == nil, let navigationController = navigationController, navigationController.viewControllers.count == 1 && navigationController.viewControllers[0] is WMFAppViewController else { return false } return true } private func displayPreferredLanguageSettings(completion: @escaping () -> Void) { self.dismissPresentedViewControllers() let languagesVC = WMFPreferredLanguagesViewController.preferredLanguagesViewController() languagesVC.showExploreFeedCustomizationSettings = true languagesVC.userDismissalCompletionBlock = completion languagesVC.apply(self.theme) let navVC = WMFThemeableNavigationController(rootViewController: languagesVC, theme: theme) present(navVC, animated: true, completion: nil) } } extension WMFAppViewController: SettingsPresentationDelegate { public func userDidTapSettings(from viewController: UIViewController?) { if viewController is ExploreViewController { logTappedSettingsFromExplore() } showSettings(animated: true) } } extension WMFAppViewController: NotificationsCenterPresentationDelegate { /// Perform conditional presentation logic depending on origin `UIViewController` public func userDidTapNotificationsCenter(from viewController: UIViewController? = nil) { let viewModel = NotificationsCenterViewModel(remoteNotificationsController: dataStore.remoteNotificationsController, languageLinkController: self.dataStore.languageLinkController) let notificationsCenterViewController = NotificationsCenterViewController(theme: theme, viewModel: viewModel) navigationController?.pushViewController(notificationsCenterViewController, animated: true) } } extension WMFAppViewController { @objc func userDidTapPushNotification() { //TODO: This is a very basic push to Notification Center. //This will need refinement when https://phabricator.wikimedia.org/T287628 is tackled dismissPresentedViewControllers() navigationController?.popToRootViewController(animated: false) let viewModel = NotificationsCenterViewModel(remoteNotificationsController: dataStore.remoteNotificationsController, languageLinkController: dataStore.languageLinkController) let notificationsCenterViewController = NotificationsCenterViewController(theme: theme, viewModel: viewModel) navigationController?.pushViewController(notificationsCenterViewController, animated: true) } }
45.471074
237
0.70647
bbd596e65105d0d274fd63c8ba97d50e03df8a70
759
// // SafariWebExtensionHandler.swift // DTMG Extension // // Created by Bin Hua on 2021/11/13. // import SafariServices import os.log let SFExtensionMessageKey = "message" class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling { func beginRequest(with context: NSExtensionContext) { let item = context.inputItems[0] as! NSExtensionItem let message = item.userInfo?[SFExtensionMessageKey] os_log(.default, "Received message from browser.runtime.sendNativeMessage: %@", message as! CVarArg) let response = NSExtensionItem() response.userInfo = [ SFExtensionMessageKey: [ "Response to": message ] ] context.completeRequest(returningItems: [response], completionHandler: nil) } }
28.111111
108
0.720685
14a1ee2ef4b26506ed8b3b36f5f9c4d921cda7c6
8,470
import Foundation /// Neural network open class NeuralNetwork { /// Visualisation view of Neural Network. If set, will be informaed about init params of Neural Network, and about adding layers. open var visualizationView: NeuralNetworkVisualisationView? /// Layers array. Settable only via `appendLayer(n: Int)` method open var layers: [Layer] = [] /// Input size open var sizeIn: Int = 0 /// Output size open var sizeOut: Int = 0 /// Default initializer /// /// - parameter sizeIn: Input size /// - parameter sizeOut: Output size /// /// - returns: `NeuralNetwork` instance public init(sizeIn: Int, sizeOut: Int, visualizationView: NeuralNetworkVisualisationView?) { // Store sizes self.sizeIn = sizeIn self.sizeOut = sizeOut // Append first layer, initially empty - start layers.append(Layer(neuron: Neuron(rows: 0, columns: sizeIn))) // Append last layer - layers.append(Layer(neuron: Neuron(rows: sizeIn, columns: sizeOut))) // self.visualizationView = visualizationView visualizationView?.inputLayerNeuronNumber = sizeIn visualizationView?.outputLayerNeuronNumber = sizeOut } /// Appends new layer to `layers` variable. New layer is inserted to pre-last position in `layers` array. /// Sets layer's neuronss to appropriate sizes. /// /// - parameter n: New `Layer` instance open func appendLayer(n: Int) { var newLayers: [Layer] = [] var last = 0 // Rewrite all layers except last one for i in 0..<(layers.count - 1) { newLayers.append(layers[i]) last = layers[i].neuron.columns } // Insert new layer newLayers.append(Layer(neuron: Neuron(rows: last, columns: n))) newLayers.append(Layer(neuron: Neuron(rows: n, columns: sizeOut))) // Store new layers array layers = newLayers // visualizationView?.addHiddenLayer(layer: NeuralNetworkLayerView(numberOfNeurons: n)) } /// Performes propagation on training data. /// /// - parameter trainingData: Trainig data /// /// - returns: Result vector of propagation open func propagate(trainingData: TrainingData) -> [Double] { // Input vector from training data var vector: [Double] = trainingData.vectorIn // Iterate through layers for i in 0..<layers.count { // Ommit first layer guard i != 0 else { continue } // Multiply let matrixA = [vector] let matrixB = layers[i].neuron.matrix // Multiply vector (as one-dimentional matrix) with i-th layer let multiplicationResult = multiplyMatrixes(a: matrixA, b: matrixB) // Slice first row in result matrix vector = multiplicationResult[0] // Perform activate function vector = vector.map { ActivationFunction.sigmoidal(β: -1, x: $0).perform() } layers[i].values = vector } return vector } /// Calculates error. /// /// - parameter trainingData: Training data /// /// - returns: Error vector open func calculateError(trainingData: TrainingData) -> [Double] { // Output vector from training data let y = trainingData.vectorOut // Propagation result on traning data let ysim = propagate(trainingData: trainingData) // Vectors difference return zip(y, ysim).map { $0 - $1 } } /// Performes back propagation on training data. /// /// - parameter trainingData: Training data open func backPropagate(trainingData: TrainingData) { // Calculate error var error = calculateError(trainingData: trainingData) let layersCount = layers.count - 1 // Iterates through layers, except last one for i in 0..<layersCount { // Performing activation function on layers values matrix let activatedValuesMatix = layers[layersCount - i].values.map { ActivationFunction.sigmoidalDeriv(β: -1, x: $0).perform() } // Vectors multiplication let delta = zip(error, activatedValuesMatix).map { $0 * $1 } let transposedNeuronMatrix = transpose(input: layers[layersCount - i].neuron.matrix) error = multiplyMatrixes(a: [delta], b: transposedNeuronMatrix)[0] let matrix1 = layers[layersCount - i].neuron.matrix let matrix2 = multiplyMatrixes2(a: [layers[layersCount - i - 1].values], b: transpose(input: [delta])) layers[layersCount - i].neuron.matrix = matrixDifferences(a: matrix1, b: transpose(input: matrix2)) } } } // MARK: - Initializers with NeuralNetworkInitParameters extension NeuralNetwork { /// Convenience initializer /// Allows to initialize `NeuralNetwork` instance with `NeuralNetworkInitParameters` object. /// /// - Parameter initParameters: All init parameters in single object convenience public init(with initParameters: NeuralNetworkInitParameters) { // Call more general conveniance initializer self.init(with: initParameters, visualizationView: nil) } /// Convenience initializer /// Allows to initialize `NeuralNetwork` instance with `NeuralNetworkInitParameters` object and `NeuralNetworkVisualisationView`. /// /// - Parameters: /// - initParameters: All init parameters in single object /// - visualizationView: Visualisation view convenience public init(with initParameters: NeuralNetworkInitParameters, visualizationView: NeuralNetworkVisualisationView?) { // Call designed initializer self.init(sizeIn: initParameters.inputSize, sizeOut: initParameters.outputSize, visualizationView: visualizationView) // Add hidden layers with given layer's sizes for layerSize in initParameters.hiddenLayersSizes { self.appendLayer(n: layerSize) } } } // MARK: - CustomStringConvertible extension NeuralNetwork: CustomStringConvertible { /// Class instance description format open var description: String { return "\(layers)" } } /// Structure contains `NuralNetwork` init parameters, all required to properly create `NeuralNetwork` instance public struct NeuralNetworkInitParameters { /// Input layer vector size public let inputSize: Int /// Output layer vector size public let outputSize: Int /// Hidden layers sizes public let hiddenLayersSizes: [Int] /// Main initializer /// /// - Parameters: /// - inputSize: Number of input neurons /// - outputSize: Number of output neurons /// - hiddenLayersSizes: Array with numbers of hidden layers neurons public init(inputSize: Int, outputSize: Int, hiddenLayersSizes: [Int]) { self.inputSize = inputSize self.outputSize = outputSize self.hiddenLayersSizes = hiddenLayersSizes } } // MARK: - Training/reseting extension NeuralNetwork { /// Reset already trained Neural Network. /// Zroes layers values and randomizes matrixes (matrixes of weights). open func reset() { for index in 0..<layers.count { layers[index].values = [Double](repeating: Double(), count: layers[index].neuron.columns) layers[index].neuron.randomizeMatrix() } } /// Trains `Neural Network` with normalized data set. Data set has to be array of `TrainingData` objects. Performs back propagation on each `TrainingData` object as manyy times as in `times` parameter. /// /// - Parameters: /// - normalizedDataSet: Normalized training data /// - times: Number of training times. Defaultly 500. If big data set, set this falue to 0. open func train(with normalizedDataSet: [TrainingData], times: Int = 500) { // Train `times` times for smaller data sets for _ in 0..<times { // perform back propagation for each `TrainingData` instance _ = normalizedDataSet.map { backPropagate(trainingData: $0) } } } }
34.855967
205
0.626564
e041a2339e3a57e6757d80203a638cacd975024b
412
// // FontAwesomeExampleCell.swift // Example // // Created by vsccw on 2019/3/26. // Copyright © 2019 qiuncheng.com. All rights reserved. // import UIKit import FontAwesomeKit_Swift class FontAwesomeExampleCell: UICollectionViewCell { @IBOutlet weak var titleLabel: UILabel! var type: FontAwesomeType = .unknown { didSet { titleLabel.fa.text = type } } }
18.727273
56
0.65534
d713702ad098a9e8c936991e4f1927db16053dc2
2,361
// // main.swift // Generics // // Created by Leo_Lei on 5/10/17. // Copyright © 2017 LibertyLeo. All rights reserved. // import Foundation // Write a name inside angle brackets to make a generic function or type. func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] { var result = [Item]() for _ in 0..<numberOfTimes { result.append(item) } return result } let circleArray = makeArray(repeating: "knock", numberOfTimes: 4) print(circleArray) /* You can make generic forms of functions and methods, as well as classes, enumerations, and structures. Reimplement the Swift standard library's optional type. */ enum OptionalValue<Wrapped> { case none case some(Wrapped) } var possibleInteger: OptionalValue<Int> = .none possibleInteger = .some(100) //possibleInteger = .some(10.2) // Uncomment to see the error /* Use where right before the body to specify a list of requirements--for example, to require a type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass. */ func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element { for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { return true } } } return false } let commonElements: Bool = anyCommonElements([1, 2, 3], [3]) print(commonElements) /* Modify the anyCommonElements(_:_:) function to make a function that returns an array of the elements that any two sequences have in common. (Exp) */ func anyCommonElementsInArray<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> [T.Iterator.Element] where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element { var commonArray: [T.Iterator.Element] = [] commonArray = [] for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { commonArray.append(lhsItem) } } } return commonArray } let commonElementArrays = anyCommonElementsInArray([1, 2, 3], [3]) print(commonElementArrays) // Writing <T: Equatable> is the same as writing <T> ... where T: Equatable.
29.5125
99
0.648878
c1c9a43912b63bd0b19eb493c16c96a46949d9ca
1,355
// // AutoLayoutViewByPrefixingAppIcon.swift // ElCanari // // Created by Pierre Molinaro on 06/12/2021. // //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— import Cocoa //—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— final class AutoLayoutViewByPrefixingAppIcon : AutoLayoutHorizontalStackView { //···················································································································· init (prefixedView inView : NSView) { super.init () let vStack = AutoLayoutVerticalStackView ().set (margins: 20) vStack.appendFlexibleSpace () vStack.appendView (AutoLayoutApplicationImage ()) vStack.appendFlexibleSpace () self.appendView (vStack) self.appendView (inView) } //···················································································································· required init? (coder inCoder : NSCoder) { fatalError ("init(coder:) has not been implemented") } //···················································································································· } //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
35.657895
120
0.330627
8fabae35fc1b635ca9a4143e525d84e6448a7872
1,885
// // Copyright (c) 2018 Commercetools. All rights reserved. // import Foundation import ReactiveSwift import Result import Commercetools import CoreLocation import DateToolsSwift class ReservationDetailsViewModel: BaseViewModel { // Outputs let productName: MutableProperty<String?> let productImageUrl: MutableProperty<String> let created: MutableProperty<String?> let total: MutableProperty<String?> let storeName: MutableProperty<String?> let storeAddress: MutableProperty<String?> let storeOpeningHours: MutableProperty<String?> let storeLocation: MutableProperty<CLLocation?> @available(iOS 12.0, *) var reservationIntent: ReserveProductIntent { return reservation.reserveIntent } private let reservation: Order // MARK: - Lifecycle init(reservation: Order) { self.reservation = reservation let reservedProduct = reservation.lineItems.first productName = MutableProperty(reservedProduct?.name.localizedString) productImageUrl = MutableProperty(reservedProduct?.variant.images?.first?.url ?? "") created = MutableProperty(reservation.createdAt.timeAgoSinceNow) total = MutableProperty(String(format: NSLocalizedString("Total %@", comment: "Order Total"), reservation.taxedPrice?.totalGross.description ?? reservation.totalPrice.description)) storeName = MutableProperty(reservedProduct?.distributionChannel?.obj?.name?.localizedString) storeAddress = MutableProperty("\(reservedProduct?.distributionChannel?.obj?.streetAndNumberInfo ?? "")\n\(reservedProduct?.distributionChannel?.obj?.zipAndCityInfo ?? "")") storeOpeningHours = MutableProperty(reservedProduct?.distributionChannel?.obj?.openingTimes) storeLocation = MutableProperty(reservedProduct?.distributionChannel?.obj?.location) super.init() } }
40.106383
188
0.744828
b9e88674e634f97e5a8da1478cbb7c5661471ce6
171
import SwiftUI struct SwiftPlantUMLAppApp: App { @available(OSX 11.0, *) var body: some Scene { WindowGroup { ContentView() } } }
15.545455
33
0.549708
33995bad2746ea30ff4ecaf85faa3f938b79589f
1,386
// // ScrollToBottomViewController.swift // APExtensions // // Created by Anton Plebanovich on 11/14/17. // Copyright © 2019 Anton Plebanovich All rights reserved. // import UIKit import APExtensions final class ScrollToBottomViewController: UIViewController, InstantiatableFromStoryboard { // ******************************* MARK: - @IBOutlets @IBOutlet private weak var scrollView: UIScrollView! // ******************************* MARK: - Private Properties // ******************************* MARK: - Initialization and Setup private func setup() { } // ******************************* MARK: - Configuration private func configure() { tabBarController?.navigationItem.rightBarButtonItems = navigationItem.rightBarButtonItems } // ******************************* MARK: - UIViewController Overrides override func viewDidLoad() { setup() super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configure() } // ******************************* MARK: - Actions @IBAction private func onScrollToBottomTap(_ sender: Any) { scrollView.scrollToBottom(animated: true) } // ******************************* MARK: - Notifications }
25.2
97
0.529582
fb4f18387838617aff054f3ec0ea9e3b193fd307
483
//1.8 Boys and Girls /* A class consists of numberOfBoys boys and numberOfGirls girls. Print the percentage of boys in the class followed by the percentage of girls in the class. The percentage should be printed rounded down to the nearest integer. For example 33.333333333333 will be printed as 33. */ var numberOfBoys = 25 var numberOfGirls = 75 var total = numberOfBoys + numberOfGirls var percentofBoy:Double = (Double(numberOfBoys) / Double(total)) * 100 print(percentofBoy)
32.2
120
0.782609
e4d31a65d5964a24efb4e175df14204a1c2982cb
1,307
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest @testable import AnalyticsExample class AnalyticsExampleTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. measure { // Put the code you want to measure the time of here. } } }
33.512821
107
0.72303
28a2b1ac1180208e31dca6fcc38f1acbd3c1714e
1,157
// // KZOrderModel.swift // kangze // 订单model // Created by gouyz on 2018/9/8. // Copyright © 2018年 gyz. All rights reserved. // import UIKit @objcMembers class KZOrderModel: LHSBaseModel { /// 订单id var order_id : String? /// 订单编号 var order_sn : String? /// 购买者id var buyer_id : String? /// 购买者姓名 var buyer_name : String? /// 订单时间 var add_time : String? /// 订单总价格 var goods_amount : String? /// 订单状态:0(已取消)10(默认):未付款;20:已付款;30:已发货;40:已收货; var order_state : String? = "" /// 订单状态字符串 var state_desc : String? /// 付款方式 var payment_name : String? /// 支付订单编号 var pay_sn : String? /// 商品列表 var goodList: [KZGoodsModel]? override func setValue(_ value: Any?, forKey key: String) { if key == "extend_order_goods"{ goodList = [KZGoodsModel]() guard let datas = value as? [[String : Any]] else { return } for dict in datas { let model = KZGoodsModel(dict: dict) goodList?.append(model) } }else { super.setValue(value, forKey: key) } } }
22.686275
72
0.55229
e066ec191c815e3ba6de810edc1e491da73378a8
1,404
// // ToArray.swift // Rx // // Created by Junior B. on 20/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ToArraySink<SourceType, O: ObserverType> : Sink<O>, ObserverType where O.E == [SourceType] { typealias Parent = ToArray<SourceType> let _parent: Parent var _list = Array<SourceType>() init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceType>) { switch event { case .next(let value): self._list.append(value) case .error(let e): forwardOn(.error(e)) self.dispose() case .completed: forwardOn(.next(_list)) forwardOn(.completed) self.dispose() } } } class ToArray<SourceType> : Producer<[SourceType]> { let _source: Observable<SourceType> init(source: Observable<SourceType>) { _source = source } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [SourceType] { let sink = ToArraySink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
27.529412
149
0.608974
ef24fec4f885470f5bc769e269bf1aa76c0e7297
2,625
// // MemeTableViewController.swift // MemeMe // // Created by Alessandro Bellotti on 08/08/17. // Copyright © 2017 Alessandro Bellotti. All rights reserved. // import UIKit class MemeTableViewController: UITableViewController { // MARK: IBOutlet @IBOutlet var myTableView: UITableView! // MARK: Variable var memes: [Meme]! var selectedItemList = UIImage() // MARK: Constant let appDelegate = UIApplication.shared.delegate as! AppDelegate override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { myTableView.reloadData() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return appDelegate.memes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MemeViewCell", for: indexPath) as! MemeTableViewCell // Configure the cell let meme = appDelegate.memes[indexPath.item] cell.listCellImageView.image = meme.memedImage cell.memeTopText.text! = meme.topString cell.memeBottomText.text! = meme.bottomString return cell } // MARK: - Table view delete override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCell.EditingStyle.delete) { // handle delete (by removing the data from your array and updating the tableview) appDelegate.memes.remove(at: indexPath.item) myTableView.reloadData() } } // MARK: - Navigation // Prepare and open MemeDetailViewController when tap on item list override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedItemList = appDelegate.memes[indexPath.item].memedImage self.performSegue(withIdentifier: "segueToMemeDetailFromList", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier! { case "segueToMemeDetailFromList": (segue.destination as! MemeDetailViewController).imageMeme = selectedItemList default: break } } }
31.626506
137
0.665143
c148ea40ea668565fef887467ec30f57cbef98e3
532
// // SecondViewController.swift // CollectionPager // // Created by Alexey Glushkov on 19.02.17. // Copyright © 2017 Alexey Glushkov. All rights reserved. // import UIKit class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.461538
80
0.684211
e84590495c510c343e7c9db045fa82b2a896b3c4
427
// // Violation.swift // StringsLintFramework // // Created by Alessandro "Sandro" Calzavara on 11/09/2018. // import Foundation public struct Violation { public let ruleDescription: RuleDescription public let severity: ViolationSeverity public let location: Location public let reason: String public var description: String { return XcodeReporter.generateForSingleViolation(self) } }
21.35
61
0.723653
f757a0e8e9ad1df768c4a29f85b047692133925e
2,279
// // RxSwiftSketchbookViewController.swift // SwiftStudy // // Created by YooHG on 9/9/20. // Copyright © 2020 Jell PD. All rights reserved. // import RxSwift import RxCocoa class RxSwiftSketchbookViewController: UIViewController { @IBOutlet var countLabel: UILabel! let vm = RxSwiftSketchbookViewModel() // let publish: PublishSubject<Int> = PublishSubject() let behavior: BehaviorSubject<Int> = BehaviorSubject(value: 0) let json: BehaviorSubject<[RxTodo]> = BehaviorSubject<[RxTodo]>(value: []) let bag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let z = 1 let a = Observable.from(optional: z) a.subscribe(onNext: { print("onNext: \($0)") }, onError: {error in print("onError: \(error)") }, onCompleted: { print("onCompleted") }, onDisposed: { print("onDisposed") }).disposed(by: bag) behavior.subscribe(onNext: {[weak self] in print("behavior: \($0)") self?.countLabel.text = "\($0)" }).disposed(by: bag) behavior.onNext(100) // vm.down(url: "https://jsonplaceholder.typicode.com/todos") // .subscribe(onNext: { // print($0) // }).disposed(by: bag) json.asObserver().subscribe(onNext: {[weak self] todo in print(todo) print("json is complete!") if (try! self?.behavior.value())! > 130 { self?.behavior.onNext(0) } }).disposed(by: bag) } @IBAction func increaseBtnClicked(_ sender: Any) { behavior.onNext(try! behavior.value() + 1) vm.down(url: "https://jsonplaceholder.typicode.com/todos") // 데이터형을 뽑아야 함. .bind(to: json) .disposed(by: bag) behavior.onNext(try! behavior.value() + 1) vm.down(url: "https://jsonplaceholder.typicode.com/todos") .bind(to: json) .disposed(by: bag) behavior.onNext(try! behavior.value() + 1) vm.down(url: "https://jsonplaceholder.typicode.com/todos") .bind(to: json) .disposed(by: bag) } }
29.597403
82
0.545853
79efe1fad2c81c68b59084e99be0cbe8d6a661f2
3,603
// // Pilot.swift // Runway // // Created by Jelle Vandenbeeck on 02/10/15. // Copyright © 2015 Soaring Book. All rights reserved. // import UIKit import CoreData import AERecord class Pilot: NSManagedObject, WizardSelectionItem { // MARK: - Core Data properties @NSManaged var id: Int64 @NSManaged var firstName: String? @NSManaged var lastName: String? @NSManaged var imageURL: String? @NSManaged var imageData: NSData? @NSManaged var shouldDownloadImage: Bool // MARK: - Core Data relationships @NSManaged var registrations: NSSet // MARK: - Transient properties var image: UIImage? // MARK: - Utilties var displayName: String { let components = [firstName, lastName].flatMap { $0 } return components.joinWithSeparator(" ") } var shortName: String? { return firstName } // MARK: - Creation static func updateObjects(fromResponse objects: [[String:AnyObject]], context: NSManagedObjectContext = AERecord.defaultContext) { for object in objects { updateObject(fromResponse: object, context: context) } } static func updateObject(fromResponse object: [String:AnyObject], context: NSManagedObjectContext = AERecord.defaultContext) { let pilot = firstOrCreateWithAttribute("id", value: object["id"] as! Int, context: context) as! Pilot pilot.updateObject(fromResponse: object) AERecord.saveContextAndWait(context) } func updateObject(fromResponse object: [String:AnyObject]) { firstName = object["first_name"] as! String? lastName = object["last_name"] as! String? imageURL = object["retina_image"] as! String? shouldDownloadImage = object["retina_image"] != nil && (imageData == nil || imageURL != object["retina_image"] as! String?) } // MARK: - Deleting static func deleteUnkownPilots(ids ids: [Int], context: NSManagedObjectContext = AERecord.defaultContext) { let predicate = NSPredicate(format: "NOT (id in %@)", ids) deleteAllWithPredicate(predicate, context: context) } // MARK: - Queries static func selectablePilotsForRegistration(query: String?, context: NSManagedObjectContext = AERecord.defaultContext) -> [Pilot] { var predicate = NSPredicate(format: "(SUBQUERY(registrations, $registration, $registration.duration == nil).@count == 0 OR registrations.@count == 0)") if let query = query where query.characters.count > 0 { let queryPredicate = NSPredicate(format: "firstName contains[c] '\(query)' OR lastName contains[c] '\(query)'") predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, queryPredicate]) } let descriptors = [ NSSortDescriptor(key: "lastName", ascending: true), NSSortDescriptor(key: "firstName", ascending: true) ] return allWithPredicate(predicate, sortDescriptors: descriptors, context: context) as! [Pilot]? ?? [Pilot]() } static func nextPilotToDownload(context: NSManagedObjectContext = AERecord.defaultContext) -> Pilot? { let predicate = NSPredicate(format: "shouldDownloadImage == 1") let descriptors = [ NSSortDescriptor(key: "lastName", ascending: true), NSSortDescriptor(key: "firstName", ascending: true) ] return firstWithPredicate(predicate, sortDescriptors: descriptors, context: context) as! Pilot? } }
37.53125
159
0.652789
7504e7a047aadda7da6f4134f3ca049a6a9dff69
1,071
//: ## High Pass Filter Operation //: import AudioKitPlaygrounds import AudioKit //: Noise Example // Bring down the amplitude so that when it is mixed it is not so loud let whiteNoise = AKWhiteNoise(amplitude: 0.1) let filteredNoise = AKOperationEffect(whiteNoise) { whiteNoise, _ in let halfPower = AKOperation.sineWave(frequency: 0.2).scale(minimum: 12_000, maximum: 100) return whiteNoise.highPassFilter(halfPowerPoint: halfPower) } //: Music Example let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true let filteredPlayer = AKOperationEffect(player) { player, _ in let halfPower = AKOperation.sineWave(frequency: 0.2).scale(minimum: 12_000, maximum: 100) return player.highPassFilter(halfPowerPoint: halfPower) } //: Mixdown and playback let mixer = AKDryWetMixer(filteredNoise, filteredPlayer, balance: 0.5) AudioKit.output = mixer try AudioKit.start() whiteNoise.start() player.play() import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true
32.454545
93
0.777778
fe756e2619eef609529d193fa52b5893cde37b39
481
import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var spriteView:SKView = self.view as SKView } override func viewDidAppear(animated: Bool) { var hello:GameScene = GameScene() hello.size = CGSizeMake(self.view.frame.width, self.view.frame.size.height) var spriteView:SKView = self.view as SKView spriteView.presentScene(hello) } }
26.722222
83
0.673597
1d03ef9e363b1224140d59c53b6e54f53397bd79
50
import Foundation public protocol CZEventData {}
12.5
30
0.82
8a3f34e7380466638f6308e989b9234e76d6ed9c
2,122
import Foundation import Result @available(*, unavailable, renamed: "MoyaError", message: "Moya.Error has been renamed to MoyaError in version 8.0.0") public typealias Error = MoyaError extension Endpoint { @available(*, unavailable, renamed: "adding(newParameters:)") public func endpointByAddingParameters(parameters: [String: AnyObject]) -> Endpoint<Target> { fatalError() } @available(*, unavailable, renamed: "adding(newHTTPHeaderFields:)") public func endpointByAddingHTTPHeaderFields(httpHeaderFields: [String: String]) -> Endpoint<Target> { fatalError() } @available(*, unavailable, renamed: "adding(newParameterEncoding:)") public func endpointByAddingParameterEncoding(newParameterEncoding: Moya.ParameterEncoding) -> Endpoint<Target> { fatalError() } @available(*, unavailable, renamed: "adding(parameters:httpHeaderFields:parameterEncoding:)") public func endpointByAdding(parameters: [String: AnyObject]? = nil, httpHeaderFields: [String: String]? = nil, parameterEncoding: Moya.ParameterEncoding? = nil) -> Endpoint<Target> { fatalError() } } @available(*, unavailable, renamed: "MultiTarget", message: "StructTarget has been renamed to MultiTarget in version 8.0.0") enum StructTarget { } extension MoyaProvider { @available(*, unavailable, renamed: "notifyPluginsOfImpendingStub(for:target:)") internal final func notifyPluginsOfImpendingStub(request: URLRequest, target: Target) { fatalError() } } extension Response { @available(*, unavailable, renamed: "filter(statusCodes:)") public func filterStatusCodes(range: ClosedRange<Int>) throws -> Response { fatalError() } @available(*, unavailable, renamed: "filter(statusCode:)") public func filterStatusCode(code: Int) throws -> Response { fatalError() } } extension PluginType { @available(*, unavailable, renamed: "willSend(_:)") func willSendRequest(request: RequestType, target: TargetType) { fatalError() } @available(*, unavailable, renamed: "didReceive(_:)") func didReceiveResponse(result: Result<Moya.Response, MoyaError>, target: TargetType) { fatalError() } }
48.227273
203
0.742696
4b2b9e02de984d87fc33178d480dad81ec6df17d
1,565
// // Copyright (c) 2018 KxCoding <[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. // //: [Previous](@previous) import Foundation /*: # Forced Ordering Option */ let upper = "STRING" let lower = "string" upper == lower // false. upper.compare(lower, options: [.caseInsensitive]) == .orderedSame // true. upper.compare(lower, options: [.caseInsensitive, .forcedOrdering]) == .orderedSame // false. 정렬을 위해 caseInsensitive를 무시한다. 두 문자가 완전히 동일하다면, Forced ordering은 의미가 없다. //: [Next](@next)
33.297872
164
0.732268
3a9bdc5d6639e7d7852e4fff10bc9af9d2e29fba
3,279
// // Helper.swift // CMU-SV-Indoor-Swift // // Created by xxx on 12/6/14. // Copyright (c) 2014 CMU-SV. All rights reserved. // import UIKit import AudioToolbox // MARK: Helper Types public enum Building: NSString { case None = "None" case BuildingSB = "BuildingSB" case Building23 = "Building23" } public enum Floor { case None case Floor1 case Floor2 } public class BuildingInfo { let coordinate: CLLocationCoordinate2D let range: CLLocationDistance var distance: CLLocationDistance init(coordinate: CLLocationCoordinate2D, range: CLLocationDistance, distance: CLLocationDistance) { self.coordinate = coordinate self.range = range self.distance = distance } } extension CLLocationCoordinate2D: Hashable { public var hashValue : Int { get { return "\(self.latitude),\(self.longitude)".hashValue } } } // MARK: Helper Functions public func shakeDevice() { AudioServicesPlaySystemSound(0x00000FFF); } public func getTopViewController() -> UIViewController { var topViewController = UIApplication.sharedApplication().keyWindow!.rootViewController! while topViewController.presentedViewController != nil { topViewController = topViewController.presentedViewController! } return topViewController } public func failGracefully(reason: String) { let failAlert = UIAlertController(title: "Applicaiton failed.", message: "Due to: \"\(reason)\"", preferredStyle: UIAlertControllerStyle.Alert) let terminateButton = UIAlertAction(title: "Terminate", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) in exit(EXIT_FAILURE) }) failAlert.addAction(terminateButton) getTopViewController().presentViewController(failAlert, animated: false, completion: nil) } public func == (left: CLLocationCoordinate2D, right: CLLocationCoordinate2D) -> Bool { return (left.latitude == right.latitude) && (left.longitude == right.longitude) } public func != (left: CLLocationCoordinate2D, right: CLLocationCoordinate2D) -> Bool { return !(left == right) } public func + (left: CLLocationCoordinate2D, right: CLLocationCoordinate2D) -> CLLocationCoordinate2D { return CLLocationCoordinate2DMake(left.latitude + right.latitude, left.longitude + right.longitude) } public func distanceInMetersBetween(left: CLLocationCoordinate2D, right: CLLocationCoordinate2D) -> CLLocationDistance { let earthRadius = 6371_010.0 // Earth radius in meters let DEG_TO_RAD = 0.017453292519943295769236907684886; let EARTH_RADIUS_IN_METERS = 6372797.560856; let latitudeArc = (left.latitude - right.latitude) * DEG_TO_RAD; let longitudeArc = (left.longitude - right.longitude) * DEG_TO_RAD; let latitudeH = sin(latitudeArc * 0.5); let lontitudeH = sin(longitudeArc * 0.5); let tmp = cos(left.latitude * DEG_TO_RAD) * cos(right.latitude * DEG_TO_RAD); return EARTH_RADIUS_IN_METERS * 2.0 * asin(sqrt(latitudeH * latitudeH + tmp * lontitudeH * lontitudeH)); //return sqrt( pow( (left.latitude - right.latitude), 2) + pow( (left.longitude - right.longitude), 2) ) * earthRadius / 360.0 } public func exitWithAlert() { exit(EXIT_FAILURE) }
30.361111
147
0.712717
d5fc82423101ed5f4df8af68f5d3321d916954b5
296
// // Preference+Extension.swift // PreferenceExample // // Created by MacBook Pro M1 on 2021/10/07. // import Preferences extension Preferences.PaneIdentifier { static let general = Self("general") static let advanced = Self("advanced") static let firebase = Self("firebase") }
19.733333
44
0.702703
ccdf5f5e88962b98303d195b553eb6af661a6dbc
1,011
// // SubwayKorea.swift // Pods // // Created by Mariam AlJamea on 1/19/16. // Copyright © 2016 kitz. All rights reserved. // public extension Applications { public struct SubwayKorea: ExternalApplication { public typealias ActionType = Applications.SubwayKorea.Action public let scheme = "subwaykorea:" public let fallbackURL = "http://blog.malangstudio.com" public let appStoreId = "325924444" public init() {} } } // MARK: - Actions public extension Applications.SubwayKorea { public enum Action { case open } } extension Applications.SubwayKorea.Action: ExternalApplicationAction { public var paths: ActionPaths { switch self { case .open: return ActionPaths( app: Path( pathComponents: ["app"], queryParameters: [:] ), web: Path() ) } } }
21.0625
70
0.548961
1e919e3972740cf7d7b46ea0c6b81a9edc2c37d0
3,737
// // CircleShapeView.swift // Superheroes // // Created by Adam Cseke on 2022. 03. 10.. // Copyright © 2022. levivig. All rights reserved. // import UIKit class CircleShapeView: UIView { private var progressShape: CAShapeLayer! private var precentageLabel: UILabel! private var titleLabel: UILabel! private var trackShape: CAShapeLayer! private var circleRadius: CGFloat = 0.0 private var circlePath: UIBezierPath! var radius: CGFloat = 0.0 { didSet { circleRadius = radius setup() } } // MARK: Properties public var currentProgress: Double = 0.0 { didSet { let precentage = currentProgress * 100 progressShape.strokeEnd = currentProgress precentageLabel.text = "\(Int(precentage))%" setupAnimation() setNeedsLayout() } } public var color: CGColor? { didSet { progressShape.strokeColor = color setNeedsLayout() } } public var title: String = "" { didSet { titleLabel.text = title } } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder: NSCoder) { super.init(coder: coder) } override func draw(_ rect: CGRect) { super.draw(rect) trackShape.position = CGPoint(x: self.layer.bounds.midX, y: self.layer.bounds.midY) progressShape.position = CGPoint(x: self.layer.bounds.midX, y: self.layer.bounds.midY) } private func setup() { configureShapeLayer() configurePrecentageLabel() configureTitleLabel() } private func configureShapeLayer() { progressShape = CAShapeLayer() circlePath = UIBezierPath(arcCenter: center, radius: circleRadius, startAngle: -(.pi / 2), endAngle: 3 * .pi / 2, clockwise: true) trackShape = CAShapeLayer() trackShape.path = circlePath.cgPath trackShape.fillColor = UIColor.clear.cgColor trackShape.lineWidth = 8 trackShape.strokeColor = Colors.orange.color.cgColor layer.addSublayer(trackShape) progressShape.path = circlePath.cgPath progressShape.strokeColor = color progressShape.strokeEnd = 0 progressShape.fillColor = UIColor.clear.cgColor progressShape.lineWidth = 16 progressShape.lineCap = .round layer.addSublayer(progressShape) } private func setupAnimation() { let animation = CABasicAnimation(keyPath: "strokeEnd") animation.toValue = currentProgress animation.duration = 0.6 animation.fromValue = 0 animation.isRemovedOnCompletion = false animation.fillMode = .forwards progressShape.add(animation, forKey: "animation") } private func configurePrecentageLabel() { precentageLabel = UILabel() precentageLabel.textAlignment = .center precentageLabel.font = FontFamily.Gotham.medium.font(size: 12) precentageLabel.sizeToFit() addSubview(precentageLabel) precentageLabel.snp.makeConstraints { make in make.top.centerY.centerX.equalToSuperview() } } private func configureTitleLabel() { titleLabel = UILabel() titleLabel.textAlignment = .center titleLabel.text = title titleLabel.font = FontFamily.Gotham.medium.font(size: 12) titleLabel.sizeToFit() addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.centerX.equalToSuperview() make.bottom.equalToSuperview() } } }
29.65873
138
0.616805
f72c0067da2f7bd0fbacdc64e08005b891e0fa9b
2,070
/* * Copyright (c) 2011-2019 HERE Europe B.V. * All rights reserved. */ import UIKit import NMAKit class ResultTableViewController: UITableViewController { @IBOutlet var resultTableView: UITableView! @IBOutlet weak var backButton: UIBarButtonItem! // Array that stores the search result from MapViewController var resultsArray: [NMALink] = [] override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return resultsArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "tableCell") // Display vicinity information of each NMAPlaceLink item.Please refer to HERE Mobile SDK for iOS API // doc for all supported APIs. let link = self.resultsArray[indexPath.row]; if link is NMAPlaceLink { cell.textLabel?.text = (link as! NMAPlaceLink).vicinityDescription; } else if (link is NMADiscoveryLink) { cell.textLabel?.text = "This is a DiscoveryLink"; } return cell; } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "PlaceDetailView") { guard let indexPath = self.resultTableView.indexPathForSelectedRow else {return} let placeDetailViewController = segue.destination as! PlaceDetailViewController // Pass the selected NMAPlaceLink object to the next view controller for retrieving place // details. let link = self.resultsArray[indexPath.row] if link is NMAPlaceLink { placeDetailViewController.placeLink = link as? NMAPlaceLink; } else { Helper.show("The item selected is a DiscoveryLink", onView: self.view) } } } @IBAction func onBackButtonClicked(_ sender: Any) { self.navigationController?.dismiss(animated: true, completion: nil) } }
38.333333
109
0.670531
90c390429b10b804d8ced9d69d7588df4a7bee7e
884
import SwiftUI public extension ViewType { struct OptionalContent {} } extension ViewType.OptionalContent: SingleViewContent { public static func content(view: Any, envObject: Any) throws -> Any { guard let content = try (view as? OptionalViewContentProvider)?.content() else { throw InspectionError.typeMismatch(view, OptionalViewContentProvider.self) } return try Inspector.unwrap(view: content) } } // MARK: - Private private protocol OptionalViewContentProvider { func content() throws -> Any } extension Optional: OptionalViewContentProvider { func content() throws -> Any { switch self { case let .some(view): return try Inspector.unwrap(view: view) case .none: throw InspectionError.viewNotFound(parent: Inspector.typeName(value: self as Any)) } } }
26
94
0.669683
c13948ed201ad500e0514b80f02f95984aadf30a
1,237
// // HorizontalProgressBar.swift // Chrysan // // Created by Harley-xk on 2020/9/28. // Copyright © 2020 Harley. All rights reserved. // import Foundation import UIKit open class HorizontalProgressBar: UIView, ProgressIndicatorView { /// 进度值,0~1 open var progress: CGFloat = 0 { didSet { setNeedsDisplay() } } private let progressLayer = CALayer() private let backgroundMask = CAShapeLayer() public override init(frame: CGRect) { super.init(frame: frame) setupLayers() } public required init?(coder: NSCoder) { super.init(coder: coder) setupLayers() } private func setupLayers() { layer.addSublayer(progressLayer) if backgroundColor == nil { backgroundColor = UIColor.darkGray } } open override func draw(_ rect: CGRect) { backgroundMask.path = UIBezierPath(roundedRect: rect, cornerRadius: rect.height * 0.5).cgPath layer.mask = backgroundMask let progressRect = CGRect(origin: .zero, size: CGSize(width: rect.width * progress, height: rect.height)) progressLayer.frame = progressRect progressLayer.backgroundColor = tintColor.cgColor } }
24.254902
113
0.643492
5b9e391ebed1818aa4225ac9ffd18ea0be87f39b
386
// // Date_Extension.swift // MyLiveBySwift // // Created by Shedows on 2017/1/1. // Copyright © 2017年 Shedows. All rights reserved. // import Foundation // MARK:- 获取当前时间 返回 以秒显示 extension Date{ static func getCurrentTime() ->String{ let nowDate = Date() let interval = nowDate.timeIntervalSince1970 return "\(interval)" } }
17.545455
52
0.611399
213664a50290826487f475f59ca5e924849355c9
1,698
import Foundation import WebRTC /** MediaChannel, SignalingChannel, WebSocketChannel の接続状態を表します。 */ public enum ConnectionState { /// 接続試行中 case connecting /// 接続成功済み case connected /// 接続解除試行中 case disconnecting /// 接続解除済み case disconnected var isConnecting: Bool { get { return self == .connecting } } var isDisconnected: Bool { get { switch self { case .disconnecting, .disconnected: return true default: return false } } } init(_ state: PeerChannelConnectionState) { switch state { case .new: self = .disconnected case .connecting: self = .connecting // RTCPeerConnectionState の disconnected は connected に遷移する可能性があるため接続中として扱う case .connected, .disconnected: self = .connected case .closed, .failed, .unknown: self = .disconnected } } } /** PeerChannel の接続状態を表します。 */ enum PeerChannelConnectionState { case new case connecting case connected case disconnected case failed case closed case unknown init(_ state: RTCPeerConnectionState) { switch state { case .new: self = .new case .connecting: self = .connecting case .connected: self = .connected case .disconnected: self = .disconnected case .failed: self = .failed case .closed: self = .closed @unknown default: self = .unknown break } } }
19.744186
82
0.535925
2fd4cf2432736434ad697808d2ff14e0d3b292f9
3,178
// // AppDelegate.swift // SensoroSDKActive-iOS // // Created by David Yang on 15/4/8. // Copyright (c) 2015年 Sensoro. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool { // Override point for customization after application launch. // let iOSVersion = (UIDevice.current.systemVersion as NSString).floatValue; // // if( iOSVersion >= 8.0 && iOSVersion < 10.0){ // UIApplication.sharedApplication.registerUserNotificationSettings(UIUserNotificationSettings(forTypes:(.Alert | .Sound | .Badge), categories: nil)) // UIApplication.shared.registerForRemoteNotifications() // }else{ // UIApplication.sharedApplication.registerForRemoteNotificationTypes((.Alert | .Sound | .Badge)) // } // //在通过Location唤醒时,launchOptions包含了UIApplicationLaunchOptionsLocationKey, //用于只是是从Location重新唤醒的。 if let options = launchOptions { NSLog("Relauched") if (options[UIApplication.LaunchOptionsKey.location] as? NSNumber) != nil { NSLog("Relauched with number") SENLocationManager.sharedInstance.startMonitor(relaunch: true); } } 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.057971
285
0.708307
e4cf142adc490fcf815cdeacfa8170e90e25d7b6
2,797
// // AboutViewController.swift // SmartGPSTracker // // Created by Mosquito1123 on 11/07/2019. // Copyright © 2019 Cranberry. All rights reserved. // import UIKit import WebKit /// /// Controller to display the About page. /// /// Internally it is a WKWebView that displays the resource file about.html. /// class AboutViewController: UIViewController { /// Embedded web browser var webView: WKWebView? /// Initializer. Only calls super required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Initializer. Only calls super override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } /// /// Configures the view. Performs the following actions: /// /// 1. Sets the title to About /// 2. Adds "Done" button /// 3. Adds the webview that loads about.html from the bundle. /// override func viewDidLoad() { super.viewDidLoad() self.title = "About" //Add the done button let shareItem = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(AboutViewController.closeViewController)) self.navigationItem.rightBarButtonItems = [shareItem] //Add the Webview self.webView = WKWebView(frame: self.view.frame, configuration: WKWebViewConfiguration()) self.webView?.navigationDelegate = self let path = Bundle.main.path(forResource: "about", ofType: "html") let text = try? String(contentsOfFile: path!, encoding: String.Encoding.utf8) webView?.loadHTMLString(text!, baseURL: nil) self.view.addSubview(webView!) } /// Closes this view controller. Triggered by pressing the "Done" button in navigation bar. @objc func closeViewController() { self.dismiss(animated: true, completion: { () -> Void in }) } } /// Handles all navigation related stuff for the web view extension AboutViewController: WKNavigationDelegate { /// Opens Safari when user clicks a link in the About page. func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { print("AboutViewController: decidePolicyForNavigationAction") if navigationAction.navigationType == .linkActivated { UIApplication.shared.openURL(navigationAction.request.url!) print("AboutViewController: external link sent to Safari") decisionHandler(.cancel) return } decisionHandler(.allow) } }
32.149425
164
0.649982
5bf6a189e097e11280a6b1171be10dc731a531ea
747
import XCTest import SPSheetKit class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.758621
111
0.601071
11e5acc45d8b64d840fa1e9dc75a1a5e8cc60189
700
// // MessageManager.swift // StaticMethods // // Created by Wade Weitzel on 5/28/20. // Copyright © 2020 Wade Weitzel. All rights reserved. import Foundation class MessageManager { var swiftStaticUtils:SwiftStaticUtilsProtocol.Type = SwiftStaticUtils.self var objectiveCStaticUtils:ObjectiveCStaticUtilsProtocol.Type = ObjectiveCStaticUtils.self func getMessage() -> String { if objectiveCStaticUtils.getAppVersionType() == "US" { return swiftStaticUtils.getUSMessage() } else if objectiveCStaticUtils.getAppVersionType() == "UK" { return swiftStaticUtils.getUKMessage() } return "Welcome Mystery User" } }
29.166667
93
0.691429
215ca639a1b0efce5206ffe258bf5a5ac904e23c
9,864
// // OAuthSwiftClient.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation public var OAuthSwiftDataEncoding: String.Encoding = .utf8 @objc public protocol OAuthSwiftRequestHandle { func cancel() } open class OAuthSwiftClient: NSObject { fileprivate(set) open var credential: OAuthSwiftCredential open var paramsLocation: OAuthSwiftHTTPRequest.ParamsLocation = .authorizationHeader /// Contains default URL session configuration open var sessionFactory = URLSessionFactory() static let separator: String = "\r\n" static var separatorData: Data = { return OAuthSwiftClient.separator.data(using: OAuthSwiftDataEncoding)! }() // MARK: init public init(credential: OAuthSwiftCredential) { self.credential = credential } public convenience init(consumerKey: String, consumerSecret: String, version: OAuthSwiftCredential.Version = .oauth1) { let credential = OAuthSwiftCredential(consumerKey: consumerKey, consumerSecret: consumerSecret) credential.version = version self.init(credential: credential) } public convenience init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String, version: OAuthSwiftCredential.Version) { self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, version: version) self.credential.oauthToken = oauthToken self.credential.oauthTokenSecret = oauthTokenSecret } // MARK: client methods @discardableResult open func get(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { return self.request(urlString, method: .GET, parameters: parameters, headers: headers, success: success, failure: failure) } @discardableResult open func post(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { return self.request(urlString, method: .POST, parameters: parameters, headers: headers, body: body, success: success, failure: failure) } @discardableResult open func put(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { return self.request(urlString, method: .PUT, parameters: parameters, headers: headers, body: body, success: success, failure: failure) } @discardableResult open func delete(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { return self.request(urlString, method: .DELETE, parameters: parameters, headers: headers, success: success, failure: failure) } @discardableResult open func patch(_ urlString: String, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { return self.request(urlString, method: .PATCH, parameters: parameters, headers: headers, success: success, failure: failure) } @discardableResult open func request(_ urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil, checkTokenExpiration: Bool = true, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { if checkTokenExpiration && self.credential.isTokenExpired() { failure?(OAuthSwiftError.tokenExpired(error: nil)) return nil } guard URL(string: urlString) != nil else { failure?(OAuthSwiftError.encodingError(urlString: urlString)) return nil } if let request = makeRequest(urlString, method: method, parameters: parameters, headers: headers, body: body) { request.start(success: success, failure: failure) return request } return nil } open func makeRequest(_ request: URLRequest) -> OAuthSwiftHTTPRequest { let request = OAuthSwiftHTTPRequest(request: request, paramsLocation: self.paramsLocation, sessionFactory: self.sessionFactory) request.config.updateRequest(credential: self.credential) return request } open func makeRequest(_ urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], headers: OAuthSwift.Headers? = nil, body: Data? = nil) -> OAuthSwiftHTTPRequest? { guard let url = URL(string: urlString) else { return nil } let request = OAuthSwiftHTTPRequest(url: url, method: method, parameters: parameters, paramsLocation: self.paramsLocation, httpBody: body, headers: headers ?? [:], sessionFactory: self.sessionFactory) request.config.updateRequest(credential: self.credential) return request } @discardableResult public func postImage(_ urlString: String, parameters: OAuthSwift.Parameters, image: Data, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { return self.multiPartRequest(url: urlString, method: .POST, parameters: parameters, image: image, success: success, failure: failure) } open func makeMultiPartRequest(_ urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters = [:], multiparts: [OAuthSwiftMultipartData] = [], headers: OAuthSwift.Headers? = nil) -> OAuthSwiftHTTPRequest? { let boundary = "AS-boundary-\(arc4random())-\(arc4random())" let type = "multipart/form-data; boundary=\(boundary)" let body = self.multiDataFromObject(parameters, multiparts: multiparts, boundary: boundary) var finalHeaders = [kHTTPHeaderContentType: type] finalHeaders += headers ?? [:] return makeRequest(urlString, method: method, parameters: parameters, headers: finalHeaders, body: body) } func multiPartRequest(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, image: Data, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { let multiparts = [ OAuthSwiftMultipartData(name: "media", data: image, fileName: "file", mimeType: "image/jpeg") ] if let request = makeMultiPartRequest(url, method: method, parameters: parameters, multiparts: multiparts) { request.start(success: success, failure: failure) return request } return nil } open func multiPartBody(from inputParameters: OAuthSwift.Parameters, boundary: String) -> Data { var parameters = OAuthSwift.Parameters() var multiparts = [OAuthSwiftMultipartData]() for (key, value) in inputParameters { if let data = value as? Data, key == "media" { let sectionType = "image/jpeg" let sectionFilename = "file" multiparts.append(OAuthSwiftMultipartData(name: key, data: data, fileName: sectionFilename, mimeType: sectionType)) } else { parameters[key] = value } } return multiDataFromObject(parameters, multiparts: multiparts, boundary: boundary) } @discardableResult open func postMultiPartRequest(_ url: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, multiparts: [OAuthSwiftMultipartData] = [], checkTokenExpiration: Bool = true, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) -> OAuthSwiftRequestHandle? { if checkTokenExpiration && self.credential.isTokenExpired() { failure?(OAuthSwiftError.tokenExpired(error: nil)) return nil } if let request = makeMultiPartRequest(url, method: method, parameters: parameters, multiparts: multiparts, headers: headers) { request.start(success: success, failure: failure) return request } return nil } func multiDataFromObject(_ object: OAuthSwift.Parameters, multiparts: [OAuthSwiftMultipartData], boundary: String) -> Data { var data = Data() let prefixString = "--\(boundary)\r\n" let prefixData = prefixString.data(using: OAuthSwiftDataEncoding)! for (key, value) in object { guard let valueData = "\(value)".data(using: OAuthSwiftDataEncoding) else { continue } data.append(prefixData) let multipartData = OAuthSwiftMultipartData(name: key, data: valueData, fileName: nil, mimeType: nil) data.append(multipartData, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData) } for multipart in multiparts { data.append(prefixData) data.append(multipart, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData) } let endingString = "--\(boundary)--\r\n" let endingData = endingString.data(using: OAuthSwiftDataEncoding)! data.append(endingData) return data } }
50.584615
363
0.707928
ff4ab4153b0cb9d035787d0039eb5e3943a60847
2,549
// RUN: %target-build-swift -module-name a %s -o %t.out // RUN: %target-run %t.out // REQUIRES: executable_test // XFAIL: linux // // This file contains reflection tests that depend on hash values. // Don't add other tests here. // import StdlibUnittest var Reflection = TestSuite("Reflection") Reflection.test("Dictionary/Empty") { let dict = [Int : Int]() var output = "" dump(dict, &output) var expected = "- 0 key/value pairs\n" expectEqual(expected, output) } Reflection.test("Dictionary") { let dict = [ "One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5 ] var output = "" dump(dict, &output) #if arch(i386) || arch(arm) var expected = "" expected += "▿ 5 key/value pairs\n" expected += " ▿ [0]: (2 elements)\n" expected += " - .0: Four\n" expected += " - .1: 4\n" expected += " ▿ [1]: (2 elements)\n" expected += " - .0: One\n" expected += " - .1: 1\n" expected += " ▿ [2]: (2 elements)\n" expected += " - .0: Two\n" expected += " - .1: 2\n" expected += " ▿ [3]: (2 elements)\n" expected += " - .0: Five\n" expected += " - .1: 5\n" expected += " ▿ [4]: (2 elements)\n" expected += " - .0: Three\n" expected += " - .1: 3\n" #elseif arch(x86_64) || arch(arm64) var expected = "" expected += "▿ 5 key/value pairs\n" expected += " ▿ [0]: (2 elements)\n" expected += " - .0: Five\n" expected += " - .1: 5\n" expected += " ▿ [1]: (2 elements)\n" expected += " - .0: Two\n" expected += " - .1: 2\n" expected += " ▿ [2]: (2 elements)\n" expected += " - .0: One\n" expected += " - .1: 1\n" expected += " ▿ [3]: (2 elements)\n" expected += " - .0: Three\n" expected += " - .1: 3\n" expected += " ▿ [4]: (2 elements)\n" expected += " - .0: Four\n" expected += " - .1: 4\n" #else fatalError("unipmelemented") #endif expectEqual(expected, output) } Reflection.test("Set") { let s = Set(1...5) var output = "" dump(s, &output) #if arch(i386) || arch(arm) var expected = "" expected += "▿ 5 members\n" expected += " - [0]: 3\n" expected += " - [1]: 1\n" expected += " - [2]: 5\n" expected += " - [3]: 2\n" expected += " - [4]: 4\n" #elseif arch(x86_64) || arch(arm64) var expected = "" expected += "▿ 5 members\n" expected += " - [0]: 5\n" expected += " - [1]: 2\n" expected += " - [2]: 3\n" expected += " - [3]: 1\n" expected += " - [4]: 4\n" #else fatalError("unimplemented") #endif expectEqual(expected, output) } runAllTests()
23.82243
69
0.52295
33706b123b1a38834a0b724efb171fb80e674e32
856
// // FrameworkViewController.swift // // Created by Azfar Siddiqui on 3/8/20. // Copyright © 2020 Syed Khalil. All rights reserved. // import UIKit public class FrameworkViewController: UIViewController { convenience init() { let bundle = Bundle(for: Self.self) self.init(nibName: "FrameworkViewController", bundle: bundle) } public override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
24.457143
106
0.66472
5d40b28383cf6e9d09a3f0f3843fb828855358f3
2,288
// // SceneDelegate.swift // Prework // // Created by Vincent Chen on 9/5/21. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.169811
147
0.712413
8f019361c28f809bcf9ba046a1607f79ef9fb5a6
3,165
// Copyright 2016 Razeware Inc. (see LICENSE.txt for details) import Foundation // --- Introduction class Person { var firstName: String var lastName: String init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } var fullName: String { return "\(firstName) \(lastName)" } } let john = Person(firstName: "Johnny", lastName: "Appleseed") // --- Reference types var homeOwner = john john.firstName = "John" // John wants to use his short name! john.firstName // "John" homeOwner.firstName // "John" john === homeOwner // true let imposterJohn = Person(firstName: "Johnny", lastName: "Appleseed") john === homeOwner // true john === imposterJohn // false imposterJohn === homeOwner // false // Assignment of existing variables changes the instances the variables reference. homeOwner = imposterJohn john === homeOwner // false homeOwner = john john === homeOwner // true // Create fake, imposter Johns. Use === to see if any of these imposters are our real John. var imposters = (0...100).map { _ in Person(firstName: "John", lastName: "Appleseed") } // Equality (==) is not effective when John cannot be identified by his name alone imposters.contains { $0.firstName == john.firstName && $0.lastName == john.lastName } // Check to ensure the real John is not found among the imposters. imposters.contains { $0 === john } // false // Now hide the "real" John somewhere among the imposters. John can now be found among the imposters imposters.insert(john, at: Int(arc4random_uniform(100))) imposters.contains { $0 === john } // true // Since `Person` is a reference type, you can use === to grab the real John out of the list of imposters and modify the value. // The original `john` variable will print the new last name! if let whereIsJohn = imposters.index(where: { $0 === john }) { imposters[whereIsJohn].lastName = "Bananapeel" } john.fullName // John Bananapeel struct Grade { let letter: String let points: Double let credits: Double } class Student { var firstName: String var lastName: String var grades: [Grade] = [] var credits = 0.0 // Added in section "Understanding state and side effects init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } func recordGrade(_ grade: Grade) { grades.append(grade) credits += grade.credits // Added in section "Understanding state and side effects } } let jane = Student(firstName: "Jane", lastName: "Appleseed") let history = Grade(letter: "B", points: 9.0, credits: 3.0) var math = Grade(letter: "A", points: 16.0, credits: 4.0) jane.recordGrade(history) jane.recordGrade(math) // Error: jane is a `let` constant //jane = Student(firstName: "John", lastName: "Appleseed") // --- Understanding state and side effects jane.credits // 7 // The teacher made a mistake; math has 5 credits math = Grade(letter: "A", points: 20.0, credits: 5.0) jane.recordGrade(math) jane.credits // 12, not 8! extension Student { var fullName: String { return "\(firstName) \(lastName)" } } jane.fullName // "Jane Appleseed"
24.160305
127
0.694471
dd2c7ec7cd0e9f2e44c69c418d5c34fc824436f7
7,454
// // ViewController.swift // HDAugmentedRealityDemo // // Created by Danijel Huis on 21/04/15. // Copyright (c) 2015 Danijel Huis. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController, ARDataSource { var filterButton: UIButton? let filterView = FilterView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) var sortedData = [InfoShot]() var locManager = CLLocationManager() var currentLocation: CLLocation! var updateButton: UIButton = { let button = UIButton() button.setTitle("Start augmented reality", for: .normal) button.setTitleColor(.white, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 25) button.backgroundColor = UIColor(red: 101/255, green: 156/255, blue: 53/255, alpha: 1) return button }() override func viewDidLoad() { super.viewDidLoad() self.locManager.requestWhenInUseAuthorization() self.assignCurrentLocation() updateButton.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 70, width: UIScreen.main.bounds.width, height: 70) updateButton.addTarget(self, action: #selector(update), for: UIControlEvents.touchUpInside) self.filterView.addSubview(updateButton) self.view.addSubview(filterView) } func update() { print("Update tapped") filterView.update() showARViewController() } internal func showFilterView() { self.filterView.showFilterView() } /// Creates random annotations around predefined center point and presents ARViewController modally func showARViewController() { self.sortedData = filterView.sortedData let result = ARViewController.createCaptureSession() if result.error != nil { let message = result.error?.userInfo["description"] as? String let alertView = UIAlertView(title: "Error", message: message, delegate: nil, cancelButtonTitle: "Close") alertView.show() return } let lat = self.currentLocation.coordinate.latitude let lon = self.currentLocation.coordinate.longitude let delta = 0.05 let dummyAnnotations = self.getDummyAnnotations(centerLatitude: lat, centerLongitude: lon, delta: delta, count: self.sortedData.count) // Present ARViewController let arViewController = ARViewController() arViewController.dataSource = self arViewController.maxDistance = 0 arViewController.maxVisibleAnnotations = 100 arViewController.maxVerticalLevel = 5 arViewController.headingSmoothingFactor = 0.05 arViewController.trackingManager.userDistanceFilter = 25 arViewController.trackingManager.reloadDistanceFilter = 75 arViewController.setAnnotations(dummyAnnotations) arViewController.uiOptions.debugEnabled = true arViewController.uiOptions.closeButtonEnabled = true //arViewController.interfaceOrientationMask = .landscape arViewController.onDidFailToFindLocation = { [weak self, weak arViewController] elapsedSeconds, acquiredLocationBefore in self?.handleLocationFailure(elapsedSeconds: elapsedSeconds, acquiredLocationBefore: acquiredLocationBefore, arViewController: arViewController) } self.present(arViewController, animated: true, completion: nil) } /// This method is called by ARViewController, make sure to set dataSource property. func ar(_ arViewController: ARViewController, viewForAnnotation: ARAnnotation) -> ARAnnotationView { // Annotation views should be lightweight views, try to avoid xibs and autolayout all together. let annotationView = TestAnnotationView() annotationView.frame = CGRect(x: 0,y: 0,width: 150,height: 50) return annotationView; } fileprivate func getDummyAnnotations(centerLatitude: Double, centerLongitude: Double, delta: Double, count: Int) -> Array<ARAnnotation> { var annotations: [ARAnnotation] = [] for data in sortedData { let deleteWhiteSpaceFromX = data.shot.xCoordinate.trimmingCharacters(in: .whitespaces) let deleteWhiteSpaceFromY = data.shot.yCoordinate.trimmingCharacters(in: .whitespaces) let getXFromArr = Double(deleteWhiteSpaceFromX.replacingOccurrences(of: ",", with: "", options: NSString.CompareOptions.literal, range: nil))! let getYFromArr = Double(deleteWhiteSpaceFromY.replacingOccurrences(of: ",", with: "", options: NSString.CompareOptions.literal, range: nil))! let lat = (30.19736606 + ((getXFromArr - 9720.476) * 0.00000276)) let long = (-81.39221191 + ((getYFromArr - 10516.2) * 0.00000315)) let annotation = ARAnnotation() annotation.location = CLLocation(latitude: lat, longitude: long) annotation.tournament = data.tournament.tourDescription annotation.title = data.player.playerFullName annotation.shotDistance = Double(data.shot.distance)! / 12 //convert inches to feet annotation.year = data.tournament.year annotation.hole = data.shot.hole annotation.round = data.shot.round annotations.append(annotation) } return annotations } func handleLocationFailure(elapsedSeconds: TimeInterval, acquiredLocationBefore: Bool, arViewController: ARViewController?) { guard let arViewController = arViewController else { return } NSLog("Failed to find location after: \(elapsedSeconds) seconds, acquiredLocationBefore: \(acquiredLocationBefore)") // Example of handling location failure if elapsedSeconds >= 20 && !acquiredLocationBefore { // Stopped bcs we don't want multiple alerts arViewController.trackingManager.stopTracking() let alert = UIAlertController(title: "Problems", message: "Cannot find location, use Wi-Fi if possible!", preferredStyle: .alert) let okAction = UIAlertAction(title: "Close", style: .cancel) { (action) in self.dismiss(animated: true, completion: nil) } alert.addAction(okAction) self.presentedViewController?.present(alert, animated: true, completion: nil) } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////// @@@@@@@ CUSTOM SECTION @@@@@@@ //////////////////////////////////// //////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// func assignCurrentLocation(){ if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways) { self.currentLocation = self.locManager.location print(self.currentLocation.coordinate.latitude) print(self.currentLocation.coordinate.longitude) } } }
45.45122
155
0.634827
11f6a31f01e3c349a434450b0039e2ba31516c9a
613
// // StackView.swift // CocoaUI // // Created by Prashant Shrestha on 5/18/20. // Copyright © 2020 Inficare. All rights reserved. // import UIKit open class StackView: UIStackView { override public init(frame: CGRect) { super.init(frame: frame) makeUI() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) makeUI() } open func makeUI() { spacing = 0 axis = .vertical distribution = .fill updateUI() } open func updateUI() { setNeedsDisplay() } }
17.027778
51
0.554649
6204ba9242e7127dafd09b1cb731187da48fdd79
2,916
// // TruthTableEntry.swift // SwiftQuantumComputing // // Created by Enrique de la Torre on 11/04/2021. // Copyright © 2021 Enrique de la Torre. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation // MARK: - Main body struct TruthTableEntry { // MARK: - Internal properties let truth: String // MARK: - Internal init methods enum InitError: Error { case truthHasToBeANonEmptyStringComposedOnlyOfZerosAndOnes case truthCanNotBeRepresentedWithGivenTruthCount } init(truth: String, truthCount: Int? = nil) throws { let truthCount = truthCount ?? truth.count guard !truth.isEmpty else { throw InitError.truthHasToBeANonEmptyStringComposedOnlyOfZerosAndOnes } guard truthCount > 0 else { throw InitError.truthCanNotBeRepresentedWithGivenTruthCount } var actualTruth = truth let offset = truthCount - truth.count if offset > 0 { actualTruth = String(repeating: "0", count: offset) + truth } else if offset < 0 { let offsetIndex = truth.index(truth.startIndex, offsetBy: abs(offset)) if let nonZero = truth[..<offsetIndex].first(where: { $0 != "0" }) { if nonZero == "1" { throw InitError.truthCanNotBeRepresentedWithGivenTruthCount } throw InitError.truthHasToBeANonEmptyStringComposedOnlyOfZerosAndOnes } actualTruth.removeSubrange(..<offsetIndex) } if !actualTruth.allSatisfy({ $0 == "0" || $0 == "1" }) { throw InitError.truthHasToBeANonEmptyStringComposedOnlyOfZerosAndOnes } self.init(truth: actualTruth) } // MARK: - Private init methods private init(truth: String) { self.truth = truth } } // MARK: - Hashable methods extension TruthTableEntry: Hashable { static func == (lhs: TruthTableEntry, rhs: TruthTableEntry) -> Bool { return lhs.truth == rhs.truth } func hash(into hasher: inout Hasher) { truth.hash(into: &hasher) } } // MARK: - Overloaded operators extension TruthTableEntry { // MARK: - Internal operators static func +(lhs: TruthTableEntry, rhs: TruthTableEntry) -> TruthTableEntry { return TruthTableEntry(truth: lhs.truth + rhs.truth) } }
28.31068
85
0.651578
39a8bcc2522188b98ec1c682131ccf069d4f90a0
7,995
// // Layout.swift // Amethyst // // Created by Ian Ynda-Hummel on 12/3/15. // Copyright © 2015 Ian Ynda-Hummel. All rights reserved. // import Foundation import Silica protocol WindowActivityCache { func windowIsActive(_ window: SIWindow) -> Bool } enum UnconstrainedDimension: Int { case horizontal case vertical } // Some window resizes reflect valid adjustments to the frame layout. // Some window resizes would not be allowed due to hard constraints. // This struct defines what adjustments to a particular window frame are allowed // and tracks its size as a proportion of available space (for use in resize calculations) struct ResizeRules { let isMain: Bool let unconstrainedDimension: UnconstrainedDimension let scaleFactor: CGFloat // the scale factor for the unconstrained dimension // given a new frame, decide which dimension will be honored and return its size func scaledDimension(_ frame: CGRect, negatePadding: Bool) -> CGFloat { let dimension: CGFloat = { switch unconstrainedDimension { case .horizontal: return frame.width case .vertical: return frame.height } }() let padding = UserConfiguration.shared.windowMargins() ? UserConfiguration.shared.windowMarginSize() : 0 return negatePadding ? dimension + padding : dimension } } struct FrameAssignment { let frame: CGRect let window: SIWindow let focused: Bool let screenFrame: CGRect let resizeRules: ResizeRules // the final frame is the desired frame, but shrunk to provide desired padding var finalFrame: CGRect { var ret = frame let padding = floor(UserConfiguration.shared.windowMarginSize() / 2) if UserConfiguration.shared.windowMargins() { ret.origin.x += padding ret.origin.y += padding ret.size.width -= 2 * padding ret.size.height -= 2 * padding } let windowMinimumWidth = UserConfiguration.shared.windowMinimumWidth() let windowMinimumHeight = UserConfiguration.shared.windowMinimumHeight() if windowMinimumWidth > ret.size.width { ret.origin.x -= ((windowMinimumWidth - ret.size.width) / 2) ret.size.width = windowMinimumWidth } if windowMinimumHeight > ret.size.height { ret.origin.y -= ((windowMinimumHeight - ret.size.height) / 2) ret.size.height = windowMinimumHeight } return ret } // Given a window frame and based on resizeRules, determine what the main pane ratio would be // this accounts for multiple main windows and primary vs non-primary being resized func impliedMainPaneRatio(windowFrame: CGRect) -> CGFloat { let oldDimension = resizeRules.scaledDimension(frame, negatePadding: false) let newDimension = resizeRules.scaledDimension(windowFrame, negatePadding: true) let implied = (newDimension / oldDimension) / resizeRules.scaleFactor return resizeRules.isMain ? implied : 1 - implied } fileprivate func perform() { var finalFrame = self.finalFrame var finalOrigin = finalFrame.origin // If this is the focused window then we need to shift it to be on screen regardless of size if focused { // Just resize the window first to see what the dimensions end up being // Sometimes applications have internal window requirements that are not exposed to us directly finalFrame.origin = window.frame().origin window.setFrame(finalFrame, withThreshold: CGSize(width: 1, height: 1)) // With the real height we can update the frame to account for the current size finalFrame.size = CGSize( width: max(window.frame().width, finalFrame.width), height: max(window.frame().height, finalFrame.height) ) finalOrigin.x = max(screenFrame.minX, min(finalOrigin.x, screenFrame.maxX - finalFrame.size.width)) finalOrigin.y = max(screenFrame.minY, min(finalOrigin.y, screenFrame.maxY - finalFrame.size.height)) } // Move the window to its final frame finalFrame.origin = finalOrigin window.setFrame(finalFrame, withThreshold: CGSize(width: 1, height: 1)) } } class ReflowOperation: Operation { let screen: NSScreen let windows: [SIWindow] let frameAssigner: FrameAssigner init(screen: NSScreen, windows: [SIWindow], frameAssigner: FrameAssigner) { self.screen = screen self.windows = windows self.frameAssigner = frameAssigner super.init() } } protocol FrameAssigner: WindowActivityCache { func performFrameAssignments(_ frameAssignments: [FrameAssignment]) } extension FrameAssigner { func performFrameAssignments(_ frameAssignments: [FrameAssignment]) { for frameAssignment in frameAssignments { if !windowIsActive(frameAssignment.window) { return } } for frameAssignment in frameAssignments { LogManager.log?.debug("Frame Assignment: \(frameAssignment)") frameAssignment.perform() } } } extension FrameAssigner where Self: Layout { func windowIsActive(_ window: SIWindow) -> Bool { return windowActivityCache.windowIsActive(window) } } extension NSScreen { func adjustedFrame() -> CGRect { var frame = UserConfiguration.shared.ignoreMenuBar() ? frameIncludingDockAndMenu() : frameWithoutDockOrMenu() if UserConfiguration.shared.windowMargins() { /* Inset for producing half of the full padding around screen as collapse only adds half of it to all windows */ let padding = floor(UserConfiguration.shared.windowMarginSize() / 2) frame.origin.x += padding frame.origin.y += padding frame.size.width -= 2 * padding frame.size.height -= 2 * padding } let windowMinimumWidth = UserConfiguration.shared.windowMinimumWidth() let windowMinimumHeight = UserConfiguration.shared.windowMinimumHeight() if windowMinimumWidth > frame.size.width { frame.origin.x -= (windowMinimumWidth - frame.size.width) / 2 frame.size.width = windowMinimumWidth } if windowMinimumHeight > frame.size.height { frame.origin.y -= (windowMinimumHeight - frame.size.height) / 2 frame.size.height = windowMinimumHeight } return frame } } protocol Layout { static var layoutName: String { get } static var layoutKey: String { get } var windowActivityCache: WindowActivityCache { get } func reflow(_ windows: [SIWindow], on screen: NSScreen) -> ReflowOperation func assignedFrame(_ window: SIWindow, of windows: [SIWindow], on screen: NSScreen) -> FrameAssignment? } protocol PanedLayout { var mainPaneRatio: CGFloat { get } func recommendMainPaneRawRatio(rawRatio: CGFloat) func shrinkMainPane() func expandMainPane() func increaseMainPaneCount() func decreaseMainPaneCount() } extension PanedLayout { func recommendMainPaneRatio(_ ratio: CGFloat) { guard 0 <= ratio && ratio <= 1 else { LogManager.log?.warning("tried to setMainPaneRatio out of range [0-1]: \(ratio)") return recommendMainPaneRawRatio(rawRatio: max(min(ratio, 1), 0)) } recommendMainPaneRawRatio(rawRatio: ratio) } func expandMainPane() { recommendMainPaneRatio(mainPaneRatio + UserConfiguration.shared.windowResizeStep()) } func shrinkMainPane() { recommendMainPaneRatio(mainPaneRatio - UserConfiguration.shared.windowResizeStep()) } } protocol StatefulLayout { func updateWithChange(_ windowChange: WindowChange) func nextWindowIDCounterClockwise() -> CGWindowID? func nextWindowIDClockwise() -> CGWindowID? }
35.533333
124
0.673171
231a26a82ad0bda5d449c6b3beaf07006666cb2f
3,934
// // MainRenderVM+ScreenShare.swift // AgoraMeetingUI // // Created by ZYP on 2021/6/16. // import Foundation import AgoraMeetingContext extension MainRenderVM { func registerNotiFormScreenShareExtension() { let observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()) let callback: CFNotificationCallback = { (_, observer, name, obj, userInfo) -> Void in if let observer = observer { let mySelf = Unmanaged<MainRenderVM>.fromOpaque(observer).takeUnretainedValue() mySelf.stopScreenShareByExtension() } } CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer, callback, "com.videoconference.shareendbyapp" as CFString, nil, .deliverImmediately) } func unregisterNotiFormScreenShareExtension() { let observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()) CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer, CFNotificationName(rawValue: "com.videoconference.shareendbyapp" as CFString), nil) } func closeScreenSharing() { screenContext.closeScreenSharing(success: {}) { [weak self](error) in self?.invokeShouldShowTip(text: error.localizedMessage) } } func openScreenSharing() { screenContext.openScreenSharing(success: { [weak self] in self?.handleScreen() }) { [weak self](error) in self?.invokeShouldShowTip(text: error.localizedMessage) } } func handleScreen() { if screenContext.isScreenSharing(), !screenContext.isScreenSharingByMyself() { /** start for other **/ return } if screenContext.isScreenSharing(), screenContext.isScreenSharingByMyself() { /** start for me **/ if let screenInfo = screenContext.getScreenInfo() { saveScreenParamInUserDefault(screenInfo: screenInfo) invokeRenderVMShouldShowSystemViewForScreenStart() return } } if !screenContext.isScreenSharing(){ /** stop **/ sendNotiToExtensionForStop() return } } func saveScreenParamInUserDefault(screenInfo: ScreenInfo) { let screenId = screenInfo.streamId let token = screenInfo.token let channelId = screenInfo.channelId let appId = screenInfo.appId let infoDict = Bundle.main.infoDictionary let temp = infoDict?["AppGroupId"] as? String if temp == nil { Log.errorText(text: "did not set AppGroupId in info.plist") } let appGroupId = temp ?? "group.io.agora.meetingInternal" let userDefault = UserDefaults(suiteName: appGroupId) userDefault?.setValue(appId, forKey: "appid") userDefault?.setValue(screenId, forKey: "screenid") userDefault?.setValue(token, forKey: "token") userDefault?.setValue(channelId, forKey: "channelid") userDefault?.synchronize() } func sendNotiToExtensionForStop() { Log.info(text:"sendNotiToExtensionForStop", tag: "MainRenderVM") let center = CFNotificationCenterGetDarwinNotifyCenter() let name = CFNotificationName("com.videoconference.exit" as CFString) let userInfo = [String : String]() as CFDictionary CFNotificationCenterPostNotification(center, name, nil, userInfo, true) } func stopScreenShareByExtension() { closeScreenSharing() } }
38.194175
121
0.598373
4a319fea790ab48c06b83ed2d5e5cb3eb601cb84
1,488
// // CareTeamStatus.swift // Asclepius // Module: R4 // // Copyright (c) 2022 Bitmatic Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** Indicates the status of the care team. URL: http://hl7.org/fhir/care-team-status ValueSet: http://hl7.org/fhir/ValueSet/care-team-status */ public enum CareTeamStatus: String, AsclepiusPrimitiveType { /// The care team has been drafted and proposed, but not yet participating in the coordination and /// delivery of patient care case proposed /// The care team is currently participating in the coordination and delivery of care case active /// The care team is temporarily on hold or suspended and not participating in the coordination and /// delivery of care. case suspended /// The care team was, but is no longer, participating in the coordination and delivery of care. case inactive /// The care team should have never existed. case enteredInError = "entered-in-error" }
33.818182
101
0.727823
189d308acbaf3ae21abcd08ce71b5eaca6b249da
10,871
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: compact_formats.proto // // For information on using the generated types, please see the documenation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that 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 } /// CompactBlock is a packaging of ONLY the data from a block that's needed to: /// 1. Detect a payment to your shielded Sapling address /// 2. Detect a spend of your shielded Sapling notes /// 3. Update your witnesses to generate new Sapling spend proofs. struct CompactBlock { // 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. /// the version of this wire format, for storage var protoVersion: UInt32 = 0 /// the height of this block var height: UInt64 = 0 var hash: Data = SwiftProtobuf.Internal.emptyData var prevHash: Data = SwiftProtobuf.Internal.emptyData var time: UInt32 = 0 /// (hash, prevHash, and time) OR (full header) var header: Data = SwiftProtobuf.Internal.emptyData /// compact transactions from this block var vtx: [CompactTx] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct CompactTx { // 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. /// Index and hash will allow the receiver to call out to chain /// explorers or other data structures to retrieve more information /// about this transaction. var index: UInt64 = 0 var hash: Data = SwiftProtobuf.Internal.emptyData /// The transaction fee: present if server can provide. In the case of a /// stateless server and a transaction with transparent inputs, this will be /// unset because the calculation requires reference to prior transactions. /// in a pure-Sapling context, the fee will be calculable as: /// valueBalance + (sum(vPubNew) - sum(vPubOld) - sum(tOut)) var fee: UInt32 = 0 var spends: [CompactSpend] = [] var outputs: [CompactOutput] = [] var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct CompactSpend { // 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 nf: Data = SwiftProtobuf.Internal.emptyData var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } struct CompactOutput { // 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 cmu: Data = SwiftProtobuf.Internal.emptyData var epk: Data = SwiftProtobuf.Internal.emptyData var ciphertext: Data = SwiftProtobuf.Internal.emptyData var unknownFields = SwiftProtobuf.UnknownStorage() init() {} } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "cash.z.wallet.sdk.rpc" extension CompactBlock: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".CompactBlock" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "protoVersion"), 2: .same(proto: "height"), 3: .same(proto: "hash"), 4: .same(proto: "prevHash"), 5: .same(proto: "time"), 6: .same(proto: "header"), 7: .same(proto: "vtx"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularUInt32Field(value: &self.protoVersion) case 2: try decoder.decodeSingularUInt64Field(value: &self.height) case 3: try decoder.decodeSingularBytesField(value: &self.hash) case 4: try decoder.decodeSingularBytesField(value: &self.prevHash) case 5: try decoder.decodeSingularUInt32Field(value: &self.time) case 6: try decoder.decodeSingularBytesField(value: &self.header) case 7: try decoder.decodeRepeatedMessageField(value: &self.vtx) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.protoVersion != 0 { try visitor.visitSingularUInt32Field(value: self.protoVersion, fieldNumber: 1) } if self.height != 0 { try visitor.visitSingularUInt64Field(value: self.height, fieldNumber: 2) } if !self.hash.isEmpty { try visitor.visitSingularBytesField(value: self.hash, fieldNumber: 3) } if !self.prevHash.isEmpty { try visitor.visitSingularBytesField(value: self.prevHash, fieldNumber: 4) } if self.time != 0 { try visitor.visitSingularUInt32Field(value: self.time, fieldNumber: 5) } if !self.header.isEmpty { try visitor.visitSingularBytesField(value: self.header, fieldNumber: 6) } if !self.vtx.isEmpty { try visitor.visitRepeatedMessageField(value: self.vtx, fieldNumber: 7) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CompactBlock, rhs: CompactBlock) -> Bool { if lhs.protoVersion != rhs.protoVersion {return false} if lhs.height != rhs.height {return false} if lhs.hash != rhs.hash {return false} if lhs.prevHash != rhs.prevHash {return false} if lhs.time != rhs.time {return false} if lhs.header != rhs.header {return false} if lhs.vtx != rhs.vtx {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CompactTx: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".CompactTx" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "index"), 2: .same(proto: "hash"), 3: .same(proto: "fee"), 4: .same(proto: "spends"), 5: .same(proto: "outputs"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularUInt64Field(value: &self.index) case 2: try decoder.decodeSingularBytesField(value: &self.hash) case 3: try decoder.decodeSingularUInt32Field(value: &self.fee) case 4: try decoder.decodeRepeatedMessageField(value: &self.spends) case 5: try decoder.decodeRepeatedMessageField(value: &self.outputs) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if self.index != 0 { try visitor.visitSingularUInt64Field(value: self.index, fieldNumber: 1) } if !self.hash.isEmpty { try visitor.visitSingularBytesField(value: self.hash, fieldNumber: 2) } if self.fee != 0 { try visitor.visitSingularUInt32Field(value: self.fee, fieldNumber: 3) } if !self.spends.isEmpty { try visitor.visitRepeatedMessageField(value: self.spends, fieldNumber: 4) } if !self.outputs.isEmpty { try visitor.visitRepeatedMessageField(value: self.outputs, fieldNumber: 5) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CompactTx, rhs: CompactTx) -> Bool { if lhs.index != rhs.index {return false} if lhs.hash != rhs.hash {return false} if lhs.fee != rhs.fee {return false} if lhs.spends != rhs.spends {return false} if lhs.outputs != rhs.outputs {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CompactSpend: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".CompactSpend" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "nf"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularBytesField(value: &self.nf) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.nf.isEmpty { try visitor.visitSingularBytesField(value: self.nf, fieldNumber: 1) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CompactSpend, rhs: CompactSpend) -> Bool { if lhs.nf != rhs.nf {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension CompactOutput: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".CompactOutput" static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "cmu"), 2: .same(proto: "epk"), 3: .same(proto: "ciphertext"), ] mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularBytesField(value: &self.cmu) case 2: try decoder.decodeSingularBytesField(value: &self.epk) case 3: try decoder.decodeSingularBytesField(value: &self.ciphertext) default: break } } } func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.cmu.isEmpty { try visitor.visitSingularBytesField(value: self.cmu, fieldNumber: 1) } if !self.epk.isEmpty { try visitor.visitSingularBytesField(value: self.epk, fieldNumber: 2) } if !self.ciphertext.isEmpty { try visitor.visitSingularBytesField(value: self.ciphertext, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: CompactOutput, rhs: CompactOutput) -> Bool { if lhs.cmu != rhs.cmu {return false} if lhs.epk != rhs.epk {return false} if lhs.ciphertext != rhs.ciphertext {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
36.116279
125
0.712354
fcec6d5f61ab4ef2c53a4796de98668dea6f3cfc
874
import Foundation class AuthRequestMessage: WebSocketMessage { public var AccessToken: String = "" private enum CodingKeys: String, CodingKey { case AccessToken = "access_token" } init(accessToken: String) { super.init("auth") self.ID = nil self.AccessToken = accessToken } required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let superdecoder = try values.superDecoder() try super.init(from: superdecoder) self.AccessToken = try values.decode(String.self, forKey: .AccessToken) } override public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(AccessToken, forKey: .AccessToken) try super.encode(to: encoder) } }
28.193548
79
0.667048
162333c5b1126764bb03b1d43aef6a92e5609f94
1,378
// // UIWindowProtocol.swift // Shared // // Copyright (c) 2019 Justin Peckner // // 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 public protocol UIWindowProtocol: AnyObject, AutoMockable { var rootViewController: UIViewController? { get set } func makeKeyAndVisible() } extension UIWindow: UIWindowProtocol {}
40.529412
82
0.753991
c1cc93f9cc1c6969ba74605384087fc43db40630
4,082
// // AutoCodable.swift // TemplatesTests // // Created by Ilya Puchka on 13/04/2018. // Copyright © 2018 Pixle. All rights reserved. // import Foundation protocol AutoDecodable: Swift.Decodable {} protocol AutoEncodable: Swift.Encodable {} protocol AutoCodable: AutoDecodable, AutoEncodable {} public struct CustomKeyDecodable: AutoDecodable { let stringValue: String let boolValue: Bool let intValue: Int enum CodingKeys: String, CodingKey { case intValue = "integer" // sourcery:inline:auto:CustomKeyDecodable.CodingKeys.AutoCodable case stringValue case boolValue // sourcery:end } } public struct CustomMethodsCodable: AutoCodable { let boolValue: Bool let intValue: Int? let optionalString: String? let requiredString: String let requiredStringWithDefault: String var computedPropertyToEncode: Int { return 0 } static let defaultIntValue: Int = 0 static let defaultRequiredStringWithDefault: String = "" static func decodeIntValue(from container: KeyedDecodingContainer<CodingKeys>) -> Int? { return (try? container.decode(String.self, forKey: .intValue)).flatMap(Int.init) } static func decodeBoolValue(from decoder: Decoder) throws -> Bool { return try decoder.container(keyedBy: CodingKeys.self).decode(Bool.self, forKey: .boolValue) } func encodeIntValue(to container: inout KeyedEncodingContainer<CodingKeys>) { try? container.encode(String(intValue ?? 0), forKey: .intValue) } func encodeBoolValue(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(boolValue, forKey: .boolValue) } func encodeComputedPropertyToEncode(to container: inout KeyedEncodingContainer<CodingKeys>) { try? container.encode(computedPropertyToEncode, forKey: .computedPropertyToEncode) } func encodeAdditionalValues(to encoder: Encoder) throws { } } public struct CustomContainerCodable: AutoCodable { let value: Int enum CodingKeys: String, CodingKey { case nested case value } static func decodingContainer(_ decoder: Decoder) throws -> KeyedDecodingContainer<CodingKeys> { return try decoder.container(keyedBy: CodingKeys.self) .nestedContainer(keyedBy: CodingKeys.self, forKey: .nested) } func encodingContainer(_ encoder: Encoder) -> KeyedEncodingContainer<CodingKeys> { var container = encoder.container(keyedBy: CodingKeys.self) return container.nestedContainer(keyedBy: CodingKeys.self, forKey: .nested) } } struct CustomCodingWithNotAllDefinedKeys: AutoCodable { let value: Int var computedValue: Int { return 0 } enum CodingKeys: String, CodingKey { case value // sourcery:inline:auto:CustomCodingWithNotAllDefinedKeys.CodingKeys.AutoCodable case computedValue // sourcery:end } func encodeComputedValue(to container: inout KeyedEncodingContainer<CodingKeys>) { try? container.encode(computedValue, forKey: .computedValue) } } struct SkipDecodingWithDefaultValueOrComputedProperty: AutoCodable { let value: Int let skipValue: Int = 0 var computedValue: Int { return 0 } enum CodingKeys: String, CodingKey { case value case computedValue } } struct SkipEncodingKeys: AutoCodable { let value: Int let skipValue: Int enum SkipEncodingKeys { case skipValue } } enum SimpleEnum: AutoCodable { case someCase case anotherCase } enum AssociatedValuesEnum: AutoCodable, Equatable { case someCase(id: Int, name: String) case anotherCase enum CodingKeys: String, CodingKey { case enumCaseKey = "type" // sourcery:inline:auto:AssociatedValuesEnum.CodingKeys.AutoCodable case someCase case anotherCase case id case name // sourcery:end } } enum AssociatedValuesEnumNoCaseKey: AutoCodable, Equatable { case someCase(id: Int, name: String) case anotherCase }
26.506494
100
0.709211
fcaa8dfefb4b0d48823e1b61776e20c507a88d49
699
// // DetailImageViewController.swift // Studio Lamda // // Created by Antonio Flores on 12/29/20. // import UIKit class DetailImageViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .red // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
23.3
106
0.665236
2f259a0c736ba47c00b936e5fad039ad9e4b5dca
9,023
// // GOCategoryNavigationView.swift // GOCategoryNavigationView // // Created by gaookey on 2021/7/28. // import UIKit import SnapKit import SDWebImage @objc public protocol GOCategoryNavigationViewDelegate: NSObjectProtocol { @objc optional func didEndDragging(categoryView: GOCategoryNavigationView, scrollView: UIScrollView) @objc optional func willBeginDragging(categoryView: GOCategoryNavigationView, scrollView: UIScrollView) } @objcMembers public class GOCategoryNavigationView: UIView { weak open var delegate: GOCategoryNavigationViewDelegate? public var didSelectItemHandler: ((_ indexPath: IndexPath, _ parameter: Any) -> ())? public var didScrollHandler: ((_ offsetX: CGFloat) -> ())? public var didEndDragging: (() -> ())? public var willBeginDragging: (() -> ())? public var dataSource: [[String]] { get { // 二维数组 直接返回 guard datas2.isEmpty else { return datas2 } // 一维数组 guard datas.count > number else { return [datas] } let data = stride(from: 0, through: datas.count - 1, by: number).map { (index) -> [String] in if (index + number) > datas.count { return Array(datas[index...]) } else { return Array(datas[index..<index+number]) } } return data } } public var contentSize: CGSize { get { guard !dataSource.isEmpty, let count = dataSource.max{ $0.count < $1.count }?.count else { return .zero } let width = UIScreen.main.bounds.width * CGFloat(dataSource.count) var rows: NSInteger = 0; if (count % options.columnCount == 0) { rows = count / options.columnCount; } else { rows = count / options.columnCount + 1; } var height = CGFloat(rows) * options.itemSize.height + (CGFloat(rows) - 1) * options.rowMargin; height = ceil(options.insetsTop + height + options.insetsBottom) return CGSize(width: width, height: height) } } public var scrollEnabled: Bool = true { willSet { collectionView.isScrollEnabled = newValue } } /// 点击事件需要传出去的参数。需要和dataSource对应 public var parameter = [[Any]]() private lazy var contentImageView: UIImageView = { let view = UIImageView() view.contentMode = .scaleAspectFill view.clipsToBounds = true view.backgroundColor = options.contentColor view.sd_setImage(with: URL(string: options.contentImage)) return view }() /// 接收的一维数组,手动转为二维数组 private var datas: [String] = [String]() /// 每页多少条 private var number: Int = 0 /// 接收的二维数组,无需转化。 private var datas2: [[String]] = [[String]]() private var options = GOCategoryNavigationOptions() private lazy var collectionView: UICollectionView = { let layout = GOCategoryNavigationFlowLayout() layout.itemSize = options.itemSize layout.columnCount = options.columnCount layout.columnMargin = options.columnMargin layout.rowMargin = options.rowMargin layout.edgeInsets = UIEdgeInsets(top: options.insetsTop, left: options.insetsLeftRight, bottom: options.insetsBottom, right: options.insetsLeftRight) layout.scrollDirection = .horizontal layout.delegate = self let view = UICollectionView(frame: .zero, collectionViewLayout: layout) view.showsHorizontalScrollIndicator = false if #available(iOS 11.0, *) { view.contentInsetAdjustmentBehavior = .never } view.register(GOCategoryNavigationCell.self, forCellWithReuseIdentifier: "GOCategoryNavigationCellID") view.delegate = self view.dataSource = self view.isPagingEnabled = true view.bounces = false view.backgroundColor = .clear return view }() private lazy var pageControl: UIPageControl = { let view = UIPageControl() view.isHidden = true return view }() public init(options: GOCategoryNavigationOptions) { super.init(frame: .zero) self.options = options initView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension GOCategoryNavigationView { /// 更新数据 /// - Parameters: /// - datas: 所有的数据 二维数组 /// - number: 每页显示多少条。需要和 GOCategoryNavigationOptions.columnCount 属性是整除的值 /// - heightHandler: 根据数据计算返回的view高度 /// - Returns: public func update(datas2: [[String]], completionHandler: ((_ height: CGFloat) -> ())?) { self.datas2 = datas2 config(completionHandler: completionHandler) } /// 更新数据 /// - Parameters: /// - datas: 所有的数据 /// - number: 每页显示多少条 /// - heightHandler: 根据数据计算返回的view高度 /// - Returns: public func update(datas: [String], number: Int, completionHandler: ((_ height: CGFloat) -> ())?) { self.datas = datas self.number = number config(completionHandler: completionHandler) } private func config(completionHandler: ((_ height: CGFloat) -> ())?) { pageControl.isHidden = options.isHiddenPageControl if !options.isHiddenPageControl { // 不隐藏 pageControl pageControl.numberOfPages = dataSource.count pageControl.currentPage = 0 pageControl.isHidden = dataSource.count <= 1 } collectionView.reloadData() collectionView.snp.updateConstraints { make in make.height.equalTo(contentSize.height) } if options.isHiddenPageControl == false, dataSource.count > 1 { completionHandler?(contentSize.height + 20) } else { completionHandler?(contentSize.height) } } } extension GOCategoryNavigationView: GOCategoryNavigationFlowLayoutDelegate { func contentSize(view: GOCategoryNavigationFlowLayout) -> CGSize { return contentSize } } extension GOCategoryNavigationView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { public func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource.count } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource[section].count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GOCategoryNavigationCellID", for: indexPath) as! GOCategoryNavigationCell cell.options = options cell.data = dataSource[indexPath.section][indexPath.row] return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard parameter.count > indexPath.section, parameter[indexPath.section].count > indexPath.row else { return } let data = parameter[indexPath.section][indexPath.row] didSelectItemHandler?(indexPath, data) } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate == false { scrollViewDidEndDecelerating(scrollView) } delegate?.didEndDragging?(categoryView: self, scrollView: scrollView) didEndDragging?() } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { pageControl.currentPage = Int(scrollView.contentOffset.x / UIScreen.main.bounds.width) } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { delegate?.willBeginDragging?(categoryView: self, scrollView: scrollView) willBeginDragging?() } public func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetX = scrollView.contentOffset.x / (contentSize.width - UIScreen.main.bounds.width) didScrollHandler?(offsetX) } } extension GOCategoryNavigationView { private func initView() { addSubview(contentImageView) addSubview(collectionView) addSubview(pageControl) contentImageView.snp.makeConstraints { make in make.edges.equalToSuperview() } collectionView.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview() make.height.equalTo(0) } pageControl.snp.makeConstraints { make in make.top.equalTo(collectionView.snp.bottom) make.leading.trailing.equalToSuperview() make.height.equalTo(20) } } }
34.837838
157
0.635044
50bd77fa8ed8fae0fe4f3b196b8afe3c9a3084d0
1,145
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SwiftSCAD", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "SwiftSCAD", targets: ["SwiftSCAD"]), ], dependencies: [ .package( url: "https://github.com/apple/swift-collections.git", .upToNextMajor(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 this package depends on. .target( name: "SwiftSCAD", dependencies: [ .product(name: "Collections", package: "swift-collections") ]), .testTarget( name: "Tests", dependencies: ["SwiftSCAD"], resources: [.copy("SCAD")] ) ] )
31.805556
117
0.582533
2059816e13c4d3688fd50be1bc7314332d1f0187
2,674
class Solution { // Solution @ Sergey Leschev, Belarusian State University // 785. Is Graph Bipartite // There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties: // There are no self-edges (graph[u] does not contain u). // There are no parallel edges (graph[u] does not contain duplicate values). // If v is in graph[u], then u is in graph[v] (the graph is undirected). // The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them. // A graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B. // Return true if and only if it is bipartite. // Finds if the given graph is bipartite. // - Parameter graph: An undirected `graph`. // - Returns: True if the given graph is bipartite, otherwise returns false. // Example 1: // Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]] // Output: false // Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other. // Example 2: // Input: graph = [[1,3],[0,2],[1,3],[0,2]] // Output: true // Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}. // Constraints: // graph.length == n // 1 <= n <= 100 // 0 <= graph[u].length < n // 0 <= graph[u][i] <= n - 1 // graph[u] does not contain u. // All the values of graph[u] are unique. // If graph[u] contains v, then graph[v] contains u. // - Complexity: // - time: O(n + e), where n is the number of nodes in the graph, and e is the number of edges in the graph. // - space: O(n), where n is the number of nodes in the graph. func isBipartite(_ graph: [[Int]]) -> Bool { var colors = Array(repeating: -1, count: graph.count) for i in 0..<graph.count where colors[i] == -1 && !validColor(&colors, 0, graph, i) { return false } return true } fileprivate func validColor(_ colors: inout [Int], _ color: Int, _ graph: [[Int]], _ index: Int) -> Bool { if colors[index] != -1 { return colors[index] == color } colors[index] = color for neighbor in graph[index] where !validColor(&colors, 1 - color, graph, neighbor) { return false } return true } }
47.75
328
0.633508
ddf662b71f83dc0d04e63d215130798ac142099d
3,042
import AppKit final class BN0035: ClockView { // MARK: - Types enum Style: String, ClockStyle { case bkbkg = "BKBKG" case whbkg = "WHBKG" case slbrg = "SLBRG" var description: String { switch self { case .bkbkg: return "Black" case .whbkg: return "White" case .slbrg: return "Silver/Brown" } } var backgroundColor: NSColor { switch self { case .bkbkg, .whbkg: return Color.darkBackground case .slbrg: return Color.leather } } var faceColor: NSColor { switch self { case .bkbkg: return backgroundColor case .whbkg: return NSColor(white: 0.996, alpha: 1) case .slbrg: return NSColor(white: 0.83, alpha: 1) } } var minuteColor: NSColor { switch self { case .bkbkg: return Color.white case .whbkg, .slbrg: return Color.black } } static var `default`: ClockStyle { return Style.bkbkg } static var all: [ClockStyle] { return [Style.bkbkg, Style.whbkg, Style.slbrg] } } // MARK: - ClockView override class var modelName: String { return "BN0035" } override var styleName: String { set { style = Style(rawValue: newValue) ?? Style.default } get { return style.description } } override class var styles: [ClockStyle] { return Style.all } override func initialize() { super.initialize() style = Style.default } // MARK: - Drawing override var fontName: String { return "HelveticaNeue" } // override func draw(day: Int) { // let dateArrowColor = Color.red // let dateBackgroundColor = NSColor(srgbRed: 0.894, green: 0.933, blue: 0.965, alpha: 1) // let clockWidth = clockFrame.size.width // let dateWidth = clockWidth * 0.057416268 // let dateFrame = CGRect( // x: clockFrame.origin.x + ((clockWidth - dateWidth) / 2.0), // y: clockFrame.origin.y + (clockWidth * 0.199362041), // width: dateWidth, // height: clockWidth * 0.071770335 // ) // // dateBackgroundColor.setFill() // NSBezierPath.fill(dateFrame) // // style.minuteColor.setFill() // // let paragraph = NSMutableParagraphStyle() // paragraph.alignment = .center // // let string = NSAttributedString(string: "\(day)", attributes: [ // .font: NSFont(name: "HelveticaNeue-Light", size: clockWidth * 0.044657098)!, // .kern: -1, // .paragraphStyle: paragraph // ]) // // var stringFrame = dateFrame // stringFrame.origin.y -= dateFrame.size.height * 0.12 // string.draw(in: stringFrame) // // dateArrowColor.setFill() // let y = dateFrame.maxY + (clockWidth * 0.015948963) // let height = clockWidth * 0.022328549 // let pointDip = clockWidth * 0.009569378 // // let path = NSBezierPath() // path.move(to: CGPoint(x: dateFrame.minX, y: y)) // path.line(to: CGPoint(x: dateFrame.minX, y: y - height)) // path.line(to: CGPoint(x: dateFrame.midX, y: y - height - pointDip)) // path.line(to: CGPoint(x: dateFrame.maxX, y: y - height)) // path.line(to: CGPoint(x: dateFrame.maxX, y: y)) // path.line(to: CGPoint(x: dateFrame.midX, y: y - pointDip)) // path.fill() // } }
22.20438
90
0.646285
291093512919e5e26983658bff8b0f321add5713
9,187
// // NationalitySelectionVC.swift // EarthLanguage // // Created by apple on 2017/9/7. // Copyright © 2017年 EarthLanguage. All rights reserved. // import UIKit import AudioToolbox typealias ReloadAllTranslationVCOne = () -> Void class NationalitySelectionVC: UIView,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout { @IBOutlet weak var inputType: LGFMagicCollectionView!/// 输入切换 @IBOutlet weak var inputTypePage: UIPageControl!/// 输入切换page显示 @IBOutlet weak var oneNat: LGFMagicButton!/// 第一个国籍 @IBOutlet weak var twoNat: LGFMagicButton!/// 第二个国籍 @IBOutlet weak var threeNat: LGFMagicButton!/// 第三个国籍 @IBOutlet weak var oneNatImg: LGFMagicImageView!/// 第一个国籍国旗 @IBOutlet weak var twoNatImg: LGFMagicImageView!/// 第二个国籍国旗 @IBOutlet weak var threeNatImg: LGFMagicImageView!/// 第三个国籍国旗 @IBOutlet weak var oneNatTitle: LGFMagicLabel!/// 第一个国籍名字 @IBOutlet weak var twoNatTitle: LGFMagicLabel!/// 第二个国籍名字 @IBOutlet weak var threeNatTitle: LGFMagicLabel!/// 第三个国籍名字 @IBOutlet weak var topHelpTitle: UIButton!/// 上帮助提示 @IBOutlet weak var bottomHelpTitle: UIButton!/// 下帮助提示 @IBOutlet weak var showHelp: LGFMagicButton!/// 第一个国籍名字 @IBOutlet weak var speekImage: LGFMagicImageView! var natButtons = [LGFMagicButton]()/// 所有国籍按钮数组 var natImgs = [LGFMagicImageView]()/// 所有国籍国旗数组 var natTitles = [LGFMagicLabel]()/// 所有国籍国旗数组 var reloadAllTranslationVC:ReloadAllTranslationVCOne? /// 初始化 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() lgf_After(seconds: 0.1) { lgf_UserDefaults.set(true, forKey: "login_bool") /// 输入方式选择 self.inputType.reloadData() DispatchQueue.main.async { self.inputType.scrollToItem(at: IndexPath.init(item: self.inputTypePage.currentPage, section: 0), at: .left, animated: false) } self.natButtons += [self.oneNat, self.twoNat, self.threeNat] self.natImgs += [self.oneNatImg, self.twoNatImg, self.threeNatImg] self.natTitles += [self.oneNatTitle, self.twoNatTitle, self.threeNatTitle] self.inputTypePage.currentPage = lgf_UserDefaults.integer(forKey: "input_type_select_item") self.bottomHelpTitle.setTitle(self.inputTypePage.currentPage == 0 ? "手动输入" : "语音输入", for: .normal) self.natImgsAndTitlesSet() /// 遍历 natDict 里所有的字典 for (_, item) in self.natButtons.enumerated() { if item.magicType == lgf_GetSelectPeople().value(forKey: "selectpeople") as! String { self.natBtnOnSelect(item) } } } } func startSpeek() -> Void { self.speekImage.animationImages = [UIImage.init(named: "speek_music_zero")!, UIImage.init(named: "speek_music_one")!, UIImage.init(named: "speek_music_two")!, UIImage.init(named: "speek_music_three")!, UIImage.init(named: "speek_music_four")!] self.speekImage.animationDuration = 1.5 self.speekImage.animationRepeatCount = Int.max self.speekImage.startAnimating() } func stopSpeek() -> Void { self.speekImage.stopAnimating() self.speekImage.image = UIImage.init(named: "speek_music_zero") } /// 国旗图片 国籍名字 设置 func natImgsAndTitlesSet() -> Void { /// 设置选中的国籍国旗图片 for (_, item) in self.natImgs.enumerated() { item.image = UIImage.init(named: ((lgf_SelectLanguaged.value(forKey: item.magicType) as! NSMutableDictionary).value(forKey: "languagedata") as! NSMutableDictionary).value(forKey: "imagename") as! String) } /// 设置选中的国籍名字 for (_, item) in self.natTitles.enumerated() { item.text = ((lgf_SelectLanguaged.value(forKey: item.magicType) as! NSMutableDictionary).value(forKey: "languagedata") as! NSMutableDictionary).value(forKey: "countryname") as? String } } /// 点击按钮 @IBAction func natBtnOnSelect(_ sender: LGFMagicButton) { if sender == showHelp { self.topHelpTitle.setTitle("长按进入帮助页面", for: .normal) } else { self.topHelpTitle.setTitle("长按切换国籍", for: .normal) /// 遍历 natDict 里所有的字典 找到点击的按钮对应的字典 for (key, value) in lgf_SelectLanguaged{ (value as! NSMutableDictionary).setValue((key as! String) == sender.magicType ? "true" : "false", forKey: "selectbool") lgf_SelectLanguaged.setValue(value, forKey: key as! String) } /// 遍历 NatButtons 里所有的按钮 找到点击的按钮 for (_, item) in self.natButtons.enumerated() { item.setBackgroundImage(UIImage.init(named: item == sender ? (lgf_SelectLanguaged.value(forKey: item.magicType) as! NSMutableDictionary).value(forKey: "bgimage") as! String : (lgf_SelectLanguaged.value(forKey: item.magicType) as! NSMutableDictionary).value(forKey: "defuleimage") as! String), for: .normal) item.shadowOpacity = item == sender ? 1.0 : 0.0 } for (_, item) in self.natTitles.enumerated() { item.textColor = item.magicType == sender.magicType ? UIColor.white : "D4D4D4".lgf_UIColor(alpha: 1.0) } /// inputType边框颜色设置 //self.inputType.borderColor = ((lgf_SelectLanguaged.value(forKey: sender.magicType) as! NSMutableDictionary).value(forKey: "peoplecolor") as! String).lgf_UIColor() lgf_SelectLanguaged.write(toFile: SelectLanguagePath, atomically: true) self.inputTypePage.currentPageIndicatorTintColor = (lgf_GetSelectPeople().value(forKey: "peoplecolor") as! String).lgf_UIColor(alpha: 1.0) self.inputType.reloadData() } } /// 取消点击按钮 @IBAction func natBtnUnSelect(_ sender: Any) { self.topHelpTitle.setTitle("", for: .normal) } /// 进入国旗选择 @IBAction func goFlagSelection(_ sender: UILongPressGestureRecognizer) { if sender.state == .began { AudioServicesPlaySystemSound(1520) sender.cancelsTouchesInView = false let VC = lgf_XibView(NibName: "FlagSelectionVC", index: 0) as! FlagSelectionVC VC.languageData = lgf_SelectLanguaged.value(forKey: (sender.view as! LGFMagicButton).magicType) as! NSMutableDictionary VC.reloadNationalitySelectionVC = { self.natImgsAndTitlesSet() } } } @IBAction func goHelpView(_ sender: UILongPressGestureRecognizer) { if sender.state == .began { AudioServicesPlaySystemSound(1520) sender.cancelsTouchesInView = false let VC = lgf_XibView(NibName: "HelpVC", index: 0) as! HelpVC VC.reloadAllTranslationVC = { self.reloadAllTranslationVC!() } lgf_LastView.addSubview(VC) } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: self.inputType.width, height: self.inputType.height) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let nib = UINib.init(nibName: "InputTypeCell", bundle: Bundle.main) collectionView.register(nib, forCellWithReuseIdentifier: "InputTypeCell") let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InputTypeCell", for: indexPath) as! InputTypeCell if indexPath.item == 0 { cell.inputImage.setBackgroundImage(UIImage.init(named: "keyboard_image"), for: .normal) cell.inputImage.setBackgroundImage(UIImage.init(named: "keyboard_image"), for: .highlighted) } else if indexPath.item == 1 { cell.inputImage.setBackgroundImage(UIImage.init(named: "microphone_image"), for: .normal) cell.inputImage.setBackgroundImage(UIImage.init(named: "sound_recording_icon_off"), for: .highlighted) } else { } cell.inputImage.tag = indexPath.item cell.reloadAllTranslationVC = {self.reloadAllTranslationVC!()} return cell } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.inputTypePage.currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.width) switch self.inputTypePage.currentPage { case 0: self.bottomHelpTitle.setTitle("键盘输入", for: .normal) break case 1: self.bottomHelpTitle.setTitle("语音输入", for: .normal) break default: break } lgf_UserDefaults.set(self.inputTypePage.currentPage, forKey: "input_type_select_item") } }
46.39899
322
0.652553
db90e82634e1d2e8cf453cb6e3187f12dc9964f1
31,275
// // File.swift // // // Created by Arthur Guiot on 2020-03-04. // import Foundation import XCTest import Euler #if os(macOS) class MatrixTests: XCTestCase { func assertEqual(_ m1: Matrix, _ m2: Matrix) { XCTAssertEqual(m1.rows, m2.rows) XCTAssertEqual(m1.columns, m2.columns) for r in 0..<m1.rows { for c in 0..<m1.columns { XCTAssertEqual(m1[r, c], m2[r, c]) } } } func assertEqual(_ m1: Matrix, _ m2: Matrix, accuracy epsilon: Double) { XCTAssertEqual(m1.rows, m2.rows) XCTAssertEqual(m1.columns, m2.columns) for r in 0..<m1.rows { for c in 0..<m1.columns { XCTAssertEqual(m1[r, c], m2[r, c], accuracy: epsilon) } } } /* Since Matrix is a struct, if you copy the matrix to another variable, Swift doesn't actually copy the memory until you modify the new variable. Because Matrix uses Accelerate framework to modify its contents, we want to make sure that it doesn't modify the original array, only the copy. This helper function forces Swift to make a copy. */ func copy(_ m: Matrix) -> Matrix { var q = m q[0,0] = m[0,0] // force Swift to make a copy return q } } // MARK: - Creating matrices extension MatrixTests { func testCreateFromArray() { let a = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]] let m = Matrix(a) XCTAssertEqual(m.rows, a.count) XCTAssertEqual(m.columns, a[0].count) for r in 0..<m.rows { for c in 0..<m.columns { XCTAssertEqual(m[r, c], a[r][c]) } } } func testCreateFromArrayRange() { let a = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] for i in 0..<3 { for j in i..<3 { let m = Matrix(a, range: i...j) XCTAssertEqual(m.rows, a.count) XCTAssertEqual(m.columns, j - i + 1) for r in 0..<m.rows { for c in i...j { XCTAssertEqual(m[r, c - i], a[r][c]) } } } } } func testCreateFromRowVector() { let v = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] let m = Matrix(v) XCTAssertEqual(m.rows, 1) XCTAssertEqual(m.columns, v.count) for c in 0..<m.columns { XCTAssertEqual(m[0, c], v[c]) } } func testCreateFromColumnVector() { let v = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] let m = Matrix(v, isColumnVector: true) XCTAssertEqual(m.rows, v.count) XCTAssertEqual(m.columns, 1) for r in 0..<m.rows { XCTAssertEqual(m[r, 0], v[r]) } } func testCreateRowVectorFromRange() { let m1 = Matrix(10..<20) XCTAssertEqual(m1.rows, 10) for r in 0..<m1.rows { XCTAssertEqual(m1[r, 0], Double(r + 10)) } let m2 = Matrix(-10...10) XCTAssertEqual(m2.rows, 21) for r in 0..<m2.rows { XCTAssertEqual(m2[r, 0], Double(-10 + r)) } } func testCreateColumnVectorFromRange() { let m1 = Matrix(10..<20, isColumnVector: true) XCTAssertEqual(m1.columns, 10) for c in 0..<m1.columns { XCTAssertEqual(m1[0, c], Double(c + 10)) } let m2 = Matrix(-10...10, isColumnVector: true) XCTAssertEqual(m2.columns, 21) for c in 0..<m2.columns { XCTAssertEqual(m2[0, c], Double(-10 + c)) } } func testZeros() { let m = Matrix.zeros(rows: 3, columns: 3) for r in 0..<3 { for c in 0..<3 { XCTAssertEqual(m[r, c], 0) } } } func testIdentityMatrix() { let m = Matrix.identity(size: 3) XCTAssertEqual(m[0, 0], 1) XCTAssertEqual(m[0, 1], 0) XCTAssertEqual(m[0, 2], 0) XCTAssertEqual(m[1, 0], 0) XCTAssertEqual(m[1, 1], 1) XCTAssertEqual(m[1, 2], 0) XCTAssertEqual(m[2, 0], 0) XCTAssertEqual(m[2, 1], 0) XCTAssertEqual(m[2, 2], 1) } func testTile() { let v = Matrix([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]) let m = v.tile(5) XCTAssertEqual(m.rows, 5) XCTAssertEqual(m.columns, v.columns) for r in 0..<m.rows { for c in 0..<m.columns { XCTAssertEqual(m[r, c], v[c]) } } assertEqual(v, v.tile(1)) } } // MARK: - Subscripts extension MatrixTests { func testChangeMatrixUsingSubscript() { var m = Matrix.ones(rows: 3, columns: 3) for r in 0..<3 { for c in 0..<3 { m[r, c] = 100*(Double(r)+1) + 10*(Double(c)+1) } } for r in 0..<3 { for c in 0..<3 { XCTAssertEqual(m[r, c], 100*(Double(r)+1) + 10*(Double(c)+1)) } } } func testSubscriptRowVector() { let v = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] let m = Matrix(v) for c in 0..<m.columns { XCTAssertEqual(m[c], v[c]) XCTAssertEqual(m[c], m[0, c]) } } func testSubscriptColumnVector() { let v = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] let m = Matrix(v, isColumnVector: true) for r in 0..<m.rows { XCTAssertEqual(m[r], v[r]) XCTAssertEqual(m[r], m[r, 0]) } } func testSubscriptRowGetter() { let a = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]] let m = Matrix(a) let M = copy(m) let r0 = m[row: 0] XCTAssertEqual(r0[0], 1.0) XCTAssertEqual(r0[1], 2.0) let r1 = m[row: 1] XCTAssertEqual(r1[0], 3.0) XCTAssertEqual(r1[1], 4.0) let r2 = m[row: 2] XCTAssertEqual(r2[0], 5.0) XCTAssertEqual(r2[1], 6.0) assertEqual(m, M) } func testSubscriptRowSetter() { let a = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]] var m = Matrix(a) m[row: 0] = Matrix([-1, -2]) XCTAssertEqual(m[0, 0], -1.0) XCTAssertEqual(m[0, 1], -2.0) m[row: 1] = Matrix([-3, -4]) XCTAssertEqual(m[1, 0], -3.0) XCTAssertEqual(m[1, 1], -4.0) m[row: 2] = Matrix([-5, -6]) XCTAssertEqual(m[2, 0], -5.0) XCTAssertEqual(m[2, 1], -6.0) } func testSubscriptRowsGetter() { let a = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] let m = Matrix(a) let M = copy(m) let r0 = m[rows: 0...0] XCTAssertEqual(r0.rows, 1) XCTAssertEqual(r0.columns, 3) XCTAssertEqual(r0[0, 0], 1.0) XCTAssertEqual(r0[0, 1], 2.0) XCTAssertEqual(r0[0, 2], 3.0) let r1 = m[rows: 0...1] XCTAssertEqual(r1.rows, 2) XCTAssertEqual(r1.columns, 3) XCTAssertEqual(r1[0, 0], 1.0) XCTAssertEqual(r1[0, 1], 2.0) XCTAssertEqual(r1[0, 2], 3.0) XCTAssertEqual(r1[1, 0], 4.0) XCTAssertEqual(r1[1, 1], 5.0) XCTAssertEqual(r1[1, 2], 6.0) let r2 = m[rows: 0...2] assertEqual(r2, m) let r3 = m[rows: 1...2] XCTAssertEqual(r3.rows, 2) XCTAssertEqual(r3.columns, 3) XCTAssertEqual(r3[0, 0], 4.0) XCTAssertEqual(r3[0, 1], 5.0) XCTAssertEqual(r3[0, 2], 6.0) XCTAssertEqual(r3[1, 0], 7.0) XCTAssertEqual(r3[1, 1], 8.0) XCTAssertEqual(r3[1, 2], 9.0) let r4 = m[rows: 2...2] XCTAssertEqual(r4.rows, 1) XCTAssertEqual(r4.columns, 3) XCTAssertEqual(r4[0, 0], 7.0) XCTAssertEqual(r4[0, 1], 8.0) XCTAssertEqual(r4[0, 2], 9.0) assertEqual(m, M) } func testSubscriptRowsSetter() { var m = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) m[rows: 0...0] = Matrix([-1, -2, -3]) assertEqual(m, Matrix([[-1, -2, -3], [4, 5, 6], [7, 8, 9]])) m[rows: 0...1] = Matrix([[10, 20, 30], [-4, -5, -6]]) assertEqual(m, Matrix([[10, 20, 30], [-4, -5, -6], [7, 8, 9]])) m[rows: 0...2] = Matrix([[-10, -20, -30], [40, 50, 60], [-7, -8, -9]]) assertEqual(m, Matrix([[-10, -20, -30], [40, 50, 60], [-7, -8, -9]])) m[rows: 1...2] = Matrix([[-40, -50, -60], [70, 80, 90]]) assertEqual(m, Matrix([[-10, -20, -30], [-40, -50, -60], [70, 80, 90]])) m[rows: 2...2] = Matrix([-70, -80, -90]) assertEqual(m, Matrix([[-10, -20, -30], [-40, -50, -60], [-70, -80, -90]])) } func testSubscriptRowIndicesGetter() { let m = Matrix([[1, 2], [3, 4], [5, 6]]) let M = copy(m) assertEqual(m[rows: [0]], [1, 2]) assertEqual(m[rows: [1]], [3, 4]) assertEqual(m[rows: [2]], [5, 6]) assertEqual(m[rows: [0, 1]], Matrix([[1, 2], [3, 4]])) assertEqual(m[rows: [1, 0]], Matrix([[3, 4], [1, 2]])) assertEqual(m[rows: [0, 2]], Matrix([[1, 2], [5, 6]])) assertEqual(m[rows: [2, 0]], Matrix([[5, 6], [1, 2]])) assertEqual(m[rows: [2, 1, 0]], Matrix([[5, 6], [3, 4], [1, 2]])) assertEqual(m, M) } func testSubscriptColumnGetter() { let a = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]] let m = Matrix(a) let M = copy(m) let c0 = m[column: 0] XCTAssertEqual(c0[0], 1.0) XCTAssertEqual(c0[1], 3.0) XCTAssertEqual(c0[2], 5.0) let c1 = m[column: 1] XCTAssertEqual(c1[0], 2.0) XCTAssertEqual(c1[1], 4.0) XCTAssertEqual(c1[2], 6.0) assertEqual(m, M) } func testSubscriptColumnSetter() { let a = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]] var m = Matrix(a) m[column: 0] = Matrix([-1, -3, -5], isColumnVector: true) XCTAssertEqual(m[0, 0], -1.0) XCTAssertEqual(m[1, 0], -3.0) XCTAssertEqual(m[2, 0], -5.0) m[column: 1] = Matrix([-2, -4, -6], isColumnVector: true) XCTAssertEqual(m[0, 1], -2.0) XCTAssertEqual(m[1, 1], -4.0) XCTAssertEqual(m[2, 1], -6.0) } func testSubscriptColumnsGetter() { let a = [[1.0, 4.0, 7.0], [2.0, 5.0, 8.0], [3.0, 6.0, 9.0]] let m = Matrix(a) let M = copy(m) let r0 = m[columns: 0...0] XCTAssertEqual(r0.rows, 3) XCTAssertEqual(r0.columns, 1) XCTAssertEqual(r0[0, 0], 1.0) XCTAssertEqual(r0[1, 0], 2.0) XCTAssertEqual(r0[2, 0], 3.0) let r1 = m[columns: 0...1] XCTAssertEqual(r1.rows, 3) XCTAssertEqual(r1.columns, 2) XCTAssertEqual(r1[0, 0], 1.0) XCTAssertEqual(r1[1, 0], 2.0) XCTAssertEqual(r1[2, 0], 3.0) XCTAssertEqual(r1[0, 1], 4.0) XCTAssertEqual(r1[1, 1], 5.0) XCTAssertEqual(r1[2, 1], 6.0) let r2 = m[columns: 0...2] assertEqual(r2, m) let r3 = m[columns: 1...2] XCTAssertEqual(r3.rows, 3) XCTAssertEqual(r3.columns, 2) XCTAssertEqual(r3[0, 0], 4.0) XCTAssertEqual(r3[1, 0], 5.0) XCTAssertEqual(r3[2, 0], 6.0) XCTAssertEqual(r3[0, 1], 7.0) XCTAssertEqual(r3[1, 1], 8.0) XCTAssertEqual(r3[2, 1], 9.0) let r4 = m[columns: 2...2] XCTAssertEqual(r4.rows, 3) XCTAssertEqual(r4.columns, 1) XCTAssertEqual(r4[0, 0], 7.0) XCTAssertEqual(r4[1, 0], 8.0) XCTAssertEqual(r4[2, 0], 9.0) assertEqual(m, M) } func testSubscriptColumnsSetter() { var m = Matrix([[1, 4, 7], [2, 5, 8], [3, 6, 9]]) m[columns: 0...0] = Matrix([[-1], [-2], [-3]]) assertEqual(m, Matrix([[-1, 4, 7], [-2, 5, 8], [-3, 6, 9]])) m[columns: 0...1] = Matrix([[10, -4], [20, -5], [30, -6]]) assertEqual(m, Matrix([[10, -4, 7], [20, -5, 8], [30, -6, 9]])) m[columns: 0...2] = Matrix([[-10, 40, -7], [-20, 50, -8], [-30, 60, -9]]) assertEqual(m, Matrix([[-10, 40, -7], [-20, 50, -8], [-30, 60, -9]])) m[columns: 1...2] = Matrix([[-40, 70], [-50, 80], [-60, 90]]) assertEqual(m, Matrix([[-10, -40, 70], [-20, -50, 80], [-30, -60, 90]])) m[columns: 2...2] = Matrix([[-70], [-80], [-90]]) assertEqual(m, Matrix([[-10, -40, -70], [-20, -50, -80], [-30, -60, -90]])) } func testSubscriptScalar() { let a1 = [[7.0, 6.0], [5.0, 4.0], [3.0, 2.0]] let m1 = Matrix(a1) XCTAssertEqual(m1.scalar, a1[0][0]) let a2 = [[9.0]] let m2 = Matrix(a2) XCTAssertEqual(m2.scalar, a2[0][0]) } func testToArray() { let a:[[Double]] = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] let m = Matrix(a) XCTAssertEqual(m.array, a) } } // MARK: - Operations extension MatrixTests { func testInverse() { let m = Matrix([[1, 2, 3], [0, 4, 0], [3, 2, 1]]) let M = copy(m) let i = m.inverse() XCTAssertEqual(m.rows, i.rows) XCTAssertEqual(m.columns, i.columns) XCTAssertEqual(i[0, 0], -0.125) XCTAssertEqual(i[0, 1], -0.125) XCTAssertEqual(i[0, 2], 0.375) XCTAssertEqual(i[1, 0], 0) XCTAssertEqual(i[1, 1], 0.25) XCTAssertEqual(i[1, 2], 0) XCTAssertEqual(i[2, 0], 0.375) XCTAssertEqual(i[2, 1], -0.125) XCTAssertEqual(i[2, 2], -0.125) let o = i.inverse() assertEqual(m, o) // make sure accelerate framework magic didn't overwrite the original assertEqual(m, M) } func testInverseIdentityMatrix() { let m = Matrix.identity(size: 3) let i = m.inverse() assertEqual(m, i) } func testInverseSingularMatrix() { // Note: currently non-invertible matrices give an assertion. // Either trap that with a test (how?), or maybe return nil? } func testTranspose() { let m = Matrix([[1, 2], [3, 4], [5, 6]]) let M = copy(m) let t = m.transpose() XCTAssertEqual(m.rows, t.columns) XCTAssertEqual(m.columns, t.rows) for r in 0..<m.rows { for c in 0..<m.columns { XCTAssertEqual(m[r, c], t[c, r]) } } let o = t.transpose() assertEqual(m, o) assertEqual(m, M) } } // MARK: - Arithmetic extension MatrixTests { func testAddMatrixMatrix() { let a = Matrix([[ 1, 2], [ 3, 4], [ 5, 6]]) let b = Matrix([[10, 20], [30, 40], [50, 60]]) let c = Matrix([[11, 22], [33, 44], [55, 66]]) let A = copy(a) let B = copy(b) assertEqual(a + b, c) assertEqual(a, A) assertEqual(b, B) } func testAddMatrixRowVector() { let a = Matrix([[10, 20], [30, 40], [50, 60]]) let b = Matrix([5, 10]) let c = Matrix([[15, 30], [35, 50], [55, 70]]) let A = copy(a) let B = copy(b) assertEqual(a + b, c) assertEqual(a, A) assertEqual(b, B) } func testAddMatrixColumnVector() { let a = Matrix([[10, 20], [30, 40], [50, 60]]) let b = Matrix([5, 10, 1], isColumnVector: true) let c = Matrix([[15, 25], [40, 50], [51, 61]]) let A = copy(a) let B = copy(b) assertEqual(a + b, c) assertEqual(a, A) assertEqual(b, B) } func testAddMatrixScalar() { let a = Matrix([[ 1, 2], [ 3, 4], [ 5, 6]]) let b = Matrix([[11, 12], [13, 14], [15, 16]]) let A = copy(a) assertEqual(a + 10, b) assertEqual(10 + a, b) assertEqual(a, A) } func testSubtractMatrixMatrix() { let a = Matrix([[ 1, 2], [ 3, 4], [ 5, 6]]) let b = Matrix([[10, 20], [30, 40], [50, 60]]) let c = Matrix([[ 9, 18], [27, 36], [45, 54]]) let A = copy(a) let B = copy(b) assertEqual(b - a, c) assertEqual(a, A) assertEqual(b, B) let d = Matrix([[-9, -18], [-27, -36], [-45, -54]]) assertEqual(a - b, d) assertEqual(a, A) assertEqual(b, B) } func testSubtractMatrixRowVector() { let a = Matrix([[10, 20], [30, 40], [50, 60]]) let b = Matrix([5, 10]) let c = Matrix([[5, 10], [25, 30], [45, 50]]) let A = copy(a) let B = copy(b) assertEqual(a - b, c) assertEqual(a, A) assertEqual(b, B) } func testSubtractMatrixColumnVector() { let a = Matrix([[10, 20], [30, 40], [50, 60]]) let b = Matrix([5, 10, 1], isColumnVector: true) let c = Matrix([[5, 15], [20, 30], [49, 59]]) let A = copy(a) let B = copy(b) assertEqual(a - b, c) assertEqual(a, A) assertEqual(b, B) } func testSubtractMatrixScalar() { let a = Matrix([[ 1, 2], [ 3, 4], [ 5, 6]]) let b = Matrix([[11, 12], [13, 14], [15, 16]]) let B = copy(b) assertEqual(b - 10, a) let c = Matrix([[-1, -2], [-3, -4], [-5, -6]]) assertEqual(10 - b, c) assertEqual(b, B) } func testNegateMatrix() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) let b = Matrix([[-1, -2], [-3, -4], [-5, -6]]) let A = copy(a) let B = copy(b) assertEqual(-a, b) assertEqual(-b, a) assertEqual(a, A) assertEqual(b, B) } func testMultiplyMatrixMatrix() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) // 3x2 let b = Matrix([[10], [20]]) // 2x1 let c = Matrix([[50], [110], [170]]) // 3x1 let A = copy(a) let B = copy(b) assertEqual(a <*> b, c) assertEqual(a, A) assertEqual(b, B) let d = Matrix([[10, 20, 30], [40, 50, 60]]) // 2x3 let e = Matrix([[90, 120, 150], [190, 260, 330], [290, 400, 510]]) // 3x3 let f = Matrix([[220, 280], [490, 640]]) // 2x2 let D = d assertEqual(a <*> d, e) assertEqual(d <*> a, f) assertEqual(a, A) assertEqual(d, D) let i = Matrix.identity(size: 2) // 2x2 let j = Matrix.identity(size: 3) // 3x3 assertEqual(a <*> i, a) assertEqual(j <*> a, a) } func testMultiplyMatrixMatrixElementwise() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) let b = Matrix([[10, 20], [30, 40], [50, 60]]) let c = Matrix([[10, 40], [90, 160], [250, 360]]) let A = copy(a) let B = copy(b) assertEqual(a * b, c) assertEqual(a, A) assertEqual(b, B) } func testMultiplyMatrixRowVector() { let a = Matrix([[2, 5], [6, 10], [12, 20]]) let b = Matrix([5, 4]) let c = Matrix([[10, 20], [30, 40], [60, 80]]) let A = copy(a) let B = copy(b) assertEqual(a * b, c) assertEqual(a, A) assertEqual(b, B) } func testMultiplyMatrixColumnVector() { let a = Matrix([[2, 4], [2, 3], [6, 8]]) let b = Matrix([5, 15, 10], isColumnVector: true) let c = Matrix([[10, 20], [30, 45], [60, 80]]) let A = copy(a) let B = copy(b) assertEqual(a * b, c) assertEqual(a, A) assertEqual(b, B) } func testMultiplyMatrixScalar() { let a = Matrix([[ 1, 2], [ 3, 4], [ 5, 6]]) let b = Matrix([[10, 20], [30, 40], [50, 60]]) let A = copy(a) assertEqual(a * 10, b) assertEqual(10 * a, b) assertEqual(a, A) } func testDivideMatrixMatrix() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) // 3x2 let b = Matrix([[5, 6], [7, 8]]) // 2x2 let c = Matrix([[3, -2], [2, -1], [1, 0]]) // 3x2 let A = copy(a) let B = copy(b) assertEqual(a </> b, c, accuracy: 1e-10) assertEqual(a <*> b.inverse(), c, accuracy: 1e-10) assertEqual(a, A) assertEqual(b, B) let i = Matrix.identity(size: 2) // 2x2 assertEqual(a </> i, a) } func testDivideMatrixMatrixElementwise() { let a = Matrix([[10, 40], [90, 160], [250, 360]]) let b = Matrix([[10, 20], [30, 40], [50, 60]]) let c = Matrix([[1, 2], [3, 4], [5, 6]]) let A = copy(a) let B = copy(b) assertEqual(a / b, c) assertEqual(a, A) assertEqual(b, B) } func testDivideMatrixRowVector() { let a = Matrix([[10, 20], [30, 40], [60, 80]]) let b = Matrix([5, 4]) let c = Matrix([[2, 5], [6, 10], [12, 20]]) let A = copy(a) let B = copy(b) assertEqual(a / b, c) assertEqual(a, A) assertEqual(b, B) } func testDivideMatrixColumnVector() { let a = Matrix([[10, 20], [30, 45], [60, 80]]) let b = Matrix([5, 15, 10], isColumnVector: true) let c = Matrix([[2, 4], [2, 3], [6, 8]]) let A = copy(a) let B = copy(b) assertEqual(a / b, c) assertEqual(a, A) assertEqual(b, B) } func testDivideMatrixScalar() { let a = Matrix([[ 1, 2], [ 3, 4], [ 5, 6]]) let b = Matrix([[10, 20], [30, 40], [50, 60]]) let c = Matrix([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]) let A = copy(a) let B = copy(b) assertEqual(a / 10, c, accuracy: 1e-10) assertEqual(b / 10, a) assertEqual(a, A) assertEqual(b, B) let d = Matrix([[10.0, 5], [10.0/3, 2.5], [2, 10.0/6]]) assertEqual(10 / a, d, accuracy: 1e-10) } } // MARK: - Other maths extension MatrixTests { func testExp() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) let b = Matrix([[2.7182818285, 7.3890560989], [20.0855369232, 54.5981500331], [148.4131591026, 403.4287934927]]) let A = copy(a) assertEqual(a.exp(), b, accuracy: 1e-10) assertEqual(a, A) } func testLog() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) let b = Matrix([[0.0000000000, 0.6931471806], [1.0986122887, 1.3862943611], [1.6094379124, 1.7917594692]]) let A = copy(a) assertEqual(a.log(), b, accuracy: 1e-10) assertEqual(a, A) } func testPow() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) let b = Matrix([[1, 4], [9, 16], [25, 36]]) let c = Matrix([[1.0000000000, 1.4142135624], [1.7320508076, 2.0000000000], [2.2360679775, 2.4494897428]]) let A = copy(a) assertEqual(a.pow(2), b, accuracy: 1e-10) assertEqual(a.pow(0.5), c, accuracy: 1e-10) assertEqual(a, A) } func testSqrt() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) let b = Matrix([[1, 4], [9, 16], [25, 36]]) let A = copy(a) assertEqual(b.sqrt(), a, accuracy: 1e-10) assertEqual(a.sqrt(), a.pow(0.5), accuracy: 1e-10) assertEqual(a, A) } func testSumAll() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) let A = copy(a) XCTAssertEqual(a.sum(), 21) assertEqual(a, A) let b = Matrix([[-1, -2], [-3, -4], [-5, -6]]) XCTAssertEqual(b.sum(), -21) let i = Matrix.identity(size: 10) XCTAssertEqual(i.sum(), 10) let z = Matrix.zeros(rows: 10, columns: 20) XCTAssertEqual(z.sum(), 0) let o = Matrix.ones(rows: 50, columns: 50) XCTAssertEqual(o.sum(), 2500) } func testSumRows() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) let b = Matrix([3, 7, 11], isColumnVector: true) let A = copy(a) assertEqual(a.sumRows(), b) assertEqual(a, A) } func testSumColumns() { let a = Matrix([[1, 2], [3, 4], [5, 6]]) let b = Matrix([9, 12]) let A = copy(a) assertEqual(a.sumColumns(), b) assertEqual(a, A) } } // MARK: - Minimum and maximum extension MatrixTests { func testMinRow() { let a = Matrix([[19, 7, 21], [3, 40, 15], [5, 4, -1]]) let A = copy(a) let r0 = a.min(row: 0) XCTAssertEqual(r0.0, 7) XCTAssertEqual(r0.1, 1) let r1 = a.min(row: 1) XCTAssertEqual(r1.0, 3) XCTAssertEqual(r1.1, 0) let r2 = a.min(row: 2) XCTAssertEqual(r2.0, -1) XCTAssertEqual(r2.1, 2) assertEqual(a, A) } func testMaxRow() { let a = Matrix([[19, 7, 21], [3, 40, 15], [5, 4, -1]]) let A = copy(a) let r0 = a.max(row: 0) XCTAssertEqual(r0.0, 21) XCTAssertEqual(r0.1, 2) let r1 = a.max(row: 1) XCTAssertEqual(r1.0, 40) XCTAssertEqual(r1.1, 1) let r2 = a.max(row: 2) XCTAssertEqual(r2.0, 5) XCTAssertEqual(r2.1, 0) assertEqual(a, A) } func testMinRows() { let a = Matrix([[19, 7, 21], [3, 40, 15], [5, 4, -1]]) let b = Matrix([7, 3, -1], isColumnVector: true) let A = copy(a) assertEqual(a.minRows(), b) assertEqual(a, A) } func testMaxRows() { let a = Matrix([[19, 7, 21], [3, 40, 15], [5, 4, -1]]) let b = Matrix([21, 40, 5], isColumnVector: true) let A = copy(a) assertEqual(a.maxRows(), b) assertEqual(a, A) } func testMinColumn() { let a = Matrix([[19, 7, -1], [3, 40, 15], [5, 4, 21]]) let A = copy(a) let r0 = a.min(column: 0) XCTAssertEqual(r0.0, 3) XCTAssertEqual(r0.1, 1) let r1 = a.min(column: 1) XCTAssertEqual(r1.0, 4) XCTAssertEqual(r1.1, 2) let r2 = a.min(column: 2) XCTAssertEqual(r2.0, -1) XCTAssertEqual(r2.1, 0) assertEqual(a, A) } func testMaxColumn() { let a = Matrix([[19, 7, -1], [3, 40, 15], [5, 4, 21]]) let A = copy(a) let r0 = a.max(column: 0) XCTAssertEqual(r0.0, 19) XCTAssertEqual(r0.1, 0) let r1 = a.max(column: 1) XCTAssertEqual(r1.0, 40) XCTAssertEqual(r1.1, 1) let r2 = a.max(column: 2) XCTAssertEqual(r2.0, 21) XCTAssertEqual(r2.1, 2) assertEqual(a, A) } func testMinColumns() { let a = Matrix([[19, 7, -1], [3, 40, 15], [5, 4, 21]]) let b = Matrix([3, 4, -1]) let A = copy(a) assertEqual(a.minColumns(), b) assertEqual(a, A) } func testMaxColumns() { let a = Matrix([[19, 7, -1], [3, 40, 15], [5, 4, 21]]) let b = Matrix([19, 40, 21]) let A = copy(a) assertEqual(a.maxColumns(), b) assertEqual(a, A) } func testMin() { let a = Matrix([[19, 7, 15], [3, 40, -1], [5, 4, 21]]) let A = copy(a) let r = a.min() XCTAssertEqual(r.0, -1) XCTAssertEqual(r.1, 1) XCTAssertEqual(r.2, 2) assertEqual(a, A) } func testMax() { let a = Matrix([[19, 7, -1], [3, 4, 15], [5, 40, 21]]) let A = copy(a) let r = a.max() XCTAssertEqual(r.0, 40) XCTAssertEqual(r.1, 2) XCTAssertEqual(r.2, 1) assertEqual(a, A) } } // MARK: - Statistics extension MatrixTests { func testMean() { let a = Matrix([[19, 7, -1], [3, 40, 15], [5, 4, 22]]) let A = copy(a) assertEqual(a.mean(), [9, 17, 12]) assertEqual(a.mean(0...0), [9, 0, 0]) assertEqual(a.mean(1...1), [0, 17, 0]) assertEqual(a.mean(2...2), [0, 0, 12]) assertEqual(a.mean(0...1), [9, 17, 0]) assertEqual(a.mean(1...2), [0, 17, 12]) assertEqual(a.mean(0...2), [9, 17, 12]) assertEqual(a, A) } func testStandardDeviation() { let a = Matrix([[19, 7, -1], [3, 40, 15], [5, 4, 22]]) let A = copy(a) assertEqual(a.std(), [8.7177978871, 19.9749843554, 11.7898261226], accuracy: 1e-10) assertEqual(a, A) } } // MARK: - Performance extension MatrixTests { func testPerfCreateFromArrayRange() { var a = [[Double]]() for _ in 0..<1000 { a.append([Double](repeating: Double.pi, count: 1000)) } measure() { for _ in 1...10 { let _ = Matrix(a, range: 0..<1000) } } } func testPerfTile() { let v = Matrix.random(rows: 1, columns: 1000) measure() { for _ in 1...10 { let _ = v.tile(2000) } } } func testCopyEntireMatrix() { let M = Matrix.random(rows: 1000, columns: 1000) measure() { for _ in 1...10 { let _ = M[rows: Array(0..<1000)] } } } func testPerfSubscriptRowGetter() { let M = Matrix.random(rows: 1000, columns: 1000) measure() { for _ in 1...10 { for i in 0..<M.rows { let _ = M[row: i] } } } } func testPerfSubscriptRowSetter() { var M = Matrix.random(rows: 1000, columns: 1000) let v = Matrix.random(rows: 1, columns: 1000) measure() { for _ in 1...10 { for i in 0..<M.rows { M[row: i] = v } } } } func testSubscripColumnGetter() { let M = Matrix.random(rows: 1000, columns: 1000) measure() { for _ in 1...10 { for i in 0..<M.columns { let _ = M[column: i] } } } } func testPerfSubscriptColumnSetter() { var M = Matrix.random(rows: 1000, columns: 1000) let v = Matrix.random(rows: 1000, columns: 1) measure() { for _ in 1...10 { for i in 0..<M.columns { M[column: i] = v } } } } func testPerfSqrt() { let M = Matrix.random(rows: 1000, columns: 1000) measure() { for _ in 1...10 { let _ = M.sqrt() } } } func testPow2() { let M = Matrix.random(rows: 1000, columns: 1000) measure() { let _ = M.pow(2) } } func testPow3() { let M = Matrix.random(rows: 1000, columns: 1000) measure() { let _ = M.pow(3) } } } #endif
29.616477
120
0.455252
1a2d94a2a11dae23828a4ebf9d48e5512f13e67c
986
import Vapor public func routes(_ router: Router) throws { router.get("ping") { req in return "123" as StaticString } router.get("json") { req in return ["foo": "bar"] } router.get("hello", String.parameter) { req in return try req.parameters.next(String.self) } router.get("search") { req in return req.query["q"] ?? "none" } let sessions = router.grouped("sessions").grouped(SessionsMiddleware.self) sessions.get("get") { req -> String in return try req.session()["name"] ?? "n/a" } sessions.get("set", String.parameter) { req -> String in let name = try req.parameters.next(String.self) try req.session()["name"] = name return name } sessions.get("del") { req -> String in try req.destroySession() return "done" } router.get("client") { req in return try req.client().get("http://vapor.codes").map { $0.description } } }
25.947368
80
0.578093
031579da369e04f461d720089b64ce2c781c7d78
1,375
// // IdentifierHarvesterTests.swift // FingerprintJSTests // // Created by Petr Palata on 12.04.2022. // import XCTest @testable import FingerprintJS class IdentifierHarvesterTests: XCTestCase { private var sut: IdentifierHarvester! override func setUpWithError() throws { sut = IdentifierHarvester() } override func tearDownWithError() throws { sut = nil } // MARK: buildTree func testBuildTreeReturnsCorrectNumberOfItemsForVersionOne() { let config = Configuration(version: .v1) let tree = sut.buildTree(config) XCTAssertEqual(tree.children?.count, 1) } func testBuildTreeReturnsCorrectItemsForVersionOne() { let config = Configuration(version: .v1) let expectedLabels = [ "Vendor identifier" ] let tree = sut.buildTree(config) let labels = tree.children?.map { $0.label } XCTAssertEqual(expectedLabels, labels) } func testBuildTreeReturnsCorrectNumberOfItemsForVersionTwo() { // Subject to change when items are added/removed in version 2 testBuildTreeReturnsCorrectItemsForVersionOne() } func testBuildTreeReturnsCorrectItemsForVersionTwo() { // Subject to change when items are added/removed in version 2 testBuildTreeReturnsCorrectNumberOfItemsForVersionOne() } }
25.462963
70
0.685818
3961c37ef6f420487c319463e6d7c9fd8b6496fa
67,071
import SwiftyJSON import Foundation //Adding date, datetime type for SwiftyJSON, the format can be custom here. class Formatter { private static var internalJsonDateFormatter: NSDateFormatter? private static var internalJsonDateTimeFormatter: NSDateFormatter? static var jsonDateFormatter: NSDateFormatter { if (internalJsonDateFormatter == nil) { internalJsonDateFormatter = NSDateFormatter() internalJsonDateFormatter!.dateFormat = "yyyy-MM-dd" } return internalJsonDateFormatter! } static var jsonDateTimeFormatter: NSDateFormatter { if (internalJsonDateTimeFormatter == nil) { internalJsonDateTimeFormatter = NSDateFormatter() internalJsonDateTimeFormatter!.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'" } return internalJsonDateTimeFormatter! } } extension JSON { public var date: NSDate? { get { switch self.type { case .String: return Formatter.jsonDateFormatter.dateFromString(self.object as! String) default: return nil } } } public var dateTime: NSDate? { get { switch self.type { case .String: return Formatter.jsonDateTimeFormatter.dateFromString(self.object as! String) default: return nil } } } } class SwiftyJSONTool{ func extractBuyerCompany(json:JSON) -> BuyerCompany?{ var buyerCompany = BuyerCompany() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return buyerCompany } if let id = json["id"].string { buyerCompany.id = id } if let name = json["name"].string { buyerCompany.name = name } if let priceList = json["priceList"].string { buyerCompany.priceList = priceList } if let rating = json["rating"].int { buyerCompany.rating = rating } if let logo = json["logo"].string { buyerCompany.logo = logo } if let owner = json["owner"].string { buyerCompany.owner = owner } if let founded = json["founded"].date { buyerCompany.founded = founded } if let version = json["version"].int { buyerCompany.version = version } //Extract one to many list here buyerCompany.costCenterList = extractCostCenterList(json["costCenterList"]) buyerCompany.creditAccountList = extractCreditAccountList(json["creditAccountList"]) buyerCompany.billingAddressList = extractBillingAddressList(json["billingAddressList"]) buyerCompany.employeeList = extractEmployeeList(json["employeeList"]) buyerCompany.orderList = extractOrderList(json["orderList"]) return buyerCompany } func extractBuyerCompanyList(json:JSON) -> [BuyerCompany]?{ guard let buyerCompanyListJson = json.array else{ //NSLog("extractBuyerCompanyList(json:JSON): there is an error here!") return nil } var buyerCompanyList = [BuyerCompany]() for element in buyerCompanyListJson{ if let buyerCompany = extractBuyerCompany(element){ buyerCompanyList.append(buyerCompany) } } return buyerCompanyList } func extractSellerCompany(json:JSON) -> SellerCompany?{ var sellerCompany = SellerCompany() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return sellerCompany } if let id = json["id"].string { sellerCompany.id = id } if let name = json["name"].string { sellerCompany.name = name } if let owner = json["owner"].string { sellerCompany.owner = owner } if let logo = json["logo"].string { sellerCompany.logo = logo } if let contractText = json["contractText"].string { sellerCompany.contractText = contractText } if let version = json["version"].int { sellerCompany.version = version } //Extract one to many list here sellerCompany.profitCenterList = extractProfitCenterList(json["profitCenterList"]) sellerCompany.creditAccountList = extractCreditAccountList(json["creditAccountList"]) sellerCompany.orderList = extractOrderList(json["orderList"]) sellerCompany.custSvcRepList = extractCustSvcRepList(json["custSvcRepList"]) return sellerCompany } func extractSellerCompanyList(json:JSON) -> [SellerCompany]?{ guard let sellerCompanyListJson = json.array else{ //NSLog("extractSellerCompanyList(json:JSON): there is an error here!") return nil } var sellerCompanyList = [SellerCompany]() for element in sellerCompanyListJson{ if let sellerCompany = extractSellerCompany(element){ sellerCompanyList.append(sellerCompany) } } return sellerCompanyList } func extractCostCenter(json:JSON) -> CostCenter?{ var costCenter = CostCenter() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return costCenter } if let id = json["id"].string { costCenter.id = id } if let name = json["name"].string { costCenter.name = name } costCenter.belongsTo = extractBuyerCompany(json["belongsTo"]) if let password = json["password"].string { costCenter.password = password } if let version = json["version"].int { costCenter.version = version } //Extract one to many list here costCenter.orderList = extractOrderList(json["orderList"]) return costCenter } func extractCostCenterList(json:JSON) -> [CostCenter]?{ guard let costCenterListJson = json.array else{ //NSLog("extractCostCenterList(json:JSON): there is an error here!") return nil } var costCenterList = [CostCenter]() for element in costCenterListJson{ if let costCenter = extractCostCenter(element){ costCenterList.append(costCenter) } } return costCenterList } func extractProfitCenter(json:JSON) -> ProfitCenter?{ var profitCenter = ProfitCenter() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return profitCenter } if let id = json["id"].string { profitCenter.id = id } if let name = json["name"].string { profitCenter.name = name } profitCenter.belongsTo = extractSellerCompany(json["belongsTo"]) if let version = json["version"].int { profitCenter.version = version } //Extract one to many list here profitCenter.orderList = extractOrderList(json["orderList"]) return profitCenter } func extractProfitCenterList(json:JSON) -> [ProfitCenter]?{ guard let profitCenterListJson = json.array else{ //NSLog("extractProfitCenterList(json:JSON): there is an error here!") return nil } var profitCenterList = [ProfitCenter]() for element in profitCenterListJson{ if let profitCenter = extractProfitCenter(element){ profitCenterList.append(profitCenter) } } return profitCenterList } func extractCreditAccount(json:JSON) -> CreditAccount?{ var creditAccount = CreditAccount() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return creditAccount } if let id = json["id"].string { creditAccount.id = id } if let name = json["name"].string { creditAccount.name = name } creditAccount.buyer = extractBuyerCompany(json["buyer"]) creditAccount.seller = extractSellerCompany(json["seller"]) if let authorized = json["authorized"].double { creditAccount.authorized = authorized } if let remain = json["remain"].double { creditAccount.remain = remain } if let version = json["version"].int { creditAccount.version = version } return creditAccount } func extractCreditAccountList(json:JSON) -> [CreditAccount]?{ guard let creditAccountListJson = json.array else{ //NSLog("extractCreditAccountList(json:JSON): there is an error here!") return nil } var creditAccountList = [CreditAccount]() for element in creditAccountListJson{ if let creditAccount = extractCreditAccount(element){ creditAccountList.append(creditAccount) } } return creditAccountList } func extractShippingAddress(json:JSON) -> ShippingAddress?{ var shippingAddress = ShippingAddress() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return shippingAddress } if let id = json["id"].string { shippingAddress.id = id } if let line1 = json["line1"].string { shippingAddress.line1 = line1 } if let line2 = json["line2"].string { shippingAddress.line2 = line2 } if let city = json["city"].string { shippingAddress.city = city } if let state = json["state"].string { shippingAddress.state = state } if let country = json["country"].string { shippingAddress.country = country } if let version = json["version"].int { shippingAddress.version = version } //Extract one to many list here shippingAddress.shippingGroupList = extractShippingGroupList(json["shippingGroupList"]) return shippingAddress } func extractShippingAddressList(json:JSON) -> [ShippingAddress]?{ guard let shippingAddressListJson = json.array else{ //NSLog("extractShippingAddressList(json:JSON): there is an error here!") return nil } var shippingAddressList = [ShippingAddress]() for element in shippingAddressListJson{ if let shippingAddress = extractShippingAddress(element){ shippingAddressList.append(shippingAddress) } } return shippingAddressList } func extractBillingAddress(json:JSON) -> BillingAddress?{ var billingAddress = BillingAddress() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return billingAddress } if let id = json["id"].string { billingAddress.id = id } billingAddress.company = extractBuyerCompany(json["company"]) if let line1 = json["line1"].string { billingAddress.line1 = line1 } if let line2 = json["line2"].string { billingAddress.line2 = line2 } if let city = json["city"].string { billingAddress.city = city } if let state = json["state"].string { billingAddress.state = state } if let country = json["country"].string { billingAddress.country = country } if let version = json["version"].int { billingAddress.version = version } //Extract one to many list here billingAddress.paymentGroupList = extractPaymentGroupList(json["paymentGroupList"]) return billingAddress } func extractBillingAddressList(json:JSON) -> [BillingAddress]?{ guard let billingAddressListJson = json.array else{ //NSLog("extractBillingAddressList(json:JSON): there is an error here!") return nil } var billingAddressList = [BillingAddress]() for element in billingAddressListJson{ if let billingAddress = extractBillingAddress(element){ billingAddressList.append(billingAddress) } } return billingAddressList } func extractEmployee(json:JSON) -> Employee?{ var employee = Employee() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return employee } if let id = json["id"].string { employee.id = id } if let name = json["name"].string { employee.name = name } employee.company = extractBuyerCompany(json["company"]) if let email = json["email"].string { employee.email = email } if let passwd = json["passwd"].string { employee.passwd = passwd } if let cellPhone = json["cellPhone"].string { employee.cellPhone = cellPhone } if let version = json["version"].int { employee.version = version } //Extract one to many list here employee.assignmentList = extractAssignmentList(json["assignmentList"]) return employee } func extractEmployeeList(json:JSON) -> [Employee]?{ guard let employeeListJson = json.array else{ //NSLog("extractEmployeeList(json:JSON): there is an error here!") return nil } var employeeList = [Employee]() for element in employeeListJson{ if let employee = extractEmployee(element){ employeeList.append(employee) } } return employeeList } func extractRole(json:JSON) -> Role?{ var role = Role() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return role } if let id = json["id"].string { role.id = id } if let roleName = json["roleName"].string { role.roleName = roleName } if let version = json["version"].int { role.version = version } //Extract one to many list here role.accessList = extractAccessList(json["accessList"]) role.custSvcRepList = extractCustSvcRepList(json["custSvcRepList"]) return role } func extractRoleList(json:JSON) -> [Role]?{ guard let roleListJson = json.array else{ //NSLog("extractRoleList(json:JSON): there is an error here!") return nil } var roleList = [Role]() for element in roleListJson{ if let role = extractRole(element){ roleList.append(role) } } return roleList } func extractAssignment(json:JSON) -> Assignment?{ var assignment = Assignment() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return assignment } if let id = json["id"].string { assignment.id = id } assignment.user = extractEmployee(json["user"]) assignment.access = extractAccess(json["access"]) if let assignedDate = json["assignedDate"].date { assignment.assignedDate = assignedDate } if let version = json["version"].int { assignment.version = version } return assignment } func extractAssignmentList(json:JSON) -> [Assignment]?{ guard let assignmentListJson = json.array else{ //NSLog("extractAssignmentList(json:JSON): there is an error here!") return nil } var assignmentList = [Assignment]() for element in assignmentListJson{ if let assignment = extractAssignment(element){ assignmentList.append(assignment) } } return assignmentList } func extractAccess(json:JSON) -> Access?{ var access = Access() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return access } if let id = json["id"].string { access.id = id } if let roleName = json["roleName"].string { access.roleName = roleName } access.role = extractRole(json["role"]) if let version = json["version"].int { access.version = version } //Extract one to many list here access.assignmentList = extractAssignmentList(json["assignmentList"]) return access } func extractAccessList(json:JSON) -> [Access]?{ guard let accessListJson = json.array else{ //NSLog("extractAccessList(json:JSON): there is an error here!") return nil } var accessList = [Access]() for element in accessListJson{ if let access = extractAccess(element){ accessList.append(access) } } return accessList } func extractOrder(json:JSON) -> Order?{ var order = Order() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return order } if let id = json["id"].string { order.id = id } order.buyer = extractBuyerCompany(json["buyer"]) order.seller = extractSellerCompany(json["seller"]) if let title = json["title"].string { order.title = title } order.costCenter = extractCostCenter(json["costCenter"]) order.profitCenter = extractProfitCenter(json["profitCenter"]) if let totalAmount = json["totalAmount"].double { order.totalAmount = totalAmount } if let type = json["type"].string { order.type = type } if let markAsDelete = json["markAsDelete"].bool { order.markAsDelete = markAsDelete } order.confirmation = extractConfirmation(json["confirmation"]) order.approval = extractApproval(json["approval"]) order.processing = extractProcessing(json["processing"]) order.shipment = extractShipment(json["shipment"]) order.delivery = extractDelivery(json["delivery"]) order.recurringInfo = extractRecurringInfo(json["recurringInfo"]) if let version = json["version"].int { order.version = version } //Extract one to many list here order.lineItemList = extractLineItemList(json["lineItemList"]) order.shippingGroupList = extractShippingGroupList(json["shippingGroupList"]) order.paymentGroupList = extractPaymentGroupList(json["paymentGroupList"]) order.actionList = extractActionList(json["actionList"]) return order } func extractOrderList(json:JSON) -> [Order]?{ guard let orderListJson = json.array else{ //NSLog("extractOrderList(json:JSON): there is an error here!") return nil } var orderList = [Order]() for element in orderListJson{ if let order = extractOrder(element){ orderList.append(order) } } return orderList } func extractRecurringInfo(json:JSON) -> RecurringInfo?{ var recurringInfo = RecurringInfo() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return recurringInfo } if let id = json["id"].string { recurringInfo.id = id } if let name = json["name"].string { recurringInfo.name = name } if let nextTime = json["nextTime"].date { recurringInfo.nextTime = nextTime } if let cronExpr = json["cronExpr"].string { recurringInfo.cronExpr = cronExpr } if let version = json["version"].int { recurringInfo.version = version } //Extract one to many list here recurringInfo.orderList = extractOrderList(json["orderList"]) return recurringInfo } func extractRecurringInfoList(json:JSON) -> [RecurringInfo]?{ guard let recurringInfoListJson = json.array else{ //NSLog("extractRecurringInfoList(json:JSON): there is an error here!") return nil } var recurringInfoList = [RecurringInfo]() for element in recurringInfoListJson{ if let recurringInfo = extractRecurringInfo(element){ recurringInfoList.append(recurringInfo) } } return recurringInfoList } func extractConfirmation(json:JSON) -> Confirmation?{ var confirmation = Confirmation() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return confirmation } if let id = json["id"].string { confirmation.id = id } if let who = json["who"].string { confirmation.who = who } if let confirmTime = json["confirmTime"].date { confirmation.confirmTime = confirmTime } if let version = json["version"].int { confirmation.version = version } //Extract one to many list here confirmation.orderList = extractOrderList(json["orderList"]) return confirmation } func extractConfirmationList(json:JSON) -> [Confirmation]?{ guard let confirmationListJson = json.array else{ //NSLog("extractConfirmationList(json:JSON): there is an error here!") return nil } var confirmationList = [Confirmation]() for element in confirmationListJson{ if let confirmation = extractConfirmation(element){ confirmationList.append(confirmation) } } return confirmationList } func extractShipment(json:JSON) -> Shipment?{ var shipment = Shipment() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return shipment } if let id = json["id"].string { shipment.id = id } if let who = json["who"].string { shipment.who = who } if let shipTime = json["shipTime"].date { shipment.shipTime = shipTime } if let version = json["version"].int { shipment.version = version } //Extract one to many list here shipment.orderList = extractOrderList(json["orderList"]) return shipment } func extractShipmentList(json:JSON) -> [Shipment]?{ guard let shipmentListJson = json.array else{ //NSLog("extractShipmentList(json:JSON): there is an error here!") return nil } var shipmentList = [Shipment]() for element in shipmentListJson{ if let shipment = extractShipment(element){ shipmentList.append(shipment) } } return shipmentList } func extractDelivery(json:JSON) -> Delivery?{ var delivery = Delivery() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return delivery } if let id = json["id"].string { delivery.id = id } if let who = json["who"].string { delivery.who = who } if let deliveryTime = json["deliveryTime"].date { delivery.deliveryTime = deliveryTime } if let version = json["version"].int { delivery.version = version } //Extract one to many list here delivery.orderList = extractOrderList(json["orderList"]) return delivery } func extractDeliveryList(json:JSON) -> [Delivery]?{ guard let deliveryListJson = json.array else{ //NSLog("extractDeliveryList(json:JSON): there is an error here!") return nil } var deliveryList = [Delivery]() for element in deliveryListJson{ if let delivery = extractDelivery(element){ deliveryList.append(delivery) } } return deliveryList } func extractProcessing(json:JSON) -> Processing?{ var processing = Processing() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return processing } if let id = json["id"].string { processing.id = id } if let who = json["who"].string { processing.who = who } if let processTime = json["processTime"].date { processing.processTime = processTime } if let version = json["version"].int { processing.version = version } //Extract one to many list here processing.orderList = extractOrderList(json["orderList"]) return processing } func extractProcessingList(json:JSON) -> [Processing]?{ guard let processingListJson = json.array else{ //NSLog("extractProcessingList(json:JSON): there is an error here!") return nil } var processingList = [Processing]() for element in processingListJson{ if let processing = extractProcessing(element){ processingList.append(processing) } } return processingList } func extractApproval(json:JSON) -> Approval?{ var approval = Approval() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return approval } if let id = json["id"].string { approval.id = id } if let who = json["who"].string { approval.who = who } if let approveTime = json["approveTime"].date { approval.approveTime = approveTime } if let version = json["version"].int { approval.version = version } //Extract one to many list here approval.orderList = extractOrderList(json["orderList"]) return approval } func extractApprovalList(json:JSON) -> [Approval]?{ guard let approvalListJson = json.array else{ //NSLog("extractApprovalList(json:JSON): there is an error here!") return nil } var approvalList = [Approval]() for element in approvalListJson{ if let approval = extractApproval(element){ approvalList.append(approval) } } return approvalList } func extractLineItem(json:JSON) -> LineItem?{ let lineItem = LineItem() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return lineItem } if let id = json["id"].string { lineItem.id = id } lineItem.bizOrder = extractOrder(json["bizOrder"]) if let skuId = json["skuId"].string { lineItem.skuId = skuId } if let skuName = json["skuName"].string { lineItem.skuName = skuName } if let amount = json["amount"].double { lineItem.amount = amount } if let quantity = json["quantity"].int { lineItem.quantity = quantity } if let active = json["active"].bool { lineItem.active = active } if let version = json["version"].int { lineItem.version = version } return lineItem } func extractLineItemList(json:JSON) -> [LineItem]?{ guard let lineItemListJson = json.array else{ //NSLog("extractLineItemList(json:JSON): there is an error here!") return nil } var lineItemList = [LineItem]() for element in lineItemListJson{ if let lineItem = extractLineItem(element){ lineItemList.append(lineItem) } } return lineItemList } func extractShippingGroup(json:JSON) -> ShippingGroup?{ var shippingGroup = ShippingGroup() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return shippingGroup } if let id = json["id"].string { shippingGroup.id = id } if let name = json["name"].string { shippingGroup.name = name } shippingGroup.bizOrder = extractOrder(json["bizOrder"]) shippingGroup.address = extractShippingAddress(json["address"]) if let amount = json["amount"].double { shippingGroup.amount = amount } if let version = json["version"].int { shippingGroup.version = version } return shippingGroup } func extractShippingGroupList(json:JSON) -> [ShippingGroup]?{ guard let shippingGroupListJson = json.array else{ //NSLog("extractShippingGroupList(json:JSON): there is an error here!") return nil } var shippingGroupList = [ShippingGroup]() for element in shippingGroupListJson{ if let shippingGroup = extractShippingGroup(element){ shippingGroupList.append(shippingGroup) } } return shippingGroupList } func extractPaymentGroup(json:JSON) -> PaymentGroup?{ var paymentGroup = PaymentGroup() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return paymentGroup } if let id = json["id"].string { paymentGroup.id = id } if let name = json["name"].string { paymentGroup.name = name } paymentGroup.bizOrder = extractOrder(json["bizOrder"]) if let cardNumber = json["cardNumber"].string { paymentGroup.cardNumber = cardNumber } paymentGroup.billingAddress = extractBillingAddress(json["billingAddress"]) if let version = json["version"].int { paymentGroup.version = version } return paymentGroup } func extractPaymentGroupList(json:JSON) -> [PaymentGroup]?{ guard let paymentGroupListJson = json.array else{ //NSLog("extractPaymentGroupList(json:JSON): there is an error here!") return nil } var paymentGroupList = [PaymentGroup]() for element in paymentGroupListJson{ if let paymentGroup = extractPaymentGroup(element){ paymentGroupList.append(paymentGroup) } } return paymentGroupList } func extractCustSvcRep(json:JSON) -> CustSvcRep?{ var custSvcRep = CustSvcRep() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return custSvcRep } if let id = json["id"].string { custSvcRep.id = id } if let email = json["email"].string { custSvcRep.email = email } if let passwd = json["passwd"].string { custSvcRep.passwd = passwd } custSvcRep.role = extractRole(json["role"]) custSvcRep.company = extractSellerCompany(json["company"]) if let version = json["version"].int { custSvcRep.version = version } return custSvcRep } func extractCustSvcRepList(json:JSON) -> [CustSvcRep]?{ guard let custSvcRepListJson = json.array else{ //NSLog("extractCustSvcRepList(json:JSON): there is an error here!") return nil } var custSvcRepList = [CustSvcRep]() for element in custSvcRepListJson{ if let custSvcRep = extractCustSvcRep(element){ custSvcRepList.append(custSvcRep) } } return custSvcRepList } func extractAction(json:JSON) -> Action?{ var action = Action() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return action } if let id = json["id"].string { action.id = id } if let name = json["name"].string { action.name = name } if let internalName = json["internalName"].string { action.internalName = internalName } action.bo = extractOrder(json["bo"]) if let version = json["version"].int { action.version = version } return action } func extractActionList(json:JSON) -> [Action]?{ guard let actionListJson = json.array else{ //NSLog("extractActionList(json:JSON): there is an error here!") return nil } var actionList = [Action]() for element in actionListJson{ if let action = extractAction(element){ actionList.append(action) } } return actionList } func extractUniversalPrice(json:JSON) -> UniversalPrice?{ var universalPrice = UniversalPrice() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return universalPrice } if let id = json["id"].string { universalPrice.id = id } universalPrice.sku = extractSku(json["sku"]) if let price = json["price"].int { universalPrice.price = price } if let version = json["version"].int { universalPrice.version = version } return universalPrice } func extractUniversalPriceList(json:JSON) -> [UniversalPrice]?{ guard let universalPriceListJson = json.array else{ //NSLog("extractUniversalPriceList(json:JSON): there is an error here!") return nil } var universalPriceList = [UniversalPrice]() for element in universalPriceListJson{ if let universalPrice = extractUniversalPrice(element){ universalPriceList.append(universalPrice) } } return universalPriceList } func extractContractPrice(json:JSON) -> ContractPrice?{ var contractPrice = ContractPrice() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return contractPrice } if let id = json["id"].string { contractPrice.id = id } if let contractId = json["contractId"].string { contractPrice.contractId = contractId } contractPrice.sku = extractSku(json["sku"]) if let price = json["price"].int { contractPrice.price = price } contractPrice.review = extractContractPriceReview(json["review"]) contractPrice.approval = extractContractPriceApproval(json["approval"]) if let version = json["version"].int { contractPrice.version = version } return contractPrice } func extractContractPriceList(json:JSON) -> [ContractPrice]?{ guard let contractPriceListJson = json.array else{ //NSLog("extractContractPriceList(json:JSON): there is an error here!") return nil } var contractPriceList = [ContractPrice]() for element in contractPriceListJson{ if let contractPrice = extractContractPrice(element){ contractPriceList.append(contractPrice) } } return contractPriceList } func extractContractPriceApproval(json:JSON) -> ContractPriceApproval?{ var contractPriceApproval = ContractPriceApproval() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return contractPriceApproval } if let id = json["id"].string { contractPriceApproval.id = id } if let who = json["who"].string { contractPriceApproval.who = who } if let approveTime = json["approveTime"].date { contractPriceApproval.approveTime = approveTime } if let remark = json["remark"].string { contractPriceApproval.remark = remark } if let version = json["version"].int { contractPriceApproval.version = version } //Extract one to many list here contractPriceApproval.contractPriceList = extractContractPriceList(json["contractPriceList"]) return contractPriceApproval } func extractContractPriceApprovalList(json:JSON) -> [ContractPriceApproval]?{ guard let contractPriceApprovalListJson = json.array else{ //NSLog("extractContractPriceApprovalList(json:JSON): there is an error here!") return nil } var contractPriceApprovalList = [ContractPriceApproval]() for element in contractPriceApprovalListJson{ if let contractPriceApproval = extractContractPriceApproval(element){ contractPriceApprovalList.append(contractPriceApproval) } } return contractPriceApprovalList } func extractContractPriceReview(json:JSON) -> ContractPriceReview?{ var contractPriceReview = ContractPriceReview() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return contractPriceReview } if let id = json["id"].string { contractPriceReview.id = id } if let who = json["who"].string { contractPriceReview.who = who } if let reviewTime = json["reviewTime"].date { contractPriceReview.reviewTime = reviewTime } if let remark = json["remark"].string { contractPriceReview.remark = remark } if let version = json["version"].int { contractPriceReview.version = version } //Extract one to many list here contractPriceReview.contractPriceList = extractContractPriceList(json["contractPriceList"]) return contractPriceReview } func extractContractPriceReviewList(json:JSON) -> [ContractPriceReview]?{ guard let contractPriceReviewListJson = json.array else{ //NSLog("extractContractPriceReviewList(json:JSON): there is an error here!") return nil } var contractPriceReviewList = [ContractPriceReview]() for element in contractPriceReviewListJson{ if let contractPriceReview = extractContractPriceReview(element){ contractPriceReviewList.append(contractPriceReview) } } return contractPriceReviewList } func extractUniversalPriceApproval(json:JSON) -> UniversalPriceApproval?{ var universalPriceApproval = UniversalPriceApproval() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return universalPriceApproval } if let id = json["id"].string { universalPriceApproval.id = id } if let who = json["who"].string { universalPriceApproval.who = who } if let approveTime = json["approveTime"].date { universalPriceApproval.approveTime = approveTime } if let remark = json["remark"].string { universalPriceApproval.remark = remark } if let version = json["version"].int { universalPriceApproval.version = version } return universalPriceApproval } func extractUniversalPriceApprovalList(json:JSON) -> [UniversalPriceApproval]?{ guard let universalPriceApprovalListJson = json.array else{ //NSLog("extractUniversalPriceApprovalList(json:JSON): there is an error here!") return nil } var universalPriceApprovalList = [UniversalPriceApproval]() for element in universalPriceApprovalListJson{ if let universalPriceApproval = extractUniversalPriceApproval(element){ universalPriceApprovalList.append(universalPriceApproval) } } return universalPriceApprovalList } func extractUniversalPriceReview(json:JSON) -> UniversalPriceReview?{ var universalPriceReview = UniversalPriceReview() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return universalPriceReview } if let id = json["id"].string { universalPriceReview.id = id } if let who = json["who"].string { universalPriceReview.who = who } if let reviewTime = json["reviewTime"].date { universalPriceReview.reviewTime = reviewTime } if let remark = json["remark"].string { universalPriceReview.remark = remark } if let version = json["version"].int { universalPriceReview.version = version } return universalPriceReview } func extractUniversalPriceReviewList(json:JSON) -> [UniversalPriceReview]?{ guard let universalPriceReviewListJson = json.array else{ //NSLog("extractUniversalPriceReviewList(json:JSON): there is an error here!") return nil } var universalPriceReviewList = [UniversalPriceReview]() for element in universalPriceReviewListJson{ if let universalPriceReview = extractUniversalPriceReview(element){ universalPriceReviewList.append(universalPriceReview) } } return universalPriceReviewList } func extractFixRiceSkuPromotion(json:JSON) -> FixRiceSkuPromotion?{ var fixRiceSkuPromotion = FixRiceSkuPromotion() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return fixRiceSkuPromotion } if let id = json["id"].string { fixRiceSkuPromotion.id = id } fixRiceSkuPromotion.sku = extractSku(json["sku"]) if let rules = json["rules"].string { fixRiceSkuPromotion.rules = rules } if let priceTo = json["priceTo"].double { fixRiceSkuPromotion.priceTo = priceTo } if let version = json["version"].int { fixRiceSkuPromotion.version = version } return fixRiceSkuPromotion } func extractFixRiceSkuPromotionList(json:JSON) -> [FixRiceSkuPromotion]?{ guard let fixRiceSkuPromotionListJson = json.array else{ //NSLog("extractFixRiceSkuPromotionList(json:JSON): there is an error here!") return nil } var fixRiceSkuPromotionList = [FixRiceSkuPromotion]() for element in fixRiceSkuPromotionListJson{ if let fixRiceSkuPromotion = extractFixRiceSkuPromotion(element){ fixRiceSkuPromotionList.append(fixRiceSkuPromotion) } } return fixRiceSkuPromotionList } func extractInventory(json:JSON) -> Inventory?{ var inventory = Inventory() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return inventory } if let id = json["id"].string { inventory.id = id } inventory.sku = extractSku(json["sku"]) inventory.warehouse = extractWarehouse(json["warehouse"]) if let stockLevel = json["stockLevel"].int { inventory.stockLevel = stockLevel } if let preorderable = json["preorderable"].int { inventory.preorderable = preorderable } if let backorderable = json["backorderable"].int { inventory.backorderable = backorderable } if let version = json["version"].int { inventory.version = version } return inventory } func extractInventoryList(json:JSON) -> [Inventory]?{ guard let inventoryListJson = json.array else{ //NSLog("extractInventoryList(json:JSON): there is an error here!") return nil } var inventoryList = [Inventory]() for element in inventoryListJson{ if let inventory = extractInventory(element){ inventoryList.append(inventory) } } return inventoryList } func extractWarehouse(json:JSON) -> Warehouse?{ var warehouse = Warehouse() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return warehouse } if let id = json["id"].string { warehouse.id = id } if let displayName = json["displayName"].string { warehouse.displayName = displayName } if let location = json["location"].string { warehouse.location = location } if let owner = json["owner"].string { warehouse.owner = owner } if let version = json["version"].int { warehouse.version = version } //Extract one to many list here warehouse.inventoryList = extractInventoryList(json["inventoryList"]) return warehouse } func extractWarehouseList(json:JSON) -> [Warehouse]?{ guard let warehouseListJson = json.array else{ //NSLog("extractWarehouseList(json:JSON): there is an error here!") return nil } var warehouseList = [Warehouse]() for element in warehouseListJson{ if let warehouse = extractWarehouse(element){ warehouseList.append(warehouse) } } return warehouseList } func extractSellerSite(json:JSON) -> SellerSite?{ var sellerSite = SellerSite() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return sellerSite } if let id = json["id"].string { sellerSite.id = id } if let siteId = json["siteId"].string { sellerSite.siteId = siteId } sellerSite.homePage = extractHomePage(json["homePage"]) sellerSite.catalog = extractCatalog(json["catalog"]) sellerSite.marketing = extractMarketingLanding(json["marketing"]) if let version = json["version"].int { sellerSite.version = version } return sellerSite } func extractSellerSiteList(json:JSON) -> [SellerSite]?{ guard let sellerSiteListJson = json.array else{ //NSLog("extractSellerSiteList(json:JSON): there is an error here!") return nil } var sellerSiteList = [SellerSite]() for element in sellerSiteListJson{ if let sellerSite = extractSellerSite(element){ sellerSiteList.append(sellerSite) } } return sellerSiteList } func extractHomePage(json:JSON) -> HomePage?{ var homePage = HomePage() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return homePage } if let id = json["id"].string { homePage.id = id } if let title = json["title"].string { homePage.title = title } if let ver = json["ver"].string { homePage.ver = ver } if let version = json["version"].int { homePage.version = version } //Extract one to many list here homePage.sellerSiteList = extractSellerSiteList(json["sellerSiteList"]) homePage.headerList = extractHeaderList(json["headerList"]) homePage.naviList = extractNaviList(json["naviList"]) homePage.bannerList = extractBannerList(json["bannerList"]) homePage.footerList = extractFooterList(json["footerList"]) return homePage } func extractHomePageList(json:JSON) -> [HomePage]?{ guard let homePageListJson = json.array else{ //NSLog("extractHomePageList(json:JSON): there is an error here!") return nil } var homePageList = [HomePage]() for element in homePageListJson{ if let homePage = extractHomePage(element){ homePageList.append(homePage) } } return homePageList } func extractMarketingLanding(json:JSON) -> MarketingLanding?{ var marketingLanding = MarketingLanding() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return marketingLanding } if let id = json["id"].string { marketingLanding.id = id } if let title = json["title"].string { marketingLanding.title = title } if let version = json["version"].int { marketingLanding.version = version } //Extract one to many list here marketingLanding.sellerSiteList = extractSellerSiteList(json["sellerSiteList"]) marketingLanding.marketingBannerList = extractMarketingBannerList(json["marketingBannerList"]) return marketingLanding } func extractMarketingLandingList(json:JSON) -> [MarketingLanding]?{ guard let marketingLandingListJson = json.array else{ //NSLog("extractMarketingLandingList(json:JSON): there is an error here!") return nil } var marketingLandingList = [MarketingLanding]() for element in marketingLandingListJson{ if let marketingLanding = extractMarketingLanding(element){ marketingLandingList.append(marketingLanding) } } return marketingLandingList } func extractMarketingBanner(json:JSON) -> MarketingBanner?{ var marketingBanner = MarketingBanner() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return marketingBanner } if let id = json["id"].string { marketingBanner.id = id } marketingBanner.parent = extractMarketingLanding(json["parent"]) if let image = json["image"].string { marketingBanner.image = image } if let link = json["link"].string { marketingBanner.link = link } if let version = json["version"].int { marketingBanner.version = version } return marketingBanner } func extractMarketingBannerList(json:JSON) -> [MarketingBanner]?{ guard let marketingBannerListJson = json.array else{ //NSLog("extractMarketingBannerList(json:JSON): there is an error here!") return nil } var marketingBannerList = [MarketingBanner]() for element in marketingBannerListJson{ if let marketingBanner = extractMarketingBanner(element){ marketingBannerList.append(marketingBanner) } } return marketingBannerList } func extractHeader(json:JSON) -> Header?{ var header = Header() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return header } if let id = json["id"].string { header.id = id } header.page = extractHomePage(json["page"]) if let image = json["image"].string { header.image = image } if let action = json["action"].string { header.action = action } if let version = json["version"].int { header.version = version } return header } func extractHeaderList(json:JSON) -> [Header]?{ guard let headerListJson = json.array else{ //NSLog("extractHeaderList(json:JSON): there is an error here!") return nil } var headerList = [Header]() for element in headerListJson{ if let header = extractHeader(element){ headerList.append(header) } } return headerList } func extractNavi(json:JSON) -> Navi?{ var navi = Navi() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return navi } if let id = json["id"].string { navi.id = id } navi.page = extractHomePage(json["page"]) if let image = json["image"].string { navi.image = image } if let action = json["action"].string { navi.action = action } if let version = json["version"].int { navi.version = version } return navi } func extractNaviList(json:JSON) -> [Navi]?{ guard let naviListJson = json.array else{ //NSLog("extractNaviList(json:JSON): there is an error here!") return nil } var naviList = [Navi]() for element in naviListJson{ if let navi = extractNavi(element){ naviList.append(navi) } } return naviList } func extractBanner(json:JSON) -> Banner?{ var banner = Banner() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return banner } if let id = json["id"].string { banner.id = id } banner.page = extractHomePage(json["page"]) if let image = json["image"].string { banner.image = image } if let action = json["action"].string { banner.action = action } if let version = json["version"].int { banner.version = version } return banner } func extractBannerList(json:JSON) -> [Banner]?{ guard let bannerListJson = json.array else{ //NSLog("extractBannerList(json:JSON): there is an error here!") return nil } var bannerList = [Banner]() for element in bannerListJson{ if let banner = extractBanner(element){ bannerList.append(banner) } } return bannerList } func extractFooter(json:JSON) -> Footer?{ var footer = Footer() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return footer } if let id = json["id"].string { footer.id = id } footer.page = extractHomePage(json["page"]) if let image = json["image"].string { footer.image = image } if let action = json["action"].string { footer.action = action } if let version = json["version"].int { footer.version = version } return footer } func extractFooterList(json:JSON) -> [Footer]?{ guard let footerListJson = json.array else{ //NSLog("extractFooterList(json:JSON): there is an error here!") return nil } var footerList = [Footer]() for element in footerListJson{ if let footer = extractFooter(element){ footerList.append(footer) } } return footerList } func extractCatalog(json:JSON) -> Catalog?{ var catalog = Catalog() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return catalog } if let id = json["id"].string { catalog.id = id } if let displayName = json["displayName"].string { catalog.displayName = displayName } if let sellerId = json["sellerId"].string { catalog.sellerId = sellerId } if let version = json["version"].int { catalog.version = version } //Extract one to many list here catalog.sellerSiteList = extractSellerSiteList(json["sellerSiteList"]) catalog.levelOneCatList = extractLevelOneCatList(json["levelOneCatList"]) return catalog } func extractCatalogList(json:JSON) -> [Catalog]?{ guard let catalogListJson = json.array else{ //NSLog("extractCatalogList(json:JSON): there is an error here!") return nil } var catalogList = [Catalog]() for element in catalogListJson{ if let catalog = extractCatalog(element){ catalogList.append(catalog) } } return catalogList } func extractLevelOneCat(json:JSON) -> LevelOneCat?{ var levelOneCat = LevelOneCat() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return levelOneCat } if let id = json["id"].string { levelOneCat.id = id } levelOneCat.catalog = extractCatalog(json["catalog"]) if let displayName = json["displayName"].string { levelOneCat.displayName = displayName } if let version = json["version"].int { levelOneCat.version = version } //Extract one to many list here levelOneCat.levelTwoCatList = extractLevelTwoCatList(json["levelTwoCatList"]) return levelOneCat } func extractLevelOneCatList(json:JSON) -> [LevelOneCat]?{ guard let levelOneCatListJson = json.array else{ //NSLog("extractLevelOneCatList(json:JSON): there is an error here!") return nil } var levelOneCatList = [LevelOneCat]() for element in levelOneCatListJson{ if let levelOneCat = extractLevelOneCat(element){ levelOneCatList.append(levelOneCat) } } return levelOneCatList } func extractLevelTwoCat(json:JSON) -> LevelTwoCat?{ var levelTwoCat = LevelTwoCat() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return levelTwoCat } if let id = json["id"].string { levelTwoCat.id = id } levelTwoCat.parentCat = extractLevelOneCat(json["parentCat"]) if let displayName = json["displayName"].string { levelTwoCat.displayName = displayName } if let version = json["version"].int { levelTwoCat.version = version } //Extract one to many list here levelTwoCat.levelThreeCatList = extractLevelThreeCatList(json["levelThreeCatList"]) return levelTwoCat } func extractLevelTwoCatList(json:JSON) -> [LevelTwoCat]?{ guard let levelTwoCatListJson = json.array else{ //NSLog("extractLevelTwoCatList(json:JSON): there is an error here!") return nil } var levelTwoCatList = [LevelTwoCat]() for element in levelTwoCatListJson{ if let levelTwoCat = extractLevelTwoCat(element){ levelTwoCatList.append(levelTwoCat) } } return levelTwoCatList } func extractLevelThreeCat(json:JSON) -> LevelThreeCat?{ var levelThreeCat = LevelThreeCat() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return levelThreeCat } if let id = json["id"].string { levelThreeCat.id = id } levelThreeCat.parentCat = extractLevelTwoCat(json["parentCat"]) if let displayName = json["displayName"].string { levelThreeCat.displayName = displayName } if let version = json["version"].int { levelThreeCat.version = version } //Extract one to many list here levelThreeCat.levelFourCatList = extractLevelFourCatList(json["levelFourCatList"]) levelThreeCat.levelNCatList = extractLevelNCatList(json["levelNCatList"]) return levelThreeCat } func extractLevelThreeCatList(json:JSON) -> [LevelThreeCat]?{ guard let levelThreeCatListJson = json.array else{ //NSLog("extractLevelThreeCatList(json:JSON): there is an error here!") return nil } var levelThreeCatList = [LevelThreeCat]() for element in levelThreeCatListJson{ if let levelThreeCat = extractLevelThreeCat(element){ levelThreeCatList.append(levelThreeCat) } } return levelThreeCatList } func extractLevelFourCat(json:JSON) -> LevelFourCat?{ var levelFourCat = LevelFourCat() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return levelFourCat } if let id = json["id"].string { levelFourCat.id = id } levelFourCat.parentCat = extractLevelThreeCat(json["parentCat"]) if let displayName = json["displayName"].string { levelFourCat.displayName = displayName } if let version = json["version"].int { levelFourCat.version = version } //Extract one to many list here levelFourCat.levelFiveCatList = extractLevelFiveCatList(json["levelFiveCatList"]) return levelFourCat } func extractLevelFourCatList(json:JSON) -> [LevelFourCat]?{ guard let levelFourCatListJson = json.array else{ //NSLog("extractLevelFourCatList(json:JSON): there is an error here!") return nil } var levelFourCatList = [LevelFourCat]() for element in levelFourCatListJson{ if let levelFourCat = extractLevelFourCat(element){ levelFourCatList.append(levelFourCat) } } return levelFourCatList } func extractLevelFiveCat(json:JSON) -> LevelFiveCat?{ var levelFiveCat = LevelFiveCat() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return levelFiveCat } if let id = json["id"].string { levelFiveCat.id = id } levelFiveCat.parentCat = extractLevelFourCat(json["parentCat"]) if let displayName = json["displayName"].string { levelFiveCat.displayName = displayName } if let version = json["version"].int { levelFiveCat.version = version } return levelFiveCat } func extractLevelFiveCatList(json:JSON) -> [LevelFiveCat]?{ guard let levelFiveCatListJson = json.array else{ //NSLog("extractLevelFiveCatList(json:JSON): there is an error here!") return nil } var levelFiveCatList = [LevelFiveCat]() for element in levelFiveCatListJson{ if let levelFiveCat = extractLevelFiveCat(element){ levelFiveCatList.append(levelFiveCat) } } return levelFiveCatList } func extractLevelNCat(json:JSON) -> LevelNCat?{ var levelNCat = LevelNCat() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return levelNCat } if let id = json["id"].string { levelNCat.id = id } levelNCat.parentCat = extractLevelThreeCat(json["parentCat"]) if let displayName = json["displayName"].string { levelNCat.displayName = displayName } if let version = json["version"].int { levelNCat.version = version } //Extract one to many list here levelNCat.productList = extractProductList(json["productList"]) return levelNCat } func extractLevelNCatList(json:JSON) -> [LevelNCat]?{ guard let levelNCatListJson = json.array else{ //NSLog("extractLevelNCatList(json:JSON): there is an error here!") return nil } var levelNCatList = [LevelNCat]() for element in levelNCatListJson{ if let levelNCat = extractLevelNCat(element){ levelNCatList.append(levelNCat) } } return levelNCatList } func extractProduct(json:JSON) -> Product?{ var product = Product() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return product } if let id = json["id"].string { product.id = id } if let displayName = json["displayName"].string { product.displayName = displayName } product.parentCat = extractLevelNCat(json["parentCat"]) product.brand = extractBrand(json["brand"]) if let origin = json["origin"].string { product.origin = origin } if let remark = json["remark"].string { product.remark = remark } if let version = json["version"].int { product.version = version } //Extract one to many list here product.skuList = extractSkuList(json["skuList"]) return product } func extractProductList(json:JSON) -> [Product]?{ guard let productListJson = json.array else{ //NSLog("extractProductList(json:JSON): there is an error here!") return nil } var productList = [Product]() for element in productListJson{ if let product = extractProduct(element){ productList.append(product) } } return productList } func extractSku(json:JSON) -> Sku?{ var sku = Sku() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return sku } if let id = json["id"].string { sku.id = id } if let displayName = json["displayName"].string { sku.displayName = displayName } if let size = json["size"].string { sku.size = size } sku.product = extractProduct(json["product"]) if let active = json["active"].bool { sku.active = active } if let version = json["version"].int { sku.version = version } //Extract one to many list here sku.universalPriceList = extractUniversalPriceList(json["universalPriceList"]) sku.contractPriceList = extractContractPriceList(json["contractPriceList"]) sku.fixRiceSkuPromotionList = extractFixRiceSkuPromotionList(json["fixRiceSkuPromotionList"]) sku.inventoryList = extractInventoryList(json["inventoryList"]) return sku } func extractSkuList(json:JSON) -> [Sku]?{ guard let skuListJson = json.array else{ //NSLog("extractSkuList(json:JSON): there is an error here!") return nil } var skuList = [Sku]() for element in skuListJson{ if let sku = extractSku(element){ skuList.append(sku) } } return skuList } func extractBrand(json:JSON) -> Brand?{ var brand = Brand() /* Need to find another way to process object guard let json = json else{ NSLog("There is an error here! The JSON object is nil or type is error") return nil } */ if json == nil{ return brand } if let id = json["id"].string { brand.id = id } if let brandName = json["brandName"].string { brand.brandName = brandName } if let logo = json["logo"].string { brand.logo = logo } if let remark = json["remark"].string { brand.remark = remark } if let version = json["version"].int { brand.version = version } //Extract one to many list here brand.productList = extractProductList(json["productList"]) return brand } func extractBrandList(json:JSON) -> [Brand]?{ guard let brandListJson = json.array else{ //NSLog("extractBrandList(json:JSON): there is an error here!") return nil } var brandList = [Brand]() for element in brandListJson{ if let brand = extractBrand(element){ brandList.append(brand) } } return brandList } }
24.37173
99
0.648716
bf739a038b95885d7f4504a1f3bccd51b976fe8a
8,575
// RUN: %target-swift-ide-test -reconstruct-type -source-filename %s | %FileCheck %s -implicit-check-not="FAILURE" struct Mystruct1 { // CHECK: decl: struct Mystruct1 func s1f1() -> Int { return 0 } // CHECK: decl: func s1f1() -> Int var intField = 3 // CHECK: decl: @_hasInitialValue var intField: Int // CHECK: decl: init(intField: Int) // CHECK: decl: init() } struct MyStruct2 { // CHECK: decl: struct MyStruct2 init() {} // CHECK: decl: init() init(x: Int) {} // CHECK: decl: init(x: Int) init(x: Int, y: Int) {} // CHECK: decl: init(x: Int, y: Int) } class Myclass1 { // CHECK: decl: class Myclass1 var intField = 4 // CHECK: decl: @_hasInitialValue var intField: Int // CHECK: decl: init() } func f1() { // CHECK: decl: func f1() var s1ins = Mystruct1() // Implicit ctor // CHECK: decl: @_hasInitialValue var s1ins: Mystruct1 _ = Mystruct1(intField: 1) // Implicit ctor s1ins.intField = 34 // CHECK: type: Mystruct1 // CHECK: type: Int var c1ins = Myclass1() // CHECK: decl: @_hasInitialValue var c1ins: Myclass1 // CHECK: type: Myclass1 c1ins.intField = 3 // CHECK: type: Int s1ins.s1f1() // CHECK: type: Mystruct1 // CHECK: type: (Mystruct1) -> () -> Int if let ifletf1 = Int?(1) { // FIXME: lookup incorrect for if let binding. // CHECK: decl: struct Int : {{.*}} for 'ifletf1' usr=s:14swift_ide_test2f1yyF7ifletf1L_Siv } } class Myclass2 { // CHECK: decl: class Myclass2 func f1() { // CHECK: decl: func f1() var arr1 = [1, 2] // CHECK: decl: @_hasInitialValue var arr1: [Int] // CHECK: type: Array<Int> arr1.append(1) // FIXME: missing append() // CHECK: dref: FAILURE for 'append' usr=s:Sa6appendyyxF // CHECK: type: (inout Array<Int>) -> (Int) -> () var arr2 : [Mystruct1] // CHECK: decl: var arr2: [Mystruct1] // CHECK: type: Array<Mystruct1> arr2.append(Mystruct1()) // CHECK: type: (inout Array<Mystruct1>) -> (Mystruct1) -> () var arr3 : [Myclass1] // CHECK: decl: var arr3: [Myclass1] // CHECK: type: Array<Myclass1> arr3.append(Myclass1()) // CHECK: type: (inout Array<Myclass1>) -> (Myclass1) -> () _ = Myclass2.init() // CHECK: dref: init() } } // CHECK: decl: enum MyEnum enum MyEnum { // FIXME // CHECK: decl: for 'ravioli' case ravioli // CHECK: decl: for 'pasta' case pasta // CHECK: decl: func method() -> Int func method() -> Int { return 0 } // CHECK: decl: func compare(_ other: MyEnum) -> Int func compare(_ other: MyEnum) -> Int { // CHECK: decl: let other: MyEnum return 0 } // CHECK: decl: mutating func mutatingMethod() mutating func mutatingMethod() {} } // CHECK: decl: func f2() func f2() { // CHECK: type: (MyEnum.Type) -> MyEnum var e = MyEnum.pasta // CHECK: type: (MyEnum) -> () -> Int e.method() // CHECK: (MyEnum) -> (MyEnum) -> Int e.compare(e) // CHECK: (inout MyEnum) -> () -> () e.mutatingMethod() } struct MyGenStruct1<T, U: ExpressibleByStringLiteral, V: Sequence> { // CHECK: decl: struct MyGenStruct1<T, U, V> where U : ExpressibleByStringLiteral, V : Sequence // FIXME: why are these references to the base type? // FIXME: TypeReconstruction should support Node::Kind::GenericTypeParamDecl ('fp') // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test12MyGenStruct1V1Txmfp // CHECK: decl: FAILURE for 'U' usr=s:14swift_ide_test12MyGenStruct1V1Uq_mfp // CHECK: decl: FAILURE for 'V' usr=s:14swift_ide_test12MyGenStruct1V1Vq0_mfp let x: T // CHECK: decl: let x: T let y: U // CHECK: decl: let y: U let z: V // CHECK: decl: let z: V func test000() { _ = x // CHECK: type: T _ = y // CHECK: type: U _ = z // CHECK: type: V } // CHECK: decl: func takesT(_ t: T) func takesT(_ t: T) { // CHECK: decl: let t: T } } let genstruct1 = MyGenStruct1<Int, String, [Float]>(x: 1, y: "", z: [1.0]) // CHECK: decl: @_hasInitialValue let genstruct1: MyGenStruct1<Int, String, [Float]> func test001() { // CHECK: decl: func test001() _ = genstruct1 // CHECK: type: MyGenStruct1<Int, String, Array<Float>> var genstruct2: MyGenStruct1<Int, String, [Int: Int]> // CHECK: decl: var genstruct2: MyGenStruct1<Int, String, [Int : Int]> _ = genstruct2 // CHECK: type: MyGenStruct1<Int, String, Dictionary<Int, Int>> _ = genstruct2.x // CHECK: type: Int _ = genstruct2.y // CHECK: type: String _ = genstruct2.z // CHECK: type: Dictionary<Int, Int> genstruct2.takesT(123) } // CHECK: decl: protocol P1 protocol P1 {} // CHECK: decl: func foo1(p: P1) func foo1(p: P1) { // CHECK: decl: let p: P1 // CHECK: type: (P1) -> () foo1(p: p) } // CHECK: decl: protocol P2 protocol P2 {} // CHECK: decl: func foo2(p: P1 & P2) func foo2(p: P1 & P2) { // CHECK: decl: let p: P1 & P2 foo2(p: p) } // CHECK: func foo3(p: P1 & AnyObject) func foo3(p: P1 & AnyObject) { // CHECK: decl: let p: P1 & AnyObject foo3(p: p) } // CHECK: func foo4(p: Myclass1 & P1 & P2) func foo4(p: P1 & P2 & Myclass1) { // CHECK: decl: let p: Myclass1 & P1 & P2 foo4(p: p) } func genericFunction<T : AnyObject>(t: T) { // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test15genericFunction1tyx_tRlzClF1TL_xmfp genericFunction(t: t) } // CHECK: decl: func takesInOut(fn: (inout Int) -> ()) // CHECK: decl: let fn: (inout Int) -> () for 'fn' func takesInOut(fn: (inout Int) -> ()) {} struct Outer { struct Inner { let x: Int } struct GenericInner<T> { // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test5OuterV12GenericInnerV1Txmfp let t: T } } struct GenericOuter<T> { // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test12GenericOuterV1Txmfp struct Inner { let t: T let x: Int } struct GenericInner<U> { // CHECK: decl: FAILURE for 'U' usr=s:14swift_ide_test12GenericOuterV0D5InnerV1Uqd__mfp let t: T let u: U } } // CHECK: decl: func takesGeneric(_ t: Outer.GenericInner<Int>) func takesGeneric(_ t: Outer.GenericInner<Int>) { takesGeneric(t) } // CHECK: decl: func takesGeneric(_ t: GenericOuter<Int>.Inner) func takesGeneric(_ t: GenericOuter<Int>.Inner) { takesGeneric(t) } // CHECK: decl: func takesGeneric(_ t: GenericOuter<Int>.GenericInner<String>) func takesGeneric(_ t: GenericOuter<Int>.GenericInner<String>) { takesGeneric(t) } func hasLocalDecls() { func localFunction() {} // FIXME // CHECK: decl: FAILURE for 'LocalType' struct LocalType { // CHECK: FAILURE for 'localMethod' func localMethod() {} // CHECK: FAILURE for 'subscript' subscript(x: Int) { get {} set {} } // CHECK: decl: FAILURE for '' // CHECK: decl: FAILURE for '' // CHECK: decl: FAILURE for '' } // FIXME // CHECK: decl: FAILURE for 'LocalClass' class LocalClass { // CHECK: FAILURE for 'deinit' deinit {} // CHECK: decl: FAILURE for '' } // CHECK: decl: FAILURE for 'LocalAlias' typealias LocalAlias = LocalType } fileprivate struct VeryPrivateData {} // CHECK: decl: fileprivate func privateFunction(_ d: VeryPrivateData) for 'privateFunction' fileprivate func privateFunction(_ d: VeryPrivateData) {} struct HasSubscript { // CHECK: decl: subscript(t: Int) -> Int { get set } subscript(_ t: Int) -> Int { // CHECK: decl: get {} for '' usr=s:14swift_ide_test12HasSubscriptVyS2icig get { return t } // CHECK: decl: set {} for '' usr=s:14swift_ide_test12HasSubscriptVyS2icis set {} } } // FIXME // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test19HasGenericSubscriptV1Txmfp struct HasGenericSubscript<T> { // CHECK: subscript<U>(t: T) -> U { get set } for 'subscript' usr=s:14swift_ide_test19HasGenericSubscriptVyqd__xclui // FIXME // CHECK: decl: FAILURE for 'U' // FIXME // CHECK: decl: FAILURE for 't' subscript<U>(_ t: T) -> U { // CHECK: decl: get {} for '' usr=s:14swift_ide_test19HasGenericSubscriptVyqd__xcluig // FIXME // CHECK: dref: FAILURE for 't' get { return t as! U } // CHECK: decl: set {} for '' usr=s:14swift_ide_test19HasGenericSubscriptVyqd__xcluis set {} } } private // CHECK: decl: private func patatino<T>(_ vers1: T, _ vers2: T) -> Bool where T : Comparable for func patatino<T: Comparable>(_ vers1: T, _ vers2: T) -> Bool { // CHECK: decl: FAILURE for 'T' usr=s:14swift_ide_test8patatino33_D7B956AE2D93947DFA67A1ECF93EF238LLySbx_xtSLRzlF1TL_xmfp decl // CHECK: decl: let vers1: T for 'vers1' usr=s:14swift_ide_test8patatino33_D7B956AE2D93947DFA67A1ECF93EF238LLySbx_xtSLRzlF5vers1L_xvp // CHECK: decl: let vers2: T for 'vers2' usr=s:14swift_ide_test8patatino33_D7B956AE2D93947DFA67A1ECF93EF238LLySbx_xtSLRzlF5vers2L_xvp return vers1 < vers2; }
25.750751
140
0.655627
50dc0ce6d6e368dbc246313ac56969692b2f26f6
171
import Foundation public func example(of description: String, action: () -> Void) { print("\n——— Example of:", description, "———") action() }
21.375
50
0.549708
b90ae08829208af9c32d0ea21fb47802dca661b0
311
#if arch(x86_64) || arch(arm64) import SwiftUI @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) final class AnglePresenter: ObservableObject { @Published var animation: Animation? @Published var value: Double = .zero @Published var range: ClosedRange<Double> = .zero ... 360 } #endif
23.923077
61
0.697749
f47678c5b81c0ba22e239cbaee443cecde0e6971
2,950
// // RealmKeyboard.swift // Georgian Keyboard // // Created by Giorgi Shavgulidze on 15/09/16. // Copyright © 2016 Giorgi Shavgulidze. All rights reserved. // import Foundation import RealmSwift import ObjectMapper import JASON enum RealmKeyboardOrientation: String { case Portrait = "portrait" case Landscape = "landscape" } class RealmKeyboard: Object, Mappable { dynamic var portraitInfo: RealmKeyboardInfo? dynamic var landscapeInfo: RealmKeyboardInfo? var languages = List<RealmKeyboardLanguage>() dynamic var bottom: RealmKeyboardLine? required convenience init?(map: Map) { self.init() } func mapping(map: Map) { portraitInfo <- map["portrait_info"] landscapeInfo <- map["landscape_info"] languages <- (map["languages"], ArrayTransform<RealmKeyboardLanguage>()) bottom <- map["bottom"] } } extension RealmKeyboard { class func initWithJsonString(jsonString: String) -> RealmKeyboard? { return Mapper<RealmKeyboard>().map(JSONString: jsonString) } } extension RealmKeyboard { func precalculate() { guard let portraitInfo = portraitInfo, let landscapeInfo = landscapeInfo else { print("Couldn't find keyboard info") return } let botLineHeightPortrait: Float = portraitInfo.height / 4 let topLineHeightPortrait: Float = portraitInfo.height - botLineHeightPortrait let botLineHeightLandscape: Float = landscapeInfo.height / 4 let topLineHeightLandscape: Float = landscapeInfo.height - botLineHeightLandscape for language in languages { language.precalculate(orientation: RealmKeyboardOrientation.Portrait, originX: 0, width: portraitInfo.width, originY: 0, height: topLineHeightPortrait) language.precalculate(orientation: RealmKeyboardOrientation.Landscape, originX: 0, width: landscapeInfo.width, originY: 0, height: topLineHeightLandscape) } bottom?.precalculate(orientation: RealmKeyboardOrientation.Portrait, widthTotal: portraitInfo.width, curX: 0, curY: topLineHeightPortrait, height: botLineHeightPortrait) bottom?.precalculate(orientation: RealmKeyboardOrientation.Landscape, widthTotal: landscapeInfo.width, curX: 0, curY: topLineHeightLandscape, height: botLineHeightLandscape) } }
35.119048
89
0.57322
33addaf0790f77708cb327dcfeb9d6fc4415964e
16,742
// // Single.swift // RxSwift // // Created by sergdort on 19/08/2017. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // #if DEBUG import Foundation #endif /// Sequence containing exactly 1 element public enum SingleTrait { } /// Represents a push style sequence containing 1 element. public typealias Single<Element> = PrimitiveSequence<SingleTrait, Element> public typealias SingleEvent<Element> = Result<Element, Swift.Error> extension PrimitiveSequenceType where Trait == SingleTrait { public typealias SingleObserver = (SingleEvent<Element>) -> Void /** Creates an observable sequence from a specified subscribe method implementation. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. - returns: The observable sequence with the specified implementation for the `subscribe` method. */ public static func create(subscribe: @escaping (@escaping SingleObserver) -> Disposable) -> Single<Element> { let source = Observable<Element>.create { observer in return subscribe { event in switch event { case .success(let element): observer.on(.next(element)) observer.on(.completed) case .failure(let error): observer.on(.error(error)) } } } return PrimitiveSequence(raw: source) } /** Subscribes `observer` to receive events for this sequence. - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. */ public func subscribe(_ observer: @escaping (SingleEvent<Element>) -> Void) -> Disposable { var stopped = false return self.primitiveSequence.asObservable().subscribe { event in if stopped { return } stopped = true switch event { case .next(let element): observer(.success(element)) case .error(let error): observer(.failure(error)) case .completed: rxFatalErrorInDebug("Singles can't emit a completion event") } } } /** Subscribes a success handler, and an error handler for this sequence. - parameter onSuccess: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is canceled by disposing subscription). - returns: Subscription object used to unsubscribe from the observable sequence. */ @available(*, deprecated, renamed: "subscribe(onSuccess:onFailure:onDisposed:)") public func subscribe(onSuccess: ((Element) -> Void)? = nil, onError: @escaping ((Swift.Error) -> Void), onDisposed: (() -> Void)? = nil) -> Disposable { subscribe(onSuccess: onSuccess, onFailure: onError, onDisposed: onDisposed) } /** Subscribes a success handler, and an error handler for this sequence. - parameter onSuccess: Action to invoke for each element in the observable sequence. - parameter onFailure: Action to invoke upon errored termination of the observable sequence. - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is canceled by disposing subscription). - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe(onSuccess: ((Element) -> Void)? = nil, onFailure: ((Swift.Error) -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { #if DEBUG let callStack = Hooks.recordCallStackOnError ? Thread.callStackSymbols : [] #else let callStack = [String]() #endif let disposable: Disposable if let onDisposed = onDisposed { disposable = Disposables.create(with: onDisposed) } else { disposable = Disposables.create() } let observer: SingleObserver = { event in switch event { case .success(let element): onSuccess?(element) disposable.dispose() case .failure(let error): if let onFailure = onFailure { onFailure(error) } else { Hooks.defaultErrorHandler(callStack, error) } disposable.dispose() } } return Disposables.create( self.primitiveSequence.subscribe(observer), disposable ) } } extension PrimitiveSequenceType where Trait == SingleTrait { /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: Element) -> Single<Element> { Single(raw: Observable.just(element)) } /** Returns an observable sequence that contains a single element. - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) - parameter element: Single element in the resulting observable sequence. - parameter scheduler: Scheduler to send the single element on. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Single<Element> { Single(raw: Observable.just(element, scheduler: scheduler)) } /** Returns an observable sequence that terminates with an `error`. - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: The observable sequence that terminates with specified error. */ public static func error(_ error: Swift.Error) -> Single<Element> { PrimitiveSequence(raw: Observable.error(error)) } /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) - returns: An observable sequence whose observers will never get called. */ public static func never() -> Single<Element> { PrimitiveSequence(raw: Observable.never()) } } extension PrimitiveSequenceType where Trait == SingleTrait { /** Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) - parameter onSuccess: Action to invoke for each element in the observable sequence. - parameter afterSuccess: Action to invoke for each element after the observable has passed an onNext event along to its downstream. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter afterError: Action to invoke after errored termination of the observable sequence. - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. - returns: The source sequence with the side-effecting behavior applied. */ public func `do`(onSuccess: ((Element) throws -> Void)? = nil, afterSuccess: ((Element) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, afterError: ((Swift.Error) throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Single<Element> { return Single(raw: self.primitiveSequence.source.do( onNext: onSuccess, afterNext: afterSuccess, onError: onError, afterError: afterError, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) ) } /** Filters the elements of an observable sequence based on a predicate. - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. */ public func filter(_ predicate: @escaping (Element) throws -> Bool) -> Maybe<Element> { return Maybe(raw: self.primitiveSequence.source.filter(predicate)) } /** Projects each element of an observable sequence into a new form. - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) - parameter transform: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. */ public func map<Result>(_ transform: @escaping (Element) throws -> Result) -> Single<Result> { return Single(raw: self.primitiveSequence.source.map(transform)) } /** Projects each element of an observable sequence into an optional form and filters all optional results. - parameter transform: A transform function to apply to each source element. - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. */ public func compactMap<Result>(_ transform: @escaping (Element) throws -> Result?) -> Maybe<Result> { Maybe(raw: self.primitiveSequence.source.compactMap(transform)) } /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ public func flatMap<Result>(_ selector: @escaping (Element) throws -> Single<Result>) -> Single<Result> { return Single<Result>(raw: self.primitiveSequence.source.flatMap(selector)) } /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ public func flatMapMaybe<Result>(_ selector: @escaping (Element) throws -> Maybe<Result>) -> Maybe<Result> { return Maybe<Result>(raw: self.primitiveSequence.source.flatMap(selector)) } /** Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) - parameter selector: A transform function to apply to each element. - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. */ public func flatMapCompletable(_ selector: @escaping (Element) throws -> Completable) -> Completable { return Completable(raw: self.primitiveSequence.source.flatMap(selector)) } /** Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ public static func zip<Collection: Swift.Collection, Result>(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> PrimitiveSequence<Trait, Result> where Collection.Element == PrimitiveSequence<Trait, Element> { if collection.isEmpty { return PrimitiveSequence<Trait, Result>.deferred { return PrimitiveSequence<Trait, Result>(raw: .just(try resultSelector([]))) } } let raw = Observable.zip(collection.map { $0.asObservable() }, resultSelector: resultSelector) return PrimitiveSequence<Trait, Result>(raw: raw) } /** Merges the specified observable sequences into one observable sequence all of the observable sequences have produced an element at a corresponding index. - returns: An observable sequence containing the result of combining elements of the sources. */ public static func zip<Collection: Swift.Collection>(_ collection: Collection) -> PrimitiveSequence<Trait, [Element]> where Collection.Element == PrimitiveSequence<Trait, Element> { if collection.isEmpty { return PrimitiveSequence<Trait, [Element]>(raw: .just([])) } let raw = Observable.zip(collection.map { $0.asObservable() }) return PrimitiveSequence(raw: raw) } /** Continues an observable sequence that is terminated by an error with a single element. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - parameter element: Last element in an observable sequence in case error occurs. - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. */ public func catchAndReturn(_ element: Element) -> PrimitiveSequence<Trait, Element> { PrimitiveSequence(raw: self.primitiveSequence.source.catchAndReturn(element)) } /** Continues an observable sequence that is terminated by an error with a single element. - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) - parameter element: Last element in an observable sequence in case error occurs. - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. */ @available(*, deprecated, renamed: "catchAndReturn(_:)") public func catchErrorJustReturn(_ element: Element) -> PrimitiveSequence<Trait, Element> { catchAndReturn(element) } /// Converts `self` to `Maybe` trait. /// /// - returns: Maybe trait that represents `self`. public func asMaybe() -> Maybe<Element> { Maybe(raw: self.primitiveSequence.source) } /// Converts `self` to `Completable` trait, ignoring its emitted value if /// one exists. /// /// - returns: Completable trait that represents `self`. public func asCompletable() -> Completable { self.primitiveSequence.source.ignoreElements().asCompletable() } }
45.494565
246
0.67029
61c749c60bc94dce59365125e7aa69938e20167f
905
// // ExampleStaticHeightView.swift // WSPopup // // Created by Ricardo Pereira on 04/02/2019. // Copyright © 2019 Whitesmith. All rights reserved. // import UIKit class ExampleStaticHeightView: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .red let titleLabel = UILabel() titleLabel.text = "OMG!" titleLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(titleLabel) NSLayoutConstraint.activate([ titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor), titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor), ]) NSLayoutConstraint.activate([ heightAnchor.constraint(equalToConstant: 200) ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
24.459459
72
0.658564
613eb70339d2b77ee8f656e1cd4c5e9e99c2eedd
2,143
// // AppDelegate.swift // SLGoogleMenuDemo // // Created by WangZHW on 16/6/4. // Copyright © 2016年 RobuSoft. 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.595745
285
0.75455
50474626e0c8164e7c3e85609f34171bb7efe8ec
625
// // MainViewController.swift // TestDY // // Created by HYJ on 17/5/16. // Copyright © 2017年 HYJ. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() tabBar.tintColor = UIColor.orangeColor() addChildVc("Home") addChildVc("Live") addChildVc("Follow") addChildVc("Profile") } private func addChildVc(storyName:String){ let chidlVc = UIStoryboard(name: storyName, bundle: nil).instantiateInitialViewController()! addChildViewController(chidlVc) } }
20.833333
100
0.6528
387c94de3d1fa367e1dcaa09e8afa0a565ed22e1
615
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "CommonKit", platforms: [.iOS(.v15), .macOS(.v12)], products: [ .library(name: "CommonUtils", targets: ["CommonUtils"]), .library(name: "CommonUI", targets: ["CommonUI"]), .library(name: "RenderingKit", targets: ["RenderingKit"]) ], targets: [ .target(name: "CommonUtils"), .target(name: "CommonUI"), .target(name: "RenderingKit", dependencies: ["CommonUtils"]) ], swiftLanguageVersions: [.v5] )
29.285714
96
0.669919
db4963e050fa52ac69a8ee87cb1677541d5ced77
3,376
import XCTest import NIOCore import NIOTestUtils @testable import PostgresNIO class ParameterStatusTests: XCTestCase { func testDecode() { var buffer = ByteBuffer() let expected: [PSQLBackendMessage] = [ .parameterStatus(.init(parameter: "DateStyle", value: "ISO, MDY")), .parameterStatus(.init(parameter: "application_name", value: "")), .parameterStatus(.init(parameter: "server_encoding", value: "UTF8")), .parameterStatus(.init(parameter: "integer_datetimes", value: "on")), .parameterStatus(.init(parameter: "client_encoding", value: "UTF8")), .parameterStatus(.init(parameter: "TimeZone", value: "Etc/UTC")), .parameterStatus(.init(parameter: "is_superuser", value: "on")), .parameterStatus(.init(parameter: "server_version", value: "13.1 (Debian 13.1-1.pgdg100+1)")), .parameterStatus(.init(parameter: "session_authorization", value: "postgres")), .parameterStatus(.init(parameter: "IntervalStyle", value: "postgres")), .parameterStatus(.init(parameter: "standard_conforming_strings", value: "on")), .backendKeyData(.init(processID: 1234, secretKey: 5678)) ] expected.forEach { message in switch message { case .parameterStatus(let parameterStatus): buffer.writeBackendMessage(id: .parameterStatus) { buffer in buffer.writeNullTerminatedString(parameterStatus.parameter) buffer.writeNullTerminatedString(parameterStatus.value) } case .backendKeyData(let backendKeyData): buffer.writeBackendMessage(id: .backendKeyData) { buffer in buffer.writeInteger(backendKeyData.processID) buffer.writeInteger(backendKeyData.secretKey) } default: XCTFail("Unexpected message type") } } XCTAssertNoThrow(try ByteToMessageDecoderVerifier.verifyDecoder( inputOutputPairs: [(buffer, expected)], decoderFactory: { PSQLBackendMessageDecoder(hasAlreadyReceivedBytes: true) })) } func testDecodeFailureBecauseOfMissingNullTermination() { var buffer = ByteBuffer() buffer.writeBackendMessage(id: .parameterStatus) { buffer in buffer.writeString("DateStyle") buffer.writeString("ISO, MDY") } XCTAssertThrowsError(try ByteToMessageDecoderVerifier.verifyDecoder( inputOutputPairs: [(buffer, [])], decoderFactory: { PSQLBackendMessageDecoder(hasAlreadyReceivedBytes: true) })) { XCTAssert($0 is PSQLDecodingError) } } func testDecodeFailureBecauseOfMissingNullTerminationInValue() { var buffer = ByteBuffer() buffer.writeBackendMessage(id: .parameterStatus) { buffer in buffer.writeNullTerminatedString("DateStyle") buffer.writeString("ISO, MDY") } XCTAssertThrowsError(try ByteToMessageDecoderVerifier.verifyDecoder( inputOutputPairs: [(buffer, [])], decoderFactory: { PSQLBackendMessageDecoder(hasAlreadyReceivedBytes: true) })) { XCTAssert($0 is PSQLDecodingError) } } }
44.421053
106
0.625592
910dfc5dde0adb80619cd14cdb0908ba70506630
12,030
// // Link.swift // KMLKit // // Created by Weston Bustraan on 2/25/21. // import Foundation import CoreGraphics import XMLDocument @objc public protocol KMLAbstractLink: class { var href: URL? { get set } } open class KMLBasicLink: KMLObject, KMLAbstractLink { @objc open var href: URL? public override init() { super.init() } public init(href: String) { super.init() self.href = URL(string: href) } public init(href: URL) { super.init() self.href = href } internal override init(_ attributes: [String : String]) { super.init(attributes) } // MARK: - XMLWriterNode override func addChildNodes(to element: XMLElement, in doc: XMLDocument) { super.addChildNodes(to: element, in: doc) addSimpleChild(to: element, withName: "href", value: href?.description) } } /** &lt;Link&gt; specifies the location of any of the following: - KML files fetched by network links - Image files used in any Overlay (the &lt;Icon&gt; element specifies the image in an Overlay; &lt;Icon&gt; has the same fields as &lt;Link&gt;) - Model files used in the &lt;Model&gt; element The file is conditionally loaded and refreshed, depending on the refresh parameters supplied here. Two different sets of refresh parameters can be specified: one set is based on time (&lt;refreshMode&gt; and &lt;refreshInterval&gt;) and one is based on the current "camera" view (&lt;viewRefreshMode&gt; and &lt;viewRefreshTime&gt;). In addition, Link specifies whether to scale the bounding box parameters that are sent to the server (&lt;viewBoundScale&gt; and provides a set of optional viewing parameters that can be sent to the server (&lt;viewFormat&gt;) as well as a set of optional parameters containing version and language information. When a file is fetched, the URL that is sent to the server is composed of three pieces of information: - the href (Hypertext Reference) that specifies the file to load. - an arbitrary format string that is created from (a) parameters that you specify in the &lt;viewFormat&gt; element or (b) bounding box parameters (this is the default and is used if no &lt;viewFormat&gt; element is included in the file). - a second format string that is specified in the &lt;httpQuery&gt; element. If the file specified in &lt;href&gt; is a local file, the &lt;viewFormat&gt; and &lt;httpQuery&gt; elements are not used. The &lt;Link&gt; element replaces the &lt;Url&gt; element of &lt;NetworkLink&gt; contained in earlier KML releases and adds functionality for the &lt;Region&gt; element (introduced in KML 2.1). In Google Earth releases 3.0 and earlier, the &lt;Link&gt; element is ignored. */ open class KMLLink: KMLBasicLink { /** Specifies a time-based refresh mode */ @objc open var refreshMode = KMLRefreshMode.onChange /** Indicates to refresh the file every n seconds. */ @objc open var refreshInterval: Double = 4.0 /** Specifies how the link is refreshed when the "camera" changes. */ @objc open var viewRefreshMode = KMLViewRefreshMode.never /** After camera movement stops, specifies the number of seconds to wait before refreshing the view. (See *viewRefreshMode* and onStop above.) */ @objc open var viewRefreshTime: Double = 4.0 /** Scales the BBOX parameters before sending them to the server. A value less than 1 specifies to use less than the full view (screen). A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. */ @objc open var viewBoundScale: Double = 1.0 /** Specifies the format of the query string that is appended to the Link's &lt;href&gt; before the file is fetched.(If the &lt;href&gt; specifies a local file, this element is ignored.) If you specify a &lt;viewRefreshMode&gt; of onStop and do not include the &lt;viewFormat&gt; tag in the file, the following information is automatically appended to the query string: ``` BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth] ``` This information matches the Web Map Service (WMS) bounding box specification. If you specify an empty &lt;viewFormat&gt; tag, no information is appended to the query string. You can also specify a custom set of viewing parameters to add to the query string. If you supply a format string, it is used instead of the BBOX information. If you also want the BBOX information, you need to add those parameters along with the custom parameters. You can use any of the following parameters in your format string (and Google Earth will substitute the appropriate current value at the time it creates the query string): - **[lookatLon]**, **[lookatLat]** - longitude and latitude of the point that &lt;LookAt&gt; is viewing - **[lookatRange]**, **[lookatTilt]**, **[lookatHeading]** - values used by the &lt;LookAt&gt; element (see descriptions of &lt;range&gt;, &lt;tilt&gt;, and &lt;heading&gt; in &lt;LookAt&gt;) - **[lookatTerrainLon]**, **[lookatTerrainLat]**, **[lookatTerrainAlt]** - point on the terrain in degrees/meters that &lt;LookAt&gt; is viewing - **[cameraLon]**, **[cameraLat]**, **[cameraAlt]** - degrees/meters of the eyepoint for the camera - **[horizFov]**, **[vertFov]** - horizontal, vertical field of view for the camera - **[horizPixels]**, **[vertPixels]** - size in pixels of the 3D viewer - **[terrainEnabled]** - indicates whether the 3D viewer is showing terrain*/ @objc open var viewFormat: String? /** Appends information to the query string, based on the parameters specified. (Google Earth substitutes the appropriate current value at the time it creates the query string.) The following parameters are supported: - [clientVersion] - [kmlVersion] - [clientName] - [language] */ @objc open var httpQuery: String? @objc public enum KMLRefreshMode: Int, CustomStringConvertible { /** refresh when the file is loaded and whenever the Link parameters change (the default). */ case onChange /** refresh every n seconds (specified in &lt;refreshInterval&gt;). */ case onInterval /** refresh the file when the expiration time is reached. If a fetched file has a NetworkLinkControl, the &lt;expires&gt; time takes precedence over expiration times specified in HTTP headers. If no &lt;expires&gt; time is specified, the HTTP max-age header is used (if present). If max-age is not present, the Expires HTTP header is used (if present). (See Section RFC261b of the Hypertext Transfer Protocol - HTTP 1.1 for details on HTTP header fields.) */ case onExpire init(_ value: String) { switch value { case "onChange": self = .onChange case "onInterval": self = .onInterval case "onExpire": self = .onExpire default: self = .onChange } } public var description: String { switch self { case .onChange: return "onChange" case .onInterval: return "onInterval" case .onExpire: return "onExpire" } } } @objc public enum KMLViewRefreshMode: Int, CustomStringConvertible { /** Ignore changes in the view. Also ignore &lt;viewFormat&gt; parameters, if any. */ case never /** Refresh the file only when the user explicitly requests it. (For example, in Google Earth, the user right-clicks and selects Refresh in the Context menu.) */ case onRequest /** Refresh the file *n* seconds after movement stops, where *n* is specified in &lt;viewRefreshTime&gt;. */ case onStop /** Refresh the file when the Region becomes active. */ case onRegion init(_ value: String) { switch value { case "never": self = .never case "onRequest": self = .onRequest case "onStop": self = .onStop case "onRegion": self = .onRegion default: self = .never } } public var description: String { switch self { case .never: return "never" case .onRequest: return "onRequest" case .onStop: return "onStop" case .onRegion: return "onRegion" } } } public override init() { super.init() } public override init(href: String) { super.init(href: href) } public override init(href: URL) { super.init(href: href) } internal override init(_ attributes: [String:String]) { super.init(attributes) if let href = attributes["href"] { self.href = URL(string: href) } } open override func setValue(_ value: Any?, forKey key: String) { if key == "refreshMode", let refreshMode = value as? KMLRefreshMode { self.refreshMode = refreshMode } else if key == "viewRefreshMode", let viewRefreshMode = value as? KMLViewRefreshMode { self.viewRefreshMode = viewRefreshMode } else { super.setValue(value, forKey: key) } } override func addChildNodes(to element: XMLElement, in doc: XMLDocument) { super.addChildNodes(to: element, in: doc) addSimpleChild(to: element, withName: "refreshMode", value: refreshMode.description, default: "onChange") addSimpleChild(to: element, withName: "refreshInterval", value: refreshInterval, default: 4.0) addSimpleChild(to: element, withName: "viewRefreshMode", value: viewRefreshMode.description, default: "never") addSimpleChild(to: element, withName: "viewRefreshTime", value: viewRefreshTime, default: 4.0) addSimpleChild(to: element, withName: "viewBoundScale", value: viewBoundScale, default: 1.0) addSimpleChild(to: element, withName: "viewFormat", value: viewFormat) addSimpleChild(to: element, withName: "httpQuery", value: httpQuery) } } /** Defines an image associated with an Icon style or overlay. The required &lt;href&gt; child element defines the location of the image to be used as the overlay or as the icon for the placemark. This location can either be on a local file system or a remote web server. */ open class KMLIcon: KMLLink { /** The &lt;gx:x&gt;, &lt;gx:y&gt;, &lt;gx:w&gt;, and &lt;gx:h&gt; elements are used to select one icon from an image that contains multiple icons (often referred to as an icon palette. */ @objc var frame = CGRect() open override func setValue(_ value: Any?, forKey key: String) { if key == "x", let x = value as? Double { frame.origin.x = CGFloat(x) } else if key == "y", let y = value as? Double { frame.origin.y = CGFloat(y) } else if key == "w", let w = value as? Double { frame.size.width = CGFloat(w) } else if key == "h", let h = value as? Double { frame.size.height = CGFloat(h) } else { super.setValue(value, forKey: key) } } override func addChildNodes(to element: XMLElement, in doc: XMLDocument) { super.addChildNodes(to: element, in: doc) if frame != CGRect() { addSimpleChild(to: element, withName: "gx:x", value: frame.origin.x) addSimpleChild(to: element, withName: "gx:y", value: frame.origin.y) addSimpleChild(to: element, withName: "gx:w", value: frame.size.width) addSimpleChild(to: element, withName: "gx:h", value: frame.size.height) } } }
45.05618
646
0.642062
f95afcc76cdb5bdc282975f51ce404ed92167039
24,646
// Copyright © MonitorControl. @JoniVR, @theOneyouseek, @waydabber and others import Cocoa import IOKit import os.log class OtherDisplay: Display { var ddc: IntelDDC? var arm64ddc: Bool = false var arm64avService: IOAVService? var isDiscouraged: Bool = false var pollingCount: Int { get { switch self.readPrefAsInt(key: .pollingMode) { case PollingMode.none.rawValue: return 0 case PollingMode.minimal.rawValue: return 1 case PollingMode.normal.rawValue: return 5 case PollingMode.heavy.rawValue: return 20 case PollingMode.custom.rawValue: return prefs.integer(forKey: PrefKey.pollingCount.rawValue + self.prefsId) default: return PollingMode.none.rawValue } } set { prefs.set(newValue, forKey: PrefKey.pollingCount.rawValue + self.prefsId) } } override init(_ identifier: CGDirectDisplayID, name: String, vendorNumber: UInt32?, modelNumber: UInt32?, isVirtual: Bool = false, isDummy: Bool = false) { super.init(identifier, name: name, vendorNumber: vendorNumber, modelNumber: modelNumber, isVirtual: isVirtual, isDummy: isDummy) if !isVirtual, !Arm64DDC.isArm64 { self.ddc = IntelDDC(for: identifier) } } func processCurrentDDCValue(isReadFromDisplay: Bool, command: Command, firstrun: Bool, currentDDCValue: UInt16) { if isReadFromDisplay { var currentValue = self.convDDCToValue(for: command, from: currentDDCValue) if !prefs.bool(forKey: PrefKey.disableCombinedBrightness.rawValue), command == .brightness { os_log("- Combined brightness mapping on DDC data.", type: .info) if currentValue > 0 { currentValue = self.combinedBrightnessSwitchingValue() + currentValue * (1 - self.combinedBrightnessSwitchingValue()) } else if currentValue == 0, firstrun, prefs.integer(forKey: PrefKey.startupAction.rawValue) != StartupAction.write.rawValue { currentValue = self.combinedBrightnessSwitchingValue() } else if self.prefExists(for: command), self.readPrefAsFloat(for: command) <= self.combinedBrightnessSwitchingValue() { currentValue = self.readPrefAsFloat(for: command) } else { currentValue = self.combinedBrightnessSwitchingValue() } } self.savePref(currentValue, for: command) if command == .brightness { self.smoothBrightnessTransient = currentValue } } else { var currentValue: Float = self.readPrefAsFloat(for: command) if !prefs.bool(forKey: PrefKey.disableCombinedBrightness.rawValue), command == .brightness { os_log("- Combined brightness mapping on saved data.", type: .info) if !self.prefExists(for: command) { currentValue = self.combinedBrightnessSwitchingValue() + self.convDDCToValue(for: command, from: currentDDCValue) * (1 - self.combinedBrightnessSwitchingValue()) } else if firstrun, currentValue < self.combinedBrightnessSwitchingValue(), prefs.integer(forKey: PrefKey.startupAction.rawValue) != StartupAction.write.rawValue { currentValue = self.combinedBrightnessSwitchingValue() } } else { currentValue = self.prefExists(for: command) ? self.readPrefAsFloat(for: command) : self.convDDCToValue(for: command, from: currentDDCValue) } self.savePref(currentValue, for: command) if command == .brightness { self.smoothBrightnessTransient = currentValue } } } func getDDCValueFromPrefs(_ command: Command) -> UInt16 { return self.convValueToDDC(for: command, from: (!prefs.bool(forKey: PrefKey.disableCombinedBrightness.rawValue) && command == .brightness) ? max(0, self.readPrefAsFloat(for: command) - self.combinedBrightnessSwitchingValue()) * (1 / (1 - self.combinedBrightnessSwitchingValue())) : self.readPrefAsFloat(for: command)) } func restoreDDCSettingsToDisplay(command: Command) { if !self.smoothBrightnessRunning, !self.isSw(), !self.readPrefAsBool(key: .unavailableDDC, for: command), self.readPrefAsBool(key: .isTouched, for: command), prefs.integer(forKey: PrefKey.startupAction.rawValue) == StartupAction.write.rawValue, !app.safeMode { let restoreValue = self.getDDCValueFromPrefs(command) os_log("Restoring %{public}@ DDC value %{public}@ for %{public}@", type: .info, String(reflecting: command), String(restoreValue), self.name) _ = self.writeDDCValues(command: command, value: restoreValue) if command == .audioSpeakerVolume, self.readPrefAsBool(key: .enableMuteUnmute) { let currentMuteValue = self.readPrefAsInt(for: .audioMuteScreenBlank) == 0 ? 2 : self.readPrefAsInt(for: .audioMuteScreenBlank) os_log("- Writing last saved DDC value for Mute: %{public}@", type: .info, String(currentMuteValue)) _ = self.writeDDCValues(command: .audioMuteScreenBlank, value: UInt16(currentMuteValue)) } } } func setupCurrentAndMaxValues(command: Command, firstrun: Bool = false) { var ddcValues: (UInt16, UInt16)? var maxDDCValue = UInt16(DDC_MAX_DETECT_LIMIT) var currentDDCValue: UInt16 switch command { case .audioSpeakerVolume: currentDDCValue = UInt16(Float(DDC_MAX_DETECT_LIMIT) * 0.125) case .contrast: currentDDCValue = UInt16(Float(DDC_MAX_DETECT_LIMIT) * 0.750) default: currentDDCValue = UInt16(Float(DDC_MAX_DETECT_LIMIT) * 1.000) } if command == .audioSpeakerVolume { currentDDCValue = UInt16(Float(DDC_MAX_DETECT_LIMIT) * 0.125) // lower default audio value as high volume might rattle the user. } os_log("Setting up display %{public}@ for %{public}@", type: .info, String(self.identifier), String(reflecting: command)) if !self.isSw() { if prefs.integer(forKey: PrefKey.startupAction.rawValue) == StartupAction.read.rawValue, self.pollingCount != 0, !app.safeMode { os_log("- Reading DDC from display %{public}@ times", type: .info, String(self.pollingCount)) let delay = self.readPrefAsBool(key: .longerDelay) ? UInt64(40 * kMillisecondScale) : nil ddcValues = self.readDDCValues(for: command, tries: UInt(self.pollingCount), minReplyDelay: delay) if ddcValues != nil { (currentDDCValue, maxDDCValue) = ddcValues ?? (currentDDCValue, maxDDCValue) self.processCurrentDDCValue(isReadFromDisplay: true, command: command, firstrun: firstrun, currentDDCValue: currentDDCValue) os_log("- DDC read successful.", type: .info) } else { os_log("- DDC read failed.", type: .info) } } else { os_log("- DDC read disabled.", type: .info) } if self.readPrefAsInt(key: .maxDDCOverride, for: command) > self.readPrefAsInt(key: .minDDCOverride, for: command) { self.savePref(self.readPrefAsInt(key: .maxDDCOverride, for: command), key: .maxDDC, for: command) } else { self.savePref(min(Int(maxDDCValue), DDC_MAX_DETECT_LIMIT), key: .maxDDC, for: command) } if ddcValues == nil { self.processCurrentDDCValue(isReadFromDisplay: false, command: command, firstrun: firstrun, currentDDCValue: currentDDCValue) currentDDCValue = self.getDDCValueFromPrefs(command) } os_log("- Current DDC value: %{public}@", type: .info, String(currentDDCValue)) os_log("- Minimum DDC value: %{public}@ (overrides 0)", type: .info, String(self.readPrefAsInt(key: .minDDCOverride, for: command))) os_log("- Maximum DDC value: %{public}@ (overrides %{public}@)", type: .info, String(self.readPrefAsInt(key: .maxDDC, for: command)), String(maxDDCValue)) os_log("- Current internal value: %{public}@", type: .info, String(self.readPrefAsFloat(for: command))) os_log("- Command status: %{public}@", type: .info, self.readPrefAsBool(key: .isTouched, for: command) ? "Touched" : "Untouched") if command == .audioSpeakerVolume { self.setupMuteUnMute() } self.restoreDDCSettingsToDisplay(command: command) } else { self.savePref(self.prefExists(for: command) ? self.readPrefAsFloat(for: command) : Float(1), for: command) self.savePref(self.readPrefAsFloat(for: command), key: .SwBrightness) self.brightnessSyncSourceValue = self.readPrefAsFloat(for: command) self.smoothBrightnessTransient = self.readPrefAsFloat(for: command) os_log("- Software controlled display current internal value: %{public}@", type: .info, String(self.readPrefAsFloat(for: command))) } } func setupMuteUnMute() { guard !self.isSw(), !self.readPrefAsBool(key: .unavailableDDC, for: .audioSpeakerVolume), self.readPrefAsBool(key: .enableMuteUnmute) else { return } var currentMuteValue = self.readPrefAsInt(for: .audioMuteScreenBlank) == 0 ? 2 : self.readPrefAsInt(for: .audioMuteScreenBlank) if self.pollingCount != 0, !app.safeMode, prefs.integer(forKey: PrefKey.startupAction.rawValue) == StartupAction.read.rawValue { os_log("- Reading DDC from display %{public}@ times for Mute", type: .info, String(self.pollingCount)) let delay = self.readPrefAsBool(key: .longerDelay) ? UInt64(40 * kMillisecondScale) : nil if let muteValues: (current: UInt16, max: UInt16) = self.readDDCValues(for: .audioMuteScreenBlank, tries: UInt(self.pollingCount), minReplyDelay: delay) { os_log("- Success, current Mute setting: %{public}@", type: .info, String(muteValues.current)) currentMuteValue = Int(muteValues.current) } else { os_log("- Mute read failed", type: .info) } } self.savePref(Int(currentMuteValue), for: .audioMuteScreenBlank) } func setupSliderCurrentValue(command: Command) -> Float { return (command == .audioSpeakerVolume && self.readPrefAsBool(key: .enableMuteUnmute) && self.readPrefAsInt(for: .audioMuteScreenBlank) == 1) ? 0 : self.readPrefAsFloat(for: command) } func stepVolume(isUp: Bool, isSmallIncrement: Bool) { guard !self.readPrefAsBool(key: .unavailableDDC, for: .audioSpeakerVolume) else { OSDUtils.showOsdVolumeDisabled(displayID: self.identifier) return } let currentValue = self.readPrefAsFloat(for: .audioSpeakerVolume) var muteValue: Int? let volumeOSDValue = self.calcNewValue(currentValue: currentValue, isUp: isUp, isSmallIncrement: isSmallIncrement) if self.readPrefAsInt(for: .audioMuteScreenBlank) == 1, volumeOSDValue > 0 { muteValue = 2 } else if self.readPrefAsInt(for: .audioMuteScreenBlank) != 1, volumeOSDValue == 0 { muteValue = 1 } let isAlreadySet = volumeOSDValue == self.readPrefAsFloat(for: .audioSpeakerVolume) if !isAlreadySet { if let muteValue = muteValue, self.readPrefAsBool(key: .enableMuteUnmute) { guard self.writeDDCValues(command: .audioMuteScreenBlank, value: UInt16(muteValue)) == true else { return } self.savePref(muteValue, for: .audioMuteScreenBlank) } if !self.readPrefAsBool(key: .enableMuteUnmute) || volumeOSDValue != 0 { _ = self.writeDDCValues(command: .audioSpeakerVolume, value: self.convValueToDDC(for: .audioSpeakerVolume, from: volumeOSDValue)) } } if !self.readPrefAsBool(key: .hideOsd) { OSDUtils.showOsd(displayID: self.identifier, command: .audioSpeakerVolume, value: volumeOSDValue, roundChiclet: !isSmallIncrement) } if !isAlreadySet { self.savePref(volumeOSDValue, for: .audioSpeakerVolume) if let slider = self.sliderHandler[.audioSpeakerVolume] { slider.setValue(volumeOSDValue, displayID: self.identifier) } } } func stepContrast(isUp: Bool, isSmallIncrement: Bool) { guard !self.readPrefAsBool(key: .unavailableDDC, for: .contrast), !self.isSw() else { return } let currentValue = self.readPrefAsFloat(for: .contrast) let contrastOSDValue = self.calcNewValue(currentValue: currentValue, isUp: isUp, isSmallIncrement: isSmallIncrement) let isAlreadySet = contrastOSDValue == self.readPrefAsFloat(for: .contrast) if !isAlreadySet { _ = self.writeDDCValues(command: .contrast, value: self.convValueToDDC(for: .contrast, from: contrastOSDValue)) } OSDUtils.showOsd(displayID: self.identifier, command: .contrast, value: contrastOSDValue, roundChiclet: !isSmallIncrement) if !isAlreadySet { self.savePref(contrastOSDValue, for: .contrast) if let slider = self.sliderHandler[.contrast] { slider.setValue(contrastOSDValue, displayID: self.identifier) } } } func toggleMute(fromVolumeSlider: Bool = false) { guard !self.readPrefAsBool(key: .unavailableDDC, for: .audioSpeakerVolume) else { OSDUtils.showOsdMuteDisabled(displayID: self.identifier) return } var muteValue: Int var volumeOSDValue: Float if self.readPrefAsInt(for: .audioMuteScreenBlank) != 1 { muteValue = 1 volumeOSDValue = 0 } else { muteValue = 2 volumeOSDValue = self.readPrefAsFloat(for: .audioSpeakerVolume) // The volume that will be set immediately after setting unmute while the old set volume was 0 is unpredictable. Hence, just set it to a single filled chiclet if volumeOSDValue == 0 { volumeOSDValue = 1 / OSDUtils.chicletCount self.savePref(volumeOSDValue, for: .audioSpeakerVolume) } } if self.readPrefAsBool(key: .enableMuteUnmute) { guard self.writeDDCValues(command: .audioMuteScreenBlank, value: UInt16(muteValue)) == true else { return } } self.savePref(muteValue, for: .audioMuteScreenBlank) if !self.readPrefAsBool(key: .enableMuteUnmute) || volumeOSDValue > 0 { _ = self.writeDDCValues(command: .audioSpeakerVolume, value: self.convValueToDDC(for: .audioSpeakerVolume, from: volumeOSDValue)) } if !fromVolumeSlider { if !self.readPrefAsBool(key: .hideOsd) { OSDUtils.showOsd(displayID: self.identifier, command: volumeOSDValue > 0 ? .audioSpeakerVolume : .audioMuteScreenBlank, value: volumeOSDValue, roundChiclet: true) } if let slider = self.sliderHandler[.audioSpeakerVolume] { slider.setValue(volumeOSDValue) } } } func isSwOnly() -> Bool { return (!self.arm64ddc && self.ddc == nil) || self.isVirtual || self.isDummy } func isSw() -> Bool { if prefs.bool(forKey: PrefKey.forceSw.rawValue + self.prefsId) || self.isSwOnly() { return true } else { return false } } let swAfterOsdAnimationSemaphore = DispatchSemaphore(value: 1) var lastAnimationStartedTime: CFTimeInterval = CACurrentMediaTime() func doSwAfterOsdAnimation() { self.lastAnimationStartedTime = CACurrentMediaTime() DispatchQueue.global(qos: .userInteractive).async { self.swAfterOsdAnimationSemaphore.wait() guard CACurrentMediaTime() < self.lastAnimationStartedTime + 0.05 else { self.swAfterOsdAnimationSemaphore.signal() return } for value: Int in stride(from: 1, to: 6, by: 1) { guard self.readPrefAsFloat(for: .brightness) <= self.combinedBrightnessSwitchingValue() else { self.swAfterOsdAnimationSemaphore.signal() return } OSDUtils.showOsd(displayID: self.identifier, command: .brightness, value: Float(value), maxValue: 100, roundChiclet: false) Thread.sleep(forTimeInterval: Double(value * 2) / 300) } for value: Int in stride(from: 5, to: 0, by: -1) { guard self.readPrefAsFloat(for: .brightness) <= self.combinedBrightnessSwitchingValue() else { self.swAfterOsdAnimationSemaphore.signal() return } OSDUtils.showOsd(displayID: self.identifier, command: .brightness, value: Float(value), maxValue: 100, roundChiclet: false) Thread.sleep(forTimeInterval: Double(value * 2) / 300) } OSDUtils.showOsd(displayID: self.identifier, command: .brightness, value: 0, roundChiclet: true) self.swAfterOsdAnimationSemaphore.signal() } } override func stepBrightness(isUp: Bool, isSmallIncrement: Bool) { if self.isSw() { super.stepBrightness(isUp: isUp, isSmallIncrement: isSmallIncrement) return } guard !self.readPrefAsBool(key: .unavailableDDC, for: .brightness) else { return } let currentValue = self.readPrefAsFloat(for: .brightness) var osdValue: Float = 1 if !prefs.bool(forKey: PrefKey.disableCombinedBrightness.rawValue), prefs.bool(forKey: PrefKey.separateCombinedScale.rawValue) { osdValue = self.calcNewValue(currentValue: currentValue, isUp: isUp, isSmallIncrement: isSmallIncrement, half: true) _ = self.setBrightness(osdValue) if osdValue > self.combinedBrightnessSwitchingValue() { OSDUtils.showOsd(displayID: self.identifier, command: .brightness, value: osdValue - self.combinedBrightnessSwitchingValue(), maxValue: self.combinedBrightnessSwitchingValue(), roundChiclet: !isSmallIncrement) } else { self.doSwAfterOsdAnimation() } } else { osdValue = self.calcNewValue(currentValue: currentValue, isUp: isUp, isSmallIncrement: isSmallIncrement) _ = self.setBrightness(osdValue) OSDUtils.showOsd(displayID: self.identifier, command: .brightness, value: osdValue, roundChiclet: !isSmallIncrement) } if let slider = self.sliderHandler[.brightness] { slider.setValue(osdValue, displayID: self.identifier) self.brightnessSyncSourceValue = osdValue } } override func setBrightness(_ to: Float = -1, slow: Bool = false) -> Bool { self.checkGammaInterference() return super.setBrightness(to, slow: slow) } override func setDirectBrightness(_ to: Float, transient: Bool = false) -> Bool { let value = max(min(to, 1), 0) if !self.isSw() { if !prefs.bool(forKey: PrefKey.disableCombinedBrightness.rawValue) { var brightnessValue: Float = 0 var brightnessSwValue: Float = 1 if value >= self.combinedBrightnessSwitchingValue() { brightnessValue = (value - self.combinedBrightnessSwitchingValue()) * (1 / (1 - self.combinedBrightnessSwitchingValue())) brightnessSwValue = 1 } else { brightnessValue = 0 brightnessSwValue = (value / self.combinedBrightnessSwitchingValue()) } _ = self.writeDDCValues(command: .brightness, value: self.convValueToDDC(for: .brightness, from: brightnessValue)) if self.readPrefAsFloat(key: .SwBrightness) != brightnessSwValue { _ = self.setSwBrightness(brightnessSwValue) } } else { _ = self.writeDDCValues(command: .brightness, value: self.convValueToDDC(for: .brightness, from: value)) } if !transient { self.savePref(value, for: .brightness) self.smoothBrightnessTransient = value } } else { _ = super.setDirectBrightness(to, transient: transient) } return true } override func getBrightness() -> Float { return self.prefExists(for: .brightness) ? self.readPrefAsFloat(for: .brightness) : 1 } func getRemapControlCodes(command: Command) -> [UInt8] { let codes = self.readPrefAsString(key: PrefKey.remapDDC, for: command).components(separatedBy: ",") var intCodes: [UInt8] = [] for code in codes { let trimmedCode = code.trimmingCharacters(in: CharacterSet(charactersIn: " ")) if !trimmedCode.isEmpty, let intCode = UInt8(trimmedCode, radix: 16), intCode != 0 { intCodes.append(intCode) } } return intCodes } public func writeDDCValues(command: Command, value: UInt16, errorRecoveryWaitTime _: UInt32? = nil) -> Bool? { guard app.sleepID == 0, app.reconfigureID == 0, !self.readPrefAsBool(key: .forceSw), !self.readPrefAsBool(key: .unavailableDDC, for: command) else { return false } var success: Bool = false var controlCodes = self.getRemapControlCodes(command: command) if controlCodes.count == 0 { controlCodes.append(command.rawValue) } for controlCode in controlCodes { DisplayManager.shared.ddcQueue.sync { if Arm64DDC.isArm64 { if self.arm64ddc { success = Arm64DDC.write(service: self.arm64avService, command: controlCode, value: value) } } else { success = self.ddc?.write(command: command.rawValue, value: value, errorRecoveryWaitTime: 2000) ?? false } self.savePref(true, key: PrefKey.isTouched, for: command) // We deliberatly consider the value tuched no matter if the call succeeded } } return success } func readDDCValues(for command: Command, tries: UInt, minReplyDelay delay: UInt64?) -> (current: UInt16, max: UInt16)? { var values: (UInt16, UInt16)? guard app.sleepID == 0, app.reconfigureID == 0, !self.readPrefAsBool(key: .forceSw), !self.readPrefAsBool(key: .unavailableDDC, for: command) else { return values } let controlCodes = self.getRemapControlCodes(command: command) let controlCode = controlCodes.count == 0 ? command.rawValue : controlCodes[0] if Arm64DDC.isArm64 { guard self.arm64ddc else { return nil } DisplayManager.shared.ddcQueue.sync { if let unwrappedDelay = delay { values = Arm64DDC.read(service: self.arm64avService, command: controlCode, tries: UInt8(min(tries, 255)), minReplyDelay: UInt32(unwrappedDelay / 1000)) } else { values = Arm64DDC.read(service: self.arm64avService, command: controlCode, tries: UInt8(min(tries, 255))) } } } else { DisplayManager.shared.ddcQueue.sync { values = self.ddc?.read(command: controlCode, tries: tries, minReplyDelay: delay) } } return values } func calcNewValue(currentValue: Float, isUp: Bool, isSmallIncrement: Bool, half: Bool = false) -> Float { let nextValue: Float if isSmallIncrement { nextValue = currentValue + (isUp ? 0.01 : -0.01) } else { let osdChicletFromValue = OSDUtils.chiclet(fromValue: currentValue, maxValue: 1, half: half) let distance = OSDUtils.getDistance(fromNearestChiclet: osdChicletFromValue) var nextFilledChiclet = isUp ? ceil(osdChicletFromValue) : floor(osdChicletFromValue) let distanceThreshold: Float = 0.25 // 25% of the distance between the edges of an osd box if distance == 0 { nextFilledChiclet += (isUp ? 1 : -1) } else if !isUp, distance < distanceThreshold { nextFilledChiclet -= 1 } else if isUp, distance > (1 - distanceThreshold) { nextFilledChiclet += 1 } nextValue = OSDUtils.value(fromChiclet: nextFilledChiclet, maxValue: 1, half: half) } return max(0, min(1, nextValue)) } func getCurveMultiplier(_ curveDDC: Int) -> Float { switch curveDDC { case 1: return 0.6 case 2: return 0.7 case 3: return 0.8 case 4: return 0.9 case 6: return 1.3 case 7: return 1.5 case 8: return 1.7 case 9: return 1.88 default: return 1.0 } } func convValueToDDC(for command: Command, from: Float) -> UInt16 { var value = from if self.readPrefAsBool(key: .invertDDC, for: command) { value = 1 - value } let curveMultiplier = self.getCurveMultiplier(self.readPrefAsInt(key: .curveDDC, for: command)) let minDDCValue = Float(self.readPrefAsInt(key: .minDDCOverride, for: command)) let maxDDCValue = Float(self.readPrefAsInt(key: .maxDDC, for: command)) let curvedValue = pow(max(min(value, 1), 0), curveMultiplier) let deNormalizedValue = (maxDDCValue - minDDCValue) * curvedValue + minDDCValue var intDDCValue = UInt16(min(max(deNormalizedValue, minDDCValue), maxDDCValue)) if from > 0, command == Command.audioSpeakerVolume { intDDCValue = max(1, intDDCValue) // Never let sound to mute accidentally, keep it digitally to at digital 1 if needed as muting breaks some displays } return intDDCValue } func convDDCToValue(for command: Command, from: UInt16) -> Float { let curveMultiplier = self.getCurveMultiplier(self.readPrefAsInt(key: .curveDDC, for: command)) let minDDCValue = Float(self.readPrefAsInt(key: .minDDCOverride, for: command)) let maxDDCValue = Float(self.readPrefAsInt(key: .maxDDC, for: command)) let normalizedValue = ((min(max(Float(from), minDDCValue), maxDDCValue) - minDDCValue) / (maxDDCValue - minDDCValue)) let deCurvedValue = pow(normalizedValue, 1.0 / curveMultiplier) var value = deCurvedValue if self.readPrefAsBool(key: .invertDDC, for: command) { value = 1 - value } return max(min(value, 1), 0) } func combinedBrightnessSwitchingValue() -> Float { return Float(self.readPrefAsInt(key: .combinedBrightnessSwitchingPoint) + 8) / 16 } }
49.292
321
0.693662
7510715c74b4c41de7f49ae9268d3a6faca231cd
3,292
// // SBUAvailable.swift // SendBirdUIKit // // Created by Tez Park on 2020/07/24. // Copyright © 2020 Sendbird, Inc. All rights reserved. // import UIKit import SendBirdSDK @objcMembers public class SBUAvailable: NSObject { // MARK: - Private static let REACTIONS = "reactions" static let ENABLE_OG_TAG = "enable_og_tag" static let USE_LAST_MESSEGE_ON_SUPER_GROUP = "use_last_messege_on_super_group" static let USE_LAST_SEEN_AT = "use_last_seen_at" static let ENABLE_MESSAGE_THREADING = "enable_message_threading" static let ALLOW_GROUP_CHANNEL_CREATE_FROM_SDK = "allow_group_channel_create_from_sdk" static let ALLOW_GROUP_CHANNEL_INVITE_FROM_SDK = "allow_group_channel_invite_from_sdk" static let ALLOW_OPERATORS_TO_EDIT_OPERATORS = "allow_operators_to_edit_operators" static let ALLOW_OPERATORS_TO_BAN_OPERATORS = "allow_operators_to_ban_operators" static let ALLOW_SUPER_GROUP_CHANNEL = "allow_super_group_channel" static let ALLOW_GROUP_CHANNEL_LEAVE_FROM_SDK = "allow_group_channel_leave_from_sdk" static let ALLOW_GROUP_CHANNEL_UPDATE_FROM_SDK = "allow_group_channel_update_from_sdk" static let ALLOW_ONLY_OPERATOR_SDK_TO_UPDATE_GROUP_CHANNEL = "allow_only_operator_sdk_to_update_group_channel" static let ALLOW_BROADCAST_CHANNEL = "allow_broadcast_channel" static let MESSAGE_SEARCH = "message_search_v3" private static func isAvailable(key: String) -> Bool { guard let appInfo = SBDMain.getAppInfo(), let applicationAttributes = appInfo.applicationAttributes, let premiumFeatureList = appInfo.premiumFeatureList else { return false } return applicationAttributes.contains(key) || premiumFeatureList.contains(key) } // MARK: - Public /// This method checks if the application support super group channel. /// - Returns: `true` if super group channel can be usable, `false` otherwise. /// - Since: 1.2.0 public static func isSupportSuperGroupChannel() -> Bool { return self.isAvailable(key: ALLOW_SUPER_GROUP_CHANNEL) } /// This method checks if the application support broadcast channel. /// - Returns: `true` if broadcast channel can be usable, `false` otherwise. /// - Since: 1.2.0 public static func isSupportBroadcastChannel() -> Bool { return self.isAvailable(key: ALLOW_BROADCAST_CHANNEL) } /// This method checks if the application support reactions. /// - Returns: `true` if the reaction operation can be usable, `false` otherwise. /// - Since: 1.2.0 public static func isSupportReactions() -> Bool { return self.isAvailable(key: REACTIONS) } /// This method checks if the application support og metadata. /// - Returns: `true` if the og metadata can be usable, `false` otherwise. /// - Since: 1.2.0 public static func isSupportOgTag() -> Bool { return self.isAvailable(key: ENABLE_OG_TAG) } /// This method checks if the application support message search. /// - Returns: `true` if the message search can be used, `false` otherwise. /// - Since: 2.1.0 public static func isSupportMessageSearch() -> Bool { return self.isAvailable(key: MESSAGE_SEARCH) } }
42.205128
114
0.719927
e86e4b2631536fc44abcb32cb48b03a4aa9972e8
1,128
/* * This class allows you to intercept and mutate incoming remote notifications. * didReceive() has ~30 seconds to modify the payload and call the contentHandler, * otherwise the system will display the notification’s original content. * * The notification payload must contain: * "mutable-content" : 1 * "alert" : { ... } * to trigger this handler. */ import UserNotifications class NotificationService: UNNotificationServiceExtension { override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { if let bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent { // Modify notification content here... if (!request.content.categoryIdentifier.isEmpty && (request.content.userInfo["experienceId"]) != nil) { bestAttemptContent.categoryIdentifier = EXScopedNotificationsUtils.scopedCategoryIdentifier(withId: request.content.categoryIdentifier, forExperience: request.content.userInfo["experienceId"] as! String) } contentHandler(bestAttemptContent) } } }
41.777778
211
0.754433
89ae7cb3f9da1190a5396d5cc38df9cf1579707f
655
class Solution { func numWays(_ n: Int, _ k: Int) -> Int { var memo: [Int: Int] = [:] func numWays(lastIndex: Int) -> Int { switch lastIndex { case 0: return k case 1: return k * k default: if let cachedValue = memo[lastIndex] { return cachedValue } let answer = (k - 1) * (numWays(lastIndex: lastIndex-1) + numWays(lastIndex: lastIndex-2)) memo[lastIndex] = answer return answer } } return numWays(lastIndex: n - 1) } }
27.291667
106
0.438168
1a1ecf7f9a6090a2fc9bf2178443028ad1078105
994
// // MenuSelectionViewController.swift // UIKitExample // // Created by Tyler Thompson on 9/24/19. // Copyright © 2021 WWT and Tyler Thompson. All rights reserved. // import Foundation import SwiftCurrent_UIKit class MenuSelectionViewController: UIWorkflowItem<Order, Order>, StoryboardLoadable { var order: Order required init?(coder: NSCoder, with order: Order) { self.order = order super.init(coder: coder) } required init?(coder: NSCoder) { fatalError() } @IBAction private func cateringMenu() { order.menuType = .catering proceedInWorkflow(order) } @IBAction private func regularMenu() { order.menuType = .regular proceedInWorkflow(order) } func shouldLoad() -> Bool { if order.location?.menuTypes.count == 1 { order.menuType = order.location?.menuTypes.first proceedInWorkflow(order) } return (order.location?.menuTypes.count ?? 0) > 1 } }
24.85
85
0.648893
031dbe0ea4e922c995188aba315fa2e2d8f1228c
197
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<d where B:d{var d{f
39.4
87
0.766497
b9b410776c95deb1fa2db3efb70eb05df25208a0
1,135
import UIKit func numberOfVowels(in sentence: String, isYAVowel: Bool = false) -> Int { var vowelCount = 0 //this is where my count is stored. if isYAVowel == false { //if isYAVowel is false, then it should run the code under here. switch sentence { case "a", "e", "i", "o", "u": // If there's any vowels, it should count them... vowelCount += 1 print(vowelCount) return vowelCount default: //if there aren't any vowels, it should return having not counted anything. return vowelCount } } else { if isYAVowel == true { //if isYAVowel isn't false, it should come here and run this code if it's true. switch sentence { case "a", "e", "i", "o", "u", "y": //if there are vowels, y included, it should count them. vowelCount += 1 print(vowelCount) return vowelCount default: //if there are no vowels, including y, it should not count them and move on. return vowelCount } } } } numberOfVowels(in: "I'm not good at coding!")
35.46875
110
0.573568
38b914736c103acaee2aad10d487ec829761807a
15,952
// // JoinChannelVC.swift // APIExample // // Created by 张乾泽 on 2020/4/17. // Copyright © 2020 Agora Corp. All rights reserved. // import Cocoa import AgoraRtcKit import AGEVideoLayout class JoinMultipleChannel: BaseViewController { var videos: [VideoView] = [] var videos2: [VideoView] = [] @IBOutlet weak var container: AGEVideoContainer! @IBOutlet weak var container2: AGEVideoContainer! var channel1: AgoraRtcChannel? var channel2: AgoraRtcChannel? var agoraKit: AgoraRtcEngineKit! // indicate if current instance has joined channel1 var isJoined: Bool = false { didSet { channelField1.isEnabled = !isJoined initJoinChannel1Button() } } /** --- Channel1 TextField --- */ @IBOutlet weak var channelField1: Input! func initChannelField1() { channelField1.label.stringValue = "Channel".localized + "1" channelField1.field.placeholderString = "Channel Name".localized + "1" } /** --- Join Channel1 Button --- */ @IBOutlet weak var joinChannel1Button: NSButton! func initJoinChannel1Button() { joinChannel1Button.title = isJoined ? "Leave Channel".localized : "Join Channel".localized } @IBAction func onJoinChannel1ButtonPressed(_ sender: NSButton) { if !isJoined { // auto subscribe options after join channel let mediaOptions = AgoraRtcChannelMediaOptions() mediaOptions.autoSubscribeAudio = true mediaOptions.autoSubscribeVideo = true var channel: AgoraRtcChannel? if channel1 == nil { channel1 = agoraKit.createRtcChannel(channelField1.stringValue) } channel = channel1 channel?.setRtcChannelDelegate(self) // start joining channel // 1. Users can only see each other after they join the // same channel successfully using the same app id. // 2. If app certificate is turned on at dashboard, token is needed // when joining channel. The channel name and uid used to calculate // the token has to match the ones used for channel join let result = channel?.join(byToken: nil, info: nil, uid: 0, options: mediaOptions) ?? -1 if result != 0 { // Usually happens with invalid parameters // Error code description can be found at: // en: https://docs.agora.io/en/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html // cn: https://docs.agora.io/cn/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html self.showAlert(title: "Error", message: "joinChannel1 call failed: \(result), please check your params") } } else { channel1?.leave() if let channelName = channel1?.getId() { if isPublished && channelName == selectedChannel { if let channel = getChannelByName(selectedChannel) { channel.setClientRole(.audience) channel.unpublish() isPublished = false } } selectChannelsPicker.picker.removeItem(withTitle: channelName) } channel1?.destroy() channel1 = nil isJoined = false } } // indicate if current instance has joined channel2 var isJoined2: Bool = false { didSet { channelField2.isEnabled = !isJoined2 initJoinChannel2Button() } } /** --- Channel1 TextField --- */ @IBOutlet weak var channelField2: Input! func initChannelField2() { channelField2.label.stringValue = "Channel".localized + "2" channelField2.field.placeholderString = "Channel Name".localized + "2" } /** --- Join Channel1 Button --- */ @IBOutlet weak var joinChannel2Button: NSButton! func initJoinChannel2Button() { joinChannel2Button.title = isJoined2 ? "Leave Channel".localized : "Join Channel".localized } @IBAction func onJoinChannel2ButtonPressed(_ sender:NSButton) { if !isJoined2 { // auto subscribe options after join channel let mediaOptions = AgoraRtcChannelMediaOptions() mediaOptions.autoSubscribeAudio = true mediaOptions.autoSubscribeVideo = true var channel: AgoraRtcChannel? if channel2 == nil { channel2 = agoraKit.createRtcChannel(channelField2.stringValue) } channel = channel2 channel?.setRtcChannelDelegate(self) // start joining channel // 1. Users can only see each other after they join the // same channel successfully using the same app id. // 2. If app certificate is turned on at dashboard, token is needed // when joining channel. The channel name and uid used to calculate // the token has to match the ones used for channel join let result = channel?.join(byToken: nil, info: nil, uid: 0, options: mediaOptions) ?? -1 if result != 0 { // Usually happens with invalid parameters // Error code description can be found at: // en: https://docs.agora.io/en/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html // cn: https://docs.agora.io/cn/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html self.showAlert(title: "Error", message: "joinChannel1 call failed: \(result), please check your params") } } else { channel2?.leave() if let channelName = channel2?.getId() { if isPublished && channelName == selectedChannel { if let channel = getChannelByName(selectedChannel) { channel.setClientRole(.audience) channel.unpublish() isPublished = false } } selectChannelsPicker.picker.removeItem(withTitle: channelName) } channel2?.destroy() channel2 = nil isJoined2 = false } } var isPublished: Bool = false { didSet { selectChannelsPicker.isEnabled = !isPublished initPublishButton() } } /** --- Channels Picker --- */ @IBOutlet weak var selectChannelsPicker: Picker! var selectedChannel: String? { return selectChannelsPicker.picker.selectedItem?.title } func initSelectChannelsPicker() { selectChannelsPicker.label.stringValue = "Channel".localized } /** --- Publish Button --- */ @IBOutlet weak var publishButton: NSButton! func initPublishButton() { publishButton.title = isPublished ? "Unpublish".localized : "Publish".localized } @IBAction func onPublishPressed(_ sender: Any) { if !isPublished { if let channel = getChannelByName(selectedChannel) { channel.setClientRole(.broadcaster) channel.publish() isPublished = true } } else { if let channel = getChannelByName(selectedChannel) { channel.setClientRole(.audience) channel.unpublish() isPublished = false } } } override func viewDidLoad() { super.viewDidLoad() layoutVideos() // set up agora instance when view loaded let config = AgoraRtcEngineConfig() config.appId = KeyCenter.AppId config.areaCode = GlobalSettings.shared.area.rawValue agoraKit = AgoraRtcEngineKit.sharedEngine(with: config, delegate: self) // this is mandatory to get camera list agoraKit.enableVideo() // set proxy configuration let proxySetting = GlobalSettings.shared.proxySetting.selectedOption().value agoraKit.setCloudProxy(AgoraCloudProxyType.init(rawValue: UInt(proxySetting)) ?? .noneProxy) initChannelField1() initJoinChannel1Button() initChannelField2() initJoinChannel2Button() initSelectChannelsPicker() initPublishButton() // set live broadcaster mode agoraKit.setChannelProfile(.liveBroadcasting) let resolution = Configs.Resolutions[GlobalSettings.shared.resolutionSetting.selectedOption().value] let fps = Configs.Fps[GlobalSettings.shared.fpsSetting.selectedOption().value] // enable video module and set up video encoding configs agoraKit.setVideoEncoderConfiguration( AgoraVideoEncoderConfiguration( size: resolution.size(), frameRate: AgoraVideoFrameRate(rawValue: fps) ?? .fps15, bitrate: AgoraVideoBitrateStandard, orientationMode: .adaptative ) ) // set up local video to render your local camera preview let localVideo = videos[0] let videoCanvas = AgoraRtcVideoCanvas() videoCanvas.uid = 0 // the view to be binded videoCanvas.view = localVideo.videocanvas videoCanvas.renderMode = .hidden agoraKit.setupLocalVideo(videoCanvas) agoraKit.startPreview() } override func viewWillBeRemovedFromSplitView() { channel1?.leave() channel1?.destroy() channel2?.leave() channel2?.destroy() AgoraRtcEngineKit.destroy() } func getChannelByName(_ channelName: String?) -> AgoraRtcChannel? { if channel1?.getId() == channelName { return channel1 } else if channel2?.getId() == channelName { return channel2 } return nil } func layoutVideos() { videos = [VideoView.createFromNib()!] videos[0].placeholder.stringValue = "Local" // layout render view container.layoutStream(views: videos) videos2 = [VideoView.createFromNib()!, VideoView.createFromNib()!] videos2[0].placeholder.stringValue = "Channel1\nRemote" videos2[1].placeholder.stringValue = "Channel2\nRemote" container2.layoutStream2(views: videos2) } } /// agora rtc engine delegate events extension JoinMultipleChannel: AgoraRtcEngineDelegate { /// callback when warning occured for agora sdk, warning can usually be ignored, still it's nice to check out /// what is happening /// Warning code description can be found at: /// en: https://docs.agora.io/en/Voice/API%20Reference/oc/Constants/AgoraWarningCode.html /// cn: https://docs.agora.io/cn/Voice/API%20Reference/oc/Constants/AgoraWarningCode.html /// @param warningCode warning code of the problem func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurWarning warningCode: AgoraWarningCode) { LogUtils.log(message: "warning: \(warningCode.rawValue)", level: .warning) } /// callback when error occured for agora sdk, you are recommended to display the error descriptions on demand /// to let user know something wrong is happening /// Error code description can be found at: /// en: https://docs.agora.io/en/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html /// cn: https://docs.agora.io/cn/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html /// @param errorCode error code of the problem func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurError errorCode: AgoraErrorCode) { LogUtils.log(message: "error: \(errorCode)", level: .error) self.showAlert(title: "Error", message: "Error \(errorCode.rawValue) occur") } } extension JoinMultipleChannel: AgoraRtcChannelDelegate { func rtcChannelDidJoin(_ rtcChannel: AgoraRtcChannel, withUid uid: UInt, elapsed: Int) { LogUtils.log(message: "Join \(rtcChannel.getId() ?? "") with uid \(uid) elapsed \(elapsed)ms", level: .info) selectChannelsPicker.picker.addItem(withTitle: rtcChannel.getId()!) if (channel1 == rtcChannel) { isJoined = true } else { isJoined2 = true } } /// callback when warning occured for a channel, warning can usually be ignored, still it's nice to check out /// what is happening /// Warning code description can be found at: /// en: https://docs.agora.io/en/Voice/API%20Reference/oc/Constants/AgoraWarningCode.html /// cn: https://docs.agora.io/cn/Voice/API%20Reference/oc/Constants/AgoraWarningCode.html /// @param warningCode warning code of the problem func rtcChannel(_ rtcChannel: AgoraRtcChannel, didOccurWarning warningCode: AgoraWarningCode) { LogUtils.log(message: "channel: \(rtcChannel.getId() ?? ""), warning: \(warningCode.rawValue)", level: .warning) } /// callback when error occured for a channel, you are recommended to display the error descriptions on demand /// to let user know something wrong is happening /// Error code description can be found at: /// en: https://docs.agora.io/en/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html /// cn: https://docs.agora.io/cn/Voice/API%20Reference/oc/Constants/AgoraErrorCode.html /// @param errorCode error code of the problem func rtcChannel(_ rtcChannel: AgoraRtcChannel, didOccurError errorCode: AgoraErrorCode) { LogUtils.log(message: "error: \(errorCode)", level: .error) self.showAlert(title: "Error", message: "Error \(errorCode.rawValue) occur") } /// callback when a remote user is joinning the channel, note audience in live broadcast mode will NOT trigger this event /// @param uid uid of remote joined user /// @param elapsed time elapse since current sdk instance join the channel in ms func rtcChannel(_ rtcChannel: AgoraRtcChannel, didJoinedOfUid uid: UInt, elapsed: Int) { LogUtils.log(message: "remote user join: \(uid) \(elapsed)ms", level: .info) // Only one remote video view is available for this // tutorial. Here we check if there exists a surface // view tagged as this uid. let videoCanvas = AgoraRtcVideoCanvas() videoCanvas.uid = uid // the view to be binded videoCanvas.view = channel1 == rtcChannel ? videos2[0].videocanvas : videos2[1].videocanvas videoCanvas.renderMode = .hidden // set channelId so that it knows which channel the video belongs to videoCanvas.channelId = rtcChannel.getId() agoraKit.setupRemoteVideo(videoCanvas) } /// callback when a remote user is leaving the channel, note audience in live broadcast mode will NOT trigger this event /// @param uid uid of remote joined user /// @param reason reason why this user left, note this event may be triggered when the remote user /// become an audience in live broadcasting profile func rtcChannel(_ rtcChannel: AgoraRtcChannel, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) { LogUtils.log(message: "remote user left: \(uid) reason \(reason)", level: .info) // to unlink your view from sdk, so that your view reference will be released // note the video will stay at its last frame, to completely remove it // you will need to remove the EAGL sublayer from your binded view let videoCanvas = AgoraRtcVideoCanvas() videoCanvas.uid = uid // the view to be binded videoCanvas.view = nil videoCanvas.renderMode = .hidden // set channelId so that it knows which channel the video belongs to videoCanvas.channelId = rtcChannel.getId() agoraKit.setupRemoteVideo(videoCanvas) } }
42.88172
125
0.631269
22fef8da551fd53bac1c12ab39fbcacbac293c5e
161
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(BlueMustangTests.allTests), ] } #endif
16.1
45
0.677019
48e6b17f445aab6e7701a9b6ab0881778ae52496
11,111
import XCTest import Mapbox #if os(iOS) import UIKit #else import Cocoa #endif /** Test cases that ensure the inline examples in the project documentation compile. To add an example: 1. Add a test case named in the form testMGLClass or testMGLClass$method. 2. Wrap the code you'd like to appear in the documentation within the following comment blocks: ``` //#-example-code ... //#-end-example-code ``` 3. Insert an empty Swift code block inside the header file where you'd like the example code to be inserted. 4. Run `make darwin-update-examples` to extract example code from the test method below and insert it into the header. */ class MGLDocumentationExampleTests: XCTestCase, MGLMapViewDelegate { var mapView: MGLMapView! var styleLoadingExpectation: XCTestExpectation! override func setUp() { super.setUp() let styleURL = Bundle(for: MGLDocumentationExampleTests.self).url(forResource: "one-liner", withExtension: "json") mapView = MGLMapView(frame: CGRect(x: 0, y: 0, width: 256, height: 256), styleURL: styleURL) mapView.delegate = self styleLoadingExpectation = expectation(description: "Map view should finish loading style") waitForExpectations(timeout: 1, handler: nil) } override func tearDown() { mapView = nil styleLoadingExpectation = nil super.tearDown() } func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) { styleLoadingExpectation.fulfill() } func testMGLShape$shapeWithData_encoding_error_() { let mainBundle = Bundle(for: MGLDocumentationExampleTests.self) //#-example-code let url = mainBundle.url(forResource: "amsterdam", withExtension: "geojson")! let data = try! Data(contentsOf: url) let feature = try! MGLShape(data: data, encoding: String.Encoding.utf8.rawValue) as! MGLShapeCollectionFeature //#-end-example-code XCTAssertNotNil(feature.shapes.first as? MGLPolygonFeature) } func testMGLShapeSource() { //#-example-code var coordinates: [CLLocationCoordinate2D] = [ CLLocationCoordinate2D(latitude: 37.77, longitude: -122.42), CLLocationCoordinate2D(latitude: 38.91, longitude: -77.04), ] let polyline = MGLPolylineFeature(coordinates: &coordinates, count: UInt(coordinates.count)) let source = MGLShapeSource(identifier: "lines", features: [polyline], options: nil) mapView.style?.addSource(source) //#-end-example-code XCTAssertNotNil(mapView.style?.source(withIdentifier: "lines")) } func testMGLRasterSource() { //#-example-code let source = MGLRasterSource(identifier: "clouds", tileURLTemplates: ["https://example.com/raster-tiles/{z}/{x}/{y}.png"], options: [ .minimumZoomLevel: 9, .maximumZoomLevel: 16, .tileSize: 512, .attributionInfos: [ MGLAttributionInfo(title: NSAttributedString(string: "© Mapbox"), url: URL(string: "http://mapbox.com")) ] ]) mapView.style?.addSource(source) //#-end-example-code XCTAssertNotNil(mapView.style?.source(withIdentifier: "clouds")) } func testMGLVectorSource() { //#-example-code let source = MGLVectorSource(identifier: "pois", tileURLTemplates: ["https://example.com/vector-tiles/{z}/{x}/{y}.mvt"], options: [ .minimumZoomLevel: 9, .maximumZoomLevel: 16, .attributionInfos: [ MGLAttributionInfo(title: NSAttributedString(string: "© Mapbox"), url: URL(string: "http://mapbox.com")) ] ]) mapView.style?.addSource(source) //#-end-example-code XCTAssertNotNil(mapView.style?.source(withIdentifier: "pois")) } func testMGLCircleStyleLayer() { let population = MGLVectorSource(identifier: "population", configurationURL: URL(string: "https://example.com/style.json")!) mapView.style?.addSource(population) //#-example-code let layer = MGLCircleStyleLayer(identifier: "circles", source: population) layer.sourceLayerIdentifier = "population" layer.circleColor = MGLStyleValue(rawValue: .green) layer.circleRadius = MGLStyleValue(interpolationMode: .exponential, cameraStops: [12: MGLStyleValue(rawValue: 2), 22: MGLStyleValue(rawValue: 180)], options: [.interpolationBase: 1.75]) layer.circleOpacity = MGLStyleValue(rawValue: 0.7) layer.predicate = NSPredicate(format: "%K == %@", "marital-status", "married") mapView.style?.addLayer(layer) //#-end-example-code XCTAssertNotNil(mapView.style?.layer(withIdentifier: "circles")) } func testMGLLineStyleLayer() { let trails = MGLVectorSource(identifier: "trails", configurationURL: URL(string: "https://example.com/style.json")!) mapView.style?.addSource(trails) //#-example-code let layer = MGLLineStyleLayer(identifier: "trails-path", source: trails) layer.sourceLayerIdentifier = "trails" layer.lineWidth = MGLStyleValue(interpolationMode: .exponential, cameraStops: [14: MGLStyleValue(rawValue: 2), 18: MGLStyleValue(rawValue: 20)], options: [.interpolationBase: 1.5]) layer.lineColor = MGLStyleValue(rawValue: .brown) layer.lineCap = MGLStyleValue(rawValue: NSValue(mglLineCap: .round)) layer.predicate = NSPredicate(format: "%K == %@", "trail-type", "mountain-biking") mapView.style?.addLayer(layer) //#-end-example-code XCTAssertNotNil(mapView.style?.layer(withIdentifier: "trails-path")) } func testMGLFillStyleLayer() { let parks = MGLVectorSource(identifier: "parks", configurationURL: URL(string: "https://example.com/style.json")!) mapView.style?.addSource(parks) //#-example-code let layer = MGLFillStyleLayer(identifier: "parks", source: parks) layer.sourceLayerIdentifier = "parks" layer.fillColor = MGLStyleValue(rawValue: .green) layer.predicate = NSPredicate(format: "type == %@", "national-park") mapView.style?.addLayer(layer) //#-end-example-code XCTAssertNotNil(mapView.style?.layer(withIdentifier: "parks")) } func testMGLFillExtrusionStyleLayer() { let buildings = MGLVectorSource(identifier: "buildings", configurationURL: URL(string: "https://example.com/style.json")!) mapView.style?.addSource(buildings) //#-example-code let layer = MGLFillExtrusionStyleLayer(identifier: "buildings", source: buildings) layer.sourceLayerIdentifier = "building" layer.fillExtrusionHeight = MGLStyleValue(interpolationMode: .identity, sourceStops: nil, attributeName: "height", options: nil) layer.fillExtrusionBase = MGLStyleValue(interpolationMode: .identity, sourceStops: nil, attributeName: "min_height", options: nil) layer.predicate = NSPredicate(format: "extrude == 'true'") mapView.style?.addLayer(layer) //#-end-example-code XCTAssertNotNil(mapView.style?.layer(withIdentifier: "buildings")) } func testMGLSymbolStyleLayer() { let pois = MGLVectorSource(identifier: "pois", configurationURL: URL(string: "https://example.com/style.json")!) mapView.style?.addSource(pois) //#-example-code let layer = MGLSymbolStyleLayer(identifier: "coffeeshops", source: pois) layer.sourceLayerIdentifier = "pois" layer.iconImageName = MGLStyleValue(rawValue: "coffee") layer.iconScale = MGLStyleValue(rawValue: 0.5) layer.text = MGLStyleValue(rawValue: "{name}") #if os(macOS) var vector = CGVector(dx: 10, dy: 0) layer.textTranslation = MGLStyleValue(rawValue: NSValue(bytes: &vector, objCType: "{CGVector=dd}")) #else layer.textTranslation = MGLStyleValue(rawValue: NSValue(cgVector: CGVector(dx: 10, dy: 0))) #endif layer.textJustification = MGLStyleValue(rawValue: NSValue(mglTextJustification: .left)) layer.textAnchor = MGLStyleValue(rawValue: NSValue(mglTextAnchor: .left)) layer.predicate = NSPredicate(format: "%K == %@", "venue-type", "coffee") mapView.style?.addLayer(layer) //#-end-example-code XCTAssertNotNil(mapView.style?.layer(withIdentifier: "coffeeshops")) } func testMGLRasterStyleLayer() { let source = MGLRasterSource(identifier: "clouds", tileURLTemplates: ["https://example.com/raster-tiles/{z}/{x}/{y}.png"], options: [ .minimumZoomLevel: 9, .maximumZoomLevel: 16, .tileSize: 512, .attributionInfos: [ MGLAttributionInfo(title: NSAttributedString(string: "© Mapbox"), url: URL(string: "http://mapbox.com")) ] ]) mapView.style?.addSource(source) //#-example-code let layer = MGLRasterStyleLayer(identifier: "clouds", source: source) layer.rasterOpacity = MGLStyleValue(rawValue: 0.5) mapView.style?.addLayer(layer) //#-end-example-code XCTAssertNotNil(mapView.style?.layer(withIdentifier: "clouds")) } func testMGLVectorStyleLayer$predicate() { let terrain = MGLVectorSource(identifier: "terrain", configurationURL: URL(string: "https://example.com/style.json")!) mapView.style?.addSource(terrain) //#-example-code let layer = MGLLineStyleLayer(identifier: "contour", source: terrain) layer.sourceLayerIdentifier = "contours" layer.predicate = NSPredicate(format: "(index == 5 || index == 10) && ele >= 1500.0") mapView.style?.addLayer(layer) //#-end-example-code XCTAssertNotNil(mapView.style?.layer(withIdentifier: "contour")) } func testMGLMapView() { //#-example-code #if os(macOS) class MapClickGestureRecognizer: NSClickGestureRecognizer { override func shouldRequireFailure(of otherGestureRecognizer: NSGestureRecognizer) -> Bool { return otherGestureRecognizer is NSClickGestureRecognizer } } #else let mapTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(myCustomFunction)) for recognizer in mapView.gestureRecognizers! where recognizer is UITapGestureRecognizer { mapTapGestureRecognizer.require(toFail: recognizer) } mapView.addGestureRecognizer(mapTapGestureRecognizer) #endif //#-end-example-code } // For testMGLMapView(). func myCustomFunction() {} }
43.065891
141
0.637566
906c1626fcb4dcbfb86f0179b788a5236e30c277
547
// // YXFilletView.swift // youxuan // // Created by 肖锋 on 2019/11/11. // Copyright © 2019 肖锋. All rights reserved. // import UIKit class YXFilletView: UIView { init(frame: CGRect, corner: UIRectCorner, size: CGSize) { super.init(frame: frame) backgroundColor = UIColor.white self.layer.mask = YXBaseTools.YX_configRectCorner(view: self, corner: corner, cornerRadii: size) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
21.038462
104
0.625229
dd062333a24f9e749fb6e86ff98bf6281d225f7e
1,303
// // QuickScannerViewController+Delegate.swift // KAI Membership // // Created by Anh Kiệt on 08/04/2021. // import AVFoundation // MARK: AVCaptureMetadataOutputObjectsDelegate extension QuickScannerViewController: AVCaptureMetadataOutputObjectsDelegate { func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { if metadataObjects.count == 0 { qrCodeFrameView?.frame = CGRect.zero messageLabel.text = "No QR code is detected" detectQRString = nil return } let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject if supportedCodeTypes.contains(metadataObj.type) { let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj) qrCodeFrameView?.frame = barCodeObject!.bounds if let stringValue = metadataObj.stringValue { Helper.launchApp(from: self, decodedURL: stringValue) messageLabel.text = stringValue detectQRString = stringValue completion?(stringValue) dismiss(animated: true, completion: nil) } } } }
34.289474
145
0.652341
e664c09a58e99223eaa24a7a8b1968ed5879c383
2,194
// // AppDelegate.swift // IOSDrawShapesTutorial // // Created by Arthur Knopper on 09/01/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.680851
285
0.757065
186943ca94ac38f5813e3de255d7e9304830ef13
2,619
// // UpbitTradeTicks.swift // UpbitSwift // // Created by ocean on 2021/03/13. // import Foundation // MARK: - UpbitTradeTick public struct UpbitTradeTick: Codable { public let market, tradeDateUTC, tradeTimeUTC: String public let timestamp: Int public let tradePrice, tradeVolume: Double public let prevClosingPrice, changePrice: Double public let askBid: String public let sequentialId: Int? enum CodingKeys: String, CodingKey { case market case tradeDateUTC = "trade_date_utc" case tradeTimeUTC = "trade_time_utc" case timestamp case tradePrice = "trade_price" case tradeVolume = "trade_volume" case prevClosingPrice = "prev_closing_price" case changePrice = "change_price" case askBid = "ask_bid" case sequentialId = "sequential_id" } } extension UpbitTradeTick { public init(data: Data) throws { self = try JSONDecoder().decode(UpbitTradeTick.self, from: data) } public init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) market = try values.decode(String.self, forKey: .market) tradeDateUTC = try values.decode(String.self, forKey: .tradeDateUTC) tradeTimeUTC = try values.decode(String.self, forKey: .tradeTimeUTC) timestamp = try values.decode(Int.self, forKey: .timestamp) tradePrice = try values.decode(Double.self, forKey: .tradePrice) tradeVolume = try values.decode(Double.self, forKey: .tradeVolume) prevClosingPrice = try values.decode(Double.self, forKey: .prevClosingPrice) changePrice = try values.decode(Double.self, forKey: .changePrice) askBid = try values.decode(String.self, forKey: .askBid) sequentialId = try values.decodeIfPresent(Int.self, forKey: .sequentialId) } } public typealias UpbitTradeTicks = [UpbitTradeTick] extension UpbitTradeTicks { public init(data: Data) throws { self = try JSONDecoder().decode(UpbitTradeTicks.self, from: data) } public init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } }
34.92
84
0.668576
1ea768ac271c01e62ba9c48ec311e3f1c06b1233
5,916
// // SHCurrentTransformerShowDataViewController.swift // Smart-Bus // // Created by Mark Liu on 2018/11/14. // Copyright © 2018 SmartHome. All rights reserved. // import UIKit /// CT24 通道总数 private let currentTransformerCount: Int = 24 /// 重用标示 private let currentTransformerChannelDataCellReuseIdentifier = "SHCurrentTransformerChannelDataViewCell" class SHCurrentTransformerShowDataViewController: SHViewController { /// CT24 var currentTransformer: SHCurrentTransformer? /// 电流值大小 private lazy var allChannels: [SHCurrentTransformerChannel] = { var array = [SHCurrentTransformerChannel]() for i in 0 ..< currentTransformerCount { let channel = SHCurrentTransformerChannel() channel.name = channelArray[i] channel.current = 0 channel.power = 0.0 array.append(channel) } return array }() /// 通道数组(横坐标) private lazy var channelArray: [String] = [ currentTransformer?.channel1 ?? "CH1", currentTransformer?.channel2 ?? "CH2", currentTransformer?.channel3 ?? "CH3", currentTransformer?.channel4 ?? "CH4", currentTransformer?.channel5 ?? "CH5", currentTransformer?.channel6 ?? "CH6", currentTransformer?.channel7 ?? "CH7", currentTransformer?.channel8 ?? "CH8", currentTransformer?.channel9 ?? "CH9", currentTransformer?.channel10 ?? "CH10", currentTransformer?.channel11 ?? "CH11", currentTransformer?.channel12 ?? "CH12", currentTransformer?.channel13 ?? "CH13", currentTransformer?.channel14 ?? "CH14", currentTransformer?.channel15 ?? "CH15", currentTransformer?.channel16 ?? "CH16", currentTransformer?.channel17 ?? "CH17", currentTransformer?.channel18 ?? "CH18", currentTransformer?.channel19 ?? "CH19", currentTransformer?.channel20 ?? "CH20", currentTransformer?.channel21 ?? "CH21", currentTransformer?.channel22 ?? "CH22", currentTransformer?.channel23 ?? "CH23", currentTransformer?.channel24 ?? "CH24" ] /// 通道名称 @IBOutlet weak var channelsLabel: UILabel! /// 电压标签 @IBOutlet weak var voltageLabel: UILabel! /// 电流 @IBOutlet weak var currentLabel: UILabel! /// 功率 @IBOutlet weak var powerLabel: UILabel! /// 显示列表 @IBOutlet weak var listView: UITableView! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = currentTransformer?.remark voltageLabel.text = "Voltage: \(currentTransformer?.voltage ?? 1) V" listView.rowHeight = SHCurrentTransformerChannelDataViewCell.rowheight listView.register( UINib(nibName: currentTransformerChannelDataCellReuseIdentifier, bundle: nil), forCellReuseIdentifier: currentTransformerChannelDataCellReuseIdentifier ) if UIDevice.is_iPad() { let font = UIView.suitFontForPad() channelsLabel.font = font voltageLabel.font = font currentLabel.font = font powerLabel.font = font } } } // MARK: - 状态与解析 extension SHCurrentTransformerShowDataViewController { /// 接收广播数据 override func analyzeReceivedSocketData(_ socketData: SHSocketData!) { if socketData.operatorCode != 0x0151 || socketData.subNetID != currentTransformer?.subnetID || socketData.deviceID != currentTransformer?.deviceID { return } // ======= 解析数据 for index in 0 ..< currentTransformerCount { // 每个通道号对应的两个字节的序号 let highChannel = index * 2 let lowChannel = index * 2 + 1 // 实时电流的单位是 ma let currentValue = ( UInt(socketData.additionalData[highChannel]) << 8) | UInt(socketData.additionalData[lowChannel] ) if currentValue != allChannels[index].current { // 功率KW = 电压V X 电流A X 0.001 allChannels[index].current = currentValue let power = Int(CGFloat((currentTransformer?.voltage ?? 1) * currentValue) * 0.001) allChannels[index].power = CGFloat(power) * 0.001 DispatchQueue.main.async { self.listView.reloadRows( at: [IndexPath(row: index, section: 0)], with: .fade ) } } } } /// 读取状态 private func readDevicestatus() { SHSocketTools.sendData( operatorCode: 0x0150, subNetID: currentTransformer?.subnetID ?? 0, deviceID: currentTransformer?.deviceID ?? 0, additionalData: [] ) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) readDevicestatus() } } // MARK: - 数据源 extension SHCurrentTransformerShowDataViewController:UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return currentTransformerCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: currentTransformerChannelDataCellReuseIdentifier, for: indexPath) as! SHCurrentTransformerChannelDataViewCell cell.channel = allChannels[indexPath.row] return cell } }
30.494845
174
0.582657
e462ac5f818574e6f5d99ae4556215226950e8d1
1,209
// Copyright 2020-2021 Tokamak contributors // // 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 Ezra Berch on 8/20/21. // import TokamakCore typealias _DomTextSanitizer = (String) -> String public extension View { func _domTextSanitizer(_ sanitizer: @escaping (String) -> String) -> some View { environment(\.domTextSanitizer, sanitizer) } } private struct DomTextSanitizerKey: EnvironmentKey { static let defaultValue: _DomTextSanitizer = Sanitizers.HTML.encode } public extension EnvironmentValues { var domTextSanitizer: (String) -> String { get { self[DomTextSanitizerKey.self] } set { self[DomTextSanitizerKey.self] = newValue } } }
28.785714
82
0.728701
207a89eaff9155840f810b0e819fe79362f82677
14,253
// // Copyright © 2019 Essential Developer. All rights reserved. // import XCTest import UIKit import MVVM import FeedFeature final class FeedUIIntegrationTests: XCTestCase { func test_feedView_hasTitle() { let (sut, _) = makeSUT() sut.loadViewIfNeeded() XCTAssertEqual(sut.title, localized("FEED_VIEW_TITLE")) } func test_loadFeedActions_requestFeedFromLoader() { let (sut, loader) = makeSUT() XCTAssertEqual(loader.loadFeedCallCount, 0, "Expected no loading requests before view is loaded") sut.loadViewIfNeeded() XCTAssertEqual(loader.loadFeedCallCount, 1, "Expected a loading request once view is loaded") sut.simulateUserInitiatedFeedReload() XCTAssertEqual(loader.loadFeedCallCount, 2, "Expected another loading request once user initiates a reload") sut.simulateUserInitiatedFeedReload() XCTAssertEqual(loader.loadFeedCallCount, 3, "Expected yet another loading request once user initiates another reload") } func test_loadingFeedIndicator_isVisibleWhileLoadingFeed() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() XCTAssertTrue(sut.isShowingLoadingIndicator, "Expected loading indicator once view is loaded") loader.completeFeedLoading(at: 0) XCTAssertFalse(sut.isShowingLoadingIndicator, "Expected no loading indicator once loading completes successfully") sut.simulateUserInitiatedFeedReload() XCTAssertTrue(sut.isShowingLoadingIndicator, "Expected loading indicator once user initiates a reload") loader.completeFeedLoadingWithError(at: 1) XCTAssertFalse(sut.isShowingLoadingIndicator, "Expected no loading indicator once user initiated loading completes with error") } func test_loadFeedCompletion_rendersSuccessfullyLoadedFeed() { let image0 = makeImage(description: "a description", location: "a location") let image1 = makeImage(description: nil, location: "another location") let image2 = makeImage(description: "another description", location: nil) let image3 = makeImage(description: nil, location: nil) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() assertThat(sut, isRendering: []) loader.completeFeedLoading(with: [image0], at: 0) assertThat(sut, isRendering: [image0]) sut.simulateUserInitiatedFeedReload() loader.completeFeedLoading(with: [image0, image1, image2, image3], at: 1) assertThat(sut, isRendering: [image0, image1, image2, image3]) } func test_loadFeedCompletion_doesNotAlterCurrentRenderingStateOnError() { let image0 = makeImage() let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0], at: 0) assertThat(sut, isRendering: [image0]) sut.simulateUserInitiatedFeedReload() loader.completeFeedLoadingWithError(at: 1) assertThat(sut, isRendering: [image0]) } func test_loadFeedCompletion_rendersErrorMessageOnErrorUntilNextReload() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() XCTAssertEqual(sut.errorMessage, nil) loader.completeFeedLoadingWithError(at: 0) XCTAssertEqual(sut.errorMessage, localized("FEED_VIEW_CONNECTION_ERROR")) sut.simulateUserInitiatedFeedReload() XCTAssertEqual(sut.errorMessage, nil) } func test_errorView_rendersErrorMessageOnLoadingError() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() XCTAssertEqual(sut.errorMessage, nil) loader.completeFeedLoadingWithError(at: 0) XCTAssertEqual(sut.errorMessage, localized("FEED_VIEW_CONNECTION_ERROR")) sut.simulateOnErrorViewClicked() XCTAssertEqual(sut.errorMessage, nil) } func test_feedImageView_loadsImageURLWhenVisible() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) XCTAssertEqual(loader.loadedImageURLs, [], "Expected no image URL requests until views become visible") sut.simulateFeedImageViewVisible(at: 0) XCTAssertEqual(loader.loadedImageURLs, [image0.url], "Expected first image URL request once first view becomes visible") sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected second image URL request once second view also becomes visible") } func test_feedImageView_cancelsImageLoadingWhenNotVisibleAnymore() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) XCTAssertEqual(loader.cancelledImageURLs, [], "Expected no cancelled image URL requests until image is not visible") sut.simulateFeedImageViewNotVisible(at: 0) XCTAssertEqual(loader.cancelledImageURLs, [image0.url], "Expected one cancelled image URL request once first image is not visible anymore") sut.simulateFeedImageViewNotVisible(at: 1) XCTAssertEqual(loader.cancelledImageURLs, [image0.url, image1.url], "Expected two cancelled image URL requests once second image is also not visible anymore") } func test_feedImageViewLoadingIndicator_isVisibleWhileLoadingImage() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage(), makeImage()]) let view0 = sut.simulateFeedImageViewVisible(at: 0) let view1 = sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(view0?.isShowingImageLoadingIndicator, true, "Expected loading indicator for first view while loading first image") XCTAssertEqual(view1?.isShowingImageLoadingIndicator, true, "Expected loading indicator for second view while loading second image") loader.completeImageLoading(at: 0) XCTAssertEqual(view0?.isShowingImageLoadingIndicator, false, "Expected no loading indicator for first view once first image loading completes successfully") XCTAssertEqual(view1?.isShowingImageLoadingIndicator, true, "Expected no loading indicator state change for second view once first image loading completes successfully") loader.completeImageLoadingWithError(at: 1) XCTAssertEqual(view0?.isShowingImageLoadingIndicator, false, "Expected no loading indicator state change for first view once second image loading completes with error") XCTAssertEqual(view1?.isShowingImageLoadingIndicator, false, "Expected no loading indicator for second view once second image loading completes with error") } func test_feedImageView_rendersImageLoadedFromURL() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage(), makeImage()]) let view0 = sut.simulateFeedImageViewVisible(at: 0) let view1 = sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(view0?.renderedImage, .none, "Expected no image for first view while loading first image") XCTAssertEqual(view1?.renderedImage, .none, "Expected no image for second view while loading second image") let imageData0 = UIImage.make(withColor: .red).pngData()! loader.completeImageLoading(with: imageData0, at: 0) XCTAssertEqual(view0?.renderedImage, imageData0, "Expected image for first view once first image loading completes successfully") XCTAssertEqual(view1?.renderedImage, .none, "Expected no image state change for second view once first image loading completes successfully") let imageData1 = UIImage.make(withColor: .blue).pngData()! loader.completeImageLoading(with: imageData1, at: 1) XCTAssertEqual(view0?.renderedImage, imageData0, "Expected no image state change for first view once second image loading completes successfully") XCTAssertEqual(view1?.renderedImage, imageData1, "Expected image for second view once second image loading completes successfully") } func test_feedImageViewRetryButton_isVisibleOnImageURLLoadError() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage(), makeImage()]) let view0 = sut.simulateFeedImageViewVisible(at: 0) let view1 = sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(view0?.isShowingRetryAction, false, "Expected no retry action for first view while loading first image") XCTAssertEqual(view1?.isShowingRetryAction, false, "Expected no retry action for second view while loading second image") let imageData = UIImage.make(withColor: .red).pngData()! loader.completeImageLoading(with: imageData, at: 0) XCTAssertEqual(view0?.isShowingRetryAction, false, "Expected no retry action for first view once first image loading completes successfully") XCTAssertEqual(view1?.isShowingRetryAction, false, "Expected no retry action state change for second view once first image loading completes successfully") loader.completeImageLoadingWithError(at: 1) XCTAssertEqual(view0?.isShowingRetryAction, false, "Expected no retry action state change for first view once second image loading completes with error") XCTAssertEqual(view1?.isShowingRetryAction, true, "Expected retry action for second view once second image loading completes with error") } func test_feedImageViewRetryButton_isVisibleOnInvalidImageData() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage()]) let view = sut.simulateFeedImageViewVisible(at: 0) XCTAssertEqual(view?.isShowingRetryAction, false, "Expected no retry action while loading image") let invalidImageData = Data("invalid image data".utf8) loader.completeImageLoading(with: invalidImageData, at: 0) XCTAssertEqual(view?.isShowingRetryAction, true, "Expected retry action once image loading completes with invalid image data") } func test_feedImageViewRetryAction_retriesImageLoad() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) let view0 = sut.simulateFeedImageViewVisible(at: 0) let view1 = sut.simulateFeedImageViewVisible(at: 1) XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected two image URL request for the two visible views") loader.completeImageLoadingWithError(at: 0) loader.completeImageLoadingWithError(at: 1) XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected only two image URL requests before retry action") view0?.simulateRetryAction() XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url, image0.url], "Expected third imageURL request after first view retry action") view1?.simulateRetryAction() XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url, image0.url, image1.url], "Expected fourth imageURL request after second view retry action") } func test_feedImageView_preloadsImageURLWhenNearVisible() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) XCTAssertEqual(loader.loadedImageURLs, [], "Expected no image URL requests until image is near visible") sut.simulateFeedImageViewNearVisible(at: 0) XCTAssertEqual(loader.loadedImageURLs, [image0.url], "Expected first image URL request once first image is near visible") sut.simulateFeedImageViewNearVisible(at: 1) XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected second image URL request once second image is near visible") } func test_feedImageView_cancelsImageURLPreloadingWhenNotNearVisibleAnymore() { let image0 = makeImage(url: URL(string: "http://url-0.com")!) let image1 = makeImage(url: URL(string: "http://url-1.com")!) let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [image0, image1]) XCTAssertEqual(loader.cancelledImageURLs, [], "Expected no cancelled image URL requests until image is not near visible") sut.simulateFeedImageViewNotNearVisible(at: 0) XCTAssertEqual(loader.cancelledImageURLs, [image0.url], "Expected first cancelled image URL request once first image is not near visible anymore") sut.simulateFeedImageViewNotNearVisible(at: 1) XCTAssertEqual(loader.cancelledImageURLs, [image0.url, image1.url], "Expected second cancelled image URL request once second image is not near visible anymore") } func test_feedImageView_doesNotRenderLoadedImageWhenNotVisibleAnymore() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage()]) let view = sut.simulateFeedImageViewNotVisible(at: 0) loader.completeImageLoading(with: anyImageData()) XCTAssertNil(view?.renderedImage, "Expected no rendered image when an image load finishes after the view is not visible anymore") } func test_loadFeedCompletion_dispatchesFromBackgroundToMainThread() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() let exp = expectation(description: "Wait for background queue") DispatchQueue.global().async { loader.completeFeedLoading(at: 0) exp.fulfill() } wait(for: [exp], timeout: 1.0) } func test_loadImageDataCompletion_dispatchesFromBackgroundToMainThread() { let (sut, loader) = makeSUT() sut.loadViewIfNeeded() loader.completeFeedLoading(with: [makeImage()]) _ = sut.simulateFeedImageViewVisible(at: 0) let exp = expectation(description: "Wait for background queue") DispatchQueue.global().async { loader.completeImageLoading(with: self.anyImageData(), at: 0) exp.fulfill() } wait(for: [exp], timeout: 1.0) } // MARK: - Helpers private func makeSUT(file: StaticString = #filePath, line: UInt = #line) -> (sut: FeedViewController, loader: LoaderSpy) { let loader = LoaderSpy() let sut = FeedUIComposer.feedComposedWith(feedLoader: loader, imageLoader: loader) trackForMemoryLeaks(loader, file: file, line: line) trackForMemoryLeaks(sut, file: file, line: line) return (sut, loader) } private func makeImage(description: String? = nil, location: String? = nil, url: URL = URL(string: "http://any-url.com")!) -> FeedImage { return FeedImage(id: UUID(), description: description, location: location, url: url) } private func anyImageData() -> Data { return UIImage.make(withColor: .red).pngData()! } }
43.587156
171
0.776959
d66de4b4a13de9fbc7444a071917d9f4d70dacb7
4,876
// // MovieDetailViewController.swift // MovieViewer // // Created by Alexander Strandberg on 6/16/16. // Copyright © 2016 Alexander Strandberg. All rights reserved. // import UIKit import AFNetworking class MovieDetailViewController: UIViewController { @IBOutlet weak var posterImageView: UIImageView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var infoView: UIView! var posterURLLow: NSURL? var posterURLHigh: NSURL? var movieTitle: String? var moviedOverview: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let title = movieTitle { self.navigationItem.title = title } if let overview = moviedOverview { overviewLabel.text = overview overviewLabel.sizeToFit() } scrollView.contentSize = CGSize(width: scrollView.frame.size.width, height: infoView.frame.origin.y + infoView.frame.size.height) if let posterURLLow = posterURLLow, posterURLHigh = posterURLHigh { let smallImageRequest = NSURLRequest(URL: posterURLLow) let largeImageRequest = NSURLRequest(URL: posterURLHigh) self.posterImageView.setImageWithURLRequest( smallImageRequest, placeholderImage: nil, success: { (smallImageRequest, smallImageResponse, smallImage) -> Void in // smallImageResponse will be nil if the smallImage is already available // in cache (might want to do something smarter in that case). self.posterImageView.alpha = 0.0 self.posterImageView.image = smallImage; UIView.animateWithDuration(0.3, animations: { () -> Void in self.posterImageView.alpha = 1.0 }, completion: { (sucess) -> Void in // The AFNetworking ImageView Category only allows one request to be sent at a time // per ImageView. This code must be in the completion block. self.posterImageView.setImageWithURLRequest( largeImageRequest, placeholderImage: smallImage, success: { (largeImageRequest, largeImageResponse, largeImage) -> Void in self.posterImageView.image = largeImage; }, failure: { (request, response, error) -> Void in // do something for the failure condition of the large image request // possibly setting the ImageView's image to a default image self.view.backgroundColor = UIColor.grayColor() self.posterImageView.alpha = 0.0 self.posterImageView.image = UIImage(named: "networkErrorIcon") UIView.animateWithDuration(0.3, animations: { () -> Void in self.posterImageView.alpha = 1.0 }) }) }) }, failure: { (request, response, error) -> Void in // do something for the failure condition // possibly try to get the large image self.view.backgroundColor = UIColor.grayColor() self.posterImageView.alpha = 0.0 self.posterImageView.image = UIImage(named: "networkErrorIcon") UIView.animateWithDuration(0.3, animations: { () -> Void in self.posterImageView.alpha = 1.0 }) }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
42.77193
137
0.518458
46a24658370ecc4bb54346837bb14019af571298
507
import UIKit extension UIImage { private final class SomeClassDefinedWithinTheUnitTestingBundle {} enum AssetIdentifier: String { case obligatoryCatImage case obligatoryFoliageImage } convenience init!(assetIdentifier: AssetIdentifier) { let testBundle = Bundle.init(for: SomeClassDefinedWithinTheUnitTestingBundle.self) self.init( named: assetIdentifier.rawValue, in: testBundle, compatibleWith: nil ) } }
24.142857
90
0.672584
ab919b59d3882b8716c796f6109f6c016d295cab
1,615
// // Message.swift // InstagramClone // // Created by David on 2020/8/8. // Copyright © 2020 David. All rights reserved. // import Foundation import Firebase class Message { var messageText: String! var fromId: String! var toId: String! var creationDate: Date! var imageUrl: String? var imageHeight: NSNumber? var imageWidth: NSNumber? var videoUrl: String? var read: Bool! init(dictionary: Dictionary<String, AnyObject>) { if let messageText = dictionary["messageText"] as? String { self.messageText = messageText } if let fromId = dictionary["fromId"] as? String { self.fromId = fromId } if let toId = dictionary["toId"] as? String { self.toId = toId } if let creationDate = dictionary["creationDate"] as? Double { self.creationDate = Date(timeIntervalSince1970: creationDate) } if let imageUrl = dictionary["imageUrl"] as? String { self.imageUrl = imageUrl } if let imageHeight = dictionary["imageHeight"] as? NSNumber { self.imageHeight = imageHeight } if let imageWidth = dictionary["imageWidth"] as? NSNumber { self.imageWidth = imageWidth } if let videoUrl = dictionary["videoUrl"] as? String { self.videoUrl = videoUrl } if let read = dictionary["read"] as? Bool { self.read = read } } func getChatPartnerId() -> String { guard let currentUid = Auth.auth().currentUser?.uid else { return ""} if fromId == currentUid { return toId } else { return fromId } } }
22.123288
73
0.622291
1c343b47211938cf28469a49eb8def993e331bab
393
@testable import BaaServiceKit extension NodeHash { static let fake1 = NodeHash(hashValue: "1", hashIdentifier: "1", urls: [URL.stub]) static let fake2 = NodeHash(hashValue: "2", hashIdentifier: "2", urls: [URL.stub]) static let fake3 = NodeHash(hashValue: "3", hashIdentifier: "3", urls: [URL.stub]) static let allFakes = [NodeHash.fake1, NodeHash.fake2, NodeHash.fake3] }
35.727273
86
0.697201
331a1e168a6f05d24a7abe7fc67f9cc1fdb707af
1,117
import Foundation import SnapshotTesting import SwiftUI import XCTest open class SnapshotTestBase: XCTestCase { public var allowAnimations: Bool = false override open func setUp() { super.setUp() UIView.setAnimationsEnabled(allowAnimations) } open var defaultDevices: [(name: String, device: ViewImageConfig)] { [ ("SE", .iPhoneSe), ("X", .iPhoneX), ("iPadMini", .iPadMini(.portrait) ), ("iPadPro", .iPadPro12_9(.portrait)) ] } open func assertSnapshotDevices<V: View>( _ view: V, devices: [(name: String, device: ViewImageConfig)]? = nil, file: StaticString = #file, testName: String = #function, line: UInt = #line ) { (devices ?? defaultDevices).forEach { let vc = UIHostingController(rootView: view) assertSnapshot( matching: vc, as: .image(on: $0.device), file: file, testName: "\(testName)-\($0.name)", line: line ) } } }
25.976744
72
0.535363
75ff12f7fa39272a8b530d2376d273b90db0ce3f
5,741
// // Persistance.swift // EP Diagram // // Created by David Mann on 5/19/20. // Copyright © 2020 EP Studios. All rights reserved. // import UIKit import os.log enum FileIOError: Error { case searchDirectoryNotFound case documentDirectoryNotFound case epDiagramDirectoryNotFound case diagramDirectoryNotFound case diagramIsUnnamed case duplicateDiagramName case diagramNameIsBlank case decodingFailed case encodingFailed } extension FileIOError: LocalizedError { public var errorDescription: String? { switch self { case .searchDirectoryNotFound: return L("Search directory not found.") case .documentDirectoryNotFound: return L("User document directory not found.") case .epDiagramDirectoryNotFound: return L("EP Diagram directory not found.") case .diagramDirectoryNotFound: return L("Diagram directory not found.") case .diagramIsUnnamed: return L("Diagram has no name.") case .duplicateDiagramName: return L("Diagram name is a duplicate.") case .diagramNameIsBlank: return L("Diagram name can't be blank.") case .decodingFailed: return L("Decoding failed.") case .encodingFailed: return L("Encoding failed.") } } } // Based on this info from Apple: https://developer.apple.com/videos/play/tech-talks/204/ and this example class https://medium.com/@sdrzn/swift-4-codable-lets-make-things-even-easier-c793b6cf29e1 final class FileIO { // Where ladder templates are stored. static let userTemplateFile = "epdiagram_ladder_templates" // Directory where save diagrams. static let epDiagramDir = "epdiagram" static let imageFilename = "image.png" static let ladderFilename = "ladder.json" static let restorationDir = "restoration" enum Directory { case documents case cache case applicationSupport } private static func getURL(for directory: Directory) -> URL? { var searchDirectory : FileManager.SearchPathDirectory switch directory { case .documents: searchDirectory = .documentDirectory case .cache: searchDirectory = .cachesDirectory case .applicationSupport: searchDirectory = .applicationSupportDirectory } let ubiqURL = (UIApplication.shared.delegate as? AppDelegate)?.ubiqURL if let ubiqURL = ubiqURL, directory == .documents { return ubiqURL } else { return FileManager.default.urls(for: searchDirectory, in: .userDomainMask).first } } static func getDocumentsURL() -> URL? { return getURL(for: .documents) } static func getCacheURL() -> URL? { return getURL(for: .cache) } static func store<T: Encodable>(_ object: T, to directory: Directory, withFileName fileName: String, subDirectory: String? = nil) throws { guard var url = getDocumentsURL() else { os_log("Search directory not found", log: .default, type: .fault) throw FileIOError.searchDirectoryNotFound } if let subDirectory = subDirectory { url = url.appendingPathComponent(subDirectory) } let fileURL = url.appendingPathComponent(fileName) let encoder = JSONEncoder() do { let data = try encoder.encode(object) // replace file with new data if FileManager.default.fileExists(atPath: fileURL.path) { try FileManager.default.removeItem(at: fileURL) } FileManager.default.createFile(atPath: fileURL.path, contents: data, attributes: nil) } catch let error { os_log("Encoding error %s", log: OSLog.default, type: .error, error.localizedDescription) throw error } } static func retrieve<T: Decodable>(_ fileName: String, from directory: Directory, subDirectory: String? = nil, as type: T.Type) -> T? { guard var url = getDocumentsURL() else { return nil } if let subDirectory = subDirectory { url = url.appendingPathComponent(subDirectory) } let fileURL = url.appendingPathComponent(fileName) if !FileManager.default.fileExists(atPath: fileURL.path) { return nil } if let data = FileManager.default.contents(atPath: fileURL.path) { let decoder = JSONDecoder() let model = try? decoder.decode(type, from: data) return model } else { return nil } } static func remove(_ fileName: String, from directory: Directory) { if let url = getURL(for: directory)?.appendingPathComponent(fileName, isDirectory: false) { if FileManager.default.fileExists(atPath: url.path) { do { try FileManager.default.removeItem(at: url) } catch { fatalError(error.localizedDescription) } } } } static func fileExists(_ fileName: String, in directory: Directory) -> Bool { if let url = getURL(for: directory)?.appendingPathComponent(fileName, isDirectory: false) { return FileManager.default.fileExists(atPath: url.path) } else { return false } } static func enumerateDirectory(_ url: URL) -> [String] { var paths: [String] = [] if let enumerator = FileManager.default.enumerator(atPath: url.path) { for case let path as String in enumerator { paths.append(path) } } return paths } }
35.220859
196
0.625501
9b1e41620762a35f9fe6c0165219aa37cc64f28b
570
// // CacheError.swift // SwiftX // // Created by wangcong on 2018/12/7. // Copyright © 2018 wangcong. All rights reserved. // import Foundation extension XCache { // MARK: 错误信息 public enum CacheError: Error { // 未查找到数据 case notExists // JSONDecoder fail case decodingFailed // NSKeyedArchiver JSONEncoder fail case encodingFailed // 读取数据失败(仅存在于磁盘存储) case dataReadFailed // 数据写入失败(仅存在于磁盘存储) case dataWriteFailed } }
17.272727
51
0.550877