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
e4986db3aacfe761ae52aad642c50c75041c14c8
1,736
// // Created by Eugene Kazaev on 07/02/2018. // #if os(iOS) import Foundation import UIKit /// The `ContainerFactory` that creates a `UITabBarController` instance. public struct TabBarControllerFactory<VC: UITabBarController, C>: ContainerFactory { // MARK: Associated types public typealias ViewController = VC public typealias Context = C // MARK: Properties /// A Xib file name public let nibName: String? /// A `Bundle` instance public let bundle: Bundle? /// `UITabBarControllerDelegate` reference public private(set) weak var delegate: UITabBarControllerDelegate? /// The additional configuration block public let configuration: ((_: VC) -> Void)? // MARK: Methods /// Constructor public init(nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil, delegate: UITabBarControllerDelegate? = nil, configuration: ((_: VC) -> Void)? = nil) { self.nibName = nibNameOrNil self.bundle = nibBundleOrNil self.delegate = delegate self.configuration = configuration } public func build(with context: C, integrating coordinator: ChildCoordinator<C>) throws -> VC { let tabBarController = VC(nibName: nibName, bundle: bundle) if let delegate = delegate { tabBarController.delegate = delegate } if !coordinator.isEmpty { tabBarController.viewControllers = try coordinator.build(with: context, integrating: tabBarController.viewControllers ?? []) } if let configuration = configuration { configuration(tabBarController) } return tabBarController } } #endif
27.555556
136
0.65265
5650cf72a93c1f73d5681dcf72823f977e8db2d7
1,340
// // File.swift // // // Created by sakiyamaK on 2022/04/14. // import MapKit public extension MKPointAnnotation { convenience init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) { self.init() self.coordinate = coordinate self.title = title self.subtitle = subtitle } convenience init(coordinate: CLLocationCoordinate2D, title: String) { self.init() self.coordinate = coordinate self.title = title } convenience init(coordinate: CLLocationCoordinate2D) { self.init() self.coordinate = coordinate } convenience init(title: String, subtitle: String) { self.init() self.title = title self.subtitle = subtitle } convenience init(title: String) { self.init() self.title = title } } //MARK: - Declarative method public extension MKPointAnnotation { @discardableResult func coordinate(_ coordinate: CLLocationCoordinate2D) -> Self { self.coordinate = coordinate return self } @discardableResult func title(_ title: String) -> Self { self.title = title return self } @discardableResult func subtitle(_ subtitle: String) -> Self { self.subtitle = subtitle return self } }
21.612903
91
0.620149
1eb2404aec72c51cc7a0d1d831ecc6b4ff1cf32c
4,704
// // UIViewController+Extensions.swift // Din Din Demo // // Created by jeet_gandhi on 14/11/20. // #if os(iOS) || os(tvOS) import UIKit import RxSwift import RxCocoa extension Reactive where Base: UIViewController { public var viewDidLoad: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.viewDidLoad)).map { _ in } return ControlEvent(events: source) } public var viewWillAppear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewWillAppear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } public var viewDidAppear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewDidAppear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } public var viewWillDisappear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewWillDisappear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } public var viewDidDisappear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewDidDisappear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } public var viewWillLayoutSubviews: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.viewWillLayoutSubviews)).map { _ in } return ControlEvent(events: source) } public var viewDidLayoutSubviews: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.viewDidLayoutSubviews)).map { _ in } return ControlEvent(events: source) } public var willMoveToParentViewController: ControlEvent<UIViewController?> { let source = self.methodInvoked(#selector(Base.willMove)).map { $0.first as? UIViewController } return ControlEvent(events: source) } public var didMoveToParentViewController: ControlEvent<UIViewController?> { let source = self.methodInvoked(#selector(Base.didMove)).map { $0.first as? UIViewController } return ControlEvent(events: source) } public var didReceiveMemoryWarning: ControlEvent<Void> { let source = self.methodInvoked(#selector(Base.didReceiveMemoryWarning)).map { _ in } return ControlEvent(events: source) } /// Rx observable, triggered when the ViewController appearance state changes (true if the View is being displayed, false otherwise) public var isVisible: Observable<Bool> { let viewDidAppearObservable = self.base.rx.viewDidAppear.map { _ in true } let viewWillDisappearObservable = self.base.rx.viewWillDisappear.map { _ in false } return Observable<Bool>.merge(viewDidAppearObservable, viewWillDisappearObservable) } /// Rx observable, triggered when the ViewController is being dismissed public var isDismissing: ControlEvent<Bool> { let source = self.sentMessage(#selector(Base.dismiss)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } } #endif extension UIViewController { public static var currentRootViewController: UIViewController { guard let window = UIApplication.shared.delegate?.window as? UIWindow else { fatalError("Window unavailable") } guard let rootViewController = window.rootViewController else { fatalError("root view controller not available") } guard let presentedViewController = rootViewController.presentedViewController else { return rootViewController } return presentedViewController } public static func make<T: MenuViewControllerProtocol>(viewController: T.Type, viewModel: T.ViewModelT, from storyBoard: String = "Main") -> T where T: UIViewController { var vc = make(viewController: viewController, from: storyBoard) vc.viewModel = viewModel return vc } public static func make<T: UIViewController>(viewController: T.Type, from storyBoard: String) -> T { let viewControllerName = String(describing: viewController) if storyBoard.isEmpty { let viewController = T(nibName: viewControllerName, bundle: nil) as T return viewController } else { let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: viewController as AnyClass)) guard let viewController = storyboard.instantiateViewController(withIdentifier: viewControllerName) as? T else { fatalError("Unable to create ViewController: \(viewControllerName) from storyboard: \(storyboard)") } return viewController } } }
39.529412
174
0.691539
56ca045c924ea222561ba3fc0194c8ab574d32fa
430
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // RuleActionProtocol is the action that is performed when the alert rule becomes active, and when an alert condition // is resolved. public protocol RuleActionProtocol : Codable { }
43
118
0.767442
20134135f591a483f36b71c59944853653803975
1,168
// // AKDrawerUITests.swift // AKDrawerUITests // // Created by Kishan Barmawala on 20/12/19. // Copyright © 2019 Gatisofttech. All rights reserved. // import XCTest class AKDrawerUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.371429
182
0.692637
e2734e643fc14104a7489a5954f54a8ac0fde06c
1,713
// // LXBaseLabel.swift // swiftPatient // // Created by 康健科技 on 2020/1/8. // Copyright © 2020 康健科技. All rights reserved. // import UIKit extension UILabel{ func setNormalLabel(fount: CGFloat,title: String,textColor: UIColor) -> UILabel { let label = UILabel() label.text = title label.font = UIFont.systemFont(ofSize: fount) label.textColor = textColor return label } func autoLabel(laebl:UILabel,lineHeight:CGFloat){ laebl.numberOfLines=0 laebl.lineBreakMode = NSLineBreakMode.byWordWrapping let text:String = laebl.text!//获取label的text laebl.attributedText = self.getAttributeStringWithString(text, lineSpace: lineHeight) let fontSize = CGSize(width: laebl.frame.width, height: laebl.font.lineHeight) let rect:CGSize = text.boundingRect(with: fontSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: laebl.font!], context: nil).size; laebl.frame = CGRect(x:laebl.frame.origin.x,y:laebl.frame.origin.y+12,width: rect.width, height: rect.height) laebl.sizeToFit() } //设置行间距 fileprivate func getAttributeStringWithString(_ string: String,lineSpace:CGFloat ) -> NSAttributedString{ let attributedString = NSMutableAttributedString(string: string) let paragraphStye = NSMutableParagraphStyle() //调整行间距 paragraphStye.lineSpacing = lineSpace let rang = NSMakeRange(0, CFStringGetLength(string as CFString?)) attributedString .addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStye, range: rang) return attributedString } }
38.066667
191
0.695271
d778e81c503fdb2ff0e146bb198fd0d8c0b887b4
378
import XCTest @testable import Example final class ViewControllerTests: XCTestCase { func test_viewDidLoad_whenInvoked_expectFooInvoked() { // mocks let sut = MockMyObject() let viewController = ViewController() // setup viewController.myObject = sut // test viewController.viewDidLoad() XCTAssertTrue(sut.invocations.isInvoked(MockMyObject.foo1.name)) } }
21
66
0.767196
1c0e665f28ecda735f62e24068d480871eea0a76
7,641
// // PlantsTableViewController.swift // Oxygen // // Created by Ezra Black on 4/27/20. // Copyright © 2020 Casanova Studios. All rights reserved. // import UIKit import CoreData class PlantsTableViewController: UITableViewController { // MARK: - Properties var shouldPresentLoginViewController: Bool { ApiController.bearer == nil } let apiController = ApiController() lazy var fetchedResultsController: NSFetchedResultsController<Plant> = { let fetchRequest: NSFetchRequest<Plant> = Plant.fetchRequest() fetchRequest.sortDescriptors = [NSSortDescriptor(key: "commonName", ascending: true)] let context = CoreDataStack.shared.mainContext let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) frc.delegate = self do { try frc.performFetch() } catch { NSLog("Error") } return frc }() // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { if shouldPresentLoginViewController { presentRegisterView() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController.sections?.count ?? 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fetchedResultsController.sections?[section].numberOfObjects ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "PlantCell", for: indexPath) as? PlantTableViewCell else { fatalError("Can't dequeue cell of type \(PlantTableViewCell())") } cell.plant = fetchedResultsController.object(at: indexPath) cell.delegate = self return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let plant = fetchedResultsController.object(at: indexPath) apiController.deletePlantFromServer(plant) { result in guard let _ = try? result.get() else { return } DispatchQueue.main.async { CoreDataStack.shared.mainContext.delete(plant) do { try CoreDataStack.shared.mainContext.save() } catch { CoreDataStack.shared.mainContext.reset() NSLog("Error saving managed object context: \(error)") } } } } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "CreatePlantSegue" { guard let createVC = segue.destination as? PlantDetailViewController else { return } createVC.apiController = apiController } else if segue.identifier == "PlantDetailSegue" { guard let detailVC = segue.destination as? PlantDetailViewController, let indexPath = tableView.indexPathForSelectedRow else { return } detailVC.plant = fetchedResultsController.object(at: indexPath) detailVC.apiController = apiController } } // MARK: - Actions @IBAction func signOut(_ sender: Any) { // Clear everything self.clearData() ApiController.bearer = nil // Move the user back to the register page self.presentRegisterView() } @IBAction func myUnwindAction(unwindSegue: UIStoryboardSegue) { } // MARK: - Core Data func clearData() { let context = CoreDataStack.shared.mainContext do { let fetchRequest: NSFetchRequest<Plant> = Plant.fetchRequest() let allPlants = try context.fetch(fetchRequest) for plant in allPlants { let plantData: NSManagedObject = plant as NSManagedObject context.delete(plantData) } try context.save() } catch { NSLog("Could not fetch plants.") } } // MARK: - Private Functions private func presentRegisterView() { let loginRegisterStoryboard = UIStoryboard(name: "Login-Register", bundle: Bundle(identifier: "CasanovaStudios.Oxygen")) let registerViewController = loginRegisterStoryboard.instantiateViewController(withIdentifier: "RegisterView") registerViewController.modalPresentationStyle = .fullScreen present(registerViewController, animated: true) } } extension PlantsTableViewController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: tableView.insertSections(IndexSet(integer: sectionIndex), with: .automatic) case .delete: tableView.deleteSections(IndexSet(integer: sectionIndex), with: .automatic) default: break } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: guard let newIndexPath = newIndexPath else { return } tableView.insertRows(at: [newIndexPath], with: .automatic) case .update: guard let indexPath = indexPath else { return } tableView.reloadRows(at: [indexPath], with: .automatic) case .move: guard let oldIndexPath = indexPath, let newIndexPath = newIndexPath else { return } tableView.deleteRows(at: [oldIndexPath], with: .automatic) tableView.insertRows(at: [newIndexPath], with: .automatic) case .delete: guard let indexPath = indexPath else { return } tableView.deleteRows(at: [indexPath], with: .automatic) @unknown default: break } } } extension PlantsTableViewController: PlantCellDelegate { func timerDidFire(plant: Plant) { showAlert(title: "Water is required", message: "\(plant.commonName ?? "egg") needs water badly") } func showAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alert, animated: true) } }
40.860963
118
0.616542
e49361746f051087d3515f61f6f3f2e15c3c38c2
869
// // LatLngRadiansTest.swift // UnitTest // // Created by Chris Arriola on 2/4/21. // Copyright © 2021 Google. All rights reserved. // import XCTest @testable import GoogleMapsUtils class LatLngRadiansTest : XCTestCase { let latLng1 = LatLngRadians(latitude: 1, longitude: 2) let latLng2 = LatLngRadians(latitude: -1, longitude: 8) let latLng3 = LatLngRadians(latitude: 0, longitude: 10) private let accuracy = 1e-15 func testAddition() { let sum = latLng1 + latLng2 XCTAssertEqual(latLng3.latitude, sum.latitude, accuracy: accuracy) XCTAssertEqual(latLng3.longitude, sum.longitude, accuracy: accuracy) } func testSubtraction() { let difference = latLng3 - latLng2 XCTAssertEqual(latLng1.latitude, difference.latitude, accuracy: accuracy) XCTAssertEqual(latLng1.longitude, difference.longitude, accuracy: accuracy) } }
28.032258
79
0.735328
1d62f743857099dbb017178e58c7316fb8db3ad5
428
// // Property+Generate.swift // JSONModelGeneratorPackageDescription // // Created by Simon Anreiter on 16.12.17. // import Foundation public typealias GeneratorOutput = [String] public protocol Generating { func render() -> [String] } // indent operator prefix operator ==> prefix func ==> (val: String) -> String { return "\t\(val)" } prefix func ==> (val: [String]) -> [String] { return val.map(==>) }
15.851852
45
0.651869
695c8c39ea3531acd6c1fe28624a371749c42293
1,698
import Foundation public struct SeverityLevelsConfiguration: RuleConfiguration, Equatable { public var consoleDescription: String { let errorString: String if let errorValue = error { errorString = ", error: \(errorValue)" } else { errorString = "" } return "warning: \(warning)" + errorString } public var shortConsoleDescription: String { if let errorValue = error { return "w/e: \(warning)/\(errorValue)" } return "w: \(warning)" } var warning: Int var error: Int? var params: [RuleParameter<Int>] { if let error = error { return [RuleParameter(severity: .error, value: error), RuleParameter(severity: .warning, value: warning)] } return [RuleParameter(severity: .warning, value: warning)] } public mutating func apply(configuration: Any) throws { if let configurationArray = [Int].array(of: configuration), !configurationArray.isEmpty { warning = configurationArray[0] error = (configurationArray.count > 1) ? configurationArray[1] : nil } else if let configDict = configuration as? [String: Int?], !configDict.isEmpty, Set(configDict.keys).isSubset(of: ["warning", "error"]) { warning = (configDict["warning"] as? Int) ?? warning error = configDict["error"] as? Int } else { throw ConfigurationError.unknownConfiguration } } } public func == (lhs: SeverityLevelsConfiguration, rhs: SeverityLevelsConfiguration) -> Bool { return lhs.warning == rhs.warning && lhs.error == rhs.error }
34.653061
97
0.607185
46b7077985546317019794db8803b69f4375c3d0
647
// // FlickrPhotoModel.swift // FlickrViperTest // // Created by Константин on 24.08.16. // Copyright © 2016 Константин. All rights reserved. // import Foundation struct FlickrPhotoModel { let photoId: String let farm: Int let secret: String let server: String let title: String var photoUrl: NSURL { return flickrImageURL() } var largePhotoUrl: NSURL { return flickrImageURL(size: "b") } private func flickrImageURL(size: String = "m") -> NSURL { return NSURL(string: "https://farm\(farm).staticflickr.com/\(server)/\(photoId)_\(secret)_\(size).jpg")! } }
20.870968
112
0.629057
468984cc4559ba0a1fe746756495c7054fce35cd
4,178
import Foundation /// This is the element for listing build configurations. public final class XCBuildConfiguration: PBXObject { // MARK: - Attributes /// Base xcconfig file reference. var baseConfigurationReference: PBXObjectReference? /// Base xcconfig file reference. public var baseConfiguration: PBXFileReference? { get { baseConfigurationReference?.getObject() } set { if let newValue = newValue { baseConfigurationReference = newValue.reference } } } /// A map of build settings. public var buildSettings: BuildSettings /// The configuration name. public var name: String // MARK: - Init /// Initializes a build configuration. /// /// - Parameters: /// - name: build configuration name. /// - baseConfiguration: base configuration. /// - buildSettings: dictionary that contains the build settings for this configuration. public init(name: String, baseConfiguration: PBXFileReference? = nil, buildSettings: BuildSettings = [:]) { baseConfigurationReference = baseConfiguration?.reference self.buildSettings = buildSettings self.name = name super.init() } // MARK: - Decodable fileprivate enum CodingKeys: String, CodingKey { case baseConfigurationReference case buildSettings case name } public required init(from decoder: Decoder) throws { let objects = decoder.context.objects let objectReferenceRepository = decoder.context.objectReferenceRepository let container = try decoder.container(keyedBy: CodingKeys.self) if let baseConfigurationReference: String = try container.decodeIfPresent(.baseConfigurationReference) { self.baseConfigurationReference = objectReferenceRepository.getOrCreate(reference: baseConfigurationReference, objects: objects) } else { baseConfigurationReference = nil } buildSettings = try container.decode([String: Any].self, forKey: .buildSettings) name = try container.decode(.name) try super.init(from: decoder) } // MARK: - Public /// Appends a value to the given setting. /// If the setting doesn't exist, it initializes it with the $(inherited) value and appends the given value to it. /// /// - Parameters: /// - name: Setting to which the value will be appended. /// - value: Value to be appended. public func append(setting name: String, value: String) { guard !value.isEmpty else { return } let existing: Any = buildSettings[name] ?? "$(inherited)" switch existing { case let string as String where string != value: let newValue = [string, value].joined(separator: " ") buildSettings[name] = newValue case let array as [String]: var newValue = array newValue.append(value) buildSettings[name] = newValue.uniqued() default: break } } override func isEqual(to object: Any?) -> Bool { guard let rhs = object as? XCBuildConfiguration else { return false } return isEqual(to: rhs) } } // MARK: - PlistSerializable extension XCBuildConfiguration: PlistSerializable { func plistKeyAndValue(proj _: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) { var dictionary: [CommentedString: PlistValue] = [:] dictionary["isa"] = .string(CommentedString(XCBuildConfiguration.isa)) dictionary["name"] = .string(CommentedString(name)) dictionary["buildSettings"] = buildSettings.plist() if let baseConfigurationReference = baseConfigurationReference { let fileElement: PBXFileElement? = baseConfigurationReference.getObject() dictionary["baseConfigurationReference"] = .string(CommentedString(baseConfigurationReference.value, comment: fileElement?.fileName())) } return (key: CommentedString(reference, comment: name), value: .dictionary(dictionary)) } }
36.649123
147
0.653183
91ba60dc1b7286b1e04c947641c1bd8cb9c42567
1,201
// // AppDelegate.swift // JSONPlaceholderViewer // // Created by Yoshikuni Kato on 6/16/18. // Copyright © 2018 Yoshikuni Kato. All rights reserved. // import UIKit import ReactiveSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { private var appDependencies: AppDependencies? private var windowCoordinator: WindowCoordinator? var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { appDependencies = AppDependenciesImpl() windowCoordinator = appDependencies?.coordinatorFactory.window() window = windowCoordinator?.window appDependencies?.components.coreDataStack .setupStack() .observe(on: UIScheduler()) .startWithResult { [unowned self] result in switch result { case .failure(let error): fatalError("Failed to load Core Data stack: \(error)") case .success: self.windowCoordinator?.start() } } return true } }
26.688889
91
0.634471
48993f693417a1aae46d9e11db1bb0dbb1dae58f
614
import Foundation import HandySwift class XcodeBuildPhasesOptions: RuleOptions { let projectPath: String let targetName: String let runScripts: [String: String] override init(_ optionsDict: [String: Any], rule: Rule.Type) { projectPath = RuleOptions.requiredString(forOption: "project_path", in: optionsDict, rule: rule) targetName = RuleOptions.requiredString(forOption: "target_name", in: optionsDict, rule: rule) runScripts = RuleOptions.requiredPathsToStrings(forOption: "run_scripts", in: optionsDict, rule: rule) super.init(optionsDict, rule: rule) } }
36.117647
110
0.726384
7240d77d4110610454febdf925e0b5d26d067f13
2,035
// // BarDemoViewController.swift // ChartsDemo-OSX // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts import Foundation import Cocoa import Charts public class BarDemoViewController: NSViewController { @IBOutlet var barChartView: BarChartView! override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let ys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) } let ys2 = Array(1..<10).map { x in return cos(Double(x) / 2.0 / 3.141) } let yse1 = ys1.enumerate().map { x, y in return BarChartDataEntry(x: Double(x), y: y) } let yse2 = ys2.enumerate().map { x, y in return BarChartDataEntry(x: Double(x), y: y) } let data = BarChartData() let ds1 = BarChartDataSet(values: yse1, label: "Hello") ds1.colors = [NSUIColor.redColor()] data.addDataSet(ds1) let ds2 = BarChartDataSet(values: yse2, label: "World") ds2.colors = [NSUIColor.blueColor()] data.addDataSet(ds2) self.barChartView.data = data self.barChartView.gridBackgroundColor = NSUIColor.whiteColor() self.barChartView.descriptionText = "Barchart Demo" } @IBAction func save(sender: AnyObject) { let panel = NSSavePanel() panel.allowedFileTypes = ["png"] panel.beginSheetModalForWindow(self.view.window!) { (result) -> Void in if result == NSFileHandlingPanelOKButton { if let path = panel.URL?.path { self.barChartView.saveToPath(path, format: .PNG, compressionQuality: 1.0) } } } } override public func viewWillAppear() { self.barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0) } }
31.796875
95
0.598526
095ba6600c41b1b93fa1aefe4c550e8871788c93
3,502
// // SignInView.swift // Chat // // Created by Lee on 2020/07/08. // Copyright © 2020 Kira. All rights reserved. // import UIKit protocol SignInViewDelegate: class { func signInButtonDidTap(email: String?, password: String?) func signUpButtonDidTap() } class SignInView: UIView { // MARK: - Properties weak var delegate: SignInViewDelegate? private let emailTextField = UITextField() private let passwordTextField = UITextField() private let signInButton = UIButton() private let signUpButton = UIButton() // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) setUI() setConstraint() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UI private func setUI() { emailTextField.placeholder = "이메일을 입력해 주세요" emailTextField.keyboardType = .emailAddress passwordTextField.placeholder = "비밀번호를 입력해 주세요" passwordTextField.isSecureTextEntry = true [emailTextField, passwordTextField].forEach { $0.font = .systemFont(ofSize: 30) $0.backgroundColor = UIColor.darkGray.withAlphaComponent(0.1) } signInButton.setTitle("입장", for: .normal) signInButton.backgroundColor = .darkGray signUpButton.setTitle("회원가입", for: .normal) signUpButton.backgroundColor = .systemBlue [signInButton, signUpButton].forEach { $0.setTitleColor(.white, for: .normal) $0.addTarget(self, action: #selector(buttonDidTap), for: .touchUpInside) } } @objc private func buttonDidTap(_ sender: UIButton) { sender == signInButton ? delegate?.signInButtonDidTap(email: emailTextField.text, password: passwordTextField.text) : delegate?.signUpButtonDidTap() } private struct Standard { static let space: CGFloat = 16 } private func setConstraint() { [emailTextField, passwordTextField, signInButton, signUpButton].forEach { self.addSubview($0) $0.translatesAutoresizingMaskIntoConstraints = false switch $0 { case is UITextField: $0.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true $0.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true case is UIButton: $0.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true $0.widthAnchor.constraint(equalToConstant: 120).isActive = true $0.heightAnchor.constraint(equalToConstant: 40).isActive = true default: break } } NSLayoutConstraint.activate([ emailTextField.topAnchor.constraint(equalTo: self.topAnchor), passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: Standard.space), signInButton.topAnchor.constraint(equalTo: passwordTextField.bottomAnchor, constant: Standard.space), signUpButton.topAnchor.constraint(equalTo: signInButton.bottomAnchor, constant: Standard.space), signUpButton.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) } }
32.425926
115
0.615648
01b22d7c3fa738ff3483210346446671b57afad9
2,030
// // Copyright (c) 2019 Nathan E. Walczak // // MIT License // // 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 XCTest @testable import BlackboardFramework class AssetDataSetTests: XCTestCase { func testDecodable() { let json = """ { "info" : { "version" : 1, "author" : "xcode" }, "data" : [ { "idiom" : "universal", "filename" : "welcome-message.txt", "universal-type-identifier" : "public.plain-text" } ] } """ let data = Data(json.utf8) do { let assetDataSet = try JSONDecoder().decode(AssetDataSet.self, from: data) XCTAssertNotNil(assetDataSet.info) XCTAssertEqual(assetDataSet.data.count, 1) } catch { XCTFail(error.localizedDescription) } } }
33.278689
86
0.617241
0a49dec82d3c834e1c9efa2fa91fc0f8401c5f13
24,889
// // PixelKitTests.swift // PixelKitTests // // Created by Anton Heestand on 2019-10-16. // Copyright © 2019 Hexagons. All rights reserved. // import XCTest import Cocoa import LiveValues import RenderKit import PixelKit_macOS class PixelKitTests: XCTestCase { var testPix: (PIX & NODEOut)! var testPixA: (PIX & NODEOut)! var testPixB: (PIX & NODEOut)! override func setUp() { PixelKit.main.logger.logAll() PixelKit.main.render.logger.logAll() PixelKit.main.render.engine.logger.logAll() } func setuUpManual() { PixelKit.main.render.engine.renderMode = .manual } func setUpTestPixs() { (testPix, testPixA, testPixB) = Files.makeTestPixs() } override func tearDown() {} func testAveragePixGenerators() { setuUpManual() /// 8bit at 128x128 let averages: [AutoPIXGenerator: CGFloat] = [ .arcpix: 0.047119140625, .circlepix: 0.197021484375, .colorpix: 1.0, .gradientpix: 0.5, .linepix: 0.0115966796875, .noisepix: 0.4070302925856992, .polygonpix: 0.16357421875, .rectanglepix: 0.19140625 ] for average in averages { print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") print("testing", average.key.name) let pix = average.key.pixType.init(at: ._128) let expect = XCTestExpectation() try! PixelKit.main.render.engine.manuallyRender { guard let pixels = pix.renderedPixels else { XCTAssert(false); expect.fulfill(); return } let lum = pixels.average.lum.cg print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", lum) XCTAssert(lum == average.value, "\(average.key.name) average should be \(average.value) and was \(lum)") expect.fulfill() } self.wait(for: [expect], timeout: 1.0) pix.destroy() } } func testShapePixGenerators() { setuUpManual() let shapes: [AutoPIXGenerator: String] = [ .arcpix: """ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ """, .circlepix: """ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ """, .colorpix: """ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ ⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️ """, .linepix: """ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️⬜️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ """, .noisepix: """ ◻️◻️◻️◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◻️◻️◽️◽️◽️◽️◽️▫️▫️◽️▫️▫️◽️◽️◽️◽️◽️◽️ ◻️◻️◻️◽️◽️◽️◽️◽️▫️▫️▫️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◻️◽️◽️◽️◽️◽️▫️▫️◽️◽️▫️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◻️◽️◽️◽️◽️◽️▫️▫️◽️◽️▫️◽️◽️◽️◽️◽️◽️◻️ ◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◻️◻️ ◻️◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◻️◻️◻️ ◻️◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◻️◻️ ◻️◻️◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◻️◽️ ◻️◻️◻️◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️ ◻️◻️◻️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◽️◻️◻️◽️◽️◽️◽️ """, .polygonpix: """ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️⬜️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️⬜️⬜️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ """, .rectanglepix: """ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️⬜️⬜️⬜️⬜️⬜️⬜️⬜️⬜️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ ◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️◾️ """ ] for shape in shapes { let pix = shape.key.pixType.init(at: .custom(w: 20, h: 20)) let expect = XCTestExpectation() try! PixelKit.main.render.engine.manuallyRender { guard let pixels = pix.renderedPixels else { XCTAssert(false); expect.fulfill(); return } var text = "" for row in pixels.raw { if text != "" { text += "\n" } for pixel in row { let c = pixel.color.lum.cg text += c <= 0.0 ? "◾️" : c <= 0.25 ? "▫️" : c <= 0.5 ? "◽️" : c <= 0.75 ? "◻️" : "⬜️" } } XCTAssertEqual(shape.value, text, "\(shape.key.name) has a bad map") expect.fulfill() } wait(for: [expect], timeout: 1.0) pix.destroy() } } func testHueSaturationPix() { setuUpManual() let colorPix = ColorPIX(at: ._128) colorPix.color = .red let hueSaturationPix = HueSaturationPIX() hueSaturationPix.input = colorPix hueSaturationPix.hue = 0.5 hueSaturationPix.saturation = 0.5 let expect = XCTestExpectation() try! PixelKit.main.render.engine.manuallyRender { guard let pixels = hueSaturationPix.renderedPixels else { XCTAssert(false); expect.fulfill(); return } let color = pixels.average let hue = color.hue.cg let sat = color.sat.cg let roundHue = round(hue * 100) / 100 let roundSat = round(sat * 100) / 100 XCTAssertEqual(roundHue, 0.5) XCTAssertEqual(roundSat, 0.5) expect.fulfill() } wait(for: [expect], timeout: 1.0) } // MARK: - Cached Standard func testCachedGenerators() { setuUpManual() guard let outputUrl = Files.outputUrl() else { XCTAssert(false); return } let folderUrl = outputUrl.appendingPathComponent("generators") for auto in AutoPIXGenerator.allCases { let pix = auto.pixType.init(at: ._128) let bgPix = .black & pix let url = folderUrl.appendingPathComponent("\(auto.name).png") guard let data = try? Data(contentsOf: url) else { XCTAssert(false, auto.name); continue } guard let img = NSImage(data: data) else { XCTAssert(false, auto.name); continue } let imgPix = ImagePIX() imgPix.image = img let diffPix = bgPix % imgPix let expect = XCTestExpectation() try! PixelKit.main.render.engine.manuallyRender { guard let pixels = diffPix.renderedPixels else { XCTAssert(false, auto.name); expect.fulfill(); return } let avg = pixels.average.lum.cg XCTAssertEqual(avg, 0.0, auto.name) // if avg != 0.0 { // let diffUrl = folderUrl.appendingPathComponent("\(auto.name)_diff.png") // guard let image: NSImage = diffPix.renderedImage else { fatalError() } // guard image.savePNG(to: diffUrl) else { fatalError() } // } pix.destroy() imgPix.destroy() diffPix.destroy() expect.fulfill(); } wait(for: [expect], timeout: 1.0) } } func testCachedSingleEffects() { setuUpManual() setUpTestPixs() guard let outputUrl = Files.outputUrl() else { XCTAssert(false); return } let folderUrl = outputUrl.appendingPathComponent("singleEffects") for auto in AutoPIXSingleEffect.allCases { let pix = auto.pixType.init() pix.input = testPix let bgPix = .black & pix let url = folderUrl.appendingPathComponent("\(auto.name).png") guard let data = try? Data(contentsOf: url) else { XCTAssert(false, auto.name); continue } guard let img = NSImage(data: data) else { XCTAssert(false, auto.name); continue } let imgPix = ImagePIX() imgPix.image = img let diffPix = bgPix % imgPix let expect = XCTestExpectation() try! PixelKit.main.render.engine.manuallyRender { guard let pixels = diffPix.renderedPixels else { XCTAssert(false, auto.name); expect.fulfill(); return } let avg = pixels.average.lum.cg XCTAssertEqual(avg, 0.0, auto.name) // if avg != 0.0 { // let diffUrl = folderUrl.appendingPathComponent("\(auto.name)_diff.png") // guard let diffImg: NSImage = diffPix.renderedImage else { fatalError() } // guard diffImg.savePNG(to: diffUrl) else { fatalError() } // } pix.destroy() imgPix.destroy() diffPix.destroy() expect.fulfill(); } wait(for: [expect], timeout: 1.0) } } func testCachedMergerEffects() { setuUpManual() setUpTestPixs() guard let outputUrl = Files.outputUrl() else { XCTAssert(false); return } let folderUrl = outputUrl.appendingPathComponent("mergerEffects") for auto in AutoPIXMergerEffect.allCases { let pix = auto.pixType.init() pix.inputA = testPixA pix.inputB = testPixB let bgPix = .black & pix let url = folderUrl.appendingPathComponent("\(auto.name).png") guard let data = try? Data(contentsOf: url) else { XCTAssert(false, auto.name); continue } guard let img = NSImage(data: data) else { XCTAssert(false, auto.name); continue } let imgPix = ImagePIX() imgPix.image = img let diffPix = bgPix % imgPix let expect = XCTestExpectation() try! PixelKit.main.render.engine.manuallyRender { guard let pixels = diffPix.renderedPixels else { XCTAssert(false, auto.name); expect.fulfill(); return } let avg = pixels.average.lum.cg XCTAssertEqual(avg, 0.0, auto.name) // if avg != 0.0 { // let diffUrl = folderUrl.appendingPathComponent("\(auto.name)_diff.png") // guard let diffImg: NSImage = diffPix.renderedImage else { fatalError() } // guard diffImg.savePNG(to: diffUrl) else { fatalError() } // } pix.destroy() imgPix.destroy() diffPix.destroy() expect.fulfill(); } wait(for: [expect], timeout: 1.0) } } // MARK: - Cached Random func testCachedRandomGenerators() { setuUpManual() guard let outputUrl = Files.outputUrl() else { XCTAssert(false); return } let folderUrl = outputUrl.appendingPathComponent("randomGenerators") for auto in AutoPIXGenerator.allCases { let pix = auto.pixType.init(at: ._128) let bgPix = .black & pix let imgPix = ImagePIX() let diffPix = bgPix % imgPix for i in 0..<Randomize.randomCount { let url = folderUrl.appendingPathComponent("\(auto.name)_\(i).png") guard let data = try? Data(contentsOf: url) else { XCTAssert(false, auto.name); continue } guard let img = NSImage(data: data) else { XCTAssert(false, auto.name); continue } imgPix.image = img Randomize.randomizeGenerator(auto: auto, with: pix, at: i) let expect = XCTestExpectation() try! PixelKit.main.render.engine.manuallyRender { guard let pixels = diffPix.renderedPixels else { XCTAssert(false, auto.name); expect.fulfill(); return } let avg = pixels.average.lum.cg XCTAssertEqual(avg, 0.0, auto.name) // if avg != 0.0 { // let diffUrl = folderUrl.appendingPathComponent("\(auto.name)_\(i)_diff.png") // guard let image: NSImage = diffPix.renderedImage else { fatalError() } // guard image.savePNG(to: diffUrl) else { fatalError() } // } expect.fulfill(); } wait(for: [expect], timeout: 1.0) } pix.destroy() imgPix.destroy() diffPix.destroy() } } func testCachedRandomSingleEffects() { setuUpManual() setUpTestPixs() guard let outputUrl = Files.outputUrl() else { XCTAssert(false); return } let folderUrl = outputUrl.appendingPathComponent("randomSingleEffects") for auto in AutoPIXSingleEffect.allCases { let pix = auto.pixType.init() pix.input = testPix let bgPix = .black & pix let imgPix = ImagePIX() let diffPix = bgPix % imgPix for i in 0..<Randomize.randomCount { let url = folderUrl.appendingPathComponent("\(auto.name)_\(i).png") guard let data = try? Data(contentsOf: url) else { XCTAssert(false, auto.name); continue } guard let img = NSImage(data: data) else { XCTAssert(false, auto.name); continue } imgPix.image = img Randomize.randomizeSingleEffect(auto: auto, with: pix, at: i) let expect = XCTestExpectation() try! PixelKit.main.render.engine.manuallyRender { guard let pixels = diffPix.renderedPixels else { XCTAssert(false, auto.name); expect.fulfill(); return } let avg = pixels.average.lum.cg XCTAssertEqual(avg, 0.0, auto.name) // if avg != 0.0 { // let diffUrl = folderUrl.appendingPathComponent("\(auto.name)_\(i)_diff.png") // guard let image: NSImage = diffPix.renderedImage else { fatalError() } // guard image.savePNG(to: diffUrl) else { fatalError() } // } expect.fulfill(); } wait(for: [expect], timeout: 1.0) } pix.destroy() imgPix.destroy() diffPix.destroy() } } func testCachedRandomMergerEffects() { setuUpManual() setUpTestPixs() guard let outputUrl = Files.outputUrl() else { XCTAssert(false); return } let folderUrl = outputUrl.appendingPathComponent("randomMergerEffects") for auto in AutoPIXMergerEffect.allCases { let pix = auto.pixType.init() pix.inputA = testPixA pix.inputB = testPixB let bgPix = .black & pix let imgPix = ImagePIX() let diffPix = bgPix % imgPix for i in 0..<Randomize.randomCount { let url = folderUrl.appendingPathComponent("\(auto.name)_\(i).png") guard let data = try? Data(contentsOf: url) else { XCTAssert(false, auto.name); continue } guard let img = NSImage(data: data) else { XCTAssert(false, auto.name); continue } imgPix.image = img Randomize.randomizeMergerEffect(auto: auto, with: pix, at: i) let expect = XCTestExpectation() try! PixelKit.main.render.engine.manuallyRender { guard let pixels = diffPix.renderedPixels else { XCTAssert(false, auto.name); expect.fulfill(); return } let avg = pixels.average.lum.cg XCTAssertEqual(avg, 0.0, auto.name) // if avg != 0.0 { // let diffUrl = folderUrl.appendingPathComponent("\(auto.name)_\(i)_diff.png") // guard let image: NSImage = diffPix.renderedImage else { fatalError() } // guard image.savePNG(to: diffUrl) else { fatalError() } // } expect.fulfill(); } wait(for: [expect], timeout: 1.0) } pix.destroy() imgPix.destroy() diffPix.destroy() } } func testImagePIX() { let imagePix = ImagePIX() imagePix.image = NSImage(named: "photo") let expect = XCTestExpectation() imagePix.nextTextureAvalible { expect.fulfill() } wait(for: [expect], timeout: 1.0) } }
37.76783
120
0.321949
cc90a5d9ade462d9ed99ec659ca3422b125093e5
1,491
import Foundation import UIKit import LocoViper2 /** The ___FILEBASENAMEASIDENTIFIER___ will <# description #> */ class ___FILEBASENAMEASIDENTIFIER___ { /// Name used to identify local notification daemon by. Should be equal to the UILocalNotification /// category string value. var category = "XXX" } // MARK: - LocalNotificationDaemonType extension ___FILEBASENAMEASIDENTIFIER___: LocalActionNotificationDaemonType { /** Daemon callback that gets fired when this local notification is received. - parameter userInfo: the userInfo attached to the location notification */ func handleNotification(userInfo: [String:AnyObject]?) { } /** OPTIONAL Will be called when the user taps a given identifier for the local notification - parameter identifier: the identifier of the button that they tapped - parameter userInfo: the userInfo attached to the location notification - parameter completionHandler: the completion handler to be called once the action has been completed */ func handleActionWithIdentifier(identifier: String?, userInfo: [String:AnyObject]?, completionHandler: () -> Void) { } } /** COPY PASTE INTO ASSEMBLY container.register(___FILEBASENAMEASIDENTIFIER___.self) { _ in return ___FILEBASENAMEASIDENTIFIER___() } COPY PASTE INTO ASSEMBLY LOAD App.sharedInstance.registerDaemon(resolver.resolve(___FILEBASENAMEASIDENTIFIER___.self)!) */
27.611111
120
0.733065
6a2b8d1cdbefda7c3a8c99c13218268c1737609c
789
// // Bolt.swift // SwiftUI-Animations // // Created by Shubham Singh on 24/10/20. // Copyright © 2020 Shubham Singh. All rights reserved. // import SwiftUI struct Bolt: Shape { func path(in rect: CGRect) -> Path { var path = Path() path.move(to: CGPoint(x: 211.67, y: 327.33)) path.addLine(to: CGPoint(x: 175, y: 371.33)) path.addLine(to: CGPoint(x: 208, y: 371.33)) path.addLine(to: CGPoint(x: 204.33, y: 400.67)) path.addLine(to: CGPoint(x: 241, y: 356.67)) path.addLine(to: CGPoint(x: 208, y: 356.67)) path.addLine(to: CGPoint(x: 211.67, y: 327.33)) return path } } struct Bolt_Previews: PreviewProvider { static var previews: some View { Bolt() } }
23.205882
56
0.565272
bbf6cc4ae1c84c52fdc0d255313ea072f7c83839
2,172
// // AppDelegate.swift // mtpng-example // // Created by Brion on 9/19/18. // Copyright © 2018 Brion Vibber. 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.212766
285
0.754604
dee77a0d631ef33007d1cf10dbb26c64c45dbbe3
16,241
// // UIViewExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/5/16. // Copyright © 2016 SwifterSwift // #if os(iOS) || os(tvOS) import UIKit // MARK: - enums /// SwifterSwift: Shake directions of a view. /// /// - horizontal: Shake left and right. /// - vertical: Shake up and down. public enum ShakeDirection { case horizontal case vertical } /// SwifterSwift: Angle units. /// /// - degrees: degrees. /// - radians: radians. public enum AngleUnit { case degrees case radians } /// SwifterSwift: Shake animations types. /// /// - linear: linear animation. /// - easeIn: easeIn animation /// - easeOut: easeOut animation. /// - easeInOut: easeInOut animation. public enum ShakeAnimationType { case linear case easeIn case easeOut case easeInOut } // MARK: - Properties public extension UIView { /// SwifterSwift: Border color of view; also inspectable from Storyboard. @IBInspectable public var borderColor: UIColor? { get { guard let color = layer.borderColor else { return nil } return UIColor(cgColor: color) } set { guard let color = newValue else { layer.borderColor = nil return } layer.borderColor = color.cgColor } } /// SwifterSwift: Border width of view; also inspectable from Storyboard. @IBInspectable public var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } /// SwifterSwift: Corner radius of view; also inspectable from Storyboard. @IBInspectable public var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.masksToBounds = true layer.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100) } } /// SwifterSwift: First responder. public var firstResponder: UIView? { guard !isFirstResponder else { return self } for subView in subviews where subView.isFirstResponder { return subView } return nil } // SwifterSwift: Height of view. public var height: CGFloat { get { return frame.size.height } set { frame.size.height = newValue } } /// SwifterSwift: Check if view is in RTL format. public var isRightToLeft: Bool { if #available(iOS 10.0, *, tvOS 10.0, *) { return effectiveUserInterfaceLayoutDirection == .rightToLeft } else { return false } } /// SwifterSwift: Take screenshot of view (if applicable). public var screenshot: UIImage? { UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { return nil } layer.render(in: context) return UIGraphicsGetImageFromCurrentImageContext() } /// SwifterSwift: Shadow color of view; also inspectable from Storyboard. @IBInspectable public var shadowColor: UIColor? { get { guard let color = layer.shadowColor else { return nil } return UIColor(cgColor: color) } set { layer.shadowColor = newValue?.cgColor } } /// SwifterSwift: Shadow offset of view; also inspectable from Storyboard. @IBInspectable public var shadowOffset: CGSize { get { return layer.shadowOffset } set { layer.shadowOffset = newValue } } /// SwifterSwift: Shadow opacity of view; also inspectable from Storyboard. @IBInspectable public var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } /// SwifterSwift: Shadow radius of view; also inspectable from Storyboard. @IBInspectable public var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } /// SwifterSwift: Size of view. public var size: CGSize { get { return frame.size } set { width = newValue.width height = newValue.height } } /// SwifterSwift: Get view's parent view controller public var parentViewController: UIViewController? { weak var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.next if let viewController = parentResponder as? UIViewController { return viewController } } return nil } /// SwifterSwift: Width of view. public var width: CGFloat { get { return frame.size.width } set { frame.size.width = newValue } } /// SwifterSwift: x origin of view. public var x: CGFloat { get { return frame.origin.x } set { frame.origin.x = newValue } } /// SwifterSwift: y origin of view. public var y: CGFloat { get { return frame.origin.y } set { frame.origin.y = newValue } } } // MARK: - Methods public extension UIView { /// SwifterSwift: Set some or all corners radiuses of view. /// /// - Parameters: /// - corners: array of corners to change (example: [.bottomLeft, .topRight]). /// - radius: radius for selected corners. public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) { let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let shape = CAShapeLayer() shape.path = maskPath.cgPath layer.mask = shape } /// SwifterSwift: Add shadow to view. /// /// - Parameters: /// - color: shadow color (default is #137992). /// - radius: shadow radius (default is 3). /// - offset: shadow offset (default is .zero). /// - opacity: shadow opacity (default is 0.5). public func addShadow(ofColor color: UIColor = UIColor(red: 0.07, green: 0.47, blue: 0.57, alpha: 1.0), radius: CGFloat = 3, offset: CGSize = .zero, opacity: Float = 0.5) { layer.shadowColor = color.cgColor layer.shadowOffset = offset layer.shadowRadius = radius layer.shadowOpacity = opacity layer.masksToBounds = true } /// SwifterSwift: Add array of subviews to view. /// /// - Parameter subviews: array of subviews to add to self. public func addSubviews(_ subviews: [UIView]) { subviews.forEach({self.addSubview($0)}) } /// SwifterSwift: Fade in view. /// /// - Parameters: /// - duration: animation duration in seconds (default is 1 second). /// - completion: optional completion handler to run with animation finishes (default is nil) public func fadeIn(duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) { if isHidden { isHidden = false } UIView.animate(withDuration: duration, animations: { self.alpha = 1 }, completion: completion) } /// SwifterSwift: Fade out view. /// /// - Parameters: /// - duration: animation duration in seconds (default is 1 second). /// - completion: optional completion handler to run with animation finishes (default is nil) public func fadeOut(duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) { if isHidden { isHidden = false } UIView.animate(withDuration: duration, animations: { self.alpha = 0 }, completion: completion) } /// SwifterSwift: Load view from nib. /// /// - Parameters: /// - name: nib name. /// - bundle: bundle of nib (default is nil). /// - Returns: optional UIView (if applicable). public class func loadFromNib(named name: String, bundle: Bundle? = nil) -> UIView? { return UINib(nibName: name, bundle: bundle).instantiate(withOwner: nil, options: nil)[0] as? UIView } /// SwifterSwift: Remove all subviews in view. public func removeSubviews() { subviews.forEach({$0.removeFromSuperview()}) } /// SwifterSwift: Remove all gesture recognizers from view. public func removeGestureRecognizers() { gestureRecognizers?.forEach(removeGestureRecognizer) } /// SwifterSwift: Rotate view by angle on relative axis. /// /// - Parameters: /// - angle: angle to rotate view by. /// - type: type of the rotation angle. /// - animated: set true to animate rotation (default is true). /// - duration: animation duration in seconds (default is 1 second). /// - completion: optional completion handler to run with animation finishes (default is nil). public func rotate(byAngle angle: CGFloat, ofType type: AngleUnit, animated: Bool = false, duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) { let angleWithType = (type == .degrees) ? CGFloat.pi * angle / 180.0 : angle let aDuration = animated ? duration : 0 UIView.animate(withDuration: aDuration, delay: 0, options: .curveLinear, animations: { () -> Void in self.transform = self.transform.rotated(by: angleWithType) }, completion: completion) } /// SwifterSwift: Rotate view to angle on fixed axis. /// /// - Parameters: /// - angle: angle to rotate view to. /// - type: type of the rotation angle. /// - animated: set true to animate rotation (default is false). /// - duration: animation duration in seconds (default is 1 second). /// - completion: optional completion handler to run with animation finishes (default is nil). public func rotate(toAngle angle: CGFloat, ofType type: AngleUnit, animated: Bool = false, duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) { let angleWithType = (type == .degrees) ? CGFloat.pi * angle / 180.0 : angle let aDuration = animated ? duration : 0 UIView.animate(withDuration: aDuration, animations: { self.transform = self.transform.concatenating(CGAffineTransform(rotationAngle: angleWithType)) }, completion: completion) } /// SwifterSwift: Scale view by offset. /// /// - Parameters: /// - offset: scale offset /// - animated: set true to animate scaling (default is false). /// - duration: animation duration in seconds (default is 1 second). /// - completion: optional completion handler to run with animation finishes (default is nil). public func scale(by offset: CGPoint, animated: Bool = false, duration: TimeInterval = 1, completion: ((Bool) -> Void)? = nil) { if animated { UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: { () -> Void in self.transform = self.transform.scaledBy(x: offset.x, y: offset.y) }, completion: completion) } else { transform = transform.scaledBy(x: offset.x, y: offset.y) completion?(true) } } /// SwifterSwift: Shake view. /// /// - Parameters: /// - direction: shake direction (horizontal or vertical), (default is .horizontal) /// - duration: animation duration in seconds (default is 1 second). /// - animationType: shake animation type (default is .easeOut). /// - completion: optional completion handler to run with animation finishes (default is nil). public func shake(direction: ShakeDirection = .horizontal, duration: TimeInterval = 1, animationType: ShakeAnimationType = .easeOut, completion:(() -> Void)? = nil) { CATransaction.begin() let animation: CAKeyframeAnimation switch direction { case .horizontal: animation = CAKeyframeAnimation(keyPath: "transform.translation.x") case .vertical: animation = CAKeyframeAnimation(keyPath: "transform.translation.y") } switch animationType { case .linear: animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) case .easeIn: animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) case .easeOut: animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) case .easeInOut: animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } CATransaction.setCompletionBlock(completion) animation.duration = duration animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ] layer.add(animation, forKey: "shake") CATransaction.commit() } /// SwifterSwift: Add Visual Format constraints. /// /// - Parameters: /// - withFormat: visual Format language /// - views: array of views which will be accessed starting with index 0 (example: [v0], [v1], [v2]..) @available(iOS 9, *) public func addConstraints(withFormat: String, views: UIView...) { // https://videos.letsbuildthatapp.com/ var viewsDictionary: [String: UIView] = [:] for (index, view) in views.enumerated() { let key = "v\(index)" view.translatesAutoresizingMaskIntoConstraints = false viewsDictionary[key] = view } addConstraints(NSLayoutConstraint.constraints(withVisualFormat: withFormat, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary)) } /// SwifterSwift: Anchor all sides of the view into it's superview. @available(iOS 9, *) public func fillToSuperview() { // https://videos.letsbuildthatapp.com/ translatesAutoresizingMaskIntoConstraints = false if let superview = superview { leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true topAnchor.constraint(equalTo: superview.topAnchor).isActive = true bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true } } /// SwifterSwift: Add anchors from any side of the current view into the specified anchors and returns the newly added constraints. /// /// - Parameters: /// - top: current view's top anchor will be anchored into the specified anchor /// - left: current view's left anchor will be anchored into the specified anchor /// - bottom: current view's bottom anchor will be anchored into the specified anchor /// - right: current view's right anchor will be anchored into the specified anchor /// - topConstant: current view's top anchor margin /// - leftConstant: current view's left anchor margin /// - bottomConstant: current view's bottom anchor margin /// - rightConstant: current view's right anchor margin /// - widthConstant: current view's width /// - heightConstant: current view's height /// - Returns: array of newly added constraints (if applicable). @available(iOS 9, *) @discardableResult public func anchor( top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] { // https://videos.letsbuildthatapp.com/ translatesAutoresizingMaskIntoConstraints = false var anchors = [NSLayoutConstraint]() if let top = top { anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant)) } if let left = left { anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant)) } if let bottom = bottom { anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant)) } if let right = right { anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant)) } if widthConstant > 0 { anchors.append(widthAnchor.constraint(equalToConstant: widthConstant)) } if heightConstant > 0 { anchors.append(heightAnchor.constraint(equalToConstant: heightConstant)) } anchors.forEach({$0.isActive = true}) return anchors } /// SwifterSwift: Anchor center X into current view's superview with a constant margin value. /// /// - Parameter constant: constant of the anchor constraint (default is 0). @available(iOS 9, *) public func anchorCenterXToSuperview(constant: CGFloat = 0) { // https://videos.letsbuildthatapp.com/ translatesAutoresizingMaskIntoConstraints = false if let anchor = superview?.centerXAnchor { centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true } } /// SwifterSwift: Anchor center Y into current view's superview with a constant margin value. /// /// - Parameter withConstant: constant of the anchor constraint (default is 0). @available(iOS 9, *) public func anchorCenterYToSuperview(constant: CGFloat = 0) { // https://videos.letsbuildthatapp.com/ translatesAutoresizingMaskIntoConstraints = false if let anchor = superview?.centerYAnchor { centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true } } /// SwifterSwift: Anchor center X and Y into current view's superview @available(iOS 9, *) public func anchorCenterSuperview() { // https://videos.letsbuildthatapp.com/ anchorCenterXToSuperview() anchorCenterYToSuperview() } } #endif
31.970472
173
0.703467
5650062d8c59f3a4958190dc7aa85e913a9e3313
1,667
// // TweetStatsCell.swift // Zirpen // // Created by Oscar Bonilla on 9/29/17. // Copyright © 2017 Oscar Bonilla. All rights reserved. // import UIKit class TweetStatsCell: UITableViewCell { @IBOutlet weak var likesLabel: UILabel! @IBOutlet weak var retweetsLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var clientLabel: UILabel! var tweet: Tweet! { didSet { if tweet.prettyLiked != nil { likesLabel.attributedText = tweet.prettyLiked! } else { likesLabel.text = String(format: "%d Likes", tweet.favouritesCount ?? 0) } if tweet.prettyRetweets != nil { retweetsLabel.attributedText = tweet.prettyRetweets! } else { retweetsLabel.text = String(format: "%d Retweets", tweet.retweetCount ?? 0) } let formatter = DateFormatter() formatter.dateFormat = "MMM d, y 'at' HH:MM" dateLabel.text = formatter.string(from: tweet.createdAt!) if tweet.prettySource != nil { clientLabel.attributedText = tweet.prettySource! } else if tweet.source != nil { clientLabel.text = "via " + tweet.source! } else { clientLabel.text = "via Unknown" } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
30.309091
91
0.577684
d7c74b39a7df55d24e887a9c6a854dd6d1ed7905
808
// // ListVideoTrialView.swift // RiMovie (iOS) // // Created by Ari Supriatna on 16/12/20. // import SwiftUI import AVKit struct ListVideoTrialView: View { var movie: MovieModel var body: some View { VStack(alignment: .leading) { Text("Trailers") .font(.title2) .fontWeight(.bold) .padding() ScrollView(.horizontal, showsIndicators: false) { HStack { ForEach(movie.videos) { item in VideoPlayer(player: AVPlayer(url: item.youtubeURL!)) .frame(width: 300, height: 200) .cornerRadius(10) } } .padding(.horizontal) } } } } struct ListVideoTrialView_Previews: PreviewProvider { static var previews: some View { ListVideoTrialView(movie: .stub) } }
19.238095
64
0.590347
1e19b82ca56ef4f944bf49ebf791dd0ecb3f6fc5
2,970
// // OpenRadarKeychain+Extension.swift // Ladybug // // Created by Ethanhuang on 2018/7/9. // Copyright © 2018年 Elaborapp Co., Ltd. All rights reserved. // import UIKit extension OpenRadarKeychain { static func presentSetupAlertController(on vc: UIViewController, completion: @escaping (_ success: Bool) -> Void) { DispatchQueue.main.async { let alertController = UIAlertController(title: "Open Radar API Key is Required".localized(), message: "Sign in Open Radar to...".localized(), preferredStyle: .alert) alertController.addTextField { (textField) in textField.placeholder = "Paste the API Key here".localized() } alertController.addAction(UIAlertAction(title: "Save".localized(), style: .default, handler: { (_) in if let apiKey = alertController.textFields?.first?.text, apiKey.isEmpty == false { completion(set(apiKey: apiKey)) } else { completion(false) } })) alertController.addAction(UIAlertAction(title: "Get My API Key".localized(), style: .default, handler: { (_) in let url = URL(string: "https://openradar.appspot.com/apikey")! UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: { (success) in if success { DispatchQueue.main.async { vc.present(alertController, animated: true) { } } } }) })) alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: { (_) in completion(false) })) vc.present(alertController, animated: true) { } } } static func presentRemoveKeyAlertContrller(on vc: UIViewController, completion: @escaping (_ success: Bool) -> Void) { DispatchQueue.main.async { let alertController = UIAlertController(title: "Remove Open Radar API Key".localized(), message: "", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Remove".localized(), style: .destructive, handler: { (_) in completion(deleteAPIKey()) })) alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: .cancel, handler: { (_) in completion(false) })) vc.present(alertController, animated: true) { } } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)}) }
46.40625
177
0.611785
e05d194811bc598e247d4a842df7bbc3c9ee76ba
319
// // FeatureFlags.swift // CV-MVVM-SwiftUI // // Created by parrilla nelson on 26/04/2020. // Copyright © 2020 Nelson Parrilla. All rights reserved. // import Foundation struct FeatureFlags { static var forceGetCV: Bool { return CommandLine.arguments.contains("--force_get_cv_response") } }
18.764706
72
0.68652
0869c9c3891b1f05f0d4a1e5373722a1d6b04c68
1,333
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Sift", platforms: [ .iOS(.v10) ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages.- .library( name: "Sift", targets: ["Sift"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "Sift-ObjC", dependencies: [], path: "Sift/objc", publicHeadersPath: nil, cSettings: [ .headerSearchPath("privateInclude") ] ), .target( name: "Sift", dependencies: ["Sift-ObjC"], path: "Sift/swift" ), .testTarget( name: "sift-iosTests", dependencies: ["Sift"]), ] )
31
118
0.554389
082dc9862e077acd88bcdaaf8a62fe623ff252a1
1,363
// // Codable.swift // Sluthware // // Created by Pat Sluth on 2017-10-08. // Copyright © 2017 patsluth. All rights reserved. // import Foundation public extension Decodable { static func decode(data: Data?) throws -> Self { guard let data = data else { throw Errors.Message("\(String(describing: Self.self)) \(#function) failed") } let decoder = JSONDecoder() return try decoder.decode(Self.self, from: data) } static func decode(string: String?) throws -> Self { guard let data = string?.removingPercentEncodingSafe.data(using: String.Encoding.utf8) else { throw Errors.Message("\(String(describing: Self.self)) \(#function) failed") } return try Self.decode(data: data) } static func decode<T>(jsonObject: T?) throws -> Self { guard let jsonObject = jsonObject else { throw Errors.Message("\(String(describing: Self.self)) \(#function) failed") } let data = try JSONSerialization.data(withJSONObject: jsonObject) return try self.decode(data: data) } static func decode<T>(_ jsonObjectType: T.Type, fileURL: URL) throws -> Self { guard let jsonObject = NSDictionary(contentsOf: fileURL) as? T else { throw Errors.Message("\(String(describing: Self.self)) \(#function) failed") } let data = try JSONSerialization.data(withJSONObject: jsonObject) return try self.decode(data: data) } }
23.912281
95
0.696258
71a0b0b15fe5029659ebee2e0ead6001c38d3736
834
// // BitMaskOption.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 7/22/15. // Copyright © 2015 PureSwift. // /// Bit mask that represents various options. public protocol BitMaskOption: RawRepresentable { static func bitmask(options: [Self]) -> Self.RawValue } public extension BitMaskOption where Self.RawValue: BinaryInteger { static func bitmask<S: Sequence>(options: S) -> Self.RawValue where S.Iterator.Element == Self { return options.reduce(0) { mask, option in mask | option.rawValue } } } public extension Sequence where Self.Iterator.Element: BitMaskOption, Self.Iterator.Element.RawValue: BinaryInteger { func optionsBitmask() -> Self.Iterator.Element.RawValue { let array = filter { (_) -> Bool in true } return Self.Iterator.Element.bitmask(options: array) } }
28.758621
117
0.719424
206f63617a48782d8b111cf804ede223e6cd5ff4
2,860
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit protocol ExperimentsListCellDelegate: class { /// Tells the delegate the user tapped the menu button for a cell. func menuButtonPressedForCell(_ cell: ExperimentsListCell, attachmentButton: UIButton) } /// A cell displaying the photo, title and menu for an experiment that has been synced to an /// account. It also displays a menu button. class ExperimentsListCell: ExperimentsListCellBase { // MARK: - Properties private weak var delegate: ExperimentsListCellDelegate? private let menuButton = MenuButton() // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } /// Configures a cell for a given experiment overview and background color. /// /// - Parameters: /// - experimentOverview: The experiment overview to use for configuring the title. /// - delegate: The delegate for this cell. /// - image: The image for this experiment or nil. func configureForExperimentOverview(_ experimentOverview: ExperimentOverview, delegate: ExperimentsListCellDelegate, image: UIImage?) { self.delegate = delegate configureForExperimentOverview(experimentOverview, image: image) } /// The item size for the cell in a width. /// /// Parameter width: The width of the item. /// Returns: The size for the item. static func itemSize(inWidth width: CGFloat) -> CGSize { // The item should be 10% taller than its width. return CGSize(width: width, height: width * 1.1) } // MARK: - Private private func configureView() { // Menu button. titleStack.addArrangedSubview(menuButton) menuButton.tintColor = ArduinoColorPalette.grayPalette.tint500 menuButton.hitAreaInsets = UIEdgeInsets(top: -30, left: -30, bottom: -10, right: -10) menuButton.addTarget(self, action: #selector(menuButtonPressed), for: .touchUpInside) menuButton.isAccessibilityElement = true } // MARK: - User actions @objc private func menuButtonPressed() { delegate?.menuButtonPressedForCell(self, attachmentButton: menuButton) } }
33.647059
92
0.704895
1c751be365527655984b9b48695245b369d05a14
3,338
// // Corona-Warn-App // // SAP SE and all other contributors // copyright owners license this file to you under the Apache // License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Foundation import UIKit extension DynamicCell { static func phone(text: String, number: String, accessibilityIdentifier: String? = nil) -> Self { var cell: DynamicCell = .icon(UIImage(systemName: "phone"), text: .string(text), tintColor: .enaColor(for: .textPrimary1), selectionStyle: .default, action: .call(number: number)) { _, cell, _ in cell.textLabel?.textColor = .enaColor(for: .textTint) (cell.textLabel as? ENALabel)?.style = .title2 cell.isAccessibilityElement = true cell.accessibilityIdentifier = accessibilityIdentifier cell.accessibilityLabel = "\(AppStrings.AccessibilityLabel.phoneNumber):\n\n\(text)" cell.accessibilityTraits = .button cell.accessibilityCustomActions?.removeAll() let actionName = "\(AppStrings.ExposureSubmissionHotline.callButtonTitle) \(AppStrings.AccessibilityLabel.phoneNumber)" cell.accessibilityCustomActions = [ UIAccessibilityCustomAction(name: actionName, actionHandler: { _ -> Bool in if let url = URL(string: "telprompt:\(AppStrings.ExposureSubmission.hotlineNumber)"), UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } return true }) ] } cell.tag = "phone" return cell } static func imprintHeadlineWithoutBottomInset(text: String, accessibilityIdentifier: String? = nil) -> Self { .headline(text: text, accessibilityIdentifier: accessibilityIdentifier) { _, cell, _ in cell.contentView.preservesSuperviewLayoutMargins = false cell.contentView.layoutMargins.bottom = 0 cell.accessibilityIdentifier = accessibilityIdentifier cell.accessibilityTraits = .header } } static func bodyWithoutTopInset(text: String, style: TextCellStyle = .label, accessibilityIdentifier: String? = nil) -> Self { .body(text: text, style: style, accessibilityIdentifier: accessibilityIdentifier) { _, cell, _ in cell.contentView.preservesSuperviewLayoutMargins = false cell.contentView.layoutMargins.top = 0 cell.accessibilityIdentifier = accessibilityIdentifier } } /// Creates a cell that renders a view of a .html file with interactive texts, such as mail links, phone numbers, and web addresses. static func html(url: URL?) -> Self { .identifier(AppInformationDetailViewController.CellReuseIdentifier.html) { viewController, cell, _ in guard let cell = cell as? DynamicTableViewHtmlCell else { return } cell.textView.delegate = viewController as? UITextViewDelegate cell.textView.isUserInteractionEnabled = true cell.textView.dataDetectorTypes = [.link, .phoneNumber] if let url = url { cell.textView.load(from: url) } } } }
40.707317
197
0.74296
16205cd5e8276c690be284a510c05fecc4c230d8
781
// // AppDelegate.swift // Stylight Technical Task // // Created by Ahmad Atef on 7/17/17. // Copyright © 2017 Ahmad Atef. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { monitorInternetConnectivity() return true } func monitorInternetConnectivity() { InternetChecker.shared.checkForInternet { (result) in if result != .REACHABLEVIAWIFI{ UIDecorator.shared.showMessage(title: "Warning",body: result.rawValue,alertType: .warning) } } } }
23.666667
144
0.669654
16a457e7c140b4626dfd69fcf59ddeee90d4e365
1,551
// // ExposureDetections.swift // BT-Tracking // // Created by Lukáš Foldýna on 15/10/2020. // Copyright © 2020 Covid19CZ. All rights reserved. // import Foundation import RealmSwift import RxSwift import RxRealm final class ExposureList { static var exposures: Results<ExposureRealm> { let realm = AppDelegate.dependency.realm return realm.objects(ExposureRealm.self).sorted(byKeyPath: "date") } static var last: Exposure? { let exposures = self.exposures let showForDays = RemoteValues.serverConfiguration.showExposureForDays let showForDate = Calendar.current.date(byAdding: .day, value: -showForDays, to: Date()) ?? Date() return exposures.last(where: { $0.date > showForDate })?.toExposure() } static func lastObservable() throws -> Observable<Exposure?> { let exposures = self.exposures let showForDays = RemoteValues.serverConfiguration.showExposureForDays let showForDate = Calendar.current.date(byAdding: .day, value: -showForDays, to: Date()) ?? Date() return Observable.collection(from: exposures).map { $0.last(where: { $0.date > showForDate })?.toExposure() } } static func add(_ exposures: [Exposure], detectionDate: Date) throws { guard !exposures.isEmpty else { return } let realm = AppDelegate.dependency.realm try realm.write { exposures.sorted { $0.date < $1.date }.forEach { realm.add(ExposureRealm($0, detectedDate: detectionDate)) } } } }
31.653061
120
0.667311
f77524c1cfb0d4e04e582d4567006a7317e9662e
28,984
// // MainWindowController.swift // NetNewsWire // // Created by Brent Simmons on 8/1/15. // Copyright © 2015 Ranchero Software, LLC. All rights reserved. // import AppKit import UserNotifications import Articles import Account import RSCore enum TimelineSourceMode { case regular, search } class MainWindowController : NSWindowController, NSUserInterfaceValidations { private var activityManager = ActivityManager() private var isShowingExtractedArticle = false private var articleExtractor: ArticleExtractor? = nil private var sharingServicePickerDelegate: NSSharingServicePickerDelegate? private let windowAutosaveName = NSWindow.FrameAutosaveName("MainWindow") static var didPositionWindowOnFirstRun = false private var currentFeedOrFolder: AnyObject? { // Nil for none or multiple selection. guard let selectedObjects = selectedObjectsInSidebar(), selectedObjects.count == 1 else { return nil } return selectedObjects.first } private var shareToolbarItem: NSToolbarItem? { return window?.toolbar?.existingItem(withIdentifier: .Share) } private static var detailViewMinimumThickness = 384 private var sidebarViewController: SidebarViewController? private var timelineContainerViewController: TimelineContainerViewController? private var detailViewController: DetailViewController? private var currentSearchField: NSSearchField? = nil private var searchString: String? = nil private var lastSentSearchString: String? = nil private var timelineSourceMode: TimelineSourceMode = .regular { didSet { timelineContainerViewController?.showTimeline(for: timelineSourceMode) detailViewController?.showDetail(for: timelineSourceMode) } } private var searchSmartFeed: SmartFeed? = nil // MARK: - NSWindowController override func windowDidLoad() { super.windowDidLoad() sharingServicePickerDelegate = SharingServicePickerDelegate(self.window) if !AppDefaults.showTitleOnMainWindow { window?.titleVisibility = .hidden } window?.setFrameUsingName(windowAutosaveName, force: true) if AppDefaults.isFirstRun && !MainWindowController.didPositionWindowOnFirstRun { if let window = window { let point = NSPoint(x: 128, y: 64) let size = NSSize(width: 1000, height: 700) let minSize = NSSize(width: 600, height: 600) window.setPointAndSizeAdjustingForScreen(point: point, size: size, minimumSize: minSize) MainWindowController.didPositionWindowOnFirstRun = true } } detailSplitViewItem?.minimumThickness = CGFloat(MainWindowController.detailViewMinimumThickness) restoreSplitViewState() NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate(_:)), name: NSApplication.willTerminateNotification, object: nil) sidebarViewController = splitViewController?.splitViewItems[0].viewController as? SidebarViewController sidebarViewController!.delegate = self timelineContainerViewController = splitViewController?.splitViewItems[1].viewController as? TimelineContainerViewController timelineContainerViewController!.delegate = self detailViewController = splitViewController?.splitViewItems[2].viewController as? DetailViewController NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshDidBegin, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshDidFinish, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshProgressDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil) DispatchQueue.main.async { self.updateWindowTitle() } } // MARK: - API func saveState() { saveSplitViewState() } func selectedObjectsInSidebar() -> [AnyObject]? { return sidebarViewController?.selectedObjects } func handle(_ response: UNNotificationResponse) { let userInfo = response.notification.request.content.userInfo guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable : Any] else { return } sidebarViewController?.deepLinkRevealAndSelect(for: articlePathUserInfo) currentTimelineViewController?.goToDeepLink(for: articlePathUserInfo) } func handle(_ activity: NSUserActivity) { guard let userInfo = activity.userInfo else { return } guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable : Any] else { return } sidebarViewController?.deepLinkRevealAndSelect(for: articlePathUserInfo) currentTimelineViewController?.goToDeepLink(for: articlePathUserInfo) } // MARK: - Notifications // func window(_ window: NSWindow, willEncodeRestorableState state: NSCoder) { // // saveSplitViewState(to: state) // } // // func window(_ window: NSWindow, didDecodeRestorableState state: NSCoder) { // // restoreSplitViewState(from: state) // // // Make sure the timeline view is first responder if possible, to start out viewing // // whatever preserved selection might have been restored // makeTimelineViewFirstResponder() // } @objc func applicationWillTerminate(_ note: Notification) { saveState() window?.saveFrame(usingName: windowAutosaveName) } @objc func refreshProgressDidChange(_ note: Notification) { CoalescingQueue.standard.add(self, #selector(makeToolbarValidate)) } @objc func unreadCountDidChange(_ note: Notification) { updateWindowTitleIfNecessary(note.object) } @objc func displayNameDidChange(_ note: Notification) { updateWindowTitleIfNecessary(note.object) } private func updateWindowTitleIfNecessary(_ noteObject: Any?) { if let folder = currentFeedOrFolder as? Folder, let noteObject = noteObject as? Folder { if folder == noteObject { updateWindowTitle() return } } if let feed = currentFeedOrFolder as? WebFeed, let noteObject = noteObject as? WebFeed { if feed == noteObject { updateWindowTitle() return } } // If we don't recognize the changed object, we will test it for identity instead // of equality. This works well for us if the window title is displaying a // PsuedoFeed object. if let currentObject = currentFeedOrFolder, let noteObject = noteObject { if currentObject === noteObject as AnyObject { updateWindowTitle() } } } // MARK: - Toolbar @objc func makeToolbarValidate() { window?.toolbar?.validateVisibleItems() } // MARK: - NSUserInterfaceValidations public func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { if item.action == #selector(openArticleInBrowser(_:)) { return currentLink != nil } if item.action == #selector(nextUnread(_:)) { return canGoToNextUnread() } if item.action == #selector(markAllAsRead(_:)) { return canMarkAllAsRead() } if item.action == #selector(toggleRead(_:)) { return validateToggleRead(item) } if item.action == #selector(toggleStarred(_:)) { return validateToggleStarred(item) } if item.action == #selector(markOlderArticlesAsRead(_:)) { return canMarkOlderArticlesAsRead() } if item.action == #selector(toggleArticleExtractor(_:)) { return validateToggleArticleExtractor(item) } if item.action == #selector(toolbarShowShareMenu(_:)) { return canShowShareMenu() } if item.action == #selector(moveFocusToSearchField(_:)) { return currentSearchField != nil } if item.action == #selector(toggleReadFeedsFilter(_:)) { return validateToggleReadFeeds(item) } if item.action == #selector(toggleReadArticlesFilter(_:)) { return validateToggleReadArticles(item) } if item.action == #selector(toggleSidebar(_:)) { guard let splitViewItem = sidebarSplitViewItem else { return false } let sidebarIsShowing = !splitViewItem.isCollapsed if let menuItem = item as? NSMenuItem { let title = sidebarIsShowing ? NSLocalizedString("Hide Sidebar", comment: "Menu item") : NSLocalizedString("Show Sidebar", comment: "Menu item") menuItem.title = title } return true } return true } // MARK: - Actions @IBAction func scrollOrGoToNextUnread(_ sender: Any?) { guard let detailViewController = detailViewController else { return } detailViewController.canScrollDown { (canScroll) in NSCursor.setHiddenUntilMouseMoves(true) canScroll ? detailViewController.scrollPageDown(sender) : self.nextUnread(sender) } } @IBAction func openArticleInBrowser(_ sender: Any?) { if let link = currentLink { Browser.open(link) } } @IBAction func openInBrowser(_ sender: Any?) { openArticleInBrowser(sender) } @IBAction func nextUnread(_ sender: Any?) { guard let timelineViewController = currentTimelineViewController, let sidebarViewController = sidebarViewController else { return } NSCursor.setHiddenUntilMouseMoves(true) // TODO: handle search mode if timelineViewController.canGoToNextUnread() { goToNextUnreadInTimeline() } else if sidebarViewController.canGoToNextUnread() { sidebarViewController.goToNextUnread() if timelineViewController.canGoToNextUnread() { goToNextUnreadInTimeline() } } } @IBAction func markAllAsRead(_ sender: Any?) { currentTimelineViewController?.markAllAsRead() } @IBAction func toggleRead(_ sender: Any?) { currentTimelineViewController?.toggleReadStatusForSelectedArticles() } @IBAction func markRead(_ sender: Any?) { currentTimelineViewController?.markSelectedArticlesAsRead(sender) } @IBAction func markUnread(_ sender: Any?) { currentTimelineViewController?.markSelectedArticlesAsUnread(sender) } @IBAction func toggleStarred(_ sender: Any?) { currentTimelineViewController?.toggleStarredStatusForSelectedArticles() } @IBAction func toggleArticleExtractor(_ sender: Any?) { guard let currentLink = currentLink, let article = oneSelectedArticle else { return } defer { makeToolbarValidate() } if articleExtractor?.state == .failedToParse { startArticleExtractorForCurrentLink() return } guard articleExtractor?.state != .processing else { articleExtractor?.cancel() articleExtractor = nil isShowingExtractedArticle = false detailViewController?.setState(DetailState.article(article), mode: timelineSourceMode) return } guard !isShowingExtractedArticle else { isShowingExtractedArticle = false detailViewController?.setState(DetailState.article(article), mode: timelineSourceMode) return } if let articleExtractor = articleExtractor, let extractedArticle = articleExtractor.article { if currentLink == articleExtractor.articleLink { isShowingExtractedArticle = true let detailState = DetailState.extracted(article, extractedArticle) detailViewController?.setState(detailState, mode: timelineSourceMode) } } else { startArticleExtractorForCurrentLink() } } @IBAction func markAllAsReadAndGoToNextUnread(_ sender: Any?) { markAllAsRead(sender) nextUnread(sender) } @IBAction func markUnreadAndGoToNextUnread(_ sender: Any?) { markUnread(sender) nextUnread(sender) } @IBAction func markReadAndGoToNextUnread(_ sender: Any?) { markUnread(sender) nextUnread(sender) } @IBAction func toggleSidebar(_ sender: Any?) { splitViewController!.toggleSidebar(sender) } @IBAction func markOlderArticlesAsRead(_ sender: Any?) { currentTimelineViewController?.markOlderArticlesRead() } @IBAction func navigateToTimeline(_ sender: Any?) { currentTimelineViewController?.focus() } @IBAction func navigateToSidebar(_ sender: Any?) { sidebarViewController?.focus() } @IBAction func navigateToDetail(_ sender: Any?) { detailViewController?.focus() } @IBAction func goToPreviousSubscription(_ sender: Any?) { sidebarViewController?.outlineView.selectPreviousRow(sender) } @IBAction func goToNextSubscription(_ sender: Any?) { sidebarViewController?.outlineView.selectNextRow(sender) } @IBAction func gotoToday(_ sender: Any?) { sidebarViewController?.gotoToday(sender) } @IBAction func gotoAllUnread(_ sender: Any?) { sidebarViewController?.gotoAllUnread(sender) } @IBAction func gotoStarred(_ sender: Any?) { sidebarViewController?.gotoStarred(sender) } @IBAction func toolbarShowShareMenu(_ sender: Any?) { guard let selectedArticles = selectedArticles, !selectedArticles.isEmpty else { assertionFailure("Expected toolbarShowShareMenu to be called only when there are selected articles.") return } guard let shareToolbarItem = shareToolbarItem else { assertionFailure("Expected toolbarShowShareMenu to be called only by the Share item in the toolbar.") return } guard let view = shareToolbarItem.view else { // TODO: handle menu form representation return } let sortedArticles = selectedArticles.sortedByDate(.orderedAscending) let items = sortedArticles.map { ArticlePasteboardWriter(article: $0) } let sharingServicePicker = NSSharingServicePicker(items: items) sharingServicePicker.delegate = sharingServicePickerDelegate sharingServicePicker.show(relativeTo: view.bounds, of: view, preferredEdge: .minY) } @IBAction func moveFocusToSearchField(_ sender: Any?) { guard let searchField = currentSearchField else { return } window?.makeFirstResponder(searchField) } @IBAction func toggleReadFeedsFilter(_ sender: Any?) { sidebarViewController?.toggleReadFilter() } @IBAction func toggleReadArticlesFilter(_ sender: Any?) { timelineContainerViewController?.toggleReadFilter() } } // MARK: - SidebarDelegate extension MainWindowController: SidebarDelegate { func sidebarSelectionDidChange(_: SidebarViewController, selectedObjects: [AnyObject]?) { // Don’t update the timeline if it already has those objects. let representedObjectsAreTheSame = timelineContainerViewController?.regularTimelineViewControllerHasRepresentedObjects(selectedObjects) ?? false if !representedObjectsAreTheSame { timelineContainerViewController?.setRepresentedObjects(selectedObjects, mode: .regular) forceSearchToEnd() } updateWindowTitle() NotificationCenter.default.post(name: .InspectableObjectsDidChange, object: nil) } func unreadCount(for representedObject: AnyObject) -> Int { guard let timelineViewController = regularTimelineViewController else { return 0 } guard timelineViewController.representsThisObjectOnly(representedObject) else { return 0 } return timelineViewController.unreadCount } } // MARK: - TimelineContainerViewControllerDelegate extension MainWindowController: TimelineContainerViewControllerDelegate { func timelineSelectionDidChange(_: TimelineContainerViewController, articles: [Article]?, mode: TimelineSourceMode) { activityManager.invalidateReading() articleExtractor?.cancel() articleExtractor = nil isShowingExtractedArticle = false makeToolbarValidate() let detailState: DetailState if let articles = articles { if articles.count == 1 { activityManager.reading(feed: nil, article: articles.first) if articles.first?.webFeed?.isArticleExtractorAlwaysOn ?? false { detailState = .loading startArticleExtractorForCurrentLink() } else { detailState = .article(articles.first!) } } else { detailState = .multipleSelection } } else { detailState = .noSelection } detailViewController?.setState(detailState, mode: mode) } } // MARK: - NSSearchFieldDelegate extension MainWindowController: NSSearchFieldDelegate { func searchFieldDidStartSearching(_ sender: NSSearchField) { startSearchingIfNeeded() } func searchFieldDidEndSearching(_ sender: NSSearchField) { stopSearchingIfNeeded() } @IBAction func runSearch(_ sender: NSSearchField) { if sender.stringValue == "" { return } startSearchingIfNeeded() handleSearchFieldTextChange(sender) } private func handleSearchFieldTextChange(_ searchField: NSSearchField) { let s = searchField.stringValue if s == searchString { return } searchString = s updateSmartFeed() } func updateSmartFeed() { guard timelineSourceMode == .search, let searchString = searchString else { return } if searchString == lastSentSearchString { return } lastSentSearchString = searchString let smartFeed = SmartFeed(delegate: SearchFeedDelegate(searchString: searchString)) timelineContainerViewController?.setRepresentedObjects([smartFeed], mode: .search) searchSmartFeed = smartFeed } func forceSearchToEnd() { timelineSourceMode = .regular searchString = nil lastSentSearchString = nil if let searchField = currentSearchField { searchField.stringValue = "" } } private func startSearchingIfNeeded() { timelineSourceMode = .search } private func stopSearchingIfNeeded() { searchString = nil lastSentSearchString = nil timelineSourceMode = .regular timelineContainerViewController?.setRepresentedObjects(nil, mode: .search) } } // MARK: - ArticleExtractorDelegate extension MainWindowController: ArticleExtractorDelegate { func articleExtractionDidFail(with: Error) { makeToolbarValidate() } func articleExtractionDidComplete(extractedArticle: ExtractedArticle) { if let article = oneSelectedArticle, articleExtractor?.state != .cancelled { isShowingExtractedArticle = true let detailState = DetailState.extracted(article, extractedArticle) detailViewController?.setState(detailState, mode: timelineSourceMode) makeToolbarValidate() } } } // MARK: - Scripting Access /* the ScriptingMainWindowController protocol exposes a narrow set of accessors with internal visibility which are very similar to some private vars. These would be unnecessary if the similar accessors were marked internal rather than private, but for now, we'll keep the stratification of visibility */ extension MainWindowController : ScriptingMainWindowController { internal var scriptingCurrentArticle: Article? { return self.oneSelectedArticle } internal var scriptingSelectedArticles: [Article] { return self.selectedArticles ?? [] } } // MARK: - NSToolbarDelegate extension NSToolbarItem.Identifier { static let Share = NSToolbarItem.Identifier("share") static let Search = NSToolbarItem.Identifier("search") } extension MainWindowController: NSToolbarDelegate { func toolbarWillAddItem(_ notification: Notification) { guard let item = notification.userInfo?["item"] as? NSToolbarItem else { return } if item.itemIdentifier == .Share, let button = item.view as? NSButton { // The share button should send its action on mouse down, not mouse up. button.sendAction(on: .leftMouseDown) } if item.itemIdentifier == .Search, let searchField = item.view as? NSSearchField { searchField.delegate = self searchField.target = self searchField.action = #selector(runSearch(_:)) currentSearchField = searchField } } func toolbarDidRemoveItem(_ notification: Notification) { guard let item = notification.userInfo?["item"] as? NSToolbarItem else { return } if item.itemIdentifier == .Search, let searchField = item.view as? NSSearchField { searchField.delegate = nil searchField.target = nil searchField.action = nil currentSearchField = nil } } } // MARK: - Private private extension MainWindowController { var splitViewController: NSSplitViewController? { guard let viewController = contentViewController else { return nil } return viewController.children.first as? NSSplitViewController } var currentTimelineViewController: TimelineViewController? { return timelineContainerViewController?.currentTimelineViewController } var regularTimelineViewController: TimelineViewController? { return timelineContainerViewController?.regularTimelineViewController } var sidebarSplitViewItem: NSSplitViewItem? { return splitViewController?.splitViewItems[0] } var detailSplitViewItem: NSSplitViewItem? { return splitViewController?.splitViewItems[2] } var selectedArticles: [Article]? { return currentTimelineViewController?.selectedArticles } var oneSelectedArticle: Article? { if let articles = selectedArticles { return articles.count == 1 ? articles[0] : nil } return nil } var currentLink: String? { return oneSelectedArticle?.preferredLink } // MARK: - Command Validation func canGoToNextUnread() -> Bool { guard let timelineViewController = currentTimelineViewController, let sidebarViewController = sidebarViewController else { return false } // TODO: handle search mode return timelineViewController.canGoToNextUnread() || sidebarViewController.canGoToNextUnread() } func canMarkAllAsRead() -> Bool { return currentTimelineViewController?.canMarkAllAsRead() ?? false } func validateToggleRead(_ item: NSValidatedUserInterfaceItem) -> Bool { let validationStatus = currentTimelineViewController?.markReadCommandStatus() ?? .canDoNothing let markingRead: Bool let result: Bool switch validationStatus { case .canMark: markingRead = true result = true case .canUnmark: markingRead = false result = true case .canDoNothing: markingRead = true result = false } let commandName = markingRead ? NSLocalizedString("Mark as Read", comment: "Command") : NSLocalizedString("Mark as Unread", comment: "Command") if let toolbarItem = item as? NSToolbarItem { toolbarItem.toolTip = commandName } if let menuItem = item as? NSMenuItem { menuItem.title = commandName } return result } func validateToggleArticleExtractor(_ item: NSValidatedUserInterfaceItem) -> Bool { guard let toolbarItem = item as? NSToolbarItem, let toolbarButton = toolbarItem.view as? ArticleExtractorButton else { if let menuItem = item as? NSMenuItem { menuItem.state = isShowingExtractedArticle ? .on : .off } return currentLink != nil } toolbarButton.state = isShowingExtractedArticle ? .on : .off guard let state = articleExtractor?.state else { toolbarButton.isError = false toolbarButton.isInProgress = false toolbarButton.state = .off return currentLink != nil } switch state { case .processing: toolbarButton.isError = false toolbarButton.isInProgress = true case .failedToParse: toolbarButton.isError = true toolbarButton.isInProgress = false case .ready, .cancelled, .complete: toolbarButton.isError = false toolbarButton.isInProgress = false } return true } func canMarkOlderArticlesAsRead() -> Bool { return currentTimelineViewController?.canMarkOlderArticlesAsRead() ?? false } func canShowShareMenu() -> Bool { guard let selectedArticles = selectedArticles else { return false } return !selectedArticles.isEmpty } func validateToggleStarred(_ item: NSValidatedUserInterfaceItem) -> Bool { let validationStatus = currentTimelineViewController?.markStarredCommandStatus() ?? .canDoNothing let starring: Bool let result: Bool switch validationStatus { case .canMark: starring = true result = true case .canUnmark: starring = false result = true case .canDoNothing: starring = true result = false } let commandName = starring ? NSLocalizedString("Mark as Starred", comment: "Command") : NSLocalizedString("Mark as Unstarred", comment: "Command") if let toolbarItem = item as? NSToolbarItem { toolbarItem.toolTip = commandName // if let button = toolbarItem.view as? NSButton { // button.image = NSImage(named: starring ? .star : .unstar) // } } if let menuItem = item as? NSMenuItem { menuItem.title = commandName } return result } func validateToggleReadFeeds(_ item: NSValidatedUserInterfaceItem) -> Bool { guard let menuItem = item as? NSMenuItem else { return false } let showCommand = NSLocalizedString("Show Read Feeds", comment: "Command") let hideCommand = NSLocalizedString("Hide Read Feeds", comment: "Command") menuItem.title = sidebarViewController?.isReadFiltered ?? false ? showCommand : hideCommand return true } func validateToggleReadArticles(_ item: NSValidatedUserInterfaceItem) -> Bool { guard let menuItem = item as? NSMenuItem else { return false } let showCommand = NSLocalizedString("Show Read Articles", comment: "Command") let hideCommand = NSLocalizedString("Hide Read Articles", comment: "Command") if let isReadFiltered = timelineContainerViewController?.isReadFiltered { menuItem.title = isReadFiltered ? showCommand : hideCommand return true } else { menuItem.title = hideCommand return false } } // MARK: - Misc. func goToNextUnreadInTimeline() { guard let timelineViewController = currentTimelineViewController else { return } if timelineViewController.canGoToNextUnread() { timelineViewController.goToNextUnread() makeTimelineViewFirstResponder() } } func makeTimelineViewFirstResponder() { guard let window = window, let timelineViewController = currentTimelineViewController else { return } window.makeFirstResponderUnlessDescendantIsFirstResponder(timelineViewController.tableView) } func updateWindowTitle() { var displayName: String? = nil var unreadCount: Int? = nil if let displayNameProvider = currentFeedOrFolder as? DisplayNameProvider { displayName = displayNameProvider.nameForDisplay } if let unreadCountProvider = currentFeedOrFolder as? UnreadCountProvider { unreadCount = unreadCountProvider.unreadCount } if displayName != nil { if unreadCount ?? 0 > 0 { window?.title = "\(displayName!) (\(unreadCount!))" } else { window?.title = "\(displayName!)" } } else { window?.title = appDelegate.appName! return } } func startArticleExtractorForCurrentLink() { if let link = currentLink, let extractor = ArticleExtractor(link) { extractor.delegate = self extractor.process() articleExtractor = extractor } } func saveSplitViewState() { // TODO: Update this for multiple windows. // Also: use standard state restoration mechanism. guard let splitView = splitViewController?.splitView else { return } let widths = splitView.arrangedSubviews.map{ Int(floor($0.frame.width)) } if AppDefaults.mainWindowWidths != widths { AppDefaults.mainWindowWidths = widths } } func restoreSplitViewState() { // TODO: Update this for multiple windows. // Also: use standard state restoration mechanism. guard let splitView = splitViewController?.splitView, let widths = AppDefaults.mainWindowWidths, widths.count == 3, let window = window else { return } let windowWidth = Int(floor(window.frame.width)) let dividerThickness: Int = Int(splitView.dividerThickness) let sidebarWidth: Int = widths[0] let timelineWidth: Int = widths[1] // Make sure the detail view has its mimimum thickness, at least. if windowWidth < sidebarWidth + dividerThickness + timelineWidth + dividerThickness + MainWindowController.detailViewMinimumThickness { return } splitView.setPosition(CGFloat(sidebarWidth), ofDividerAt: 0) splitView.setPosition(CGFloat(sidebarWidth + dividerThickness + timelineWidth), ofDividerAt: 1) } // func saveSplitViewState(to coder: NSCoder) { // // // TODO: Update this for multiple windows. // // guard let splitView = splitViewController?.splitView else { // return // } // // let widths = splitView.arrangedSubviews.map{ Int(floor($0.frame.width)) } // coder.encode(widths, forKey: MainWindowController.mainWindowWidthsStateKey) // // } // func arrayOfIntFromCoder(_ coder: NSCoder, withKey: String) -> [Int]? { // let decodedFloats: [Int]? // do { // decodedFloats = try coder.decodeTopLevelObject(forKey: MainWindowController.mainWindowWidthsStateKey) as? [Int]? ?? nil // } // catch { // decodedFloats = nil // } // return decodedFloats // } // func restoreSplitViewState(from coder: NSCoder) { // // // TODO: Update this for multiple windows. // guard let splitView = splitViewController?.splitView, let widths = arrayOfIntFromCoder(coder, withKey: MainWindowController.mainWindowWidthsStateKey), widths.count == 3, let window = window else { // return // } // // let windowWidth = Int(floor(window.frame.width)) // let dividerThickness: Int = Int(splitView.dividerThickness) // let sidebarWidth: Int = widths[0] // let timelineWidth: Int = widths[1] // // // Make sure the detail view has its mimimum thickness, at least. // if windowWidth < sidebarWidth + dividerThickness + timelineWidth + dividerThickness + MainWindowController.detailViewMinimumThickness { // return // } // // splitView.setPosition(CGFloat(sidebarWidth), ofDividerAt: 0) // splitView.setPosition(CGFloat(sidebarWidth + dividerThickness + timelineWidth), ofDividerAt: 1) // } }
29.247225
200
0.753623
1d44cd7eab90f1d14862ba3befbd27ce11aa630c
4,267
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import Foundation import Amplify import AmplifyPlugins class FlutterApiRequest { // ====== SHARED ====== static func getMap(args: Any) throws -> [String: Any] { guard let res = args as? [String: Any] else { throw APIError.invalidConfiguration("The FlutterMethodCall argument was not passed as a dictionary", "The request should include the FlutterMethodCall argument as a [String: Any] dictionary") } return res } static func getCancelToken(args: Any) throws -> String { guard let cancelToken = args as? String else { throw APIError.invalidConfiguration("The cancelToken request argument was not passed as a String", "The request should include the cancelToken document as a String") } return cancelToken } static func getCancelToken(methodChannelRequest: [String: Any]) throws -> String { guard let cancelToken = methodChannelRequest["cancelToken"] as? String else { throw APIError.invalidConfiguration("The cancelToken request argument was not passed as a String", "The request should include the cancelToken document as a String") } return cancelToken } // ====== GRAPH QL ====== static func getGraphQLDocument(methodChannelRequest: [String: Any]) throws -> String { guard let document = methodChannelRequest["document"] as? String else { throw APIError.invalidConfiguration("The graphQL document request argument was not passed as a String", "The request should include the graphQL document as a String") } return document } static func getVariables(methodChannelRequest: [String: Any]) throws -> [String:Any] { guard let variables = methodChannelRequest["variables"] as? [String: Any] else { throw APIError.invalidConfiguration("The variables request argument was not passed as a dictionary", "The request should include the variables argument as a [String: Any] dictionary") } return variables } // ====== REST API ======= static func getRestRequest(methodChannelRequest: [String: Any]) throws -> RESTRequest { guard let restOptionsMap = methodChannelRequest["restOptions"] as? [String: Any] else { throw APIError.invalidConfiguration("The restOptions request argument was not passed as a dictionary", "The request should include the restOptions argument as a [String: Any] dictionary") } var path: String? var body: Data? var queryParameters: [String: String]? var headers: [String: String]? var apiName: String? for(key, value) in restOptionsMap { switch key { case "apiName" : apiName = value as? String case "path" : path = value as? String case "body" : body = (value as? FlutterStandardTypedData)?.data case "queryParameters" : queryParameters = value as? [String: String] case "headers" : headers = value as? [String: String] default: print("Invalid RestOption key: " + key) } } return RESTRequest(apiName: apiName, path: path, headers: headers, queryParameters: queryParameters, body: body) } }
43.10101
138
0.602765
f8fb01e2c3d317fe772d49de3d57b8aa1953ef24
2,302
// // AppDelegate.swift // HExtension // // Created by space on 16/1/8. // Copyright © 2016年 Space. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow() window?.frame = UIScreen.main.bounds window?.makeKeyAndVisible() window?.rootViewController = UINavigationController.init(rootViewController: ViewController()) 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.04
285
0.748914
d9daa864b8e709cf7e65c24534c70396ef2afc1d
1,385
// // ViewController.swift // APSRateViewController // // Created by Aishwarya Pratap Singh on 3/22/17. // Copyright © 2017 Aishwarya Pratap Singh. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { } func presentRatingsView(theme:UIColor){ let ratingVC = APSRateViewController() ratingVC.themeColor = theme ratingVC.ratingTitle = "Demo" // let navigationController = UINavigationController(rootViewController: ratingVC) self.navigationController?.pushViewController(ratingVC, animated: true) } @IBAction func orangeTheme(_ sender: Any) { presentRatingsView(theme: UIColor(red: 92/255, green: 158/255, blue: 192/255, alpha: 1.0)) } @IBAction func whiteTheme(_ sender: Any) { presentRatingsView(theme: UIColor(red: 204/255, green: 47/255, blue: 40/255, alpha: 1.0)) } @IBAction func blackTheme(_ sender: Any) { presentRatingsView(theme: UIColor.black) } }
28.265306
98
0.66065
9c6681a82c6529a7b72d15b4ed796e08390fa789
1,830
// WalletSyncRequest.swift /* Copyright 2021 The Tari Project Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public struct WalletSyncRequest: Codable { public let signature: String public let source: String public init(signature: String, source: String) { self.signature = signature self.source = source } }
40.666667
81
0.751366
56a344778624354b7ebf016d71af2dd5bc9af04e
11,965
// SPDX-License-Identifier: MIT // Copyright © 2018-2021 WireGuard LLC. All Rights Reserved. import UIKit import SystemConfiguration.CaptiveNetwork import NetworkExtension protocol SSIDOptionEditTableViewControllerDelegate: class { func ssidOptionSaved(option: ActivateOnDemandViewModel.OnDemandSSIDOption, ssids: [String]) } class SSIDOptionEditTableViewController: UITableViewController { private enum Section { case ssidOption case selectedSSIDs case addSSIDs } private enum AddSSIDRow { case addConnectedSSID(connectedSSID: String) case addNewSSID } weak var delegate: SSIDOptionEditTableViewControllerDelegate? private var sections = [Section]() private var addSSIDRows = [AddSSIDRow]() let ssidOptionFields: [ActivateOnDemandViewModel.OnDemandSSIDOption] = [ .anySSID, .onlySpecificSSIDs, .exceptSpecificSSIDs ] var selectedOption: ActivateOnDemandViewModel.OnDemandSSIDOption var selectedSSIDs: [String] var connectedSSID: String? init(option: ActivateOnDemandViewModel.OnDemandSSIDOption, ssids: [String]) { selectedOption = option selectedSSIDs = ssids super.init(style: .grouped) loadSections() addSSIDRows.removeAll() addSSIDRows.append(.addNewSSID) getConnectedSSID { [weak self] ssid in guard let self = self else { return } self.connectedSSID = ssid self.updateCurrentSSIDEntry() self.updateTableViewAddSSIDRows() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = tr("tunnelOnDemandSSIDViewTitle") tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableView.automaticDimension tableView.register(CheckmarkCell.self) tableView.register(EditableTextCell.self) tableView.register(TextCell.self) tableView.isEditing = true tableView.allowsSelectionDuringEditing = true tableView.keyboardDismissMode = .onDrag } func loadSections() { sections.removeAll() sections.append(.ssidOption) if selectedOption != .anySSID { sections.append(.selectedSSIDs) sections.append(.addSSIDs) } } func updateCurrentSSIDEntry() { if let connectedSSID = connectedSSID, !selectedSSIDs.contains(connectedSSID) { if let first = addSSIDRows.first, case .addNewSSID = first { addSSIDRows.insert(.addConnectedSSID(connectedSSID: connectedSSID), at: 0) } } else if let first = addSSIDRows.first, case .addConnectedSSID = first { addSSIDRows.removeFirst() } } func updateTableViewAddSSIDRows() { guard let addSSIDSection = sections.firstIndex(of: .addSSIDs) else { return } let numberOfAddSSIDRows = addSSIDRows.count let numberOfAddSSIDRowsInTableView = tableView.numberOfRows(inSection: addSSIDSection) switch (numberOfAddSSIDRowsInTableView, numberOfAddSSIDRows) { case (1, 2): tableView.insertRows(at: [IndexPath(row: 0, section: addSSIDSection)], with: .automatic) case (2, 1): tableView.deleteRows(at: [IndexPath(row: 0, section: addSSIDSection)], with: .automatic) default: break } } override func viewWillDisappear(_ animated: Bool) { delegate?.ssidOptionSaved(option: selectedOption, ssids: selectedSSIDs) } } extension SSIDOptionEditTableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch sections[section] { case .ssidOption: return ssidOptionFields.count case .selectedSSIDs: return selectedSSIDs.isEmpty ? 1 : selectedSSIDs.count case .addSSIDs: return addSSIDRows.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch sections[indexPath.section] { case .ssidOption: return ssidOptionCell(for: tableView, at: indexPath) case .selectedSSIDs: if !selectedSSIDs.isEmpty { return selectedSSIDCell(for: tableView, at: indexPath) } else { return noSSIDsCell(for: tableView, at: indexPath) } case .addSSIDs: return addSSIDCell(for: tableView, at: indexPath) } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { switch sections[indexPath.section] { case .ssidOption: return false case .selectedSSIDs: return !selectedSSIDs.isEmpty case .addSSIDs: return true } } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { switch sections[indexPath.section] { case .ssidOption: return .none case .selectedSSIDs: return .delete case .addSSIDs: return .insert } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch sections[section] { case .ssidOption: return nil case .selectedSSIDs: return tr("tunnelOnDemandSectionTitleSelectedSSIDs") case .addSSIDs: return tr("tunnelOnDemandSectionTitleAddSSIDs") } } private func ssidOptionCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let field = ssidOptionFields[indexPath.row] let cell: CheckmarkCell = tableView.dequeueReusableCell(for: indexPath) cell.message = field.localizedUIString cell.isChecked = selectedOption == field cell.isEditing = false return cell } private func noSSIDsCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell: TextCell = tableView.dequeueReusableCell(for: indexPath) cell.message = tr("tunnelOnDemandNoSSIDs") if #available(iOS 13.0, *) { cell.setTextColor(.secondaryLabel) } else { cell.setTextColor(.gray) } cell.setTextAlignment(.center) return cell } private func selectedSSIDCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell: EditableTextCell = tableView.dequeueReusableCell(for: indexPath) cell.message = selectedSSIDs[indexPath.row] cell.placeholder = tr("tunnelOnDemandSSIDTextFieldPlaceholder") cell.isEditing = true cell.onValueBeingEdited = { [weak self, weak cell] text in guard let self = self, let cell = cell else { return } if let row = self.tableView.indexPath(for: cell)?.row { self.selectedSSIDs[row] = text self.updateCurrentSSIDEntry() self.updateTableViewAddSSIDRows() } } return cell } private func addSSIDCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell: TextCell = tableView.dequeueReusableCell(for: indexPath) switch addSSIDRows[indexPath.row] { case .addConnectedSSID: cell.message = tr(format: "tunnelOnDemandAddMessageAddConnectedSSID (%@)", connectedSSID!) case .addNewSSID: cell.message = tr("tunnelOnDemandAddMessageAddNewSSID") } cell.isEditing = true return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { switch sections[indexPath.section] { case .ssidOption: assertionFailure() case .selectedSSIDs: assert(editingStyle == .delete) selectedSSIDs.remove(at: indexPath.row) if !selectedSSIDs.isEmpty { tableView.deleteRows(at: [indexPath], with: .automatic) } else { tableView.reloadRows(at: [indexPath], with: .automatic) } updateCurrentSSIDEntry() updateTableViewAddSSIDRows() case .addSSIDs: assert(editingStyle == .insert) let newSSID: String switch addSSIDRows[indexPath.row] { case .addConnectedSSID(let connectedSSID): newSSID = connectedSSID case .addNewSSID: newSSID = "" } selectedSSIDs.append(newSSID) loadSections() let selectedSSIDsSection = sections.firstIndex(of: .selectedSSIDs)! let indexPath = IndexPath(row: selectedSSIDs.count - 1, section: selectedSSIDsSection) if selectedSSIDs.count == 1 { tableView.reloadRows(at: [indexPath], with: .automatic) } else { tableView.insertRows(at: [indexPath], with: .automatic) } updateCurrentSSIDEntry() updateTableViewAddSSIDRows() if newSSID.isEmpty { if let selectedSSIDCell = tableView.cellForRow(at: indexPath) as? EditableTextCell { selectedSSIDCell.beginEditing() } } } } private func getConnectedSSID(completionHandler: @escaping (String?) -> Void) { #if targetEnvironment(simulator) completionHandler("Simulator Wi-Fi") #else if #available(iOS 14, *) { NEHotspotNetwork.fetchCurrent { hotspotNetwork in completionHandler(hotspotNetwork?.ssid) } } else { if let supportedInterfaces = CNCopySupportedInterfaces() as? [CFString] { for interface in supportedInterfaces { if let networkInfo = CNCopyCurrentNetworkInfo(interface) { if let ssid = (networkInfo as NSDictionary)[kCNNetworkInfoKeySSID as String] as? String { completionHandler(!ssid.isEmpty ? ssid : nil) return } } } } completionHandler(nil) } #endif } } extension SSIDOptionEditTableViewController { override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { switch sections[indexPath.section] { case .ssidOption: return indexPath case .selectedSSIDs, .addSSIDs: return nil } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch sections[indexPath.section] { case .ssidOption: let previousOption = selectedOption selectedOption = ssidOptionFields[indexPath.row] guard previousOption != selectedOption else { tableView.deselectRow(at: indexPath, animated: true) return } loadSections() if previousOption == .anySSID { let indexSet = IndexSet(1 ... 2) tableView.insertSections(indexSet, with: .fade) } if selectedOption == .anySSID { let indexSet = IndexSet(1 ... 2) tableView.deleteSections(indexSet, with: .fade) } tableView.reloadSections(IndexSet(integer: indexPath.section), with: .none) case .selectedSSIDs, .addSSIDs: assertionFailure() } } }
36.478659
137
0.622064
d5e46a3a720b0a28501ddddda8e0a5458df9ae09
2,306
// // AppDelegate.swift // PhotoApp // // Created by sergio on 06/04/2019. // Copyright © 2019 PacktPublishing. All rights reserved. // import UIKit import Firebase struct InitFirebase { init() { FirebaseApp.configure() } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var initFirebase = InitFirebase() 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:. } }
43.509434
285
0.748482
bb4b41b4be2683429eefb09429d6049963067c02
146
import Foundation @objc (RNSUSvgUrlManager) class SvgUrlManager: RCTViewManager { override func view() -> UIView! { return SvgUrl() } }
14.6
37
0.705479
0eca51e4d43b336e1af62646fc2aee4e9253c255
13,490
// // ChatViewController.swift // speaker // // Created by to0 on 2/26/15. // Copyright (c) 2015 to0. All rights reserved. // import UIKit import AudioToolbox import AVFoundation let messageFontSize: CGFloat = 17 let toolBarMinHeight: CGFloat = 44 let textViewMaxHeight: (portrait: CGFloat, landscape: CGFloat) = (portrait: 272, landscape: 90) let messageSoundOutgoing: SystemSoundID = createMessageSoundOutgoing() class ChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AVAudioRecorderDelegate, MessageInputAccessoryViewDelegate { let chat: Chat = Chat(user: User(ID: 2, username: "samihah", firstName: "Angel", lastName: "Rao"), lastMessageText: "6 sounds good :-)", lastMessageSentDate: NSDate()) // var audioRecorder: AVAudioRecorder var tableView: UITableView! var inputAccessory: MessageInputAccessoryView! var rotating = false let mqtt = MQTTClient(clientId: "ios") var remoteAudioPath: String? override var inputAccessoryView: UIView! { if inputAccessory == nil { inputAccessory = MessageInputAccessoryView(frame: CGRectMake(0, 0, 0, toolBarMinHeight-0.5)) inputAccessory.messageDelegate = self } return inputAccessory } // init(chat: Chat) { // self.chat = chat // super.init(nibName: nil, bundle: nil) // title = chat.user.name // } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) title = chat.user.name mqtt.messageHandler = {[unowned self] (message: MQTTMessage!) -> Void in let topic = message.topic // let type = topic.componentsSeparatedByString("/")[2] var speaker: String self.remoteAudioPath = topic.componentsSeparatedByString("/")[4] if message.payloadString() == "unknown" { speaker = "We don't have your voice record?" } else { speaker = "\(message.payloadString()) is speaking" } println(speaker) dispatch_async(dispatch_get_main_queue(), { self.chat.loadedMessages.append([Message(incoming: true, text: speaker, sentDate: NSDate())]) self.inputAccessory.textView.text = nil // updateTextViewHeight() let lastSection = self.tableView.numberOfSections() self.tableView.beginUpdates() self.tableView.insertSections(NSIndexSet(index: lastSection), withRowAnimation: UITableViewRowAnimation.Right) self.tableView.insertRowsAtIndexPaths([ NSIndexPath(forRow: 0, inSection: lastSection), NSIndexPath(forRow: 1, inSection: lastSection) ], withRowAnimation: UITableViewRowAnimation.Right) self.tableView.endUpdates() self.tableViewScrollToBottomAnimated(true) AudioServicesPlaySystemSound(messageSoundOutgoing) }) } mqtt.connectToHost("iot.eclipse.org", completionHandler: {[weak self](code: MQTTConnectionReturnCode) -> Void in println(code) if code.value == 0 { self?.mqtt.subscribe("ais/recognize/result/+/+", withCompletionHandler: nil) // self?.mqtt.subscribe("ais/recognize/unknown/+", withCompletionHandler: nil) } }) } override func canBecomeFirstResponder() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() chat.loadedMessages = [] let whiteColor = UIColor.whiteColor() view.backgroundColor = whiteColor // smooths push animation tableView = UITableView(frame: view.bounds, style: .Plain) tableView.autoresizingMask = .FlexibleWidth | .FlexibleHeight tableView.backgroundColor = whiteColor let edgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: toolBarMinHeight, right: 0) tableView.contentInset = edgeInsets tableView.dataSource = self tableView.delegate = self tableView.keyboardDismissMode = .Interactive tableView.estimatedRowHeight = 44 tableView.separatorStyle = .None tableView.registerClass(MessageSentDateCell.self, forCellReuseIdentifier: NSStringFromClass(MessageSentDateCell)) view.addSubview(tableView) let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil) // tableViewScrollToBottomAnimated(false) // doesn't work } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) tableView.flashScrollIndicators() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) chat.draft = inputAccessory.textView.text // chat.draft = textView.text } // This gets called a lot. Perhaps there's a better way to know when `view.window` has been set? // override func viewDidLayoutSubviews() { // super.viewDidLayoutSubviews() // toolBar.textView.becomeFirstResponder() // if !chat.draft.isEmpty { // toolBar.textView.text = chat.draft //// textView.text = chat.draft // chat.draft = "" //// textViewDidChange(toolBar.textView) // toolBar.textView.becomeFirstResponder() // } // } // // #iOS7.1 // override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { // super.willAnimateRotationToInterfaceOrientation(toInterfaceOrientation, duration: duration) // // if UIInterfaceOrientationIsLandscape(toInterfaceOrientation) { // if toolBar.frame.height > textViewMaxHeight.landscape { // toolBar.frame.size.height = textViewMaxHeight.landscape+8*2-0.5 // } // } else { // portrait //// updateTextViewHeight() // } // } // // #iOS8 // override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator!) { // super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) // } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return chat.loadedMessages.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return chat.loadedMessages[section].count + 1 // for sent-date cell } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(MessageSentDateCell), forIndexPath: indexPath)as! MessageSentDateCell let message = chat.loadedMessages[indexPath.section][0] dateFormatter.dateStyle = .ShortStyle dateFormatter.timeStyle = .ShortStyle cell.sentDateLabel.text = dateFormatter.stringFromDate(message.sentDate) return cell } else { let cellIdentifier = NSStringFromClass(MessageBubbleCell) var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as!MessageBubbleCell! if cell == nil { cell = MessageBubbleCell(style: .Default, reuseIdentifier: cellIdentifier) } let message = chat.loadedMessages[indexPath.section][indexPath.row-1] cell.configureWithMessage(message) return cell } } // Reserve row selection #CopyMessage // func tableView(tableView: UITableView!, willSelectRowAtIndexPath indexPath: NSIndexPath!)-> NSIndexPath!?{ // return nil // } // func textViewDidChange(textView: UITextView) { // updateTextViewHeight() // toolBar.sendButton.enabled = toolBar.textView.hasText() // } func keyboardWillShow(notification: NSNotification) { let userInfo = notification.userInfo as NSDictionary! let frameNew = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let insetNewBottom = tableView.convertRect(frameNew, fromView: nil).height let insetOld = tableView.contentInset let insetChange = insetNewBottom - insetOld.bottom let overflow = tableView.contentSize.height - (tableView.frame.height-insetOld.top-insetOld.bottom) let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let animations: (() -> Void) = { if !(self.tableView.tracking || self.tableView.decelerating) { // Move content with keyboard if overflow > 0 { // scrollable before self.tableView.contentOffset.y += insetChange if self.tableView.contentOffset.y < -insetOld.top { self.tableView.contentOffset.y = -insetOld.top } } else if insetChange > -overflow { // scrollable after self.tableView.contentOffset.y += insetChange + overflow } } } if duration > 0 { let options = UIViewAnimationOptions(UInt((userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue << 16)) // http://stackoverflow.com/a/18873820/242933 UIView.animateWithDuration(duration, delay: 0, options: options, animations: animations, completion: nil) } else { animations() } } func keyboardDidShow(notification: NSNotification) { let userInfo = notification.userInfo as NSDictionary! let frameNew = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let insetNewBottom = tableView.convertRect(frameNew, fromView: nil).height // Inset `tableView` with keyboard let contentOffsetY = tableView.contentOffset.y tableView.contentInset.bottom = insetNewBottom tableView.scrollIndicatorInsets.bottom = insetNewBottom // Prevents jump after keyboard dismissal if self.tableView.tracking || self.tableView.decelerating { tableView.contentOffset.y = contentOffsetY } } func didEndRecording(voiceData: NSData) { mqtt.publishData(voiceData, toTopic: "ais/recognize/voice/ios_id", withQos: MQTTQualityOfService(0), retain: false, completionHandler: nil) chat.loadedMessages.append([Message(incoming: false, text: "Voice sent", sentDate: NSDate())]) inputAccessory.textView.text = nil // updateTextViewHeight() let lastSection = tableView.numberOfSections() tableView.beginUpdates() tableView.insertSections(NSIndexSet(index: lastSection), withRowAnimation: UITableViewRowAnimation.Right) tableView.insertRowsAtIndexPaths([ NSIndexPath(forRow: 0, inSection: lastSection), NSIndexPath(forRow: 1, inSection: lastSection) ], withRowAnimation: UITableViewRowAnimation.Right) tableView.endUpdates() tableViewScrollToBottomAnimated(true) AudioServicesPlaySystemSound(messageSoundOutgoing) } func didEndInput(inputView: MessageInputAccessoryView, message: String) { if remoteAudioPath == nil { return } mqtt.publishString("\(remoteAudioPath!)=\(message)", toTopic: "ais/recognize/setname/ios_id", withQos: MQTTQualityOfService(0), retain: false, completionHandler: nil) chat.loadedMessages.append([Message(incoming: false, text: "It's \(message)", sentDate: NSDate())]) inputAccessory.textView.text = nil // updateTextViewHeight() let lastSection = tableView.numberOfSections() tableView.beginUpdates() tableView.insertSections(NSIndexSet(index: lastSection), withRowAnimation: UITableViewRowAnimation.Right) tableView.insertRowsAtIndexPaths([ NSIndexPath(forRow: 0, inSection: lastSection), NSIndexPath(forRow: 1, inSection: lastSection) ], withRowAnimation: UITableViewRowAnimation.Right) tableView.endUpdates() tableViewScrollToBottomAnimated(true) AudioServicesPlaySystemSound(messageSoundOutgoing) } func tableViewScrollToBottomAnimated(animated: Bool) { let numberOfSections = tableView.numberOfSections() let numberOfRows = tableView.numberOfRowsInSection(numberOfSections - 1) if numberOfRows > 0 { let indexPath = NSIndexPath(forRow: numberOfRows - 1, inSection: numberOfSections - 1) tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: animated) } } } func createMessageSoundOutgoing() -> SystemSoundID { var soundID: SystemSoundID = 0 let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "MessageOutgoing", "aiff", nil) AudioServicesCreateSystemSoundID(soundURL, &soundID) return soundID }
44.668874
181
0.663677
5df04ec1a00b5ca573cc1f484f03866a6733e65d
9,377
// // InfiniteBanner.swift // InfiniteBanner // // Created by LLeven on 2019/5/28. // Copyright © 2019 lianleven. All rights reserved. // import UIKit import SDWebImage public struct BannerItem { var imageUrl: String = "" var link: String = "" var title: String = "" public init (url: String, link: String = "", title: String = "") { self.imageUrl = url self.link = link self.title = title } } public protocol InfiniteBannerDelegate: class { func banner(_ banner: InfiniteBanner, didSelectItem item:BannerItem, atIndexPath indexPath: IndexPath) } open class InfiniteBanner: UIView { public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } open override func didMoveToWindow() { super.didMoveToWindow() guard let _ = self.window else { return } collectionView.contentOffset = collectionViewLayout.targetContentOffset(forProposedContentOffset: collectionView.contentOffset, withScrollingVelocity: .zero) } deinit { NotificationCenter.default.removeObserver(self) } fileprivate func setup() { collectionViewLayout.scrollDirection = .horizontal collectionViewLayout.minimumLineSpacing = 0 collectionViewLayout.minimumInteritemSpacing = 0 collectionView = UICollectionView(frame: bounds, collectionViewLayout: collectionViewLayout) addSubview(collectionView) collectionView.backgroundColor = .clear collectionView.decelerationRate = .fast collectionView.register(InfiniteBannerCell.self, forCellWithReuseIdentifier: "InfiniteBannerCell") collectionView.showsHorizontalScrollIndicator = false collectionView.delegate = self collectionView.dataSource = self collectionView.autoresizingMask = UIView.AutoresizingMask(rawValue: UIView.AutoresizingMask.flexibleWidth.rawValue | UIView.AutoresizingMask.flexibleHeight.rawValue); itemSize = self.frame.size; itemSpacing = 0; collectionView.fill() collectionView.layoutIfNeeded() timeInterval = 5 NotificationCenter.default.addObserver(self, selector: #selector(applicationDidChangeStatusBarOrientationNotification), name: UIApplication.didChangeStatusBarOrientationNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActiveNotification), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActiveNotification), name: UIApplication.didBecomeActiveNotification, object: nil) } @objc fileprivate func applicationDidChangeStatusBarOrientationNotification () { collectionView.contentOffset = collectionViewLayout.targetContentOffset(forProposedContentOffset: collectionView.contentOffset, withScrollingVelocity: .zero) } @objc fileprivate func applicationWillResignActiveNotification () { autoScroll = false } @objc fileprivate func applicationDidBecomeActiveNotification () { autoScroll = true } // MARK: Timer fileprivate func setupTimer () { tearDownTimer() if (!self.autoScroll) { return } if (self.itemCount <= 1) { return } timer = Timer(timeInterval: TimeInterval(timeInterval), target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: .common) } @objc fileprivate func timerAction() { if (!self.autoScroll) { return } let curOffset = self.collectionView.contentOffset.x let targetOffset = curOffset + self.itemSize.width + self.itemSpacing self.collectionView.setContentOffset(CGPoint(x: targetOffset, y: self.collectionView.contentOffset.y), animated: true) } fileprivate func tearDownTimer () { timer?.invalidate() timer = nil } fileprivate func reload() { DispatchQueue.main.async {[weak self] in self?.collectionView.reloadData() DispatchQueue.main.async {[weak self] in guard let self = self else { return } let curOffset = self.collectionView.contentOffset.x let targetOffset = curOffset + self.itemSize.width + self.itemSpacing self.collectionView.setContentOffset(CGPoint(x: targetOffset, y: self.collectionView.contentOffset.y), animated: true) } } } fileprivate var collectionView: UICollectionView! fileprivate var collectionViewLayout: InfiniteBannerLayout = InfiniteBannerLayout() fileprivate var timer: Timer? fileprivate var itemCount: Int = 0 public var animation: Bool = true // public var autoScroll: Bool = true public var autoScroll: Bool = true { didSet { setupTimer() if items.count >= 3 { reload() } } } public var timeInterval: Int = 3 { didSet { setupTimer() } } public var itemSize: CGSize = .zero{ didSet { collectionViewLayout.itemSize = itemSize } } public var itemSpacing: CGFloat = 0{ didSet { collectionViewLayout.minimumLineSpacing = itemSpacing } } public var setBannerImage:((_ url: String) -> UIImage)? public var placeholder: UIImage? public weak var delegate: InfiniteBannerDelegate? fileprivate var _items: [BannerItem] = [] public var items: [BannerItem] { get{ return _items } set { if newValue.count > 0 { itemCount = newValue.count _items.removeAll() for _ in 0..<3{ _items.append(contentsOf: newValue) } setupTimer() reload() } } } } extension InfiniteBanner: UICollectionViewDataSource, UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.items.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InfiniteBannerCell", for: indexPath) as! InfiniteBannerCell let item = self.items[indexPath.row] // cell.imageView.image = setBannerImage?(item.imageUrl) cell.imageView.sd_setImage(with: URL(string: item.imageUrl), placeholderImage: placeholder) cell.imageView.layer.cornerRadius = 4; tranform(cell: cell) return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let index = indexPath.row % (self.items.count / 3) let item = self.items[indexPath.row] let indexPathTemp = IndexPath(row: index, section: 0) self.delegate?.banner(self, didSelectItem: item, atIndexPath: indexPathTemp) } // MARK: UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageWidth = itemSize.width + itemSpacing let periodOffset = pageWidth * CGFloat((items.count / 3)) let offsetActivatingMoveToBeginning = pageWidth * CGFloat((items.count / 3) * 2); let offsetActivatingMoveToEnd = pageWidth * CGFloat((self.items.count / 3) * 1); let offsetX = scrollView.contentOffset.x; if (offsetX > offsetActivatingMoveToBeginning) { scrollView.contentOffset = CGPoint(x: (offsetX - periodOffset), y: 0); } else if (offsetX < offsetActivatingMoveToEnd) { scrollView.contentOffset = CGPoint(x: (offsetX + periodOffset),y: 0); } if !animation { return } for cell in collectionView.visibleCells { tranform(cell: cell) } } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { tearDownTimer() } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { setupTimer() } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { collectionView.contentOffset = collectionViewLayout.targetContentOffset(forProposedContentOffset: collectionView.contentOffset, withScrollingVelocity: .zero) } fileprivate func tranform(cell: UICollectionViewCell) { if !animation { return } let centerPoint = self.convert(cell.center,from: collectionView) let d = abs(centerPoint.x - collectionView.frame.width * 0.5) / itemSize.width var scale = 1 - 0.2 * d if scale < 0 { scale = 0 } if scale > 1 { scale = 1 } cell.layer.transform = CATransform3DMakeScale(scale, scale, 1) } }
38.273469
203
0.655967
26614b4b404fe80d25dffdb933f701c7d7ff8512
1,025
// // Copyright (C) 2021 Twilio, Inc. // // 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. // struct PlayerMetadata: Decodable { typealias Identity = String struct Participant: Decodable { /// Volume. /// /// - Note: Value is -1 when speaker is muted. let v: Int } /// Sequence identifier used to detect and discard out of sequence metadata since order is not gauranteed. let s: Int /// Participants. let p: [Identity: Participant] }
31.060606
110
0.67122
5b4a7da4ecbeaab22dbfec53837f0a05b49bf9ef
613
// // AppDelegate.swift // GitHub // // Created by Anton Polyakov on 07/08/2019. // Copyright © 2019 ton252. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() let router = RootRouter() router.setRoot() return true } }
21.137931
145
0.663948
29bdb1dd529113375c36db61dc5338b5aaabd248
2,221
// // ViewControllerView.swift // Reversi // // Created by Yoshiki Tsukada on 2020/05/04. // Copyright © 2020 Yuta Koshizawa. All rights reserved. // import UIKit class ViewControllerView: UIView { @IBOutlet var boardView: BoardView! @IBOutlet var messageDiskView: DiskView! @IBOutlet var messageLabel: UILabel! @IBOutlet var messageDiskSizeConstraint: NSLayoutConstraint! /// Storyboard 上で設定されたサイズを保管します。 /// 引き分けの際は `messageDiskView` の表示が必要ないため、 /// `messageDiskSizeConstraint.constant` を `0` に設定します。 /// その後、新しいゲームが開始されたときに `messageDiskSize` を /// 元のサイズで表示する必要があり、 /// その際に `messageDiskSize` に保管された値を使います。 private var messageDiskSize: CGFloat! @IBOutlet var playerControls: [UISegmentedControl]! @IBOutlet var countLabels: [UILabel]! @IBOutlet var playerActivityIndicators: [UIActivityIndicatorView]! override init(frame: CGRect) { super.init(frame: frame) loadNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! loadNib() } func loadNib() { guard let view = UINib(nibName: String(describing: type(of: self)), bundle: nil).instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Could not load Nibfile.") } view.frame = bounds addSubview(view) } func setupViews() { } // /// どちらの色のプレイヤーのターンかを表します。ゲーム終了時は `nil` です。 // private var turn: Disk? = .dark // // private var animationCanceller: Canceller? // private var isAnimating: Bool { animationCanceller != nil } // // private var playerCancellers: [Disk: Canceller] = [:] // // override func viewDidLoad() { // super.viewDidLoad() // // boardView.delegate = self // messageDiskSize = messageDiskSizeConstraint.constant // // do { // try loadGame() // } catch _ { // newGame() // } // } // // private var viewHasAppeared: Bool = false // override func viewDidAppear(_ animated: Bool) { // super.viewDidAppear(animated) // // if viewHasAppeared { return } // viewHasAppeared = true // waitForPlayer() // } }
27.419753
155
0.630797
7a454a769e21903a1a1e560c84d47ef11bdd29d3
1,314
// Copyright 2022 Pera Wallet, LDA // 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. // AnnouncementCell.swift import Foundation import MacaroonUIKit import UIKit final class GenericAnnouncementCell: CollectionCell<AnnouncementView>, ViewModelBindable, UIInteractionObservable { static let theme = GenericAnnouncementViewTheme() override init( frame: CGRect ) { super.init(frame: frame) contextView.customize(Self.theme) } } final class GovernanceAnnouncementCell: CollectionCell<AnnouncementView>, ViewModelBindable, UIInteractionObservable { static let theme = GovernanceAnnouncementViewTheme() override init( frame: CGRect ) { super.init(frame: frame) contextView.customize(Self.theme) } }
27.375
75
0.7207
ff85d79cfb55b54b7e1e7e31d54217c21c941e4a
224
// // ResponseHandler.swift // FanapPodChatSDK // // Created by Hamed Hosseini on 2/15/21. // import Foundation protocol ResponseHandler { static func handle(_ chatMessage:NewChatMessage ,_ asyncMessage:AsyncMessage) }
18.666667
78
0.758929
accbc9b4fdd8133a2d28a776a3f28440e575525d
986
// // Book.swift // project // // Created by Ling on 6/4/21. // Copyright © 2021 tranthihoaitrang. All rights reserved. // import Foundation; import UIKit; class Book { var bookID: Int; var bookName: String; var bookAuthors: String; var bookType: String; var bookQuantity: Int; var bookQuantityCurrent: Int; var imagePath: String; var bookImage: UIImage?; init?(id: Int, name: String, authors: String, type: String, quantity: Int, quantityCurrent: Int, path: String, image: UIImage?) { if name.isEmpty == true || authors.isEmpty == true || type.isEmpty == true { return nil; } bookID = id; bookName = name; bookAuthors = authors; bookType = type; bookQuantity = quantity; bookQuantityCurrent = quantityCurrent; imagePath = path; bookImage = image; } public static func toString() -> String { return "This is a book!"; } }
24.65
133
0.60142
e2574acc4f45ebeafd7de02151c510e1c24690ab
3,736
// Converted to Swift 4 by Swiftify v4.1.6640 - https://objectivec2swift.com/ // // PVAtari7800ControllerViewController.swift // Provenance // // Created by James Addyman on 05/09/2013. // Copyright (c) 2013 James Addyman. All rights reserved. // // // PVAtari7800ControllerViewController.swift // Provenance // // Created by Joe Mattiello on 08/22/2016. // Copyright (c) 2016 Joe Mattiello. All rights reserved. // import PVSupport private extension JSButton { var buttonTag: PV7800Button { get { return PV7800Button(rawValue: tag)! } set { tag = newValue.rawValue } } } final class PVAtari7800ControllerViewController: PVControllerViewController<PV7800SystemResponderClient> { override func layoutViews() { buttonGroup?.subviews.forEach { guard let button = $0 as? JSButton, let title = button.titleLabel?.text else { return } if title == "Fire 1" || title == "1" { button.buttonTag = .fire1 } else if title == "Fire 2" || title == "2" { button.buttonTag = .fire2 } else if title == "Select" { button.buttonTag = .select } else if title == "Reset" { button.buttonTag = .reset } else if title == "Pause" { button.buttonTag = .pause } } startButton?.buttonTag = .reset selectButton?.buttonTag = .select } override func dPad(_: JSDPad, didPress direction: JSDPadDirection) { emulatorCore.didRelease(.up, forPlayer: 0) emulatorCore.didRelease(.down, forPlayer: 0) emulatorCore.didRelease(.left, forPlayer: 0) emulatorCore.didRelease(.right, forPlayer: 0) switch direction { case .upLeft: emulatorCore.didPush(.up, forPlayer: 0) emulatorCore.didPush(.left, forPlayer: 0) case .up: emulatorCore.didPush(.up, forPlayer: 0) case .upRight: emulatorCore.didPush(.up, forPlayer: 0) emulatorCore.didPush(.right, forPlayer: 0) case .left: emulatorCore.didPush(.left, forPlayer: 0) case .right: emulatorCore.didPush(.right, forPlayer: 0) case .downLeft: emulatorCore.didPush(.down, forPlayer: 0) emulatorCore.didPush(.left, forPlayer: 0) case .down: emulatorCore.didPush(.down, forPlayer: 0) case .downRight: emulatorCore.didPush(.down, forPlayer: 0) emulatorCore.didPush(.right, forPlayer: 0) default: break } vibrate() } override func dPadDidReleaseDirection(_: JSDPad) { emulatorCore.didRelease(.up, forPlayer: 0) emulatorCore.didRelease(.down, forPlayer: 0) emulatorCore.didRelease(.left, forPlayer: 0) emulatorCore.didRelease(.right, forPlayer: 0) } override func buttonPressed(_ button: JSButton) { emulatorCore.didPush(button.buttonTag, forPlayer: 0) vibrate() } override func buttonReleased(_ button: JSButton) { emulatorCore.didRelease(button.buttonTag, forPlayer: 0) } override func pressStart(forPlayer player: Int) { emulatorCore.didPush(.reset, forPlayer: player) } override func releaseStart(forPlayer player: Int) { emulatorCore.didRelease(.reset, forPlayer: player) } override func pressSelect(forPlayer player: Int) { emulatorCore.didPush(.select, forPlayer: player) } override func releaseSelect(forPlayer player: Int) { emulatorCore.didRelease(.select, forPlayer: player) } }
31.931624
106
0.607869
71685799d96895c8d20c2084a83f4daffdfaaaab
12,076
// // Headache+CoreDataClassTests.swift // HeadacheTracker2Tests // // Created by Morgan Davison on 5/17/19. // Copyright © 2019 Morgan Davison. All rights reserved. // import XCTest @testable import HeadacheTracker2 import CoreData class HeadacheTests: XCTestCase { var coreDataStack: TestCoreDataStack? var headache: Headache? override func setUp() { super.setUp() coreDataStack = TestCoreDataStack(modelName: "HeadacheTracker2") guard let coreDataStack = coreDataStack else { XCTFail("Expected coreDataStack to be set") return } headache = Headache(context: coreDataStack.managedContext) // Make sure we start with an empty db clearDatabase() } override func tearDown() { super.tearDown() // Try to empty the db clearDatabase() } func testCheckEmpty() { if let coreDataStack = coreDataStack { let headaches = Headache.getAll(coreDataStack: coreDataStack)! XCTAssertEqual(headaches.count, 0) } else { XCTFail() } } func testSeverityDisplayText() { guard let headache = headache else { XCTFail("Expected headache to be set") return } headache.severity = 1 XCTAssert(headache.severityDisplayText == "❶") headache.severity = 2 XCTAssert(headache.severityDisplayText == "❷") headache.severity = 3 XCTAssert(headache.severityDisplayText == "❸") headache.severity = 4 XCTAssert(headache.severityDisplayText == "❹") headache.severity = 5 XCTAssert(headache.severityDisplayText == "❺") } func testSeverityDisplayColor() { guard let headache = headache else { XCTFail("Expected headache to be set") return } headache.severity = 1 XCTAssert(headache.severityDisplayColor == UIColor(named: "Severity1")!) headache.severity = 2 XCTAssert(headache.severityDisplayColor == UIColor(named: "Severity2")!) headache.severity = 3 XCTAssert(headache.severityDisplayColor == UIColor(named: "Severity3")!) headache.severity = 4 XCTAssert(headache.severityDisplayColor == UIColor(named: "Severity4")!) headache.severity = 5 XCTAssertTrue(headache.severityDisplayColor == UIColor(named: "Severity5")!) } func testGetAll() { guard let coreDataStack = coreDataStack else { XCTFail("Expected coreDataStack to be set") return } let _ = [ Headache(context: coreDataStack.managedContext), Headache(context: coreDataStack.managedContext), Headache(context: coreDataStack.managedContext) ] coreDataStack.saveContext() let headaches = Headache.getAll(coreDataStack: coreDataStack) XCTAssertEqual(headaches?.count, 3) } func testUpdateDate() { guard let coreDataStack = coreDataStack else { XCTFail("Expected coreDataStack to be set") return } var headache = Headache(context: coreDataStack.managedContext) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" guard let formattedDate = dateFormatter.date(from: "2019-07-01") else { XCTFail("Expected formatted date to return a Date object") return } headache.date = formattedDate coreDataStack.saveContext() guard let headaches = Headache.getAll(coreDataStack: coreDataStack), let firstHeadache = headaches.first else { XCTFail("Expected Headache.getAll() to return headaches") return } headache = firstHeadache XCTAssertEqual(dateFormatter.string(from: formattedDate), "2019-07-01") guard let newDate = dateFormatter.date(from: "2019-06-15") else { XCTFail("Expected newDate to be set") return } firstHeadache.date = newDate coreDataStack.saveContext() guard let headachesUpdated = Headache.getAll(coreDataStack: coreDataStack), let updatedHeadache = headachesUpdated.first else { XCTFail("Expected Headache.getAll() to return updated headache") return } headache = updatedHeadache XCTAssertEqual(dateFormatter.string(from: headache.date), "2019-06-15") } func testUpdateSeverity() { guard let coreDataStack = coreDataStack else { XCTFail("Expected coreDataStack to be set") return } var headache = Headache(context: coreDataStack.managedContext) headache.severity = Int16(3) coreDataStack.saveContext() guard let headaches = Headache.getAll(coreDataStack: coreDataStack), let firstHeadache = headaches.first else { XCTFail("Expected Headache.getAll() to return headaches") return } headache = firstHeadache XCTAssertEqual(headache.severity, 3) headache.severity = Int16(4) coreDataStack.saveContext() guard let headachesUpdated = Headache.getAll(coreDataStack: coreDataStack), let updatedHeadache = headachesUpdated.first else { XCTFail("Expected Headache.getAll() to return updated headache") return } headache = updatedHeadache XCTAssertEqual(headache.severity, 4) } func testUpdateNote() { guard let coreDataStack = coreDataStack else { XCTFail("Expected coreDataStack to be set") return } var headache = Headache(context: coreDataStack.managedContext) headache.note = "Testing gives me a headache." coreDataStack.saveContext() guard let headaches = Headache.getAll(coreDataStack: coreDataStack), let firstHeadache = headaches.first else { XCTFail("Expected Headache.getAll() to return headaches") return } headache = firstHeadache XCTAssertEqual(headache.note, "Testing gives me a headache.") headache.note = "Tests are terrific!" coreDataStack.saveContext() guard let headachesUpdated = Headache.getAll(coreDataStack: coreDataStack), let updatedHeadache = headachesUpdated.first else { XCTFail("Expected Headache.getAll() to return updated headache") return } headache = updatedHeadache XCTAssertEqual(headache.note, "Tests are terrific!") } func testUpdateDoses() { guard let coreDataStack = coreDataStack else { XCTFail("Expected coreDataStack to be set") return } var headache = Headache(context: coreDataStack.managedContext) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" guard let formattedDate = dateFormatter.date(from: "2019-07-01") else { XCTFail("Expected formattedDate to return a Date object") return } headache.date = formattedDate let medication = Medication(context: coreDataStack.managedContext) medication.name = "Tylenol" let dose = Dose(context: coreDataStack.managedContext) dose.date = formattedDate dose.headache = headache dose.medication = medication dose.quantity = Int16(1) coreDataStack.saveContext() guard let headaches = Headache.getAll(coreDataStack: coreDataStack), let firstHeadache = headaches.first else { XCTFail("Expected Headache.getAll() to return headaches") return } headache = firstHeadache // Assert that headache only has 1 dose of 1 Tylenol XCTAssertEqual(headache.doses?.count, 1) guard let medicationDoses = headache.getMedicationsDoses() else { XCTFail("Expected medicationDoses to be set") return } for (med, qty) in medicationDoses { XCTAssertEqual(med.name, "Tylenol") XCTAssertEqual(qty, 1) } let headacheMedicationQuantities = [medication: 2] // When we call updateDoses with [Medication: Int] we should see new results headache.updateDoses(coreDataStack: coreDataStack, medicationQuantities: headacheMedicationQuantities) coreDataStack.saveContext() // Make sure we still only have 1 headache let allHeadaches = Headache.getAll(coreDataStack: coreDataStack) XCTAssertEqual(allHeadaches?.count, 1) guard let allHeadachesFirst = allHeadaches?.first else { XCTFail("Expected firstHeadache to be set") return } headache = allHeadachesFirst // Assert that headache still only has 1 dose XCTAssert(headache.doses?.count == 1) // Assert that headache now has 2 Tylenol guard let medicationDosesUpdated = headache.getMedicationsDoses() else { XCTFail("Expected medicationDosesUpdated to be set") return } for (med, qty) in medicationDosesUpdated { XCTAssertEqual(med.name, "Tylenol") XCTAssertEqual(qty, 2) } } func testGetDatesForLast() { guard let coreDataStack = coreDataStack else { XCTFail("Expected coreDataStack to be set") return } let today = Date() let dates = [ today, Calendar.current.date(byAdding: .day, value: -3, to: today), Calendar.current.date(byAdding: .day, value: -7, to: today), Calendar.current.date(byAdding: .day, value: -20, to: today), Calendar.current.date(byAdding: .day, value: -30, to: today), Calendar.current.date(byAdding: .day, value: -60, to: today), Calendar.current.date(byAdding: .day, value: -365, to: today) ] var headache: Headache for date in dates { headache = Headache(context: coreDataStack.managedContext) headache.date = date! headache.severity = 3 coreDataStack.saveContext() } var (startDate, endDate) = Headache.getDatesForLast(numDays: ChartInterval.week.rawValue)! var headaches = Headache.getAll(startDate: startDate, endDate: endDate, coreDataStack: coreDataStack) XCTAssertEqual(headaches?.count, 2) (startDate, endDate) = Headache.getDatesForLast(numDays: ChartInterval.month.rawValue)! headaches = Headache.getAll(startDate: startDate, endDate: endDate, coreDataStack: coreDataStack) XCTAssertEqual(headaches?.count, 4) (startDate, endDate) = Headache.getDatesForLast(numDays: ChartInterval.year.rawValue)! headaches = Headache.getAll(startDate: startDate, endDate: endDate, coreDataStack: coreDataStack) XCTAssertEqual(headaches?.count, 6) } // MARK: - Helper methods private func clearDatabase() { if let headaches = Headache.getAll(coreDataStack: coreDataStack!) { for headache in headaches { coreDataStack?.managedContext.delete(headache) } } } }
33.267218
110
0.592332
fbbae16373d8ba3364ec38cb6ae5f636cb8a8d27
812
// // AddEventLocationCell.swift // Pretto // // Created by Francisco de la Pena on 7/6/15. // Copyright (c) 2015 Pretto. All rights reserved. // import UIKit class AddEventLocationCell: UITableViewCell { @IBOutlet weak var cellTitle: UILabel! @IBOutlet weak var cellContent: UILabel! override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = UITableViewCellSelectionStyle.None self.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cellTitle.textColor = UIColor.prettoOrange() cellContent.textColor = UIColor.lightGrayColor() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
26.193548
77
0.703202
1115402a43d3643682b88dff6715f6e8fc04e5fc
1,865
// APIs.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation open class SwaggerClientAPI { open static var basePath = "https://graphhopper.com/api/1" open static var credential: URLCredential? open static var customHeaders: [String:String] = [:] open static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() } open class RequestBuilder<T> { var credential: URLCredential? var headers: [String:String] public let parameters: [String:Any]? public let isBody: Bool public let method: String public let URLString: String /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody self.headers = headers addHeaders(SwaggerClientAPI.customHeaders) } open func addHeaders(_ aHeaders:[String:String]) { for (header, value) in aHeaders { headers[header] = value } } open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { headers[name] = value } return self } open func addCredential() -> Self { self.credential = SwaggerClientAPI.credential return self } } public protocol RequestBuilderFactory { func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type func getBuilder<T:Decodable>() -> RequestBuilder<T>.Type }
30.080645
134
0.667024
500d143fef961c979e0b739fb98dc38ba00b4bda
2,188
// // MarketService.swift // sweettrex // // Created by Cassius Pacheco on 24/9/17. // // import Foundation protocol MarketServiceProtocol { func allMarkets(onCompletion: @escaping (Result<[Market]>) -> Void) throws } struct MarketService: MarketServiceProtocol { private let service: HttpServiceProtocol init() { self.init(httpService: HttpService()) } init(httpService: HttpServiceProtocol) { self.service = httpService } func allMarkets(onCompletion: @escaping (Result<[Market]>) -> Void) throws { do { print("\nFetching markets...") let result = try service.request(.market, httpMethod: .GET, bodyData: nil) switch result { case .successful(let json): do { let markets = try self.parse(json) onCompletion(.successful(markets)) } catch { // TODO: handle errors print("💥 failed to parse and save markets") onCompletion(.failed(.parsing)) } case .failed(let error): // TODO: handle errors print(error) onCompletion(.failed(.unknown)) } } catch { // TODO: handle errors print("failed to request markets") onCompletion(.failed(.unknown)) } } func parse(_ json: JSON) throws -> [Market] { guard let marketsJSON: [JSON] = try json.get("result") else { throw Abort.badRequest } let markets = try marketsJSON.map({ try Market(json: $0) }) for market in markets { guard let dbMarket = try Market.find(byName: market.name) else { continue } market.id = dbMarket.id market.exists = true } return markets } }
25.149425
94
0.468464
28630bf72aee146fe5e462aade4eca165dc1cd72
375
// // Distance.swift // Scroller // // Created by Pavel Krasnobrovkin on 29/03/2019. // Copyright © 2019 Pavel Krasnobrovkin. All rights reserved. // import Foundation internal func distance(aX: CGFloat, bX: CGFloat, aY: CGFloat, bY: CGFloat) -> CGFloat { let xDistance = pow(bX - aX, 2) let yDistance = pow(bY - aY, 2) return sqrt(xDistance + yDistance) }
22.058824
85
0.674667
114b81a3785c09d4e84edca216a995ec233df5f0
5,318
// // ViewController.swift // iOS_JS_InteractUseJavaScriptCore // // Created by Mazy on 2017/10/27. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit import WebKit import JavaScriptCore import AVFoundation class ViewController: UIViewController { fileprivate var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() webView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 300)) webView.delegate = self let htmlURL = Bundle.main.url(forResource: "index.html", withExtension: nil) let request = URLRequest(url: htmlURL!) // 如果不想要webView 的回弹效果 // webView.scrollView.bounces = false // UIWebView 滚动的比较慢,这里设置为正常速度 webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal // 请求数据 webView.loadRequest(request) view.addSubview(webView) } } extension ViewController: UIWebViewDelegate { func webViewDidFinishLoad(_ webView: UIWebView) { addCustomActions() } } extension ViewController { fileprivate func addCustomActions() { guard let context = self.webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as? JSContext else { return } addShareWithContext(context) addScanWithContext(context) addLocationWithContext(context) addSetBGColorWithContext(context) addPayActionWithContext(context) addShakeActionWithContext(context) addGoBackWithContext(context) } func addScanWithContext(_ context: JSContext) { let callBack : @convention(block) (AnyObject?) -> Void = {_ in print("扫一扫") } context.setObject(unsafeBitCast(callBack, to: AnyObject.self), forKeyedSubscript: "scan" as NSCopying & NSObjectProtocol) } func addLocationWithContext(_ context: JSContext) { let callBack : @convention(block) (AnyObject?) -> Void = { _ in // Waiting let jsStr = "setLocation('\("湖北省—武汉市")')" JSContext.current().evaluateScript(jsStr) } context.setObject(unsafeBitCast(callBack, to: AnyObject.self), forKeyedSubscript: "getLocation" as NSCopying & NSObjectProtocol) } func addSetBGColorWithContext(_ context: JSContext) { let callBack : @convention(block) (AnyObject?) -> Void = { [weak self] (paramFromJS) -> Void in // Waiting let value = JSContext.currentArguments() as! [JSValue] let r = value[0].toDouble() let g = value[1].toDouble() let b = value[2].toDouble() let a = value[3].toDouble() DispatchQueue.main.sync { self?.view.backgroundColor = UIColor(red: CGFloat(r/255.0), green: CGFloat(g/255.0), blue: CGFloat(b/255.0), alpha: CGFloat(a)) } } context.setObject(unsafeBitCast(callBack, to: AnyObject.self), forKeyedSubscript: "setColor" as NSCopying & NSObjectProtocol) } func addShareWithContext(_ context: JSContext) { let callBack : @convention(block) (AnyObject?) -> Void = {_ in // Waiting let value = JSContext.currentArguments() as! [JSValue] let title = value[0].toString() ?? "" let content = value[1].toString() ?? "" let url = value[2].toString() ?? "" let jsStr = "shareResult('\(title)','\(content)', '\(url)')" JSContext.current().evaluateScript(jsStr) } context.setObject(unsafeBitCast(callBack, to: AnyObject.self), forKeyedSubscript: "share" as NSCopying & NSObjectProtocol) } func addPayActionWithContext(_ context: JSContext) { let callBack : @convention(block) (AnyObject?) -> Void = { _ in let value = JSContext.currentArguments() as! [JSValue] let orderNo = value[0].toString() ?? "" let channel = value[1].toString() ?? "" let amount = value[2].toString() ?? "" let subject = value[3].toString() ?? "" let jsStr = "payResult('\(orderNo)','\(channel)', '\(amount)', '\(subject)')" JSContext.current().evaluateScript(jsStr) } context.setObject(unsafeBitCast(callBack, to: AnyObject.self), forKeyedSubscript: "payAction" as NSCopying & NSObjectProtocol) } func addShakeActionWithContext(_ context: JSContext) { let callBack : @convention(block) (AnyObject?) -> Void = { _ in AudioServicesPlaySystemSound (kSystemSoundID_Vibrate); } context.setObject(unsafeBitCast(callBack, to: AnyObject.self), forKeyedSubscript: "shake" as NSCopying & NSObjectProtocol) } func addGoBackWithContext(_ context: JSContext) { let callBack : @convention(block) (AnyObject?) -> Void = { [weak self] (paramFromJS) -> Void in DispatchQueue.main.async { self?.webView.goBack() } } context.setObject(unsafeBitCast(callBack, to: AnyObject.self), forKeyedSubscript: "goBack" as NSCopying & NSObjectProtocol) } }
36.675862
143
0.610756
1c54f2c65adaa38693430a5c735e73373d69a9ce
767
// // Business.swift // YelpAPI // // Created by Daniel Lau on 8/5/18. // Copyright © 2018 Daniel Lau. All rights reserved. // import Foundation import MapViewPlus struct Yelp: Codable { let total : Int let businesses : [Business] } struct Business : Codable, CalloutViewModel { let name : String let image_url : String let coordinates : Coordinates let location : Location } struct Coordinates : Codable { let latitude : Double let longitude: Double } struct Location : Codable { let address1 : String let city : String let zipCode : String let state : String enum CodingKeys: String, CodingKey { case address1 case city case state case zipCode = "zip_code" } }
17.431818
53
0.644068
0a9828524da447aabc25c908c521401a67b92070
2,316
// // AppDataManager.swift // FavQuotes // // Created by Jeffery Wang on 10/5/20. // Copyright © 2020 eagersoft.io. All rights reserved. // import UIKit class AppDataManager{ public static let shared = AppDataManager() public var quotes: Array<Quote> = [] private init(){ //self.setupTestData() } private func setupTestData(){ let q1 = Quote(author: "Francis Bacon", text: "Knowledge is power.") let q2 = Quote(author: "Hermann Meyer", text: "No enemy bomber can reach the Ruhr. If one reaches the Ruhr, my name is not Göring. You may call me Meyer") let q3 = Quote(author: "Donald J. Trump", text: "The beauty of me is that i'm very rich") self.quotes = [q1, q2, q3] } private func setupForFirstTime(){ CoreDataManager.shared.saveObject(to: .Quote, with: ["Deng Xiaoping", "The colour of the cat doesn't matter as long as it catches the mice."]) CoreDataManager.shared.saveObject(to: .Quote, with: ["Francis Bacon", "Knowledge is power."]) CoreDataManager.shared.saveObject(to: .Quote, with: ["Karl Marx", "Surround yourself with people who make you happy. People who make you laugh, who help you when you’re in need. People who genuinely care. They are the ones worth keeping in your life. Everyone else is just passing through."]) CoreDataManager.shared.saveObject(to: .Quote, with: ["Ruth Bader Ginsburg", "Fight for the things that you care about, but do it in a way that will lead others to join you."]) } public func setupData(){ if(Util.isAppFirstTimeLaunched()){ self.setupForFirstTime() } let quotes = CoreDataManager.shared.fetchObject(with: .Quote) as! Array<QuoteEntity> for quote in quotes{ let q = Quote(author: quote.author!, text: quote.quote!) AppDataManager.shared.quotes.append(q) } } public func syncQuotesWithCoreData(){ let quotes = CoreDataManager.shared.fetchObject(with: .Quote) as! Array<QuoteEntity> for quote in quotes{ CoreDataManager.shared.deleteObject(of: .Quote, with: quote) } for quote in self.quotes{ CoreDataManager.shared.saveObject(to: .Quote, with: [quote.author, quote.quote]) } } }
42.888889
300
0.653282
bb130d98f0821a8bf9c84fa757a748db3599c454
7,431
#if os(iOS) import UIKit import DateToolsSwift public final class DayHeaderView: UIView, DaySelectorDelegate, DayViewStateUpdating, UIPageViewControllerDataSource, UIPageViewControllerDelegate { public private(set) var daysInWeek = 7 public let calendar: Calendar private var style = DayHeaderStyle() private var currentSizeClass = UIUserInterfaceSizeClass.compact public weak var state: DayViewState? { willSet(newValue) { state?.unsubscribe(client: self) } didSet { state?.subscribe(client: self) swipeLabelView.state = state } } private var currentWeekdayIndex = -1 private var daySymbolsViewHeight: CGFloat = 20 private var pagingScrollViewHeight: CGFloat = 40 private var swipeLabelViewHeight: CGFloat = 20 private let daySymbolsView: DaySymbolsView private var pagingViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) private let swipeLabelView: SwipeLabelView public init(calendar: Calendar) { self.calendar = calendar let symbols = DaySymbolsView(calendar: calendar) let swipeLabel = SwipeLabelView(calendar: calendar) self.swipeLabelView = swipeLabel self.daySymbolsView = symbols super.init(frame: .zero) configure() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configure() { [daySymbolsView, swipeLabelView].forEach(addSubview) backgroundColor = style.backgroundColor configurePagingViewController() } private func configurePagingViewController() { let selectedDate = Date() let vc = makeSelectorController(startDate: beginningOfWeek(selectedDate)) vc.selectedDate = selectedDate currentWeekdayIndex = vc.selectedIndex pagingViewController.setViewControllers([vc], direction: .forward, animated: false, completion: nil) pagingViewController.dataSource = self pagingViewController.delegate = self addSubview(pagingViewController.view!) } private func makeSelectorController(startDate: Date) -> DaySelectorController { let new = DaySelectorController() new.calendar = calendar new.transitionToHorizontalSizeClass(currentSizeClass) new.updateStyle(style.daySelector) new.startDate = startDate new.delegate = self return new } private func beginningOfWeek(_ date: Date) -> Date { let weekOfYear = component(component: .weekOfYear, from: date) let yearForWeekOfYear = component(component: .yearForWeekOfYear, from: date) return calendar.date(from: DateComponents(calendar: calendar, weekday: calendar.firstWeekday, weekOfYear: weekOfYear, yearForWeekOfYear: yearForWeekOfYear))! } private func component(component: Calendar.Component, from date: Date) -> Int { return calendar.component(component, from: date) } public func updateStyle(_ newStyle: DayHeaderStyle) { style = newStyle daySymbolsView.updateStyle(style.daySymbols) swipeLabelView.updateStyle(style.swipeLabel) (pagingViewController.viewControllers as? [DaySelectorController])?.forEach{$0.updateStyle(newStyle.daySelector)} backgroundColor = style.backgroundColor } override public func layoutSubviews() { super.layoutSubviews() daySymbolsView.frame = CGRect(origin: .zero, size: CGSize(width: bounds.width, height: daySymbolsViewHeight)) pagingViewController.view?.frame = CGRect(origin: CGPoint(x: 0, y: daySymbolsViewHeight), size: CGSize(width: bounds.width, height: pagingScrollViewHeight)) swipeLabelView.frame = CGRect(origin: CGPoint(x: 0, y: bounds.height - 10 - swipeLabelViewHeight), size: CGSize(width: bounds.width, height: swipeLabelViewHeight)) } public func transitionToHorizontalSizeClass(_ sizeClass: UIUserInterfaceSizeClass) { currentSizeClass = sizeClass daySymbolsView.isHidden = sizeClass == .regular (pagingViewController.children as? [DaySelectorController])?.forEach{$0.transitionToHorizontalSizeClass(sizeClass)} } // MARK: DaySelectorDelegate public func dateSelectorDidSelectDate(_ date: Date) { state?.move(to: date) } // MARK: DayViewStateUpdating public func move(from oldDate: Date, to newDate: Date) { let newDate = newDate.dateOnly(calendar: calendar) let centerView = pagingViewController.viewControllers![0] as! DaySelectorController let startDate = centerView.startDate.dateOnly(calendar: calendar) let daysFrom = newDate.days(from: startDate, calendar: calendar) let newStartDate = beginningOfWeek(newDate) let new = makeSelectorController(startDate: newStartDate) if daysFrom < 0 { currentWeekdayIndex = abs(daysInWeek + daysFrom % daysInWeek) % daysInWeek new.selectedIndex = currentWeekdayIndex pagingViewController.setViewControllers([new], direction: .reverse, animated: true, completion: nil) } else if daysFrom > daysInWeek - 1 { currentWeekdayIndex = daysFrom % daysInWeek new.selectedIndex = currentWeekdayIndex pagingViewController.setViewControllers([new], direction: .forward, animated: true, completion: nil) } else { currentWeekdayIndex = daysFrom centerView.selectedDate = newDate centerView.selectedIndex = currentWeekdayIndex } } // MARK: UIPageViewControllerDataSource public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if let selector = viewController as? DaySelectorController { let previousDate = selector.startDate.add(TimeChunk.dateComponents(weeks: -1)) return makeSelectorController(startDate: previousDate) } return nil } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let selector = viewController as? DaySelectorController { let nextDate = selector.startDate.add(TimeChunk.dateComponents(weeks: 1)) return makeSelectorController(startDate: nextDate) } return nil } // MARK: UIPageViewControllerDelegate public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { guard completed else {return} if let selector = pageViewController.viewControllers?.first as? DaySelectorController { selector.selectedIndex = currentWeekdayIndex if let selectedDate = selector.selectedDate { state?.client(client: self, didMoveTo: selectedDate) } } // Deselect all the views but the currently visible one (previousViewControllers as? [DaySelectorController])?.forEach{$0.selectedIndex = -1} } public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { (pendingViewControllers as? [DaySelectorController])?.forEach{$0.updateStyle(style.daySelector)} } } #endif
40.606557
195
0.721706
5d2fd6ec620b27ac789a242d1727422e5b642cf1
1,869
// RUN: %target-run-simple-swift %s // REQUIRES: executable_test protocol P { func f0() -> Int; func f(x:Int, y:Int) -> Int; } protocol Q { func f(x:Int, y:Int) -> Int; } struct S : P, Q, Equatable { // Test that it's possible to denote a zero-arg requirement // (This involved extended the parser for unqualified DeclNames) @_implements(P, f0()) func g0() -> Int { return 10 } // Test that it's possible to implement two different protocols with the // same-named requirements. @_implements(P, f(x:y:)) func g(x:Int, y:Int) -> Int { return 5 } @_implements(Q, f(x:y:)) func h(x:Int, y:Int) -> Int { return 6 } // Test that it's possible to denote an operator requirement // (This involved extended the parser for unqualified DeclNames) @_implements(Equatable, ==(_:_:)) public static func isEqual(_ lhs: S, _ rhs: S) -> Bool { return false } } func call_P_f_generic<T:P>(p:T, x: Int, y: Int) -> Int { return p.f(x:x, y:y) } func call_P_f_existential(p:P, x: Int, y: Int) -> Int { return p.f(x:x, y:y) } func call_Q_f_generic<T:Q>(q:T, x: Int, y: Int) -> Int { return q.f(x:x, y:y) } func call_Q_f_existential(q:Q, x: Int, y: Int) -> Int { return q.f(x:x, y:y) } let s = S() assert(call_P_f_generic(p:s, x:1, y:2) == 5) assert(call_P_f_existential(p:s, x:1, y:2) == 5) assert(call_Q_f_generic(q:s, x:1, y:2) == 6) assert(call_Q_f_existential(q:s, x:1, y:2) == 6) assert(!(s == s)) // Note: at the moment directly calling the member 'f' on the concrete type 'S' // doesn't work, because it's considered ambiguous between the 'g' and 'h' // members (each of which provide an 'f' via the 'P' and 'Q' protocol // conformances), and adding a non-@_implements member 'f' to S makes it win // over _both_ the @_implements members. Unclear if this is correct; I think so? // print(s.f(x:1, y:2))
25.60274
80
0.638844
69e8d3fc0f35c12d9ee1dd5b88320e6c29ebc97c
15,996
// UIImageExtensions.swift - Copyright 2020 SwifterSwift #if canImport(UIKit) import UIKit // MARK: - Properties public extension UIImage { /// SwifterSwift: Size in bytes of UIImage var bytesSize: Int { return jpegData(compressionQuality: 1)?.count ?? 0 } /// SwifterSwift: Size in kilo bytes of UIImage var kilobytesSize: Int { return (jpegData(compressionQuality: 1)?.count ?? 0) / 1024 } /// SwifterSwift: UIImage with .alwaysOriginal rendering mode. var original: UIImage { return withRenderingMode(.alwaysOriginal) } /// SwifterSwift: UIImage with .alwaysTemplate rendering mode. var template: UIImage { return withRenderingMode(.alwaysTemplate) } #if canImport(CoreImage) /// SwifterSwift: Average color for this image func averageColor() -> UIColor? { // https://stackoverflow.com/questions/26330924 guard let ciImage = ciImage ?? CIImage(image: self) else { return nil } // CIAreaAverage returns a single-pixel image that contains the average color for a given region of an image. let parameters = [kCIInputImageKey: ciImage, kCIInputExtentKey: CIVector(cgRect: ciImage.extent)] guard let outputImage = CIFilter(name: "CIAreaAverage", parameters: parameters)?.outputImage else { return nil } // After getting the single-pixel image from the filter extract pixel's RGBA8 data var bitmap = [UInt8](repeating: 0, count: 4) let workingColorSpace: Any = cgImage?.colorSpace ?? NSNull() let context = CIContext(options: [.workingColorSpace: workingColorSpace]) context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: .RGBA8, colorSpace: nil) // Convert pixel data to UIColor return UIColor(red: CGFloat(bitmap[0]) / 255.0, green: CGFloat(bitmap[1]) / 255.0, blue: CGFloat(bitmap[2]) / 255.0, alpha: CGFloat(bitmap[3]) / 255.0) } #endif } // MARK: - Methods public extension UIImage { /// SwifterSwift: Compressed UIImage from original UIImage. /// /// - Parameter quality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality), (default is 0.5). /// - Returns: optional UIImage (if applicable). func compressed(quality: CGFloat = 0.5) -> UIImage? { guard let data = jpegData(compressionQuality: quality) else { return nil } return UIImage(data: data) } /// SwifterSwift: Compressed UIImage data from original UIImage. /// /// - Parameter quality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality), (default is 0.5). /// - Returns: optional Data (if applicable). func compressedData(quality: CGFloat = 0.5) -> Data? { return jpegData(compressionQuality: quality) } /// SwifterSwift: UIImage Cropped to CGRect. /// /// - Parameter rect: CGRect to crop UIImage to. /// - Returns: cropped UIImage func cropped(to rect: CGRect) -> UIImage { guard rect.size.width <= size.width, rect.size.height <= size.height else { return self } let scaledRect = rect.applying(CGAffineTransform(scaleX: scale, y: scale)) guard let image = cgImage?.cropping(to: scaledRect) else { return self } return UIImage(cgImage: image, scale: scale, orientation: imageOrientation) } /// SwifterSwift: UIImage scaled to height with respect to aspect ratio. /// /// - Parameters: /// - toHeight: new height. /// - opaque: flag indicating whether the bitmap is opaque. /// - Returns: optional scaled UIImage (if applicable). func scaled(toHeight: CGFloat, opaque: Bool = false) -> UIImage? { let scale = toHeight / size.height let newWidth = size.width * scale UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: toHeight), opaque, self.scale) draw(in: CGRect(x: 0, y: 0, width: newWidth, height: toHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } /// SwifterSwift: UIImage scaled to width with respect to aspect ratio. /// /// - Parameters: /// - toWidth: new width. /// - opaque: flag indicating whether the bitmap is opaque. /// - Returns: optional scaled UIImage (if applicable). func scaled(toWidth: CGFloat, opaque: Bool = false) -> UIImage? { let scale = toWidth / size.width let newHeight = size.height * scale UIGraphicsBeginImageContextWithOptions(CGSize(width: toWidth, height: newHeight), opaque, self.scale) draw(in: CGRect(x: 0, y: 0, width: toWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } /// SwifterSwift: Creates a copy of the receiver rotated by the given angle. /// /// // Rotate the image by 180° /// image.rotated(by: Measurement(value: 180, unit: .degrees)) /// /// - Parameter angle: The angle measurement by which to rotate the image. /// - Returns: A new image rotated by the given angle. @available(tvOS 10.0, watchOS 3.0, *) func rotated(by angle: Measurement<UnitAngle>) -> UIImage? { let radians = CGFloat(angle.converted(to: .radians).value) let destRect = CGRect(origin: .zero, size: size) .applying(CGAffineTransform(rotationAngle: radians)) let roundedDestRect = CGRect(x: destRect.origin.x.rounded(), y: destRect.origin.y.rounded(), width: destRect.width.rounded(), height: destRect.height.rounded()) UIGraphicsBeginImageContextWithOptions(roundedDestRect.size, false, scale) guard let contextRef = UIGraphicsGetCurrentContext() else { return nil } contextRef.translateBy(x: roundedDestRect.width / 2, y: roundedDestRect.height / 2) contextRef.rotate(by: radians) draw(in: CGRect(origin: CGPoint(x: -size.width / 2, y: -size.height / 2), size: size)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } /// SwifterSwift: Creates a copy of the receiver rotated by the given angle (in radians). /// /// // Rotate the image by 180° /// image.rotated(by: .pi) /// /// - Parameter radians: The angle, in radians, by which to rotate the image. /// - Returns: A new image rotated by the given angle. func rotated(by radians: CGFloat) -> UIImage? { let destRect = CGRect(origin: .zero, size: size) .applying(CGAffineTransform(rotationAngle: radians)) let roundedDestRect = CGRect(x: destRect.origin.x.rounded(), y: destRect.origin.y.rounded(), width: destRect.width.rounded(), height: destRect.height.rounded()) UIGraphicsBeginImageContextWithOptions(roundedDestRect.size, false, scale) guard let contextRef = UIGraphicsGetCurrentContext() else { return nil } contextRef.translateBy(x: roundedDestRect.width / 2, y: roundedDestRect.height / 2) contextRef.rotate(by: radians) draw(in: CGRect(origin: CGPoint(x: -size.width / 2, y: -size.height / 2), size: size)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } /// SwifterSwift: UIImage filled with color /// /// - Parameter color: color to fill image with. /// - Returns: UIImage filled with given color. func filled(withColor color: UIColor) -> UIImage { #if !os(watchOS) if #available(tvOS 10.0, *) { let format = UIGraphicsImageRendererFormat() format.scale = scale let renderer = UIGraphicsImageRenderer(size: size, format: format) return renderer.image { context in color.setFill() context.fill(CGRect(origin: .zero, size: size)) } } #endif UIGraphicsBeginImageContextWithOptions(size, false, scale) color.setFill() guard let context = UIGraphicsGetCurrentContext() else { return self } context.translateBy(x: 0, y: size.height) context.scaleBy(x: 1.0, y: -1.0) context.setBlendMode(CGBlendMode.normal) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) guard let mask = cgImage else { return self } context.clip(to: rect, mask: mask) context.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } /// SwifterSwift: UIImage tinted with color /// /// - Parameters: /// - color: color to tint image with. /// - blendMode: how to blend the tint /// - Returns: UIImage tinted with given color. func tint(_ color: UIColor, blendMode: CGBlendMode, alpha: CGFloat = 1.0) -> UIImage { let drawRect = CGRect(origin: .zero, size: size) #if !os(watchOS) if #available(tvOS 10.0, *) { let format = UIGraphicsImageRendererFormat() format.scale = scale return UIGraphicsImageRenderer(size: size, format: format).image { context in color.setFill() context.fill(drawRect) draw(in: drawRect, blendMode: blendMode, alpha: alpha) } } #endif UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } let context = UIGraphicsGetCurrentContext() color.setFill() context?.fill(drawRect) draw(in: drawRect, blendMode: blendMode, alpha: alpha) return UIGraphicsGetImageFromCurrentImageContext()! } /// SwifterSwift: UImage with background color /// /// - Parameters: /// - backgroundColor: Color to use as background color /// - Returns: UIImage with a background color that is visible where alpha < 1 func withBackgroundColor(_ backgroundColor: UIColor) -> UIImage { #if !os(watchOS) if #available(tvOS 10.0, *) { let format = UIGraphicsImageRendererFormat() format.scale = scale return UIGraphicsImageRenderer(size: size, format: format).image { context in backgroundColor.setFill() context.fill(context.format.bounds) draw(at: .zero) } } #endif UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } backgroundColor.setFill() UIRectFill(CGRect(origin: .zero, size: size)) draw(at: .zero) return UIGraphicsGetImageFromCurrentImageContext()! } /// SwifterSwift: UIImage with rounded corners /// /// - Parameters: /// - radius: corner radius (optional), resulting image will be round if unspecified /// - Returns: UIImage with all corners rounded func withRoundedCorners(radius: CGFloat? = nil) -> UIImage? { let maxRadius = min(size.width, size.height) / 2 let cornerRadius: CGFloat if let radius = radius, radius > 0, radius <= maxRadius { cornerRadius = radius } else { cornerRadius = maxRadius } UIGraphicsBeginImageContextWithOptions(size, false, scale) let rect = CGRect(origin: .zero, size: size) UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip() draw(in: rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } /// SwifterSwift: Base 64 encoded PNG data of the image. /// /// - returns: Base 64 encoded PNG data of the image as a String. func pngBase64String() -> String? { return pngData()?.base64EncodedString() } /// SwifterSwift: Base 64 encoded JPEG data of the image. /// /// - parameter compressionQuality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality). /// - returns: Base 64 encoded JPEG data of the image as a String. func jpegBase64String(compressionQuality: CGFloat) -> String? { return jpegData(compressionQuality: compressionQuality)?.base64EncodedString() } } // MARK: - Initializers public extension UIImage { /// SwifterSwift: Create UIImage from color and size. /// /// - Parameters: /// - color: image fill color. /// - size: image size. convenience init(color: UIColor, size: CGSize) { UIGraphicsBeginImageContextWithOptions(size, false, 1) defer { UIGraphicsEndImageContext() } color.setFill() UIRectFill(CGRect(origin: .zero, size: size)) guard let aCgImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { self.init() return } self.init(cgImage: aCgImage) } /// SwifterSwift: Create a new image from a base 64 string. /// /// - Parameters: /// - base64String: a base-64 `String`, representing the image /// - scale: The scale factor to assume when interpreting the image data created from the base-64 string. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property. convenience init?(base64String: String, scale: CGFloat = 1.0) { guard let data = Data(base64Encoded: base64String) else { return nil } self.init(data: data, scale: scale) } /// SwifterSwift: Create a new image from a URL /// /// - Important: /// Use this method to convert data:// URLs to UIImage objects. /// Don't use this synchronous initializer to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated. /// Instead, for non-file URLs, consider using this in an asynchronous way, using `dataTask(with:completionHandler:)` method of the URLSession class or a library such as `AlamofireImage`, `Kingfisher`, `SDWebImage`, or others to perform asynchronous network image loading. /// - Parameters: /// - url: a `URL`, representing the image location /// - scale: The scale factor to assume when interpreting the image data created from the URL. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property. convenience init?(url: URL, scale: CGFloat = 1.0) throws { let data = try Data(contentsOf: url) self.init(data: data, scale: scale) } } #endif
42.656
322
0.633033
db1d4fb4537e4a8ba3c8a4bbb29588e03ea7f2e4
5,130
// // WriteUserConfigurationPLIST.swift // RsyncUI // // Created by Thomas Evensen on 17/05/2021. // // swiftlint:disable line_length function_body_length cyclomatic_complexity trailing_comma import Foundation final class WriteUserConfigurationPLIST: NamesandPaths { private func convertuserconfiguration() -> [NSMutableDictionary] { var version3Rsync: Int? var detailedlogging: Int? var minimumlogging: Int? var fulllogging: Int? var marknumberofdayssince: String? var haltonerror: Int? var monitornetworkconnection: Int? var array = [NSMutableDictionary]() var json: Int? if SharedReference.shared.rsyncversion3 { version3Rsync = 1 } else { version3Rsync = 0 } if SharedReference.shared.detailedlogging { detailedlogging = 1 } else { detailedlogging = 0 } if SharedReference.shared.minimumlogging { minimumlogging = 1 } else { minimumlogging = 0 } if SharedReference.shared.fulllogging { fulllogging = 1 } else { fulllogging = 0 } if SharedReference.shared.haltonerror { haltonerror = 1 } else { haltonerror = 0 } if SharedReference.shared.monitornetworkconnection { monitornetworkconnection = 1 } else { monitornetworkconnection = 0 } marknumberofdayssince = String(SharedReference.shared.marknumberofdayssince) let dict: NSMutableDictionary = [ DictionaryStrings.version3Rsync.rawValue: version3Rsync ?? 0 as Int, DictionaryStrings.detailedlogging.rawValue: detailedlogging ?? 0 as Int, DictionaryStrings.minimumlogging.rawValue: minimumlogging ?? 0 as Int, DictionaryStrings.fulllogging.rawValue: fulllogging ?? 0 as Int, DictionaryStrings.marknumberofdayssince.rawValue: marknumberofdayssince ?? "5.0", DictionaryStrings.haltonerror.rawValue: haltonerror ?? 0 as Int, DictionaryStrings.monitornetworkconnection.rawValue: monitornetworkconnection ?? 0 as Int, DictionaryStrings.json.rawValue: json ?? 0 as Int, ] if let rsyncpath = SharedReference.shared.localrsyncpath { dict.setObject(rsyncpath, forKey: DictionaryStrings.rsyncPath.rawValue as NSCopying) } if let restorepath = SharedReference.shared.temporarypathforrestore { dict.setObject(restorepath, forKey: DictionaryStrings.restorePath.rawValue as NSCopying) } else { dict.setObject("", forKey: DictionaryStrings.restorePath.rawValue as NSCopying) } if let pathrsyncosx = SharedReference.shared.pathrsyncosx { if pathrsyncosx.isEmpty == false { dict.setObject(pathrsyncosx, forKey: DictionaryStrings.pathrsyncosx.rawValue as NSCopying) } } if let pathrsyncosxsched = SharedReference.shared.pathrsyncosxsched { if pathrsyncosxsched.isEmpty == false { dict.setObject(pathrsyncosxsched, forKey: DictionaryStrings.pathrsyncosxsched.rawValue as NSCopying) } } if let environment = SharedReference.shared.environment { dict.setObject(environment, forKey: DictionaryStrings.environment.rawValue as NSCopying) } if let environmentvalue = SharedReference.shared.environmentvalue { dict.setObject(environmentvalue, forKey: DictionaryStrings.environmentvalue.rawValue as NSCopying) } if let sshkeypathandidentityfile = SharedReference.shared.sshkeypathandidentityfile { dict.setObject(sshkeypathandidentityfile, forKey: DictionaryStrings.sshkeypathandidentityfile.rawValue as NSCopying) } if let sshport = SharedReference.shared.sshport { dict.setObject(sshport, forKey: DictionaryStrings.sshport.rawValue as NSCopying) } array.append(dict) return array } // Function for write data to persistent store @discardableResult func writeNSDictionaryToPersistentStorage(_ array: [NSDictionary]) -> Bool { let dictionary = NSDictionary(object: array, forKey: SharedReference.shared.userconfigkey as NSCopying) if let path = fullpathmacserial { let write = dictionary.write(toFile: path + SharedReference.shared.userconfigplist, atomically: true) if write && SharedReference.shared.menuappisrunning { Notifications().showNotification("Sending reload message to menu app") DistributedNotificationCenter.default().postNotificationName(NSNotification.Name("no.blogspot.RsyncOSX.reload"), object: nil, deliverImmediately: true) } return write } return false } @discardableResult init() { super.init(.configurations) let userconfig = convertuserconfiguration() writeNSDictionaryToPersistentStorage(userconfig) } }
42.75
167
0.664522
799fc7a5e7cdfe8879ef87a8ee23e3648b4d0e6d
750
// // FavoritesAndAttentionBaseTableViewCell.swift // HiPDA // // Created by leizh007 on 2017/7/8. // Copyright © 2017年 HiPDA. All rights reserved. // import UIKit class FavoritesAndAttentionBaseTableViewCell: UITableViewCell { @IBOutlet fileprivate weak var forumNameLabel: UILabel! @IBOutlet fileprivate weak var titleLabel: UILabel! var model: FavoritesAndAttentionBaseModel! { didSet { forumNameLabel.text = model.forumName titleLabel.text = model.title } } override func awakeFromNib() { super.awakeFromNib() titleLabel.preferredMaxLayoutWidth = C.UI.screenWidth - 16.0 } } extension FavoritesAndAttentionBaseTableViewCell: NibLoadableView { }
25.862069
69
0.694667
3946df0201bb44fe7c54423fc5e32002fe47dede
1,440
// // ScryptSwiftTests.swift // ScryptSwiftTests // // Created by 林子帆 on 2018/10/28. // Copyright © 2018 nicholas. All rights reserved. // import XCTest @testable import ScryptSwift class ScryptSwiftTests: 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. var params = ScryptParams() params.n = 1024 params.r = 8 params.p = 16 params.desiredKeyLength = 64 params.salt = "Salt".data(using: .utf8)! let scrypt = Scrypt(params: params) let res = try! scrypt.calculate(password: "12345678") let expected = Data(hexString: "4532db458960204248a708d1131c638b8a0a3a8d406e3e839f2e1d69ba12711d6bcab50837b4007f558401ffa174c4950570cf03ce05e51ee7027cb6212c6e57") XCTAssertEqual(res, expected) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
30
170
0.654167
0a920ab35a9b23dfe8f128d4dcfc3e6ce83714fc
25,888
// // RSANative.swift // BVLinearGradient import Foundation import CommonCrypto typealias SecKeyPerformBlock = (SecKey) -> () class RSAECNative: NSObject { var publicKey: SecKey? var privateKey: SecKey? var keyTag: String? let publicKeyTag: String? let privateKeyTag: String? var publicKeyBits: Data? var keyAlgorithm = KeyAlgorithm.rsa(signatureType: .sha512) public init(keyTag: String?){ self.publicKeyTag = "\(keyTag ?? "").public" self.privateKeyTag = "\(keyTag ?? "").private" self.keyTag = keyTag super.init() } public convenience override init(){ self.init(keyTag: nil) } public func generate(keySize: Int) -> Bool? { var publicKeyParameters: [String: AnyObject] = [ String(kSecAttrAccessible): kSecAttrAccessibleAlways, ] var privateKeyParameters: [String: AnyObject] = [ String(kSecAttrAccessible): kSecAttrAccessibleAlways, ] if((self.keyTag) != nil){ privateKeyParameters[String(kSecAttrIsPermanent)] = kCFBooleanTrue privateKeyParameters[String(kSecAttrApplicationTag)] = self.privateKeyTag as AnyObject publicKeyParameters[String(kSecAttrIsPermanent)] = kCFBooleanTrue publicKeyParameters[String(kSecAttrApplicationTag)] = self.publicKeyTag as AnyObject } #if !arch(i386) && !arch(x86_64) //This only works for Secure Enclave consistign of 256 bit key, note, the signatureType is irrelavent for this check if keyAlgorithm.type == KeyAlgorithm.ec(signatureType: .sha1).type{ let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleAlwaysThisDeviceOnly, .privateKeyUsage, nil)! // Ignore error privateKeyParameters[String(kSecAttrAccessControl)] = access } #endif //Define what type of keys to be generated here var parameters: [String: AnyObject] = [ String(kSecReturnRef): kCFBooleanTrue, kSecPublicKeyAttrs as String: publicKeyParameters as AnyObject, kSecPrivateKeyAttrs as String: privateKeyParameters as AnyObject, ] parameters[String(kSecAttrKeySizeInBits)] = keySize as AnyObject if #available(iOS 10, *) { parameters[String(kSecAttrKeyType)] = keyAlgorithm.secKeyAttrType } else { // Fallback on earlier versions parameters[String(kSecAttrKeyType)] = keyAlgorithm.secKeyAttrTypeiOS9 } #if !arch(i386) && !arch(x86_64) //iOS only allows EC 256 keys to be secured in enclave. This will attempt to allow any EC key in the enclave, assuming iOS will do it outside of the enclave if it doesn't like the key size, note: the signatureType is irrelavent for this check if keyAlgorithm.type == KeyAlgorithm.ec(signatureType: .sha1).type{ parameters[String(kSecAttrTokenID)] = kSecAttrTokenIDSecureEnclave } #endif // TODO: Fix for when not set keytag and dont use keychain if #available(iOS 10.0, *) { var error: Unmanaged<CFError>? self.privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) if self.privateKey == nil { print("Error occured: keys weren't created") return nil } self.publicKey = SecKeyCopyPublicKey(self.privateKey!) } else { // Fallback on earlier versions let result = SecKeyGeneratePair(parameters as CFDictionary, &publicKey, &privateKey) if result != errSecSuccess{ print("Error occured: \(result)") return nil } } guard self.publicKey != nil else { print( "Error in setUp(). PublicKey shouldn't be nil") return nil } guard self.privateKey != nil else{ print("Error in setUp(). PrivateKey shouldn't be nil") return nil } return true } public func generateEC() -> Bool? { self.keyAlgorithm = KeyAlgorithm.ec(signatureType: .sha256) // ios support 256 return self.generate(keySize: 256); } public func generateCSR(CN: String?, withAlgorithm: String) -> String? { self.setAlgorithm(algorithm: withAlgorithm) // self.privateKey = self.getPrivateKeyChain(tag: self.privateKeyTag!) self.publicKeyBits = self.getPublicKeyChainData(tag: self.publicKeyTag!) var csrString: String? let csrBlock: SecKeyPerformBlock = { privateKey in let csr = CertificateSigningRequest(commonName: CN, organizationName: nil, organizationUnitName: nil, countryName: nil, stateOrProvinceName: nil, localityName: nil, keyAlgorithm: self.keyAlgorithm) csrString = csr.buildCSRAndReturnString(self.publicKeyBits!, privateKey: privateKey) } if ((self.keyTag) != nil) { self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!, block: csrBlock) } else { csrBlock(self.privateKey!); } return csrString } private func getPublicKeyChainData(tag : String) -> Data? { //Ask keychain to provide the publicKey in bits var query: [String: AnyObject] = [ String(kSecClass): kSecClassKey, String(kSecAttrApplicationTag): self.publicKeyTag as AnyObject, String(kSecReturnData): kCFBooleanTrue ] if #available(iOS 10, *) { query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrType } else { // Fallback on earlier versions query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrTypeiOS9 } var tempPublicKeyBits:AnyObject? let result = SecItemCopyMatching(query as CFDictionary, &tempPublicKeyBits) switch result { case errSecSuccess: guard let keyBits = tempPublicKeyBits as? Data else { print("error in: convert to publicKeyBits") return nil } return keyBits default: print("error in: convert to publicKeyBits") return nil } } private func setAlgorithm(algorithm: String) -> Void { switch algorithm { case "SHA256withRSA": self.keyAlgorithm = .rsa(signatureType: .sha256) case "SHA512withRSA": self.keyAlgorithm = .rsa(signatureType: .sha512) case "SHA1withRSA": self.keyAlgorithm = .rsa(signatureType: .sha1) case "SHA256withECDSA": self.keyAlgorithm = .ec(signatureType: .sha256) case "SHA512withECDSA": self.keyAlgorithm = .ec(signatureType: .sha512) case "SHA1withECDSA": self.keyAlgorithm = .ec(signatureType: .sha1) default: self.keyAlgorithm = .rsa(signatureType: .sha1) } } public func deletePrivateKey(){ var query: [String: AnyObject] = [ String(kSecClass) : kSecClassKey, String(kSecAttrApplicationTag): self.privateKeyTag as AnyObject, String(kSecReturnRef) : true as AnyObject ] if #available(iOS 10, *) { query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrType } else { // Fallback on earlier versions query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrTypeiOS9 } let result = SecItemDelete(query as CFDictionary) if result != errSecSuccess{ print("Error delete private key: \(result)") // return nil } } public func encodedPublicKeyRSA() -> String? { if ((self.keyTag) != nil) { var encodedPublicKey: String? self.performWithPublicKeyTag(tag: self.publicKeyTag!) { (publicKey) in encodedPublicKey = self.externalRepresentationForPublicKeyRSA(key: publicKey) } return encodedPublicKey; } if(self.publicKey == nil) { return nil } return self.externalRepresentationForPublicKeyRSA(key: self.publicKey!) } public func encodedPublicKeyDER() -> String? { if ((self.keyTag) != nil) { var encodedPublicKey: String? self.performWithPublicKeyTag(tag: self.publicKeyTag!) { (publicKey) in encodedPublicKey = self.externalRepresentationForPublicKeyDER(key: publicKey) } return encodedPublicKey; } if(self.publicKey == nil) { return nil } return self.externalRepresentationForPublicKeyDER(key: self.publicKey!) } public func encodedPublicKey() -> String? { if ((self.keyTag) != nil) { var encodedPublicKey: String? self.performWithPublicKeyTag(tag: self.publicKeyTag!) { (publicKey) in encodedPublicKey = self.externalRepresentationForPublicKey(key: publicKey) } return encodedPublicKey; } if(self.publicKey == nil) { return nil } return self.externalRepresentationForPublicKey(key: self.publicKey!) } public func encodedPrivateKeyRSA() -> String? { if ((self.keyTag) != nil) { var encodedPrivateKey: String? self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!) { (privateKey) in encodedPrivateKey = self.externalRepresentationForPrivateKeyRSA(key: privateKey) } return encodedPrivateKey; } if(self.privateKey == nil) { return nil } return self.externalRepresentationForPrivateKeyRSA(key: self.privateKey!) } public func encodedPrivateKeyDER() -> String? { if ((self.keyTag) != nil) { var encodedPrivateKey: String? self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!) { (privateKey) in encodedPrivateKey = self.externalRepresentationForPrivateKeyDER(key: privateKey) } return encodedPrivateKey; } if(self.privateKey == nil) { return nil } return self.externalRepresentationForPrivateKeyDER(key: self.privateKey!) } public func setPublicKey(publicKey: String) -> Bool? { guard let publicKeyStr = RSAECFormatter.stripHeaders(pemString: publicKey) else { return false } let query: [String: AnyObject] = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecAttrKeyClass): kSecAttrKeyClassPublic, ] print(publicKeyStr, "publicKeyStrpublicKeyStr") var error: Unmanaged<CFError>? guard let data = Data(base64Encoded: publicKeyStr, options: .ignoreUnknownCharacters) else { return false } print(data, "datadatadata") if #available(iOS 10.0, *) { guard let key = SecKeyCreateWithData(data as CFData, query as CFDictionary, &error) else { return false } self.publicKey = key return true } else { // Fallback on earlier versions } return false } public func setPrivateKey(privateKey: String) -> Bool? { guard let privateKeyStr = RSAECFormatter.stripHeaders(pemString: privateKey) else { return nil } let query: [String: AnyObject] = [ String(kSecAttrKeyType): kSecAttrKeyTypeRSA, String(kSecAttrKeyClass): kSecAttrKeyClassPrivate, ] var error: Unmanaged<CFError>? guard let data = Data(base64Encoded: privateKeyStr, options: .ignoreUnknownCharacters) else { return nil } if #available(iOS 10.0, *) { guard let key = SecKeyCreateWithData(data as CFData, query as CFDictionary, &error) else { return nil } self.privateKey = key return true } else { // Fallback on earlier versions } return nil } public func encrypt64(message: String) -> String? { guard let data = Data(base64Encoded: message, options: .ignoreUnknownCharacters) else { return nil } var limit = (2048 / 8) - 11 var limitTmp = limit var position = 0 var finalString : Data? = nil while (position < data.count) { if (data.count - position < limit) { limitTmp = data.count } let encrypted = self._encrypt(data: data[position..<limitTmp]) finalString = finalString == nil ? encrypted! : finalString! + encrypted! position += limit limitTmp += limit } return finalString!.base64EncodedString(options: .lineLength64Characters) } public func encrypt(message: String) -> String? { guard let data = message.data(using: .utf8) else { return nil } let encrypted = self._encrypt(data: data) return encrypted?.base64EncodedString(options: .lineLength64Characters) } public func _encrypt(data: Data) -> Data? { var cipherText: Data? // Closures let encryptor:SecKeyPerformBlock = { publicKey in if #available(iOS 10.0, *) { let canEncrypt = SecKeyIsAlgorithmSupported(publicKey, .encrypt, .rsaEncryptionPKCS1) if(canEncrypt){ var error: Unmanaged<CFError>? cipherText = SecKeyCreateEncryptedData(publicKey, .rsaEncryptionPKCS1, data as CFData, &error) as Data? } } else { // Fallback on earlier versions }; } if ((self.keyTag) != nil) { self.performWithPublicKeyTag(tag: self.publicKeyTag!, block: encryptor) } else { encryptor(self.publicKey!); } return cipherText; } public func decrypt64(message: String) -> String? { guard let data = Data(base64Encoded: message, options: .ignoreUnknownCharacters) else { return nil } let decrypted = self._decrypt(data: data) return decrypted?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) } public func decrypt(message: String) -> String? { guard let data = Data(base64Encoded: message, options: .ignoreUnknownCharacters) else { return nil } var limit = 2048 / 8 var limitTmp = limit var position = 0 var finalString = "" while (position < data.count) { if (data.count - position < limit) { limitTmp = data.count - position } let decrypted = self._decrypt(data: data[position..<limitTmp]) let descryptedString = String(data: decrypted!, encoding: String.Encoding.utf8) finalString += descryptedString ?? "" position += limit limitTmp += limit } return finalString } private func _decrypt(data: Data) -> Data? { var clearText: Data? let decryptor: SecKeyPerformBlock = {privateKey in if #available(iOS 10.0, *) { let canEncrypt = SecKeyIsAlgorithmSupported(privateKey, .decrypt, .rsaEncryptionPKCS1) if(canEncrypt){ var error: Unmanaged<CFError>? clearText = SecKeyCreateDecryptedData(privateKey, .rsaEncryptionPKCS1, data as CFData, &error) as Data? } } else { // Fallback on earlier versions }; } if ((self.keyTag) != nil) { self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!, block: decryptor) } else { decryptor(self.privateKey!); } return clearText } public func sign64(b64message: String, withAlgorithm: String) -> String? { guard let data = Data(base64Encoded: b64message, options: .ignoreUnknownCharacters) else { return nil } let encodedSignature = self._sign(messageBytes: data, withAlgorithm: withAlgorithm, withEncodeOption: .lineLength64Characters) return encodedSignature } public func sign(message: String, withAlgorithm: String, withEncodeOption: NSData.Base64EncodingOptions) -> String? { guard let data = message.data(using: .utf8) else { return nil } let encodedSignature = self._sign(messageBytes: data, withAlgorithm: withAlgorithm, withEncodeOption: withEncodeOption) return encodedSignature } private func _sign(messageBytes: Data, withAlgorithm: String, withEncodeOption: NSData.Base64EncodingOptions) -> String? { self.setAlgorithm(algorithm: withAlgorithm) var encodedSignature: String? let signer: SecKeyPerformBlock = { privateKey in if #available(iOS 11, *) { // Build signature - step 1: SHA1 hash // Build signature - step 2: Sign hash // var signature: Data? = nil var error: Unmanaged<CFError>? let signature = SecKeyCreateSignature(privateKey, self.keyAlgorithm.signatureAlgorithm, messageBytes as CFData, &error) as Data? if error != nil{ print("Error in creating signature: \(error!.takeRetainedValue())") } encodedSignature = signature!.base64EncodedString(options: withEncodeOption) } else { // TODO: fix and test // Fallback on earlier versions // Build signature - step 1: SHA1 hash var signature = [UInt8](repeating: 0, count: self.keyAlgorithm.availableKeySizes.last!) var signatureLen:Int = signature.count var messageDataBytes = [UInt8](repeating: 0, count: messageBytes.count) messageBytes.copyBytes(to: &messageDataBytes, count: messageBytes.count) var digest = [UInt8](repeating: 0, count: self.keyAlgorithm.digestLength) let padding = self.keyAlgorithm.padding switch self.keyAlgorithm { case .rsa(signatureType: .sha1), .ec(signatureType: .sha1): var SHA1 = CC_SHA1_CTX() CC_SHA1_Init(&SHA1) CC_SHA1_Update(&SHA1, messageDataBytes, CC_LONG(messageBytes.count)) CC_SHA1_Final(&digest, &SHA1) case .rsa(signatureType: .sha256), .ec(signatureType: .sha256): var SHA256 = CC_SHA256_CTX() CC_SHA256_Init(&SHA256) CC_SHA256_Update(&SHA256, messageDataBytes, CC_LONG(messageBytes.count)) CC_SHA256_Final(&digest, &SHA256) case .rsa(signatureType: .sha512), .ec(signatureType: .sha512): var SHA512 = CC_SHA512_CTX() CC_SHA512_Init(&SHA512) CC_SHA512_Update(&SHA512, messageDataBytes, CC_LONG(messageBytes.count)) CC_SHA512_Final(&digest, &SHA512) } // Build signature - step 2: Sign hash let result = SecKeyRawSign(privateKey, padding, digest, digest.count, &signature, &signatureLen) if result != errSecSuccess{ print("Error signing: \(result)") return } var signData = Data() let zero:UInt8 = 0 signData.append(zero) signData.append(signature, count: signatureLen) encodedSignature = signData.base64EncodedString(options: withEncodeOption) } } if ((self.keyTag) != nil) { self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!, block: signer) } else { signer(self.privateKey!); } return encodedSignature } public func verify64(encodedSignature: String, withMessage: String, withAlgorithm: String) -> Bool? { guard let messageBytes = Data(base64Encoded: encodedSignature, options: .ignoreUnknownCharacters) else { return nil } guard let signatureBytes = Data(base64Encoded: withMessage, options: .ignoreUnknownCharacters) else { return nil } return self._verify(signatureBytes: signatureBytes, withMessage: messageBytes, withAlgorithm: withAlgorithm) } public func verify(encodedSignature: String, withMessage: String, withAlgorithm: String) -> Bool? { guard let messageBytes = withMessage.data(using: .utf8) else { return nil } guard let signatureBytes = Data(base64Encoded: encodedSignature, options: .ignoreUnknownCharacters) else { return nil } return self._verify(signatureBytes:signatureBytes , withMessage: messageBytes, withAlgorithm: withAlgorithm) } private func _verify(signatureBytes: Data, withMessage: Data, withAlgorithm: String) -> Bool? { var result = false // Closures let verifier: SecKeyPerformBlock = { publicKey in if #available(iOS 10.0, *) { var error: Unmanaged<CFError>? result = SecKeyVerifySignature(publicKey, self.keyAlgorithm.signatureAlgorithm, withMessage as CFData, signatureBytes as CFData, &error) } else { // Fallback on earlier versions } } if ((self.keyTag) != nil) { self.performWithPublicKeyTag(tag: self.publicKeyTag!, block: verifier) } else { verifier(self.publicKey!); } return result } private func performWithPrivateKeyTag(keyTag: String, block: SecKeyPerformBlock){ var query: [String: AnyObject] = [ String(kSecClass) : kSecClassKey, String(kSecAttrApplicationTag): keyTag as AnyObject, String(kSecReturnRef) : true as AnyObject ] if #available(iOS 10, *) { query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrType } else { // Fallback on earlier versions query[String(kSecAttrKeyType)] = self.keyAlgorithm.secKeyAttrTypeiOS9 } var result : AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &result) if status == errSecSuccess { print("\(keyTag) Key existed!") block((result as! SecKey?)!) } } private func performWithPublicKeyTag(tag: String, block: SecKeyPerformBlock){ self.performWithPrivateKeyTag(keyTag: self.privateKeyTag!) { (privateKey) in if #available(iOS 10.0, *) { let publicKey = SecKeyCopyPublicKey(privateKey) block(publicKey!) } else { // Fallback on earlier versions } } } private func externalRepresentationForPublicKeyRSA(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } return RSAECFormatter.PEMFormattedPublicKeyRSA(publicKeyData: data) } private func externalRepresentationForPublicKey(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } return RSAECFormatter.PEMFormattedPublicKey(publicKeyData: data) } private func externalRepresentationForPublicKeyDER(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } let convertedData = RSAKeyEncoding().convertToX509EncodedKey(data) return RSAECFormatter.PEMFormattedPublicKey(publicKeyData: convertedData) } private func externalRepresentationForPrivateKeyRSA(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } return RSAECFormatter.PEMFormattedPrivateKeyRSA(privateKeyData: data) } private func externalRepresentationForPrivateKeyDER(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } let convertedData = RSAKeyEncoding().convertToX509EncodedKey(data) return RSAECFormatter.PEMFormattedPrivateKey(privateKeyData: convertedData) } private func externalRepresentationForPrivateKey(key: SecKey) -> String? { guard let data = self.dataForKey(key: key) else { return nil } return RSAECFormatter.PEMFormattedPrivateKey(privateKeyData: data) } private func dataForKey(key: SecKey) -> Data? { var error: Unmanaged<CFError>? var keyData: Data? if #available(iOS 10.0, *) { keyData = SecKeyCopyExternalRepresentation(key, &error) as Data? } else { // Fallback on earlier versions } if (keyData == nil) { print("error in dataForKey") return nil } return keyData; } }
40.704403
250
0.590776
e5c6b8d124440a0c1873ca8c1f205cd145ecefac
738
// // Icon.swift // ApiCore // // Created by Ondrej Rafaj on 17/05/2018. // import Foundation @_exported import SwiftGD /// Icon size public enum IconSize: Int, Codable { /// Favicon, 16x16 px case favicon = 16 /// 64x64 px case at1x = 64 /// 128x128 px case at2x = 128 /// 192x192 px case at3x = 192 /// 256x256 px case regular = 256 /// 512x512 px case large = 512 /// Size public var size: Size { return Size(width: rawValue, height: rawValue) } /// All values public static let all: [IconSize] = [ .favicon, .at1x, .at2x, .at3x, .regular, .large ] }
14.76
54
0.504065
5d069c417b3504c86034ef23bd9e0794998c9573
30,170
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIO import NIOHTTP1 import NIOFoundationCompat import Dispatch // MARK: Test Harness var warning: String = "" assert({ print("======================================================") print("= YOU ARE RUNNING NIOPerformanceTester IN DEBUG MODE =") print("======================================================") warning = " <<< DEBUG MODE >>>" return true }()) public func measure(_ fn: () throws -> Int) rethrows -> [Double] { func measureOne(_ fn: () throws -> Int) rethrows -> Double { let start = DispatchTime.now().uptimeNanoseconds _ = try fn() let end = DispatchTime.now().uptimeNanoseconds return Double(end - start) / Double(TimeAmount.seconds(1).nanoseconds) } _ = try measureOne(fn) /* pre-heat and throw away */ var measurements = Array(repeating: 0.0, count: 10) for i in 0..<10 { measurements[i] = try measureOne(fn) } return measurements } let limitSet = CommandLine.arguments.dropFirst() public func measureAndPrint(desc: String, fn: () throws -> Int) rethrows -> Void { if limitSet.isEmpty || limitSet.contains(desc) { print("measuring\(warning): \(desc): ", terminator: "") let measurements = try measure(fn) print(measurements.reduce(into: "") { $0.append("\($1), ") }) } else { print("skipping '\(desc)', limit set = \(limitSet)") } } // MARK: Utilities private final class SimpleHTTPServer: ChannelInboundHandler { typealias InboundIn = HTTPServerRequestPart typealias OutboundOut = HTTPServerResponsePart private var files: [String] = Array() private var seenEnd: Bool = false private var sentEnd: Bool = false private var isOpen: Bool = true private let cachedHead: HTTPResponseHead private let cachedBody: [UInt8] private let bodyLength = 1024 private let numberOfAdditionalHeaders = 10 init() { var head = HTTPResponseHead(version: HTTPVersion(major: 1, minor: 1), status: .ok) head.headers.add(name: "Content-Length", value: "\(self.bodyLength)") for i in 0..<self.numberOfAdditionalHeaders { head.headers.add(name: "X-Random-Extra-Header", value: "\(i)") } self.cachedHead = head var body: [UInt8] = [] body.reserveCapacity(self.bodyLength) for i in 0..<self.bodyLength { body.append(UInt8(i % Int(UInt8.max))) } self.cachedBody = body } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { if case .head(let req) = self.unwrapInboundIn(data) { switch req.uri { case "/perf-test-1": var buffer = context.channel.allocator.buffer(capacity: self.cachedBody.count) buffer.writeBytes(self.cachedBody) context.write(self.wrapOutboundOut(.head(self.cachedHead)), promise: nil) context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) return case "/perf-test-2": var req = HTTPResponseHead(version: HTTPVersion(major: 1, minor: 1), status: .ok) for i in 1...8 { req.headers.add(name: "X-ResponseHeader-\(i)", value: "foo") } req.headers.add(name: "content-length", value: "0") context.write(self.wrapOutboundOut(.head(req)), promise: nil) context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) return default: fatalError("unknown uri \(req.uri)") } } } } let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) defer { try! group.syncShutdownGracefully() } let serverChannel = try ServerBootstrap(group: group) .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) .childChannelInitializer { channel in channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true).flatMap { channel.pipeline.addHandler(SimpleHTTPServer()) } }.bind(host: "127.0.0.1", port: 0).wait() defer { try! serverChannel.close().wait() } var head = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/perf-test-1") head.headers.add(name: "Host", value: "localhost") final class RepeatedRequests: ChannelInboundHandler { typealias InboundIn = HTTPClientResponsePart typealias OutboundOut = HTTPClientRequestPart private let numberOfRequests: Int private var remainingNumberOfRequests: Int private var doneRequests = 0 private let isDonePromise: EventLoopPromise<Int> init(numberOfRequests: Int, eventLoop: EventLoop) { self.remainingNumberOfRequests = numberOfRequests self.numberOfRequests = numberOfRequests self.isDonePromise = eventLoop.makePromise() } func wait() throws -> Int { let reqs = try self.isDonePromise.futureResult.wait() precondition(reqs == self.numberOfRequests) return reqs } func errorCaught(context: ChannelHandlerContext, error: Error) { context.channel.close(promise: nil) self.isDonePromise.fail(error) } func channelRead(context: ChannelHandlerContext, data: NIOAny) { let reqPart = self.unwrapInboundIn(data) if case .end(nil) = reqPart { if self.remainingNumberOfRequests <= 0 { context.channel.close().map { self.doneRequests }.cascade(to: self.isDonePromise) } else { self.doneRequests += 1 self.remainingNumberOfRequests -= 1 context.write(self.wrapOutboundOut(.head(head)), promise: nil) context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) } } } } private func someString(size: Int) -> String { var s = "A" for f in 1..<size { s += String("\(f)".first!) } return s } // MARK: Performance Tests measureAndPrint(desc: "write_http_headers") { var headers: [(String, String)] = [] for i in 1..<10 { headers.append(("\(i)", "\(i)")) } var val = 0 for _ in 0..<100_000 { let headers = HTTPHeaders(headers) val += headers.underestimatedCount } return val } measureAndPrint(desc: "bytebuffer_write_12MB_short_string_literals") { let bufferSize = 12 * 1024 * 1024 var buffer = ByteBufferAllocator().buffer(capacity: bufferSize) for _ in 0 ..< 5 { buffer.clear() for _ in 0 ..< (bufferSize / 4) { buffer.writeString("abcd") } } let readableBytes = buffer.readableBytes precondition(readableBytes == bufferSize) return readableBytes } measureAndPrint(desc: "bytebuffer_write_12MB_short_calculated_strings") { let bufferSize = 12 * 1024 * 1024 var buffer = ByteBufferAllocator().buffer(capacity: bufferSize) let s = someString(size: 4) for _ in 0 ..< 5 { buffer.clear() for _ in 0 ..< (bufferSize / 4) { buffer.writeString(s) } } let readableBytes = buffer.readableBytes precondition(readableBytes == bufferSize) return readableBytes } measureAndPrint(desc: "bytebuffer_write_12MB_medium_string_literals") { let bufferSize = 12 * 1024 * 1024 var buffer = ByteBufferAllocator().buffer(capacity: bufferSize) for _ in 0 ..< 10 { buffer.clear() for _ in 0 ..< (bufferSize / 24) { buffer.writeString("012345678901234567890123") } } let readableBytes = buffer.readableBytes precondition(readableBytes == bufferSize) return readableBytes } measureAndPrint(desc: "bytebuffer_write_12MB_medium_calculated_strings") { let bufferSize = 12 * 1024 * 1024 var buffer = ByteBufferAllocator().buffer(capacity: bufferSize) let s = someString(size: 24) for _ in 0 ..< 10 { buffer.clear() for _ in 0 ..< (bufferSize / 24) { buffer.writeString(s) } } let readableBytes = buffer.readableBytes precondition(readableBytes == bufferSize) return readableBytes } measureAndPrint(desc: "bytebuffer_write_12MB_large_calculated_strings") { let bufferSize = 12 * 1024 * 1024 var buffer = ByteBufferAllocator().buffer(capacity: bufferSize) let s = someString(size: 1024 * 1024) for _ in 0 ..< 10 { buffer.clear() for _ in 0 ..< 12 { buffer.writeString(s) } } let readableBytes = buffer.readableBytes precondition(readableBytes == bufferSize) return readableBytes } measureAndPrint(desc: "bytebuffer_lots_of_rw") { let dispatchData = ("A" as StaticString).withUTF8Buffer { ptr in DispatchData(bytes: UnsafeRawBufferPointer(start: UnsafeRawPointer(ptr.baseAddress), count: ptr.count)) } var buffer = ByteBufferAllocator().buffer(capacity: 7 * 1024 * 1024) @inline(never) func doWrites(buffer: inout ByteBuffer) { /* all of those should be 0 allocations */ // buffer.writeBytes(foundationData) // see SR-7542 buffer.writeBytes([0x41]) buffer.writeBytes(dispatchData) buffer.writeBytes("A".utf8) buffer.writeString("A") buffer.writeStaticString("A") buffer.writeInteger(0x41, as: UInt8.self) } @inline(never) func doReads(buffer: inout ByteBuffer) { /* these ones are zero allocations */ let val = buffer.readInteger(as: UInt8.self) precondition(0x41 == val, "\(val!)") var slice = buffer.readSlice(length: 1) let sliceVal = slice!.readInteger(as: UInt8.self) precondition(0x41 == sliceVal, "\(sliceVal!)") buffer.withUnsafeReadableBytes { ptr in precondition(ptr[0] == 0x41) } /* those down here should be one allocation each */ let arr = buffer.readBytes(length: 1) precondition([0x41] == arr!, "\(arr!)") let str = buffer.readString(length: 1) precondition("A" == str, "\(str!)") } for _ in 0 ..< 1024*1024 { doWrites(buffer: &buffer) doReads(buffer: &buffer) } return buffer.readableBytes } func writeExampleHTTPResponseAsString(buffer: inout ByteBuffer) { buffer.writeString("HTTP/1.1 200 OK") buffer.writeString("\r\n") buffer.writeString("Connection") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("close") buffer.writeString("\r\n") buffer.writeString("Proxy-Connection") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("close") buffer.writeString("\r\n") buffer.writeString("Via") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("HTTP/1.1 localhost (IBM-PROXY-WTE)") buffer.writeString("\r\n") buffer.writeString("Date") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("Tue, 08 May 2018 13:42:56 GMT") buffer.writeString("\r\n") buffer.writeString("Server") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("Apache/2.2.15 (Red Hat)") buffer.writeString("\r\n") buffer.writeString("Strict-Transport-Security") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("max-age=15768000; includeSubDomains") buffer.writeString("\r\n") buffer.writeString("Last-Modified") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("Tue, 08 May 2018 13:39:13 GMT") buffer.writeString("\r\n") buffer.writeString("ETag") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("357031-1809-56bb1e96a6240") buffer.writeString("\r\n") buffer.writeString("Accept-Ranges") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("bytes") buffer.writeString("\r\n") buffer.writeString("Content-Length") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("6153") buffer.writeString("\r\n") buffer.writeString("Content-Type") buffer.writeString(":") buffer.writeString(" ") buffer.writeString("text/html; charset=UTF-8") buffer.writeString("\r\n") buffer.writeString("\r\n") } func writeExampleHTTPResponseAsStaticString(buffer: inout ByteBuffer) { buffer.writeStaticString("HTTP/1.1 200 OK") buffer.writeStaticString("\r\n") buffer.writeStaticString("Connection") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("close") buffer.writeStaticString("\r\n") buffer.writeStaticString("Proxy-Connection") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("close") buffer.writeStaticString("\r\n") buffer.writeStaticString("Via") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("HTTP/1.1 localhost (IBM-PROXY-WTE)") buffer.writeStaticString("\r\n") buffer.writeStaticString("Date") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("Tue, 08 May 2018 13:42:56 GMT") buffer.writeStaticString("\r\n") buffer.writeStaticString("Server") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("Apache/2.2.15 (Red Hat)") buffer.writeStaticString("\r\n") buffer.writeStaticString("Strict-Transport-Security") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("max-age=15768000; includeSubDomains") buffer.writeStaticString("\r\n") buffer.writeStaticString("Last-Modified") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("Tue, 08 May 2018 13:39:13 GMT") buffer.writeStaticString("\r\n") buffer.writeStaticString("ETag") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("357031-1809-56bb1e96a6240") buffer.writeStaticString("\r\n") buffer.writeStaticString("Accept-Ranges") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("bytes") buffer.writeStaticString("\r\n") buffer.writeStaticString("Content-Length") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("6153") buffer.writeStaticString("\r\n") buffer.writeStaticString("Content-Type") buffer.writeStaticString(":") buffer.writeStaticString(" ") buffer.writeStaticString("text/html; charset=UTF-8") buffer.writeStaticString("\r\n") buffer.writeStaticString("\r\n") } measureAndPrint(desc: "bytebuffer_write_http_response_ascii_only_as_string") { var buffer = ByteBufferAllocator().buffer(capacity: 16 * 1024) for _ in 0..<20_000 { writeExampleHTTPResponseAsString(buffer: &buffer) buffer.writeString(htmlASCIIOnly) buffer.clear() } return buffer.readableBytes } measureAndPrint(desc: "bytebuffer_write_http_response_ascii_only_as_staticstring") { var buffer = ByteBufferAllocator().buffer(capacity: 16 * 1024) for _ in 0..<20_000 { writeExampleHTTPResponseAsStaticString(buffer: &buffer) buffer.writeStaticString(htmlASCIIOnlyStaticString) buffer.clear() } return buffer.readableBytes } measureAndPrint(desc: "bytebuffer_write_http_response_some_nonascii_as_string") { var buffer = ByteBufferAllocator().buffer(capacity: 16 * 1024) for _ in 0..<20_000 { writeExampleHTTPResponseAsString(buffer: &buffer) buffer.writeString(htmlMostlyASCII) buffer.clear() } return buffer.readableBytes } measureAndPrint(desc: "bytebuffer_write_http_response_some_nonascii_as_staticstring") { var buffer = ByteBufferAllocator().buffer(capacity: 16 * 1024) for _ in 0..<20_000 { writeExampleHTTPResponseAsStaticString(buffer: &buffer) buffer.writeStaticString(htmlMostlyASCIIStaticString) buffer.clear() } return buffer.readableBytes } try measureAndPrint(desc: "no-net_http1_10k_reqs_1_conn") { final class MeasuringHandler: ChannelDuplexHandler { typealias InboundIn = Never typealias InboundOut = ByteBuffer typealias OutboundIn = ByteBuffer private var requestBuffer: ByteBuffer! private var expectedResponseBuffer: ByteBuffer? private var remainingNumberOfRequests: Int private let completionHandler: (Int) -> Void private let numberOfRequests: Int init(numberOfRequests: Int, completionHandler: @escaping (Int) -> Void) { self.completionHandler = completionHandler self.numberOfRequests = numberOfRequests self.remainingNumberOfRequests = numberOfRequests } func handlerAdded(context: ChannelHandlerContext) { self.requestBuffer = context.channel.allocator.buffer(capacity: 512) self.requestBuffer.writeString(""" GET /perf-test-2 HTTP/1.1\r Host: example.com\r X-Some-Header-1: foo\r X-Some-Header-2: foo\r X-Some-Header-3: foo\r X-Some-Header-4: foo\r X-Some-Header-5: foo\r X-Some-Header-6: foo\r X-Some-Header-7: foo\r X-Some-Header-8: foo\r\n\r\n """) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { var buf = self.unwrapOutboundIn(data) if self.expectedResponseBuffer == nil { self.expectedResponseBuffer = buf } precondition(buf == self.expectedResponseBuffer, "got \(buf.readString(length: buf.readableBytes)!)") let channel = context.channel self.remainingNumberOfRequests -= 1 if self.remainingNumberOfRequests > 0 { context.eventLoop.execute { self.kickOff(channel: channel) } } else { self.completionHandler(self.numberOfRequests) } } func kickOff(channel: Channel) -> Void { try! (channel as! EmbeddedChannel).writeInbound(self.requestBuffer) } } let eventLoop = EmbeddedEventLoop() let channel = EmbeddedChannel(handler: nil, loop: eventLoop) var done = false var requestsDone = -1 let measuringHandler = MeasuringHandler(numberOfRequests: 10_000) { reqs in requestsDone = reqs done = true } try channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true, withErrorHandling: true).flatMap { channel.pipeline.addHandler(SimpleHTTPServer()) }.flatMap { channel.pipeline.addHandler(measuringHandler, position: .first) }.wait() measuringHandler.kickOff(channel: channel) while !done { eventLoop.run() } _ = try channel.finish() precondition(requestsDone == 10_000) return requestsDone } measureAndPrint(desc: "http1_10k_reqs_1_conn") { let repeatedRequestsHandler = RepeatedRequests(numberOfRequests: 10_000, eventLoop: group.next()) let clientChannel = try! ClientBootstrap(group: group) .channelInitializer { channel in channel.pipeline.addHTTPClientHandlers().flatMap { channel.pipeline.addHandler(repeatedRequestsHandler) } } .connect(to: serverChannel.localAddress!) .wait() clientChannel.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil) try! clientChannel.writeAndFlush(NIOAny(HTTPClientRequestPart.end(nil))).wait() return try! repeatedRequestsHandler.wait() } measureAndPrint(desc: "http1_10k_reqs_100_conns") { var reqs: [Int] = [] let reqsPerConn = 100 reqs.reserveCapacity(reqsPerConn) for _ in 0..<reqsPerConn { let repeatedRequestsHandler = RepeatedRequests(numberOfRequests: 100, eventLoop: group.next()) let clientChannel = try! ClientBootstrap(group: group) .channelInitializer { channel in channel.pipeline.addHTTPClientHandlers().flatMap { channel.pipeline.addHandler(repeatedRequestsHandler) } } .connect(to: serverChannel.localAddress!) .wait() clientChannel.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil) try! clientChannel.writeAndFlush(NIOAny(HTTPClientRequestPart.end(nil))).wait() reqs.append(try! repeatedRequestsHandler.wait()) } return reqs.reduce(0, +) / reqsPerConn } measureAndPrint(desc: "future_whenallsucceed_100k_immediately_succeeded_off_loop") { let loop = group.next() let expected = Array(0..<100_000) let futures = expected.map { loop.makeSucceededFuture($0) } let allSucceeded = try! EventLoopFuture.whenAllSucceed(futures, on: loop).wait() return allSucceeded.count } measureAndPrint(desc: "future_whenallsucceed_100k_immediately_succeeded_on_loop") { let loop = group.next() let expected = Array(0..<100_000) let allSucceeded = try! loop.makeSucceededFuture(()).flatMap { _ -> EventLoopFuture<[Int]> in let futures = expected.map { loop.makeSucceededFuture($0) } return EventLoopFuture.whenAllSucceed(futures, on: loop) }.wait() return allSucceeded.count } measureAndPrint(desc: "future_whenallsucceed_100k_deferred_off_loop") { let loop = group.next() let expected = Array(0..<100_000) let promises = expected.map { _ in loop.makePromise(of: Int.self) } let allSucceeded = EventLoopFuture.whenAllSucceed(promises.map { $0.futureResult }, on: loop) for (index, promise) in promises.enumerated() { promise.succeed(index) } return try! allSucceeded.wait().count } measureAndPrint(desc: "future_whenallsucceed_100k_deferred_on_loop") { let loop = group.next() let expected = Array(0..<100_000) let promises = expected.map { _ in loop.makePromise(of: Int.self) } let allSucceeded = try! loop.makeSucceededFuture(()).flatMap { _ -> EventLoopFuture<[Int]> in let result = EventLoopFuture.whenAllSucceed(promises.map { $0.futureResult }, on: loop) for (index, promise) in promises.enumerated() { promise.succeed(index) } return result }.wait() return allSucceeded.count } measureAndPrint(desc: "future_whenallcomplete_100k_immediately_succeeded_off_loop") { let loop = group.next() let expected = Array(0..<100_000) let futures = expected.map { loop.makeSucceededFuture($0) } let allSucceeded = try! EventLoopFuture.whenAllComplete(futures, on: loop).wait() return allSucceeded.count } measureAndPrint(desc: "future_whenallcomplete_100k_immediately_succeeded_on_loop") { let loop = group.next() let expected = Array(0..<100_000) let allSucceeded = try! loop.makeSucceededFuture(()).flatMap { _ -> EventLoopFuture<[Result<Int, Error>]> in let futures = expected.map { loop.makeSucceededFuture($0) } return EventLoopFuture.whenAllComplete(futures, on: loop) }.wait() return allSucceeded.count } measureAndPrint(desc: "future_whenallcomplete_100k_deferred_off_loop") { let loop = group.next() let expected = Array(0..<100_000) let promises = expected.map { _ in loop.makePromise(of: Int.self) } let allSucceeded = EventLoopFuture.whenAllComplete(promises.map { $0.futureResult }, on: loop) for (index, promise) in promises.enumerated() { promise.succeed(index) } return try! allSucceeded.wait().count } measureAndPrint(desc: "future_whenallcomplete_100k_deferred_on_loop") { let loop = group.next() let expected = Array(0..<100_000) let promises = expected.map { _ in loop.makePromise(of: Int.self) } let allSucceeded = try! loop.makeSucceededFuture(()).flatMap { _ -> EventLoopFuture<[Result<Int, Error>]> in let result = EventLoopFuture.whenAllComplete(promises.map { $0.futureResult }, on: loop) for (index, promise) in promises.enumerated() { promise.succeed(index) } return result }.wait() return allSucceeded.count } measureAndPrint(desc: "future_reduce_10k_futures") { let el1 = group.next() let oneHundredFutures = (1 ... 10_000).map { i in el1.makeSucceededFuture(i) } return try! EventLoopFuture<Int>.reduce(0, oneHundredFutures, on: el1, +).wait() } measureAndPrint(desc: "future_reduce_into_10k_futures") { let el1 = group.next() let oneHundredFutures = (1 ... 10_000).map { i in el1.makeSucceededFuture(i) } return try! EventLoopFuture<Int>.reduce(into: 0, oneHundredFutures, on: el1, { $0 += $1 }).wait() } try measureAndPrint(desc: "channel_pipeline_1m_events", benchmark: ChannelPipelineBenchmark()) try measureAndPrint(desc: "websocket_encode_50b_space_at_front_1m_frames_cow", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 50, runCount: 1_000_000, dataStrategy: .spaceAtFront, cowStrategy: .always, maskingKeyStrategy: .never)) try measureAndPrint(desc: "websocket_encode_50b_space_at_front_1m_frames_cow_masking", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 50, runCount: 100_000, dataStrategy: .spaceAtFront, cowStrategy: .always, maskingKeyStrategy: .always)) try measureAndPrint(desc: "websocket_encode_1kb_space_at_front_100k_frames_cow", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 1024, runCount: 100_000, dataStrategy: .spaceAtFront, cowStrategy: .always, maskingKeyStrategy: .never)) try measureAndPrint(desc: "websocket_encode_50b_no_space_at_front_1m_frames_cow", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 50, runCount: 1_000_000, dataStrategy: .noSpaceAtFront, cowStrategy: .always, maskingKeyStrategy: .never)) try measureAndPrint(desc: "websocket_encode_1kb_no_space_at_front_100k_frames_cow", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 1024, runCount: 100_000, dataStrategy: .noSpaceAtFront, cowStrategy: .always, maskingKeyStrategy: .never)) try measureAndPrint(desc: "websocket_encode_50b_space_at_front_10k_frames", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 50, runCount: 10_000, dataStrategy: .spaceAtFront, cowStrategy: .never, maskingKeyStrategy: .never)) try measureAndPrint(desc: "websocket_encode_50b_space_at_front_10k_frames_masking", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 50, runCount: 100_000, dataStrategy: .spaceAtFront, cowStrategy: .never, maskingKeyStrategy: .always)) try measureAndPrint(desc: "websocket_encode_1kb_space_at_front_1k_frames", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 1024, runCount: 1_000, dataStrategy: .spaceAtFront, cowStrategy: .never, maskingKeyStrategy: .never)) try measureAndPrint(desc: "websocket_encode_50b_no_space_at_front_10k_frames", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 50, runCount: 10_000, dataStrategy: .noSpaceAtFront, cowStrategy: .never, maskingKeyStrategy: .never)) try measureAndPrint(desc: "websocket_encode_1kb_no_space_at_front_1k_frames", benchmark: WebSocketFrameEncoderBenchmark(dataSize: 1024, runCount: 1_000, dataStrategy: .noSpaceAtFront, cowStrategy: .never, maskingKeyStrategy: .never)) try measureAndPrint(desc: "websocket_decode_125b_100k_frames", benchmark: WebSocketFrameDecoderBenchmark(dataSize: 125, runCount: 100_000)) try measureAndPrint(desc: "websocket_decode_125b_with_а_masking_key_100k_frames", benchmark: WebSocketFrameDecoderBenchmark(dataSize: 125, runCount: 100_000, maskingKey: [0x80, 0x08, 0x10, 0x01])) try measureAndPrint(desc: "websocket_decode_64kb_100k_frames", benchmark: WebSocketFrameDecoderBenchmark(dataSize: Int(UInt16.max), runCount: 100_000)) try measureAndPrint(desc: "websocket_decode_64kb_with_а_masking_key_100k_frames", benchmark: WebSocketFrameDecoderBenchmark(dataSize: Int(UInt16.max), runCount: 100_000, maskingKey: [0x80, 0x08, 0x10, 0x01])) try measureAndPrint(desc: "websocket_decode_64kb_+1_100k_frames", benchmark: WebSocketFrameDecoderBenchmark(dataSize: Int(UInt16.max) + 1, runCount: 100_000)) try measureAndPrint(desc: "websocket_decode_64kb_+1_with_а_masking_key_100k_frames", benchmark: WebSocketFrameDecoderBenchmark(dataSize: Int(UInt16.max) + 1, runCount: 100_000, maskingKey: [0x80, 0x08, 0x10, 0x01])) try measureAndPrint(desc: "circular_buffer_into_byte_buffer_1kb", benchmark: CircularBufferIntoByteBufferBenchmark(iterations: 10000, bufferSize: 1024)) try measureAndPrint(desc: "circular_buffer_into_byte_buffer_1mb", benchmark: CircularBufferIntoByteBufferBenchmark(iterations: 20, bufferSize: 1024*1024)) try measureAndPrint(desc: "byte_buffer_view_iterator_1mb", benchmark: ByteBufferViewIteratorBenchmark(iterations: 20, bufferSize: 1024*1024))
39.181818
178
0.663208
f91ed1de83ffe193a8c0ce54105d606126bbbfb3
2,557
// // ERC721Events.swift // web3swift // // Created by Miguel on 09/05/2019. // Copyright © 2019 Argent Labs Limited. All rights reserved. // import Foundation import BigInt public enum ERC721Events { public struct Transfer: ABIEvent { public static let name = "Transfer" public static let types: [ABIType.Type] = [ EthereumAddress.self , EthereumAddress.self , BigUInt.self] public static let typesIndexed = [true, true, true] public let log: EthereumLog public let from: EthereumAddress public let to: EthereumAddress public let tokenId: BigUInt public init?(topics: [ABIType], data: [ABIType], log: EthereumLog) throws { try Transfer.checkParameters(topics, data) self.log = log self.from = try topics[0].decoded() self.to = try topics[1].decoded() self.tokenId = try topics[2].decoded() } } public struct Approval: ABIEvent { public static let name = "Approval" public static let types: [ABIType.Type] = [ EthereumAddress.self , EthereumAddress.self , BigUInt.self] public static let typesIndexed = [true, true, true] public let log: EthereumLog public let from: EthereumAddress public let approved: EthereumAddress public let tokenId: BigUInt public init?(topics: [ABIType], data: [ABIType], log: EthereumLog) throws { try Approval.checkParameters(topics, data) self.log = log self.from = try topics[0].decoded() self.approved = try topics[1].decoded() self.tokenId = try topics[2].decoded() } } public struct ApprovalForAll: ABIEvent { public static let name = "ApprovalForAll" public static let types: [ABIType.Type] = [ EthereumAddress.self , EthereumAddress.self , BigUInt.self] public static let typesIndexed = [true, true, true] public let log: EthereumLog public let from: EthereumAddress public let `operator`: EthereumAddress public let approved: Bool public init?(topics: [ABIType], data: [ABIType], log: EthereumLog) throws { try ApprovalForAll.checkParameters(topics, data) self.log = log self.from = try topics[0].decoded() self.operator = try topics[1].decoded() self.approved = try topics[2].decoded() } } }
35.027397
111
0.601877
6ab056b345adeaf4274e39a68b47d549189276cb
592
// // SectionDivider.swift // Scryfall // // Created by Alexander on 12.08.2021. // import SwiftUI struct SectionDivider: View { var body: some View { ZStack(alignment: .top) { Color("SectionSeparator").frame(height: 4) Color("SectionSeparatorShadow").frame(height: 1) .blur(radius: 1.0) .offset(y: -1.0) .opacity(0.7) } .clipped() .frame(height: 8) } } struct SectionDivider_Previews: PreviewProvider { static var previews: some View { SectionDivider() } }
20.413793
60
0.555743
48f03fe23f4c6314c5ff98be8c4a0c36bb76f0a2
6,088
/* * Copyright 2020, gRPC Authors 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 Logging import NIO internal final class ServerInterceptorPipeline<Request, Response> { /// The `EventLoop` this RPC is being executed on. internal let eventLoop: EventLoop /// The path of the RPC in the format "/Service/Method", e.g. "/echo.Echo/Get". internal let path: String /// The type of the RPC, e.g. "unary". internal let type: GRPCCallType /// A logger. internal let logger: Logger /// A reference to a 'UserInfo'. internal let userInfoRef: Ref<UserInfo> /// The contexts associated with the interceptors stored in this pipeline. Contexts will be /// removed once the RPC has completed. Contexts are ordered from inbound to outbound, that is, /// the head is first and the tail is last. private var contexts: InterceptorContextList<ServerInterceptorContext<Request, Response>>? /// Returns the next context in the outbound direction for the context at the given index, if one /// exists. /// - Parameter index: The index of the `ServerInterceptorContext` which is requesting the next /// outbound context. /// - Returns: The `ServerInterceptorContext` or `nil` if one does not exist. internal func nextOutboundContext( forIndex index: Int ) -> ServerInterceptorContext<Request, Response>? { return self.context(atIndex: index - 1) } /// Returns the next context in the inbound direction for the context at the given index, if one /// exists. /// - Parameter index: The index of the `ServerInterceptorContext` which is requesting the next /// inbound context. /// - Returns: The `ServerInterceptorContext` or `nil` if one does not exist. internal func nextInboundContext( forIndex index: Int ) -> ServerInterceptorContext<Request, Response>? { return self.context(atIndex: index + 1) } /// Returns the context for the given index, if one exists. /// - Parameter index: The index of the `ServerInterceptorContext` to return. /// - Returns: The `ServerInterceptorContext` or `nil` if one does not exist for the given index. private func context(atIndex index: Int) -> ServerInterceptorContext<Request, Response>? { return self.contexts?[checked: index] } /// The context closest to the `NIO.Channel`, i.e. where inbound events originate. This will be /// `nil` once the RPC has completed. internal var head: ServerInterceptorContext<Request, Response>? { return self.contexts?.first } /// The context closest to the application, i.e. where outbound events originate. This will be /// `nil` once the RPC has completed. internal var tail: ServerInterceptorContext<Request, Response>? { return self.contexts?.last } internal init( logger: Logger, eventLoop: EventLoop, path: String, callType: GRPCCallType, userInfoRef: Ref<UserInfo>, interceptors: [ServerInterceptor<Request, Response>], onRequestPart: @escaping (GRPCServerRequestPart<Request>) -> Void, onResponsePart: @escaping (GRPCServerResponsePart<Response>, EventLoopPromise<Void>?) -> Void ) { self.logger = logger self.eventLoop = eventLoop self.path = path self.type = callType self.userInfoRef = userInfoRef // We need space for the head and tail as well as any user provided interceptors. self.contexts = InterceptorContextList( for: self, interceptors: interceptors, onRequestPart: onRequestPart, onResponsePart: onResponsePart ) } /// Emit a request part message into the interceptor pipeline. /// /// - Parameter part: The part to emit into the pipeline. /// - Important: This *must* to be called from the `eventLoop`. internal func receive(_ part: GRPCServerRequestPart<Request>) { self.eventLoop.assertInEventLoop() self.head?.invokeReceive(part) } /// Write a response message into the interceptor pipeline. /// /// - Parameters: /// - part: The response part to sent. /// - promise: A promise to complete when the response part has been successfully written. /// - Important: This *must* to be called from the `eventLoop`. internal func send(_ part: GRPCServerResponsePart<Response>, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() if let tail = self.tail { tail.invokeSend(part, promise: promise) } else { promise?.fail(GRPCError.AlreadyComplete()) } } internal func close() { self.eventLoop.assertInEventLoop() self.contexts = nil } } private extension InterceptorContextList { init<Request, Response>( for pipeline: ServerInterceptorPipeline<Request, Response>, interceptors: [ServerInterceptor<Request, Response>], onRequestPart: @escaping (GRPCServerRequestPart<Request>) -> Void, onResponsePart: @escaping (GRPCServerResponsePart<Response>, EventLoopPromise<Void>?) -> Void ) where Element == ServerInterceptorContext<Request, Response> { let middle = interceptors.enumerated().map { index, interceptor in ServerInterceptorContext( for: .userProvided(interceptor), atIndex: index, in: pipeline ) } let first = ServerInterceptorContext<Request, Response>( for: .head(for: pipeline, onResponsePart), atIndex: middle.startIndex - 1, in: pipeline ) let last = ServerInterceptorContext<Request, Response>( for: .tail(onRequestPart), atIndex: middle.endIndex, in: pipeline ) self.init(first: first, middle: middle, last: last) } }
36.45509
99
0.708279
abfbcbf20812294b8e0d27a30faca982ad99ba62
2,563
// // ChartDataEntry.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class ChartDataEntry: ChartDataEntryBase { /// the x value @objc open var x = Double(0.0) public required init() { super.init() } /// An Entry represents one single entry in the chart. /// - parameter x: the x value /// - parameter y: the y value (the actual value of the entry) @objc public init(x: Double, y: Double) { super.init(y: y) self.x = x } /// An Entry represents one single entry in the chart. /// - parameter x: the x value /// - parameter y: the y value (the actual value of the entry) /// - parameter data: Space for additional data this Entry represents. @objc public init(x: Double, y: Double, data: AnyObject?) { super.init(y: y) self.x = x self.data = data } /// An Entry represents one single entry in the chart. /// - parameter x: the x value /// - parameter y: the y value (the actual value of the entry) /// - parameter icon: icon image @objc public init(x: Double, y: Double, icon: NSUIImage?) { super.init(y: y, icon: icon) self.x = x } /// An Entry represents one single entry in the chart. /// - parameter x: the x value /// - parameter y: the y value (the actual value of the entry) /// - parameter icon: icon image /// - parameter data: Space for additional data this Entry represents. @objc public init(x: Double, y: Double, icon: NSUIImage?, data: AnyObject?) { super.init(y: y, icon: icon, data: data) self.x = x } // MARK: NSObject open override var description: String { return "ChartDataEntry, x: \(x), y \(y)" } // MARK: NSCopying @objc open func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = type(of: self).init() copy.x = x copy.y = y copy.data = data return copy } } // MARK: Equatable extension ChartDataEntry/*: Equatable*/ { open override func isEqual(_ object: Any?) -> Bool { guard let object = object as? ChartDataEntry else { return false } if self === object { return true } return ((data == nil && object.data == nil) || (data?.isEqual(object.data) ?? false)) && y == object.y && x == object.x } }
25.63
93
0.585642
fcb64e6e00d4761afd441eea24383040171ed67d
829
// // BasicAuthHeader.swift // // Created by Janusz Czornik on 30/04/2021. // import Foundation /// HTTP header that supports basic authorization struct BasicAuthHeader: AuthHeader { /// Encoded user and password data let content: String /// Header name let name = "Authorization" /// Initializes object /// /// - Parameters: /// - user: user name /// - password: user password /// /// - Returns: New object if can encode data, otherwise nil init?(user: String, password: String) { guard !user.isEmpty, !password.isEmpty, let token = String("\(user):\(password)") .data(using: .utf8)? .base64EncodedString() else { return nil } content = "Basic \(token)" } }
23.027778
63
0.554885
64b70c619500ade2959a9ad0d385a20ce7dd742b
1,017
// // MultiPicker.swift // Countdown // // Created by Guilherme Andrade on 2021-07-11. // import SwiftUI struct MultiPicker: View { let options: [String] @Binding var selectedOptions: Set<String> var body: some View { VStack(alignment: .leading, spacing: 15) { ForEach(options, id: \.self) { option in HStack { Image(systemName: "checkmark") .opacity(selectedOptions.contains(option) ? 1 : 0) Text(option) } .onTapGesture { toggleOption(option) } } .listStyle(InsetListStyle()) } } private func toggleOption(_ option: String) { if selectedOptions.contains(option) { selectedOptions.remove(option) } else { selectedOptions.insert(option) } } } struct MultiPicker_Previews: PreviewProvider { @State static var options: Set<String> = [] static var previews: some View { let options = Reminder.allCases.map(\.rawValue) MultiPicker(options: options, selectedOptions: $options) } }
22.6
62
0.643068
76d34902565f1198536bbc12ea07c85bad94a6af
1,926
// // This is free and unencumbered software released into the public domain. // // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non-commercial, and by any // means. // // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // // 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 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. // // For more information, please refer to <http://unlicense.org/> // // MARK: - OtherPalette /// A `Palette` that reference-wraps another `Palette`. public final class OtherPalette<Base: Palette>: Palette { /// Creates an `OtherPalette` by reference-wrapping `base`. /// /// - parameter base: The `Palette` to be reference-wrapped. public init(_ base: Base) { self.base = base } /// The reference-wrapped `Palette`. public var base: Base // MARK: Palette public typealias Preset = Base.Preset public typealias Sample = Base.Sample public subscript(preset preset: Preset) -> Sample { get { return self.base[preset: preset] } set { self.base[preset: preset] = newValue } } }
32.644068
74
0.73053
fbb9771b9c391acff40c4ad944e00a29dc3ffda6
341
// // Html.swift // Bitbucket User Finder // // Created by Jemimah Beryl M. Sai on 14/08/2018. // Copyright © 2018 Jemimah Beryl M. Sai. All rights reserved. // import ObjectMapper class Html: Mappable { var href: String? required init?(map: Map) { } func mapping(map: Map) { href <- map["href"] } }
17.05
63
0.595308
0eaf4820fcc4487891fd12daf5ff3e8f89f7c441
1,021
// // LocationResultTableViewCell.swift // OverEats // // Created by 배태웅 on 2018. 4. 25.. // Copyright © 2018년 sangwook park. All rights reserved. // import UIKit class LocationResultTableViewCell: UITableViewCell { @IBOutlet weak var logoImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var detailAddress: UILabel! var locationData: LocationData? override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configure(locationData: LocationTableUtility) { logoImageView.image = UIImage(named: locationData.iconName!) titleLabel.text = locationData.title detailAddress.text = locationData.cellData?.formattedAddress self.locationData = locationData.cellData } }
25.525
68
0.677767
723d8ab2928eec14cb982c3ae48175656d38607d
579
// // Holder.swift // Breakout // // Created by Fredrik on 06.04.18. // Copyright © 2018 fwcd. All rights reserved. // import Foundation class Holder<T> { private var storedValue: T private var listeners = [(T) -> ()]() var value: T { get { return storedValue } set { storedValue = newValue fireListeners(with: newValue) } } init(with value: T) { storedValue = value } func add(listener: @escaping (T) -> ()) { listeners.append(listener) } private func fireListeners(with value: T) { for listener in listeners { listener(value) } } }
16.083333
47
0.637306
f8b6ca6808d1bdf25479388734b4764abefb3595
458
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // JobDeleteHeadersProtocol is defines headers for Delete operation. public protocol JobDeleteHeadersProtocol : Codable { var clientRequestId: String? { get set } var requestId: String? { get set } }
41.636364
96
0.746725
6acb12bdcd7f898a52dc00a63e057c09e28ce7ed
1,764
// // AVAudioSessionRouteDescription+Additions.swift // import AVFoundation public extension AVAudioSessionRouteDescription { var ft_debugDescription: String { let inputStrs = inputs.map(\.ft_debugDescription).joined(separator: ", ") let outputStr = outputs.map(\.ft_debugDescription).joined(separator: ", ") return "\(inputStrs) / \(outputStr)" } } public extension AVAudioSessionPortDescription { var ft_debugDescription: String { uid } } public extension AVAudioSession.Port { var ft_debugDescription: String { if let desc = type(of: self).ft_casesAndDebugDescriptions[self] { return desc } else { return "unknown" } } private static let ft_casesAndDebugDescriptions: [AVAudioSession.Port : String] = { var result: [AVAudioSession.Port : String] = [ .lineIn: "lineIn", .builtInMic: "builtInMic", .headsetMic: "headsetMic", .lineOut: "lineOut", .headphones: "headphones", .bluetoothA2DP: "bluetoothA2DP", .builtInReceiver: "builtInReceiver", .builtInSpeaker: "builtInSpeaker", .HDMI: "HDMI", .airPlay: "airPlay", .bluetoothLE: "bluetoothLE", .bluetoothHFP: "bluetoothHFP", .usbAudio: "usbAudio", .carAudio: "carAudio", ] if #available(iOS 14.0, *) { result[virtual] = "virtual" result[PCI] = "PCI" result[fireWire] = "fireWire" result[displayPort] = "displayPort" result[AVB] = "AVB" result[thunderbolt] = "thunderbolt" } return result }() }
29.4
87
0.570295
f7499c24572fd801a8e083bc955a2b09eee68fdb
200
// // JKNSDateExtension.swift // JKPinTu-Swift // // Created by bingjie-macbookpro on 15/12/15. // Copyright © 2015年 Bingjie. All rights reserved. // import Foundation extension Date { }
11.764706
51
0.675
894c814364bd6ed011a5f327ec3d4fe25492c022
1,381
// // ListViewModel.swift // ESXDQNLWEJ // // Created by davut.gunes on 12/20/20. // import UIKit import MapKit class DetailViewModel: NSObject { var item:ItemModel? var totalHeight:Float = 0 var heights = [CGFloat]() init(model: ItemModel? = nil) { if let inputModel = model { item = inputModel } } public func setMatView(mapView: MKMapView) { let initialLocation = CLLocation(latitude: self.item?.venue?.location?.lat ?? 0, longitude: self.item?.venue?.location?.lng ?? 0) mapView.centerToLocation(initialLocation) } public func setName(lblName: UILabel) { lblName.text = item?.venue?.name } public func setCellContent(cell: TipCell, indexPath: IndexPath) { let tip = item?.tips?[indexPath.row] cell.setContent(tip: tip) if heights.count <= indexPath.row { heights.append(getCellHeight(lblText: cell.lblText)) } print("\(heights), \(heights.count)") } public func setTableViewHeight(constraint: NSLayoutConstraint, indexPath: IndexPath) { var totalHeights:CGFloat = 32 for height in heights { totalHeights = totalHeights + height + 30 } constraint.constant = totalHeights } func getCellHeight(lblText: UILabel) -> CGFloat { return lblText.frame.height } }
28.770833
137
0.630702
e0205b83a756fbf93596a8e0784c915ffbd0c729
1,441
// // Copyright 2021 New Vector 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. // import SwiftUI @available(iOS 14.0, *) struct OtherNotificationSettings: View { @ObservedObject var viewModel: NotificationSettingsViewModel var body: some View { NotificationSettings(viewModel: viewModel) .navigationTitle(VectorL10n.settingsOther) .track(screen: .settingsNotifications) } } @available(iOS 14.0, *) struct OtherNotifications_Previews: PreviewProvider { static var previews: some View { NavigationView { DefaultNotificationSettings( viewModel: NotificationSettingsViewModel( notificationSettingsService: MockNotificationSettingsService.example, ruleIds: NotificationSettingsScreen.other.pushRules ) ) .navigationBarTitleDisplayMode(.inline) } } }
32.75
89
0.691187
723b61c9d888e0954ac815b3f1a65190b4b136c6
15,322
// // MoviesViewController.swift // Flicks // // Created by Ryuji Mano on 1/31/17. // Copyright © 2017 Ryuji Mano. All rights reserved. // import UIKit import AFNetworking import MBProgressHUD class MoviesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var networkErrorButton: UIButton! @IBOutlet weak var movieSearchBar: UISearchBar! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var flowLayout: UICollectionViewFlowLayout! // @IBOutlet var pinchGestureRecognizer: UIPinchGestureRecognizer! var movies: [Movie] = [] var endpoint: String! //variable of the page number used for API calls var page = 0 //boolean value to check if the collection view is in front of the tableview var onFront: Bool = true //array of dictionaries filtered from movies (used for search) var filteredMovies: [Movie] = [] //custom components for refreshControl let refreshContents = Bundle.main.loadNibNamed("RefreshView", owner: self, options: nil) var customView: UIView! var icon: UIImageView! let refreshControl = UIRefreshControl() // // MARK - View Configuration // override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) //hide network error button networkErrorButton.isHidden = true //initial configuration of the tableview and the collectionview if endpoint == "similar" { tableView.alpha = 0 collectionView.alpha = 1 collectionView.isUserInteractionEnabled = true tableView.isUserInteractionEnabled = false } else { collectionView.alpha = 0 tableView.alpha = 1 tableView.isUserInteractionEnabled = true collectionView.isUserInteractionEnabled = false } } override func viewDidLoad() { super.viewDidLoad() //configure search bar movieSearchBar.delegate = self //set page to 1 initially page += 1 //load movies from the API and assign the resulting JSON to the movies array loadMovies(at: page) //configure custom refreshControl customView = refreshContents?[0] as! UIView icon = customView.viewWithTag(1) as! UIImageView icon.tintColor = .lightGray refreshControl.tintColor = .clear refreshControl.backgroundColor = .clear setUpRefreshControl() refreshControl.addTarget(self, action: #selector(loadMovies(_:)), for: .valueChanged) if endpoint == "similar" { //configure collectionview collectionView.dataSource = self collectionView.delegate = self flowLayout.scrollDirection = .vertical flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) collectionView.insertSubview(refreshControl, at: 0) } else { //configure tableview tableView.dataSource = self tableView.delegate = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 190.0 tableView.insertSubview(self.refreshControl, at: 0) } if let navigationBar = navigationController?.navigationBar { navigationBar.tintColor = .yellow navigationBar.barTintColor = .black navigationBar.subviews.first?.alpha = 0.7 } movieSearchBar.sizeToFit() navigationItem.titleView = movieSearchBar if let tabBar = tabBarController?.tabBar { tabBar.tintColor = .yellow tabBar.barTintColor = .black tabBar.alpha = 0.7 } } // // MARK - Refresh Control Setup // func setUpRefreshControl() { //set custom view bounds equal to refreshControl bounds customView.frame = refreshControl.bounds customView.backgroundColor = .black //add custom view to refreshControl refreshControl.addSubview(customView) } func animateRefreshControl() { //animate color of refreshControl background (repeated color change from black to yellow) UIView.animate(withDuration: 0.5, delay: 0, options: [.autoreverse, .curveLinear, .repeat], animations: { self.customView.backgroundColor = .black self.customView.backgroundColor = .yellow }, completion: nil) } // // MARK - ScrollView // func scrollViewDidScroll(_ scrollView: UIScrollView) { //if 1 < height of the refreshControl <= 60, rotate the icon if refreshControl.bounds.height > 1 && refreshControl.bounds.height <= 60 { icon.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi) + CGFloat(Double.pi) * (refreshControl.bounds.height / CGFloat(60))) } //if height of the refreshControl > 60, keep icon upright else if refreshControl.bounds.height > 60 { icon.transform = CGAffineTransform(rotationAngle: CGFloat(0)) } } // // MARK - API Calls // func loadMovies(at page:Int) { MBProgressHUD.showAdded(to: self.view, animated: true) if endpoint == "similar" { APIClient.shared.superHeroMovies(at: page, movies: self.movies, completion: { (movies, error) in //end loading display MBProgressHUD.hide(for: self.view, animated: true) if let movies = movies { self.movies = movies //assign movies to filteredMovies self.filteredMovies = self.movies //reload data self.tableView.reloadData() self.collectionView.reloadData() } else { self.animateNetworkErrorButton() } }) } else { APIClient.shared.nowPlayingMovies(at: page, movies: self.movies, completion: { (movies, error) in //end loading display MBProgressHUD.hide(for: self.view, animated: true) if let movies = movies { self.movies = movies //assign movies to filteredMovies self.filteredMovies = self.movies //reload data self.tableView.reloadData() self.collectionView.reloadData() } else { self.animateNetworkErrorButton() } }) } } //function for API call used when the user refreshes the contents @objc func loadMovies(_ refreshControl:UIRefreshControl) { animateRefreshControl() if endpoint == "similar" { APIClient.shared.superHeroMovies(at: nil, movies: [], completion: { (movies, error) in //end loading display MBProgressHUD.hide(for: self.view, animated: true) if let movies = movies { self.movies = movies //assign movies to filteredMovies self.filteredMovies = self.movies //reload data self.tableView.reloadData() self.collectionView.reloadData() refreshControl.endRefreshing() self.customView.backgroundColor = .black } else { self.animateNetworkErrorButton() refreshControl.endRefreshing() } }) } else { APIClient.shared.nowPlayingMovies(at: nil, movies: [], completion: { (movies, error) in //end loading display MBProgressHUD.hide(for: self.view, animated: true) if let movies = movies { self.movies = movies //assign movies to filteredMovies self.filteredMovies = self.movies //reload data self.tableView.reloadData() self.collectionView.reloadData() refreshControl.endRefreshing() self.customView.backgroundColor = .black } else { self.animateNetworkErrorButton() refreshControl.endRefreshing() } }) } } // // MARK - TableView // //set number of rows to the amount of elements in filteredMovies func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredMovies.count } //configure the cells of the tableview func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell", for: indexPath) as! MovieCell let movie = filteredMovies[indexPath.row] cell.setUp(with: movie) return cell } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { //when the user is using the search bar, exit function if movieSearchBar.isFirstResponder { return } //when the tableview reaches the last cell, load the next page of movies and increment pages if indexPath.row >= tableView.numberOfRows(inSection: 0) - 1 { page += 1 loadMovies(at: page) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) } // // MARK - CollectionView // //set number of items in the collectionview to the amount of elements in filteredMovies func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return filteredMovies.count } //configure cell func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "movieCollectionCell", for: indexPath) as! MovieCollectionViewCell let movie = filteredMovies[indexPath.row] cell.setUp(with: movie) return cell } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { //if the user is using the search bar, exit the function if movieSearchBar.isFirstResponder { return } //if the collectionview hits the last item, load the next page of movies and increment pages if indexPath.row >= collectionView.numberOfItems(inSection: 0) - 1 { page += 1 loadMovies(at: page) } } // // MARK - Search Bar // func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { //filter the movies array based on the user's search let filtered = searchText.isEmpty ? movies : movies.filter({ movie -> Bool in let dataString = movie.title return dataString.lowercased().range(of: searchText.lowercased()) != nil }) //assign the filtered array to filteredMovies filteredMovies = filtered ?? [] //reload data tableView.reloadData() collectionView.reloadData() } //function that shows the cancel button when the user is using the search bar func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { movieSearchBar.showsCancelButton = true } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { //remove the text and cancel button when the user clicks on the cancel button movieSearchBar.showsCancelButton = false movieSearchBar.text = "" //retract keyboard when the cancel button is clicked movieSearchBar.resignFirstResponder() //reload data with all of the movies array content filteredMovies = movies ?? [] tableView.reloadData() collectionView.reloadData() } // // MARK - Network Error Button // //retract the network error button when tapped @IBAction func networkErrorButtonTapped(_ sender: Any) { animateRetractingNetworkErrorButton() } func animateNetworkErrorButton() { //add animation to network error button //translate the network error button from behind the search bar UIView.animate(withDuration: 0.3, animations: { self.networkErrorButton.isHidden = false let yValue = UIApplication.shared.statusBarFrame.height + self.movieSearchBar.frame.height - 1 self.networkErrorButton.frame = CGRect(x: 0, y: yValue, width: self.networkErrorButton.frame.width, height: self.networkErrorButton.frame.height) }, completion: { isComplete in self.networkErrorButton.isHidden = false }) } func animateRetractingNetworkErrorButton() { //add retracting animation to the network error button //translate the network error button from the view to behind the search bar UIView.animate(withDuration: 0.3, animations: { let yValue = UIApplication.shared.statusBarFrame.height + self.movieSearchBar.frame.height self.networkErrorButton.frame = CGRect(x: 0, y: 0 - self.networkErrorButton.frame.height + yValue, width: self.networkErrorButton.frame.width, height: self.networkErrorButton.frame.height) }, completion: { (isComplete) in //when animation is completed, hide the network error button and load movies self.networkErrorButton.isHidden = true self.loadMovies(at: self.page) }) } // // MARK: Navigation // override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? UITableViewCell { let indexPath = tableView.indexPath(for: cell) let movie = movies[(indexPath?.row)!] let destination = segue.destination as! DetailViewController destination.movie = movie } else if let item = sender as? UICollectionViewCell { let indexPath = collectionView.indexPath(for: item) let movie = movies[(indexPath?.item)!] let destination = segue.destination as! DetailViewController destination.movie = movie } } }
35.061785
200
0.602989
4b8d2b34131637646aec7386080b5dea8c8fd192
2,008
// Based on hyp's original Swift 1 implementation: https://github.com/hyp/LPATHBench/blob/1920f809a2f22f6fbfe4393ab87557bea8364416/swift.swift // Compile with: swiftc -O swift.swift import Foundation import QuartzCore struct Route { let dest: Int let cost: Int } struct Node { var neighbours: [Route] = [] } func readPlaces() -> [Node] { var places = [Node]() if let data = try? String(contentsOfFile: "agraph", encoding: .utf8) { data.enumerateLines { line, stop in places = Array(repeating: Node(), count: Int(line) ?? 0) stop = true } data.enumerateLines { (line, stop) in let components = line.components(separatedBy: CharacterSet.whitespaces) guard components.count >= 3 else { return } switch (Int(components[0]), Int(components[1]), Int(components[2])) { case let (.some(node), .some(dest), .some(cost)): places[node].neighbours.append(Route(dest: dest, cost: cost)) default: break } } } return places } func getLongestPath(nodes: [Node], nodeId: Int, visited: inout [Bool]) -> Int { visited[nodeId] = true var max = 0 for neighbour in nodes[nodeId].neighbours { guard !visited[neighbour.dest] else { continue } let dist = neighbour.cost + getLongestPath(nodes: nodes, nodeId: neighbour.dest, visited: &visited) if dist > max { max = dist } } visited[nodeId] = false return max } func getLongestPath(nodes: [Node]) -> Int { var visited = Array<Bool>(repeating: false, count: nodes.count) return getLongestPath(nodes: nodes, nodeId: 0, visited: &visited) } let nodes = readPlaces() let startTime = CACurrentMediaTime() let length = getLongestPath(nodes: nodes) let endTime = CACurrentMediaTime() let ms = Int((endTime - startTime) * 1000) print("\(length) LANGUAGE Swift \(ms)")
28.685714
142
0.610558
90dde54a88023778ff3dfed909f08aaa7d6934d0
746
// // SnappedPoint.swift // digital-fare-lib // // Created by Nguyen Quoc Vuong on 7/29/20. // import Foundation import CPAPIService import CoreLocation public struct SnappedPoint: BaseModel { public var places: [Place]? enum CodingKeys: String, CodingKey { case places = "snappedPoints" } public func getList2DLocation() -> [CLLocationCoordinate2D] { var listLocation : [CLLocationCoordinate2D] = [] if let places = places { for item in places { if let location = item.location?.to2DLocation { listLocation.append(location) } } } return listLocation } public init() { } }
21.314286
65
0.573727
4bb1875c819d9f1d3134839b822559c17c073bfd
2,287
// Main File For SwipeTableViewCell //class SwipeTVC import Foundation import UIKit public class SwipeTVC: UITableViewCell { var rightSwipe:UIPanGestureRecognizer! var swipeView: UIView! var behindView: UIView! var mainView: UIView! public func setUp(userBehindView: UIView, slideAreaFrame: CGRect, userMainView: UIView){ // let width = (slideAreaWidth ? slideAreaWidth : CGFloat(self.frame.width)) // let height = (slideAreaHeight ? slideAreaHeight : CGFloat(self.frame.height)) behindView = userBehindView mainView = userMainView self.addSubview(mainView) self.drawBehindView(behindView: userBehindView) self.drawSwipeView(frame: slideAreaFrame) } fileprivate func drawSwipeView(frame: CGRect){ swipeView = UIView(frame: frame) swipeView.backgroundColor = UIColor.clear self.mainView.addSubview(swipeView) rightSwipe = UIPanGestureRecognizer(target: self, action:#selector(self.draggedView(_:))) swipeView.addGestureRecognizer(rightSwipe) } fileprivate func drawBehindView(behindView: UIView) { self.contentView.addSubview(behindView) } @objc func draggedView(_ sender:UIPanGestureRecognizer){ switch sender.state { case .began: break case .changed: break case .ended: let originalTransform = self.mainView.transform let xpos = CGFloat(0) let changeX = xpos - self.mainView.frame.minX let scaledAndTranslatedTransform = originalTransform.translatedBy(x: changeX, y: 0) UIView.animate(withDuration: 0.7, animations: { self.mainView.transform = scaledAndTranslatedTransform }) default: () } } } extension UIPanGestureRecognizer { func isDown(view: UIView) -> Bool { let velocity2 : CGPoint = velocity(in: view) print("VELOCITRY: ", velocity2) if abs(velocity2.y) > 30 { print("Gesture is going up and down") return true } else { print("Gesture is going side to side") return false } } }
31.328767
97
0.619589
20871e5c3acef38597b0f837f68c35702c0e6ca4
1,731
// // ViewController.swift // CICategoryColorAdjustment // // Created by Bourbon on 2021/8/13. // import UIKit class ViewController: UIViewController { let array : [String] = ["CIColorClamp", "CIColorControls", "CIColorMatrix", "CIColorPolynomial", "CIExposureAdjust", "CIGammaAdjust", "CIHueAdjust", "CILinearToSRGBToneCurve", "CISRGBToneCurveToLinear", "CITemperatureAndTint", "CIToneCurve", "CIVibrance", "CIWhitePointAdjust"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } extension ViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let vc = storyboard?.instantiateViewController(identifier: "FilterViewController") { vc.title = array[indexPath.row] navigationController?.pushViewController(vc, animated: true) } } } extension ViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = array[indexPath.row] return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } }
32.055556
100
0.566724
16267c44c9d0a7bef7e66b511ed4f32a0663c41a
1,284
// Copyright © 2018 Stormbird PTE. LTD. import Foundation import UIKit struct RequestViewModel { private let account: Wallet private let server: RPCServer init(account: Wallet, server: RPCServer) { self.account = account self.server = server } var myAddressText: String { return account.address.eip55String } var myAddress: AlphaWallet.Address { return account.address } var shareMyAddressText: String { return R.string.localizable.requestMyAddressIsLabelTitle(server.name, myAddressText) } var copyWalletText: String { return R.string.localizable.requestCopyWalletButtonTitle() } var addressCopiedText: String { return R.string.localizable.requestAddressCopiedTitle() } var backgroundColor: UIColor { return Colors.appBackground } var addressLabelColor: UIColor { return .black } var copyButtonsFont: UIFont { return Fonts.semibold(size: 17)! } var labelColor: UIColor? { return R.color.mine() } var addressFont: UIFont { return Fonts.semibold(size: 17)! } var addressBackgroundColor: UIColor { return UIColor(red: 237, green: 237, blue: 237) } var instructionFont: UIFont { return Fonts.regular(size: 17)! } var instructionText: String { return R.string.localizable.aWalletAddressScanInstructions() } }
19.164179
86
0.744548
7ae3cf3da19206b3cf99002c96b89d93b59681bf
497
// // ViewController.swift // Gank_Swift // // Created by Yuns on 2017/9/7. // Copyright © 2017年 ZXEVPOP. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.115385
80
0.665996
8959ddd027ee4bc58b7ba5ba30dc6293a82a6e02
954
// RUN: %target-swift-frontend -parse-as-library -module-name=test -primary-file %s -O -emit-sil | %FileCheck %s // Check if the compiler can convert a partial_apply of a dead argument (an // unused metatype) to a thin_to_thick_function extension Int32 { // This function has an unused metatype argument. // CHECK-LABEL: sil [signature_optimized_thunk] [always_inline] @$Ss5Int32V4testE8lessthan3lhs3rhsSbAB_ABtFZ : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool public static func lessthan (lhs: Int32, rhs: Int32) -> Bool { return lhs < rhs } } // CHECK-LABEL: sil hidden @$S4test6callitSbs5Int32V_ADtcyF : $@convention(thin) () -> @owned @callee_guaranteed (Int32, Int32) -> Bool // CHECK: [[F:%[0-9]+]] = function_ref @$Ss5Int32V4testE8lessthan3lhs3rhsSbAB_ABtFZTf4nnd_n // CHECK: [[R:%[0-9]+]] = thin_to_thick_function [[F]] // CHECK: return [[R]] func callit() -> (Int32, Int32) -> Bool { return (Int32.lessthan) }
38.16
172
0.710692
cc46b822e0a6140c17229bec78bb47add8934155
720
import Foundation import Validator final class LongStringExampleTableViewCell: ExampleTableViewCell { @IBOutlet private(set) var textView: UITextView! { didSet { textView.text = nil } } var validationRuleSet: ValidationRuleSet<String>? { didSet { textView.validationRules = validationRuleSet } } override func awakeFromNib() { super.awakeFromNib() textView.validateOnInputChange(enabled: true) textView.validationHandler = { result in self.updateValidationState(result: result) } } override func prepareForReuse() { textView.text = "" } }
21.818182
93
0.597222
e5b8b8e49835d57d6ec7309ce145dac62a2d826a
2,826
//: [Previous](@previous) /*: # PropertyList */ import Foundation struct MacBook: Codable { let model: String let modelYear: Int let display: Int } let macBook = MacBook( model: "MacBook Pro", modelYear: 2018, display: 15 ) // Codable 이전 - PropertyListSerialization // Codable 이후 - PropertyListEncoder / PropertyListDecoder /*: --- ## Encoder --- */ print("\n---------- [ Encoder ] ----------\n") let pListEncoder = PropertyListEncoder() let encodedMacBook = try! pListEncoder.encode(macBook) print(encodedMacBook) let appSupportDir = FileManager.default.urls( for: .applicationSupportDirectory, in: .userDomainMask ).first! let archiveURL = appSupportDir .appendingPathComponent("macBookData") .appendingPathExtension("plist") try? encodedMacBook.write(to: archiveURL) /*: --- ## Decoder --- */ print("\n---------- [ Decoder ] ----------\n") let pListDecoder = PropertyListDecoder() if let decodedMacBook = try? pListDecoder.decode(MacBook.self, from: encodedMacBook) { print(decodedMacBook) } if let retrievedData = try? Data(contentsOf: archiveURL), let decodedMacBook = try? pListDecoder.decode(MacBook.self, from: retrievedData) { print(retrievedData) print(decodedMacBook) } /*: --- ### Question - MacBook 타입을 Array, Dictionary 형태로 Encoding / Decoding 하려면? --- */ let arr1 = [macBook,macBook,macBook] let encoded = try? PropertyListEncoder().encode(arr1) let decoded = try? PropertyListDecoder().decode([MacBook].self, from: encoded!) print(decoded) let dict1 = ["1": macBook, "2": macBook] let encoded1 = try? PropertyListEncoder().encode(dict1) let decoded1 = try? PropertyListDecoder().decode([String: MacBook].self, from: encoded1!) print(decoded1) /*: --- ### Answer --- */ // Array print("\n---------- [ Array ] ----------\n") let arr = [macBook, macBook, macBook] let encodedArr = try! pListEncoder.encode(arr) try? encodedArr.write(to: archiveURL) if let decodedArr = try? pListDecoder.decode([MacBook].self, from: encodedArr) { print(decodedArr) } if let retrievedData = try? Data(contentsOf: archiveURL), let decodedArr = try? pListDecoder.decode([MacBook].self, from: retrievedData) { print(retrievedData) print(decodedArr) } // Dictionary print("\n---------- [ Dictionary ] ----------\n") let dict = ["mac": macBook, "mac1": macBook, "mac2": macBook] let encodedDict = try! pListEncoder.encode(dict) try? encodedDict.write(to: archiveURL) if let decodedDict = try? pListDecoder.decode([String: MacBook].self, from: encodedDict) { print(decodedDict) } if let retrievedData = try? Data(contentsOf: archiveURL), let decodedDict = try? pListDecoder.decode([String: MacBook].self, from: retrievedData) { print(retrievedData) print(decodedDict) } //: [Table of Contents](Contents) | [Previous](@previous) | [Next](@next)
22.251969
91
0.691791
0a2178a2ac061910afc3839706fdc7729438d086
1,553
// // RuntimeChartView.swift // MynewtManager // // Created by Antonio on 05/12/2016. // Copyright © 2016 Adafruit. All rights reserved. // import UIKit class RuntimeChartView: UIView { // Data var chartColors: [UIColor]? { didSet { setNeedsDisplay() } } var items: [UInt]? { didSet { setNeedsDisplay() } } // MARK: - View Lifecycle override func layoutSubviews() { super.layoutSubviews() setNeedsDisplay() } override func draw(_ rect: CGRect) { guard let chartColors = chartColors, let items = items, let context = UIGraphicsGetCurrentContext() else { return } context.setAllowsAntialiasing(true) let kItemSeparation: CGFloat = 4 let viewWidth = rect.size.width - CGFloat(items.count - 1) * kItemSeparation let sumTotals = items.reduce(0, +) var offsetX: CGFloat = 0 for (i, runtime) in items.enumerated() { let totalFactor = CGFloat(runtime) / CGFloat(sumTotals) let totalColor = chartColors[i%chartColors.count] let itemWidth = viewWidth * totalFactor // Total let rectangleTotal = CGRect(x: offsetX, y: 0, width: itemWidth, height: rect.size.height) context.setFillColor(totalColor.cgColor) context.addRect(rectangleTotal) context.fillPath() offsetX = offsetX + itemWidth + kItemSeparation } } }
26.775862
123
0.580167
ab2f288c64fe9867af4bca5b5f6aacecbaf3e349
2,198
// // TodayViewController.swift // SimpleWorksWidget // // Created by 심다래 on 2016. 3. 18.. // Copyright © 2016년 XNRND. All rights reserved. // import UIKit import NotificationCenter extension UIInputViewController { func openURL(url: NSURL) -> Bool { do { let application = try self.sharedApplication() return application.performSelector("openURL:", withObject: url) != nil } catch { return false } } func sharedApplication() throws -> UIApplication { var responder: UIResponder? = self while responder != nil { if let application = responder as? UIApplication { return application } responder = responder?.nextResponder() } throw NSError(domain: "UIInputViewController+sharedApplication.swift", code: 1, userInfo: nil) } } class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet weak var number: UILabel! @IBAction func CallBtn(sender: UIButton) { print("Call") extensionContext?.openURL(NSURL(string: "foo://")!, completionHandler: nil) // let urlString = "tel://" + number.text! // print(urlString) // // let numberURL = NSURL(string: urlString) // UIApplication.sharedApplication().openURL(numberURL!) //UIApplication.openURL(numberURL) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view from its nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.NewData) } }
28.179487
102
0.619199
e20ed3215d3c5974c9e8da8ddd8a2302b6f23126
5,254
import TSCBasic import TuistCore import TuistGraph import TuistSupport import XCTest @testable import TuistSupportTesting final class SwiftPackageManagerControllerTests: TuistUnitTestCase { private var subject: SwiftPackageManagerController! override func setUp() { super.setUp() subject = SwiftPackageManagerController() } override func tearDown() { subject = nil super.tearDown() } func test_resolve() throws { // Given let path = try temporaryPath() system.succeedCommand([ "swift", "package", "--package-path", path.pathString, "resolve", ]) // When / Then XCTAssertNoThrow(try subject.resolve(at: path, printOutput: false)) } func test_update() throws { // Given let path = try temporaryPath() system.succeedCommand([ "swift", "package", "--package-path", path.pathString, "update", ]) // When / Then XCTAssertNoThrow(try subject.update(at: path, printOutput: false)) } func test_setToolsVersion_specificVersion() throws { // Given let path = try temporaryPath() let version = "5.4" system.succeedCommand([ "swift", "package", "--package-path", path.pathString, "tools-version", "--set", version, ]) // When / Then XCTAssertNoThrow(try subject.setToolsVersion(at: path, to: version)) } func test_setToolsVersion_currentVersion() throws { // Given let path = try temporaryPath() system.succeedCommand([ "swift", "package", "--package-path", path.pathString, "tools-version", "--set-current", ]) // When / Then XCTAssertNoThrow(try subject.setToolsVersion(at: path, to: nil)) } func test_loadPackageInfo() throws { // Given let path = try temporaryPath() system.succeedCommand( [ "swift", "package", "--package-path", path.pathString, "dump-package", ], output: PackageInfo.testJSON ) // When let packageInfo = try subject.loadPackageInfo(at: path) // Then XCTAssertEqual(packageInfo, PackageInfo.test) } func test_loadPackageInfo_alamofire() throws { // Given let path = try temporaryPath() system.succeedCommand( [ "swift", "package", "--package-path", path.pathString, "dump-package", ], output: PackageInfo.alamofireJSON ) // When let packageInfo = try subject.loadPackageInfo(at: path) // Then XCTAssertEqual(packageInfo, PackageInfo.alamofire) } func test_loadPackageInfo_googleAppMeasurement() throws { // Given let path = try temporaryPath() system.succeedCommand( [ "swift", "package", "--package-path", path.pathString, "dump-package", ], output: PackageInfo.googleAppMeasurementJSON ) // When let packageInfo = try subject.loadPackageInfo(at: path) // Then XCTAssertEqual(packageInfo, PackageInfo.googleAppMeasurement) } func test_buildFatReleaseBinary() throws { // Given let packagePath = try temporaryPath() let product = "my-product" let buildPath = try temporaryPath() let outputPath = try temporaryPath() system.succeedCommand([ "swift", "build", "--configuration", "release", "--disable-sandbox", "--package-path", packagePath.pathString, "--product", product, "--build-path", buildPath.pathString, "--triple", "arm64-apple-macosx", ]) system.succeedCommand([ "swift", "build", "--configuration", "release", "--disable-sandbox", "--package-path", packagePath.pathString, "--product", product, "--build-path", buildPath.pathString, "--triple", "x86_64-apple-macosx", ]) system.succeedCommand([ "lipo", "-create", "-output", outputPath.appending(component: product).pathString, buildPath.appending(components: "arm64-apple-macosx", "release", product).pathString, buildPath.appending(components: "x86_64-apple-macosx", "release", product).pathString, ]) // When try subject.buildFatReleaseBinary( packagePath: packagePath, product: product, buildPath: buildPath, outputPath: outputPath ) // Then // Assert that `outputPath` was created XCTAssertTrue(fileHandler.isFolder(outputPath)) } }
26.94359
98
0.530834
500445ebf2148a62156cf98b12c0184bf116839e
555
public enum Method: RawRepresentable { case notify case mSearch case httpOk public var rawValue: String { switch self { case .notify: return "NOTIFY" case .mSearch: return "M-SEARCH" case .httpOk: return "HTTP/1.1 200 OK" } } public init?(rawValue: String) { if rawValue == "NOTIFY" { self = Method.notify } else if rawValue == "M-SEARCH" { self = Method.mSearch } else if rawValue == "HTTP/1.1" { self = Method.httpOk } else { return nil } } }
26.428571
64
0.562162
c135ca05efd8e09a64bb92468cdbaa6c4e0f97c6
975
// // BlankView.swift // Devote // // Created by Christopher Bartling on 3/28/21. // import SwiftUI struct BlankView: View { var backgroundColor: Color var backgroundOpacity: Double var body: some View { VStack { Spacer() } .frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, minHeight: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, maxHeight: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: .center) .background(backgroundColor) .opacity(backgroundOpacity) .blendMode(.overlay) .edgesIgnoringSafeArea(.all) } } struct BlankView_Previews: PreviewProvider { static var previews: some View { BlankView(backgroundColor: Color.black, backgroundOpacity: 0.3) .background(BackgroundImageView()) .background(backgroundGradient.ignoresSafeArea(.all)) } }
28.676471
272
0.652308
d71f2c45698ac3376838fb97327da6db1bb8f30f
9,156
// // ViewController.swift // VideoQuickStart // // Copyright © 2016-2019 Twilio, Inc. All rights reserved. // import UIKit import AgoraRtcKit class ViewController: UIViewController { // MARK:- View Controller Members // Configure access token manually for testing, if desired! Create one manually in the console // at https://www.twilio.com/console/video/runtime/testing-tools var accessToken = "TWILIO_ACCESS_TOKEN" // Configure remote URL to fetch token from var tokenUrl = "http://localhost:8000/token.php" // Video SDK components var remoteView: UIView? var audioEnabled = true var agoraKit: AgoraRtcEngineKit! let AppID = "appID" // MARK:- UI Element Outlets and handles // `VideoView` created from a storyboard @IBOutlet weak var previewView: UIView! @IBOutlet weak var connectButton: UIButton! @IBOutlet weak var disconnectButton: UIButton! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var roomTextField: UITextField! @IBOutlet weak var roomLine: UIView! @IBOutlet weak var roomLabel: UILabel! @IBOutlet weak var micButton: UIButton! deinit { } // MARK:- UIViewController override func viewDidLoad() { super.viewDidLoad() self.title = "QuickStart" self.messageLabel.adjustsFontSizeToFitWidth = true; self.messageLabel.minimumScaleFactor = 0.75; initializeAgoraEngine() setupVideo() setupLocalVideo(uid: 0) if PlatformUtils.isSimulator { self.previewView.removeFromSuperview() } else { // Preview our local camera track in the local video preview view. startPreview() } // Disconnect and mic button will be displayed when the Client is connected to a Room. self.disconnectButton.isHidden = true self.micButton.isHidden = true self.roomTextField.autocapitalizationType = .none self.roomTextField.delegate = self let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)) self.view.addGestureRecognizer(tap) } func initializeAgoraEngine() { let appDelegate = UIApplication.shared.delegate as! AppDelegate agoraKit = AgoraRtcEngineKit.sharedEngine(withAppId: appDelegate.AppID, delegate: self) } func setupVideo() { agoraKit.enableVideo() agoraKit.setVideoEncoderConfiguration(AgoraVideoEncoderConfiguration(size: AgoraVideoDimension640x360, frameRate: .fps15, bitrate: AgoraVideoBitrateStandard, orientationMode: .adaptative) ) // Default video profile is 360P } func startPreview() { if PlatformUtils.isSimulator { return } previewView.backgroundColor = UIColor.orange let videoCanvas = AgoraRtcVideoCanvas() videoCanvas.uid = 0 videoCanvas.view = previewView videoCanvas.renderMode = .hidden agoraKit.setupLocalVideo(videoCanvas) } func setupLocalVideo(uid: UInt) { previewView.tag = Int(uid) previewView.backgroundColor = UIColor.orange let videoCanvas = AgoraRtcVideoCanvas() videoCanvas.uid = uid videoCanvas.view = previewView videoCanvas.renderMode = .hidden agoraKit.setupLocalVideo(videoCanvas) } @IBAction func toggleMic(sender: AnyObject) { agoraKit.muteLocalAudioStream(audioEnabled) audioEnabled = !audioEnabled // Update the button title if (audioEnabled) { self.micButton.setTitle("Mute", for: .normal) } else { self.micButton.setTitle("Unmute", for: .normal) } } // MARK:- Private @objc func flipCamera() { agoraKit.switchCamera() } // Update our UI based upon if we are in a Room or not func showRoomUI(inRoom: Bool) { self.connectButton.isHidden = inRoom self.roomTextField.isHidden = inRoom self.roomLine.isHidden = inRoom self.roomLabel.isHidden = inRoom self.micButton.isHidden = !inRoom self.disconnectButton.isHidden = !inRoom self.navigationController?.setNavigationBarHidden(inRoom, animated: true) UIApplication.shared.isIdleTimerDisabled = inRoom // Show / hide the automatic home indicator on modern iPhones. self.setNeedsUpdateOfHomeIndicatorAutoHidden() } @objc func dismissKeyboard() { if (self.roomTextField.isFirstResponder) { self.roomTextField.resignFirstResponder() } } func logMessage(messageText: String) { NSLog(messageText) messageLabel.text = messageText } @IBAction func connect(sender: AnyObject) { let channelName = self.roomTextField.text ?? "default" // Connect to the channel using the channel name provided. agoraKit.setDefaultAudioRouteToSpeakerphone(true) agoraKit.joinChannel(byToken: nil, channelId: channelName, info:nil, uid:0) {(sid, uid, elapsed) -> Void in print("successfully joined channel") } UIApplication.shared.isIdleTimerDisabled = true logMessage(messageText: "Attempting to connect to channel \(channelName)") self.showRoomUI(inRoom: true) self.dismissKeyboard() } @IBAction func disconnect(sender: AnyObject) { agoraKit.leaveChannel(nil) } func setupRemoteVideoView(uid: UInt) { // Creating `VideoView` programmatically self.remoteView = UIView() remoteView?.tag = Int(uid) remoteView?.backgroundColor = UIColor.purple let videoCanvas = AgoraRtcVideoCanvas() videoCanvas.uid = uid videoCanvas.view = remoteView videoCanvas.renderMode = .hidden agoraKit.setupRemoteVideo(videoCanvas) self.view.insertSubview(self.remoteView!, at: 0) // `VideoView` supports scaleToFill, scaleAspectFill and scaleAspectFit // scaleAspectFit is the default mode when you create `VideoView` programmatically. self.remoteView!.contentMode = .scaleAspectFit; let centerX = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0); self.view.addConstraint(centerX) let centerY = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0); self.view.addConstraint(centerY) let width = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.width, multiplier: 1, constant: 0); self.view.addConstraint(width) let height = NSLayoutConstraint(item: self.remoteView!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.height, multiplier: 1, constant: 0); self.view.addConstraint(height) } } // MARK:- UITextFieldDelegate extension ViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.connect(sender: textField) return true } } extension ViewController: AgoraRtcEngineDelegate { func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) { setupRemoteVideoView(uid: uid) } internal func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid:UInt, reason:AgoraUserOfflineReason) { self.remoteView?.removeFromSuperview() self.remoteView = nil } }
35.765625
230
0.599279
cc51c14fdbf932c2812eda7dfdafd08716889710
402
// // File.swift // Charito // // Created by Amit on 8/23/18. // Copyright © 2018 Auzia. All rights reserved. // import Foundation class Game { var topics: [Topic] var pickedTopic: Int var score: Float init(topics: [Topic], pickedTopic: Int = 0, score: Float = 0.0){ self.topics = topics self.pickedTopic = pickedTopic self.score = score } }
17.478261
68
0.59204