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
9183c331ffe35bbd355e3dbc7a6cc1dde519a87e
2,697
// // StorageService.swift // TopMoviePlayer // // Created by Sergei Popyvanov on 19.09.2020. // Copyright © 2020 Sergey Popyvanov. All rights reserved. // import Foundation import CoreData protocol StorageService { func addToFavorite(_ film: TopMovieData) func deleteFromFavorite(_ film: TopMovieData) func isFavorite(id: Int) -> Bool func fetchAllFavoriteFilms() -> [TopMovieData] } final class StorageServiceImpl: StorageService { // MARK: - Private Properties private let persistentContainer: NSPersistentContainer private var backgroundContext: NSManagedObjectContext { persistentContainer.newBackgroundContext() } // MARK: - Initializers init(persistentContainer: NSPersistentContainer) { self.persistentContainer = persistentContainer } // MARK: - Public Methods func addToFavorite(_ film: TopMovieData) { let context = backgroundContext let topMovieDataModel = TopMovieDataModel(context: context) topMovieDataModel.id = Int32(film.id) topMovieDataModel.title = film.title topMovieDataModel.description_ = film.description topMovieDataModel.posterURL = film.posterURL saveContext(context) } func deleteFromFavorite(_ film: TopMovieData) { let context = backgroundContext let request: NSFetchRequest<TopMovieDataModel> = TopMovieDataModel.fetchRequest() request.predicate = NSPredicate(format: "id = %@", String(film.id)) let fetchResults = (try? context.fetch(request)) ?? [] guard let deleteObject = fetchResults.first else { return } context.delete(deleteObject) saveContext(context) } func isFavorite(id: Int) -> Bool { let context = backgroundContext let request: NSFetchRequest<TopMovieDataModel> = TopMovieDataModel.fetchRequest() let fetchResults = (try? context.fetch(request)) ?? [] return fetchResults.contains(where: { Int($0.id) == id }) } func fetchAllFavoriteFilms() -> [TopMovieData] { let context = backgroundContext let request: NSFetchRequest<TopMovieDataModel> = TopMovieDataModel.fetchRequest() let fetchResults = (try? context.fetch(request)) ?? [] return fetchResults.map { TopMovieData(topMovieDataModel: $0) } } // MARK: - Private Methods private func saveContext(_ context: NSManagedObjectContext) { if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
31.729412
89
0.667408
0e6a8d133fc1246c114dae35c33d9c2be23c32d7
2,341
// // AppDelegate.swift // SwiftCamera // // Created by Mohamed Rias <[email protected]> on 12/06/2017. // Copyright (c) 2017 Mohamed Rias <[email protected]>. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { /* Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. */ } func applicationDidEnterBackground(application: UIApplication) { /* Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. */ } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
41.803571
194
0.709526
0a1c7b4664e2aab58b6ae422d303c7d072edc7b9
510
// // SearchWordNetworkRequest.swift // Translate // // Created by Stanislav Ivanov on 29.03.2020. // Copyright © 2020 Stanislav Ivanov. All rights reserved. // import Foundation extension NetworkRequest { static func makeWordSearch(query: String, page: Int = 1, pageSize: Int = 5) -> NetworkRequest { let networkRequest = NetworkRequest() networkRequest.path = NetworkPath.search.rawValue + "?search=\(query)&page=\(page)&pageSize=\(pageSize)" return networkRequest } }
28.333333
112
0.694118
5b91ccea160f6c2dc0a9bc9469dca0d3314571d2
1,273
// // Articulo.swift // newsApp // // Created by Miguel Gutiérrez Moreno on 2/2/15. // Copyright (c) 2015 MGM. All rights reserved. // import Foundation import CoreData @objc(Articulo) class Articulo: NSManagedObject { // MARK: properties @NSManaged var fecha: NSDate @NSManaged var nombre: String @NSManaged var texto: String // MARK: métodos de ayuda class func entityName() -> String { return "Articulo" } class func articulos() -> [Articulo]? { let request = NSFetchRequest() let model = StoreNewsApp.defaultStore().model let entidad = model.entitiesByName[Articulo.entityName()] request.entity = entidad let sd = NSSortDescriptor(key: "nombre", ascending: true) request.sortDescriptors = [sd] let context = StoreNewsApp.defaultStore().context let result: [AnyObject]? do { result = try context.executeFetchRequest(request) return result as? [Articulo] } catch let error as NSError { NSException.raise(MensajesErrorCoreData.fetchFailed, format: MensajesErrorCoreData.errorFetchObjectFormat, arguments:getVaList([error])) return nil } } }
25.979592
148
0.626866
e588b27e64467e462f31b2b5c8bc5082a5bdfece
1,016
// // TestFullfilledParent.swift // CoreDataCodable // // Created by Alsey Coleman Miller on 11/2/17. // Copyright © 2017 ColemanCDA. All rights reserved. // import Foundation import CoreData import CoreDataCodable struct TestFullfilledParent: Codable, TestUnique { typealias Identifier = TestParent.Identifier var identifier: Identifier var child: TestChild? var children: [TestChild] } extension TestFullfilledParent: CoreDataCodable { static var identifierKey: CodingKey { return CodingKeys.identifier } static func findOrCreate(_ identifier: TestFullfilledParent.Identifier, in context: NSManagedObjectContext) throws -> TestParentManagedObject { let identifier = identifier.rawValue as NSNumber let identifierProperty = "identifier" let entityName = "TestParent" return try context.findOrCreate(identifier: identifier, property: identifierProperty, entityName: entityName) } }
25.4
147
0.708661
08f05b676982be76635f7b5f331a68a47f83feb0
1,889
import UIKit import CDockFramework @objc(CustomElementsFunctionsSwift) /** In this class you can handle callback from ContentDock SDK */ class CustomElementsFunctionsSwift: NSObject { /** This function calls when user custom elements initilized. Name of this function you can set in ContentDock admin panel - parameters: - elementView: UIView for your custom element */ @objc class func myElementFunction(_ elementView: UIView) { } /** Calls when user custom element been layouted(size changed, positions change and etc...) - parameters: - elementView: UIView for your redrawed element */ @objc class func layoutSubviews(_ elementView: UIView) { } /** Calls before device will rotate. - parameters: - orientation: Orientation that device will rotate to. You can use it as UIInterfaceOrientation(rawValue: orientation.intValue) */ @objc class func willRotateTo(_ orientation: NSNumber) { if let newOrientation: UIInterfaceOrientation = UIInterfaceOrientation(rawValue: orientation.intValue) { if newOrientation == .landscapeLeft || newOrientation == .landscapeRight { //do something cool } } } /** Calls after device been rotated. */ @objc class func didRotate() { if UIDevice.current.orientation.isLandscape { //do something cool } else { //do something others cool } } /** App Start */ @objc class func appStarted() { let vc = UIStoryboard(name: "CustomUI", bundle: nil).instantiateViewController(withIdentifier: "VCCustomTabs") as! UITabBarController let nc = UINavigationController(rootViewController: vc) CDockSDK.showCustomVC(nc) } }
26.236111
141
0.634198
f5b99870f902a2d9a8e6441fa06e4278d0154162
1,236
// // EngineClass+ControlFunctionable.swift // The App // // Created by Mikk Rätsep on 27/09/2017. // Copyright © 2017 High-Mobility GmbH. All rights reserved. // import Foundation extension EngineClass: ControlFunctionable { var boolValue: (ControlFunction.Kind) -> Bool? { return { guard $0 == .engine else { return nil } return self.on } } var controlFunctions: [ControlFunction] { let mainAction = ControlAction(name: "on", iconName: "EngineON") { errorHandler in Car.shared.sendEngineCommand(on: true) { if let error = $0 { errorHandler?(error) } } } let oppositeAction = ControlAction(name: "off", iconName: "EngineOFF") { errorHandler in Car.shared.sendEngineCommand(on: false) { if let error = $0 { errorHandler?(error) } } } return [DualControlFunction(kind: .engine, mainAction: mainAction, oppositeAction: oppositeAction, isMainTrue: true)] } var kinds: [ControlFunction.Kind] { return [.engine] } var stringValue: (ControlFunction.Kind) -> String? { return { _ in nil } } }
25.75
125
0.583333
6a6f4eae0f4186ef97c7e87445cc87bca8040be1
3,862
// // LeftTypeFiveViewController.swift // AnimatedDropdownMenu // // Created by JonyFang on 17/3/3. // Copyright © 2017年 JonyFang. All rights reserved. // import UIKit import AnimatedDropdownMenu class LeftTypeFiveViewController: UIViewController { // MARK: - Properties fileprivate let dropdownItems: [AnimatedDropdownMenu.Item] = [ AnimatedDropdownMenu.Item.init("From | Photography", nil, nil), AnimatedDropdownMenu.Item.init("From | Artwork", nil, nil), AnimatedDropdownMenu.Item.init("Others", nil, nil) ] fileprivate var selectedStageIndex: Int = 0 fileprivate var lastStageIndex: Int = 0 fileprivate var dropdownMenu: AnimatedDropdownMenu! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setupAnimatedDropdownMenu() view.backgroundColor = .white } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) resetNavigationBarColor() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) dropdownMenu.show() } // MARK: - Private Methods fileprivate func setupAnimatedDropdownMenu() { let dropdownMenu = AnimatedDropdownMenu(navigationController: navigationController, containerView: view, selectedIndex: selectedStageIndex, items: dropdownItems) dropdownMenu.cellBackgroundColor = UIColor.menuLightRedColor() dropdownMenu.cellSelectedColor = UIColor.menuDarkRedColor() dropdownMenu.menuTitleColor = UIColor.menuLightTextColor() dropdownMenu.menuArrowTintColor = UIColor.menuLightTextColor() dropdownMenu.cellTextColor = UIColor.menuLightTextColor() dropdownMenu.cellTextAlignment = .left dropdownMenu.cellSeparatorColor = .clear dropdownMenu.didSelectItemAtIndexHandler = { [weak self] selectedIndex in guard let strongSelf = self else { return } strongSelf.lastStageIndex = strongSelf.selectedStageIndex strongSelf.selectedStageIndex = selectedIndex guard strongSelf.selectedStageIndex != strongSelf.lastStageIndex else { return } //Configure Selected Action strongSelf.selectedAction() } self.dropdownMenu = dropdownMenu navigationItem.titleView = dropdownMenu } private func selectedAction() { print("\(dropdownItems[selectedStageIndex].title)") } fileprivate func resetNavigationBarColor() { navigationController?.navigationBar.barStyle = .black navigationController?.navigationBar.barTintColor = UIColor.menuLightRedColor() let textAttributes: [String: Any] = [ convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): UIColor.menuLightTextColor(), convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.navigationBarTitleFont() ] navigationController?.navigationBar.titleTextAttributes = convertToOptionalNSAttributedStringKeyDictionary(textAttributes) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
34.482143
169
0.676334
f8959f088808c4e24968c6807f8a72b04dc412e2
6,730
// // Copyright © 2020 Suppy.io - All rights reserved. // import Foundation @objc public final class SuppyConfig: NSObject { private let context: Context private let configFetcher: RetryExecutor private let variantsFetcher: RetryExecutor private let defaults: UserDefaults private let logger: Logger? internal init(context: Context, configFetcher: RetryExecutor? = nil, variantsFetcher: RetryExecutor? = nil, defaults: UserDefaults) { self.context = context self.defaults = defaults self.logger = context.enableDebugMode ? Logger() : nil if let fetcher = configFetcher { self.configFetcher = fetcher } else { self.configFetcher = RetryExecutor(with: ConfigFetcher(), logger: self.logger) } if let variantsFetcher = variantsFetcher { self.variantsFetcher = variantsFetcher } else { self.variantsFetcher = RetryExecutor(attempts: 1, with: VariantsFetcher(), logger: self.logger) } /// Registered defaults are never stored between runs of an application. /// /// Adds the registrationDictionary to the last item in every search list. This means that /// after NSUserDefaults has looked for a value in every other valid location, /// it will look in registered defaults. let defaultsRegister = context.dependencies.reduce(into: [:]) { (result, dependency) in result[dependency.name] = dependency.value } self.defaults.register(defaults: defaultsRegister) super.init() self.logger?.debug("anonymous ID: \(anonymousId)") } /// Maps the configurations received from the server into the UserDefaults following the dependencies name and type. private func handleSuccessFetch(_ fetchResult: FetchResult) { switch fetchResult { case let .newData(data): guard let config = Config(data: data, logger: logger), config.hasAttributes else { return } self.context.dependencies.forEach { dependency in guard let attribute = (config.attributes.first { $0.name == dependency.name }) else { logger?.debug("Dependency of name: \"\(dependency.name)\" was not returned from the server.") return } FetchResultHandler(defaults: defaults, logger: logger) .handle(mappedType: dependency.mappedType, defaultsKey: dependency.name, newValue: attribute.value) } case let .noData(httpStatusCode): logger?.debug("no data received - HTTP status code: \(httpStatusCode)") } } } extension SuppyConfig { /// UUID that identifies an SDK instance @objc public var anonymousId: String { return Persistence().anonymousId } /// Identifier of the variant to be used. @objc public var variantId: String? { get { Persistence().variantId } set { Persistence().save(variantId: newValue) } } /// Constructor /// /// Note on dependencies: /// Dependencies have 2 functions: /// 1 - To specify the name and (value) type of configurations required by an app. /// 2 - fallback when configuration isn't returned from the server. /// /// - parameters: /// - configId: Configuration used. /// - applicationName: Application identifier seen in the web interface routing table. /// - dependencies: Configurations required by the application. /// - suiteName: Intializes a UserDefaults database using the specified name /// @see https://developer.apple.com/documentation/foundation/userdefaults/1409957-init /// - enableDebugMode: Outputs configuration fetching and processing information. @objc public convenience init(configId: String, applicationName: String, dependencies: [Dependency], suiteName: String? = nil, enableDebugMode: Bool = false) { let defaults: UserDefaults if let suiteName = suiteName, let defaultSuite = UserDefaults(suiteName: suiteName) { defaults = defaultSuite } else { defaults = UserDefaults.standard } let context = Context(configId: configId, applicationName: applicationName, dependencies: dependencies, enableDebugMode: enableDebugMode) self.init(context: context, defaults: defaults) } /// Fetches the configuration correspondent to the init(configId:) parameter /// and updates the user defaults based on the init(dependencies:) parameter. /// /// - parameter completion: Called when fetching is complete irrespective of the result. @objc public func fetchConfiguration(completion: (() -> Void)? = nil) { logger?.debug("Fetching config") configFetcher.execute(context: context) { result in switch result { case let .success(fetchResult): self.handleSuccessFetch(fetchResult) case let .failure(error): self.logger?.error(error) } self.logger?.debug("Completed fetching config") completion?() } } /// Fetches variants of a configuration. /// /// - parameter completion: Called with a Dictionary<[String: String]> parameter /// when fetching is complete irrespective of the result. @objc public func fetchVariants(completion: (([String: String]) -> Void)? = nil) { logger?.debug("Fetching variants") variantsFetcher.execute(context: context) { result in var variants = [String: String]() switch result { case let .success(fetchResult): switch fetchResult { case let .newData(data): variants = Variant.toDictionary(data: data, logger: self.logger) case let .noData(httpStatusCode): self.logger?.debug("no variants received - HTTP status code: \(httpStatusCode)") } case let .failure(error): self.logger?.error(error) } self.logger?.debug("Completed fetching variants") completion?(variants) // completion must be called } } }
38.678161
120
0.593016
646de97a8d3ee4cc3298627bc14e0074c489a28d
1,255
import Foundation struct EntryModel { let title: String? let author: String? let creation: Date? let thumbnailURL: URL? let commentsCount: Int? let url: URL? init(withDictionary dictionary: [String: AnyObject]) { func dateFromDictionary(withAttributeName attribute: String) -> Date? { guard let rawDate = dictionary[attribute] as? Double else { return nil } return Date(timeIntervalSince1970: rawDate) } func urlFromDictionary(withAttributeName attribute: String) -> URL? { guard let rawURL = dictionary[attribute] as? String else { return nil } return URL(string: rawURL) } self.title = dictionary["title"] as? String self.author = dictionary["author"] as? String self.creation = dateFromDictionary(withAttributeName: "created_utc") self.thumbnailURL = urlFromDictionary(withAttributeName: "thumbnail") self.commentsCount = dictionary["num_comments"] as? Int self.url = urlFromDictionary(withAttributeName: "url") } }
29.880952
79
0.572112
39fd843c8e4b0358a6346e997ef0467f79cc165e
2,241
// // PostController.swift // App // // Created by Johann Kerr on 3/6/18. // import Foundation import Vapor import Fluent final class PostController : RouteCollection { func boot(router: Router) throws { // GET /posts // POST /posts let postRouter = router.grouped("posts") postRouter.get("/",use: index) postRouter.post("/", use: create) postRouter.get(Post.parameter, use: show) postRouter.delete(Post.parameter, use: destroy) postRouter.patch(Post.parameter, use: update) postRouter.get("/search", use: search) // Create Read Update Destroy } func index(_ req:Request) throws -> Future<[Post]> { return Post.query(on: req).all() } func create(_ req: Request) throws -> Future<Post> { /* { content: "hello world", author: "johann" } */ let post = try req.content.decode(Post.self).await(on: req) return post.save(on: req) } /// GET /posts/:id func show(_ req: Request) throws -> Future<Post> { return try req.parameter(Post.self) } /// DELETE /posts/:id func destroy(_ req: Request) throws -> Future<HTTPStatus> { return try req.parameter(Post.self).flatMap(to: HTTPStatus.self) { post in return post.delete(on: req).transform(to: .noContent) } } /// PATCH /posts/:id /// { content: "hello from vapor 3!!", author: "johann" } func update(_ req: Request) throws -> Future<Post> { return try flatMap(to: Post.self, req.parameter(Post.self), req.content.decode(Post.self)) { post, updatedPost in post.content = updatedPost.content post.author = updatedPost.author return post.save(on: req) } } /// /posts/search?author=Johann func search(_ req: Request) throws -> Future<[Post]> { guard let searchItem = req.query[String.self, at: "author"] else { throw Abort(.badRequest) } return Post.query(on: req).filter(\.author == searchItem).all() } }
26.05814
121
0.552878
d7f09c93542dcf44496ba1d527cc063fbb9ea0d1
11,883
// // ViewController.swift // MoreNumbers // // Created by primetimer on 02/23/2019. // Copyright (c) 2019 primetimer. All rights reserved. // import UIKit import BigInt import iosMath import PrimeFactors import MoreNumbers //class ViewController: UIViewController { // // var uiinput : UITextField! // // override func viewDidLoad() { // // view.backgroundColor = .blue // // super.viewDidLoad() // // // uiinput = UITextField() // view.addSubview(uiinput) // uiinput.text = "Hallo x Welt" // //uiinput.isUserInteractionEnabled = true // uiinput.frame = CGRect(x: 20, y: 0, width: view.frame.width, height: 100) // // // Do any additional setup after loading the view. // } // // override func viewDidAppear(_ animated: Bool) { // view.backgroundColor = .blue // super.viewDidAppear(animated) // } // // //} #if true class ViewController: UIViewController { var uimath : MTMathUILabel! var uilabel : UILabel! var uiinput : UITextField! // private func testPIN() { let pcalc = PrimeCalculator() let pitable = PiTable(pcalc: pcalc, tableupto: 100000) let ml = PiMeisselLehmer(pcalc: pcalc, pitable: pitable) let n = BigUInt(100000*100000/10) let pin = ml.Pin(n: UInt64(n)) // let pintester = PinTester10n() print("Pin:",pin) } private func testSheldon() { let ptester = SheldonNumberTester() let n = BigUInt(73) let special = ptester.isSpecial(n: n, cancel: nil) let latex = ptester.getLatex(n: n) print(special!,latex!) uimath.latex = latex } private func testSheldonPrimeAsinOEIS() { let ptester = SheldonPrimeTester() let n = BigUInt(2475989) let special = ptester.isSpecial(n: n, cancel: nil) let latex = ptester.getLatex(n: n) print(special!,latex!) uimath.latex = latex } private func testCongruent() { let ptester = CongruentTester() // let n = BigUInt(318) let n = BigUInt(37) let special = ptester.isSpecial(n: n, cancel: nil) let latex = ptester.getLatex(n: n) print(special!,latex!) uimath.latex = latex } private func testSchizophrenic() { let t = SchizophrenicTester() let n = SchizophrenicTester.fn[27] let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testGelfond() { let t = MathConstantTester() let n = BigUInt(231) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testGompertz() { let t = RationalApproxTester(.gompertz) let n = BigUInt(124) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex let desc = t.Desc(n: n) print(desc) } private func testPadovan() { let t = PadovanTester() let n = PadovanTester.Nth(n: 13) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testViswanath() { let t = MathConstantTester() let n = BigUInt(113) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testAmicable() { let t = AmicableTester() // let n = BigUInt(220) let n = BigUInt(9363584) guard let special = t.isSpecial(n: n, cancel: TimeOut()) else { return } if special { let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } } private func testSocial() { let t = SocialTester() // let n = BigUInt(220) let n = BigUInt(12496) guard let special = t.isSpecial(n: n, cancel: TimeOut()) else { return } if special { let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } } private func testCarefree() { let t = MathConstantTester() let n = BigUInt(428) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testMultiplicativePersistence() { let t = MultiplicativePersistenceTester() let n = BigUInt(428) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testPrimorial() { let t2 = PrimorialTester() let n = BigUInt(30) //let n = BigUInt("304250263527210") let latex = t2.getLatex(n: n) print(latex!) uimath.latex = latex } private func testFactorial() { // let t = FactorialPrimeTester() let tf = FactorialTester() //let n = BigUInt(30029) let n = BigUInt("120")*BigUInt(6)*BigUInt(7) let latex = tf.getLatex(n: n) print(latex!) uimath.latex = latex } private func testSkewes() { let t = SkewesTester() let n = BigUInt(139) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testGraham() { let t = GrahamNumberTester() let n = BigUInt(387) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testRational() { // let t = RationalApproxTester(.pi) let n = BigUInt(22) //let n = BigUInt("304250263527210") // let latex = t.getLatex(n: n) // print(latex) // uimath.latex = latex for r in Tester.shared.completetesters { if r is RationalApproxTester { if r.isSpecial(n: n, cancel: nil) ?? false { let latex = r.getLatex(n: n) uimath.latex = latex } } } } private func testSquares() { let ts : [NumTester] = [SumOfTwoSquaresTester(),SumOf3SquaresTester(),SumOf4SquaresTester()] // let n = BigUInt(252) // 4 Squares // let n = BigUInt(381) // 3 Squares // let n = BigUInt(17*29) // 2 Square // let n = BigUInt(13) // 2 square prime let n = BigUInt(40) for t in ts { if t.isSpecial(n: n, cancel: nil) ?? false { let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } } } private func testPalindromic2() { let t = Palindromic2Tester() let n = BigUInt(1031) // let n = BigUInt(1030) // let n = BigUInt(1001) //Nothing let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testGoldbach(){ let t = GoldbachTester() let n = BigUInt(210) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testPadic() { let t = DivergentTester() // let n = BigUInt(404) // let n = BigUInt(334) // let n = BigUInt(445) // 1 / 3 // let n = BigUInt(666) let n = BigUInt(999) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testLookAndSay() { let t = LookAndSayTester() // let n = BigUInt(404) // let n = BigUInt(334) // let n = BigUInt(445) // 1 / 3 // let n = BigUInt(666) let n = BigUInt(1211) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testLattice() { let t = LatticeTester() // let n = BigUInt(404) // let n = BigUInt(334) // let n = BigUInt(445) // 1 / 3 // let n = BigUInt(666) let n = BigUInt(5) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testEisenstein() { let t = GeneralizedCubanPrimeTester() // let n = BigUInt(404) // let n = BigUInt(334) // let n = BigUInt(445) // 1 / 3 // let n = BigUInt(666) let n = BigUInt(21) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testGauss() { let t = PythagoreanPrimeTester() // let n = BigUInt(404) // let n = BigUInt(334) // let n = BigUInt(445) // 1 / 3 // let n = BigUInt(666) let n = BigUInt(2) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testEuler5() { let t = EulerCounterexampleTester() // let n = BigUInt(404) // let n = BigUInt(334) // let n = BigUInt(445) // 1 / 3 // let n = BigUInt(666) let n = BigUInt(144) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testFermatMiss() { let t = FermatNearMissTester() // let n = BigUInt(404) // let n = BigUInt(334) // let n = BigUInt(445) // 1 / 3 // let n = BigUInt(666) let n = BigUInt(12) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } private func testTower() { let t = PowerTowerTester() // let n = BigUInt(404) // let n = BigUInt(334) // let n = BigUInt(445) // 1 / 3 // let n = BigUInt(666) let n = BigUInt(256) let latex = t.getLatex(n: n) print(latex!) uimath.latex = latex } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //uiinput.becomeFirstResponder() print("Will Appear") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // uiinput.becomeFirstResponder() print("Did Appear") } override func viewDidLoad() { super.viewDidLoad() #if true uimath = MTMathUILabel() view.addSubview(uimath) uimath.frame = CGRect(x: 0, y: 100, width: view.frame.width, height: view.frame.height-100) #endif uiinput = UITextField() view.addSubview(uiinput) uiinput.text = "Hallo x Welt" //uiinput.isUserInteractionEnabled = true uiinput.frame = CGRect(x: 20, y: 0, width: view.frame.width, height: 100) //testAmicable() // testSocial() // testPIN() // testSheldon() //testCongruent() //testSheldonPrimeAsinOEIS() // testSheldon() // testPadovan() // testViswanath() // testCarefree() // testMultiplicativePersistence() // testPrimorial() // testFactorial() // testGelfond() // testRational() // testSkewes() // testGraham() // testSquares() // testGompertz() // testPadic() // testPalindromic2() // testLookAndSay() // testLattice() // testGoldbach() // testEisenstein() // testGauss() // testEuler5() testTower() //uimath.latex = "\\triangle" // Do any additional setup after loading the view, typically from a nib. } } #endif
27.130137
100
0.508289
fb23f9ba8f2f26135c3364b9736f43d391f6cb5b
311
// // EthSignerError.swift // ZKSync // // Created by Eugene Belyakov on 11/01/2021. // import Foundation public enum EthSignerError: Error { case invalidKey case invalidMessage case invalidMnemonic case signingFailed case invalidTransactionType(String) case unsupportedOperation }
17.277778
45
0.729904
035aae2dc9ecfb3b36b2edcc03e58baf523831c3
1,183
// // MarkerViewDot.swift // motoRoutes // // Created by Peter Pohlmann on 21.12.16. // Copyright © 2016 Peter Pohlmann. All rights reserved. // import Foundation import UIKit import Mapbox class MarkerViewDot: MGLAnnotationView { var initFrame = CGRect(x: 0, y: 0, width: 30, height: 30) var dot = DotAnimation() //MARK: INIT init(reuseIdentifier: String, color: UIColor) { super.init(reuseIdentifier: reuseIdentifier) dot = DotAnimation(frame: CGRect(x: initFrame.width/2, y: initFrame.height/2, width: initFrame.width, height: initFrame.height), color: blue1) dot.tag=100 self.addSubview(dot) dot.addDotAnimation() } //MARK: Initialiser override init(frame: CGRect) { super.init(frame: initFrame) print("init markerview frame") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
25.170213
150
0.639899
3a9049c9c7820defc1a3efc58f8b39eadfd2adf7
3,077
// ASCollectionView. Created by Apptek Studios 2019 import Foundation final class ASCache<Key: Hashable, Value> { private let wrappedCache = NSCache<WrappedKey, Entry>() private let keyTracker = KeyTracker() private let entryLifetime: TimeInterval? init(entryLifetime: TimeInterval? = nil) { self.entryLifetime = entryLifetime wrappedCache.delegate = keyTracker } subscript(_ key: Key) -> Value? { get { value(forKey: key) } set { setValue(newValue, forKey: key) } } func setValue(_ value: Value?, forKey key: Key) { guard let value = value else { removeValue(forKey: key) return } let expirationDate = entryLifetime.map { Date().addingTimeInterval($0) } let entry = Entry(key: key, value: value, expirationDate: expirationDate) setEntry(entry) } func value(forKey key: Key) -> Value? { return entry(forKey: key)?.value } func removeValue(forKey key: Key) { wrappedCache.removeObject(forKey: WrappedKey(key)) } } private extension ASCache { func entry(forKey key: Key) -> Entry? { guard let entry = wrappedCache.object(forKey: WrappedKey(key)) else { return nil } guard !entry.hasExpired else { removeValue(forKey: key) return nil } return entry } func setEntry(_ entry: Entry) { wrappedCache.setObject(entry, forKey: WrappedKey(entry.key)) keyTracker.keys.insert(entry.key) } } private extension ASCache { final class KeyTracker: NSObject, NSCacheDelegate { var keys = Set<Key>() func cache( _ cache: NSCache<AnyObject, AnyObject>, willEvictObject object: Any) { guard let entry = object as? Entry else { return } keys.remove(entry.key) } } } private extension ASCache { final class WrappedKey: NSObject { let key: Key init(_ key: Key) { self.key = key } override var hash: Int { return key.hashValue } override func isEqual(_ object: Any?) -> Bool { guard let value = object as? WrappedKey else { return false } return value.key == key } } final class Entry { let key: Key let value: Value let expirationDate: Date? var hasExpired: Bool { if let expirationDate = expirationDate { // Discard values that have expired return Date() >= expirationDate } return false } init(key: Key, value: Value, expirationDate: Date? = nil) { self.key = key self.value = value self.expirationDate = expirationDate } } } extension ASCache.Entry: Codable where Key: Codable, Value: Codable {} extension ASCache: Codable where Key: Codable, Value: Codable { convenience init(from decoder: Decoder) throws { self.init() let container = try decoder.singleValueContainer() let entries = try container.decode([Entry].self) // Only load non-expired entries entries.filter { !$0.hasExpired }.forEach(setEntry) } func encode(to encoder: Encoder) throws { // Only save non-expired entries let currentEntries = keyTracker.keys.compactMap(entry).filter { !$0.hasExpired } var container = encoder.singleValueContainer() try container.encode(currentEntries) } }
19.23125
82
0.691908
4a5372d3871922012fbec49a128fcd45afdc59c3
19,160
///* // * MachinesTestCase.swift // * MachinesTests // * // * Created by Callum McColl on 19/02/2017. // * Copyright © 2017 Callum McColl. All rights reserved. // * // * Redistribution and use in source and binary forms, with or without // * modification, are permitted provided that the following conditions // * are met: // * // * 1. Redistributions of source code must retain the above copyright // * notice, this list of conditions and the following disclaimer. // * // * 2. Redistributions in binary form must reproduce the above // * copyright notice, this list of conditions and the following // * disclaimer in the documentation and/or other materials // * provided with the distribution. // * // * 3. All advertising materials mentioning features or use of this // * software must display the following acknowledgement: // * // * This product includes software developed by Callum McColl. // * // * 4. Neither the name of the author nor the names of contributors // * may be used to endorse or promote products derived from this // * software without specific prior written permission. // * // * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER // * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // * // * ----------------------------------------------------------------------- // * This program is free software; you can redistribute it and/or // * modify it under the above terms or under the terms of the GNU // * General Public License as published by the Free Software Foundation; // * either version 2 of the License, or (at your option) any later version. // * // * This program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with this program; if not, see http://www.gnu.org/licenses/ // * or write to the Free Software Foundation, Inc., 51 Franklin Street, // * Fifth Floor, Boston, MA 02110-1301, USA. // * // */ // //import Foundation //@testable import SwiftMachines //import XCTest // //public class MachinesTestCase: XCTestCase { // // public var pingPongBuildDir: URL { // return URL(fileURLWithPath: "machines/PingPong.machine/.build/PingPongMachine", isDirectory: true) // } // // public let pingPongFiles: [URL] = [ // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Package.swift"), // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Sources/PingPongMachine/CallbackSleepingState.swift"), // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Sources/PingPongMachine/EmptySleepingState.swift"), // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Sources/PingPongMachine/factory.swift"), // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Sources/PingPongMachine/main.swift"), // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Sources/PingPongMachine/PingPongRinglet.swift"), // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Sources/PingPongMachine/PingPongVars.swift"), // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Sources/PingPongMachine/PingState.swift"), // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Sources/PingPongMachine/PongState.swift"), // URL(fileURLWithPath: "machines/PingPong/.build/PingPongMachine/Sources/PingPongMachine/SleepingState.swift") // ] // // public let pingPongMachine = Machine( // name: "PingPong", // filePath: URL(fileURLWithPath: NSString(string: "machines/PingPong.machine").standardizingPath, isDirectory: true).resolvingSymlinksInPath(), // externalVariables: [], // packageDependencies: [], // swiftIncludeSearchPaths: [ // "/usr/local/include/swiftfsm" // ], // includeSearchPaths: [ // "/usr/local/include", // "../../../../..", // "../../../../../../Common" // ], // libSearchPaths: [ // "/usr/local/lib", // "/usr/local/lib/swiftfsm" // ], // imports: "", // includes: nil, // vars: [], // model: Model( // actions: ["onEntry"], // ringlet: Ringlet( // imports: "", // vars: [ // Variable( // accessType: .readAndWrite, // label: "previousState", // type: "PingPongState", // initialValue: "EmptyPingPongState(\"_previous\")" // ) // ], // execute: "// Call onEntry if we have just transitioned into this state.\nif (state != previousState) {\n state.onEntry()\n}\npreviousState = state\n// Can we transition to another state?\nif let target = checkTransitions(forState: state) {\n // Yes - Return the next state to execute.\n return target\n}\nreturn state" // ) // ), // parameters: nil, // returnType: nil, // initialState: State( // name: "Ping", // imports: "", // vars: [], // actions: [ // Action(name: "onEntry", implementation: "print(\"Ping\")") // ], // transitions: [Transition(target: "Pong", condition: nil)] // ), // suspendState: nil, // states: [ // State( // name: "Ping", // imports: "", // vars: [], // actions: [ // Action(name: "onEntry", implementation: "print(\"Ping\")") // ], // transitions: [Transition(target: "Pong", condition: nil)] // ), // State( // name: "Pong", // imports: "", // vars: [], // actions: [ // Action(name: "onEntry", implementation: "print(\"Pong\")") // ], // transitions: [Transition(target: "Ping", condition: nil)] // ) // ], // submachines: [], // callableMachines: [], // invocableMachines: [] // ) // // public var controllerBuildDir: URL { // return URL(fileURLWithPath: "machines/Controller.machine/.build/ControllerMachine", isDirectory: true) // } // // public let controllerFiles: [URL] = [ // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachineBridging/Package.swift"), // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachineBridging/Controller-Bridging-Header.h"), // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachineBridging/module.modulemap"), // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachine/Package.swift"), // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachine/Sources/ControllerMachine/ControllerState.swift"), // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachine/Sources/ControllerMachine/ControllerVars.swift"), // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachine/Sources/ControllerMachine/ExitState.swift"), // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachine/Sources/ControllerMachine/wb_count.swift"), // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachine/Sources/ControllerMachine/factory.swift"), // URL(fileURLWithPath: "machines/Controller/.build/ControllerMachine/Sources/ControllerMachine/main.swift") // ] // // public var controllerMachine: Machine { // return Machine( // name: "Controller", // filePath: URL(fileURLWithPath: NSString(string: "machines/Controller.machine").standardizingPath, isDirectory: true).resolvingSymlinksInPath(), // externalVariables: [ // Variable( // accessType: .readOnly, // label: "wbcount", // type: "WhiteboardVariable<wb_count>", // initialValue: "WhiteboardVariable<wb_count>(msgType: kCount_v)" // ) // ], // packageDependencies: [], // swiftIncludeSearchPaths: [ // "/usr/local/include/swiftfsm" // ], // includeSearchPaths: [ // "/usr/local/include", // "../../../../..", // "../../../../../../Common" // ], // libSearchPaths: [ // "/usr/local/lib", // "/usr/local/lib/swiftfsm" // ], // imports: "", // includes: "#include <gu_util.h>", // vars: [], // parameters: nil, // returnType: nil, // initialState: State( // name: "Controller", // imports: "", // vars: [ // Variable( // accessType: .readAndWrite, // label: "count", // type: "UInt8", // initialValue: "0" // ) // ], // actions: [ // Action(name: "onEntry", implementation: "PingPongMachine.restart()\ncount = 0"), // Action(name: "main", implementation: "count += 1"), // Action(name: "onExit", implementation: "PingPongMachine.exit()") // ], // transitions: [Transition(target: "Add", condition: "state.count >= 100")] // ), // suspendState: nil, // states: [ // State( // name: "Controller", // imports: "", // vars: [ // Variable( // accessType: .readAndWrite, // label: "count", // type: "UInt8", // initialValue: "0" // ) // ], // actions: [ // Action(name: "onEntry", implementation: "PingPongMachine.restart()\ncount = 0"), // Action(name: "main", implementation: "count += 1"), // Action(name: "onExit", implementation: "PingPongMachine.exit()") // ], // transitions: [Transition(target: "Exit", condition: "state.count >= 100")] // ), // State( // name: "Add", // imports: "", // vars: [ // Variable( // accessType: .readAndWrite, // label: "promise", // type: "Promise<Int>", // initialValue: nil // ) // ], // actions: [ // Action(name: "onEntry", implementation: "promise = SumMachine(a: 2, b: 3)"), // Action(name: "main", implementation: ""), // Action(name: "onExit", implementation: "print(\"result: \\(promise.result)\")") // ], // transitions: [Transition(target: "Add_2", condition: "state.promise.hasFinished")] // ), // State( // name: "Add_2", // imports: "", // vars: [ // Variable( // accessType: .readAndWrite, // label: "promise", // type: "Promise<Int>", // initialValue: nil // ) // ], // actions: [ // Action(name: "onEntry", implementation: "promise = SumMachine(a: 2, b: 3)"), // Action(name: "main", implementation: ""), // Action(name: "onExit", implementation: "print(\"result: \\(promise.result)\")") // ], // transitions: [Transition(target: "Exit", condition: "state.promise.hasFinished")] // ), // State( // name: "Exit", // imports: "", // vars: [], // actions: [ // Action(name: "onEntry", implementation: ""), // Action(name: "main", implementation: ""), // Action(name: "onExit", implementation: "") // ], // transitions: [] // ) // ], // submachines: [self.pingPongMachine], // callableMachines: [self.factorialMachine], // invocableMachines: [self.sumMachine] // ) // } // // public let factorialMachine = Machine( // name: "Factorial", // filePath: URL(fileURLWithPath: NSString(string: "machines/Factorial.machine").standardizingPath, isDirectory: true).resolvingSymlinksInPath(), // externalVariables: [], // packageDependencies: [], // swiftIncludeSearchPaths: [ // "/usr/local/include/swiftfsm" // ], // includeSearchPaths: [ // "/usr/local/include", // "../../../../..", // "../../../../../../Common" // ], // libSearchPaths: [ // "/usr/local/lib", // "/usr/local/lib/swiftfsm" // ], // imports: "", // includes: "", // vars: [Variable(accessType: .readAndWrite, label: "total", type: "UInt", initialValue: "1")], // parameters: [ // Variable(accessType: .readAndWrite, label: "num", type: "UInt", initialValue: "1") // ], // returnType: "UInt", // initialState: State( // name: "Factorial", // imports: "", // vars: [], // actions: [ // Action(name: "onEntry", implementation: ""), // Action(name: "main", implementation: ""), // Action(name: "onExit", implementation: "") // ], // transitions: [ // Transition(target: "Recurse", condition: "num > 0"), // Transition(target: "Exit", condition: "num <= 1") // ] // ), // suspendState: nil, // states: [ // State( // name: "Factorial", // imports: "", // vars: [], // actions: [ // Action(name: "onEntry", implementation: ""), // Action(name: "main", implementation: ""), // Action(name: "onExit", implementation: "") // ], // transitions: [ // Transition(target: "Recurse", condition: "num > 0"), // Transition(target: "Exit", condition: "num <= 1") // ] // ), // State( // name: "Recurse", // imports: "", // vars: [Variable(accessType: .readAndWrite, label: "factorial", type: "Promise<UInt>", initialValue: nil)], // actions: [ // Action(name: "onEntry", implementation: "factorial = Factorial(num: num - 1)"), // Action(name: "main", implementation: ""), // Action(name: "onExit", implementation: "total = num * factorial.result") // ], // transitions: [ // Transition(target: "Exit", condition: "factorial.hasFinished") // ] // ), // State( // name: "Exit", // imports: "", // vars: [], // actions: [ // Action(name: "onEntry", implementation: "result = total\nprint(\"Factorial of \\(num) is \\(result)\")"), // Action(name: "main", implementation: ""), // Action(name: "onExit", implementation: "") // ], // transitions: [] // ) // ], // submachines: [], // callableMachines: [], // invocableMachines: [] // ) // // public let sumMachine = Machine( // name: "Sum", // filePath: URL(fileURLWithPath: NSString(string: "machines/Sum.machine").standardizingPath, isDirectory: true).resolvingSymlinksInPath(), // externalVariables: [], // packageDependencies: [], // swiftIncludeSearchPaths: [ // "/usr/local/include/swiftfsm" // ], // includeSearchPaths: [ // "/usr/local/include", // "../../../../..", // "../../../../../../Common" // ], // libSearchPaths: [ // "/usr/local/lib", // "/usr/local/lib/swiftfsm" // ], // imports: "", // includes: "", // vars: [], // parameters: [ // Variable(accessType: .readOnly, label: "a", type: "Int", initialValue: nil), // Variable(accessType: .readOnly, label: "b", type: "Int", initialValue: nil) // ], // returnType: "Int", // initialState: State( // name: "Initial", // imports: "", // vars: [], // actions: [ // Action(name: "onEntry", implementation: "result = a + b"), // Action(name: "main", implementation: ""), // Action(name: "onExit", implementation: "") // ], // transitions: [] // ), // suspendState: nil, // states: [ // State( // name: "Initial", // imports: "", // vars: [], // actions: [ // Action(name: "onEntry", implementation: "result = a + b"), // Action(name: "main", implementation: ""), // Action(name: "onExit", implementation: "") // ], // transitions: [] // ) // ], // submachines: [], // callableMachines: [], // invocableMachines: [] // ) // //}
44.249423
345
0.501461
216e31aac94d11b0d8971446e3a70fe639aa6a61
1,462
import XCTest @testable import ObjectUI final class ObjectUITests: XCTestCase { func testExample() { enum Value: String { case text } let object = Object() object.set(variable: Value.text, value: "Hello, World!") XCTAssertEqual(object.variable(named: Value.text).value(), "Hello, World!") } func testTextVariable() { let object = Object() object.set(variable: "text", value: "Hello, World!") XCTAssertEqual(object.text.value(), "Hello, World!") } func testArray() { let json = """ [ { "userId": 19, "id": 2, "title": "quis ut nam facilis et officia qui", "completed": false }, { "userId": 1, "id": 8, "title": "quo adipisci enim quam ut ab", "completed": true } ] """ .data(using: .utf8) let object = Object(json) XCTAssertEqual(object.array.count, 2) let post = object.array[0] XCTAssertEqual(post.userId.value(), 19) XCTAssertEqual(post.id.value(), 2) XCTAssertEqual(post.title.value(), "quis ut nam facilis et officia qui") XCTAssertEqual(post.completed.value(), false) } }
27.584906
83
0.471272
c137820b4a17af91677f596994b61b4fcbdda037
6,754
// // GroupedButtons.swift // UIKitten // // Created by Matteo Gavagnin on 15/03/2017. // Copyright © 2017 Dolomate. All rights reserved. // import UIKit public class GroupedButtons : UIView, Alignable { fileprivate var heightConstraint : NSLayoutConstraint? public var width: Width? public var height: Height? public var align : Align? public var margin = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) public var type : ButtonType = .normal { didSet { layoutIfNeeded() } } @IBInspectable public var typeString : String = "normal" { didSet { guard let typed = ButtonType(rawValue: typeString) else { return } type = typed } } fileprivate var buttons : [Button]? fileprivate let stackView = UIStackView() public var distribution : UIStackViewDistribution = .fillEqually { didSet { stackView.distribution = distribution layoutIfNeeded() } } public var axis : UILayoutConstraintAxis = .vertical { didSet { stackView.axis = axis layoutIfNeeded() } } public var spacing : CGFloat = 0 { didSet { stackView.spacing = spacing layoutIfNeeded() if spacing == 0 { for button in stackView.arrangedSubviews { if let button = button as? Button { button.style = .grouped } } } else { for button in stackView.arrangedSubviews { if let button = button as? Button { // TODO: don't override the button original style button.style = .normal } } } } } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } public init(frame: CGRect, buttons: [Button], axis: UILayoutConstraintAxis = .horizontal) { super.init(frame: frame) self.buttons = buttons self.axis = axis commonInit() } func commonInit() { if axis == .horizontal { bounds.size.height = Size.normal.height } else { bounds.size.height = Size.normal.height * CGFloat(stackView.arrangedSubviews.count) + CGFloat(stackView.arrangedSubviews.count - 1) * spacing } layer.cornerRadius = Style.normal.cornerRadius(height: bounds.size.height) layer.masksToBounds = true if stackView.superview != nil { stackView.removeFromSuperview() } stackView.frame = bounds stackView.axis = axis stackView.distribution = .fillEqually stackView.translatesAutoresizingMaskIntoConstraints = false addSubview(stackView) addConstraint(NSLayoutConstraint(item: stackView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: stackView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: stackView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: stackView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)) guard let buttons = buttons else { return } for arrangedView in stackView.arrangedSubviews { stackView.removeArrangedSubview(arrangedView) } for button in buttons { stackView.addArrangedSubview(button.style(.grouped)) } if axis == .horizontal { bounds.size.height = Size.normal.height } else { bounds.size.height = Size.normal.height * CGFloat(stackView.arrangedSubviews.count) + CGFloat(stackView.arrangedSubviews.count - 1) * spacing } stackView.frame.size.height = bounds.size.height layoutIfNeeded() } public func insert(button: Button, at: Int, animated: Bool = true) { if animated && axis == .horizontal { button.isHidden = true } if spacing == 0 { button.style = .grouped } stackView.insertArrangedSubview(button, at: at) if animated && axis == .horizontal { DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { UIView.animate(withDuration: 0.25, animations: { button.isHidden = false }) } } else { layoutIfNeeded() } } public func remove(button: Button, animated: Bool = true) { if animated && axis == .horizontal { UIView.animate(withDuration: 0.25, animations: { button.isHidden = true }) { (complete) in self.stackView.removeArrangedSubview(button) button.removeFromSuperview() } } else { self.stackView.removeArrangedSubview(button) button.removeFromSuperview() layoutIfNeeded() } } public override func layoutIfNeeded() { super.layoutIfNeeded() layer.borderWidth = type.borderWidth if spacing == 0 { layer.borderColor = type.borderColor.cgColor layer.cornerRadius = Style.normal.cornerRadius(height: bounds.size.height) } else { layer.borderColor = UIColor.clear.cgColor layer.cornerRadius = 0 } if heightConstraint == nil { heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1) addConstraint(heightConstraint!) } guard let heightConstraint = heightConstraint else { return } if axis == .vertical { heightConstraint.constant = Size.normal.height * CGFloat(stackView.arrangedSubviews.count) + CGFloat(stackView.arrangedSubviews.count - 1) * spacing } else { heightConstraint.constant = Size.normal.height } frame.size.height = heightConstraint.constant stackView.frame.size.height = bounds.size.height } }
33.77
169
0.573734
fb09b6a35275f6b315a37e5c1856721d400e4130
9,902
// // AppDelegate.swift // Cogs // /** * Copyright (C) 2017 Aviata Inc. All Rights Reserved. * This code is licensed under the Apache License 2.0 * * This license can be found in the LICENSE.txt at or near the root of the * project or repository. It can also be found here: * http://www.apache.org/licenses/LICENSE-2.0 * * You should have received a copy of the Apache License 2.0 license with this * code or source file. If not, please contact [email protected] */ import UIKit import CogsSDK // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } var DeviceTokenString: String = "" var Environment: String = "production" extension URL { func getKeyVals() -> Dictionary<String, String>? { var results = [String:String]() let keyValues = self.query?.components(separatedBy: "&") if keyValues?.count > 0 { for pair in keyValues! { let kv = pair.components(separatedBy: "=") if kv.count > 1 { results.updateValue(kv[1], forKey: kv[0]) } } } return results } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. sleep(3) // set API_BASE_URL #if DEBUG GambitService.sharedGambitService.baseURL = nil #else GambitService.sharedGambitService.baseURL = nil #endif // Register the supported notification types. let types: UIUserNotificationType = [.badge, .sound, .alert] let userSettings = UIUserNotificationSettings(types: types, categories: nil) application.registerUserNotificationSettings(userSettings) return true } func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { if notificationSettings.types != .none { // Register for remote notifications application.registerForRemoteNotifications() } } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { if let queryString = url.getKeyVals() { print(queryString) let prefs = UserDefaults.standard prefs.setValue(queryString["access_key"], forKey: "accessKey") prefs.setValue(queryString["client_salt"], forKey: "clientSalt") prefs.setValue(queryString["client_secret"], forKey: "clientSecret") prefs.setValue(queryString["campaign_id"], forKey: "campaignID") prefs.setValue(queryString["event_name"], forKey: "eventName") prefs.setValue(queryString["namespace"], forKey: "namespaceName") prefs.setValue(queryString["application_id"], forKey: "applicationID") prefs.synchronize() } 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. application.applicationIconBadgeNumber = 0 } 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:. } /** Request Message payload per message id from Cogs service - parameter request: GambitRequestMessage */ func gambitMessage(_ request: GambitRequestMessage) { let service = GambitService.sharedGambitService service.message(request) { data, response, error in do { guard let data = data else { // handle missing data response error DispatchQueue.main.async { var msg = "Request Failed" if let er = error { msg += ": \(er.localizedDescription)" } print(msg) } return } let json: JSON = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as JSON let msgResponse = try GambitMessageResponse(json: json) DispatchQueue.main.async { let alertController = UIAlertController(title: "Message Response", message: "\(msgResponse)", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)) self.window?.rootViewController?.present(alertController, animated: true, completion: nil) } // let parsedData = try GambitResponseEvent(json: json) } catch let error as NSError { DispatchQueue.main.async { print("Error: \(error)") if error.code == 1 { if let data = data { self.printErrorData(data) } } } } } } fileprivate func printErrorData(_ data: Data) { do { let json: JSON = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as JSON if let jsonString = json["message"] as? String { let msgJSON = try JSONSerialization.jsonObject(with: jsonString.data(using: String.Encoding.utf8)!, options: .allowFragments) DispatchQueue.main.async { let alertController = UIAlertController(title: "Message Response", message: "\(msgJSON)", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)) self.window?.rootViewController?.present(alertController, animated: true, completion: nil) } } } catch { } } // MARK: Notifications func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) DeviceTokenString = deviceTokenString print(DeviceTokenString) #if DEBUG Environment = "dev" #else Environment = "production" #endif print(Environment) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Fail to get token: \(error.localizedDescription)") } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { DispatchQueue.main.async { let alertController = UIAlertController(title: "Push Payload", message: "\(userInfo)", preferredStyle: UIAlertControllerStyle.alert) var msgRequest: GambitRequestMessage? if let msgID = userInfo["aviata_gambit_message_id"] as? String { let prefs = UserDefaults.standard if let accessKey = prefs.string(forKey: "accessKey"), let clientSalt = prefs.string(forKey: "clientSalt"), let clientSecret = prefs.string(forKey: "clientSecret"), let namespaceName = prefs.string(forKey: "namespaceName"), let attributesList = prefs.string(forKey: "attributesList") { do { let jsonAtts = try JSONSerialization .jsonObject(with: attributesList.data(using: String.Encoding.utf8)!, options: .allowFragments) msgRequest = GambitRequestMessage(accessKey: accessKey, clientSalt: clientSalt, clientSecret: clientSecret, token: msgID, namespace: namespaceName, attributes: jsonAtts as! [String: AnyObject]) } catch { print("Attributes Error! Invalid Attributes JSON.") } } } else { print("missing message ID") } let action = UIAlertAction(title: "View Message", style: UIAlertActionStyle.cancel) { _ in if msgRequest != nil { self.gambitMessage(msgRequest!) } } alertController.addAction(action) self.window?.rootViewController?.present(alertController, animated: true, completion: nil) } } }
37.086142
281
0.681882
901c6fbb534f639c35cea4dae52a0c3e505a9982
29,454
// VirtualSticksViewController.swift // // GPS Virtual Stick added by Kilian Eisenegger 01.12.2020 // This is a project from Dennis Baldwin and Kilian Eisenegger // Copyright © 2020 DroneBlocks & hdrpano. All rights reserved. // import UIKit import DJISDK class VirtualSticksViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var bearingLabel: UILabel! @IBOutlet weak var altitudeLabel: UILabel! @IBOutlet weak var xLabel: UILabel! @IBOutlet weak var yLabel: UILabel! @IBOutlet weak var zLabel: UILabel! @IBOutlet weak var gimbalPitchLabel: UILabel! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var missionButton: UIButton! @IBOutlet weak var speedLabel: UILabel! @IBOutlet weak var fpvView: UIView! @IBOutlet weak var fpvRatio: NSLayoutConstraint! @IBOutlet weak var remainingChargeSlider: UIProgressView! @IBOutlet weak var distanceTrigger: UIProgressView! //MARK: MKMapView var homeAnnotation = DJIImageAnnotation(identifier: "homeAnnotation") var aircraftAnnotation = DJIImageAnnotation(identifier: "aircraftAnnotation") var waypointAnnotation = DJIImageAnnotation(identifier: "waypointAnnotation") var aircraftAnnotationView: MKAnnotationView! var flightController: DJIFlightController? var timer: Timer? var photoTimer: Timer? // MARK: GCD Variables var queue = DispatchQueue(label: "com.virtual.myqueue") var photoDispatchGroup = DispatchGroup() var aircraftDispatchGroup = DispatchGroup() var yawDispatchGroup = DispatchGroup() var gimbalDispatchGroup = DispatchGroup() var GCDaircraftYaw: Bool = true var GCDphoto: Bool = true var GCDgimbal: Bool = true var GCDvs: Bool = true var GCDProcess: Bool = false var GCDaircraftYawFT: Double = 0 var GCDgimbalFT: Double = 0 var GCDvsFT: Double = 0 var GCDphotoFT: Double = 0 //MARK: GPS Variables var aircraftLocation: CLLocationCoordinate2D = kCLLocationCoordinate2DInvalid var aircraftLocationBefore: CLLocationCoordinate2D = kCLLocationCoordinate2DInvalid var homeLocation: CLLocationCoordinate2D = kCLLocationCoordinate2DInvalid var vsTargetLocation: CLLocationCoordinate2D = kCLLocationCoordinate2DInvalid var aircraftAltitude: Double = 0 var aircraftHeading: Double = 0 var vsTargetAltitude: Double = 0 var vsTargetAircraftYaw: Double = 0 var vsTargetGimbalPitch: Double = 0 var vsTargetGimbalYaw: Double = 0 var gimbalPitch: Double = 0 let start = Date() var vsSpeed: Float = 0 var sdCardCount: Int = 0 var photoCount: Int = 0 var bracketing: Int = 1 var nearTargetDistance: Double = 0.5 var intervall: Bool = false var distanceBetweenTwoPhotos: Double = 15 var triggerDistance: Double = 0 var GPSController = GPS() var vsController = VirtualSticksController() var camController = CameraController() var adapter: VideoPreviewerAdapter? override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent; } override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() self.mapView.delegate = self DJIVideoPreviewer.instance()?.start() self.adapter = VideoPreviewerAdapter.init() self.adapter?.start() // Grab a reference to the aircraft if let aircraft = DJISDKManager.product() as? DJIAircraft { // Debug Virtual Stick if it still on if self.vsController.isVirtualStick() { self.vsController.stopVirtualStick() } if self.vsController.isVirtualStickAdvanced() { self.vsController.stopAdvancedVirtualStick() } // Grab a reference to the flight controller if let fc = aircraft.flightController { // Store the flightController self.flightController = fc // Stop Virtual Stick if somebody touches the sticks let rc = aircraft.remoteController if rc != nil { rc?.delegate = self } // Prepare Virtual Stick let fcMode = DJIFlightOrientationMode.aircraftHeading self.flightController?.setFlightOrientationMode(fcMode, withCompletion: { (error: Error?) in if error != nil { print("Error setting FlightController Orientation Mode"); } }) self.flightController?.setMultipleFlightModeEnabled(true, withCompletion: { (error: Error?) in if error != nil { print("Error setting multiple flight mode"); } }) // Reset fpv View self.camController.setCameraMode(cameraMode: .shootPhoto) //MARK: ajust fpv view switch self.camController.getRatio() { case DJICameraPhotoAspectRatio.ratio4_3: fpvRatio.constant = 4/3 case DJICameraPhotoAspectRatio.ratio3_2: fpvRatio.constant = 3/2 case DJICameraPhotoAspectRatio.ratio16_9: fpvRatio.constant = 16/9 default: fpvRatio.constant = 4/3 } // Get remaining charge self.remainingChargeSlider.setProgress(Float(self.vsController.getChargeRemainingInPercent())/100, animated: false) self.missionButton.setTitle("Start Mission", for: .normal) } } } override func viewWillAppear(_ animated: Bool) { self.mapView.addAnnotations([self.aircraftAnnotation, self.homeAnnotation]) self.addKeys() DJIVideoPreviewer.instance()?.setView(self.fpvView) } //MARK: View Did Disappear override func viewDidDisappear(_ animated: Bool) { if self.vsController.isVirtualStick() { self.vsController.stopVirtualStick() } if self.vsController.isVirtualStickAdvanced() { self.vsController.stopAdvancedVirtualStick() } if self.timer != nil { self.timer?.invalidate() } } @IBAction func startVSMission(_ sender: UIButton) { self.timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(updateGCD), userInfo: nil, repeats: true) self.photoTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(distancePhotoTrigger), userInfo: nil, repeats: true) self.sdCardCount = self.camController.getSDPhotoCount() self.photoCount = 0 self.GCDProcess = true if !self.vsController.isVirtualStick() { self.vsController.startVirtualStick() } if !self.vsController.isVirtualStickAdvanced() { self.vsController.startAdvancedVirtualStick() } self.camController.setShootMode(shootMode: .single) self.deleteAnnotations() self.missionButton.setTitleColor(UIColor.red, for: .normal) self.missionButton.setTitle("Fly VS Star...", for: .normal) self.aircraftLocationBefore = self.aircraftLocation self.triggerDistance = 0 let grid = self.GPSController.star(radius: 50, points: 10, latitude: self.aircraftLocation.latitude, longitude: self.aircraftLocation.longitude, altitude: self.aircraftAltitude, pitch: -90) self.addWaypoints(grid: grid) self.startVSStarNow(grid: grid, speed: 4) } @IBAction func intervallSwitchAction(_ sender: UISwitch) { self.intervall = sender.isOn } //MARK: GCD Timer Dispatch Management @objc func updateGCD() { if !self.GCDaircraftYaw { self.showAircraftYaw() } if !self.GCDgimbal { self.showGimbal() } if !self.GCDphoto { self.showPhoto() } if !self.GCDvs { self.showVS() } } //MARK: GCD Timer Dispatch Management @objc func distancePhotoTrigger() { if self.aircraftLocationBefore.latitude != self.aircraftLocation.latitude || self.aircraftLocationBefore.longitude != self.aircraftLocation.longitude { let distance = self.GPSController.getDistanceBetweenTwoPoints(point1: self.aircraftLocationBefore, point2: self.aircraftLocation) self.triggerDistance += distance self.aircraftLocationBefore = self.aircraftLocation } if self.intervall {self.distanceTrigger.setProgress(Float(self.triggerDistance/self.distanceBetweenTwoPhotos), animated: false)} if self.triggerDistance >= self.distanceBetweenTwoPhotos && self.intervall { self.triggerDistance = 0 DispatchQueue.main.async() { self.camController.startShootPhoto() } } self.remainingChargeSlider.setProgress(Float(self.vsController.getChargeRemainingInPercent())/100, animated: false) } //MARK: Virtual Stick Yaw Aircraft func yawAircraft() { self.yawDispatchGroup.enter() self.GCDaircraftYaw = false self.GCDaircraftYawFT = self.start.timeIntervalSinceNow * -1 self.yawDispatchGroup.wait() } //MARK: Virtual Stick Move Aircraft func moveAircraft() { self.aircraftDispatchGroup.enter() self.GCDvs = false self.GCDvsFT = self.start.timeIntervalSinceNow * -1 self.aircraftDispatchGroup.wait() } //MARK: Move Gimbal GCD func moveGimbal() { self.gimbalDispatchGroup.enter() self.GCDgimbal = false self.GCDgimbalFT = self.start.timeIntervalSinceNow * -1 self.vsController.moveGimbal(pitch: Float(self.vsTargetGimbalPitch), roll: 0, yaw: 0, time: 1, rotationMode: .absoluteAngle) self.gimbalDispatchGroup.wait() } //MARK: Take Photo GCD func takePhoto() { self.photoDispatchGroup.enter() self.GCDphoto = false self.GCDphotoFT = self.start.timeIntervalSinceNow * -1 self.camController.startShootPhoto() self.photoDispatchGroup.wait() } //MARK: Add Key Listener private func addKeys() { //MARK: Location Listener if let locationKey = DJIFlightControllerKey(param: DJIFlightControllerParamAircraftLocation) { DJISDKManager.keyManager()?.startListeningForChanges(on: locationKey, withListener: self) { [unowned self] (oldValue: DJIKeyedValue?, newValue: DJIKeyedValue?) in if newValue != nil { let newLocationValue = newValue!.value as! CLLocation if CLLocationCoordinate2DIsValid(newLocationValue.coordinate) { self.aircraftLocation = newLocationValue.coordinate let gps = GPS() self.aircraftAnnotation.coordinate = newLocationValue.coordinate if !self.GCDvs { let distance = gps.getDistanceBetweenTwoPoints(point1: self.aircraftLocation, point2: self.vsTargetLocation) let bearing = gps.getBearingBetweenTwoPoints(point1: self.aircraftLocation, point2: self.vsTargetLocation) if distance < 1000 {self.distanceLabel.text = String((distance*10).rounded()/10) + "m"} self.bearingLabel.text = String((bearing*10).rounded()/10) + " °" let viewRegion = MKCoordinateRegion(center: self.aircraftLocation, latitudinalMeters: 100, longitudinalMeters: 100) self.mapView.setRegion(viewRegion, animated: true) self.mapView.setNeedsDisplay() } } } } //MARK: Focus on MapView DJISDKManager.keyManager()?.getValueFor(locationKey, withCompletion: { (value:DJIKeyedValue?, error:Error?) in if value != nil { let newLocationValue = value!.value as! CLLocation if CLLocationCoordinate2DIsValid(newLocationValue.coordinate) { self.aircraftLocation = newLocationValue.coordinate self.aircraftAnnotation.coordinate = newLocationValue.coordinate DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { let viewRegion = MKCoordinateRegion(center: self.aircraftLocation, latitudinalMeters: 200, longitudinalMeters: 200) self.mapView.setRegion(viewRegion, animated: true) self.mapView.setNeedsDisplay() } } } }) } //MARK: Aircraft Attitude Listener if let aircraftAttitudeKey = DJIFlightControllerKey(param: DJIFlightControllerParamAttitude) { DJISDKManager.keyManager()?.startListeningForChanges(on: aircraftAttitudeKey, withListener: self , andUpdate: { (oldValue: DJIKeyedValue?, newValue: DJIKeyedValue?) in if newValue != nil { let Vector = newValue!.value as! DJISDKVector3D // Double in degrees self.xLabel.text = String((Vector.x*10).rounded()/10) + "°" self.yLabel.text = String((Vector.y*10).rounded()/10) + "°" self.zLabel.text = String((Vector.z*10).rounded()/10) + "°" self.aircraftHeading = Vector.z self.aircraftAnnotation.heading = Vector.z if (self.aircraftAnnotationView != nil) { self.aircraftAnnotationView.transform = CGAffineTransform(rotationAngle: CGFloat(self.degreesToRadians(Double(self.aircraftAnnotation.heading)))) } self.speedLabel.text = String((self.vsController.velocity() * 10).rounded()/10) + "m/s" } }) } //MARK: Gimbal Attitude Listener if let gimbalAttitudeKey = DJIGimbalKey(param: DJIGimbalParamAttitudeInDegrees) { DJISDKManager.keyManager()?.startListeningForChanges(on: gimbalAttitudeKey, withListener: self , andUpdate: { (oldValue: DJIKeyedValue?, newValue: DJIKeyedValue?) in if newValue != nil { var gimbalAttitude = DJIGimbalAttitude() // Float in degrees let nsvalue = newValue!.value as! NSValue nsvalue.getValue(&gimbalAttitude) self.gimbalPitchLabel.text = String((gimbalAttitude.pitch*10).rounded()/10) + "°" self.gimbalPitch = Double(gimbalAttitude.pitch) } }) } //MARK: Altitude Listener if let altitudeKey = DJIFlightControllerKey(param: DJIFlightControllerParamAltitudeInMeters) { DJISDKManager.keyManager()?.startListeningForChanges(on: altitudeKey, withListener: self , andUpdate: { (oldValue: DJIKeyedValue?, newValue: DJIKeyedValue?) in if (newValue != nil) { self.altitudeLabel.text = String((newValue!.doubleValue*10).rounded()/10) + "m" self.aircraftAltitude = newValue!.doubleValue } }) } //MARK: Home Location Listener if let homeLocationKey = DJIFlightControllerKey(param: DJIFlightControllerParamHomeLocation) { DJISDKManager.keyManager()?.startListeningForChanges(on: homeLocationKey, withListener: self) { [unowned self] (oldValue: DJIKeyedValue?, newValue: DJIKeyedValue?) in if newValue != nil { let newLocationValue = newValue!.value as! CLLocation if CLLocationCoordinate2DIsValid(newLocationValue.coordinate) { self.homeLocation = newLocationValue.coordinate self.homeAnnotation.coordinate = newLocationValue.coordinate } } } DJISDKManager.keyManager()?.getValueFor(homeLocationKey, withCompletion: { (newValue:DJIKeyedValue?, error:Error?) in if newValue != nil { let newLocationValue = newValue!.value as! CLLocation if CLLocationCoordinate2DIsValid(newLocationValue.coordinate) { self.homeLocation = newLocationValue.coordinate self.homeAnnotation.coordinate = newLocationValue.coordinate } } }) } //MARK: SD Card Count Listener if let sdCountKey = DJICameraKey(param: DJICameraParamSDCardAvailablePhotoCount) { DJISDKManager.keyManager()?.startListeningForChanges(on: sdCountKey, withListener: self , andUpdate: { (oldValue: DJIKeyedValue?, newValue: DJIKeyedValue?) in if newValue != nil { self.photoCount += 1 self.missionButton.setTitle("Photo count \(self.photoCount)", for: .normal) if self.intervall { let annotation = DJIImageAnnotation(identifier: "Photo") annotation.title = "Photo" let gps = self.GPSController.coordinateString(self.aircraftLocation.latitude, self.aircraftLocation.longitude) annotation.subtitle = "\(gps)\n\(self.aircraftAltitude)m" annotation.coordinate = self.aircraftLocation self.mapView?.addAnnotation(annotation) } } }) } } //MARK: Show Virtual Stick Move Action func showVS() { var bearing = self.GPSController.getBearingBetweenTwoPoints(point1: self.aircraftLocation, point2: self.vsTargetLocation) let distance = self.GPSController.getDistanceBetweenTwoPoints(point1: self.aircraftLocation, point2: self.vsTargetLocation) // Slow down the aircraft when distance to target is close if distance <= Double(self.vsSpeed) && distance > self.nearTargetDistance { self.vsSpeed = max(Float(distance / 3), 0.2) if distance < self.nearTargetDistance * 2 { print("Close, slow speed \((self.vsSpeed*10).rounded()/10)m/s distance to target \((distance*10).rounded()/10)m") } } else { print("Move, distance to target \((distance*10).rounded()/10)m speed \((self.vsSpeed*10).rounded()/10)m/s") } // Move to the target altitude, control bearing to target bearing if self.aircraftAltitude - self.vsTargetAltitude > self.nearTargetDistance && distance < self.nearTargetDistance { bearing = self.vsTargetAircraftYaw print("Move vertical \(Int(self.aircraftAltitude)) target [\(Int(self.vsTargetAltitude))") } // Virtual Stick send command // Use pitch instead of roll for POI self.vsController.vsMove(pitch: 0, roll: self.vsSpeed, yaw: Float(bearing), vertical: Float(self.vsTargetAltitude)) // We reach the waypoint if distance < self.nearTargetDistance && self.aircraftAltitude - self.vsTargetAltitude < self.nearTargetDistance { self.vsController.vsMove(pitch: 0, roll: 0, yaw: Float(bearing), vertical: Float(self.vsTargetAltitude)) self.GCDvs = true print("VS Mission step complete") DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { self.aircraftDispatchGroup.leave() } } } //MARK: Show Aircraft Yaw Action func showAircraftYaw() { let time = self.start.timeIntervalSinceNow * -1 - self.GCDaircraftYawFT var velocity: Float = 45 var direction: Double = 1 if !self.GCDaircraftYaw { var diff: Double = abs(self.aircraftHeading - self.vsTargetAircraftYaw) if self.GPSController.yawControl(yaw: Float(self.vsTargetAircraftYaw - self.aircraftHeading)) < 0 { direction = -1 } else { direction = 1 } if diff >= 180 { diff = abs(diff - 360) } if diff < 2 { // 1.5° - 3° print("**** Aircraft yaw \(Int(diff*10)/10) yaw \(Int(self.aircraftHeading*10)/10) timeout \((time*10).rounded()/10)") self.GCDaircraftYaw = true DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { self.yawDispatchGroup.leave() } } else { print("**** Wait on aircraft yaw \(Int(diff*10)/10) yaw \(Int(self.aircraftHeading*10)/10) timeout \((time*10).rounded()/10)") if diff < 15 { velocity = Float(diff * direction) } else { velocity = velocity * Float(direction) } self.vsController.vsYaw(velocity: velocity) } // Timeout call on velocity 45°/s if time > 360 / 45 + 1 { self.GCDaircraftYaw = true self.yawDispatchGroup.leave() print("Timeout on aircraft yaw!") } } } //MARK: Show Gimbal Yaw Action func showGimbal() { let time = self.start.timeIntervalSinceNow * -1 - self.GCDgimbalFT if !self.GCDgimbal && time > 0.9 { let pitchDiff = abs(self.gimbalPitch - self.vsTargetGimbalPitch) if pitchDiff < 2 { // 1.5° - 3° print("Gimbal pitch \((pitchDiff*10).rounded()/10) heading \((self.aircraftHeading*10).rounded()/10)") self.GCDgimbal = true DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { self.gimbalDispatchGroup.leave() } } else { print("Wait on gimbal pitch \(self.gimbalPitch) timeout \((time*10).rounded()/10)") } // Timeout call if time > 2 { self.GCDgimbal = true self.gimbalDispatchGroup.leave() print("Timeout on gimbal yaw!") } } } //MARK: Show Photo Action func showPhoto() { let time = self.start.timeIntervalSinceNow * -1 - self.GCDphotoFT if !self.GCDphoto && time > 0.9 { print("Photo finished \(self.camController.getSDPhotoCount()) \(self.sdCardCount) \(time)") if time > 3 || self.sdCardCount - self.camController.getSDPhotoCount() > 0 { self.GCDphoto = true DispatchQueue.main.asyncAfter(deadline: .now() + 0.25 ) { self.photoDispatchGroup.leave() // send closure } } } } func stopVS() { self.GCDProcess = false self.camController.stopShootPhoto() if !self.GCDphoto { self.GCDphoto = true ; self.photoDispatchGroup.leave() } if !self.GCDgimbal { self.GCDgimbal = true; self.gimbalDispatchGroup.leave() } if !self.GCDaircraftYaw { self.GCDaircraftYaw = true; self.yawDispatchGroup.leave() } if !self.GCDvs { self.GCDvs = true; self.aircraftDispatchGroup.leave() } if self.vsController.isVirtualStick() { self.vsController.stopVirtualStick() } if self.vsController.isVirtualStickAdvanced() { self.vsController.stopAdvancedVirtualStick() } if self.timer != nil { self.timer?.invalidate() } if self.photoTimer != nil { self.photoTimer?.invalidate() } self.missionButton.setTitleColor(UIColor.white, for: .normal) self.missionButton.setTitle("Start Mission", for: .normal) } //MARK: Start 2D Virtual Stick Mission func startVSStarNow(grid: [[Double]], speed: Float = 4) { self.vsSpeed = speed // Trigger the LED lights self.vsController.frontLed(frontLEDs: false) self.queue.asyncAfter(deadline: .now() + 1.0) { for mP in grid { let lat = mP[0] let lon = mP[1] let alt = mP[2] let pitch = mP[3] if CLLocationCoordinate2DIsValid(CLLocationCoordinate2DMake(lat, lon)) && alt < 250 { self.vsTargetLocation.latitude = lat self.vsTargetLocation.longitude = lon self.vsTargetAltitude = alt self.vsTargetGimbalPitch = pitch self.vsTargetAircraftYaw = self.GPSController.getBearingBetweenTwoPoints(point1: self.aircraftLocation, point2:self.vsTargetLocation) self.moveGimbal() if abs(self.aircraftHeading - self.vsTargetAircraftYaw) > 5 { self.yawAircraft() if self.GCDProcess == false { break } // Exit point for dispatch group } self.vsSpeed = speed self.moveAircraft() if self.GCDProcess == false { break } // Exit point for dispatch group } } self.vsTargetGimbalPitch = 0 self.moveGimbal() // Trigger the LED lights self.vsController.frontLed(frontLEDs: true) print("Stop VS Star") DispatchQueue.main.asyncAfter(deadline: .now() + 1) { if self.GCDProcess { self.stopVS() } self.missionButton.setTitleColor(UIColor.white, for: .normal) self.missionButton.setTitle("GPS Fly VS Mission", for: .normal) } } } func degreesToRadians(_ degrees: Double) -> Double { return Double.pi / 180 * degrees } // MARK: MKMapViewDelegate mixed func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { var image: UIImage! if annotation.isEqual(self.aircraftAnnotation) { image = #imageLiteral(resourceName: "drone") } else if annotation.isEqual(self.homeAnnotation) { image = #imageLiteral(resourceName: "home_point") } else { image = #imageLiteral(resourceName: "navigation_poi_pin") } let imageAnnotation = annotation as! DJIImageAnnotation var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: imageAnnotation.identifier) if annotationView == nil { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: imageAnnotation.identifier) } if imageAnnotation.identifier == "Photo" { image = #imageLiteral(resourceName: "camera") } annotationView?.image = image if annotation.isEqual(self.aircraftAnnotation) { if annotationView != nil { self.aircraftAnnotationView = annotationView! } } return annotationView } //MARK: Delete Annotations func deleteAnnotations() { self.mapView?.annotations.forEach { if ($0 is MKPointAnnotation) { let title: String = $0.title! ?? "" if title.lowercased().range(of:"photo") != nil { self.mapView?.removeAnnotation($0) } } } } //MARK: Add Annotations func addWaypoints(grid: [[Double]]) { for mP in grid { let lat = mP[0] let lon = mP[1] let alt = mP[2] if CLLocationCoordinate2DIsValid(CLLocationCoordinate2DMake(lat, lon)) && alt < 250 { let annotation = DJIImageAnnotation(identifier: "Waypoint") annotation.title = "Waypoint" let gps = self.GPSController.coordinateString(lat, lon) annotation.subtitle = "\(gps)\n\(alt)m" annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon) self.mapView?.addAnnotation(annotation) NSLog("Add annotation \(gps)") } } } } //MARK: Remote Controller Delegate extension VirtualSticksViewController: DJIRemoteControllerDelegate { func remoteController(_ remoteController: DJIRemoteController, didUpdate state: DJIRCHardwareState) { if self.GCDProcess && (state.leftStick.verticalPosition != 0 || (state.leftStick.horizontalPosition != 0 || state.rightStick.verticalPosition != 0 || state.rightStick.horizontalPosition != 0) || state.goHomeButton.isClicked.boolValue) { NSLog("Stop VS \(state.leftStick) \(state.rightStick)") self.missionButton.setTitle("VS Remote Interrupt", for: .normal) self.stopVS() } } }
45.523957
244
0.594486
e67e97485b9bda2f607577d8a8f7a578447b8e0f
1,362
// // AppDelegate.swift // VIPER_Example // // Created by Anastasia Shepureva on 05.02.2021. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.810811
179
0.748164
9c8a453c5730f2e733d08661fd05dc549f1ed60a
17,101
// // HomeViewController.swift // ZhiBo_Swift // // Created by JornWu on 2017/2/27. // Copyright © 2017年 Jorn.Wu([email protected]). All rights reserved. // import UIKit import SnapKit class HomeViewController: BaseViewController, UIViewControllerTransitioningDelegate, UIScrollViewDelegate { ///点击“广场”按钮展开的下拉视图 private var dropDownMaskView: UIView! ///首页类别标签选择的滚动视图 private var labelSelectScrollView: UIScrollView! ///标签下的pageControl private var pageCtrl: UIView! ///右侧展开的种类标签按钮的容器视图 private var labelButtonContainerVC: UIViewController! ///中间的主视图 private var mainView: UIScrollView! private var mainContentView: UIView! ///热门中的内容视图 private var hotView: UIView! ///最新中的内容视图 private var newView: UIView! ///关注中的内容视图 private var loveView: LoveView! ///首页控制器对应的VM,处理首页中的所有业务逻辑 private lazy var homeVM: HomeViewModel = { return HomeViewModel() }() override func viewDidLoad() { super.viewDidLoad() self.createNavigationButtons() self.createDropDownView() self.createLabelScrollView() self.createLabelButtonContainerVC() self.createMainView() } func createNavigationButtons() { self.navigationController?.isNavigationBarHidden = false self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "search_15x14"), style: .done, target: self, action: nil) self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "head_crown_24x24"), style: .done, target: self, action: #selector(showRankingList)) let titleBtn = UIButton(type: .custom) titleBtn.setTitle("广场", for: .normal) titleBtn.setTitleColor(UIColor.white, for: .normal) titleBtn.setImage(#imageLiteral(resourceName: "title_down_9x16"), for: .normal) titleBtn.setImage(#imageLiteral(resourceName: "title_up_9x16"), for: .selected) titleBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 30, 0, -30) titleBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 30) titleBtn.frame = CGRect(x: 0, y: 0, width: 80, height: 40) self.navigationItem.titleView = titleBtn //titleBtn.rac_signalForControlEvents(UIControlEvents.TouchUpInside) titleBtn.addTarget(self, action: #selector(showDropDownView(clickedButton:)), for: .touchUpInside) } func showRankingList() { self.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(RankingListViewController(), animated: true) self.hidesBottomBarWhenPushed = false } func showDropDownView(clickedButton button: UIButton) { self.dropDownMaskView.isHidden = button.isSelected button.isSelected = !button.isSelected } func createDropDownView() { dropDownMaskView = UIView() dropDownMaskView.isHidden = true dropDownMaskView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8) self.view.addSubview(dropDownMaskView) let dropDownView = UIView() dropDownView.backgroundColor = UIColor.gray dropDownMaskView.addSubview(dropDownView) dropDownMaskView.snp.makeConstraints {(make) in make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(0, 0, 0, 0)) } dropDownView.snp.makeConstraints {(make) in //make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(0, 0, 500, 0)) //make.top.equalTo(self.view).offset(0) //make.left.equalTo(self.view).offset(0) //make.right.equalTo(self.view).offset(0) make.top.equalTo(0) make.left.equalTo(0) make.right.equalTo(0) make.height.equalTo(150) } } func createLabelScrollView() { let containerView = UIView() containerView.backgroundColor = UIColor.white self.view.insertSubview(containerView, at: 0) labelSelectScrollView = UIScrollView()///这里只设三个标签,如果更多的话,会用到滚动视图 //labelSelectScrollView.backgroundColor = UIColor.cyan; containerView.addSubview(labelSelectScrollView) let foldBtn = UIButton() foldBtn.setTitle("Open", for: .normal) foldBtn.titleLabel?.font = UIFont.systemFont(ofSize: 10) foldBtn.backgroundColor = UIColor.brown containerView.addSubview(foldBtn) foldBtn.addTarget(self, action: #selector(showLabelButtonContainerView), for: .touchUpInside) containerView.snp.makeConstraints { (make) in make.top.equalTo(0) make.left.equalTo(0) make.right.equalTo(0) make.height.equalTo(40) } labelSelectScrollView.snp.makeConstraints { (make) in make.top.equalTo(0) make.left.equalTo(0) make.right.equalTo(-40) make.height.equalTo(40) } foldBtn.snp.makeConstraints { (make) in make.top.equalTo(labelSelectScrollView.snp.top) make.right.lessThanOrEqualTo(0) make.width.height.equalTo(40) } let hotLabelBtn = UIButton(type: .custom) hotLabelBtn.setTitle("最热", for: .normal) hotLabelBtn.setTitleColor(UIColor(red: 223.0 / 225.0, green: 55.0 / 255.0, blue: 125.0 / 255.0, alpha: 1), for: .normal) ///默认选择热门这个标签 hotLabelBtn.tag = 100 //hotLabelBtn.backgroundColor = UIColor.blue hotLabelBtn.addTarget(self, action: #selector(labelButtonAction(clickedButton:)), for: .touchUpInside) let newLabelBtn = UIButton(type: .custom) newLabelBtn.setTitle("最新", for: .normal) newLabelBtn.setTitleColor(UIColor(red: 106.0 / 225.0, green: 37.0 / 255.0, blue: 99.0 / 255.0, alpha: 1), for: .normal) newLabelBtn.tag = 101 //newLabelBtn.backgroundColor = UIColor.gray newLabelBtn.addTarget(self, action: #selector(labelButtonAction(clickedButton:)), for: .touchUpInside) let loveLabelBtn = UIButton(type: .custom) loveLabelBtn.setTitle("关注", for: .normal) loveLabelBtn.setTitleColor(UIColor(red: 106.0 / 225.0, green: 37.0 / 255.0, blue: 99.0 / 255.0, alpha: 1), for: .normal) loveLabelBtn.tag = 102 //loveLabelBtn.backgroundColor = UIColor.blue loveLabelBtn.addTarget(self, action: #selector(labelButtonAction(clickedButton:)), for: .touchUpInside) labelSelectScrollView.contentSize = labelSelectScrollView.frame.size labelSelectScrollView.addSubview(hotLabelBtn) labelSelectScrollView.addSubview(newLabelBtn) labelSelectScrollView.addSubview(loveLabelBtn) hotLabelBtn.snp.makeConstraints { (make) in make.top.equalTo(labelSelectScrollView).offset(0) make.left.equalTo(labelSelectScrollView).offset(0) make.height.equalTo(labelSelectScrollView).offset(-2) make.width.equalTo(labelSelectScrollView.snp.width).multipliedBy(0.333) } newLabelBtn.snp.makeConstraints { (make) in make.top.equalTo(hotLabelBtn) make.bottom.equalTo(hotLabelBtn) make.left.equalTo(hotLabelBtn.snp.right) make.width.equalTo(hotLabelBtn) } loveLabelBtn.snp.makeConstraints { (make) in make.top.equalTo(hotLabelBtn) make.bottom.equalTo(hotLabelBtn) make.left.equalTo(newLabelBtn.snp.right) make.width.equalTo(hotLabelBtn) } pageCtrl = UIView() ///模拟pageControl pageCtrl.backgroundColor = UIColor(red: 223.0 / 225.0, green: 55.0 / 255.0, blue: 125.0 / 255.0, alpha: 1) labelSelectScrollView.addSubview(pageCtrl) pageCtrl.snp.makeConstraints { (make) in make.width.equalTo(labelSelectScrollView).multipliedBy(0.333) make.height.equalTo(2) make.left.equalTo(0)///默认选择热门这个标签 make.top.equalTo(hotLabelBtn.snp.bottom) } } func createLabelButtonContainerVC() { labelButtonContainerVC = UIViewController() labelButtonContainerVC.view.backgroundColor = UIColor.orange let bgView = UIView() bgView.backgroundColor = UIColor.gray labelButtonContainerVC.view.addSubview(bgView) bgView.snp.makeConstraints { (make) in make.size.equalTo(CGSize(width: 300, height: 200)) make.center.equalTo(labelButtonContainerVC.view) } let labelArr = ["最热", "最新", "关注"] for index in 0..<labelArr.count { let labelBtn = UIButton(type: .custom) labelBtn.setTitle(labelArr[index], for: .normal) labelBtn.backgroundColor = UIColor.blue labelBtn.tag = index + 100 ///与之前的hotLabelBtn等对应 labelBtn.addTarget(self, action: #selector(labelButtonAction(clickedButton:)), for: .touchUpInside) labelBtn.backgroundColor = UIColor(red: CGFloat(index) * 25.0 / 255.0, green: CGFloat(index) * 45.0 / 255.0, blue: CGFloat(index) * 65.0 / 255.0, alpha: 1) bgView.addSubview(labelBtn) let row = labelArr.count % 2 + labelArr.count / 2 let r = index / 2 let c = index % 2 labelBtn.snp.makeConstraints({ (make) in make.width.equalTo(bgView.snp.width).multipliedBy(0.5) make.height.equalTo(bgView.snp.height).dividedBy(row) if r == 0 { make.top.equalTo(0) } else if r == 1 { make.bottom.equalTo(0) } if c == 0 { make.left.equalTo(0) } else if c == 1 { make.right.equalTo(0) } }) } let closeBtn = UIButton(type: .custom) closeBtn.setTitle("Close", for: .normal) closeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12) closeBtn.addTarget(self, action: #selector(closeLabelButtonContainerView), for: .touchUpInside) labelButtonContainerVC.view.addSubview(closeBtn) closeBtn.snp.makeConstraints { (make) in make.size.equalTo(CGSize(width: 40, height: 30)) make.top.equalTo(40) make.right.equalTo(-20) } } func showLabelButtonContainerView() { /* * tips:系统没有提供从右侧弹出模态视图的style,可以才用自定义的style来实现,要做的事有点多 * 也可以采用平移视图的的方式,而labelButtonContainerVC可以换成UIView类型 */ self.present(labelButtonContainerVC, animated: true, completion: nil) //self.modalPresentationStyle = .custom ///自定义 //self.transitioningDelegate = self } func closeLabelButtonContainerView() { self.dismiss(animated: true, completion: nil) } /*-------------------------transitioningDelegate------------------------*/ /* * 该代理方法用于返回负责转场的控制器对象 */ /* func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { <#code#> } /* * 该代理方法用于告诉系统谁来负责控制器如何弹出 */ func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { <#code#> } /* * 该该代理方法用于告诉系统谁来负责控制器如何消失 */ func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { <#code#> } /* * 该该代理方法用于告诉系统谁来负责控制器如何消失 */ func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { } /* * 该该代理方法用于告诉系统谁来负责控制器如何消失 */ func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { } */ /* * 标签点击的响应方法 */ func labelButtonAction(clickedButton button: UIButton) { closeLabelButtonContainerView() let index = button.tag - 100 UIView.animate(withDuration: 0.3) { [unowned self] in self.pageCtrl.frame.origin.x = self.pageCtrl.frame.width * CGFloat(index) } ///设置当前标签的文字颜色 for btn in labelSelectScrollView.subviews { if btn.tag == button.tag {///因为有可能是LabelButtonContainerVC里的按钮 if btn is UIButton { (btn as! UIButton).setTitleColor(THEME_COLOR, for: .normal) } } else { if btn is UIButton { (btn as! UIButton).setTitleColor(NORMAL_TEXT_COLOR, for: .normal) } } } ///选择当前的主视图 mainView.contentOffset = CGPoint(x: mainView.frame.width * CGFloat(index), y: CGFloat(0)) } /* * 创建中间的主视图 */ func createMainView() { mainView = UIScrollView() mainView.backgroundColor = UIColor.cyan mainView.showsVerticalScrollIndicator = false mainView.showsHorizontalScrollIndicator = false mainView.isPagingEnabled = true mainView.bounces = false mainView.delegate = self self.view.insertSubview(mainView, at: 0) mainView.snp.makeConstraints { (make) in make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(40, 0, 0, 0)) } mainContentView = UIView() mainContentView.backgroundColor = UIColor.gray mainView.addSubview(mainContentView) mainContentView.snp.makeConstraints { (make) in make.edges.height.equalToSuperview() } hotView = HotViewController().view hotView.backgroundColor = UIColor.white mainContentView.addSubview(hotView) newView = NewViewController().view newView.backgroundColor = UIColor.white mainContentView.addSubview(newView) loveView = LoveView() loveView.backgroundColor = UIColor.white mainContentView.addSubview(loveView) hotView.snp.makeConstraints { (make) in make.top.bottom.left.equalToSuperview() make.width.equalTo(mainView) } newView.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.left.equalTo(hotView.snp.right) make.width.equalTo(mainView) } loveView.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.left.equalTo(newView.snp.right) make.width.equalTo(mainView) } mainContentView.snp.makeConstraints { (make) in make.right.equalTo(loveView) } } ///滑动主视图时的代理方法 func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset if scrollView.frame.width > 0 { let index = Int(offset.x / scrollView.frame.width) for btn in labelSelectScrollView.subviews { if btn.tag == (index + 100) {///因为有可能是LabelButtonContainerVC里的按钮 if btn is UIButton { (btn as! UIButton).setTitleColor(THEME_COLOR, for: .normal) UIView.animate(withDuration: 0.3) { [unowned self] in self.pageCtrl.frame.origin.x = self.pageCtrl.frame.width * CGFloat(index) } } } else { if btn is UIButton { (btn as! UIButton).setTitleColor(NORMAL_TEXT_COLOR, for: .normal) } } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
37.257081
184
0.596222
6714ae74156295e372fd951735407eac8ea12d50
2,199
// // CKIUserNetworkingTests.swift // CanvasKit // // Created by Nathan Lambson on 7/29/14. // Copyright (c) 2014 Instructure. All rights reserved. // import XCTest class CKIUserNetworkingTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testfetchUsersForContext() { let courseDictionary = Helpers.loadJSONFixture("course") as NSDictionary let course = CKICourse(fromJSONDictionary: courseDictionary) let client = MockCKIClient() let dictionary = ["include": ["avatar_url", "enrollments"]]; client.fetchUsersForContext(course) XCTAssertEqual(client.capturedPath!, "/api/v1/courses/1/users", "CKIUser returned API path for testfetchUsersForContext was incorrect") XCTAssertEqual(client.capturedParameters!.count, dictionary.count, "CKIUser returned API parameters for testfetchUsersForContext was incorrect") } func testFetchUsersWithParametersAndContext() { let courseDictionary = Helpers.loadJSONFixture("course") as NSDictionary let course = CKICourse(fromJSONDictionary: courseDictionary) let client = MockCKIClient() let dictionary = ["include": ["avatar_url", "enrollments"]]; client.fetchUsersWithParameters(dictionary, context: course) XCTAssertEqual(client.capturedPath!, "/api/v1/courses/1/users", "CKIUser returned API path for testFetchUsersWithParametersAndContext was incorrect") XCTAssertEqual(client.capturedParameters!.count, dictionary.count, "CKIUser returned API parameters for testFetchUsersWithParametersAndContext was incorrect") } func testFetchCurrentUser() { let client = MockCKIClient() client.fetchCurrentUser() XCTAssertEqual(client.capturedPath!, "/api/v1/users/self/profile", "CKIUser returned API path for testFetchCurrentUser was incorrect") } }
42.288462
166
0.709868
64fcb1aa725c1a9a6de9105c0dee55f4609d1aa0
7,470
/* * -------------------------------------------------------------------------------- * <copyright company="Aspose" file="DeleteTableRequest.swift"> * Copyright (c) 2021 Aspose.Words for Cloud * </copyright> * <summary> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * </summary> * -------------------------------------------------------------------------------- */ import Foundation // Request model for deleteTable operation. @available(macOS 10.12, iOS 10.3, watchOS 3.3, tvOS 12.0, *) public class DeleteTableRequest : WordsApiRequest { private let name : String; private let index : Int; private let nodePath : String?; private let folder : String?; private let storage : String?; private let loadEncoding : String?; private let password : String?; private let destFileName : String?; private let revisionAuthor : String?; private let revisionDateTime : String?; private enum CodingKeys: String, CodingKey { case name; case index; case nodePath; case folder; case storage; case loadEncoding; case password; case destFileName; case revisionAuthor; case revisionDateTime; case invalidCodingKey; } // Initializes a new instance of the DeleteTableRequest class. public init(name : String, index : Int, nodePath : String? = nil, folder : String? = nil, storage : String? = nil, loadEncoding : String? = nil, password : String? = nil, destFileName : String? = nil, revisionAuthor : String? = nil, revisionDateTime : String? = nil) { self.name = name; self.index = index; self.nodePath = nodePath; self.folder = folder; self.storage = storage; self.loadEncoding = loadEncoding; self.password = password; self.destFileName = destFileName; self.revisionAuthor = revisionAuthor; self.revisionDateTime = revisionDateTime; } // The filename of the input document. public func getName() -> String { return self.name; } // Object index. public func getIndex() -> Int { return self.index; } // The path to the node in the document tree. public func getNodePath() -> String? { return self.nodePath; } // Original document folder. public func getFolder() -> String? { return self.folder; } // Original document storage. public func getStorage() -> String? { return self.storage; } // Encoding that will be used to load an HTML (or TXT) document if the encoding is not specified in HTML. public func getLoadEncoding() -> String? { return self.loadEncoding; } // Password for opening an encrypted document. public func getPassword() -> String? { return self.password; } // Result path of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document. public func getDestFileName() -> String? { return self.destFileName; } // Initials of the author to use for revisions.If you set this parameter and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions. public func getRevisionAuthor() -> String? { return self.revisionAuthor; } // The date and time to use for revisions. public func getRevisionDateTime() -> String? { return self.revisionDateTime; } // Creates the api request data public func createApiRequestData(apiInvoker : ApiInvoker, configuration : Configuration) throws -> WordsApiRequestData { var rawPath = "/words/{name}/{nodePath}/tables/{index}"; rawPath = rawPath.replacingOccurrences(of: "{name}", with: try ObjectSerializer.serializeToString(value: self.getName())); rawPath = rawPath.replacingOccurrences(of: "{index}", with: try ObjectSerializer.serializeToString(value: self.getIndex())); if (self.getNodePath() != nil) { rawPath = rawPath.replacingOccurrences(of: "{nodePath}", with: try ObjectSerializer.serializeToString(value: self.getNodePath()!)); } else { rawPath = rawPath.replacingOccurrences(of: "{nodePath}", with: ""); } rawPath = rawPath.replacingOccurrences(of: "//", with: "/"); let urlPath = (try configuration.getApiRootUrl()).appendingPathComponent(rawPath); var urlBuilder = URLComponents(url: urlPath, resolvingAgainstBaseURL: false)!; var queryItems : [URLQueryItem] = []; if (self.getFolder() != nil) { queryItems.append(URLQueryItem(name: "folder", value: try ObjectSerializer.serializeToString(value: self.getFolder()!))); } if (self.getStorage() != nil) { queryItems.append(URLQueryItem(name: "storage", value: try ObjectSerializer.serializeToString(value: self.getStorage()!))); } if (self.getLoadEncoding() != nil) { queryItems.append(URLQueryItem(name: "loadEncoding", value: try ObjectSerializer.serializeToString(value: self.getLoadEncoding()!))); } if (self.getPassword() != nil) { queryItems.append(URLQueryItem(name: apiInvoker.isEncryptionAllowed() ? "encryptedPassword" : "password", value: try apiInvoker.encryptString(value: self.getPassword()!))); } if (self.getDestFileName() != nil) { queryItems.append(URLQueryItem(name: "destFileName", value: try ObjectSerializer.serializeToString(value: self.getDestFileName()!))); } if (self.getRevisionAuthor() != nil) { queryItems.append(URLQueryItem(name: "revisionAuthor", value: try ObjectSerializer.serializeToString(value: self.getRevisionAuthor()!))); } if (self.getRevisionDateTime() != nil) { queryItems.append(URLQueryItem(name: "revisionDateTime", value: try ObjectSerializer.serializeToString(value: self.getRevisionDateTime()!))); } if (queryItems.count > 0) { urlBuilder.queryItems = queryItems; } let result = WordsApiRequestData(url: urlBuilder.url!, method: "DELETE"); return result; } // Deserialize response of this request public func deserializeResponse(data : Data) throws -> Any? { return nil; } }
42.685714
272
0.652744
29cff5eb066ff272bf4882baf7e02ec28ec20adb
968
// // ModuloNativoiOSTests.swift // ModuloNativoiOSTests // // Created by Lucas on 03/07/20. // Copyright © 2020 Lucas. All rights reserved. // import XCTest @testable import ModuloNativoiOS class ModuloNativoiOSTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.657143
111
0.674587
eb1c490faebf8f9b6944c6e103bcd330aade8419
4,832
import WebRTC import Promises public class Track: MulticastDelegate<TrackDelegate> { public static let cameraName = "camera" public static let screenShareName = "screenshare" public enum Kind { case audio case video case none } public enum State { case stopped case started } public enum Source { case unknown case camera case microphone case screenShareVideo case screenShareAudio } public let kind: Track.Kind public let source: Track.Source public internal(set) var name: String public internal(set) var sid: Sid? public let mediaTrack: RTCMediaStreamTrack public private(set) var muted: Bool = false public internal(set) var transceiver: RTCRtpTransceiver? public internal(set) var stats: TrackStats? public var sender: RTCRtpSender? { return transceiver?.sender } /// Dimensions of the video (only if video track) public private(set) var dimensions: Dimensions? /// The last video frame received for this track public private(set) var videoFrame: RTCVideoFrame? public private(set) var state: State = .stopped { didSet { guard oldValue != state else { return } didUpdateState() } } init(name: String, kind: Kind, source: Source, track: RTCMediaStreamTrack) { self.name = name self.kind = kind self.source = source mediaTrack = track } // will fail if already started (to prevent duplicate code execution) internal func start() -> Promise<Void> { guard state != .started else { return Promise(TrackError.state(message: "Already started")) } if let videoTrack = mediaTrack as? RTCVideoTrack { DispatchQueue.webRTC.sync { videoTrack.add(self) } } self.state = .started return Promise(()) } // will fail if already stopped (to prevent duplicate code execution) public func stop() -> Promise<Void> { guard state != .stopped else { return Promise(TrackError.state(message: "Already stopped")) } if let videoTrack = mediaTrack as? RTCVideoTrack { DispatchQueue.webRTC.sync { videoTrack.remove(self) } } self.state = .stopped return Promise(()) } internal func enable() -> Promise<Void> { Promise(on: .sdk) { self.mediaTrack.isEnabled = true } } internal func disable() -> Promise<Void> { Promise(on: .sdk) { self.mediaTrack.isEnabled = false } } internal func didUpdateState() { // } internal func set(muted: Bool, shouldNotify: Bool = true, shouldSendSignal: Bool = false) { guard muted != self.muted else { return } self.muted = muted if shouldNotify { notify { $0.track(self, didUpdate: muted, shouldSendSignal: shouldSendSignal) } } } } // MARK: - Internal internal extension Track { func set(stats newValue: TrackStats) { guard self.stats != newValue else { return } self.stats = newValue notify { $0.track(self, didUpdate: newValue) } } } // MARK: - Private private extension Track { func set(dimensions newValue: Dimensions?) { guard self.dimensions != newValue else { return } // DispatchQueue.mainSafeSync { self.dimensions = newValue // } guard let videoTrack = self as? VideoTrack else { return } notify { $0.track(videoTrack, didUpdate: newValue) } } func set(videoFrame newValue: RTCVideoFrame?) { // guard self.videoFrame != newValue else { return } self.videoFrame = newValue guard let videoTrack = self as? VideoTrack else { return } notify { $0.track(videoTrack, didReceive: self.videoFrame) } } } extension Track: RTCVideoRenderer { public func setSize(_ size: CGSize) { // guard let videoTrack = self as? VideoTrack else { return } // notify { $0.track(videoTrack, didReceive: size) } } public func renderFrame(_ frame: RTCVideoFrame?) { if let frame = frame { let dimensions = Dimensions(width: frame.width, height: frame.height) // ignore unsafe dimensions guard dimensions.isRenderSafe else { log("Skipping render for dimension \(dimensions)", .warning) // renderState.insert(.didSkipUnsafeFrame) return } set(dimensions: dimensions) } else { set(dimensions: nil) } set(videoFrame: frame) } }
27.146067
91
0.592508
f40e05c4940c9ffd3aa4ef15bfe7bf2fcbfef079
535
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse protocol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { struct d<f : e, g: e where g.h == f.h> { if c == .b { } var f = 1
29.722222
78
0.685981
ddb01c86a81dee753f61d3940c49ace75d3d8c04
5,688
import Flutter import UIKit public class SwiftFlutterMPGSPlugin: NSObject, FlutterPlugin { var flutterResult: FlutterResult? var gateway:Gateway? = nil var apiVersion:String? = nil public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "flutter_mpgs_sdk", binaryMessenger: registrar.messenger()) let instance = SwiftFlutterMPGSPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } func getRegion(_ region:String) -> GatewayRegion{ switch region { case "ap-": return .asiaPacific case "eu-": return .europe case "na-": return .northAmerica default: return .mtf } } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { if let arguments:NSDictionary = call.arguments as? NSDictionary { switch call.method { case "init": let region = arguments.value(forKey: "region") as! String let gatewayId = arguments.value(forKey: "gatewayId") as! String self.apiVersion = (arguments.value(forKey: "apiVersion") as! String) self.gateway = Gateway(region: getRegion(region), merchantId: gatewayId) result(true) break // case "scanner": // self.flutterResult = result // self.microblinkLicense = arguments.value(forKey: "license") as? String // if(self.microblinkLicense == nil){ // result(nil) // } // MBMicroblinkSDK.sharedInstance().setLicenseKey(self.microblinkLicense!) // // /** Create BlinkCard recognizer */ // blinkCardRecognizer = MBBlinkCardRecognizer() // // /** Create BlinkCard settings */ // let settings : MBBlinkCardOverlaySettings = MBBlinkCardOverlaySettings() // // /** Crate recognizer collection */ // let recognizerList = [blinkCardRecognizer!] // let recognizerCollection : MBRecognizerCollection = MBRecognizerCollection(recognizers: recognizerList) // // /** Create your overlay view controller */ // let blinkCardOverlayViewController = MBBlinkCardOverlayViewController(settings: settings, recognizerCollection: recognizerCollection, delegate: self) // // /** Create recognizer view controller with wanted overlay view controller */ // let recognizerRunneViewController : UIViewController = MBViewControllerFactory.recognizerRunnerViewController(withOverlayViewController: blinkCardOverlayViewController) // recognizerRunneViewController.modalPresentationStyle = .fullScreen // if var topController = UIApplication.shared.keyWindow?.rootViewController { // while let presentedViewController = topController.presentedViewController { // topController = presentedViewController // } // /** Present the recognizer runner view controller. You can use other presentation methods as well (instead of presentViewController) */ // topController.present(recognizerRunneViewController, animated: true, completion: nil) // } // break case "updateSession": if(gateway == nil){ print("Not initialized!") result(FlutterError(code: "MPGS-01", message: "Not initialized", details: nil)) } if(self.apiVersion == nil){ result(FlutterError(code: "MPGS-02", message: "Invalid api version", details: nil)) } let sessionId = arguments.value(forKey: "sessionId") as! String let cardHolder = arguments.value(forKey: "cardHolder") as! String let cardNumber = arguments.value(forKey: "cardNumber") as! String let year = arguments.value(forKey: "year") as! String let month = arguments.value(forKey: "month") as! String let cvv = arguments.value(forKey: "cvv") as! String var request:GatewayMap = GatewayMap() request[at: "sourceOfFunds.provided.card.nameOnCard"] = cardHolder request[at: "sourceOfFunds.provided.card.number"] = cardNumber request[at: "sourceOfFunds.provided.card.securityCode"] = cvv request[at: "sourceOfFunds.provided.card.expiry.month"] = month request[at: "sourceOfFunds.provided.card.expiry.year"] = year self.gateway?.updateSession(sessionId, apiVersion: self.apiVersion!, payload: request, completion: { (response: GatewayResult<GatewayMap>) in switch(response){ case .error(let error): result(FlutterError(code: "MPGS-000", message: String(describing: error), details: nil)) break case .success(_): result(true) break } self.gateway = nil }) break default: result(FlutterError(code: "0", message: "Not implimented", details: nil)) } } } }
48.615385
186
0.565577
2f39f8beb1cb23cf49b3c0a92cf90e925f5106f0
818
// // Virtual_TouristTests.swift // Virtual TouristTests // // Created by Daniel Riehs on 4/2/15. // Copyright (c) 2015 Daniel Riehs. All rights reserved. // import UIKit import XCTest class Virtual_TouristTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
22.108108
105
0.698044
3987c0d721aef8521c99c8d28fd11beeda4e3737
18,040
// // MessagePresenter.swift // SwiftMessages // // Created by Timothy Moose on 7/30/16. // Copyright © 2016 SwiftKick Mobile LLC. All rights reserved. // import UIKit protocol PresenterDelegate: AnimationDelegate { func hide(presenter: Presenter) } class Presenter: NSObject { enum PresentationContext { case viewController(_: Weak<UIViewController>) case view(_: Weak<UIView>) func viewControllerValue() -> UIViewController? { switch self { case .viewController(let weak): return weak.value case .view: return nil } } func viewValue() -> UIView? { switch self { case .viewController(let weak): return weak.value?.view case .view(let weak): return weak.value } } } var config: SwiftMessages.Config let view: UIView weak var delegate: PresenterDelegate? let maskingView = MaskingView() var presentationContext = PresentationContext.viewController(Weak<UIViewController>(value: nil)) let animator: Animator init(config: SwiftMessages.Config, view: UIView, delegate: PresenterDelegate) { self.config = config self.view = view self.delegate = delegate self.animator = Presenter.animator(forPresentationStyle: config.presentationStyle, delegate: delegate) if let identifiable = view as? Identifiable { id = identifiable.id } else { var mutableView = view id = withUnsafePointer(to: &mutableView) { "\($0)" } } super.init() } private static func animator(forPresentationStyle style: SwiftMessages.PresentationStyle, delegate: AnimationDelegate) -> Animator { switch style { case .top: return TopBottomAnimation(style: .top, delegate: delegate) case .bottom: return TopBottomAnimation(style: .bottom, delegate: delegate) case .center: return PhysicsAnimation(delegate: delegate) case .custom(let animator): animator.delegate = delegate return animator } } var id: String var pauseDuration: TimeInterval? { let duration: TimeInterval? switch self.config.duration { case .automatic: duration = 2 case .seconds(let seconds): duration = seconds case .forever, .indefinite: duration = nil } return duration } var showDate: CFTimeInterval? private var interactivelyHidden = false; var delayShow: TimeInterval? { if case .indefinite(let opts) = config.duration { return opts.delay } return nil } /// Returns the required delay for hiding based on time shown var delayHide: TimeInterval? { if interactivelyHidden { return 0 } if case .indefinite(let opts) = config.duration, let showDate = showDate { let timeIntervalShown = CACurrentMediaTime() - showDate return max(0, opts.minimum - timeIntervalShown) } return nil } /* MARK: - Showing and hiding */ func show(completion: @escaping AnimationCompletion) throws { try presentationContext = getPresentationContext() install() self.config.eventListeners.forEach { $0(.willShow) } showAnimation() { completed in completion(completed) if completed { if self.config.dimMode.modal { self.showAccessibilityFocus() } else { self.showAccessibilityAnnouncement() } self.config.eventListeners.forEach { $0(.didShow) } } } } private func showAnimation(completion: @escaping AnimationCompletion) { func dim(_ color: UIColor) { self.maskingView.backgroundColor = UIColor.clear UIView.animate(withDuration: 0.2, animations: { self.maskingView.backgroundColor = color }) } func blur(style: UIBlurEffect.Style, alpha: CGFloat) { let blurView = UIVisualEffectView(effect: nil) blurView.alpha = alpha maskingView.backgroundView = blurView UIView.animate(withDuration: 0.3) { blurView.effect = UIBlurEffect(style: style) } } let context = animationContext() animator.show(context: context) { (completed) in completion(completed) } switch config.dimMode { case .none: break case .gray: dim(UIColor(white: 0, alpha: 0.3)) case .color(let color, _): dim(color) case .blur(let style, let alpha, _): blur(style: style, alpha: alpha) } } private func showAccessibilityAnnouncement() { guard let accessibleMessage = view as? AccessibleMessage, let message = accessibleMessage.accessibilityMessage else { return } UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: message) } private func showAccessibilityFocus() { guard let accessibleMessage = view as? AccessibleMessage, let focus = accessibleMessage.accessibilityElement ?? accessibleMessage.additonalAccessibilityElements?.first else { return } UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: focus) } var isHiding = false func hide(animated: Bool, completion: @escaping AnimationCompletion) { isHiding = true self.config.eventListeners.forEach { $0(.willHide) } let context = animationContext() let action = { if let viewController = self.presentationContext.viewControllerValue() as? WindowViewController { viewController.uninstall() } self.maskingView.removeFromSuperview() completion(true) self.config.eventListeners.forEach { $0(.didHide) } } guard animated else { action() return } animator.hide(context: context) { (completed) in action() } func undim() { UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { self.maskingView.backgroundColor = UIColor.clear }, completion: nil) } func unblur() { guard let view = maskingView.backgroundView as? UIVisualEffectView else { return } UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { view.effect = nil }, completion: nil) } switch config.dimMode { case .none: break case .gray: undim() case .color: undim() case .blur: unblur() } } private func animationContext() -> AnimationContext { return AnimationContext(messageView: view, containerView: maskingView, safeZoneConflicts: safeZoneConflicts(), interactiveHide: config.interactiveHide) } private func safeZoneConflicts() -> SafeZoneConflicts { guard let window = maskingView.window else { return [] } let windowLevel: UIWindow.Level = { if let vc = presentationContext.viewControllerValue() as? WindowViewController { return vc.windowLevel } return UIWindow.Level.normal }() // TODO `underNavigationBar` and `underTabBar` should look up the presentation context's hierarchy // TODO for cases where both should be true (probably not an issue for typical height messages, though). let underNavigationBar: Bool = { if let vc = presentationContext.viewControllerValue() as? UINavigationController { return vc.sm_isVisible(view: vc.navigationBar) } return false }() let underTabBar: Bool = { if let vc = presentationContext.viewControllerValue() as? UITabBarController { return vc.sm_isVisible(view: vc.tabBar) } return false }() if #available(iOS 11, *) { if windowLevel > UIWindow.Level.normal { // TODO seeing `maskingView.safeAreaInsets.top` value of 20 on // iPhone 8 with status bar window level. This seems like an iOS bug since // the message view's window is above the status bar. Applying a special rule // to allow the animator to revove this amount from the layout margins if needed. // This may need to be reworked if any future device has a legitimate 20pt top safe area, // such as with a potentially smaller notch. if maskingView.safeAreaInsets.top == 20 { return [.overStatusBar] } else { var conflicts: SafeZoneConflicts = [] if maskingView.safeAreaInsets.top > 0 { conflicts.formUnion(.sensorNotch) } if maskingView.safeAreaInsets.bottom > 0 { conflicts.formUnion(.homeIndicator) } return conflicts } } var conflicts: SafeZoneConflicts = [] if !underNavigationBar { conflicts.formUnion(.sensorNotch) } if !underTabBar { conflicts.formUnion(.homeIndicator) } return conflicts } else { #if SWIFTMESSAGES_APP_EXTENSIONS return [] #else if UIApplication.shared.isStatusBarHidden { return [] } if (windowLevel > UIWindow.Level.normal) || underNavigationBar { return [] } let statusBarFrame = UIApplication.shared.statusBarFrame let statusBarWindowFrame = window.convert(statusBarFrame, from: nil) let statusBarViewFrame = maskingView.convert(statusBarWindowFrame, from: nil) return statusBarViewFrame.intersects(maskingView.bounds) ? SafeZoneConflicts.statusBar : [] #endif } } private func getPresentationContext() throws -> PresentationContext { func newWindowViewController(_ windowLevel: UIWindow.Level) -> UIViewController { let viewController = WindowViewController.newInstance(windowLevel: windowLevel, config: config) return viewController } switch config.presentationContext { case .automatic: #if SWIFTMESSAGES_APP_EXTENSIONS throw SwiftMessagesError.noRootViewController #else if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } let viewController = topController.sm_selectPresentationContextTopDown(config) return .viewController(Weak(value: viewController)) } else { throw SwiftMessagesError.noRootViewController } #endif case .window(let level): let viewController = newWindowViewController(level) return .viewController(Weak(value: viewController)) case .viewController(let viewController): let viewController = viewController.sm_selectPresentationContextBottomUp(config) return .viewController(Weak(value: viewController)) case .view(let view): return .view(Weak(value: view)) } } /* MARK: - Installation */ func install() { func topLayoutConstraint(view: UIView, containerView: UIView, viewController: UIViewController?) -> NSLayoutConstraint { if case .top = config.presentationStyle, let nav = viewController as? UINavigationController, nav.sm_isVisible(view: nav.navigationBar) { return NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: nav.navigationBar, attribute: .bottom, multiplier: 1.00, constant: 0.0) } return NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1.00, constant: 0.0) } func bottomLayoutConstraint(view: UIView, containerView: UIView, viewController: UIViewController?) -> NSLayoutConstraint { if case .bottom = config.presentationStyle, let tab = viewController as? UITabBarController, tab.sm_isVisible(view: tab.tabBar) { return NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: tab.tabBar, attribute: .top, multiplier: 1.00, constant: 0.0) } return NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1.00, constant: 0.0) } func installMaskingView(containerView: UIView) { maskingView.translatesAutoresizingMaskIntoConstraints = false if let nav = presentationContext.viewControllerValue() as? UINavigationController { containerView.insertSubview(maskingView, belowSubview: nav.navigationBar) } else if let tab = presentationContext.viewControllerValue() as? UITabBarController { containerView.insertSubview(maskingView, belowSubview: tab.tabBar) } else { containerView.addSubview(maskingView) } maskingView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor).isActive = true maskingView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor).isActive = true topLayoutConstraint(view: maskingView, containerView: containerView, viewController: presentationContext.viewControllerValue()).isActive = true bottomLayoutConstraint(view: maskingView, containerView: containerView, viewController: presentationContext.viewControllerValue()).isActive = true if let keyboardTrackingView = config.keyboardTrackingView { maskingView.install(keyboardTrackingView: keyboardTrackingView) } // Update the container view's layout in order to know the masking view's frame containerView.layoutIfNeeded() } func installInteractive() { guard config.dimMode.modal else { return } if config.dimMode.interactive { maskingView.tappedHander = { [weak self] in guard let strongSelf = self else { return } strongSelf.interactivelyHidden = true strongSelf.delegate?.hide(presenter: strongSelf) } } else { // There's no action to take, but the presence of // a tap handler prevents interaction with underlying views. maskingView.tappedHander = { } } } func installAccessibility() { var elements: [NSObject] = [] if let accessibleMessage = view as? AccessibleMessage { if let message = accessibleMessage.accessibilityMessage { let element = accessibleMessage.accessibilityElement ?? view element.isAccessibilityElement = true if element.accessibilityLabel == nil { element.accessibilityLabel = message } elements.append(element) } if let additional = accessibleMessage.additonalAccessibilityElements { elements += additional } } else { elements += [view] } if config.dimMode.interactive { let dismissView = UIView(frame: maskingView.bounds) dismissView.translatesAutoresizingMaskIntoConstraints = true dismissView.autoresizingMask = [.flexibleWidth, .flexibleHeight] maskingView.addSubview(dismissView) maskingView.sendSubviewToBack(dismissView) dismissView.isUserInteractionEnabled = false dismissView.isAccessibilityElement = true dismissView.accessibilityLabel = config.dimModeAccessibilityLabel dismissView.accessibilityTraits = UIAccessibilityTraits.button elements.append(dismissView) } if config.dimMode.modal { maskingView.accessibilityViewIsModal = true } maskingView.accessibleElements = elements } guard let containerView = presentationContext.viewValue() else { return } if let windowViewController = presentationContext.viewControllerValue() as? WindowViewController { if #available(iOS 13, *) { let scene = UIApplication.shared.keyWindow?.windowScene windowViewController.install(becomeKey: becomeKeyWindow, scene: scene) } else { windowViewController.install(becomeKey: becomeKeyWindow) } } installMaskingView(containerView: containerView) installInteractive() installAccessibility() } private var becomeKeyWindow: Bool { if config.becomeKeyWindow == .some(true) { return true } switch config.dimMode { case .gray, .color, .blur: // Should become key window in modal presentation style // for proper VoiceOver handling. return true case .none: return false } } }
40.907029
169
0.608149
913d73cdfbee5113834df7e5b487a11b550a9229
1,440
// // UITableView+Type.swift // JSONPlaceholderViewer // // Created by Yoshikuni Kato on 6/23/18. // Copyright © 2018 Yoshikuni Kato. All rights reserved. // import UIKit public extension UITableView { public func registerNibForCellWithType<T: UITableViewCell>(_ type: T.Type) { let nib = UINib(nibName: String(describing: type), bundle: Bundle(for: type)) register(nib, forCellReuseIdentifier: String(describing: type)) } public func registerClassForCellWithType<T: UITableViewCell>(_ type: T.Type) { register(type, forCellReuseIdentifier: String(describing: type)) } public func dequeueReusableCellWithType<T: UITableViewCell>( _ type: T.Type, forIndexPath indexPath: IndexPath ) -> T { // swiftlint:disable:next force_cast return dequeueReusableCell(withIdentifier: String(describing: type), for: indexPath) as! T } // header footer view public func registerNibForHeaderFooterViewWithType<T: UITableViewHeaderFooterView>(_ type: T.Type) { let nib = UINib(nibName: String(describing: type), bundle: Bundle(for: type)) register(nib, forHeaderFooterViewReuseIdentifier: String(describing: type)) } public func dequeueReusableHeaderFooterViewWithType<T: UITableViewHeaderFooterView>(_ type: T.Type) -> T? { return dequeueReusableHeaderFooterView(withIdentifier: String(describing: type)) as? T } }
36
111
0.711111
1db2322fac52dcaea0ebc597277f5a2ac6ccb919
915
// // TimberjackTests.swift // TimberjackTests // // Created by Andy Smart on 04/09/2015. // Copyright (c) 2015 Rocket Town Ltd. All rights reserved. // import UIKit import XCTest class TimberjackTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.72973
111
0.618579
ed3d931730c7b206882f1c64c90217bdd739dc4a
613
// // HSLConverterTest.swift // PaileadTests // // Created by Patrick Metcalfe on 1/6/18. // import XCTest @testable import Pailead class HSLConverterTests : XCTestCase { func testReversability() { let converter = HSLConverter() let subject = Pixel(red: 123, green: 45, blue: 67) let hsl = converter.hslFor(subject) let reversed = converter.pixelFor(hue: hsl.0, saturation: hsl.1, lumience: hsl.2) XCTAssertEqual(subject.red, reversed.red) XCTAssertEqual(subject.green, reversed.green) XCTAssertEqual(subject.blue, reversed.blue) } }
25.541667
89
0.663948
5bd31dc037e0c35166361dfccd76155cf6939df2
428
// // AlamofireRestClientProtocol.swift // DataModule // // Created by Ahmad Mahmoud on 19/02/2021. // import Alamofire public protocol AlamofireRestClientProtocol: RestClientProtocol { func createAlamofireSession() -> Session func getEventMonitorsList() -> [EventMonitor] func createAlamofireRequestFactory() -> AlamofireRequestFactory func createAPIRequestExecuter<T: APIRequestExecuterProtocol>() -> T }
26.75
71
0.766355
fe9bb30f8244f56bbc0cf2dcbef8b4afd4d3faae
1,364
// // KeyboardView.swift // WordleDebug // // Created by Vasily Martin for the Developer Academy // import SwiftUI struct KeyboardView: View { @EnvironmentObject var gameModel: GameModel private let spacing: CGFloat = 5 private var maxNumberOfKeysInRow: Int { gameModel.keyboard.rows.reduce(0) { $0 > $1.count ? $0 : $1.count } } private var keySize: CGFloat { (UIScreen.main.bounds.width - CGFloat(maxNumberOfKeysInRow + 1) * spacing) / CGFloat(maxNumberOfKeysInRow) } var body: some View { VStack(spacing: spacing) { ForEach(gameModel.keyboard.rows, id: \.self) { row in HStack(spacing: spacing) { ForEach(row) { key in Text(key.value) .frame(width: keySize, height: keySize) .background(Color.blue) .cornerRadius(5) .onTapGesture { gameModel.keyDown(key: key) } } } } } } } struct KeyboardView_Previews: PreviewProvider { static let gameModel = GameModel() static var previews: some View { KeyboardView() .environmentObject(gameModel) } }
26.745098
114
0.514663
4bb20f210d00ef85683e7d9fbc49a3be4aa9a6fc
1,446
// // UserIdentityViewController.swift // MySampleApp // // // Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved. // // Code generated by AWS Mobile Hub. Amazon gives unlimited permission to // copy, distribute and modify it. // // Source code generated from template: aws-my-sample-app-ios-swift v0.8 // import Foundation import UIKit import AWSMobileHubHelper class UserIdentityViewController: UIViewController { @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var userID: UILabel! // MARK: - View lifecycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let identityManager = AWSIdentityManager.defaultIdentityManager() if let identityUserName = identityManager.userName { userName.text = identityUserName } else { userName.text = NSLocalizedString("Guest User", comment: "Placeholder text for the guest user.") } userID.text = identityManager.identityId if let imageURL = identityManager.imageURL { let imageData = NSData(contentsOfURL: imageURL)! if let profileImage = UIImage(data: imageData) { userImageView.image = profileImage } else { userImageView.image = UIImage(named: "UserIcon") } } } }
30.125
108
0.656985
9c1808180005e59111f519a270afdccbafeeabbc
4,492
// // BaseCommand.swift // XMPP API Demo // // Created by Valio Cholakov on 4/21/17. // Copyright © 2017 Valentin Cholakov. All rights reserved. // import UIKit import Foundation import XMPPFramework class BaseCommand: NSObject, XMPPStreamDelegate { // MARK: Variables private var _hasTimedOut: Bool private var _queue: DispatchQueue private var _timer: Timer? internal var response: NSDictionary? internal var command: Command internal var data: [String : Any] // MARK: Constants private let kTimeout: TimeInterval = 30.0 private let kQueueName: String = "com.vc.XMPP-API-Demo-command" // MARK: De/Initializers override init() { command = .unknown data = [:] _hasTimedOut = false _queue = DispatchQueue(label: kQueueName, qos: .`default`, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil) super.init() self.customInit() } deinit { XMPPManager.shared.xmppStream?.removeDelegate(self, delegateQueue: _queue) self.stopTimer() } // MARK: XMPP Stream Delegate func xmppStream(_ sender: XMPPStream!, didReceive message: XMPPMessage!) { if message.forName(Parameters.delay) != nil { // Ignore offline messages return } if !self.messageIsCommandResponse(message) { return } self.handleResponseMessage(message) } // MARK: Public Methods func send() { _hasTimedOut = false if self.startTimer { _timer = Timer.scheduledTimer(timeInterval: kTimeout, target: self, selector: #selector(didTimeout), userInfo: nil, repeats: false) } self.sendCommand(command, data: data) } func stopTimer() { guard let timer = _timer else { return } if timer.isValid { timer.invalidate() } _timer = nil } // MARK: Abstract Command Methods func messageIsCommandResponse(_ message: XMPPMessage) -> Bool { assert(false, "Abstract method not implemented \(#function)") return false } var number: Int { return command.rawValue } var successAction: Selector? { assert(false, "Abstract method not implemented \(#function)") return nil } var failedAction: Selector? { assert(false, "Abstract method not implemented \(#function)") return nil } var onSuccessData: Any? { return nil } var startTimer: Bool { return true } func handleResponseMessage(_ message: XMPPMessage) { self.response = message.response self.stopTimer() CommunicationManager.shared.didReceiveResponseForCommand(self) } // MARK: Private Methods private func customInit() { XMPPManager.shared.xmppStream?.addDelegate(self, delegateQueue: _queue) } private func sendCommand(_ command: Command, data: [String : Any]) { self.sendMessage(XMPPJID.componentJID, command: command, body: self.bodyForCommand(command, data: data)!) } private func sendMessage(_ receiver: XMPPJID, command: Command, body: String) { let message = XMPPMessage.chatMessage(receiver, subject: command.rawValue, body: body) ApplicationManager.shared.networkActivityDidStart() XMPPManager.shared.xmppStream?.send(message) } @objc private func didTimeout() { Logger.log("Command \(self.command) timed out with data: \(self.data)") _hasTimedOut = true self.stopTimer() CommunicationManager.shared.commandTimedOut(self) } // MARK: Helpers private func bodyForCommand(_ command: Command, data: [String : Any]) -> String? { let json = NSDictionary.requestForCommand(command.rawValue, extraData: data) var data: Data? do { data = try JSONSerialization.data(withJSONObject: json, options: []) return String(data: data!, encoding: String.Encoding.utf8) } catch let error as NSError { Logger.log("Could not parse message body from JSON to string. Error: \(error)") return nil } } }
26.423529
143
0.595726
67b12f8cb40ca48470e9c76c530cd5ecaf25f41b
10,914
// // DTCollectionViewManagerAnomalyHandler.swift // DTCollectionViewManager // // Created by Denys Telezhkin on 03.05.2018. // Copyright © 2018 Denys Telezhkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import DTModelStorage #if swift(>=4.1) /// `DTCollectionViewManagerAnomaly` represents various errors and unwanted behaviors that can happen when using `DTTableViewManager` class. /// - SeeAlso: `MemoryStorageAnomaly`, `DTTableViewManagerAnomaly`. public enum DTCollectionViewManagerAnomaly: Equatable, CustomStringConvertible, CustomDebugStringConvertible { case nilCellModel(IndexPath) case nilSupplementaryModel(kind: String, indexPath: IndexPath) case noCellMappingFound(modelDescription: String, indexPath: IndexPath) case noSupplementaryMappingFound(modelDescription: String, kind: String, indexPath: IndexPath) case differentCellReuseIdentifier(mappingReuseIdentifier: String, cellReuseIdentifier: String) case differentSupplementaryReuseIdentifier(mappingReuseIdentifier: String, supplementaryReuseIdentifier: String) case differentCellClass(xibName: String, cellClass: String, expectedCellClass: String) case differentSupplementaryClass(xibName: String, viewClass: String, expectedViewClass: String) case emptyXibFile(xibName: String, expectedViewClass: String) case modelEventCalledWithCellClass(modelType: String, methodName: String, subclassOf: String) case unusedEventDetected(viewType: String, methodName: String) /// Debug information for happened anomaly public var debugDescription: String { switch self { case .nilCellModel(let indexPath): return "❗️[DTCollectionViewManager] UICollectionView requested a cell at \(indexPath), however the model at that indexPath was nil." case .nilSupplementaryModel(kind: let kind, indexPath: let indexPath): return "❗️[DTCollectionViewManager] UICollectionView requested a supplementary view of kind: \(kind) at \(indexPath), however the model was nil." case .noCellMappingFound(modelDescription: let description, indexPath: let indexPath): return "❗️[DTCollectionViewManager] UICollectionView requested a cell for model at \(indexPath), but view model mapping for it was not found, model description: \(description)" case .noSupplementaryMappingFound(modelDescription: let description, kind: let kind, let indexPath): return "❗️[DTCollectionViewManager] UICollectionView requested a supplementary view of kind: \(kind) for model ar \(indexPath), but view model mapping for it was not found, model description: \(description)" case .differentCellReuseIdentifier(mappingReuseIdentifier: let mappingReuseIdentifier, cellReuseIdentifier: let cellReuseIdentifier): return "❗️[DTCollectionViewManager] Reuse identifier of UICollectionViewCell: \(cellReuseIdentifier) does not match reuseIdentifier used to register with UICollectionView: \(mappingReuseIdentifier). \n" + "If you are using XIB, please remove reuseIdentifier from XIB file, or change it to name of UICollectionViewCell subclass. If you are using Storyboards, please change UICollectionViewCell identifier to name of the class. \n" + "If you need different reuseIdentifier for any reason, you can change reuseIdentifier when registering mapping." case .differentCellClass(xibName: let xibName, cellClass: let cellClass, expectedCellClass: let expectedCellClass): return "⚠️[DTCollectionViewManager] Attempted to register xib \(xibName), but view found in a xib was of type \(cellClass), while expected type is \(expectedCellClass). This can prevent cells from being updated with models and react to events." case .differentSupplementaryClass(xibName: let xibName, viewClass: let viewClass, expectedViewClass: let expectedViewClass): return "⚠️[DTCollectionViewManager] Attempted to register xib \(xibName), but view found in a xib was of type \(viewClass), while expected type is \(expectedViewClass). This can prevent supplementary views from being updated with models and react to events." case .emptyXibFile(xibName: let xibName, expectedViewClass: let expectedViewClass): return "⚠️[DTCollectionViewManager] Attempted to register xib \(xibName) for \(expectedViewClass), but this xib does not contain any views." case .differentSupplementaryReuseIdentifier(mappingReuseIdentifier: let mappingIdentifier, supplementaryReuseIdentifier: let supplementaryIdentifier): return "❗️[DTCollectionViewManager] Reuse identifier of UICollectionReusableView: \(supplementaryIdentifier) does not match reuseIdentifier used to register with UICollectionView: \(mappingIdentifier). \n" + "If you are using XIB, please remove reuseIdentifier from XIB file, or change it to name of UICollectionReusableView subclass. If you are using Storyboards, please change UICollectionReusableView identifier to name of the class. \n" + "If you need different reuseIdentifier for any reason, you can change reuseIdentifier when registering mapping." case .modelEventCalledWithCellClass(modelType: let modelType, methodName: let methodName, subclassOf: let subclassOf): return """ ⚠️[DTCollectionViewManager] Event \(methodName) registered with model type, that happens to be a subclass of \(subclassOf): \(modelType). This is likely not what you want, because this event expects to receive model type used for current indexPath instead of cell/view. Reasoning behind it is the fact that for some events views have not yet been created(for example: func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath)). Because they are not created yet, this event cannot be called with cell/view object, and even it's type is unknown at this point, as the mapping resolution will happen later. Most likely you need to use model type, that will be passed to this cell/view through ModelTransfer protocol. For example, for size of cell that expects to receive model Int, event would look like so: manager.sizeForCell(withItem: Int.self) { model, indexPath in return CGSize(height: 44, width: 44) } """ case .unusedEventDetected(viewType: let view, methodName: let methodName): return "⚠️[DTCollectionViewManager] \(methodName) event registered for \(view), but there were no view mappings registered for \(view) type. This event will never be called." } } /// Short description for `DTCollectionViewManagerAnomaly`. Useful for sending to analytics, which might have character limit. public var description: String { switch self { case .nilCellModel(let indexPath): return "DTCollectionViewManagerAnomaly.nilCellModel(\(indexPath))" case .nilSupplementaryModel(let indexPath): return "DTCollectionViewManagerAnomaly.nilSupplementaryModel(\(indexPath))" case .noCellMappingFound(modelDescription: let description, indexPath: let indexPath): return "DTCollectionViewManagerAnomaly.noCellMappingFound(\(description), \(indexPath))" case .noSupplementaryMappingFound(modelDescription: let description, kind: let kind, indexPath: let indexPath): return "DTCollectionViewManagerAnomaly.noSupplementaryMappingFound(\(description), \(kind), \(indexPath))" case .differentCellReuseIdentifier(mappingReuseIdentifier: let mappingIdentifier, cellReuseIdentifier: let cellIdentifier): return "DTCollectionViewManagerAnomaly.differentCellReuseIdentifier(\(mappingIdentifier), \(cellIdentifier))" case .differentCellClass(xibName: let xibName, cellClass: let cellClass, expectedCellClass: let expected): return "DTCollectionViewManagerAnomaly.differentCellClass(\(xibName), \(cellClass), \(expected))" case .differentSupplementaryClass(xibName: let xibName, viewClass: let viewClass, expectedViewClass: let expected): return "DTCollectionViewManagerAnomaly.differentSupplementaryClass(\(xibName), \(viewClass), \(expected))" case .emptyXibFile(xibName: let xibName, expectedViewClass: let expected): return "DTCollectionViewManagerAnomaly.emptyXibFile(\(xibName), \(expected))" case .modelEventCalledWithCellClass(modelType: let model, methodName: let method, subclassOf: let subclass): return "DTCollectionViewManagerAnomaly.modelEventCalledWithCellClass(\(model), \(method), \(subclass))" case .unusedEventDetected(viewType: let view, methodName: let method): return "DTCollectionViewManagerAnomaly.unusedEventDetected(\(view), \(method))" case .differentSupplementaryReuseIdentifier(let mappingReuseIdentifier, let supplementaryReuseIdentifier): return "DTCollectionViewManagerAnomaly.differentSupplementaryReuseIdentifier(\(mappingReuseIdentifier), \(supplementaryReuseIdentifier))" } } } /// `DTCollectionViewManagerAnomalyHandler` handles anomalies from `DTTableViewManager`. open class DTCollectionViewManagerAnomalyHandler : AnomalyHandler { /// Default action to perform when anomaly is detected. Prints debugDescription of anomaly by default. public static var defaultAction : (DTCollectionViewManagerAnomaly) -> Void = { print($0.debugDescription) } /// Action to perform when anomaly is detected. Defaults to `defaultAction`. open var anomalyAction: (DTCollectionViewManagerAnomaly) -> Void = DTCollectionViewManagerAnomalyHandler.defaultAction /// Creates `DTCollectionViewManagerAnomalyHandler`. public init() {} } #endif
89.459016
271
0.758659
e662617329bbdc07f7d5aa6def9500ac4716066b
35,983
// // PulleyViewController.swift // Pulley // // Created by Brendan Lee on 7/6/16. // Copyright © 2016 52inc. All rights reserved. // import UIKit /** * The base delegate protocol for Pulley delegates. */ @objc public protocol PulleyDelegate: class { @objc optional func drawerPositionDidChange(drawer: PulleyViewController) @objc optional func makeUIAdjustmentsForFullscreen(progress: CGFloat) @objc optional func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat) } /** * View controllers in the drawer can implement this to receive changes in state or provide values for the different drawer positions. */ public protocol PulleyDrawerViewControllerDelegate: PulleyDelegate { func collapsedDrawerHeight() -> CGFloat func partialRevealDrawerHeight() -> CGFloat func supportedDrawerPositions() -> [PulleyPosition] } /** * View controllers that are the main content can implement this to receive changes in state. */ public protocol PulleyPrimaryContentControllerDelegate: PulleyDelegate { // Not currently used for anything, but it's here for parity with the hopes that it'll one day be used. } /** * A completion block used for animation callbacks. */ public typealias PulleyAnimationCompletionBlock = ((_ finished: Bool) -> Void) /** Represents a Pulley drawer position. - collapsed: When the drawer is in its smallest form, at the bottom of the screen. - partiallyRevealed: When the drawer is partially revealed. - open: When the drawer is fully open. - closed: When the drawer is off-screen at the bottom of the view. Note: Users cannot close or reopen the drawer on their own. You must set this programatically */ public enum PulleyPosition: Int { case collapsed = 0 case partiallyRevealed = 1 case open = 2 case closed = 3 public static let all: [PulleyPosition] = [ .collapsed, .partiallyRevealed, .open, .closed ] public static func positionFor(string: String?) -> PulleyPosition { guard let positionString = string?.lowercased() else { return .collapsed } switch positionString { case "collapsed": return .collapsed case "partiallyrevealed": return .partiallyRevealed case "open": return .open case "closed": return .closed default: print("PulleyViewController: Position for string '\(positionString)' not found. Available values are: collapsed, partiallyRevealed, open, and closed. Defaulting to collapsed.") return .collapsed } } } private let kPulleyDefaultCollapsedHeight: CGFloat = 68.0 private let kPulleyDefaultPartialRevealHeight: CGFloat = 264.0 open class PulleyViewController: UIViewController { // Interface Builder /// When using with Interface Builder only! Connect a containing view to this outlet. @IBOutlet public var primaryContentContainerView: UIView! /// When using with Interface Builder only! Connect a containing view to this outlet. @IBOutlet public var drawerContentContainerView: UIView! // Internal fileprivate let primaryContentContainer: UIView = UIView() fileprivate let drawerContentContainer: UIView = UIView() fileprivate let drawerShadowView: UIView = UIView() fileprivate let drawerScrollView: PulleyPassthroughScrollView = PulleyPassthroughScrollView() fileprivate let backgroundDimmingView: UIView = UIView() fileprivate var dimmingViewTapRecognizer: UITapGestureRecognizer? fileprivate var lastDragTargetContentOffset: CGPoint = CGPoint.zero /// The current content view controller (shown behind the drawer). public fileprivate(set) var primaryContentViewController: UIViewController! { willSet { guard let controller = primaryContentViewController else { return; } controller.view.removeFromSuperview() controller.willMove(toParentViewController: nil) controller.removeFromParentViewController() } didSet { guard let controller = primaryContentViewController else { return; } controller.view.translatesAutoresizingMaskIntoConstraints = true self.primaryContentContainer.addSubview(controller.view) self.addChildViewController(controller) controller.didMove(toParentViewController: self) if self.isViewLoaded { self.view.setNeedsLayout() self.setNeedsSupportedDrawerPositionsUpdate() } } } /// The current drawer view controller (shown in the drawer). public fileprivate(set) var drawerContentViewController: UIViewController! { willSet { guard let controller = drawerContentViewController else { return; } controller.view.removeFromSuperview() controller.willMove(toParentViewController: nil) controller.removeFromParentViewController() } didSet { guard let controller = drawerContentViewController else { return; } controller.view.translatesAutoresizingMaskIntoConstraints = true self.drawerContentContainer.addSubview(controller.view) self.addChildViewController(controller) controller.didMove(toParentViewController: self) if self.isViewLoaded { self.view.setNeedsLayout() self.setNeedsSupportedDrawerPositionsUpdate() } } } /// The content view controller and drawer controller can receive delegate events already. This lets another object observe the changes, if needed. public weak var delegate: PulleyDelegate? /// The current position of the drawer. public fileprivate(set) var drawerPosition: PulleyPosition = .collapsed { didSet { setNeedsStatusBarAppearanceUpdate() } } // The visible height of the drawer. Useful for adjusting the display of content in the main content view. public var visibleDrawerHeight: CGFloat { if drawerPosition == .closed { return 0.0 } else { return drawerScrollView.bounds.height } } /// The background visual effect layer for the drawer. By default this is the extraLight effect. You can change this if you want, or assign nil to remove it. public var drawerBackgroundVisualEffectView: UIVisualEffectView? = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight)) { willSet { drawerBackgroundVisualEffectView?.removeFromSuperview() } didSet { if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView, self.isViewLoaded { drawerScrollView.insertSubview(drawerBackgroundVisualEffectView, aboveSubview: drawerShadowView) drawerBackgroundVisualEffectView.clipsToBounds = true drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius } } } /// The inset from the top of the view controller when fully open. @IBInspectable public var topInset: CGFloat = 50.0 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The corner radius for the drawer. @IBInspectable public var drawerCornerRadius: CGFloat = 13.0 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() drawerBackgroundVisualEffectView?.layer.cornerRadius = drawerCornerRadius } } } /// The opacity of the drawer shadow. @IBInspectable public var shadowOpacity: Float = 0.1 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The radius of the drawer shadow. @IBInspectable public var shadowRadius: CGFloat = 3.0 { didSet { if self.isViewLoaded { self.view.setNeedsLayout() } } } /// The opaque color of the background dimming view. @IBInspectable public var backgroundDimmingColor: UIColor = UIColor.black { didSet { if self.isViewLoaded { backgroundDimmingView.backgroundColor = backgroundDimmingColor } } } /// The maximum amount of opacity when dimming. @IBInspectable public var backgroundDimmingOpacity: CGFloat = 0.5 { didSet { if self.isViewLoaded { self.scrollViewDidScroll(drawerScrollView) } } } /// The starting position for the drawer when it first loads public var initialDrawerPosition: PulleyPosition = .collapsed /// This is here exclusively to support IBInspectable in Interface Builder because Interface Builder can't deal with enums. If you're doing this in code use the -initialDrawerPosition property instead. Available strings are: open, closed, partiallyRevealed, collapsed @IBInspectable public var initialDrawerPositionFromIB: String? { didSet { initialDrawerPosition = PulleyPosition.positionFor(string: initialDrawerPositionFromIB) } } /// Whether the drawer's position can be changed by the user. If set to `false`, the only way to move the drawer is programmatically. Defaults to `true`. public var allowsUserDrawerPositionChange: Bool = true { didSet { enforceCanScrollDrawer() } } /// The drawer positions supported by the drawer fileprivate var supportedDrawerPositions: [PulleyPosition] = PulleyPosition.all { didSet { guard self.isViewLoaded else { return } guard supportedDrawerPositions.count > 0 else { supportedDrawerPositions = PulleyPosition.all return } self.view.setNeedsLayout() if supportedDrawerPositions.contains(drawerPosition) { setDrawerPosition(position: drawerPosition) } else { let lowestDrawerState: PulleyPosition = supportedDrawerPositions.min { (pos1, pos2) -> Bool in return pos1.rawValue < pos2.rawValue } ?? .collapsed setDrawerPosition(position: lowestDrawerState, animated: false) } enforceCanScrollDrawer() } } /** Initialize the drawer controller programmtically. - parameter contentViewController: The content view controller. This view controller is shown behind the drawer. - parameter drawerViewController: The view controller to display inside the drawer. - note: The drawer VC is 20pts too tall in order to have some extra space for the bounce animation. Make sure your constraints / content layout take this into account. - returns: A newly created Pulley drawer. */ required public init(contentViewController: UIViewController, drawerViewController: UIViewController) { super.init(nibName: nil, bundle: nil) ({ self.primaryContentViewController = contentViewController self.drawerContentViewController = drawerViewController })() } /** Initialize the drawer controller from Interface Builder. - note: Usage notes: Make 2 container views in Interface Builder and connect their outlets to -primaryContentContainerView and -drawerContentContainerView. Then use embed segues to place your content/drawer view controllers into the appropriate container. - parameter aDecoder: The NSCoder to decode from. - returns: A newly created Pulley drawer. */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func loadView() { super.loadView() // IB Support if primaryContentContainerView != nil { primaryContentContainerView.removeFromSuperview() } if drawerContentContainerView != nil { drawerContentContainerView.removeFromSuperview() } // Setup primaryContentContainer.backgroundColor = UIColor.white definesPresentationContext = true drawerScrollView.bounces = false drawerScrollView.delegate = self drawerScrollView.clipsToBounds = false drawerScrollView.showsVerticalScrollIndicator = false drawerScrollView.showsHorizontalScrollIndicator = false drawerScrollView.delaysContentTouches = true drawerScrollView.canCancelContentTouches = true drawerScrollView.backgroundColor = UIColor.clear drawerScrollView.decelerationRate = UIScrollViewDecelerationRateFast drawerScrollView.scrollsToTop = false drawerScrollView.touchDelegate = self drawerShadowView.layer.shadowOpacity = shadowOpacity drawerShadowView.layer.shadowRadius = shadowRadius drawerShadowView.backgroundColor = UIColor.clear drawerContentContainer.backgroundColor = UIColor.clear backgroundDimmingView.backgroundColor = backgroundDimmingColor backgroundDimmingView.isUserInteractionEnabled = false backgroundDimmingView.alpha = 0.0 drawerBackgroundVisualEffectView?.clipsToBounds = true dimmingViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(PulleyViewController.dimmingViewTapRecognizerAction(gestureRecognizer:))) backgroundDimmingView.addGestureRecognizer(dimmingViewTapRecognizer!) drawerScrollView.addSubview(drawerShadowView) if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView { drawerScrollView.addSubview(drawerBackgroundVisualEffectView) drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius } drawerScrollView.addSubview(drawerContentContainer) primaryContentContainer.backgroundColor = UIColor.white self.view.backgroundColor = UIColor.white self.view.addSubview(primaryContentContainer) self.view.addSubview(backgroundDimmingView) self.view.addSubview(drawerScrollView) } override open func viewDidLoad() { super.viewDidLoad() // IB Support if primaryContentViewController == nil || drawerContentViewController == nil { assert(primaryContentContainerView != nil && drawerContentContainerView != nil, "When instantiating from Interface Builder you must provide container views with an embedded view controller.") // Locate main content VC for child in self.childViewControllers { if child.view == primaryContentContainerView.subviews.first { primaryContentViewController = child } if child.view == drawerContentContainerView.subviews.first { drawerContentViewController = child } } assert(primaryContentViewController != nil && drawerContentViewController != nil, "Container views must contain an embedded view controller.") } enforceCanScrollDrawer() setDrawerPosition(position: initialDrawerPosition, animated: false) scrollViewDidScroll(drawerScrollView) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setNeedsSupportedDrawerPositionsUpdate() } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Layout main content primaryContentContainer.frame = self.view.bounds backgroundDimmingView.frame = self.view.bounds // Layout container var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } let lowestStop = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight].min() ?? 0 let bounceOverflowMargin: CGFloat = 20.0 if supportedDrawerPositions.contains(.open) { // Layout scrollview drawerScrollView.frame = CGRect(x: 0, y: topInset, width: self.view.bounds.width, height: self.view.bounds.height - topInset) } else { // Layout scrollview let adjustedTopInset: CGFloat = supportedDrawerPositions.contains(.partiallyRevealed) ? partialRevealHeight : collapsedHeight drawerScrollView.frame = CGRect(x: 0, y: self.view.bounds.height - adjustedTopInset, width: self.view.bounds.width, height: adjustedTopInset) } drawerContentContainer.frame = CGRect(x: 0, y: drawerScrollView.bounds.height - lowestStop, width: drawerScrollView.bounds.width, height: drawerScrollView.bounds.height + bounceOverflowMargin) drawerBackgroundVisualEffectView?.frame = drawerContentContainer.frame drawerShadowView.frame = drawerContentContainer.frame drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width, height: (drawerScrollView.bounds.height - lowestStop) + drawerScrollView.bounds.height) // Update rounding mask and shadows let borderPath = UIBezierPath(roundedRect: drawerContentContainer.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: drawerCornerRadius, height: drawerCornerRadius)).cgPath let cardMaskLayer = CAShapeLayer() cardMaskLayer.path = borderPath cardMaskLayer.frame = drawerContentContainer.bounds cardMaskLayer.fillColor = UIColor.white.cgColor cardMaskLayer.backgroundColor = UIColor.clear.cgColor drawerContentContainer.layer.mask = cardMaskLayer drawerShadowView.layer.shadowPath = borderPath // Make VC views match frames primaryContentViewController?.view.frame = primaryContentContainer.bounds drawerContentViewController?.view.frame = CGRect(x: drawerContentContainer.bounds.minX, y: drawerContentContainer.bounds.minY, width: drawerContentContainer.bounds.width, height: drawerContentContainer.bounds.height) setDrawerPosition(position: drawerPosition, animated: false) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Private State Updates private func enforceCanScrollDrawer() { guard isViewLoaded else { return } drawerScrollView.isScrollEnabled = allowsUserDrawerPositionChange && supportedDrawerPositions.count > 1 } // MARK: Configuration Updates /** Set the drawer position, with an option to animate. - parameter position: The position to set the drawer to. - parameter animated: Whether or not to animate the change. (Default: true) - parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. (Default: nil) */ public func setDrawerPosition(position: PulleyPosition, animated: Bool, completion: PulleyAnimationCompletionBlock? = nil) { guard supportedDrawerPositions.contains(position) else { print("PulleyViewController: You can't set the drawer position to something not supported by the current view controller contained in the drawer. If you haven't already, you may need to implement the PulleyDrawerViewControllerDelegate.") return } drawerPosition = position var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } let stopToMoveTo: CGFloat switch drawerPosition { case .collapsed: stopToMoveTo = collapsedHeight case .partiallyRevealed: stopToMoveTo = partialRevealHeight case .open: stopToMoveTo = (self.view.bounds.size.height - topInset) case .closed: stopToMoveTo = 0 } let drawerStops = [(self.view.bounds.size.height - topInset), collapsedHeight, partialRevealHeight] let lowestStop = drawerStops.min() ?? 0 if animated { UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.0, options: .curveEaseInOut, animations: { [weak self] () -> Void in self?.drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false) if let drawer = self { drawer.delegate?.drawerPositionDidChange?(drawer: drawer) (drawer.drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: drawer) (drawer.primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: drawer) drawer.view.layoutIfNeeded() } }, completion: { (completed) in completion?(completed) }) } else { drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false) delegate?.drawerPositionDidChange?(drawer: self) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: self) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: self) completion?(true) } } /** Set the drawer position, the change will be animated. - parameter position: The position to set the drawer to. */ public func setDrawerPosition(position: PulleyPosition) { setDrawerPosition(position: position, animated: true) } /** Change the current primary content view controller (The one behind the drawer) - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. Defaults to true. - parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. */ public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true, completion: PulleyAnimationCompletionBlock?) { if animated { UIView.transition(with: primaryContentContainer, duration: 0.5, options: .transitionCrossDissolve, animations: { [weak self] () -> Void in self?.primaryContentViewController = controller }, completion: { (completed) in completion?(completed) }) } else { primaryContentViewController = controller completion?(true) } } /** Change the current primary content view controller (The one behind the drawer). This method exists for backwards compatibility. - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. Defaults to true. */ public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true) { setPrimaryContentViewController(controller: controller, animated: animated, completion: nil) } /** Change the current drawer content view controller (The one inside the drawer) - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. - parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. */ public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true, completion: PulleyAnimationCompletionBlock?) { if animated { UIView.transition(with: drawerContentContainer, duration: 0.5, options: .transitionCrossDissolve, animations: { [weak self] () -> Void in self?.drawerContentViewController = controller self?.setDrawerPosition(position: self?.drawerPosition ?? .collapsed, animated: false) }, completion: { (completed) in completion?(completed) }) } else { drawerContentViewController = controller setDrawerPosition(position: drawerPosition, animated: false) completion?(true) } } /** Change the current drawer content view controller (The one inside the drawer). This method exists for backwards compatibility. - parameter controller: The controller to replace it with - parameter animated: Whether or not to animate the change. */ public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true) { setDrawerContentViewController(controller: controller, animated: animated, completion: nil) } /** Update the supported drawer positions allows by the Pulley Drawer */ public func setNeedsSupportedDrawerPositionsUpdate() { if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { supportedDrawerPositions = drawerVCCompliant.supportedDrawerPositions() } else { supportedDrawerPositions = PulleyPosition.all } } // MARK: Actions @objc func dimmingViewTapRecognizerAction(gestureRecognizer: UITapGestureRecognizer) { if gestureRecognizer == dimmingViewTapRecognizer { if gestureRecognizer.state == .ended { self.setDrawerPosition(position: .collapsed, animated: true) } } } // MARK: Propogate child view controller style / status bar presentation based on drawer state override open var childViewControllerForStatusBarStyle: UIViewController? { get { if drawerPosition == .open { return drawerContentViewController } return primaryContentViewController } } override open var childViewControllerForStatusBarHidden: UIViewController? { get { if drawerPosition == .open { return drawerContentViewController } return primaryContentViewController } } } extension PulleyViewController: PulleyPassthroughScrollViewDelegate { func shouldTouchPassthroughScrollView(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> Bool { let contentDrawerLocation = drawerContentContainer.frame.origin.y if point.y < contentDrawerLocation { return true } return false } func viewToReceiveTouch(scrollView: PulleyPassthroughScrollView) -> UIView { if drawerPosition == .open { return backgroundDimmingView } return primaryContentContainer } } extension PulleyViewController: UIScrollViewDelegate { public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if scrollView == drawerScrollView { // Find the closest anchor point and snap there. var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } var drawerStops: [CGFloat] = [CGFloat]() if supportedDrawerPositions.contains(.open) { drawerStops.append((self.view.bounds.size.height - topInset)) } if supportedDrawerPositions.contains(.partiallyRevealed) { drawerStops.append(partialRevealHeight) } if supportedDrawerPositions.contains(.collapsed) { drawerStops.append(collapsedHeight) } let lowestStop = drawerStops.min() ?? 0 let distanceFromBottomOfView = lowestStop + lastDragTargetContentOffset.y var currentClosestStop = lowestStop for currentStop in drawerStops { if abs(currentStop - distanceFromBottomOfView) < abs(currentClosestStop - distanceFromBottomOfView) { currentClosestStop = currentStop } } if abs(Float(currentClosestStop - (self.view.bounds.size.height - topInset))) <= Float.ulpOfOne && supportedDrawerPositions.contains(.open) { setDrawerPosition(position: .open, animated: true) } else if abs(Float(currentClosestStop - collapsedHeight)) <= Float.ulpOfOne && supportedDrawerPositions.contains(.collapsed) { setDrawerPosition(position: .collapsed, animated: true) } else if supportedDrawerPositions.contains(.partiallyRevealed){ setDrawerPosition(position: .partiallyRevealed, animated: true) } } } public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { if scrollView == drawerScrollView { lastDragTargetContentOffset = targetContentOffset.pointee // Halt intertia targetContentOffset.pointee = scrollView.contentOffset } } public func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == drawerScrollView { var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate { collapsedHeight = drawerVCCompliant.collapsedDrawerHeight() partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight() } var drawerStops: [CGFloat] = [CGFloat]() if supportedDrawerPositions.contains(.open) { drawerStops.append((self.view.bounds.size.height - topInset)) } if supportedDrawerPositions.contains(.partiallyRevealed) { drawerStops.append(partialRevealHeight) } if supportedDrawerPositions.contains(.collapsed) { drawerStops.append(collapsedHeight) } let lowestStop = drawerStops.min() ?? 0 if scrollView.contentOffset.y > partialRevealHeight - lowestStop { // Calculate percentage between partial and full reveal let fullRevealHeight = (self.view.bounds.size.height - topInset) let progress = (scrollView.contentOffset.y - (partialRevealHeight - lowestStop)) / (fullRevealHeight - (partialRevealHeight)) delegate?.makeUIAdjustmentsForFullscreen?(progress: progress) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress) backgroundDimmingView.alpha = progress * backgroundDimmingOpacity backgroundDimmingView.isUserInteractionEnabled = true } else { if backgroundDimmingView.alpha >= 0.001 { backgroundDimmingView.alpha = 0.0 delegate?.makeUIAdjustmentsForFullscreen?(progress: 0.0) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0) backgroundDimmingView.isUserInteractionEnabled = false } } delegate?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop) (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop) (primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop) } } }
39.325683
271
0.637579
e00d5d3f5a6891d292bef979e06c15a8ae4416c4
1,262
// // AuthMiddleware.swift // Main // // Created by iq3AddLi on 2019/09/26. // import Vapor struct AlwaysErrorMiddleware: Middleware { func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> { return request.response( ServerError( reason: "Your authentication is bad.") , as: .json) .encode(status: .unauthorized, for: request) } } struct AuthMiddleware: Middleware { func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> { guard let token = request.http.headers["Authentication"].first, token == "hello" else{ return request.response( ServerError( reason: "Your authentication is bad.") , as: .json) .encode(status: .unauthorized, for: request) } let relay = (try request.privateContainer.make(RelayInfomation.self)) relay.infomation = randomString(length: 16) print("\(request.description) token=\(relay.infomation)") return try next.respond(to: request) } } private func randomString(length: Int) -> String { let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" return String((0..<length).map{ _ in letters.randomElement()! }) }
36.057143
101
0.675911
aca8adf080cfb42c1718a9f780af03535c303e8b
1,451
// // UIStoryboard+Extension.swift // Cyton // // Created by 晨风 on 2018/10/8. // Copyright © 2018 Cryptape. All rights reserved. // import Foundation import UIKit protocol StoryboardIdentifiable { static var storyboardIdentifier: String { get } } extension StoryboardIdentifiable where Self: UIViewController { static var storyboardIdentifier: String { return String(describing: self.classForCoder()) } } extension UIViewController: StoryboardIdentifiable { } extension UIStoryboard { enum Name: String { case authentication case settings case switchWallet case guide case addWallet case main case overlay case transactionHistory case sendTransaction case walletManagement case dAppBrowser case transactionDetails var capitalized: String { let capital = String(rawValue.prefix(1)).uppercased() return capital + rawValue.dropFirst() } } convenience init(name: Name, bundle storyboardBundleOrNil: Bundle? = nil) { self.init(name: name.capitalized, bundle: nil) } func instantiateViewController<VC: UIViewController>() -> VC { guard let controller = instantiateViewController(withIdentifier: VC.storyboardIdentifier) as? VC else { fatalError("Error - \(#function): \(VC.storyboardIdentifier)") } return controller } }
25.910714
111
0.664369
460ecd096e8173eafc8db775cd1a7b043d34be84
2,864
// // WMVideoTools.swift // AVPlayerExample // // Created by 许永霖 on 2020/8/12. // Copyright © 2020 Gsafety. All rights reserved. // import UIKit import AVFoundation class WMVideoTools: NSObject { /// compressVideo /// /// - Parameters: /// - presetName: AVAssetExportPresetLowQuality /// - inputURL: input url /// - maxFileSize: byte eg: mb = assetExport.fileLengthLimit = 3 * 1024 * 1024 /// - completionHandler: (URL)->()) /// class func wm_compressVideoWithQuality(presetName: String, inputURL:URL,outputFileType:AVFileType = AVFileType.mp4,maxFileSize:Int64 = 0, completionHandler:@escaping (_ outputUrl: URL?) -> ()) { let videoFilePath = NSTemporaryDirectory().appendingFormat("/compressVideo.mp4") if FileManager.default.fileExists(atPath: videoFilePath) { do { try FileManager.default.removeItem(atPath: videoFilePath) } catch { fatalError("Unable to delete file: \(error) : \(#function).") } } let savePathUrl = URL(fileURLWithPath: videoFilePath) let sourceAsset = AVURLAsset(url: inputURL, options: nil) let assetExport: AVAssetExportSession = AVAssetExportSession(asset: sourceAsset, presetName: presetName)! if maxFileSize > 0{ assetExport.fileLengthLimit = maxFileSize } assetExport.outputFileType = outputFileType assetExport.outputURL = savePathUrl assetExport.shouldOptimizeForNetworkUse = true assetExport.exportAsynchronously { () -> Void in switch assetExport.status { case AVAssetExportSessionStatus.completed: DispatchQueue.main.async { print("successfully exported at \(savePathUrl.path))") completionHandler(savePathUrl) } case AVAssetExportSessionStatus.failed: print("failed \(String(describing: assetExport.error))") DispatchQueue.main.async { print("successfully exported at \(savePathUrl.path))") completionHandler(nil) } case AVAssetExportSessionStatus.cancelled: print("cancelled \(String(describing: assetExport.error))") completionHandler(nil) default: print("complete") completionHandler(nil) } } } /// get file size /// /// - Parameter url: url /// - Returns: Double file size class func wm_getFileSize(_ url:String) -> Double { if let fileData:Data = try? Data.init(contentsOf: URL.init(fileURLWithPath: url)) { let size = Double(fileData.count) / (1024.00 * 1024.00) return size } return 0.00 } }
37.194805
198
0.598115
89134f822b3350aebc4d88b5ce1efdb2b732a85b
295
// // TeadsAdCollectionViewCell.swift // TeadsApp // // Created by Jérémy Grosjean on 29/05/2017. // Copyright © 2018 Teads. All rights reserved. // import UIKit import TeadsSDK class TeadsAdCollectionViewCell: UICollectionViewCell { @IBOutlet var teadsAdContainerView: UIView! }
18.4375
55
0.738983
50a2fc61d15b85405d5ba416f809661b7fdd8b07
3,344
// // PageSelectionView.swift // Monotone // // Created by Xueliang Chen on 2021/1/1. // import UIKit import RxSwift import RxRelay // MARK: - PageSelectionView class PageSelectionView: BaseView { // MARK: - Public public var items: BehaviorRelay<[(key:Any,value:String)]?> = BehaviorRelay<[(key:Any,value:String)]?>(value: nil) public var selectedItem: BehaviorRelay<(key:Any,value:String)?> = BehaviorRelay<(key:Any,value:String)?>(value: nil) // MARK: - Controls private var tableView: UITableView! /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ // MARK: - Private private let disposeBag: DisposeBag = DisposeBag() // MARK: - Life Cycle override func buildSubviews() { super.buildSubviews() // TableView. self.tableView = UITableView() self.tableView.showsVerticalScrollIndicator = false self.tableView.backgroundColor = UIColor.clear self.tableView.separatorStyle = .none self.tableView.register(PageSelectionTableViewCell.self, forCellReuseIdentifier: "PageSelectionTableViewCell") self.tableView.rx.setDelegate(self).disposed(by: self.disposeBag) self.addSubview(self.tableView) self.tableView.snp.makeConstraints { (make) in make.left.right.equalTo(self) make.top.equalTo(self).offset(0) make.bottom.equalTo(self).offset(0) } } override func buildLogic() { super.buildLogic() // Bindings // Pages. self.items .unwrap() .bind(to: self.tableView.rx.items(cellIdentifier: "PageSelectionTableViewCell")){ (row, element, cell) in let pcell: PageSelectionTableViewCell = cell as! PageSelectionTableViewCell pcell.item.accept(element) } .disposed(by: self.disposeBag) // SelectedPage. self.tableView.rx.modelSelected((key:Any,value:String).self) .subscribe(onNext:{ [weak self] (item) in guard let self = self else { return } self.selectedItem.accept(item) }) .disposed(by: self.disposeBag) // ReloadData. self.tableView.rx.methodInvoked(#selector(UITableView.reloadData)) .subscribe(onNext: { [weak self] (_) in guard let self = self else { return } if(self.tableView.numberOfSections > 0 && self.tableView.numberOfRows(inSection: 0) > 0){ let indexPath = IndexPath(row: 0, section: 0) self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) self.tableView.delegate?.tableView?(self.tableView, didSelectRowAt: indexPath) } }) .disposed(by: self.disposeBag) } } // MARK: - UITableViewDelegate extension PageSelectionView: UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 49.0 } }
33.108911
120
0.601376
9160a70d438e3ab0ea1b28756616a1c8af06ae44
2,424
// // KeychainStorage.swift // KeychainApp // // Created by Kakeru Fukuda on 2021/10/04. // import Foundation protocol Storage { func save<T: Codable>(key: String, value: T) throws func load<T: Codable>(key: String, type: T.Type) throws -> T } struct KeychainStorage: Storage { func save<T: Codable>(key: String, value: T) throws { let encoder = JSONEncoder() let encoded = try encoder.encode(value) let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: "[email protected]", kSecAttrLabel as String: key, kSecValueData as String: encoded, ] let status = SecItemCopyMatching(query as CFDictionary, nil) switch status { case errSecItemNotFound: SecItemAdd(query as CFDictionary, nil) case errSecSuccess: SecItemUpdate(query as CFDictionary, [kSecValueData as String: encoded] as CFDictionary) default: print("error: \(status)") throw KeychainError.unhandled(error: status) } } func load<T: Codable>(key: String, type: T.Type) throws -> T { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrLabel as String: key, kSecAttrAccount as String: "[email protected]", kSecMatchLimit as String: kSecMatchLimitOne, kSecReturnAttributes as String: true, kSecReturnData as String: true, ] var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &item) switch status { case errSecItemNotFound: throw KeychainError.notfound case errSecSuccess: guard let item = item, let value = item[kSecValueData as String] as? Data else { throw KeychainError.unexpectedPasswordData } return try JSONDecoder().decode(type, from: value) default: print("error: \(status)") throw KeychainError.unhandled(error: status) } } } enum KeychainError: Error { case notfound case unexpectedPasswordData case unhandled(error: OSStatus) }
31.480519
100
0.57467
0efe5c04b285a5cc43370d05a5b2b31b796f2361
381
// // ViewController.swift // com.pingIdentity.authn // // Copyright © 2020 Ping Identity. All rights reserved. // // See LICENSE.txt for the Ping Authentication licensing information. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
17.318182
70
0.687664
1143cb2031fc94bc6234ac4783d33236b5c06264
1,405
// MIT License // // Copyright (c) 2017-present qazyn951230 [email protected] // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. public struct FileSystems { public static var `default`: FileSystem { darwin } public static let darwin: DarwinFileSystem = DarwinFileSystem() public static let foundation: FoundationFileSystem = FoundationFileSystem() }
43.90625
81
0.758719
f718d12222e1eec1695c204c38ab2e456339ceca
3,925
import XCTest import UIKit @testable import ShimmerView class ShimmerCoreViewAnimatorTests: XCTestCase { func testEffectRadius() { let style = ShimmerViewStyle( baseColor: .clear, highlightColor: .clear, duration: 10, interval: 10, effectSpan: .points(100), effectAngle: 0 ) let baseBounds = CGRect(x: 0, y: 0, width: 300, height: 300) var animator = ShimmerCoreView.Animator( baseBounds: baseBounds, elementFrame: baseBounds, gradientFrame: baseBounds, style: style, effectBeginTime: 0 ) XCTContext.runActivity(named: "Effect Angle = 0.0 pi") { _ in animator.style.effectAngle = 0.0 * CGFloat.pi XCTAssertEqual( animator.effectRadius, baseBounds.width / 2, accuracy: 0.001 ) } XCTContext.runActivity(named: "Effect Angle = 0.25 pi") { _ in animator.style.effectAngle = 0.25 * CGFloat.pi XCTAssertEqual( animator.effectRadius, baseBounds.diagonalDistance/2, accuracy: 0.001 ) } XCTContext.runActivity(named: "Effect Angle = 0.5 pi") { _ in animator.style.effectAngle = 0.5 * CGFloat.pi XCTAssertEqual( animator.effectRadius, baseBounds.height / 2, accuracy: 0.001 ) } XCTContext.runActivity(named: "Effect Angle = 0.75 pi") { _ in animator.style.effectAngle = 0.75 * CGFloat.pi XCTAssertEqual( animator.effectRadius, baseBounds.diagonalDistance/2, accuracy: 0.001 ) } } func testStartPoint() { let style = ShimmerViewStyle( baseColor: .clear, highlightColor: .clear, duration: 10, interval: 10, effectSpan: .points(100), effectAngle: 0 ) let baseBounds = CGRect(x: 0, y: 0, width: 300, height: 300) let animator = ShimmerCoreView.Animator( baseBounds: baseBounds, elementFrame: baseBounds, gradientFrame: baseBounds, style: style, effectBeginTime: 0 ) let denominator = max(baseBounds.width, baseBounds.height) let fromValue = animator.startPointAnimationFromValue XCTAssertEqual(fromValue.x, -100/denominator, accuracy: 0.01) XCTAssertEqual(fromValue.y, 150/denominator, accuracy: 0.01) let toValue = animator.startPointAnimationToValue XCTAssertEqual(toValue.x, 300/denominator, accuracy: 0.01) XCTAssertEqual(toValue.y, 150/denominator, accuracy: 0.01) } func testEndPoint() { let style = ShimmerViewStyle( baseColor: .clear, highlightColor: .clear, duration: 10, interval: 10, effectSpan: .points(100), effectAngle: 0 ) let baseBounds = CGRect(x: 0, y: 0, width: 300, height: 300) let animator = ShimmerCoreView.Animator( baseBounds: baseBounds, elementFrame: baseBounds, gradientFrame: baseBounds, style: style, effectBeginTime: 0 ) let denominator = max(baseBounds.width, baseBounds.height) let fromValue = animator.endPointAnimationFromValue XCTAssertEqual(fromValue.x, 0/denominator, accuracy: 0.01) XCTAssertEqual(fromValue.y, 150/denominator, accuracy: 0.01) let toValue = animator.endPointAnimationToValue XCTAssertEqual(toValue.x, 400/denominator, accuracy: 0.01) XCTAssertEqual(toValue.y, 150/denominator, accuracy: 0.01) } }
33.836207
70
0.563822
fe5549aace0e636fa12338609979d5c729a841f0
907
// // CommandInvoker.swift // PatternsExample // // Created by Yaroslav Voloshyn on 23/02/2017. // Copyright © 2017 Yaroslav Voloshyn. All rights reserved. // import UIKit final class CommandInvoker { fileprivate var commands: [Command] = [] fileprivate func invokeCommand(_ command: Command) { print("**************Start invoke command**********") command.execute() print("**************End invoke command**********") } } extension CommandInvoker { public func addCommand(_ command: Command) -> Int { commands.append(command) return commands.count - 1 } public func invokeCommand(commandId index: Int) { if 0..<commands.count ~= index { invokeCommand(commands[index]) } } public func invokeAllCommands() { for command in commands { invokeCommand(command) } } }
21.595238
61
0.590959
8fe80710b1f5a8ad8e712ceee6f04eb387751698
965
// // Referencable.swift // Ballcap // // Created by 1amageek on 2019/03/27. // Copyright © 2019 Stamp Inc. All rights reserved. // import FirebaseFirestore import FirebaseStorage public protocol Referencable { static var name: String { get } static var path: String { get } static var collectionReference: CollectionReference { get } static var parent: DocumentReference? { get } } public extension Referencable { static var name: String { return String(describing: Mirror(reflecting: self).subjectType).components(separatedBy: ".").first!.lowercased() } static var path: String { return self.collectionReference.path } static var collectionReference: CollectionReference { return BallcapApp.default.rootReference?.collection(self.name) ?? Firestore.firestore().collection(self.name) } static var parent: DocumentReference? { return self.collectionReference.parent } }
23.536585
120
0.703627
acf58b5c919427aae65956e990f726ed9ea986c6
1,350
// // SearchTextRangeService.swift // GMLXcodeTool // // Created by GML on 2021/5/1. // import Foundation class SearchTextRangeService: NSObject { } //MARK:- Class Range Search extension SearchTextRangeService { func classEndIndex(content: String, fileStruct: ClassFileStruct, isAnalysis: (OCClaseStruct?, FileTextRange) -> Bool = { (_, _) in true }, result: (OCClaseStruct?, String.Index) -> Bool) { if fileStruct.classStructs.isEmpty { return } for classInfo in fileStruct.classStructs { if !isAnalysis(classInfo.info, classInfo.range) { continue } var previousCodeEndIndex = content.startIndex var distance = -4 for codeRange in fileStruct.codeRanges { distance += content.distance(from: previousCodeEndIndex, to: codeRange.lowerBound) let index = content.index( classInfo.range.upperBound, offsetBy: distance ) if codeRange.contains(index) { let isNext = result(classInfo.info, index) if isNext { break }else { return } } previousCodeEndIndex = codeRange.upperBound } } } }
32.142857
192
0.556296
87c0a725870cd806652c37fce0ace1696abd0668
3,993
// 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 Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif struct ServiceAccountCredentials : Codable { let CredentialType : String let ProjectId : String let PrivateKeyId : String let PrivateKey : String let ClientEmail : String let ClientID : String let AuthURI : String let TokenURI : String let AuthProviderX509CertURL : String let ClientX509CertURL : String enum CodingKeys: String, CodingKey { case CredentialType = "type" case ProjectId = "project_id" case PrivateKeyId = "private_key_id" case PrivateKey = "private_key" case ClientEmail = "client_email" case ClientID = "client_id" case AuthURI = "auth_uri" case TokenURI = "token_uri" case AuthProviderX509CertURL = "auth_provider_x509_cert_url" case ClientX509CertURL = "client_x509_cert_url" } } public class ServiceAccountTokenProvider : TokenProvider { public var token: Token? var credentials : ServiceAccountCredentials var scopes : [String] var rsaKey : RSAKey public init?(credentialsData:Data, scopes:[String]) { let decoder = JSONDecoder() guard let credentials = try? decoder.decode(ServiceAccountCredentials.self, from: credentialsData) else { return nil } self.credentials = credentials self.scopes = scopes guard let rsaKey = RSAKey(privateKey:credentials.PrivateKey) else { return nil } self.rsaKey = rsaKey } convenience public init?(credentialsURL:URL, scopes:[String]) { guard let credentialsData = try? Data(contentsOf:credentialsURL, options:[]) else { return nil } self.init(credentialsData:credentialsData, scopes:scopes) } public func withToken(_ callback:@escaping (Token?, Error?) -> Void) throws { let iat = Date() let exp = iat.addingTimeInterval(3600) let jwtClaimSet = JWTClaimSet(Issuer:credentials.ClientEmail, Audience:credentials.TokenURI, Scope: scopes.joined(separator: " "), IssuedAt: Int(iat.timeIntervalSince1970), Expiration: Int(exp.timeIntervalSince1970)) let jwtHeader = JWTHeader(Algorithm: "RS256", Format: "JWT") let msg = try JWT.encodeWithRS256(jwtHeader:jwtHeader, jwtClaimSet:jwtClaimSet, rsaKey:rsaKey) let json: [String: Any] = ["grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": msg] let data = try? JSONSerialization.data(withJSONObject: json) var urlRequest = URLRequest(url:URL(string:credentials.TokenURI)!) urlRequest.httpMethod = "POST" urlRequest.httpBody = data urlRequest.setValue("application/json", forHTTPHeaderField:"Content-Type") let session = URLSession(configuration: URLSessionConfiguration.default) let task: URLSessionDataTask = session.dataTask(with:urlRequest) {(data, response, error) -> Void in let decoder = JSONDecoder() if let data = data, let token = try? decoder.decode(Token.self, from: data) { callback(token, error) } else { callback(nil, error) } } task.resume() } }
35.972973
91
0.658903
6736647ffde3602f73afdedc36d760b8f06889cc
3,821
// // AudioPlayerManager.swift // ela // // Created by Bastien Falcou on 4/14/16. // Copyright © 2016 Fueled. All rights reserved. // // swiftlint:disable indentation_character import Foundation import AVFoundation final class AudioPlayerManager: NSObject { static let shared = AudioPlayerManager() var isRunning: Bool { guard let audioPlayer = self.audioPlayer, audioPlayer.isPlaying else { return false } return true } private var audioPlayer: AVAudioPlayer? private var audioMeteringLevelTimer: Timer? // MARK: - Reinit and play from the beginning func play(at url: URL, with audioVisualizationTimeInterval: TimeInterval = 0.05) throws -> TimeInterval { if AudioRecorderManager.shared.isRunning { print("Audio Player did fail to start: AVFoundation is recording") throw AudioErrorType.alreadyRecording } if self.isRunning { print("Audio Player did fail to start: already playing a file") throw AudioErrorType.alreadyPlaying } if !URL.checkPath(url.path) { print("Audio Player did fail to start: file doesn't exist") throw AudioErrorType.audioFileWrongPath } try self.audioPlayer = AVAudioPlayer(contentsOf: url) self.setupPlayer(with: audioVisualizationTimeInterval) print("Started to play sound") return self.audioPlayer!.duration } func play(_ data: Data, with audioVisualizationTimeInterval: TimeInterval = 0.05) throws -> TimeInterval { try self.audioPlayer = AVAudioPlayer(data: data) self.setupPlayer(with: audioVisualizationTimeInterval) print("Started to play sound") return self.audioPlayer!.duration } private func setupPlayer(with audioVisualizationTimeInterval: TimeInterval) { if let player = self.audioPlayer { player.play() player.isMeteringEnabled = true player.delegate = self self.audioMeteringLevelTimer = Timer.scheduledTimer(timeInterval: audioVisualizationTimeInterval, target: self, selector: #selector(AudioPlayerManager.timerDidUpdateMeter), userInfo: nil, repeats: true) } } // MARK: - Resume and pause current if exists func resume() throws -> TimeInterval { if self.audioPlayer?.play() == false { print("Audio Player did fail to resume for internal reason") throw AudioErrorType.internalError } print("Resumed sound") return self.audioPlayer!.duration - self.audioPlayer!.currentTime } func pause() throws { if !self.isRunning { print("Audio Player did fail to start: there is nothing currently playing") throw AudioErrorType.notCurrentlyPlaying } self.audioPlayer?.pause() print("Paused current playing sound") } func stop() throws { if !self.isRunning { print("Audio Player did fail to stop: there is nothing currently playing") throw AudioErrorType.notCurrentlyPlaying } self.audioPlayer?.stop() print("Audio player stopped") } // MARK: - Private @objc private func timerDidUpdateMeter() { if self.isRunning { self.audioPlayer!.updateMeters() let averagePower = self.audioPlayer!.averagePower(forChannel: 0) let percentage: Float = pow(10, (0.05 * averagePower)) NotificationCenter.default.post(name: .audioPlayerManagerMeteringLevelDidUpdateNotification, object: self, userInfo: [audioPercentageUserInfoKey: percentage]) } } } extension AudioPlayerManager: AVAudioPlayerDelegate { func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { NotificationCenter.default.post(name: .audioPlayerManagerMeteringLevelDidFinishNotification, object: self) } } extension Notification.Name { static let audioPlayerManagerMeteringLevelDidUpdateNotification = Notification.Name("AudioPlayerManagerMeteringLevelDidUpdateNotification") static let audioPlayerManagerMeteringLevelDidFinishNotification = Notification.Name("AudioPlayerManagerMeteringLevelDidFinishNotification") }
30.814516
161
0.766553
acd6bd4f996f69f8a5466e6ce435802001f34081
1,131
// // MapMarker.swift // TravelApp // // Created by Anik on 25/11/20. // import SwiftUI struct MapMarker: View { @State var animate = false let placeName: String var body: some View { ZStack { Circle() .fill(Color.red) .frame(width: 10, height: 10) Circle() .fill(Color.red.opacity(0.2)) .frame(width: 10, height: 10) .scaleEffect(animate ? 8.0 : 1.0) .opacity(animate ? 0.1 : 1.0) .animation(Animation.linear(duration: 2.5).repeatForever(autoreverses: false)) GeometryReader { geometry in ZStack { Text(placeName) .font(.system(size: 14)) .padding(6) .background(Color.white) .cornerRadius(5) .fixedSize() } .offset(x: geometry.size.width/2 + 15, y: -8) } } .onAppear { animate = true } } }
26.302326
94
0.425287
7972ec03977841a1d0d117ff8058a2ac961f25b5
1,078
// // ReactiveUI.swift // BlurryCamera // // Created by Nader Besada on 2018-06-01. // Copyright © 2018 Nader Besada. All rights reserved. // import UIKit public protocol ReactiveUI: class { associatedtype UIType: ReactiveUI var rb: Reactive<UIType> { get } } public extension ReactiveUI where Self: ReactiveUI { /// Access ReactiveBind public var rb: Reactive<Self> { return Reactive<Self>(base: self) } } extension UITextField: ReactiveUI { public typealias UIType = UITextField } extension UILabel: ReactiveUI { public typealias UIType = UILabel } extension UIImageView: ReactiveUI { public typealias UIType = UIImageView } extension UISlider: ReactiveUI { public typealias UIType = UISlider } extension UIActivityIndicatorView: ReactiveUI { public typealias UIType = UIActivityIndicatorView } extension UICollectionView: ReactiveUI { public typealias UIType = UICollectionView } extension UIButton: ReactiveUI { public typealias UIType = UIButton } extension UISwitch: ReactiveUI { public typealias UIType = UISwitch }
25.666667
99
0.746753
eb8a4876cf67c052a792afcac4e74e08a9b71b37
307
// // MagiStudyUserSessionRepository.swift // MagiStudyDataKit // // Created by anran on 2019/3/29. // Copyright © 2019 anran. All rights reserved. // import Foundation public class MagiStudyUserSessionRepository { public init(userSessionStore: Int, authRemoteAPI: Int) { } }
17.055556
60
0.687296
2f3661472bbedce68d69188b8a0d8bd047bb9c0a
2,596
// // Copyright © 2021 Newbedev. All rights reserved. import SwiftUI struct HStackDynamicHeight<Model, V>: View where Model: Hashable, V: View { typealias ViewGenerator = (Model) -> V var models: [Model] var viewGenerator: ViewGenerator var horizontalSpacing: CGFloat = 2 var verticalSpacing: CGFloat = 0 @State private var totalHeight = CGFloat.zero // << variant for ScrollView/List // = CGFloat.infinity // << variant for VStack var body: some View { VStack { GeometryReader { geometry in self.generateContent(in: geometry) } } .frame(height: totalHeight)// << variant for ScrollView/List //.frame(maxHeight: totalHeight) // << variant for VStack } private func generateContent(in geometry: GeometryProxy) -> some View { var width = CGFloat.zero var height = CGFloat.zero return ZStack(alignment: .topLeading) { ForEach(self.models, id: \.self) { model in viewGenerator(model) .padding(.horizontal, horizontalSpacing) .padding(.vertical, verticalSpacing) .alignmentGuide(.leading, computeValue: { dimension in if (abs(width - dimension.width) > geometry.size.width) { width = 0 height -= dimension.height } let result = width if model == self.models.last { width = 0 //last item } else { width -= dimension.width } return result }) .alignmentGuide(.top, computeValue: {dimension in let result = height if model == self.models.last { height = 0 // last item } return result }) } } .background(viewHeightReader($totalHeight)) } private func viewHeightReader(_ binding: Binding<CGFloat>) -> some View { return GeometryReader { geometry -> Color in let rect = geometry.frame(in: .local) DispatchQueue.main.async { binding.wrappedValue = rect.size.height } return .clear } } } /// NOTE: A dynamic height is calculated in run-time only. No preview is available
35.081081
82
0.504622
1cd0ab951bb3b78a8319843c36c6f04cb9b59e86
1,745
// // Collection+SafeAccessTest.swift // BXSwiftUtilsTests-macOS // // Created by Stefan Fochler on 08.03.18. // Copyright © 2018 Boinx Software Ltd. All rights reserved. // import XCTest import BXSwiftUtils class Collection_SafeAccessTests: XCTestCase { let data = ["hello", "world", "one", "two", "three"] let empty: [String] = [] func testSuccessfullAccess() { XCTAssertEqual(data[safe: 0], "hello", "retrieves existing element") } func testOutOfBoundsAccess() { XCTAssertEqual(data[safe: 1337], nil, "safely returns nil") } func testClosedRangeAccess() { XCTAssertEqual(data[safe: 0...1], ["hello", "world"]) XCTAssertEqual(data[safe: 1...1], ["world"]) XCTAssertEqual(data[safe: 2...4], ["one", "two", "three"]) XCTAssertEqual(data[safe: 2...10], ["one", "two", "three"]) XCTAssertEqual(data[safe: -1...1], ["hello", "world"]) XCTAssertEqual(Array(data[safe: -10...10]), data) XCTAssertEqual(data[safe: 10...20], []) XCTAssertEqual(data[safe: -20...(-10)], []) XCTAssertEqual(empty[safe: -10...10], []) } func testRangeAccess() { XCTAssertEqual(data[safe: 0..<2], ["hello", "world"]) XCTAssertEqual(data[safe: 0..<1], ["hello"]) XCTAssertEqual(data[safe: 2..<5], ["one", "two", "three"]) XCTAssertEqual(data[safe: 2..<10], ["one", "two", "three"]) XCTAssertEqual(data[safe: -1..<2], ["hello", "world"]) XCTAssertEqual(Array(data[safe: -10..<10]), data) XCTAssertEqual(data[safe: 10..<20], []) XCTAssertEqual(data[safe: -20..<(-10)], []) XCTAssertEqual(empty[safe: -10..<10], []) } }
31.160714
76
0.570201
fed297317117e5fb126db6f0f0fce80201cd20d5
153
// // File.swift // SIMS // // Created by Danish Khan on 19/04/19. // Copyright © 2019 Abhishek Agarwal. All rights reserved. // import Foundation
15.3
59
0.660131
f53ec98aad0038a7c5ade30073e4ae0f5bb2a615
333
// // ComparableExtension.swift // XWAppKit_Swift // // Created by ZHXW on 2020/9/25. // Copyright © 2020 ZhuanagXiaowei. All rights reserved. // import Foundation public extension Comparable { func clamped(to limits: ClosedRange<Self>) -> Self { return min(max(self, limits.lowerBound), limits.upperBound) } }
20.8125
67
0.693694
2036446e7040f32d5b54161cbba93fd00d799ade
2,068
// // User.swift // Twitter // // Created by Adam Epstein on 2/16/16. // Copyright © 2016 Adam Epstein. All rights reserved. // import UIKit class User: NSObject { var name: String? var screenname: String? var imageURL: String? var tagline: String? var dictionary: NSDictionary var profileURL: NSURL? init(dictionary: NSDictionary) { self.dictionary = dictionary as NSDictionary name = dictionary["name"] as? String screenname = "@\(dictionary["screen_name"]!)" as? String imageURL = dictionary["profile_image_url"] as? String tagline = dictionary["description"] as? String let profileURLString = dictionary["profile_image_url_https"] as? String if let profileURLString = profileURLString { profileURL = NSURL(string: profileURLString) //print(profileURLString) } } static let userDidLogoutNotification = "UserDidLogout" static var _currentUser: User? class var currentUser: User? { get { if _currentUser == nil{ let defaults = NSUserDefaults.standardUserDefaults() let userData = defaults.objectForKey("currentUserData") as? NSData if let userData = userData { let dictionary = try! NSJSONSerialization.JSONObjectWithData(userData, options: []) as! NSDictionary _currentUser = User(dictionary: dictionary) } } return _currentUser } set(user) { _currentUser = user let defaults = NSUserDefaults.standardUserDefaults() if let user = user { let data = try! NSJSONSerialization.dataWithJSONObject(user.dictionary, options: []) defaults.setObject(data, forKey: "currentUserData") } else{ defaults.setObject(nil, forKey: "currentUserData") } defaults.synchronize() } } }
29.971014
120
0.584623
0eb433cda7fd12e1fbdeee65d4c1ab9d2e156e59
1,274
// // AdPostImageDelete.swift // AdForest // // Created by apple on 4/28/18. // Copyright © 2018 apple. All rights reserved. // import Foundation struct AdPostImageDeleteRoot { var data : AdPostImageDeleteData! var message : String! var success : Bool! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: [String:Any]){ if let dataData = dictionary["data"] as? [String:Any]{ data = AdPostImageDeleteData(fromDictionary: dataData) } message = dictionary["message"] as? String success = dictionary["success"] as? Bool } /** * Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> [String:Any] { var dictionary = [String:Any]() if data != nil{ dictionary["data"] = data.toDictionary() } if message != nil{ dictionary["message"] = message } if success != nil{ dictionary["success"] = success } return dictionary } }
26.541667
183
0.600471
1150b9d4a6eff7af2e9e71cfccfaa0b653c015ce
22,698
// This source file is part of the Swift.org open source project // // Copyright 2015-2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for Swift project authors // This file contains Swift bindings for the llbuild C API. import Foundation // We don't need this import if we're building // this file as part of the llbuild framework. #if !LLBUILD_FRAMEWORK import llbuild #endif enum DatabaseError: Error { case AttachFailure(message: String) } private func stringFromData(data: llb_data_t) -> String { // Convert as a UTF8 string, if possible. let tmp = Data(UnsafeBufferPointer(start: unsafeBitCast(data.data, to: UnsafePointer<UInt8>.self), count: Int(data.length))) if let str = String(data: tmp, encoding: String.Encoding.utf8) { return str } // Otherwise, return a string representation of the bytes. return String(describing: [UInt8](UnsafeBufferPointer(start: data.data, count: Int(data.length)))) } private func stringFromUInt8Array(_ data: [UInt8]) -> String { // Convert as a UTF8 string, if possible. if let str = String(data: Data(data), encoding: String.Encoding.utf8) { return str } // Otherwise, return a string representation of the bytes. return String(describing: data) } /// Key objects are used to identify rules that can be built. public struct Key: CustomStringConvertible, Equatable, Hashable { public let data: [UInt8] // MARK: CustomStringConvertible Conformance public var description: String { return "<Key: '\(toString())'>" } // MARK: Hashable Conformance public var hashValue: Int { // FIXME: Use a real hash function. var result = data.count for c in data { result = result*31 + Int(c) } return result } // MARK: Implementation public init(_ data: [UInt8]) { self.data = data } public init(_ str: String) { self.init(Array(str.utf8)) } /// Convert to a string representation. public func toString() -> String { return stringFromUInt8Array(self.data) } /// Create a Key object from an llb_data_t. fileprivate static func fromInternalData(_ data: llb_data_t) -> Key { return Key([UInt8](UnsafeBufferPointer(start: data.data, count: Int(data.length)))) } /// Provide a Key contents as an llb_data_t pointer. fileprivate func withInternalDataPtr<T>(closure: (UnsafePointer<llb_data_t>) -> T) -> T { return data.withUnsafeBufferPointer { (dataPtr: UnsafeBufferPointer<UInt8>) -> T in var value = llb_data_t(length: UInt64(self.data.count), data: dataPtr.baseAddress) return withUnsafePointer(to: &value, closure) } } } public func ==(lhs: Key, rhs: Key) -> Bool { return lhs.data == rhs.data } /// Value objects are the result of building rules. public struct Value: CustomStringConvertible { public let data: [UInt8] public var description: String { return "<Value: '\(toString())'>" } public init(_ data: [UInt8]) { self.data = data } public init(_ str: String) { self.init(Array(str.utf8)) } /// Convert to a string representation. public func toString() -> String { return stringFromUInt8Array(self.data) } /// Create a Value object from an llb_data_t. fileprivate static func fromInternalData(_ data: llb_data_t) -> Value { return Value([UInt8](UnsafeBufferPointer(start: data.data, count: Int(data.length)))) } /// Provide a Value contents as an llb_data_t pointer. fileprivate func withInternalDataPtr<T>(closure: (UnsafePointer<llb_data_t>) -> T) -> T { return data.withUnsafeBufferPointer { (dataPtr: UnsafeBufferPointer<UInt8>) -> T in var value = llb_data_t(length: UInt64(self.data.count), data: dataPtr.baseAddress) return withUnsafePointer(to: &value, closure) } } /// Create a Value object by providing an pointer to write the output into. /// /// \param closure The closure to execute with a pointer to a llb_data_t to /// use. The structure *must* be filled in by the closure. /// /// \return The output Value. fileprivate static func fromInternalDataOutputPtr(closure: (UnsafeMutablePointer<llb_data_t>) -> Void) -> Value { var data = llb_data_t() withUnsafeMutablePointer(to: &data, closure) return Value.fromInternalData(data) } } /// Enumeration describing the possible status of a Rule, used by \see /// Rule.updateStatus(). public enum RuleStatus { /// Indicates the rule is being scanned. case IsScanning /// Indicates the rule is up-to-date, and doesn't need to run. case IsUpToDate /// Indicates the rule was run, and is now complete. case IsComplete } /// A rule represents an individual element of computation that can be performed /// by the build engine. /// /// Each rule is identified by a unique key and the value for that key can be /// computed to produce a result, and supplies a set of callbacks that are used /// to implement the rule's behavior. /// /// The computation for a rule is done by invocation of its \see Action /// callback, which is responsible for creating a Task object which will manage /// the computation. /// /// All callbacks for the Rule are always invoked synchronously on the primary /// BuildEngine thread. public protocol Rule { /// Called to create the task to build the rule, when necessary. func createTask() -> Task /// Called to check whether the previously computed value for this rule is /// still valid. /// /// This callback is designed for use in synchronizing values which represent /// state managed externally to the build engine. For example, a rule which /// computes something on the file system may use this to verify that the /// computed output has not changed since it was built. func isResultValid(_ priorValue: Value) -> Bool /// Called to indicate a change in the rule status. func updateStatus(_ status: RuleStatus) } /// Protocol extension for default Rule methods. public extension Rule { func isResultValid(_ priorValue: Value) -> Bool { return true } func updateStatus(_ status: RuleStatus) { } } /// A task object represents an abstract in-progress computation in the build /// engine. /// /// The task represents not just the primary computation, but also the process /// of starting the computation and necessary input dependencies. Tasks are /// expected to be created in response to \see BuildEngine requests to initiate /// the production of particular result value. /// /// The creator may use \see TaskBuildEngine.taskNeedsInput() to specify input /// dependencies on the Task. The Task itself may also specify additional input /// dependencies dynamically during the execution of \see Task.start() or \see /// Task.provideValue(). /// /// Once a task has been created and registered, the BuildEngine will invoke /// \see Task::start() to initiate the computation. The BuildEngine will provide /// the in progress task with its requested inputs via \see /// Task.provideValue(). /// /// After all inputs requested by the Task have been delivered, the BuildEngine /// will invoke \see Task.inputsAvailable() to instruct the Task it should /// complete its computation and provide the output. The Task is responsible for /// providing the engine with the computed value when ready using \see /// TaskBuildEngine.taskIsComplete(). public protocol Task { /// Executed by the build engine when the task should be started. func start(_ engine: TaskBuildEngine) /// Invoked by the build engine to provide an input value as it becomes /// available. /// /// \param inputID The unique identifier provided to the build engine to /// represent this input when requested in \see /// TaskBuildEngine.taskNeedsInput(). /// /// \param value The computed value for the given input. func provideValue(_ engine: TaskBuildEngine, inputID: Int, value: Value) /// Executed by the build engine to indicate that all inputs have been /// provided, and the task should begin its computation. /// /// The task is expected to call \see TaskBuildEngine.taskIsComplete() when it is /// done with its computation. /// /// It is an error for any client to request an additional input for a task /// after the last requested input has been provided by the build engine. func inputsAvailable(_ engine: TaskBuildEngine) } /// Delegate interface for use with the build engine. public protocol BuildEngineDelegate { /// Get the rule to use for the given Key. /// /// The delegate *must* provide a rule for any possible key that can be /// requested (either by a client, through \see BuildEngine.build(), or via a /// Task through mechanisms such as \see TaskBuildEngine.taskNeedsInput(). If a /// requested Key cannot be supplied, the delegate should provide a dummy rule /// that the client can translate into an error. func lookupRule(_ key: Key) -> Rule } /// Wrapper to allow passing an opaque pointer to a protocol type. // // FIXME: Why do we need this, why can't we get a pointer to the protocol // typed object? private class Wrapper<T> { let item: T init(_ item: T) { self.item = item } } /// This protocol encapsulates the API that a task can use to communicate with /// the build engine. public protocol TaskBuildEngine { var engine: BuildEngine { get } /// Specify that the task depends upon the result of computing \arg key. /// /// The result, when available, will be provided to the task via \see /// Task.provideValue(), supplying the provided \arg inputID to allow the task /// to identify the particular input. /// /// NOTE: It is an unchecked error for a task to request the same input value /// multiple times. /// /// \param inputID An arbitrary value that may be provided by the client to /// use in efficiently associating this input. func taskNeedsInput(_ key: Key, inputID: Int) /// Specify that the task must be built subsequent to the computation of \arg /// key. /// /// The value of the computation of \arg key is not available to the task, and /// the only guarantee the engine provides is that if \arg key is computed /// during a build, then task will not be computed until after it. func taskMustFollow(_ key: Key) /// Inform the engine of an input dependency that was discovered by the task /// during its execution, a la compiler generated dependency files. /// /// This call may only be made after a task has received all of its inputs; /// inputs discovered prior to that point should simply be requested as normal /// input dependencies. /// /// Such a dependency is not used to provide additional input to the task, /// rather it is a way for the task to report an additional input which should /// be considered the next time the rule is evaluated. The expected use case /// for a discovered dependency is is when a processing task cannot predict /// all of its inputs prior to being run, but can presume that any unknown /// inputs already exist. In such cases, the task can go ahead and run and can /// report the all of the discovered inputs as it executes. Once the task is /// complete, these inputs will be recorded as being dependencies of the task /// so that it will be recomputed when any of the inputs change. /// /// It is legal to call this method from any thread, but the caller is /// responsible for ensuring that it is never called concurrently for the same /// task. func taskDiscoveredDependency(_ key: Key) /// Indicate that the task has completed and provide its resulting value. /// /// It is legal to call this method from any thread. /// /// \param value The new value for the task's rule. /// /// \param forceChange If true, treat the value as changed and trigger /// dependents to rebuild, even if the value itself is not different from the /// prior result. func taskIsComplete(_ result: Value, forceChange: Bool) } extension TaskBuildEngine { /// Indicate that the task has completed and provide its resulting value. /// /// It is legal to call this method from any thread. /// /// - Parameter result: value The new value for the task's rule. public func taskIsComplete(_ result: Value) { self.taskIsComplete(result, forceChange: false) } } /// Single concrete implementation of the TaskBuildEngine protocol. private class TaskWrapper: CustomStringConvertible, TaskBuildEngine { let engine: BuildEngine let task: Task var taskInternal: OpaquePointer? var description: String { return "<TaskWrapper engine:\(engine), task:\(task)>" } init(_ engine: BuildEngine, _ task: Task) { self.engine = engine self.task = task } func taskNeedsInput(_ key: Key, inputID: Int) { engine.taskNeedsInput(self, key: key, inputID: inputID) } func taskMustFollow(_ key: Key) { engine.taskMustFollow(self, key: key) } func taskDiscoveredDependency(_ key: Key) { engine.taskDiscoveredDependency(self, key: key) } func taskIsComplete(_ result: Value, forceChange: Bool = false) { engine.taskIsComplete(self, result: result, forceChange: forceChange) } } /// A build engine supports fast, incremental, persistent, and parallel /// execution of computational graphs. /// /// Computational elements in the graph are modeled by \see Rule objects, which /// are assocated with a specific \see Key, and which can be executed to produce /// an output \see Value for that key. /// /// Rule objects are evaluated by first invoking their action to produce a \see /// Task object which is responsible for the live execution of the /// computation. The Task object can interact with the BuildEngine to request /// inputs or to notify the engine of its completion, and receives various /// callbacks from the engine as the computation progresses. /// /// The engine itself executes using a deterministic, serial operation, but it /// supports parallel computation by allowing the individual Task objects to /// defer their own computation to signal the BuildEngine of its completion on /// alternate threads. /// /// To support persistence, the engine allows attaching a database (\see /// attachDB()) which can be used to record the prior results of evaluating Rule /// instances. public class BuildEngine { /// The client delegate. private var delegate: BuildEngineDelegate /// The internal llbuild build engine. private var _engine: OpaquePointer? /// Our llbuild engine delegate object. private var _delegate = llb_buildengine_delegate_t() /// The number of rules which have been defined. public var numRules: Int = 0 public init(delegate: BuildEngineDelegate) { self.delegate = delegate // Initialize the delegate. _delegate.context = unsafeBitCast(Unmanaged.passUnretained(self), to: UnsafeMutableRawPointer.self) _delegate.lookup_rule = { BuildEngine.toEngine($0!).lookupRule($1!, $2!) } // FIXME: Include cycleDetected callback. // Create the engine. _engine = llb_buildengine_create(_delegate) } deinit { if _engine != nil { close() } } public func close() { assert(_engine != nil) llb_buildengine_destroy(_engine) _engine = nil } /// Build the result for a particular key. public func build(key: Key) -> Value { return Value.fromInternalDataOutputPtr { resultPtr in key.withInternalDataPtr { llb_buildengine_build(self._engine, $0, resultPtr) } } } /// Attach a database for persisting build state. /// /// A database should only be attached immediately after creating the engine, /// it is an error to attach a database after adding rules or initiating any /// builds, or to attempt to attach multiple databases. public func attachDB(path: String, schemaVersion: Int = 0) throws { let errorPtr = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1) defer { errorPtr.deinitialize(count: 1) } // FIXME: Why do I have to name the closure signature here? var errorMsgOpt: String? = nil Key(path).withInternalDataPtr { (ptr) -> Void in if !llb_buildengine_attach_db(self._engine, ptr, UInt32(schemaVersion), errorPtr) { // If there was an error, report it. if let errorPointee = errorPtr.pointee { errorMsgOpt = String(cString: errorPointee) } } } // Throw the error, if found. if let errorMsg = errorMsgOpt { throw DatabaseError.AttachFailure(message: errorMsg) } } /// MARK: Internal Task-Only API fileprivate func taskNeedsInput(_ taskWrapper: TaskWrapper, key: Key, inputID: Int) { key.withInternalDataPtr { keyPtr in llb_buildengine_task_needs_input(self._engine, taskWrapper.taskInternal, keyPtr, UInt(inputID)) } } fileprivate func taskMustFollow(_ taskWrapper: TaskWrapper, key: Key) { key.withInternalDataPtr { keyPtr in llb_buildengine_task_must_follow(self._engine, taskWrapper.taskInternal, keyPtr) } } fileprivate func taskDiscoveredDependency(_ taskWrapper: TaskWrapper, key: Key) { key.withInternalDataPtr { keyPtr in llb_buildengine_task_discovered_dependency(self._engine, taskWrapper.taskInternal, keyPtr) } } fileprivate func taskIsComplete(_ taskWrapper: TaskWrapper, result: Value, forceChange: Bool = false) { result.withInternalDataPtr { dataPtr in llb_buildengine_task_is_complete(self._engine, taskWrapper.taskInternal, dataPtr, forceChange) } } /// MARK: Internal Delegate Implementation /// Helper function for getting the engine from the delegate context. static fileprivate func toEngine(_ context: UnsafeMutableRawPointer) -> BuildEngine { return Unmanaged<BuildEngine>.fromOpaque(context).takeUnretainedValue() } /// Helper function for getting the rule from a rule delegate context. static fileprivate func toRule(_ context: UnsafeMutableRawPointer) -> Rule { return Unmanaged<Wrapper<Rule>>.fromOpaque(context).takeUnretainedValue().item } /// Helper function for getting the task from a task delegate context. static fileprivate func toTaskWrapper(_ context: UnsafeMutableRawPointer) -> TaskWrapper { return Unmanaged<TaskWrapper>.fromOpaque(context).takeUnretainedValue() } fileprivate func lookupRule(_ key: UnsafePointer<llb_data_t>, _ ruleOut: UnsafeMutablePointer<llb_rule_t>) { numRules += 1 // Get the rule from the client. let rule = delegate.lookupRule(Key.fromInternalData(key.pointee)) // Fill in the output structure. // // FIXME: We need a deallocation callback in order to ensure this is released. ruleOut.pointee.context = unsafeBitCast(Unmanaged.passRetained(Wrapper(rule)), to: UnsafeMutableRawPointer.self) ruleOut.pointee.create_task = { (context, engineContext) -> OpaquePointer? in let rule = BuildEngine.toRule(context!) let engine = BuildEngine.toEngine(engineContext!) return engine.ruleCreateTask(rule) } ruleOut.pointee.is_result_valid = { (context, engineContext, internalRule, value) -> Bool in let rule = BuildEngine.toRule(context!) return rule.isResultValid(Value.fromInternalData(value!.pointee)) } ruleOut.pointee.update_status = { (context, engineContext, status) in let rule = BuildEngine.toRule(context!) let status = { (kind: llb_rule_status_kind_t) -> RuleStatus in switch kind.rawValue { case llb_rule_is_scanning.rawValue: return .IsScanning case llb_rule_is_up_to_date.rawValue: return .IsUpToDate case llb_rule_is_complete.rawValue: return .IsComplete default: fatalError("unknown status kind") } }(status) return rule.updateStatus(status) } } private func ruleCreateTask(_ rule: Rule) -> OpaquePointer { // Create the task. let task = rule.createTask() // Create the task wrapper. // // Note that the wrapper here is serving two purposes, it is providing a way // to communicate the internal task object to clients, and it is providing a // way to segregate the Task-only API from the rest of the BuildEngine API. let taskWrapper = TaskWrapper(self, task) // Create the task delegate. // // FIXME: Separate the delegate from the context pointer. var taskDelegate = llb_task_delegate_t() // FIXME: We need a deallocation callback in order to ensure this is released. taskDelegate.context = unsafeBitCast(Unmanaged.passRetained(taskWrapper), to: UnsafeMutableRawPointer.self) taskDelegate.start = { (context, engineContext, internalTask) in let taskWrapper = BuildEngine.toTaskWrapper(context!) taskWrapper.task.start(taskWrapper) } taskDelegate.provide_value = { (context, engineContext, internalTask, inputID, value) in let taskWrapper = BuildEngine.toTaskWrapper(context!) taskWrapper.task.provideValue(taskWrapper, inputID: Int(inputID), value: Value.fromInternalData(value!.pointee)) } taskDelegate.inputs_available = { (context, engineContext, internalTask) in let taskWrapper = BuildEngine.toTaskWrapper(context!) taskWrapper.task.inputsAvailable(taskWrapper) } // Create the internal task. taskWrapper.taskInternal = llb_task_create(taskDelegate) // FIXME: Why do we have both of these, it is kind of annoying. It makes // some amount of sense in the C++ API, but the C API should probably just // collapse them. return llb_buildengine_register_task(self._engine, taskWrapper.taskInternal) } }
40.459893
128
0.685259
205d498049bad5e1a9e02f5802c11bee423cde26
364
// // UIStackView+Convenience.swift // LongShot // // Created by Brandon on 2018-08-27. // Copyright © 2018 XIO. All rights reserved. // import Foundation import UIKit public extension UIStackView { @discardableResult func addArrangedSubviews(_ views: [UIView]) -> Self { views.forEach({ addArrangedSubview($0) }) return self } }
19.157895
57
0.67033
48fb0a3c8449a530aed02cd36301a8a59a93cd94
4,325
// // NSWindow-NoodleEffects.swift // XUCore // // Created by Charlie Monroe on 11/21/15. // Copyright © 2015 Charlie Monroe Software. All rights reserved. // import AppKit import Foundation /// Set this variable to a speed-up or slow down the effect private let kXUZoomAnimationTimeMultiplier = 0.4 private class __XUZoomWindow: NSPanel { @objc override func animationResizeTime(_ newWindowFrame: CGRect) -> TimeInterval { return super.animationResizeTime(newWindowFrame) * kXUZoomAnimationTimeMultiplier } } public extension NSWindow { private static var __zoomWindow: NSWindow? /// Creates a new zoom window in screen rect. Nil is returned when there is /// no contentView, or the view fails to create the bitmap image representation. private func _createZoomWindowWithRect(_ rect: CGRect) -> NSPanel? { let frame = self.frame let isOneShot = self.isOneShot if isOneShot { self.isOneShot = false } if self.windowNumber <= 0 { // Force window device. Kinda crufty but I don't see a visible flash // when doing this. May be a timing thing wrt the vertical refresh. self.orderBack(self) self.orderOut(self) } let image = NSImage(size: frame.size) guard let view = self.contentView?.superview else { return nil } guard let imageRep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { return nil } view.cacheDisplay(in: view.bounds, to: imageRep) image.addRepresentation(imageRep) let mask = NSWindow.StyleMask.borderless let zoomWindow = __XUZoomWindow(contentRect: rect, styleMask: mask, backing: .buffered, defer: false) zoomWindow.backgroundColor = NSColor(deviceWhite: 0.0, alpha: 0.0) zoomWindow.hasShadow = self.hasShadow zoomWindow.level = .modalPanel zoomWindow.isOpaque = false let imageView = NSImageView(frame: zoomWindow.contentRect(forFrameRect: frame)) imageView.image = image imageView.imageFrameStyle = .none imageView.imageScaling = .scaleAxesIndependently imageView.autoresizingMask = [.width, .height] zoomWindow.contentView = imageView // Reset one shot flag self.isOneShot = isOneShot NSWindow.__zoomWindow = zoomWindow return zoomWindow } /// Pops the window on screen from startRect. func zoomIn(fromRect startRect: CGRect) { if self.isVisible { return // Do nothing if we're already on-screen } let frame = self.frame self.setFrame(frame, display: true) let zoomWindow = self._createZoomWindowWithRect(startRect) zoomWindow?.orderFront(self) zoomWindow?.setFrame(frame, display: true, animate: true) self.orderFront(nil) zoomWindow?.close() NSWindow.__zoomWindow = nil } /// Removes the window from screen by zooming off to the center of the window. func popAway() { var frame = self.frame frame.origin.x += (frame.width / 2.0) - 10.0 frame.origin.y += (frame.height / 2.0) - 10.0 frame.size.width = 20.0 frame.size.height = 20.0 self.zoomOut(toRect: frame) } /// Pops the window on screen from the middle of self.frame. func pop() { self.display() let frame = self.frame if self.isVisible { return // Already visible } let originalFrame = frame var enlargedFrame = originalFrame enlargedFrame.origin.x -= 12.5 enlargedFrame.origin.y -= 12.5 enlargedFrame.size.width += 25.0 enlargedFrame.size.height += 25.0 var fromRect = originalFrame fromRect.origin.x += originalFrame.width / 2.0 fromRect.origin.y += originalFrame.height / 2.0 fromRect.size.width = 1.0 fromRect.size.height = 1.0 let zoomWindow = self._createZoomWindowWithRect(fromRect) zoomWindow?.orderFront(self) zoomWindow?.setFrame(enlargedFrame, display: true, animate: true) zoomWindow?.setFrame(originalFrame, display: true, animate: true) self.makeKeyAndOrderFront(self) zoomWindow?.close() NSWindow.__zoomWindow = nil } /// Removes the window from screen by zooming off to endRect. func zoomOut(toRect endRect: CGRect) { if !self.isVisible { return // Already off screen } let frame = self.frame let zoomWindow = self._createZoomWindowWithRect(frame) zoomWindow?.orderFront(self) self.orderOut(self) zoomWindow?.setFrame(endRect, display: true, animate: true) zoomWindow?.close() NSWindow.__zoomWindow = nil } }
26.371951
103
0.720694
eb815ecacd9362eec8968018cae21019894a00d0
1,244
// // FocusPlanUITests.swift // FocusPlanUITests // // Created by Vojtech Rinik on 6/28/17. // Copyright © 2017 Median. All rights reserved. // import XCTest class FocusPlanUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.621622
182
0.663183
4b77203d1c5024c9be4299e70433c358371c921f
1,985
// // ReachabilityManager.swift // breadwallet // // Created by Adrian Corscadden on 2017-06-17. // Copyright © 2017 breadwallet LLC. All rights reserved. // import Foundation import SystemConfiguration private func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) { guard let info = info else { return } let reachability = Unmanaged<ReachabilityMonitor>.fromOpaque(info).takeUnretainedValue() reachability.notify() } class ReachabilityMonitor : Trackable { init() { networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "google.com") start() } var didChange: ((Bool) -> Void)? private var networkReachability: SCNetworkReachability? private let reachabilitySerialQueue = DispatchQueue(label: "com.adelaidecreative.reachabilityQueue") func notify() { DispatchQueue.main.async { self.didChange?(self.isReachable) self.saveEvent(self.isReachable ? "reachability.isReachble" : "reachability.isNotReachable") } } var isReachable: Bool { return flags.contains(.reachable) } private func start() { var context = SCNetworkReachabilityContext() context.info = UnsafeMutableRawPointer(Unmanaged<ReachabilityMonitor>.passUnretained(self).toOpaque()) guard let reachability = networkReachability else { return } SCNetworkReachabilitySetCallback(reachability, callback, &context) SCNetworkReachabilitySetDispatchQueue(reachability, reachabilitySerialQueue) } private var flags: SCNetworkReachabilityFlags { var flags = SCNetworkReachabilityFlags(rawValue: 0) if let reachability = networkReachability, withUnsafeMutablePointer(to: &flags, { SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0)) }) == true { return flags } else { return [] } } }
33.083333
172
0.70932
9c4ec9c48d920a4d6aab3b7830d1cb2b2f88e3dc
6,319
// RUN: %target-swift-frontend -primary-file %s -emit-ir -Onone -enable-copy-propagation | %FileCheck %s -DINT=i%target-ptrsize // Test debug_value [poison] emission class K { init() {} } protocol P : AnyObject {} class D : P {} protocol Q {} class E : Q {} func useInt(_ i: Int) {} func useAny(_: Any) {} func useOptionalAny(_: Any?) {} func useNone() {} func getK() -> K { return K() } func getOptionalK() -> K? { return K() } private func useK(_: K) -> Int { return 2 } private func useOptionalK(_: K?) -> Int { return 2 } // Hoist and poison 'b' above useInt(y). // // CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison13testPoisonRefyyF" // CHECK: %b.debug = alloca %T12debug_poison1KC* // CHECK: %y.debug = alloca [[INT]] // CHECK: [[REF:%.*]] = call {{.*}} %T12debug_poison1KC* @"$s12debug_poison4getKAA1KCyF"() // CHECK: store %T12debug_poison1KC* [[REF]], %T12debug_poison1KC** %b.debug // CHECK: [[Y:%.*]] = call {{.*}} [[INT]] @"$s12debug_poison4use{{.*}}"(%T12debug_poison1KC* [[REF]]) // CHECK: call void {{.*}} @swift_release {{.*}} [[REF]] // CHECK: store %T12debug_poison1KC* inttoptr ([[INT]] 2176 to %T12debug_poison1KC*), %T12debug_poison1KC** %b.debug // CHECK: store [[INT]] [[Y]], [[INT]]* %y.debug // CHECK: call {{.*}} void @"$s12debug_poison6useIntyySiF"([[INT]] [[Y]]) public func testPoisonRef() { let b = getK() let y = useK(b) useInt(y) } // Hoist and poison 'b' above useInt(y). // // CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison21testPoisonOptionalRefyyF" // CHECK: %b.debug = alloca [[INT]] // CHECK: %y.debug = alloca [[INT]] // CHECK: [[REF:%.*]] = call {{.*}} [[INT]] @"$s12debug_poison12getOptionalKAA1KCSgyF"() // CHECK: store [[INT]] [[REF]], [[INT]]* %b.debug // CHECK: [[Y:%.*]] = call {{.*}} [[INT]] @"$s12debug_poison12useOptionalK{{.*}}"([[INT]] [[REF]]) // CHECK: call void @swift_release // CHECK: [[NIL:%.*]] = icmp eq [[INT]] [[REF]], 0 // CHECK: [[POISON:%.*]] = select i1 [[NIL]], [[INT]] [[REF]], [[INT]] 2176 // CHECK: store [[INT]] [[POISON]], [[INT]]* %b.debug // CHECK: store [[INT]] [[Y]], [[INT]]* %y.debug // CHECK: call {{.*}} void @"$s12debug_poison6useIntyySiF"([[INT]] [[Y]]) public func testPoisonOptionalRef() { let b: K? = getOptionalK() let y = useOptionalK(b) useInt(y) } // Hoist and poison 'b' above useNone. // // CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison21testPoisonExistentialyyF" // CHECK: %b.debug = alloca %T12debug_poison1PP // CHECK: [[INIT:%.*]] = call {{.*}} %T12debug_poison1DC* @"$s12debug_poison1DCACycfC"( // CHECK: [[REF:%.*]] = bitcast %T12debug_poison1DC* [[INIT]] to %[[REFTY:.*]]* // CHECK: [[GEP0:%.*]] = getelementptr inbounds %T12debug_poison1PP, %T12debug_poison1PP* %b.debug, i32 0, i32 0 // CHECK: store %[[REFTY]]* [[REF]], %[[REFTY]]** [[GEP0]] // CHECK: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s12debug_poison1DCAA1PAAWP", i32 0, i32 0), i8*** // CHECK: call %[[REFTY]]* @swift_{{unknownObjectRetain|retain}}(%[[REFTY]]* returned [[REF]]) // CHECK: store %[[REFTY]]* [[REF]], %[[REFTY]]** // CHECK: call {{.*}} void @"$s12debug_poison6useAnyyyypF"( // CHECK: call void @swift_{{unknownObjectRelease|release}}(%[[REFTY]]* [[REF]]) #1 // CHECK: [[GEP1:%.*]] = getelementptr inbounds %T12debug_poison1PP, %T12debug_poison1PP* %b.debug, i32 0, i32 0 // CHECK: store %[[REFTY]]* inttoptr ([[INT]] 2176 to %[[REFTY]]*), %[[REFTY]]** [[GEP1]] // CHECK: call {{.*}} void @"$s12debug_poison7useNoneyyF"() public func testPoisonExistential() { let b: P = D() useAny(b) useNone() } // Hoist and poison 'b' above useNone. // // CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison19testPoisonCompositeyyF"() // CHECK: %b.debug = alloca %T12debug_poison1Q_Xl // CHECK: [[INIT:%.*]] = call {{.*}} %T12debug_poison1EC* @"$s12debug_poison1ECACycfC"( // CHECK: [[REF:%.*]] = bitcast %T12debug_poison1EC* [[INIT]] to %[[REFTY]]* // CHECK: [[GEP0:%.*]] = getelementptr inbounds %T12debug_poison1Q_Xl, %T12debug_poison1Q_Xl* %b.debug, i32 0, i32 0 // CHECK: store %[[REFTY]]* [[REF]], %[[REFTY]]** [[GEP0]] // CHECK: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$s12debug_poison1ECAA1QAAWP", i32 0, i32 0), i8*** // CHECK: call %[[REFTY]]* @swift_{{unknownObjectRetain|retain}}(%[[REFTY]]* returned [[REF]]) // CHECK: store %[[REFTY]]* [[REF]], %[[REFTY]]** // CHECK: call {{.*}} void @"$s12debug_poison6useAnyyyypF"( // CHECK: call void @swift_{{unknownObjectRelease|release}}(%[[REFTY]]* [[REF]]) #1 // CHECK: [[GEP1:%.*]] = getelementptr inbounds %T12debug_poison1Q_Xl, %T12debug_poison1Q_Xl* %b.debug, i32 0, i32 0 // CHECK: store %[[REFTY]]* inttoptr ([[INT]] 2176 to %[[REFTY]]*), %[[REFTY]]** [[GEP1]] // CHECK: call {{.*}} void @"$s12debug_poison7useNoneyyF"() public func testPoisonComposite() { let b: Q & AnyObject = E() useAny(b) useNone() } // CopyPropagation hoists 'b' above useNone, but IRGen currently bails on emitting poison. // // CHECK-LABEL: define {{.*}}swiftcc void @"$s12debug_poison27testPoisonOptionalCompositeyyF"() // CHECK: %b.debug = alloca %T12debug_poison1Q_XlSg // CHECK: [[INIT:%.*]] = call {{.*}} %T12debug_poison1EC* @"$s12debug_poison1ECACycfC"( // CHECK: [[REF0:%.*]] = bitcast %T12debug_poison1EC* [[INIT]] to %[[REFTY]]* // CHECK: [[REFINT0:%.*]] = ptrtoint %[[REFTY]]* [[REF0]] to [[INT]] // CHECK: [[SHADOW0:%.*]] = bitcast %T12debug_poison1Q_XlSg* %b.debug to { [[INT]], [[INT]] }* // CHECK: [[GEP0:%.*]] = getelementptr inbounds {{.*}} [[SHADOW0]], i32 0, i32 0 // CHECK: store [[INT]] [[REFINT0]], [[INT]]* [[GEP0]] // CHECK: store [[INT]] ptrtoint ([1 x i8*]* @"$s12debug_poison1ECAA1QAAWP" to [[INT]]), // CHECK: [[REF1:%.*]] = inttoptr [[INT]] [[REFINT0]] to %[[REFTY]]* // CHECK: call %[[REFTY]]* @swift_{{unknownObjectRetain|retain}}(%[[REFTY]]* returned [[REF1]]) // CHECK: icmp eq [[INT]] [[REFINT0]], 0 // CHECK: [[PHI:%.*]] = phi %[[REFTY]]* // CHECK: call void @swift_{{unknownObjectRelease|release}}(%[[REFTY]]* // CHECK: store %[[REFTY]]* [[PHI]], %[[REFTY]]** // CHECK: call {{.*}} void @"$s12debug_poison14useOptionalAnyyyypSgF"( // // Currently no poison store here. // CHECK-NOT: store // CHECK: call {{.*}} void @"$s12debug_poison7useNoneyyF"() public func testPoisonOptionalComposite() { let b: Optional<Q & AnyObject> = E() useOptionalAny(b) useNone() }
45.135714
127
0.623042
f42b1f82f1ccffd8cb8e44b2d5a07e6ea08c4f61
391
// // BookDetailWorker.swift // BookFinder // // Created by CNOO on 2021/09/29. // Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit class BookDetailWorker { func doSomeWork() { } }
18.619048
67
0.703325
9bef13c66f5c68ec49d588f48f87a5e563688988
2,666
// Copyright 2020-2021 Tokamak contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import TokamakShim struct Star: Shape { func path(in rect: CGRect) -> Path { Path { path in path.move(to: .init(x: 40, y: 0)) path.addLine(to: .init(x: 20, y: 76)) path.addLine(to: .init(x: 80, y: 30.4)) path.addLine(to: .init(x: 0, y: 30.4)) path.addLine(to: .init(x: 64, y: 76)) path.addLine(to: .init(x: 40, y: 0)) } } } struct PathDemo: View { var body: some View { VStack { HStack { Star() .fill(Color(red: 1, green: 0.75, blue: 0.1, opacity: 1)) Circle() .stroke(Color.blue) .frame(width: 80, height: 80, alignment: .center) } Path { path in path.addRect(.init(origin: .zero, size: .init(width: 20, height: 20))) path.addEllipse(in: .init( origin: .init(x: 25, y: 0), size: .init(width: 20, height: 20) )) path.addRoundedRect( in: .init(origin: .init(x: 50, y: 0), size: .init(width: 20, height: 20)), cornerSize: .init(width: 4, height: 4) ) path.addArc( center: .init(x: 85, y: 10), radius: 10, startAngle: .degrees(90), endAngle: .degrees(180), clockwise: true ) } .stroke(Color(red: 1, green: 0.75, blue: 0.1, opacity: 1), lineWidth: 4) .padding(.vertical) HStack { Circle() .frame(width: 25, height: 25) Rectangle() .frame(width: 25, height: 25) Capsule() .frame(width: 50, height: 25) } .foregroundColor(Color.blue) if #available(macOS 12.0, iOS 15, *) { #if compiler(>=5.5) || os(WASI) // Xcode 13 required for `containerShape`. ZStack { ContainerRelativeShape() .fill(Color.blue) .frame(width: 100, height: 100, alignment: .center) ContainerRelativeShape() .fill(Color.green) .frame(width: 50, height: 50) } .containerShape(Circle()) #endif } } } }
31
84
0.564141
33a114d93b081959d49ef091c770c58a9b1bd0af
913
// // PaymentSettings.swift // Alamofire // // Created by FEDAR TRUKHAN on 8/25/19. // public struct BGPaymentSettings { public var endpoint: String public var isTestMode: Bool public var locale: String let securedBy = "beGateway" public var supportedCardTypes: [BGCardType] public var styleSettings: BGStyleSettings public var cardViewColorsSettings: BGCardViewColorsSettings public var image: UIImage? public var returnURL: String public var notificationURL: String public static var standart: BGPaymentSettings { return BGPaymentSettings( endpoint: "", isTestMode: true, locale: "en", supportedCardTypes: [], styleSettings: BGStyleSettings.standart, cardViewColorsSettings: BGCardViewColorsSettings.standart, returnURL: "", notificationURL: "") } }
28.53125
70
0.66046
9baffe7bd4c4997e58d501ae71ec9f827f558c8c
460
protocol CommingSoonViewProtocol: ControllerBackedProtocol {} protocol CommingSoonPresenterProtocol: class { func setup() func activateDevStatus() func activateRoadmap() } protocol CommingSoonInteractorInputProtocol: class {} protocol CommingSoonInteractorOutputProtocol: class {} protocol CommingSoonWireframeProtocol: WebPresentable {} protocol CommingSoonViewFactoryProtocol: class { static func createView() -> CommingSoonViewProtocol? }
25.555556
61
0.817391
67cef6bddcb0d2e741995fe0e6636c8fe9429230
957
// // Wireframe.swift // SVNewsletter // // Created by Sam on 21/11/2016. // Copyright © 2016 Semyon Vyatkin. All rights reserved. // import Foundation import UIKit protocol WireframeProtocol: class { func showRootViewController(_ viewController: UIViewController, in window: UIWindow?) func viewControllerWith(name: String) -> UIViewController } class Wireframe: WireframeProtocol { func showRootViewController(_ viewController: UIViewController, in window: UIWindow?) { let navigationController = window?.rootViewController as! UINavigationController navigationController.viewControllers = [viewController] } // MARK: - Wireframe Methods func viewControllerWith(name: String) -> UIViewController { let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) let controller = storyboard.instantiateViewController(withIdentifier: name) return controller } }
29.90625
91
0.723093
390708a34238496177f98bfae08f38e321398262
977
// // ItemsSettings.swift // GildedRoseKata // // Created by Shaher Kassam on 08/03/2019. // Copyright © 2019 Shaher. All rights reserved. // import Foundation enum ItemName: String { //Normal Items case vest = "+5 Dexterity Vest" case elixir = "Elixir of the Mongoose" //Inversed Items case brie = "Aged Brie" case pass = "Backstage passes to a TAFKAL80ETC concert ipso illium Backstage passes to a TAFKAL80ETC concert ipso illiumBackstage passes to a TAFKAL80ETC concert ipso illiumBackstage passes to a TAFKAL80ETC concert ipso illium Backstage passes to a TAFKAL80ETC concert ipso illiumBackstage passes to a TAFKAL80ETC concert ipso illiumBackstage passes to a TAFKAL80ETC concert " //Legendary Items case sulfuras = "Sulfuras, Hand of Ragnaros" //Conjured Items case cake = "Conjured Mana Cake" } enum QualitySettings: Int { case min = 0 case max = 50 case double = 10 case triple = 5 }
28.735294
381
0.707267
abedc94d497634b4e88bbf3983016eaea00cf711
816
/** * https://leetcode.com/problems/unique-paths-ii/ * * */ class Solution { func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int { let n = obstacleGrid.count guard let m = obstacleGrid.first?.count else { return 0 } var mark = Array(repeating: Array(repeating: 0, count: m), count: n) // It's important to check if the start position is valid or not. mark[0][0] = 1 - obstacleGrid[0][0] for x in 0 ..< n { for y in 0 ..< m { if obstacleGrid[x][y] == 1 { continue } if x > 0 { mark[x][y] += mark[x - 1][y] } if y > 0 { mark[x][y] += mark[x][y - 1] } } } return mark[n - 1][m - 1] } }
31.384615
76
0.449755
d7f44dde9ba6461364b09b8627df6a1925b96c83
2,660
// // DetailReducer.swift // // // Created by Markus Pfeifer on 05.05.21. // import Foundation public protocol DetailReducerProtocol : ReducerProtocol { associatedtype State associatedtype Detail associatedtype Action var keyPath : WritableKeyPath<State, Detail> {get} func apply(_ action: Action, to detail: inout Detail) } public extension DetailReducerProtocol { @inlinable func apply(_ action: Action, to state: inout State) { apply(action, to: &state[keyPath: keyPath]) } } public protocol DetailReducerWrapper : ErasedReducer { associatedtype Body : ErasedReducer var keyPath : WritableKeyPath<State, Body.State> {get} var body : Body {get} } public extension DetailReducerWrapper { @inlinable func applyErased<Action : ActionProtocol>(_ action: Action, to state: inout State) { body.applyErased(action, to: &state[keyPath: keyPath]) } func acceptsAction<Action : ActionProtocol>(_ action: Action) -> Bool { body.acceptsAction(action) } } public struct DetailReducer<State, Reducer : ErasedReducer> : DetailReducerWrapper { public let keyPath: WritableKeyPath<State, Reducer.State> public let body : Reducer @inlinable public init(_ detail: WritableKeyPath<State, Reducer.State>, reducer: Reducer) { self.keyPath = detail self.body = reducer } @inlinable public init(_ detail: WritableKeyPath<State, Reducer.State>, build: @escaping () -> Reducer) { self.keyPath = detail self.body = build() } @inlinable public init<Detail, Action : ActionProtocol>(_ detail: WritableKeyPath<State, Detail>, closure: @escaping (Action, inout Detail) -> Void) where Reducer == ClosureReducer<Detail, Action> { self.keyPath = detail self.body = ClosureReducer(closure) } } public extension ErasedReducer { @inlinable func bind<Root>(to property: WritableKeyPath<Root, State>) -> DetailReducer<Root, Self> { DetailReducer(property, reducer: self) } } public extension Reducers.Native { func detailReducer<State, Detail, Action : ActionProtocol>(_ detail: WritableKeyPath<State, Detail>, _ closure: @escaping (Action, inout Detail) -> Void) -> DetailReducer<State, ClosureReducer<Detail, Action>> { DetailReducer(detail, closure: closure) } }
24.859813
115
0.616165
03c3671862899ac3d05c97bfee63089c206d9889
8,999
// Copyright 2018 Vincent Duvert. // Distributed under the terms of the MIT License. import XCTest import Foundation final class SwitchControllerLogger: SwitchUserInterfaceProtocol, AudioDeviceSystemInterface { var uids = [String]() var displayed = [String]() init() { } init(observer: AudioDeviceObserver, queue: DispatchQueue) { } func deactivate() { fatalError("deactivate called during test") } func currentOutputUid() -> String { fatalError("currentOutputUid called during test") } func display(text: String) { displayed.append(text) } func switchTo(uid: String) { uids.append(uid) } } class AudioDeviceSwitchControllerTest: XCTestCase { typealias DInfo = AudioDeviceListManager.DeviceInfo func testSwitchNoDevices() { let logger = SwitchControllerLogger() let controller = AudioDeviceSwitchController(systemInterface: logger, userInterface: logger) controller.switchToNextDevice(in: []) XCTAssertEqual(logger.displayed, ["<No Output>"]) XCTAssertEqual(logger.uids, []) } func testSwitchAllDevicesUnavailable() { let devices = [ DInfo(uid: "a", connected: false, name: "", title: "Device A", enabled: true), DInfo(uid: "b", connected: true, name: "B", title: "", enabled: false), DInfo(uid: "c", connected: false, name: "", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "", enabled: false), ] let logger = SwitchControllerLogger() let controller = AudioDeviceSwitchController(systemInterface: logger, userInterface: logger) controller.switchToNextDevice(in: devices) XCTAssertEqual(logger.displayed, ["<No Output>"]) XCTAssertEqual(logger.uids, []) } func testSwitchOneDeviceNoInitialDevice() { let devices = [ DInfo(uid: "a", connected: true, name: "A", title: "Device A", enabled: true), DInfo(uid: "b", connected: true, name: "B", title: "", enabled: false), DInfo(uid: "c", connected: false, name: "", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "", enabled: false), ] let logger = SwitchControllerLogger() let controller = AudioDeviceSwitchController(systemInterface: logger, userInterface: logger) controller.switchToNextDevice(in: devices) XCTAssertEqual(logger.displayed, ["Device A"]) XCTAssertEqual(logger.uids, ["a"]) controller.switchToNextDevice(in: devices) XCTAssertEqual(logger.displayed, ["Device A", "Device A"]) XCTAssertEqual(logger.uids, ["a", "a"]) } func testSwitchOneDeviceDisabledInitialDevice() { let devices = [ DInfo(uid: "a", connected: true, name: "A", title: "Device A", enabled: true), DInfo(uid: "b", connected: true, name: "B", title: "", enabled: false), DInfo(uid: "c", connected: false, name: "", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "", enabled: false), ] let logger = SwitchControllerLogger() let controller = AudioDeviceSwitchController(systemInterface: logger, userInterface: logger) controller.switchToNextDevice(in: devices, afterUid: "b") XCTAssertEqual(logger.displayed, ["Device A"]) XCTAssertEqual(logger.uids, ["a"]) controller.switchToNextDevice(in: devices, afterUid: "a") XCTAssertEqual(logger.displayed, ["Device A", "Device A"]) XCTAssertEqual(logger.uids, ["a", "a"]) } func testSwitchTwoDevices() { let devices = [ DInfo(uid: "a", connected: true, name: "A", title: "Device A", enabled: true), DInfo(uid: "b", connected: true, name: "B", title: "", enabled: false), DInfo(uid: "c", connected: false, name: "", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "", enabled: true), // No title so the name should be used when switching ] let logger = SwitchControllerLogger() let controller = AudioDeviceSwitchController(systemInterface: logger, userInterface: logger) controller.switchToNextDevice(in: devices, afterUid: "d") XCTAssertEqual(logger.displayed, ["Device A"]) XCTAssertEqual(logger.uids, ["a"]) controller.switchToNextDevice(in: devices, afterUid: "a") XCTAssertEqual(logger.displayed, ["Device A", "D"]) XCTAssertEqual(logger.uids, ["a", "d"]) } func testSwitchDisablingCurrentDevice() { let devicesInit = [ DInfo(uid: "a", connected: true, name: "A", title: "Device A", enabled: true), DInfo(uid: "b", connected: true, name: "B", title: "Device B", enabled: true), DInfo(uid: "c", connected: true, name: "C", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "Device D", enabled: true), ] let devicesBDisabled = [ DInfo(uid: "a", connected: true, name: "A", title: "Device A", enabled: true), DInfo(uid: "b", connected: true, name: "B", title: "Device B", enabled: false), DInfo(uid: "c", connected: true, name: "C", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "Device D", enabled: true), ] let logger = SwitchControllerLogger() let controller = AudioDeviceSwitchController(systemInterface: logger, userInterface: logger) controller.switchToNextDevice(in: devicesInit, afterUid: "a") XCTAssertEqual(logger.displayed, ["Device B"]) XCTAssertEqual(logger.uids, ["b"]) controller.switchToNextDevice(in: devicesBDisabled, afterUid: "b") XCTAssertEqual(logger.displayed, ["Device B", "Device C"]) XCTAssertEqual(logger.uids, ["b", "c"]) } func testSwitchDisconnectingCurrentDevice() { let devicesInit = [ DInfo(uid: "a", connected: true, name: "A", title: "Device A", enabled: true), DInfo(uid: "b", connected: true, name: "B", title: "Device B", enabled: true), DInfo(uid: "c", connected: true, name: "C", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "Device D", enabled: true), ] let devicesBDisconnected = [ DInfo(uid: "a", connected: true, name: "A", title: "Device A", enabled: true), DInfo(uid: "b", connected: false, name: "B", title: "Device B", enabled: true), DInfo(uid: "c", connected: true, name: "C", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "Device D", enabled: true), ] let logger = SwitchControllerLogger() let controller = AudioDeviceSwitchController(systemInterface: logger, userInterface: logger) controller.switchToNextDevice(in: devicesInit, afterUid: "a") XCTAssertEqual(logger.displayed, ["Device B"]) XCTAssertEqual(logger.uids, ["b"]) controller.switchToNextDevice(in: devicesBDisconnected, afterUid: "b") XCTAssertEqual(logger.displayed, ["Device B", "Device C"]) XCTAssertEqual(logger.uids, ["b", "c"]) } func testSwitchRemovingCurrentDevice() { // This should not happen, but the controller should not crash/infinite loop in that case let devicesInit = [ DInfo(uid: "a", connected: true, name: "A", title: "Device A", enabled: true), DInfo(uid: "b", connected: true, name: "B", title: "Device B", enabled: true), DInfo(uid: "c", connected: true, name: "C", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "Device D", enabled: true), ] let devicesBRemoved = [ DInfo(uid: "a", connected: true, name: "A", title: "Device A", enabled: true), DInfo(uid: "c", connected: true, name: "C", title: "Device C", enabled: true), DInfo(uid: "d", connected: true, name: "D", title: "Device D", enabled: true), ] let logger = SwitchControllerLogger() let controller = AudioDeviceSwitchController(systemInterface: logger, userInterface: logger) controller.switchToNextDevice(in: devicesInit, afterUid: "a") XCTAssertEqual(logger.displayed, ["Device B"]) XCTAssertEqual(logger.uids, ["b"]) controller.switchToNextDevice(in: devicesBRemoved, afterUid: "b") XCTAssertEqual(logger.displayed, ["Device B", "Device A"]) XCTAssertEqual(logger.uids, ["b", "a"]) } }
46.148718
136
0.600622
20ef6a12a9230601a77770774d20b6f67ad1e1b2
591
// // IntTokenGenerator.swift // Ogma // // Created by Mathias Quintero on 4/23/19. // import Foundation public struct IntLiteralTokenGenerator: SingleGroupRegexTokenGenerator { public typealias Token = Int public let pattern: String = "-?\\d+(e\\d+)?\\b" let numberFormatter = NumberFormatter() public init() { } public func token(from matched: String) throws -> Token? { guard let value = numberFormatter.number(from: matched)?.intValue else { throw LexerError.invalidLiteral(matched, type: Int.self) } return value } }
22.730769
80
0.658206
185d74731e73ba39c71bdbc551907f78804cc63d
1,541
// // StringUtils.swift // JsonSerializer // // Created by Fuji Goro on 2014/09/15. // Copyright (c) 2014 Fuji Goro. All rights reserved. // let unescapeMapping: [UnicodeScalar: UnicodeScalar] = [ "t": "\t", "r": "\r", "n": "\n", ] let escapeMapping: [Character : String] = [ "\r": "\\r", "\n": "\\n", "\t": "\\t", "\\": "\\\\", "\"": "\\\"", "\u{2028}": "\\u2028", // LINE SEPARATOR "\u{2029}": "\\u2029", // PARAGRAPH SEPARATOR // XXX: countElements("\r\n") is 1 in Swift 1.0 "\r\n": "\\r\\n", ] let hexMapping: [UnicodeScalar : UInt32] = [ "0": 0x0, "1": 0x1, "2": 0x2, "3": 0x3, "4": 0x4, "5": 0x5, "6": 0x6, "7": 0x7, "8": 0x8, "9": 0x9, "a": 0xA, "A": 0xA, "b": 0xB, "B": 0xB, "c": 0xC, "C": 0xC, "d": 0xD, "D": 0xD, "e": 0xE, "E": 0xE, "f": 0xF, "F": 0xF, ] let digitMapping: [UnicodeScalar:Int] = [ "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, ] extension String { public var escapedJsonString: String { let mapped = characters .map { escapeMapping[$0] ?? String($0) } .joinWithSeparator("") return "\"" + mapped + "\"" } } public func escapeAsJsonString(source : String) -> String { return source.escapedJsonString } func digitToInt(b: UInt8) -> Int? { return digitMapping[UnicodeScalar(b)] } func hexToDigit(b: UInt8) -> UInt32? { return hexMapping[UnicodeScalar(b)] }
18.792683
59
0.482803
871033340ce42d8ddc072e8ca8d25427fd17f7b9
2,576
// // UIResponder.swift // SwiftEasyKit // // Created by ctslin on 8/2/16. // Copyright © 2016 airfont. All rights reserved. // import Foundation import Alamofire import UserNotifications extension UIResponder { open func parentViewController() -> UIViewController? { if self.next is UIViewController { return self.next as? UIViewController } else { if self.next != nil { return (self.next!).parentViewController() } else {return nil} } } // // @objc open func bootFrom(_ vc: UIViewController) -> UIWindow? { // let window: UIWindow? = UIWindow(frame: UIScreen.main.bounds) // window!.backgroundColor = K.Color.body // window!.rootViewController = vc // window!.makeKeyAndVisible() // return window! // } open func pushServerAppID() -> String { return "" } open func getDeviceName() -> String { return UIDevice.current.name } open func application(_ application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings){ _logForAnyMode() application.registerForRemoteNotifications() } open func sendTokenToPushServer(_ token: String, name: String, enabled: Bool = true, success: @escaping (_ response: DataResponse<Any>) -> () = {_ in }) { PushServer.subscribeToken(appid: K.Api.appID, name: name, token: token, enabled: enabled, success: success) } open func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { _logForAnyMode() } @nonobjc open func applicationWillResignActive(_ application: UIApplication) { _logForAnyMode() } @objc open func applicationDidEnterBackground(_ application: UIApplication) { _logForAnyMode("work!") } @objc open func applicationWillEnterForeground(_ application: UIApplication) { _logForAnyMode() } @objc open func applicationDidBecomeActive(_ application: UIApplication) { _logForAnyMode() } @objc open func applicationWillTerminate(_ application: UIApplication) { _logForAnyMode() } public func getDeviceTokenString(_ deviceToken: Data) -> String { _logForAnyMode("work!") return deviceToken.map { String(format: "%02.2hhx", $0) }.joined() // let characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" ) // let deviceTokenString: String = ( deviceToken.description as NSString ) // .stringByTrimmingCharactersInSet( characterSet ) // .stringByReplacingOccurrencesOfString( " ", withString: "" ) as String // return deviceTokenString } }
31.802469
156
0.715839
464a88b6f56b22dc0ee613e428634d277a29c335
5,809
// // OneShotDownload.swift // RSWeb // // Created by Brent Simmons on 8/27/16. // Copyright © 2016 Ranchero Software, LLC. All rights reserved. // import Foundation // Main thread only. public typealias OneShotDownloadCallback = (Data?, URLResponse?, Error?) -> Swift.Void private final class OneShotDownloadManager { private let urlSession: URLSession fileprivate static let shared = OneShotDownloadManager() public init() { let sessionConfiguration = URLSessionConfiguration.ephemeral sessionConfiguration.requestCachePolicy = .reloadIgnoringLocalCacheData sessionConfiguration.httpShouldSetCookies = false sessionConfiguration.httpCookieAcceptPolicy = .never sessionConfiguration.httpMaximumConnectionsPerHost = 2 sessionConfiguration.httpCookieStorage = nil sessionConfiguration.urlCache = nil sessionConfiguration.timeoutIntervalForRequest = 30 if let userAgentHeaders = UserAgent.headers() { sessionConfiguration.httpAdditionalHeaders = userAgentHeaders } urlSession = URLSession(configuration: sessionConfiguration) } deinit { urlSession.invalidateAndCancel() } public func download(_ url: URL, _ completion: @escaping OneShotDownloadCallback) { let task = urlSession.dataTask(with: url) { (data, response, error) in DispatchQueue.main.async() { completion(data, response, error) } } task.resume() } public func download(_ urlRequest: URLRequest, _ completion: @escaping OneShotDownloadCallback) { let task = urlSession.dataTask(with: urlRequest) { (data, response, error) in DispatchQueue.main.async() { completion(data, response, error) } } task.resume() } } // Call one of these. It’s easier than referring to OneShotDownloadManager. // callback is called on the main queue. public func download(_ url: URL, _ completion: @escaping OneShotDownloadCallback) { precondition(Thread.isMainThread) OneShotDownloadManager.shared.download(url, completion) } public func download(_ urlRequest: URLRequest, _ completion: @escaping OneShotDownloadCallback) { precondition(Thread.isMainThread) OneShotDownloadManager.shared.download(urlRequest, completion) } // MARK: - Downloading using a cache private struct WebCacheRecord { let url: URL let dateDownloaded: Date let data: Data let response: URLResponse } private final class WebCache { private var cache = [URL: WebCacheRecord]() func cleanup(_ cleanupInterval: TimeInterval) { let cutoffDate = Date(timeInterval: -cleanupInterval, since: Date()) cache.keys.forEach { (key) in let cacheRecord = self[key]! if shouldDelete(cacheRecord, cutoffDate) { cache[key] = nil } } } private func shouldDelete(_ cacheRecord: WebCacheRecord, _ cutoffDate: Date) -> Bool { return cacheRecord.dateDownloaded < cutoffDate } subscript(_ url: URL) -> WebCacheRecord? { get { return cache[url] } set { if let cacheRecord = newValue { cache[url] = cacheRecord } else { cache[url] = nil } } } } // URLSessionConfiguration has a cache policy. // But we don’t know how it works, and the unimplemented parts spook us a bit. // So we use a cache that works exactly as we want it to work. // It also makes sure we don’t have multiple requests for the same URL at the same time. private struct CallbackRecord { let url: URL let completion: OneShotDownloadCallback } private final class DownloadWithCacheManager { static let shared = DownloadWithCacheManager() private var cache = WebCache() private static let timeToLive: TimeInterval = 10 * 60 // 10 minutes private static let cleanupInterval: TimeInterval = 5 * 60 // clean up the cache at most every 5 minutes private var lastCleanupDate = Date() private var pendingCallbacks = [CallbackRecord]() private var urlsInProgress = Set<URL>() func download(_ url: URL, _ completion: @escaping OneShotDownloadCallback, forceRedownload: Bool = false) { if lastCleanupDate.timeIntervalSinceNow < -DownloadWithCacheManager.cleanupInterval { lastCleanupDate = Date() cache.cleanup(DownloadWithCacheManager.timeToLive) } if !forceRedownload { let cacheRecord: WebCacheRecord? = cache[url] if let cacheRecord = cacheRecord { completion(cacheRecord.data, cacheRecord.response, nil) return } } let callbackRecord = CallbackRecord(url: url, completion: completion) pendingCallbacks.append(callbackRecord) if urlsInProgress.contains(url) { completion(nil, nil, nil) return // It will get called later. } urlsInProgress.insert(url) OneShotDownloadManager.shared.download(url) { (data, response, error) in self.urlsInProgress.remove(url) if let data = data, let response = response, response.statusIsOK, error == nil { let cacheRecord = WebCacheRecord(url: url, dateDownloaded: Date(), data: data, response: response) self.cache[url] = cacheRecord } var callbackCount = 0 self.pendingCallbacks.forEach{ (callbackRecord) in if url == callbackRecord.url { callbackRecord.completion(data, response, error) callbackCount += 1 } } self.pendingCallbacks.removeAll(where: { (callbackRecord) -> Bool in return callbackRecord.url == url }) } } } public func downloadUsingCache(_ url: URL, _ completion: @escaping OneShotDownloadCallback) { precondition(Thread.isMainThread) DownloadWithCacheManager.shared.download(url, completion) } public func downloadAddingToCache(_ url: URL, _ completion: @escaping OneShotDownloadCallback) { precondition(Thread.isMainThread) DownloadWithCacheManager.shared.download(url, completion, forceRedownload: true) }
29.943299
108
0.721983
e2910ef40f300b73b91b9d53e7ce1934a712a76d
5,603
// // InputObjectGenerationTests.swift // ApolloCodegenTests // // Created by Ellen Shapiro on 4/1/20. // Copyright © 2020 Apollo GraphQL. All rights reserved. // import XCTest import ApolloCodegenTestSupport @testable import ApolloCodegenLib class InputObjectGenerationTests: XCTestCase { private func colorInput(named name: String) -> ASTTypeUsed { let red = ASTTypeUsed.Field(name: "red", typeNode: .nonNullNamed("Int"), description: nil) let green = ASTTypeUsed.Field(name: "green", typeNode: .nonNullNamed("Int"), description: nil) let blue = ASTTypeUsed.Field(name: "blue", typeNode: .nonNullNamed("Int"), description: nil) let colorInput = ASTTypeUsed(kind: .InputObjectType, name: name, description: "The input object sent when passing in a color", values: nil, fields: [ red, green, blue, ]) return colorInput } private func reviewInput(named name: String) -> ASTTypeUsed { let stars = ASTTypeUsed.Field(name: "stars", typeNode: .nonNullNamed("Int"), description: "0-5 stars") let commentary = ASTTypeUsed.Field(name: "commentary", typeNode: .named("String"), description: "Comment about the movie, optional") let favoriteColor = ASTTypeUsed.Field(name: "favoriteColor", typeNode: .named("ColorInput"), description: "Favorite color, optional") let reviewInput = ASTTypeUsed(kind: .InputObjectType, name: name, description: "The input object sent when someone is creating a new review", values: nil, fields: [ stars, commentary, favoriteColor, ]) return reviewInput } func testGeneratingInputObjectWithNoOptionalProperties() { do { let output = try InputObjectGenerator().run(typeUsed: self.colorInput(named: "ColorInput"), options: CodegenTestHelper.dummyOptions()) let expectedFileURL = CodegenTestHelper.sourceRootURL() .appendingPathComponent("Tests") .appendingPathComponent("ApolloCodegenTests") .appendingPathComponent("ExpectedColorInput.swift") LineByLineComparison.between(received: output, expectedFileURL: expectedFileURL, trimImports: true) } catch { CodegenTestHelper.handleFileLoadError(error) } } func testGeneratingInputWithNoOptionalPropertiesAndNoModifier() { let dummyURL = CodegenTestHelper.apolloFolderURL() let options = ApolloCodegenOptions(modifier: .none, outputFormat: .singleFile(atFileURL: dummyURL), urlToSchemaFile: dummyURL) do { let output = try InputObjectGenerator().run(typeUsed: self.colorInput(named: "ColorInputNoModifier"), options: options) let expectedFileURL = CodegenTestHelper.sourceRootURL() .appendingPathComponent("Tests") .appendingPathComponent("ApolloCodegenTests") .appendingPathComponent("ExpectedColorInputNoModifier.swift") LineByLineComparison.between(received: output, expectedFileURL: expectedFileURL, trimImports: true) } catch { CodegenTestHelper.handleFileLoadError(error) } } func testGeneratingInputObjectWithOptionalProperties() { do { let output = try InputObjectGenerator().run(typeUsed: self.reviewInput(named: "ReviewInput"), options: CodegenTestHelper.dummyOptions()) let expectedFileURL = CodegenTestHelper.sourceRootURL() .appendingPathComponent("Tests") .appendingPathComponent("ApolloCodegenTests") .appendingPathComponent("ExpectedReviewInput.swift") LineByLineComparison.between(received: output, expectedFileURL: expectedFileURL, trimImports: true) } catch { CodegenTestHelper.handleFileLoadError(error) } } func testGeneratingInputObjectWithOptionalPropertiesAndNoModifier() { do { let output = try InputObjectGenerator().run(typeUsed: self.reviewInput(named: "ReviewInputNoModifier"), options: CodegenTestHelper.dummyOptionsNoModifier()) let expectedFileURL = CodegenTestHelper.sourceRootURL() .appendingPathComponent("Tests") .appendingPathComponent("ApolloCodegenTests") .appendingPathComponent("ExpectedReviewInputNoModifier.swift") LineByLineComparison.between(received: output, expectedFileURL: expectedFileURL, trimImports: true) } catch { CodegenTestHelper.handleFileLoadError(error) } } }
41.813433
162
0.560593
90f86b2f36a1f7feea2393a027b1d6ad1270ab22
5,390
// // HhDataParser.swift // task2_generic_api_client // // Created by Roman Brazhnikov on 30.06.2018. // Copyright © 2018 Roman Brazhnikov. All rights reserved. // import Foundation class HhDataParser: DataParserProtocol { let dateFormatter: DateFormatter = { let df = DateFormatter() df.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return df }() func fetchVacancyListFrom(JSON json: Data) -> VacanciesRequestResult { do{ let jsonObject = try JSONSerialization.jsonObject(with: json, options: []) print(jsonObject) // // parsing JSON for vacancies // guard let jsonDictionary = jsonObject as? [AnyHashable:Any], let vacancies = jsonDictionary["items"] as? [[String:Any]] else { return .error(NSError(domain: "Fail", code: 1, userInfo: nil)) } var vacancyList = [Vacancy]() // // Populating list of Vacancies TODO: Total convertion // for item in vacancies { // title let title = item["name"] as? String // url let url = item["url"] as? String // // date // let published_at = item["published_at"] as? String let date = dateFormatter.date(from: published_at!) // // description // let snippet = item["snippet"] as? [String:Any] var requirement = "" if let req = snippet!["requirement"] as? String { requirement = req } var responsibility = "" if let res = snippet!["responsibility"] as? String { responsibility = res } let description = "\(requirement)\n\nResponsibility:\n\(responsibility)" // // salary // var salary_from: Decimal? var salary_to: Decimal? if let salary = item["salary"] as? [String:Any] { // to if let s_to = salary["to"] as? Double { salary_to = Decimal(s_to) } // from if let s_from = salary["from"] as? Double { salary_from = Decimal(s_from) } } // // EMPLOYER // var actualEmployer = Employer.genericEmployer() if let employer = item["employer"] as? [String:Any] { let employerName = employer["name"] as? String let employerUrl = employer["url"] as? String let employerLogos = employer["logo_urls"] as? [String: Any] guard let e_name = employerName, let e_url = employerUrl else { return .error(NSError(domain: "Fail", code: 1, userInfo: nil)) } var logo_url = "" if let logos = employerLogos { let logo_90 = logos["90"] as! String logo_url = logo_90 } actualEmployer = Employer(Name: e_name, Description: e_url, LogoUrl: logo_url) } // // Building vacancy // let vacancy = Vacancy(title: title!, description: description, date: date!, salary_from: salary_from, salary_to: salary_to, employer: actualEmployer, experience: "", url: url!) vacancyList.append(vacancy) } return .success(vacancyList) } catch { return .error(error) } } func fetchEmployerFrom(JSON json: Data) -> EmployerRequestResult { do{ let jsonObject = try JSONSerialization.jsonObject(with: json, options: []) print(jsonObject) // // parsing JSON for employer // guard let jsonDictionary = jsonObject as? [AnyHashable:Any], let name = jsonDictionary["name"] as? String, let description = jsonDictionary["description"] as? String else { return .error(NSError(domain: "Fail", code: 1, userInfo: nil)) } let employer = Employer(Name: name, Description: description, LogoUrl: nil) return .success(employer) } catch { return .error(error) } } }
34.551282
98
0.418924
91cc27809cb478a000a4f27a4b540ff2d349c4b6
1,244
// // PeopleAndPetAccurate.swift // FritzVision // // Created by Christopher Kelly on 9/20/19. // Copyright © 2019 Fritz Labs Incorporated. All rights reserved. // import Foundation /// Image segmentation model to detect people and pets. @available(iOS 11.0, *) @objc(FritzVisionPeopleAndPetSegmentationModelAccurate) public final class FritzVisionPeopleAndPetSegmentationModelAccurate: FritzVisionPeopleAndPetSegmentationPredictor, DownloadableModel { @objc public static let modelConfig = FritzModelConfiguration( identifier: "996011d930ad4a0791f02349f0971039", version: 2, pinnedVersion: 2 ) @objc public static var managedModel: FritzManagedModel { return modelConfig.buildManagedModel() } @objc public static var wifiRequiredForModelDownload: Bool = _wifiRequiredForModelDownload /// Fetch model. Downloads model if model has not been downloaded before. /// /// - Parameter completionHandler: CompletionHandler called after fetchModel request finishes. @objc(fetchModelWithCompletionHandler:) public static func fetchModel( completionHandler: @escaping (FritzVisionPeopleAndPetSegmentationModelAccurate?, Error?) -> Void ) { _fetchModel(completionHandler: completionHandler) } }
31.1
114
0.782154
ab672cdd33a7e0ae411b55811e05e22a5e33528b
2,359
// Tests/SwiftProtobufTests/Test_BinaryDelimited.swift - Delimited message tests // // Copyright (c) 2014 - 2017 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- import Foundation import XCTest import SwiftProtobuf class Test_BinaryDelimited: XCTestCase { func testEverything() { // Don't need to test encode/decode since there are plenty of tests specific to that, // just test the delimited behaviors. let stream1 = OutputStream.toMemory() stream1.open() let msg1 = ProtobufUnittest_TestAllTypes.with { $0.optionalBool = true $0.optionalInt32 = 123 $0.optionalInt64 = 123456789 $0.optionalGroup.a = 456 $0.optionalNestedEnum = .baz $0.repeatedString.append("wee") $0.repeatedFloat.append(1.23) } XCTAssertNoThrow(try BinaryDelimited.serialize(message: msg1, to: stream1)) let msg2 = ProtobufUnittest_TestPackedTypes.with { $0.packedBool.append(true) $0.packedInt32.append(234) $0.packedDouble.append(345.67) } XCTAssertNoThrow(try BinaryDelimited.serialize(message: msg2, to: stream1)) stream1.close() // See https://bugs.swift.org/browse/SR-5404 let nsData = stream1.property(forKey: .dataWrittenToMemoryStreamKey) as! NSData let data = Data(referencing: nsData) let stream2 = InputStream(data: data) stream2.open() var msg1a = ProtobufUnittest_TestAllTypes() XCTAssertNoThrow(try BinaryDelimited.merge(into: &msg1a, from: stream2)) XCTAssertEqual(msg1, msg1a) do { let msg2a = try BinaryDelimited.parse( messageType: ProtobufUnittest_TestPackedTypes.self, from: stream2) XCTAssertEqual(msg2, msg2a) } catch let e { XCTFail("Unexpected failure: \(e)") } do { _ = try BinaryDelimited.parse(messageType: ProtobufUnittest_TestAllTypes.self, from: stream2) XCTFail("Should not have gotten here") } catch BinaryDelimited.Error.truncated { // Nothing, this is what we expect since there is nothing left to read. } catch let e { XCTFail("Unexpected failure: \(e)") } } }
31.453333
99
0.674014
e8827083264a26d65196808a0b262ecd3c7134fd
2,382
// // FDTextFieldTableViewCell.swift // FDTextFieldTableViewCell // // Created by William Entriken on 2/2/16. // Copyright © 2016 William Entriken. All rights reserved. // import UIKit //@IBDesignable /// A UITableViewCell with a UITextField inside open class FDTextFieldTableViewCell: UITableViewCell { open var textField = UITextField() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .default, reuseIdentifier: reuseIdentifier) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override open func awakeFromNib() { super.awakeFromNib() self.setup() } private func setup() { self.detailTextLabel?.isHidden = true self.contentView.viewWithTag(3)?.removeFromSuperview() self.textField.tag = 3 self.textField.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(self.textField) self.contentView.addConstraint(NSLayoutConstraint( item: self.textField, attribute: .leading, relatedBy: .equal, toItem: self.contentView, attribute: .leading, multiplier: 1, constant: 50 )) self.contentView.addConstraint(NSLayoutConstraint( item: self.textField, attribute: .top, relatedBy: .equal, toItem: self.contentView, attribute: .top, multiplier: 1, constant: 8 )) self.contentView.addConstraint(NSLayoutConstraint( item: self.textField, attribute: .bottom, relatedBy: .equal, toItem: self.contentView, attribute: .bottom, multiplier: 1, constant: -8 )) self.contentView.addConstraint(NSLayoutConstraint( item: self.textField, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1, constant: -16 )) self.textField.textAlignment = .right } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.textField.becomeFirstResponder() } }
29.775
84
0.602855
f45bfd25a8b38a66d4a7800bd3e8446b44101423
690
// // Keyboard.swift // WordleDebug // // Created by Vasily Martin for the Developer Academy // import Foundation enum KeyboardKeyAction: String, Decodable { // add a character case character // delete the last character case backspace // submit the word case enter } // describes a virtual keyboard key struct KeyboardKey: Identifiable, Hashable, Decodable { var action: KeyboardKeyAction let value: String var id: String { value } } // describes virtual keyboard keys in a row typealias KeyboardRow = [KeyboardKey] // describes a virtual keyboard struct Keyboard: Decodable { let language: String let rows: [KeyboardRow] }
18.648649
55
0.695652
ccf16401e04257f432071294099861226b6ece39
11,060
// // SwiftyUserDefaults // // Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /// Class important for saving and getting values from UserDefaults. Be careful when you /// subclass your own! open class DefaultsBridge<T> { public init() {} /// This method provides a way of saving your data in UserDefaults. Usually needed /// when you want to create your custom Bridge, so you'll have to override it. open func save(key: String, value: T?, userDefaults: UserDefaults) { fatalError("This Bridge wasn't subclassed! Please do so before using it in your type.") } /// This method provides a way of saving your data in UserDefaults. Usually needed /// when you want to create your custom Bridge, so you'll have to override it. open func get(key: String, userDefaults: UserDefaults) -> T? { fatalError("This Bridge wasn't subclassed! Please do so before using it in your type.") } /// Override this function if your data is represented differently in UserDefaults /// and you map it in save/get methods. /// /// For instance, if you store it as Data in UserDefaults, but your type is not Data in your /// defaults key, then you need to `return true` here and provide `deserialize(_:)` method as well. /// /// Similar if you store your array of type as e.g. `[String]` but the type you use is actually `[SomeClassThatHasOnlyOneStringProperty]`. /// /// See `DefaultsRawRepresentableBridge` or `DefaultsCodableBridge` for examples. open func isSerialized() -> Bool { return false } /// Override this function if you've returned `true` in `isSerialized()` method. /// /// See `isSerialized()` method description for more details. open func deserialize(_ object: Any) -> T? { fatalError("You set `isSerialized` to true, now you have to implement `deserialize` method.") } } public final class DefaultsObjectBridge<T>: DefaultsBridge<T> { public override func save(key: String, value: T?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public override func get(key: String, userDefaults: UserDefaults) -> T? { return userDefaults.object(forKey: key) as? T } } public final class DefaultsArrayBridge<T: Collection>: DefaultsBridge<T> { public override func save(key: String, value: T?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public override func get(key: String, userDefaults: UserDefaults) -> T? { return userDefaults.array(forKey: key) as? T } } public final class DefaultsStringBridge: DefaultsBridge<String> { public override func save(key: String, value: String?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public override func get(key: String, userDefaults: UserDefaults) -> String? { return userDefaults.string(forKey: key) } } public final class DefaultsIntBridge: DefaultsBridge<Int> { public override func save(key: String, value: Int?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public override func get(key: String, userDefaults: UserDefaults) -> Int? { if let int = userDefaults.number(forKey: key)?.intValue { return int } // Fallback for launch arguments if let string = userDefaults.object(forKey: key) as? String, let int = Int(string) { return int } return nil } } public final class DefaultsDoubleBridge: DefaultsBridge<Double> { public override func save(key: String, value: Double?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public override func get(key: String, userDefaults: UserDefaults) -> Double? { if let double = userDefaults.number(forKey: key)?.doubleValue { return double } // Fallback for launch arguments if let string = userDefaults.object(forKey: key) as? String, let double = Double(string) { return double } return nil } } public final class DefaultsBoolBridge: DefaultsBridge<Bool> { public override func save(key: String, value: Bool?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public override func get(key: String, userDefaults: UserDefaults) -> Bool? { // @warning we use number(forKey:) instead of bool(forKey:), because // bool(forKey:) will always return value, even if it's not set // // Now, let's see if there is value in defaults that converts to Bool first: if let bool = userDefaults.number(forKey: key)?.boolValue { return bool } // If not, fallback for values saved in a plist (e.g. for testing) // For instance, few of the string("YES", "true", "NO", "false") convert to Bool from a property list return (userDefaults.object(forKey: key) as? String)?.bool } } public final class DefaultsDataBridge: DefaultsBridge<Data> { public override func save(key: String, value: Data?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public override func get(key: String, userDefaults: UserDefaults) -> Data? { return userDefaults.data(forKey: key) } } public final class DefaultsUrlBridge: DefaultsBridge<URL> { public override func save(key: String, value: URL?, userDefaults: UserDefaults) { userDefaults.set(value, forKey: key) } public override func get(key: String, userDefaults: UserDefaults) -> URL? { return userDefaults.url(forKey: key) } public override func isSerialized() -> Bool { return true } public override func deserialize(_ object: Any) -> URL? { if let object = object as? URL { return object } if let object = object as? Data { return NSKeyedUnarchiver.unarchiveObject(with: object) as? URL } if let object = object as? NSString { let path = object.expandingTildeInPath return URL(fileURLWithPath: path) } return nil } } public final class DefaultsCodableBridge<T: Codable>: DefaultsBridge<T> { public override func save(key: String, value: T?, userDefaults: UserDefaults) { guard let value = value else { userDefaults.removeObject(forKey: key) return } userDefaults.set(encodable: value, forKey: key) } public override func get(key: String, userDefaults: UserDefaults) -> T? { guard let data = userDefaults.data(forKey: key) else { return nil } return deserialize(data) } public override func isSerialized() -> Bool { return true } public override func deserialize(_ object: Any) -> T? { guard let data = object as? Data else { return nil } return try? JSONDecoder().decode(T.self, from: data) } } public final class DefaultsKeyedArchiverBridge<T>: DefaultsBridge<T> { public override func get(key: String, userDefaults: UserDefaults) -> T? { guard let data = userDefaults.data(forKey: key) else { return nil } return deserialize(data) } public override func save(key: String, value: T?, userDefaults: UserDefaults) { guard let value = value else { userDefaults.removeObject(forKey: key) return } // Needed because Quick/Nimble have min target 10.10... if #available(OSX 10.11, *) { userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key) } else { fatalError("Shouldn't really happen. We do not support macOS 10.10, if it happened to you please report your use-case on GitHub issues.") } } public override func isSerialized() -> Bool { return true } public override func deserialize(_ object: Any) -> T? { guard let data = object as? Data else { return nil } return NSKeyedUnarchiver.unarchiveObject(with: data) as? T } } public final class DefaultsRawRepresentableBridge<T: RawRepresentable>: DefaultsBridge<T> { public override func get(key: String, userDefaults: UserDefaults) -> T? { guard let object = userDefaults.object(forKey: key) else { return nil } return deserialize(object) } public override func save(key: String, value: T?, userDefaults: UserDefaults) { userDefaults.set(value?.rawValue, forKey: key) } public override func isSerialized() -> Bool { return true } public override func deserialize(_ object: Any) -> T? { guard let rawValue = object as? T.RawValue else { return nil } return T(rawValue: rawValue) } } public final class DefaultsRawRepresentableArrayBridge<T: Collection>: DefaultsBridge<T> where T.Element: RawRepresentable { public override func get(key: String, userDefaults: UserDefaults) -> T? { guard let object = userDefaults.array(forKey: key) else { return nil } return deserialize(object) } public override func save(key: String, value: T?, userDefaults: UserDefaults) { let raw = value?.map { $0.rawValue } userDefaults.set(raw, forKey: key) } public override func isSerialized() -> Bool { return true } public override func deserialize(_ object: Any) -> T? { guard let rawValue = object as? [T.Element.RawValue] else { return nil } return rawValue.compactMap { T.Element(rawValue: $0) } as? T } }
36.143791
149
0.647468
646d952c3a23e7c62eb7ede86a6c855fc24ded05
360
// // ListsFooterViewDelegate.swift // Tinylog // // Created by Spiros Gerokostas on 17/08/2019. // Copyright © 2019 Spiros Gerokostas. All rights reserved. // protocol ListsFooterViewDelegate: AnyObject { func listsFooterViewAddNewList(_ listsFooterView: ListsFooterView) func listsFooterViewDisplayArchives(_ listsFooterView: ListsFooterView) }
27.692308
75
0.780556
7208298095cbc6f787987a87cfa05c45c1d08a96
1,941
// // XLsn0wDispatchQueue.swift // XLsn0wAnimation // // Created by golong on 2017/12/11. // Copyright © 2017年 XLsn0w. All rights reserved. // import UIKit class XLsn0wDispatchQueue: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // let queue = DispatchQueue(label: "xlsn0w") // QoS是个基于具体场景的枚举类型,在初始队列时,可以提供合适的QoS参数来得到相应的权限,如果没有指定QoS,那么初始方法会使用队列提供的默认的QoS值 // QoS等级(QoS classes),从前到后,优先级从高到低: // userInteractive // userInitiated // default // utility // background // unspecified let queue = DispatchQueue(label: "xlsn0w", qos: DispatchQoS.unspecified, attributes:.concurrent) queue.async { ///code } print("DispatchQueue.main.sync: befor", Thread.current) DispatchQueue.global().async { print("DispatchQueue.global().async: Time task", Thread.current, "\n --: 耗时操作在后台线程中执行!") DispatchQueue.main.async { print("DispatchQueue.main.async: update UI", Thread.current, "\n --: 耗时操作执行完毕后在主线程更新 UI 界面!") } } print("DispatchQueue.main.sync: after", Thread.current) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
26.958333
109
0.583205
21ce0cb45cc9735dd3bf6addfd8cc9278227f6c2
1,711
// // HttpRequestBuilder.swift // ConcreteMovieApp // // Created by Wilson Kim on 21/03/20. // Copyright © 2020 Wilson Kim. All rights reserved. // import Foundation public struct Request: HTTPRequestParamsProtocol { public var url: String public var method: HTTPMethod public var query: [String: Any]? public var path: String? public var header: [String: Any]? public var body: [String: Any]? } public class RequestBuilder { private var url: String private var method: HTTPMethod private var query: [String: Any]? private var path: String? private var header: [String: Any]? private var body: [String: Any]? public init(withUrl url: String, andMethod method: HTTPMethod) { self.url = url self.method = method } public func withQuery(_ query: [String: Any]) -> RequestBuilder { self.query = query return self } public func withPath(_ path: String) -> RequestBuilder { self.path = path return self } public func withHeader(_ header: [String: Any]) -> RequestBuilder { self.header = header return self } public func addHeader(key: String, value: String) -> RequestBuilder { self.header?[key] = value return self } public func withBody(_ body: [String: Any]) -> RequestBuilder { self.body = body return self } public func create() -> Request { return Request(url: url, method: method, query: query, path: path, header: header, body: body) } }
24.797101
73
0.57744
09b1a60373d85e1559139bb095b90c75bc15108f
1,787
// // NERoomServiceProtocol.swift // NELiveRoom // // Created by Wenchao Ding on 2021/5/25. // import Foundation @objc public protocol NERoomAPIServiceProtocol: NSObjectProtocol { /// 当前房间,如果没有房间则为nil @objc var currentRoom: NERoomDetail? { get set} /// 当前用户,创建房间或加入房间后由server返回 @objc var currentUser: NERoomUserDetail? { get } /// 创建房间 /// @param params 参数 @see NECreateRoomParams /// @param completion 回调 @objc func createRoom(_ params: NECreateRoomParams, completion: NECreateRoomCompletion?) /// 销毁房间,成功后会触发NERoomServiceDelegate#onRoomDestroyed() /// @param params 参数 @see NEDestroyRoomParams /// @param completion 回调 @objc func destroyRoom(_ params: NEDestroyRoomParams, completion: NEDestroyRoomCompletion?) /// 加入房间,成功后触发NERoomServiceDelegate#onUserEnterRoom() /// @param params 参数 @see NEEnterRoomParams /// @param completion 回调 @objc func enterRoom(_ params: NEEnterRoomParams, completion: NEEnterRoomCompletion?) /// 离开房间,成功后触发NERoomServiceDelegate#onUserLeaveRoom() /// @param params 参数 @see NELeaveRoomParams /// @param completion 回调 @objc func leaveRoom(_ params: NELeaveRoomParams, completion: NELeaveRoomCompletion?) /// 获取房间列表 /// @param params 参数 @see NEListRoomParams /// @param completion 回调 @objc func listRooms(_ params: NEListRoomParams, completion: NEListRoomCompletion?) } @objc public protocol NERoomServiceProtocol: NERoomAPIServiceProtocol { /// 添加事件代理 /// @param delegate 需要添加的代理对象 @objc(addDelegate:) func add(delegate: NERoomServiceDelegate) /// 移除事件回调 /// @param delegate 需要移除的代理对象 @objc(removeDelegate:) func remove(delegate: NERoomServiceDelegate) }
26.671642
89
0.69502
50bee9e08eab29e560f53b229a5626899ea1840a
28,837
// // JIRA.swift // Pods // // Created by Will Powell on 30/08/2017. // // import Foundation import MBProgressHUD public enum JIRAAuthentication { case basic case oauth } public class JIRA { // Jira singleton instance public static var shared = JIRA() public var authenticationMethod:JIRAAuthentication = .basic public var preferredOrder = [String]() // This is how we specify the order of fields public var stringFieldsAsTextView = [String]() public var defaultToOnlyRequired:Bool = true // END POINTS private static let url_issue = "rest/api/2/issue"; private static let url_issue_attachments = "rest/api/2/issue/%@/attachments"; private static let url_issue_createmeta = "/rest/api/2/issue/createmeta?expand=projects.issuetypes.fields" private static let url_myself = "/rest/api/2/myself" private static let url_jql_property = "/rest/api/1.0/jql/autocomplete?" internal static let MainColor = UIColor(red:32/255.0, green: 80.0/255.0, blue: 129.0/255.0,alpha:1.0) private var _host:String? // jira host eg. http://company.atlassian.net for JIRA cloud hosted public var host:String? { get{ return _host } } private var _username:String? // jira host eg. http://company.atlassian.net for JIRA cloud hosted var username:String? { get{ if _username != nil { return _username } return UserDefaults.standard.string(forKey: "JIRA_USE") } set { _username = newValue UserDefaults.standard.set(newValue, forKey: "JIRA_USE") UserDefaults.standard.synchronize() } } private var _password:String? var password:String? { get{ if _password != nil { return _password } return UserDefaults.standard.string(forKey: "JIRA_PWD") } set { _password = newValue UserDefaults.standard.set(newValue, forKey: "JIRA_PWD") UserDefaults.standard.synchronize() } } public func preAuth(username:String, password:String){ _password = password _username = username } private var _project:String? // this is the core project identifier for the project within JIRA public var project:String? { get{ return _project } } private var _defaultIssueType:String? // the issue type that you would like the application to use as the default starting case public var defaultIssueType:String? { get{ return _defaultIssueType } } // The fields that should be added for all tasks by default public var globalDefaultFields:[String:Any]? var projects:[JIRAProject]? internal static func getBundle()->Bundle{ let podBundle = Bundle.init(for: JIRA.self) let bundleURL = podBundle.url(forResource: "JIRAMobileKit" , withExtension: "bundle") return Bundle(url: bundleURL!)! } // public func setup(host:String, project:String, defaultIssueType:String? = "Bug", defaultValues:[String:Any]? = nil){ guard !host.isEmpty, URL(string:host) != nil else { print("JIRAKIT ERROR - Host is invalid, must be a url") return } guard project != "[[PROJECT_KEY]]" else { print("JIRAKIT ERROR - Project key not Set") return } var shouldReset = false if let originalHost = UserDefaults.standard.string(forKey: "JIRA_HOST"), let originalProject = UserDefaults.standard.string(forKey: "JIRA_PROJECT") { if originalHost != host || project != originalProject { shouldReset = true } }else{ shouldReset = true } _host = host _project = project _defaultIssueType = defaultIssueType if shouldReset { UserDefaults.standard.set(nil, forKey: "JIRA_CREATEMETA_CACHE") UserDefaults.standard.set(host,forKey: "JIRA_HOST") UserDefaults.standard.set(project,forKey: "JIRA_PROJECT") UserDefaults.standard.set(nil, forKey: "JIRA_PWD") UserDefaults.standard.set(nil, forKey: "JIRA_USE") UserDefaults.standard.synchronize() } } public func doLogin(completion: @escaping ()->Void){ guard let rootController = UIApplication.shared.keyWindow?.rootViewController else { return } let loginVC = JIRALoginViewController(nibName: "JIRALoginViewController", bundle: JIRA.getBundle()) loginVC.onLoginCompletionBlock = completion /*let nav = UINavigationController(rootViewController: loginVC); nav.navigationBar.barStyle = .blackOpaque nav.navigationBar.tintColor = UIColor.white nav.navigationBar.barTintColor = JIRA.MainColor nav.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] nav.navigationBar.isTranslucent = false nav.navigationBar.isOpaque = true*/ rootController.present(loginVC, animated: true, completion: nil) } public func doOauth(completion:@escaping () -> Void){ /*let oauthswift = OAuth2Swift( consumerKey: "E053rqqra4mXVnfhEHRYRecir5bW3K38", consumerSecret: "dqFbY9HrYVqAyzuFR3UGDxYUlf0zDCmVRlZFwJjYUEUJL2g-2kErIpVbKd3dRjYZ", authorizeUrl: "https://auth.atlassian.com/authorize", accessTokenUrl: "https://auth.atlassian.com/oauth/token", responseType: "code" ) oauthswift.allowMissingStateCheck = true //2 guard let vc = UIApplication.shared.keyWindow?.rootViewController else { return } oauthswift.authorizeURLHandler = SafariURLHandler(viewController: vc, oauthSwift: oauthswift) guard let rwURL = URL(string: "jiramobilekit://oauth2Callback") else { return } //3 oauthswift.authorize(withCallbackURL: rwURL, scope: "read:jira-user read:jira-work write:jira-work", state: "", success: { (credential, response, parameters) in print("Logged in") }, failure: { (error) in print("Failed") })*/ } public func raise(defaultFields:[String:Any]? = nil, withScreenshot screenshot:Bool = true){ switch(self.authenticationMethod){ case .basic: if JIRA.shared.username == nil || JIRA.shared.password == nil { doLogin { self.launchCreateScreen(defaultFields: defaultFields, withScreenshot:screenshot) } return } break case .oauth: doOauth{ self.launchCreateScreen(defaultFields: defaultFields, withScreenshot:screenshot) } return break } launchCreateScreen(defaultFields: defaultFields, withScreenshot:screenshot) } private func launchCreateScreen(defaultFields:[String:Any]? = nil, withScreenshot screenshot:Bool = true){ guard let rootController = UIApplication.shared.keyWindow?.rootViewController else { return } // Start with global fields var fields = self.globalDefaultFields ?? [String:Any]() // merge in default fields for current view if let singleDefaults = defaultFields { singleDefaults.forEach({ (key, value) in fields[key] = value }) } // Add Image if screenshot == true, let image = UIApplication.shared.keyWindow?.capture() { if let attachments = fields["attachment"] { if var attachmentAry = attachments as? [Any] { attachmentAry.insert(image, at: 0) fields["attachment"] = attachmentAry }else{ fields["attachment"] = [image,attachments] } }else{ fields["attachment"] = [image] } } if let environment = fields["environment"] as? String { fields["environment"] = environment + " " + JIRA.environmentString() }else{ fields["environment"] = JIRA.environmentString() } let newVC = JIRARaiseTableViewController() var currentController: UIViewController! = rootController while( currentController.presentedViewController != nil ) { currentController = currentController.presentedViewController } newVC.singleInstanceDefaultFields = fields newVC.image = UIApplication.shared.keyWindow?.capture() let nav = UINavigationController(rootViewController: newVC); nav.navigationBar.barStyle = .blackOpaque nav.navigationBar.tintColor = UIColor.white nav.navigationBar.barTintColor = JIRA.MainColor nav.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] nav.navigationBar.isTranslucent = false nav.navigationBar.isOpaque = true currentController.present(nav, animated: true) } func generateBearerToken(username:String, password:String)->String?{ let userPasswordString = username + ":" + password if let userPasswordData = userPasswordString.data(using: String.Encoding.utf8) { let base64EncodedCredential = userPasswordData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue:0)) return "Basic \(base64EncodedCredential)" } return nil } func getBearerToken()->String?{ if let username = self.username, let password = self.password { return generateBearerToken(username: username, password: password) } return "" } func session()->URLSession{ let config = URLSessionConfiguration.default config.httpAdditionalHeaders = ["Authorization" : getBearerToken()!] return URLSession(configuration: config) } func session(_ username:String, _ password:String)->URLSession{ let config = URLSessionConfiguration.default if let authString = generateBearerToken(username: username, password: password) { config.httpAdditionalHeaders = ["Authorization" : authString] } return URLSession(configuration: config) } public func login(username:String, password:String, completion: @escaping (_ completed:Bool, _ error:String?) -> Void) { let url = URL(string: "\(host!)\(JIRA.url_myself)")! var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "GET" let task = session(username, password).dataTask(with:request) { data, response, error in guard let httpURLResponse = response as? HTTPURLResponse else { completion(false,"Could connect to JIRA. Check your configurations.") return } if httpURLResponse.statusCode > 500 { completion(false,"Internal Server Error Occured.") return }else if httpURLResponse.statusCode > 400 { completion(false,"Not found or no permission to access url") return } do { _ = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary self.username = username self.password = password completion(true, nil) } catch { print("error serializing JSON: \(error)") completion(false,"Could not authenticate you with username \(username) and password.") } } task.resume() } static func environmentString()->String { var buildStr = ""; var versionStr = ""; if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { versionStr = version } if let version = Bundle.main.infoDictionary?["CFBundleVersion"] as? String { buildStr = version } let systemVersion = UIDevice.current.systemVersion /*var output = "" Bundle.allFrameworks.forEach { (bundle) in if let bundleIdentifier = bundle.bundleIdentifier, bundleIdentifier.contains("com.apple") == false{ var record = bundleIdentifier if let version = bundle.infoDictionary!["CFBundleShortVersionString"] as? String { record += " - \(version)" } output += record+"\n" } }*/ return "\(UIDevice.current.model) \(systemVersion) version: \(versionStr) - build: \(buildStr)" } private func createDataTransferObject(_ issueData:[AnyHashable:Any]) -> [String:Any]{ var data = [String:Any]() issueData.forEach { (key,value) in if let key = key as? String { if value is String { data[key] = value }else if let jiraEntity = value as? JIRAEntity { data[key] = jiraEntity.export() }else if let jiraEntityAry = value as? [JIRAEntity] { let entities = jiraEntityAry.map({ (entity) -> Any? in return entity.export() }) data[key] = entities } } } return ["fields":data] } internal func create(issueData:[AnyHashable:Any], completion: @escaping (_ error:String?,_ key:String?) -> Void){ guard let url = URL(string: "\(host!)/\(JIRA.url_issue)") else { print("JIRA KIT Error - Create url invalid") completion("Create url invalid", nil) return } let data = createDataTransferObject(issueData) var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" do{ let jsonData = try JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions(rawValue: 0)) request.httpBody = jsonData let task = session().dataTask(with:request) { data, response, error in guard let _ = response as? HTTPURLResponse else { return } do { let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary if let key = json?.object(forKey: "key") as? String { if let attachments = issueData["attachment"] as? [Any] { self.uploadAttachments(key: key, attachments: attachments, completion: completion) }else{ completion(nil, key) } return }else if let errors = json?.object(forKey: "errors") as? [String:Any] { var str = [String]() errors.forEach({ (key, value) in if let val = value as? String { str.append(val) } }) let errorMessage = str.joined(separator: "\n") completion(errorMessage, nil) return } completion("Could not complete create", nil) } catch { print("error serializing JSON: \(error)") completion("error serializing JSON: \(error)", nil) } } task.resume() } catch { print(error) completion("error serializing JSON: \(error)", nil) } } internal func uploadAttachments(key:String, attachments:[Any], completion: @escaping (_ error:String?,_ key:String?) -> Void){ var datas = [(name:String, data:Data, mimeType:String)]() attachments.forEach { (attachment) in if let attachmentPath = attachment as? String, let attachmentURL:URL = URL(string:attachmentPath) { if let data = try? Data(contentsOf:attachmentURL) { let mimeType = attachmentURL.absoluteString.mimeType() let fileName = attachmentURL.lastPathComponent datas.append((name: fileName, data: data, mimeType: mimeType)) } }else if let attachmentURL = attachment as? URL { if let data = try? Data(contentsOf:attachmentURL) { let mimeType = attachmentURL.absoluteString.mimeType() let fileName = attachmentURL.lastPathComponent datas.append((name: fileName, data: data, mimeType: mimeType)) } }else if let attachmentImage = attachment as? UIImage{ if let data = attachmentImage.pngData() { datas.append((name: "Screenshot.png", data: data, mimeType: "image/png")) } } } uploadDataAttachments(key:key, attachments: datas, count:0, completion: completion) } internal func uploadDataAttachments(key:String, attachments:[(name:String, data:Data, mimeType:String)], count:Int, completion: @escaping (_ error:String?,_ key:String?) -> Void){ if count >= attachments.count { completion(nil, key) }else{ let attachment = attachments[count] postAttachment(key: key, data: attachment, completion: { (error, keyStr) in self.uploadDataAttachments(key: key, attachments: attachments, count: (count + 1), completion: completion) }) } } internal func postAttachment(key:String, data:(name:String, data:Data, mimeType:String), completion: @escaping (_ error:String?,_ key:String?) -> Void) { let url = URL(string: "\(host!)/rest/api/2/issue/\(key)/attachments")! var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("nocheck", forHTTPHeaderField: "X-Atlassian-Token") request.httpMethod = "POST" let boundary = generateBoundaryString() request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let attachmentData = data.data let body = NSMutableData() let fname = data.name let mimetype = data.mimeType //define the data post parameter body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!) body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!) body.append(attachmentData) body.append("\r\n".data(using: String.Encoding.utf8)!) body.append("--\(boundary)--\r\n".data(using:String.Encoding.utf8)!) let outputData = body as Data request.httpBody = outputData let task = session().dataTask(with:request) { data, response, error in if let _ = response as? HTTPURLResponse { do { let _ = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary completion(nil, key) } catch { print("error serializing JSON: \(error)") completion("error serializing JSON: \(error)", nil) } }else{ completion("error connecting to JIRA no attachment uploaded", nil) } } task.resume() } internal func createMeta(_ completion: @escaping (_ error:Bool, _ project:JIRAProject?) -> Void){ if let cachedData = UserDefaults.standard.data(forKey: "JIRA_CREATEMETA_CACHE") { processCreateMetaData(cachedData, completion: { [weak self] (err, project) in guard err == false else { self?.continueCreateMeta(completion) return } self?.continueCreateMeta(completion) }) return } continueCreateMeta(completion) } internal func continueCreateMeta(_ completion: @escaping (_ error:Bool, _ project:JIRAProject?) -> Void){ let url = URL(string: "\(host!)\(JIRA.url_issue_createmeta)&projectKeys=\(self.project!)")! var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "GET" let task = session().dataTask(with:request) { data, response, error in if let _ = response as? HTTPURLResponse { UserDefaults.standard.set(data!, forKey: "JIRA_CREATEMETA_CACHE") UserDefaults.standard.synchronize() self.processCreateMetaData(data, completion: completion) } } task.resume() } internal func jqlQuery(field:JIRAField, term:String,_ completion: @escaping (_ error:Bool, _ options:[JIRAJQLValue]?) -> Void){ guard let fieldName = field.name else{ return; } guard let fieldNameEscaped = fieldName.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let termEscaped = term.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string:"\(host!)\(JIRA.url_jql_property)fieldName=\(fieldNameEscaped)&fieldValue=\(termEscaped)") else{ return } var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "GET" let task = session().dataTask(with:request) { data, response, error in if let _ = response as? HTTPURLResponse { do { let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [AnyHashable:Any] if let items = json?["results"] as? [[String:String]] { let options = items.compactMap({ (item) -> JIRAJQLValue? in let v = JIRAJQLValue() v.applyData(data: item) return v }) return completion(false, options) } return completion(true, nil) } catch { print("error serializing JSON: \(error)") DispatchQueue.main.async { completion(true,nil) } } } } task.resume() } func processCreateMetaData(_ data:Data?, completion: @escaping (_ error:Bool, _ project:JIRAProject?) -> Void){ do { let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [AnyHashable:Any] var projects = [JIRAProject]() if let projectsData = json?["projects"] as? [[AnyHashable:Any]]{ projectsData.forEach({ (projectData) in let project = JIRAProject() project.applyData(data: projectData) projects.append(project) }) } self.projects = projects let currentProject = self.projects?.filter({ (project) -> Bool in return project.key == self.project }) if currentProject?.count == 1 { DispatchQueue.main.async { completion(false,currentProject?[0]) } }else{ // todo when no project is found error DispatchQueue.main.async { completion(true,nil) } } } catch { print("error serializing JSON: \(error)") DispatchQueue.main.async { completion(true,nil) } } } internal func getChildEntities(dClass: JIRAEntity.Type,urlstr:String, _ completion: @escaping (_ error:Bool, _ values:[JIRAEntity]?) -> Void){ guard var urlComponents = URLComponents(string: urlstr) else { completion(true, nil) return } var parameters = urlComponents.queryItems?.filter({ (queryItem) -> Bool in return queryItem.value != "null" }) let params = parameters?.map({ (queryItem) -> URLQueryItem in if queryItem.name == "currentProjectId" { return URLQueryItem(name: "currentProjectId", value: project) } return queryItem }) if let params2 = params{ parameters = params2 } parameters?.append(URLQueryItem(name: "project", value: project)) urlComponents.queryItems = parameters guard let url = urlComponents.url else { completion(true, nil) return } var request = URLRequest(url: url) request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "GET" let task = session().dataTask(with:request) { data, response, error in if let _ = response as? HTTPURLResponse { do { let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) var values = [JIRAEntity]() if let jsonAry = json as? [[AnyHashable:Any]] { values = jsonAry.compactMap({ (element) -> JIRAEntity? in let val = dClass.init() if let valDisplayClass = val as? DisplayClass { valDisplayClass.applyData(data: element) } return val }) }else if let jsonData = json as? [AnyHashable:Any] { if let jsonAry = jsonData["suggestions"] as? [[AnyHashable:Any]] { values = jsonAry.compactMap({ (element) -> JIRAEntity? in let val = dClass.init() if let valDisplayClass = val as? DisplayClass { valDisplayClass.applyData(data: element) } return val }) }else if let jsonAry = jsonData["sections"] as? [[AnyHashable:Any]] { values = jsonAry.compactMap({ (element) -> JIRAEntity? in let val = dClass.init() if let valDisplayClass = val as? DisplayClass { valDisplayClass.applyData(data: element) } return val }) } } completion(true,values) } catch { print("error serializing JSON: \(error)") completion(false,nil) } } } task.resume() } public func generateBoundaryString() -> String { return "Boundary-\(NSUUID().uuidString)" } public func getFullImage()->UIImage{ let window: UIWindow! = UIApplication.shared.keyWindow return window.capture() } }
41.492086
183
0.561813
f97fa8cb2047852a0a55e9ebe2c061b077e6adbe
713
import Vapor /// Controls basic CRUD operations on `Todo`s. final class TodoController { /// Returns a list of all `Todo`s. func index(_ req: Request) throws -> Future<[Todo]> { return Todo.query(on: req).all() } /// Saves a decoded `Todo` to the database. func create(_ req: Request) throws -> Future<Todo> { return try req.content.decode(Todo.self).flatMap { todo in return todo.save(on: req) } } /// Deletes a parameterized `Todo`. func delete(_ req: Request) throws -> Future<HTTPStatus> { return try req.content.decode(Todo.self).flatMap { todo in return todo.delete(on: req) }.transform(to: .ok) } }
29.708333
66
0.603086
fb3d273ae7572036998e997200818721df3fb7a0
2,873
/* * Copyright (c) 2019 Ableton AG, Berlin * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ import UIKit @IBDesignable class SliderWithValue: UISlider { let kValueFieldWidth: CGFloat = 53.0 let kPadding: CGFloat = 16.0 var valueFormatter = { (value: Float) in return "\(Int(value))" } private var valueField = UITextField() override var value: Float { didSet { updateValueField() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override init(frame: CGRect) { super.init(frame: frame) initialize() } private func initialize() { valueField.borderStyle = .roundedRect valueField.font = UIFont.systemFont(ofSize: 15.0) valueField.textAlignment = .center valueField.isUserInteractionEnabled = false valueField.translatesAutoresizingMaskIntoConstraints = false addSubview(valueField) updateValueField() let valueFieldWidthConstraint = NSLayoutConstraint( item: valueField, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: kValueFieldWidth) let valueFieldConstraint = NSLayoutConstraint( item: valueField, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0) NSLayoutConstraint.activate([valueFieldWidthConstraint, valueFieldConstraint]) self.addTarget(self, action: #selector(onValueChange), for: .valueChanged) } override func trackRect(forBounds bounds: CGRect) -> CGRect { var rect = super.trackRect(forBounds: bounds) rect.size.width = rect.width - kValueFieldWidth - kPadding return rect } @objc private func onValueChange() { updateValueField() } private func updateValueField() { valueField.text = valueFormatter(value) } }
35.036585
82
0.732684
33b95a36caf45e76d190fab1232af2fac6ff8bdb
1,916
// // Copyright © 2019 Essential Developer. All rights reserved. // import XCTest import FeedStoreChallenge class FeedStoreChallengeTests: XCTestCase, FeedStoreSpecs { func test_retrieve_deliversEmptyOnEmptyCache() { let sut = makeSUT() assertThatRetrieveDeliversEmptyOnEmptyCache(on: sut) } func test_retrieve_hasNoSideEffectsOnEmptyCache() { let sut = makeSUT() assertThatRetrieveHasNoSideEffectsOnEmptyCache(on: sut) } func test_retrieve_deliversFoundValuesOnNonEmptyCache() { let sut = makeSUT() assertThatRetrieveDeliversFoundValuesOnNonEmptyCache(on: sut) } func test_retrieve_hasNoSideEffectsOnNonEmptyCache() { let sut = makeSUT() assertThatRetrieveHasNoSideEffectsOnNonEmptyCache(on: sut) } func test_insert_deliversNoErrorOnEmptyCache() { let sut = makeSUT() assertThatInsertDeliversNoErrorOnEmptyCache(on: sut) } func test_insert_deliversNoErrorOnNonEmptyCache() { let sut = makeSUT() assertThatInsertDeliversNoErrorOnNonEmptyCache(on: sut) } func test_insert_overridesPreviouslyInsertedCacheValues() { let sut = makeSUT() assertThatInsertOverridesPreviouslyInsertedCacheValues(on: sut) } func test_delete_deliversNoErrorOnEmptyCache() { let sut = makeSUT() assertThatDeleteDeliversNoErrorOnEmptyCache(on: sut) } func test_delete_hasNoSideEffectsOnEmptyCache() { let sut = makeSUT() assertThatDeleteHasNoSideEffectsOnEmptyCache(on: sut) } func test_delete_deliversNoErrorOnNonEmptyCache() { let sut = makeSUT() assertThatDeleteDeliversNoErrorOnNonEmptyCache(on: sut) } func test_delete_emptiesPreviouslyInsertedCache() { let sut = makeSUT() assertThatDeleteEmptiesPreviouslyInsertedCache(on: sut) } func test_storeSideEffects_runSerially() { let sut = makeSUT() assertThatSideEffectsRunSerially(on: sut) } // - MARK: Helpers private func makeSUT() -> FeedStore { return InMemoryFeedStore() } }
21.288889
65
0.786013
0a8303583e2d3bde38e3e04f8c55472390a787a5
1,345
import UIKit /// Описание параметров запуска анимаций прямого модального перехода на UISplitViewController public struct ModalMasterDetailPresentationAnimationLaunchingContext { /// контроллер, на который нужно осуществить модальный переход public private(set) weak var targetViewController: UISplitViewController? /// аниматор, выполняющий анимации прямого и обратного перехода public let animator: ModalMasterDetailTransitionsAnimator public init( targetViewController: UISplitViewController, animator: ModalMasterDetailTransitionsAnimator) { self.targetViewController = targetViewController self.animator = animator } // контроллер, с которого нужно осуществить модальный переход public weak var sourceViewController: UIViewController? public var isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute: Bool { if targetViewController == nil { return true } if sourceViewController?.presentedViewController == nil { marshrouteAssertionFailure( """ It looks like \(targetViewController as Any) did not deallocate due to some retain cycle! """ ) return true } return false } }
33.625
106
0.682528
e4e94266b41b2bbcb634ad605a6ba5b87e79c17e
4,795
// Copyright © 2020 Jamit Labs GmbH. All rights reserved. import UIKit /// Protocol a header view should conform to to be informed about certain changes public protocol CollapsibleHeaderViewDelegate { /// Called when the state of the collapsible view has changed. /// ///- Parameter to: The current state of the collapsible view.. func didChangeCollapsibleState(to isCollapsed: Bool) } /// A stateful collapsible view. /// /// Example: /// ```swift /// /// let itemView: UIView = .init() /// itemView.backgroundColor = .red /// itemView.heightAnchor.constraint(equalToConstant: 44.0).isActive = true /// itemView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true /// /// collapsibleView.model = .init( /// headerViewModel: .init( /// title: "Header title", /// titleFont: .systemFont(ofSize: 16.0), /// arrowImageUp: nil // TODO: Place an image here if needed /// ), /// items: [itemView], /// isCollapsed: true, /// animationDuration: 0.3 /// ) /// ``` public final class CollapsibleView<HeaderView: StatefulViewProtocol>: StatefulView<CollapsibleViewModel<HeaderView.Model>> { private lazy var headerView: HeaderView = .instantiate() private lazy var actionButton: UIButton = { let actionButton: UIButton = .init() actionButton.setTitle("", for: .normal) actionButton.addTarget(self, action: #selector(didTriggerAction), for: .primaryActionTriggered) actionButton.addTarget(self, action: #selector(updateBackgroundColor), for: .allTouchEvents) actionButton.addTarget(self, action: #selector(lateUpdateBackgroundColor), for: .allTouchEvents) return actionButton }() private lazy var stackView: UIStackView = { let stackView: UIStackView = .init() stackView.alignment = .center stackView.axis = .vertical stackView.distribution = .fillProportionally return stackView }() public override func viewDidLoad() { super.viewDidLoad() clipsToBounds = true headerView.translatesAutoresizingMaskIntoConstraints = false addSubview(headerView) headerView.topAnchor.constraint(equalTo: topAnchor).isActive = true headerView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true headerView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true actionButton.translatesAutoresizingMaskIntoConstraints = false addSubview(actionButton) actionButton.topAnchor.constraint(equalTo: headerView.topAnchor).isActive = true actionButton.leadingAnchor.constraint(equalTo: headerView.leadingAnchor).isActive = true actionButton.trailingAnchor.constraint(equalTo: headerView.trailingAnchor).isActive = true actionButton.bottomAnchor.constraint(equalTo: headerView.bottomAnchor).isActive = true stackView.translatesAutoresizingMaskIntoConstraints = false addSubview(stackView) stackView.topAnchor.constraint(equalTo: headerView.bottomAnchor).isActive = true stackView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true stackView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true stackView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true } public override func didChangeModel() { super.didChangeModel() headerView.model = model.headerViewModel if (stackView.arrangedSubviews.count != model.items.count) { stackView.arrangedSubviews.forEach { $0.removeFromSuperview() } model.items.forEach { view in view.isHidden = model.isCollapsed stackView.addArrangedSubview(view) } } else { UIView.animate(withDuration: model.animationDuration) { self.model.items.forEach { view in view.isHidden = self.model.isCollapsed } } } (headerView as? CollapsibleHeaderViewDelegate)?.didChangeCollapsibleState(to: model.isCollapsed) } @objc private func didTriggerAction() { model.isCollapsed.toggle() model.didChangeCollapsibleState?(model.isCollapsed) } @objc private func updateBackgroundColor() { if [.highlighted, .selected].contains(actionButton.state) { actionButton.backgroundColor = UIColor.black.withAlphaComponent(0.15) } else { actionButton.backgroundColor = UIColor.black.withAlphaComponent(0) } } @objc private func lateUpdateBackgroundColor() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in self?.updateBackgroundColor() } } }
38.669355
124
0.684254
3a1ffb759a6887b50135e2cf0b740d8346b0aff3
11,225
// // OffersService.swift // Wuakup // // Created by Guillermo Gutiérrez on 15/01/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import Foundation import CoreLocation import Alamofire import SwiftyJSON public struct FilterOptions { public let searchTerm: String? public let tags: [String]? public let companyId: Int? public let categoryId: Int? public init(searchTerm: String? = nil, tags: [String]? = nil, companyId: Int? = nil, categoryId: Int? = nil) { self.searchTerm = searchTerm self.tags = tags self.companyId = companyId self.categoryId = categoryId } } public struct PaginationInfo { public let page: Int? public let perPage: Int? public init(page: Int? = nil, perPage: Int? = nil) { self.page = page self.perPage = perPage } } public class OffersService: BaseService { public static let sharedInstance = OffersService() public var highlightedOfferUrl: String { let url = "\(offerHostUrl)offers/highlighted" if let apiKey = apiKey { return url + "/" + apiKey } return url } public func redemptionCodeImageUrl(_ offerId: Int, format: String, width: Int, height: Int) -> String? { guard let userToken = UserService.sharedInstance.userToken else { return .none } return "\(offerHostUrl)offers/\(offerId)/code/\(format)/\(width)/\(height)?userToken=\(userToken)" } public func findOffers(usingLocation location: CLLocationCoordinate2D, sensor: Bool, filterOptions: FilterOptions? = nil, pagination: PaginationInfo? = nil, completion: @escaping ([Coupon]?, Error?) -> Void) { let url = "\(offerHostUrl)offers/find" let locationParameters: [String: Any] = ["latitude": location.latitude, "longitude": location.longitude, "sensor": "\(sensor)"] var parameters = getPaginationParams(pagination: pagination, combinedWith: locationParameters) parameters = getFilterParams(filter: filterOptions, combinedWith: parameters) getOffersFromURL(url: url, parameters: parameters, completion: completion) } public func getRecommendedOffers(usingLocation location: CLLocationCoordinate2D, sensor: Bool, pagination: PaginationInfo? = nil, completion: @escaping ([Coupon]?, Error?) -> Void) { let url = "\(offerHostUrl)offers/recommended" let locationParameters: [String: Any] = ["latitude": location.latitude, "longitude": location.longitude, "sensor": "\(sensor)"] let parameters = getPaginationParams(pagination: pagination, combinedWith: locationParameters) getOffersFromURL(url: url, parameters: parameters, completion: completion) } public func findRelatedOffer(toOffer offer: Coupon, pagination: PaginationInfo? = nil, completion: @escaping ([Coupon]?, Error?) -> Void) { let url = "\(offerHostUrl)offers/related" let offerParameters = ["storeId": offer.store?.id ?? -1, "offerId": offer.id] let parameters = getPaginationParams(pagination: pagination, combinedWith: offerParameters as [String : Any]?) getOffersFromURL(url: url, parameters: parameters, completion: completion) } public func findStoreOffers(nearLocation location: CLLocationCoordinate2D, radius: CLLocationDistance, sensor: Bool, filterOptions: FilterOptions? = nil, completion: @escaping ([Coupon]?, Error?) -> Void) { let url = "\(offerHostUrl)offers/find" var parameters: [String: Any] = ["latitude": location.latitude , "longitude": location.longitude , "sensor": "\(sensor)" , "radiusInKm": radius / 1000, "includeOnline": false, "perPage": 50] parameters = getFilterParams(filter: filterOptions, combinedWith: parameters) getOffersFromURL(url: url, parameters: parameters, completion: completion) } public func getOfferDetails(_ ids: [Int], location: CLLocationCoordinate2D, sensor: Bool, completion: @escaping ([Coupon]?, Error?) -> Void) { let url = "\(offerHostUrl)offers/get" let idsStr = ids.map(String.init).joined(separator: ",") let parameters: [String: Any] = ["ids": idsStr , "latitude": location.latitude , "longitude": location.longitude , "sensor": "\(sensor)" , "includeOnline": false ] getOffersFromURL(url: url, parameters: parameters, completion: completion) } public func getCategories(completion: @escaping ([CompanyCategory]?, Error?) -> Void) -> Void { let url = "\(offerHostUrl)categories" self.createRequest(.get, url) { json, error in let result = json?.arrayValue.map(self.parseCompanyCategory) completion(result, error) } } public func getRedemptionCode(forOffer offer: Coupon, completion: @escaping (RedemptionCode?, Error?) -> Void) { let url = "\(offerHostUrl)offers/\(offer.id)/code" self.createRequest(.get, url) { (json, error) in // TODO: Process error codes let redemptionCode = json.flatMap { self.parseRedemptionCode(json: $0) } completion(redemptionCode, error) } } public func reportErrorUrl(forOffer offer: Coupon) -> String { let url = "\(offerHostUrl)offers/\(offer.id)/report" if let store = offer.store { return "\(url)?storeId=\(store.id)" } return url } fileprivate func getOffersFromURL(url: String, parameters: [String: Any]? = nil, completion: @escaping ([Coupon]?, Error?) -> Void) { self.createRequest(.get, url, parameters: parameters) { (json, error) in let coupons = json.map { $0.arrayValue.map { json in self.parseCoupon(json: json) } } completion(coupons, error) } } fileprivate func getPaginationParams(pagination: PaginationInfo?, combinedWith parameters: [String: Any]? = nil) -> [String: Any] { var result = parameters ?? [String: Any]() if let pagination = pagination { if let page = pagination.page { result["page"] = page } if let perPage = pagination.perPage { result["perPage"] = perPage } } return result } fileprivate func getFilterParams(filter: FilterOptions?, combinedWith parameters: [String: Any]? = nil) -> [String: Any] { var result = parameters ?? [String: Any]() if let filter = filter { if let query = filter.searchTerm { result["query"] = query } if let tags = filter.tags , tags.count > 0 { result["tags"] = tags.joined(separator: ",") } if let companyId = filter.companyId { result["companyId"] = companyId } if let categoryId = filter.categoryId { result["categoryId"] = categoryId } } return result } fileprivate func parseImage(json: JSON) -> CouponImage? { if (json.isEmpty) { return nil } let sourceUrl = URL(string: json["url"].stringValue) let width = json["width"].float ?? 100 let height = json["height"].float ?? 100 let color = UIColor(fromHexString: json["rgbColor"].stringValue) if let sourceUrl = sourceUrl { return CouponImage(sourceUrl: sourceUrl, width: width, height: height, color: color) } else { return .none } } fileprivate func parseCompany(json: JSON) -> Company { let id = json["id"].intValue let name = json["name"].stringValue let logo = parseImage(json: json["logo"]) return Company(id: id, name: name, logo: logo) } fileprivate func parseCompanyWithCount(json: JSON) -> CompanyWithCount { let id = json["id"].intValue let name = json["name"].stringValue let logo = parseImage(json: json["logo"]) let offerCount = json["offerCount"].intValue return CompanyWithCount(id: id, name: name, logo: logo, offerCount: offerCount) } fileprivate func parseDate(string: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.date(from: string) } fileprivate func parseStore(json: JSON) -> Store? { if (json.isEmpty) { return nil } let id = json["id"].intValue let name = json["name"].string let address = json["address"].string let latitude = json["latitude"].float let longitude = json["longitude"].float return Store(id: id, name: name, address: address, latitude: latitude, longitude: longitude) } fileprivate func parseRedemptionCodeInfo(json: JSON) -> RedemptionCodeInfo? { if (json.isEmpty) { return nil } let totalCodes = json["totalCodes"].int let availableCodes = json["availableCodes"].int let limited = json["limited"].boolValue let alreadyAssigned = json["alreadyAssigned"].boolValue return RedemptionCodeInfo(limited: limited, totalCodes: totalCodes, availableCodes: availableCodes, alreadyAssigned: alreadyAssigned) } fileprivate func parseCoupon(json: JSON) -> Coupon { let id = json["id"].intValue let shortText = json["shortOffer"].stringValue let shortDescription = json["shortDescription"].stringValue let description = json["description"].stringValue let tags = json["tags"].arrayValue.map { $0.stringValue } let online = json["isOnline"].boolValue let link = json["link"].url let expirationDate: Date? = json["expirationDate"].string.map { self.parseDate(string: $0) } ?? .none let thumbnail = parseImage(json: json["thumbnail"]) let image = parseImage(json: json["image"]) let store = parseStore(json: json["store"]) let company = parseCompany(json: json["company"]) let redemptionCodeInfo = parseRedemptionCodeInfo(json: json["redemptionCode"]) return Coupon(id: id, shortText: shortText, shortDescription: shortDescription, description: description, tags: tags, online: online, link: link, expirationDate: expirationDate, thumbnail: thumbnail, image: image, store: store, company: company, redemptionCode: redemptionCodeInfo) } fileprivate func parseRedemptionCode(json: JSON) -> RedemptionCode? { if (json.isEmpty) { return nil } let code = json["code"].stringValue let displayCode = json["displayCode"].stringValue let formats = json["formats"].array?.map { $0.stringValue } ?? [] return RedemptionCode(code: code, displayCode: displayCode, formats: formats) } fileprivate func parseCompanyCategory(json: JSON) -> CompanyCategory { let id = json["id"].intValue let name = json["name"].stringValue let tags = json["tags"].arrayValue.map{ $0.stringValue } let companies = json["companies"].arrayValue.map(parseCompanyWithCount) return CompanyCategory(id: id, name: name, tags: tags, companies: companies) } }
45.630081
289
0.637862
08ebd58c0f8508a13c54737ff40d82869ebcd1fe
5,610
// // CharacteristicBatteryLevelState.swift // BluetoothMessageProtocol // // Created by Kevin Hoogheem on 8/12/17. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import DataDecoder import FitnessUnits /// BLE Battery Level State Characteristic @available(swift 3.1) @available(iOS 10.0, tvOS 10.0, watchOS 3.0, OSX 10.12, *) final public class CharacteristicBatteryLevelState: Characteristic { /// Characteristic Name public static var name: String { "Battery Level State" } /// Characteristic UUID public static var uuidString: String { "2A1B" } /// Name of the Characteristic public var name: String { Self.name } /// Characteristic UUID String public var uuidString: String { Self.uuidString } /// Battery Level /// /// The current charge level of a battery. 100% represents fully charged /// while 0% represents fully discharged. /// private(set) public var level: Measurement<UnitPercent> /// Battery Power State private(set) public var state: BatteryPowerState? /// Creates Battery Level State Characteristic /// /// - Parameters: /// - level: Percent Battery level /// - state: Battery Power State public init(level: Measurement<UnitPercent>, state: BatteryPowerState?) { self.level = level self.state = state } /// Decodes Characteristic Data into Characteristic /// /// - Parameter data: Characteristic Data /// - Returns: Characteristic Result public class func decode<C: Characteristic>(with data: Data) -> Result<C, BluetoothDecodeError> { var decoder = DecodeData() let percent = Double(decoder.decodeUInt8(data)) let level = Measurement(value: percent, unit: UnitPercent.percent) //Might be better to check the size of data.. //but if they are all unknown it is the same as not being there.. var state: BatteryPowerState? let stateValue = decoder.decodeUInt8(data) if stateValue > 0 { state = BatteryPowerState(stateValue) } let char = CharacteristicBatteryLevelState(level: level, state: state) return.success(char as! C) } /// Encodes the Characteristic into Data /// /// - Returns: Characteristic Data Result public func encode() -> Result<Data, BluetoothEncodeError> { guard kBatteryBounds.contains(level.value) else { return.failure(BluetoothEncodeError.boundsError(title: "Battery level must be between", msg: "Percent", range: kBatteryBounds)) } var msgData = Data() msgData.append(Data(from: Int8(level.value))) if let battState = state { msgData.append(battState.rawValue) } return.success(msgData) } } extension CharacteristicBatteryLevelState: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// Implement this method to conform to the `Hashable` protocol. The /// components used for hashing must be the same as the components compared /// in your type's `==` operator implementation. Call `hasher.combine(_:)` /// with each of these components. /// /// - Important: Never call `finalize()` on `hasher`. Doing so may become a /// compile-time error in the future. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. public func hash(into hasher: inout Hasher) { hasher.combine(uuidString) hasher.combine(level) hasher.combine(state) } } extension CharacteristicBatteryLevelState: Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: CharacteristicBatteryLevelState, rhs: CharacteristicBatteryLevelState) -> Bool { return (lhs.uuidString == rhs.uuidString) && (lhs.level == rhs.level) && (lhs.state == rhs.state) } }
36.666667
112
0.63672