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
dd5fa9635f46f5afe3471e3115b495fb4c71ea6c
4,131
import Vapor import AuthProvider import Sessions import HTTP final class Routes: RouteCollection { let view: ViewRenderer //route builder for protected routes let authRoutes : RouteBuilder //route builder for login routes let loginRouteBuilder : RouteBuilder // 1. we need a reference to our droplet to create the routes init(_ view: ViewRenderer,_ drop: Droplet) { //this stays the same self.view = view //create a password middleware with our user let passwordMiddleware = PasswordAuthenticationMiddleware(User.self) //create a memory storage for our sessions let memory = MemorySessions() //create the persis middleware with our User let persistMiddleware = PersistMiddleware(User.self) //create the sessions middleware with our memory let sessionsMiddleware = SessionsMiddleware(memory) //2. now that we have instantiated everthing, all we need to do is create two routes. // the first route is for password protected routes self.authRoutes = drop.grouped([sessionsMiddleware, persistMiddleware, passwordMiddleware]) // the second one is to login, We need this route to have the sessions and persist middleware in place to store // that a user has logged in and give him a vapor access token which he can use in the upcoming requests self.loginRouteBuilder = drop.grouped([sessionsMiddleware, persistMiddleware]) //1. Modify this controller to be built by "authRoutes" to protect all it's routes /// GET /hello/... authRoutes.resource("hello", HelloController(view)) //3. implement the login logic, built by the "loginRouteBuilder" so our session is persisted loginRouteBuilder.post("login") { req in guard let email = req.formURLEncoded?["email"]?.string, let password = req.formURLEncoded?["password"]?.string else { return "Bad credentials" } //create a Password object with email and password let credentials = Password(username: email, password: password) //User.authenticate queries the user by username and password and informs the middlewar that this user is now authenticated //the middleware creates a session token, ties it to the user and sends it in a cookie to the client. //the requests done with this request token automatically are authenticated with this user. do { let user = try User.authenticate(credentials) req.auth.authenticate(user) //redirect to the protected route /hello return Response(redirect: "hello") } catch let error { return try JSON(node: [ "Error": "Wrong email or password for \(email)", "Message": "\(error.localizedDescription)" ]) } } } func build(_ builder: RouteBuilder) throws { /// GET / builder.get { req in return try self.view.make("welcome") } //2. create the login route builder.get("login") { req in return try self.view.make("login") } builder.get("register") { req in return try self.view.make("register") } builder.post("register") { req in if let name = req.formURLEncoded?["name"]?.string, !name.isEmpty, let email = req.formURLEncoded?["email"]?.string, !email.isEmpty, let password = req.formURLEncoded?["password"]?.string, !password.isEmpty{ let user = User(name: name, email: email, password: password) try user.save() } return "success" } /// GET /hello/... builder.resource("hello", HelloController(view)) } }
40.5
135
0.59114
0335b8ec23ce17798a326088c1ade0a1b572ee6f
463
// // AppDelegate.swift // ArrowExample // // Created by Sacha Durand Saint Omer on 6/7/15. // Copyright (c) 2015 Sacha Durand Saint Omer. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Usage.show() return true } }
21.045455
127
0.708423
fe27e6936c8e68d10bdbcc7274e69f4929200387
1,105
// // PlayerVC.swift // TestCode // // Created by Anil Prasad on 10/17/18. // Copyright © 2018 Anil Prasad. All rights reserved. // import Foundation import UIKit class PlayerVC { init() { saveUserdefaults() loadUserdefaults() // Get Plist path #if arch(i386) || arch(x86_64) if let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.path { print("Document Directory: \(documentsPath)") // This file is in binary format. } #endif } func saveUserdefaults() { let player = Player(name: "Jamal Khan", highScore: 323) UserDefaults.standard.set(try? PropertyListEncoder().encode(player), forKey: "player") } func loadUserdefaults() { guard let playerData = UserDefaults.standard.object(forKey: "player") as? Data else { return } guard let player = try? PropertyListDecoder().decode(Player.self, from: playerData) else { return } print(player.name) } }
28.333333
119
0.59457
4884c71ff9eba81c8c155bbd9fc7d3f0848c2992
1,961
import Foundation import BigInt import SoraFoundation import SubstrateSdk final class AcalaContributionConfirmPresenter: CrowdloanContributionConfirmPresenter { let contributionMethod: AcalaContributionMethod init( contributionMethod: AcalaContributionMethod, interactor: CrowdloanContributionConfirmInteractorInputProtocol, wireframe: CrowdloanContributionConfirmWireframeProtocol, balanceViewModelFactory: BalanceViewModelFactoryProtocol, contributionViewModelFactory: CrowdloanContributionViewModelFactoryProtocol, dataValidatingFactory: CrowdloanDataValidatorFactoryProtocol, inputAmount: Decimal, bonusRate: Decimal?, assetInfo: AssetBalanceDisplayInfo, explorers: [ChainModel.Explorer]?, localizationManager: LocalizationManagerProtocol, logger: LoggerProtocol? = nil ) { self.contributionMethod = contributionMethod super.init( interactor: interactor, wireframe: wireframe, balanceViewModelFactory: balanceViewModelFactory, contributionViewModelFactory: contributionViewModelFactory, dataValidatingFactory: dataValidatingFactory, inputAmount: inputAmount, bonusRate: bonusRate, assetInfo: assetInfo, localizationManager: localizationManager, explorers: explorers, logger: logger ) } override func didReceiveMinimumContribution(result: Result<BigUInt, Error>) { switch result { case .success: switch contributionMethod { case .liquid: minimumContribution = BigUInt(1e+10) provideAssetVewModel() case .direct: super.didReceiveMinimumContribution(result: result) } case .failure: super.didReceiveMinimumContribution(result: result) } } }
36.314815
86
0.682815
762c80890f5dad56b74da57cfba4a2e9007f56a0
2,494
// // AppMiniCell.swift // TopMiniApps // // Created by Pedro Albuquerque on 08/11/19. // Copyright © 2019 Soluevo. All rights reserved. // import UIKit import AlamofireImage @available(iOS 8.2, *) @available(iOS 9.0, *) class SLAppMiniCell: UICollectionViewCell { var miniApp: SLMiniApp? { didSet{ self.icon.image = miniApp?.icon if let urlStr = miniApp?.iconUrl, let url = URL(string: urlStr) { self.icon.af_setImage(withURL: url) } self.title.text = miniApp?.title } } lazy var icon: UIImageView = { let icon = UIImageView(frame: .zero) icon.translatesAutoresizingMaskIntoConstraints = false icon.contentMode = .scaleAspectFit icon.clipsToBounds = true return icon }() lazy var title: UILabel = { let title = UILabel(frame: .zero) title.translatesAutoresizingMaskIntoConstraints = false title.font = UIFont.systemFont(ofSize: 10, weight: .semibold) title.textAlignment = .center title.textColor = #colorLiteral(red: 0.6392156863, green: 0.6352941176, blue: 0.631372549, alpha: 1) title.numberOfLines = 1 return title }() override init(frame: CGRect) { super.init(frame: frame) self.clipsToBounds = true self.loadSubViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func loadSubViews(){ self.addSubview(icon) icon.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true icon.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true icon.heightAnchor.constraint(equalToConstant: 60).isActive = true icon.widthAnchor.constraint(equalToConstant: 60).isActive = true icon.layer.cornerRadius = 30 icon.layer.borderColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) icon.layer.borderWidth = 1 self.addSubview(title) title.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true title.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true title.topAnchor.constraint(equalTo: self.icon.bottomAnchor, constant: 5).isActive = true // title.heightAnchor.constraint(equalToConstant: 30).isActive = true } }
34.164384
116
0.64595
6af6ce3e18176914dcb9c179361426bf66743935
7,145
// // AVACRNTonePlayerUnit.swift // Tinitus Buddy // // Created by Thomas Sorensen on 2/15/21. // import Foundation import AVFoundation class AVACRNTonePlayerNode: AVAudioPlayerNode { // Mark - Constants let bufferCapacity: AVAudioFrameCount = 512 * 4 let NumberOfTimesToRepeatTones = 4 let NumberOfToneSequences = 20 let SilenceTimeBetweenTones = 0.01 let SilenceTimeBetweenSeqences = 1.4 let ToneLength = 0.15 // each tone is played for 0.15s let useFixedTonePattern = false // Contains current Tone being Generated // When Empty, then tone should be pop'd from ToneList private var toneBuffer = [Float]() // List of tones private var toneList = [Double]() // Pointer to currently playing tone in toneList private(set) var currentToneIndex = 0 // Current Theta (will be updated for each generated sample) private var theta: Double = 0.0 private(set) var audioFormat: AVAudioFormat! init(withBaseTone:Double, audioFormat:AVAudioFormat) { super.init() self.audioFormat = audioFormat InitializeToneSequence(withBaseTone: withBaseTone) } private func prepareBuffer() -> AVAudioPCMBuffer { let buffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: bufferCapacity)! fillBuffer(buffer) return buffer } func fillBuffer(_ buffer: AVAudioPCMBuffer) { let data = buffer.floatChannelData?[0] let numberFrames = buffer.frameCapacity for frame in 0..<Int(numberFrames) { if (toneBuffer.count == 0) { LoadNextToneIntoBuffer() } data?[frame] = toneBuffer.popLast()! } buffer.frameLength = numberFrames } func scheduleBuffer() { let buffer = prepareBuffer() self.scheduleBuffer(buffer) { if self.isPlaying { self.scheduleBuffer() } } } override func play() { preparePlaying() super.play() } private func preparePlaying() { for _ in 0..<3 { scheduleBuffer() } } func InitializeToneSequence(withBaseTone baseFreq : Double) { if useFixedTonePattern { // FIXME: This tone sequence came from the original post about the approach based on the official app // The frequencies spans much wider, need to investigate.. maybe make an option to select??? generateFixedToneSequence(withBaseTone: baseFreq) } else { // This is the approach from https://github.com/headphonejames/acrn-react // Frequencies are much closer to baseTone. Which one is correct?? generateRandomToneSequence(withBaseTone: baseFreq) } } private func generateRandomToneSequence(withBaseTone baseFreq: Double) { var tones = [floor(baseFreq * 0.773 - 44.5), floor(baseFreq * 0.903 - 21.5), floor(baseFreq * 1.09 + 52), floor(baseFreq * 1.395 + 26.5)]; let silence = 0.0 toneList.removeAll() for _ in 0...NumberOfToneSequences { for _ in 0...NumberOfTimesToRepeatTones { tones.shuffle() toneList.append(contentsOf: tones) } toneList.append(silence) } } private func generateFixedToneSequence(withBaseTone baseFreq: Double) { let tones = [baseFreq - 900.0,baseFreq - 400.0,baseFreq + 400.0, baseFreq + 1500.0] let silence = 0.0 toneList.removeAll() // Sequence 2 for n in [1,2,3,4,4,2,1,3,4,3,2,1] { toneList.append(tones[n-1]) } toneList.append(silence) // Sequence 3 for n in [2,4,1,3,4,2,1,3,4,3,2,1] { toneList.append(tones[n-1]) } toneList.append(silence) // Sequence 3 for n in [3,2,4,1,4,2,1,3,1,4,2,2] { toneList.append(tones[n-1]) } toneList.append(silence) // Sequence 4 for n in [2,3,4,1,1,2,4,3,4,3,2,1] { toneList.append(tones[n-1]) } toneList.append(silence) // Sequence 5 for n in [1,3,2,4,4,2,3,1,4,1,3,2] { toneList.append(tones[n-1]) } toneList.append(silence) // Sequence 6 for n in [2,3,4,1,4,1,3,2,2,4,3,1] { toneList.append(tones[n-1]) } toneList.append(silence) // Sequence 7 for n in [2,3,4,1,3,1,2,4,1,2,4,3] { toneList.append(tones[n-1]) } toneList.append(silence) // Sequence 8 for n in [1,2,4,3,4,3,1,2,1,4] { toneList.append(tones[n-1]) } toneList.append(silence) } func LoadNextToneIntoBuffer() { if currentToneIndex == toneList.count-1 { currentToneIndex = 0 } else { currentToneIndex += 1 } GenerateToneData(toneFreq: toneList[currentToneIndex]) } func GenerateToneData(toneFreq : Double) { // Amplitude: I did 0.5 (closest match to the sample) // 0.07 Fade in, 0.07 Fade out // 12 tones then 1.4 second silence // silense is 0 frequency in the array if (toneFreq == 0) { // Silence // After 12 tones we need to generate silent frames // We need to generate 1.4 seconds of Silence let numberFrames = Int(audioFormat.sampleRate * SilenceTimeBetweenSeqences) for _ in 0..<Int(numberFrames) { toneBuffer.append(Float(0)) } } else { // Duration: 0.15 seconds let numberFrames = Int(audioFormat.sampleRate * ToneLength) // How much tone change in tone wave value over each sample let theta_increment = 2.0 * .pi * toneFreq / audioFormat.sampleRate // Calculate fadein/fadeout let maxAmplitude = 0.5 let amplitudeFadeOut = Int(numberFrames / 2) let amplitudeChange = maxAmplitude / Double(amplitudeFadeOut) var frameAplitude = 0.0 for frame in 0..<Int(numberFrames) { if (frame < amplitudeFadeOut) { frameAplitude += amplitudeChange // Fade in } else { frameAplitude -= amplitudeChange // Fade out } toneBuffer.append(Float(sin(theta) * frameAplitude)) theta += theta_increment if theta > 2.0 * .pi { theta -= 2.0 * .pi } } // make 0.01 seconds silence after each tone let numberOfSilenceFrames = Int(audioFormat.sampleRate * SilenceTimeBetweenTones) for _ in 0..<Int(numberOfSilenceFrames) { toneBuffer.append(Float(0)) } } } }
31.897321
113
0.552834
eb04d98a14ba58896cedf92bff67f0a6cdfaae9f
504
// // Candy+CoreDataProperties.swift // CoreDataProject // // Created by SUPER on 2021/7/30. // // import Foundation import CoreData extension Candy { @nonobjc public class func fetchRequest() -> NSFetchRequest<Candy> { return NSFetchRequest<Candy>(entityName: "Candy") } @NSManaged public var name: String? public var wrappedName: String { name ?? "Unknown Candy" } @NSManaged public var origin: Country? } extension Candy : Identifiable { }
15.75
72
0.654762
f836e48c1dfa9aab6d484634caafdca4ea08350f
368
// // BetshopDetailsViewControllerDelegate.swift // Betshops // // Created by Matija Kruljac on 3/30/19. // Copyright © 2019 Matija Kruljac. All rights reserved. // import Foundation import CoreLocation protocol BetshopDetailsViewControllerDelegate: class { func didTapCloseButton() func didTapRouteButton(betshopLocation: CLLocationCoordinate2D) }
21.647059
67
0.769022
1cf011e7b8ab7abadb6ff1b7d5da8df8694eb926
270
// // SourceModel.swift // News-App // // Created by Bakhtovar Umarov on 21/08/21. // import Foundation struct Sources: Codable { var sources: [SourceModel] } struct SourceModel: Codable { let id: String? let name: String? let category: String? }
14.210526
44
0.655556
e0d22d883c11cd598a4a977011a2025daf022984
923
// // IssueCommentDraft.swift // Cashew // // Created by Hicham Bouabdallah on 7/13/16. // Copyright © 2016 SimpleRocket LLC. All rights reserved. // import Cocoa @objc(SRIssueCommentDraftType) enum IssueCommentDraftType: NSInteger { case issue case comment } @objc(SRIssueCommentDraft) class IssueCommentDraft: NSObject { let account: QAccount let repository: QRepository let issueCommentId: NSNumber? let issueNumber: NSNumber @objc let body: String let type: IssueCommentDraftType @objc required init(account: QAccount, repository: QRepository, issueCommentId: NSNumber?, issueNumber: NSNumber, body: String, type: IssueCommentDraftType) { self.account = account self.repository = repository self.issueCommentId = issueCommentId self.issueNumber = issueNumber self.body = body self.type = type super.init() } }
24.945946
162
0.699892
288ef1bb6c4be81a0f3d17e15fffc6ad254b1187
598
// // extensions.swift // Sompa // // Created by Park Seyoung on 28/10/16. // Copyright © 2016 Park Seyoung. All rights reserved. // import Foundation import UIKit extension UIViewController { // func set } extension UINavigationControllerDelegate { } extension UINavigationController: UINavigationControllerDelegate { public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { print("Show vc") viewController.navigationItem.title = viewController.tabBarItem.title } }
21.357143
145
0.742475
610afd82342be8366f163eb1b6888c28b24abda0
1,787
import AppKit import JavaScriptCore import Quartz import AVKit import CoreMedia import CoreSpotlight import CoreImage import CoreGraphics import Quartz // Interface /** - Selector: QuartzFilter */ @objc(QuartzFilter) protocol QuartzFilterExports: JSExport, NSObjectExports { // Static Methods /** - Selector: quartzFilterWithOutputIntents: */ @objc static func createWithOutputIntents(_ outputIntents: [Any]) -> QuartzFilter /** - Selector: quartzFilterWithProperties: */ @objc static func createWithProperties(_ properties: [AnyHashable: Any]) -> QuartzFilter /** - Selector: quartzFilterWithURL: */ @objc static func createWithUrl(_ url: URL) -> QuartzFilter // Instance Methods /** - Selector: applyToContext: */ @objc (applyToContext:) func apply(to: CGContext) -> Bool /** - Selector: localizedName */ @objc func localizedName() -> String /** - Selector: properties */ @objc func properties() -> [AnyHashable: Any] /** - Selector: removeFromContext: */ @objc (removeFromContext:) func remove(from: CGContext) /** - Selector: url */ @objc func url() -> URL } extension QuartzFilter: QuartzFilterExports { /** - Selector: quartzFilterWithOutputIntents: */ @objc public static func createWithOutputIntents(_ outputIntents: [Any]) -> QuartzFilter { return self.init(outputIntents: outputIntents) } /** - Selector: quartzFilterWithProperties: */ @objc public static func createWithProperties(_ properties: [AnyHashable: Any]) -> QuartzFilter { return self.init(properties: properties) } /** - Selector: quartzFilterWithURL: */ @objc public static func createWithUrl(_ url: URL) -> QuartzFilter { return self.init(url: url) } }
20.078652
99
0.686626
692fc4b67453bcddf4959e2332d430282b5aaedc
1,632
class Solution { // Solution @ Sergey Leschev, Belarusian State University // 1854. Maximum Population Year // You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. // The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. // Return the earliest year with the maximum population. // Example 1: // Input: logs = [[1993,1999],[2000,2010]] // Output: 1993 // Explanation: The maximum population is 1, and 1993 is the earliest year with this population. // Example 2: // Input: logs = [[1950,1961],[1960,1971],[1970,1981]] // Output: 1960 // Explanation: // The maximum population is 2, and it had happened in years 1960 and 1970. // The earlier year between them is 1960. // Constraints: // 1 <= logs.length <= 100 // 1950 <= birthi < deathi <= 2050 func maximumPopulation(_ logs: [[Int]]) -> Int { var lifePeriods = [Int](repeating: 0, count: 105) var total = 0 var ans: (year:Int, num: Int) = (-1,-1) for log in logs { lifePeriods[log[0] - 1950] += 1 lifePeriods[log[1] - 1950] -= 1 } for year in 1950...2050 { total += lifePeriods[year - 1950] if total > ans.num { ans.year = year ans.num = total } } return ans.year } }
34.723404
249
0.593137
ab9a77243e34ee29aea343069d4ecf94a98206f8
1,559
// // TabBar.swift // InstaPosts // // Created by InnAppsCoding on 02/08/2020. // Copyright © 2020 InnAppsCoding. All rights reserved. // import SwiftUI struct Bar: Shape { var tab: CGFloat var animatableData: Double { get { return Double(tab) } set { tab = CGFloat(newValue) } } func path(in rect: CGRect) -> Path { var path = Path() let widthFactor = rect.maxX/(CGFloat(TabItems.shared.items.count) + 1) let widthFactorTimesCount = (rect.maxX/(CGFloat(TabItems.shared.items.count) + 1)) * tab path.move(to: CGPoint(x: rect.minX, y: rect.minY)) path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) path.addLine(to: CGPoint(x: widthFactorTimesCount + widthFactor, y: rect.minY)) path.addCurve(to: CGPoint(x: widthFactorTimesCount, y: rect.midY), control1: CGPoint(x: widthFactorTimesCount + 40, y: rect.minY), control2: CGPoint(x: widthFactorTimesCount + 40, y: rect.minY + 50)) path.addCurve(to: CGPoint(x: widthFactorTimesCount - widthFactor, y: rect.minY), control1: CGPoint(x: widthFactorTimesCount - 40, y: rect.minY + 50), control2: CGPoint(x: widthFactorTimesCount - 40, y: rect.minY)) path.addLine(to: CGPoint(x: rect.maxX - widthFactorTimesCount, y: rect.minY)) return path } }
38.02439
96
0.606158
f50ddf3e83dc6cad6256c116830cb1a1d758c135
163
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(MacShellSwiftTests.allTests), ] } #endif
16.3
46
0.680982
1ea562b20aadbd3ea1f037f21956b9df6c717c4f
508
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: %target-swift-frontend %s -emit-silgen // Test case submitted to project by https://github.com/airspeedswift (airspeedswift) ["1"].map { String($0) }
42.333333
85
0.744094
ac7ddbb8fcbf41b7ef94432a86def134df876f9a
434
// // ADViewMoel.swift // SwiftIoC_Example // // Created by imacN24 on 2022/3/11. // Copyright © 2022 CocoaPods. All rights reserved. // import Foundation class ADViewModel:BaseViewModel { var userName:String init(name:String) { userName = name } func speakMyName() { print("my name is \(userName)") } override func function1() { print("my name is \(userName)") } }
16.074074
52
0.601382
69d1055035542a80b7562b6cf1bd485da316c0c4
1,205
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "VaporSpices", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "VaporSpices", targets: ["VaporSpices"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"), .package(url: "https://github.com/vapor/fluent.git", from: "3.0.0-rc") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "VaporSpices", dependencies: [ "Vapor", "Fluent" ]), .testTarget( name: "VaporSpicesTests", dependencies: [ "VaporSpices" ]), ] )
35.441176
122
0.6
5bea62e58e0c29a92cf612566e1c4ff62846885c
10,423
// // File.swift // // // Created by Yannick Heinrich on 11.03.21. // import Foundation import CoreLocation // MARK: - Cancellable /// A `Cancellable` action @objc public protocol Cancellable { /// Cancel the current operation func cancel() } /// :nodoc: extension Operation: Cancellable { } // MARK: - Client /// A client object that can query the `Chargeprice` API. @objcMembers public final class ChargepriceClient: NSObject { /// The errors returned during API calls. public enum ClientError: Error { /// Failed due to network case network(Error) /// API returns an error case apiError([ErrorObject]) /// Unexpected empty data case emptyData /// Unexpected empty included case emptyIncluded } // MARK: - Concurrency let queue: OperationQueue = { let queue = OperationQueue() queue.maxConcurrentOperationCount = 10 queue.qualityOfService = .utility return queue }() private let key: String public init(key: String) { self.key = key super.init() } // MARK: - Internals | Networking private func createRequestOperation<End, Body, Encoding, ResponseBody, Decoding>(endpoint: End, encoding: CodingPart<Body, Encoding>?, decoding: Decoding?, completionCall: @escaping (Result<ResponseBody, Error>) -> Void) -> Operation where End: Endpoint, Encoding: FormatEncoder, Decoding: FormatDecoder, Body: Encodable, ResponseBody: Decodable { let operation = RequestOperation(apiKey: self.key, endpoint: endpoint, encoding: encoding, decoding: decoding, completionCall: completionCall) return operation } // MARK: - Internals | JSONSpec func getJSONSpec<End, Request, Data, Meta, Included>(endpoint: End, request: Request?, completion: @escaping (Result<OkDocument<Data, Meta, Included>, ClientError>) -> Void) -> Operation where End: Endpoint, Request: Encodable, Data: Decodable, Meta: Decodable, Included: Decodable { let decoding = JSONDecoder() let completion = { (result: Result<Document<Data, Meta, Included>, Error>) in switch result { case .failure(let error): completion(.failure(ClientError.network(error))) case .success(let document): // NOTE: We still needs to check other cases from the specs if let error = document.errors { completion(.failure(.apiError(error))) } else { completion(.success(OkDocument(data: document.data, meta: document.meta, included: document.included))) } } } if let request = request { let encoding = CodingPart(body: request, coding: JSONEncoder()) return self.createRequestOperation(endpoint: endpoint, encoding: encoding, decoding: decoding, completionCall: completion) } else { return self.createRequestOperation(endpoint: endpoint, encoding: NoCodingPart, decoding: decoding, completionCall: completion) } } // MARK: - Public API func getVehiculesOperation(completion: @escaping (Result<[Vehicule], ClientError>) -> Void) -> Operation { let operation = self.getJSONSpec(endpoint: API.vehicules, request: NoCodingPartBody) { (result: Result<OkDocument<[ResourceObject<VehiculeAttributes, JSONSpecRelationShip<ManufacturerAttributes>>], NoData, NoData>, ClientError>) in switch result { case .failure(let error): completion(.failure(error)) case .success(let document): guard let data = document.data else { completion(.failure(.emptyData)) return } let converted = data.map(Vehicule.init) completion(.success(converted)) } } return operation } /// Load the vehicules /// - Parameter completion: The completion /// - Returns: A `Cancellable` element @discardableResult public func getVehicules(completion: @escaping (Result<[Vehicule], ClientError>) -> Void) -> Cancellable { let operation = self.getVehiculesOperation(completion: completion) self.queue.addOperation(operation) return operation } func getChargingStationOperation(topLeft: CLLocationCoordinate2D, bottomRight: CLLocationCoordinate2D, freeCharging: Bool? = nil, freeParking: Bool? = nil, power: Float? = nil, plugs: [Plug]? = nil, operatorID: String? = nil, completion: @escaping (Result<ChargingStationResponse, ClientError>) -> Void) -> Operation { let endpoint = API.chargingStations(topLeft: topLeft, bottomRight: bottomRight, freeCharging: freeCharging, freeParking: freeParking, power: power, plugs: plugs, operatorID: operatorID) let operation = self.getJSONSpec(endpoint: endpoint, request: NoCodingPartBody) { (result: Result<OkDocument<[ResourceObject<ChargingStationAttributes, JSONSpecRelationShip<OperatorAttributes>>], ChargingStationMeta, [ResourceObject<CompanyAttributes, NoData>]>, ClientError>) in switch result { case .failure(let error): completion(.failure(error)) case .success(let document): guard let data = document.data else { completion(.failure(.emptyData)) return } guard let included = document.included else { completion(.failure(.emptyIncluded)) return } let attributes = included.reduce(into: [String: CompanyAttributes](), { $0[$1.id] = $1.attributes }) let converted = data.map { ChargingStation(obj: $0, dict: attributes) } let response = ChargingStationResponse(stations: converted, disableGoingElectrics: document.meta!.countries) completion(.success(response)) } } return operation } /// Get the charging stations /// - Parameters: /// - topLeft: The topleft coordinate /// - bottomRight: The bottom right coordinate /// - freeCharging: Filter by free charging /// - freeParking: Filter by free parking /// - power: Filter by power /// - plugs: Filter by plugs /// - operatorID: filter by operatorID /// - completion: The compltion block /// - Returns: A `Cancellable` element @discardableResult public func getChargingStation(topLeft: CLLocationCoordinate2D, bottomRight: CLLocationCoordinate2D, freeCharging: Bool? = nil, freeParking: Bool? = nil, power: Float? = nil, plugs: [Plug]? = nil, operatorID: String? = nil, completion: @escaping (Result<ChargingStationResponse, ClientError>) -> Void) -> Cancellable { let operation = getChargingStationOperation(topLeft: topLeft, bottomRight: bottomRight, freeCharging: freeCharging, freeParking: freeParking, power: power, plugs: plugs, operatorID: operatorID, completion: completion) self.queue.addOperation(operation) return operation } func getTarrifsOperation(isDirectPayment: Bool? = nil, isProviderCustomerOnly: Bool? = nil, completion: @escaping (Result<[Tariff], ClientError>) -> Void) -> Operation { let endpoint = API.tariff(isDirectPayment: isDirectPayment, isProviderCustomerOnly: isProviderCustomerOnly) let operation = getJSONSpec(endpoint: endpoint, request: NoCodingPartBody) { (result: Result<OkDocument<[ResourceObject<TariffAttributes, NoData>], NoData, NoData>, ClientError>) in switch result { case .failure(let error): completion(.failure(error)) case .success(let document): guard let data = document.data else { completion(.failure(.emptyData)) return } let elements = data.map(Tariff.init) completion(.success(elements)) } } return operation } /// Get the tarrifs /// - Parameters: /// - isDirectPayment: Filter by direct payment /// - isProviderCustomerOnly: Filter by provider customer only /// - completion: The completion block /// - Returns: A `Cancellable` element @discardableResult public func getTarrifs(isDirectPayment: Bool? = nil, isProviderCustomerOnly: Bool? = nil, completion: @escaping (Result<[Tariff], ClientError>) -> Void) -> Cancellable { let operation = getTarrifsOperation(completion: completion) self.queue.addOperation(operation) return operation } }
42.717213
288
0.537177
030b2e7b2c6bbeb82a9444a1ec103fb62c1f943a
1,928
// // AddItemView.swift // shoppingList // // Created by Damian Pasko on 2019/12/05. // Copyright © 2019 Damian Pasko. All rights reserved. // import SwiftUI struct AddItemView: View { @EnvironmentObject private var store: AppStore @State private var nameText: String = "" @State private var priorityField: Priority = .medium @State private var dateField: Date = Date() @Binding var isAddingMode: Bool var body: some View { NavigationView { Form { TextField("Name", text: $nameText) Picker(selection: $priorityField, label: Text("Priority")) { Text("Low").tag(Priority.low) Text("Medium").tag(Priority.medium) Text("High").tag(Priority.high) } DatePicker(selection: $dateField, displayedComponents: .date) { Text("Date") } } .navigationBarTitle("Item Details", displayMode: .inline) .navigationBarItems( leading: Button(action: { self.isAddingMode = false }) { Text("Cancel") }, trailing: Button(action: { let item = Item( name: self.nameText, date: self.dateField, priority: self.priorityField ) self.store.dispatch(action: .addItem(item: item)) self.isAddingMode = false }) { Text("Save") } .disabled(nameText.isEmpty) ) } } } struct AddItemView_Previews: PreviewProvider { static var previews: some View { AddItemView(isAddingMode: Binding.constant(false)) .environmentObject(AppStore()) } }
31.096774
79
0.498963
bfd68bffdc979a9a0ae9c937e99c2442df46376a
2,072
/********************************************* * * This code is under the MIT License (MIT) * * Copyright (c) 2016 AliSoftware * *********************************************/ import UIKit // MARK: Protocol Definition /// Make your UIView subclasses conform to this protocol when: /// * they *are* NIB-based, and /// * this class is used as the XIB's File's Owner /// /// to be able to instantiate them from the NIB in a type-safe manner public protocol NibOwnerLoadable: class { /// The nib file to use to load a new instance of the View designed in a XIB static var nib: UINib { get } } // MARK: Default implementation public extension NibOwnerLoadable { /// By default, use the nib which have the same name as the name of the class, /// and located in the bundle of that class static var nib: UINib { return UINib(nibName: String(describing: self), bundle: Bundle(for: self)) } } // MARK: Support for instantiation from NIB public extension NibOwnerLoadable where Self: UIView { /** Returns a `UIView` object instantiated from nib - parameter owner: The instance of the view which will be your File's Owner (and to which you want to add the XIB's views as subviews). Defaults to a brand new instance if not provided. - returns: A `NibOwnLoadable`, `UIView` instance */ @discardableResult static func loadFromNib(owner: Self = Self()) -> Self { let layoutAttributes: [NSLayoutConstraint.Attribute] = [.top, .leading, .bottom, .trailing] for view in nib.instantiate(withOwner: owner, options: nil) { if let view = view as? UIView { view.translatesAutoresizingMaskIntoConstraints = false owner.addSubview(view) layoutAttributes.forEach { attribute in owner.addConstraint(NSLayoutConstraint(item: view, attribute: attribute, relatedBy: .equal, toItem: owner, attribute: attribute, multiplier: 1, constant: 0.0)) } } } return owner } }
31.876923
95
0.628861
4a5d99e13d0cb051d14d6275aef56ef8f5eab340
857
// // Theme.swift // Zakkuri // // Created by mironal on 2019/09/23. // Copyright © 2019 mironal. All rights reserved. // import UIKit public struct Theme { let baseColor: UIColor let secondColor: UIColor let accentColor: UIColor public static let defailt = Theme(baseColor: UIColor(hexString: "5289FF")!, secondColor: UIColor(hexString: "2753B3")!, accentColor: UIColor(hexString: "FF836B")!) } class ThemeAppier { let theme: Theme = Theme.defailt func apply() { UISlider.appearance().tintColor = theme.baseColor UINavigationBar.appearance().barTintColor = theme.baseColor UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white] UINavigationBar.appearance().tintColor = .white } }
26.78125
92
0.635939
e07fbde7b2128a5c98e7229b61d5fe393ebeaf4e
515
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "Zeitgeist", platforms: [ .iOS(.v13) ], products: [ .library( name: "Zeitgeist", targets: ["Zeitgeist"]), ], dependencies: [ ], targets: [ .target( name: "Zeitgeist", dependencies: []), .testTarget( name: "ZeitgeistTests", dependencies: ["Zeitgeist"]), ], swiftLanguageVersions: [.v5] )
19.074074
41
0.493204
0a58097fa1aa381c7af2ef14a6d7ab00b28cfa39
257
import Foundation struct PayoutsInfo { let activeEra: EraIndex let historyDepth: UInt32 let payouts: [PayoutInfo] } struct PayoutInfo { let era: EraIndex let validator: Data let reward: Decimal let identity: AccountIdentity? }
17.133333
34
0.708171
79d9c315b89817106958e3c3a71545539815562f
4,325
// // ATSmartBezierPath+RecognizerTemplates.swift // ATSketchKit // // Created by Arnaud Thiercelin on 1/8/16. // Copyright © 2016 Arnaud Thiercelin. 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 extension ATSmartBezierPath { func loadTemplates() { let pathToTemplates = (Bundle(identifier: "com.arnaudthiercelin.ATSketchKit")?.bundlePath)! + "/Templates" do { let templateFiles = try FileManager.default.contentsOfDirectory(atPath: pathToTemplates) for filePath in templateFiles { let newTemplate = ATUnistrokeTemplate(json: filePath) self.unistrokeTemplates.append(newTemplate) } } catch { print("Error trying to load templates - \(error)") } } // func createCircleTemplates() { // let templateName = "Circle" // let newTemplate = ATUnistrokeTemplate() // newTemplate.name = templateName // newTemplate.recognizedPathWithRect = { (rect: CGRect) -> UIBezierPath in // let maxValue = rect.size.height > rect.size.width ? rect.size.height : rect.size.width // let circleRect = CGRect(x: rect.origin.x, y: rect.origin.y, width: maxValue, height: maxValue) // // return UIBezierPath(ovalIn: circleRect) // } // newTemplate.points = [CGPoint(x: 43.5, y: 12.0)) // CGPoint(x: 42.5, y: 12.0)) // CGPoint(x: 41.0, y: 12.0)) // CGPoint(x: 37.0, y: 12.0)) // CGPoint(x: 32.5, y: 12.0)) // CGPoint(x: 24.5, y: 12.0)) // CGPoint(x: 20.0, y: 13.5)) // CGPoint(x: 14.0, y: 20.5)) // CGPoint(x: 10.0, y: 27.5)) // CGPoint(x: 4.0, y: 35.0)) // CGPoint(x: 2.5, y: 42.0)) // CGPoint(x: 0.0, y: 53.0)) // CGPoint(x: 0.0, y: 57.5)) // CGPoint(x: 0.0, y: 60.0)) // CGPoint(x: 0.0, y: 68.0)) // CGPoint(x: 0.0, y: 75.0)) // CGPoint(x: 0.0, y: 82.0)) // CGPoint(x: 0.0, y: 87.5)) // CGPoint(x: 1.0, y: 97.0)) // CGPoint(x: 5.0, y: 104.0)) // CGPoint(x: 10.5, y: 109.5)) // CGPoint(x: 21.0, y: 117.0)) // CGPoint(x: 29.5, y: 121.5)) // CGPoint(x: 42.0, y: 125.5)) // CGPoint(x: 52.0, y: 129.0)) // CGPoint(x: 62.0, y: 130.5)) // CGPoint(x: 77.0, y: 130.5)) // CGPoint(x: 87.0, y: 130.5)) // CGPoint(x: 95.5, y: 129.0)) // CGPoint(x: 108.0, y: 122.0)) // CGPoint(x: 111.0, y: 119.5)) // CGPoint(x: 117.5, y: 103.5)) // CGPoint(x: 117.5, y: 92.5)) // CGPoint(x: 120.0, y: 76.0)) // CGPoint(x: 121.5, y: 70.5)) // CGPoint(x: 121.5, y: 60.0)) // CGPoint(x: 121.5, y: 42.0)) // CGPoint(x: 121.5, y: 34.0)) // CGPoint(x: 120.5, y: 28.0)) // CGPoint(x: 116.5, y: 21.5)) // CGPoint(x: 112.5, y: 15.5)) // CGPoint(x: 107.0, y: 11.5)) // CGPoint(x: 97.0, y: 7.0)) // CGPoint(x: 90.0, y: 4.0)) // CGPoint(x: 83.0, y: 3.0)) // CGPoint(x: 72.5, y: 1.5)) // CGPoint(x: 65.5, y: 0.0)) // CGPoint(x: 58.5, y: 0.0)) // CGPoint(x: 54.0, y: 0.0)) // CGPoint(x: 48.5, y: 0.0)) // CGPoint(x: 43.0, y: 0.0)) // CGPoint(x: 38.5, y: 0.0)) // CGPoint(x: 35.5, y: 0.0)) // CGPoint(x: 33.0, y: 1.5)) // CGPoint(x: 30.5, y: 4.0)) // CGPoint(x: 27.5, y: 5.5)) // CGPoint(x: 26.5, y: 8.0)) // CGPoint(x: 26.5, y: 9.0)) // ] // // self.unistrokeTemplates.append(newTemplate) //} }
36.652542
112
0.597457
b9d583ba3099fd6c05257282a884fa577d1c1cf9
962
import UIKit public final class RootTransition: NSObject, PresentableTransition { // MARK: - Properties private weak var window: UIWindow? private let options: UIView.AnimationOptions private let duration: TimeInterval // MARK: - Inits public init(window: UIWindow, options: UIView.AnimationOptions = .transitionCrossDissolve, duration: TimeInterval = 0.2) { self.window = window self.options = options self.duration = duration } // MARK: - PresentableTransition public func present(_ viewController: UIViewController, animated: Bool, completion: Completion?) { guard let window = window else { return } window.rootViewController = viewController if animated { UIView.transition( with: window, duration: duration, options: options, animations: nil ) { _ in completion?() } } else { completion?() } } }
24.666667
100
0.64553
efab82a74417be7dfffc4daaf2c688b349346192
1,427
// // AppDelegate.swift // SinzuMoneyExamples // // Created by Afees Lawal on 02/05/2020. // Copyright © 2020 Afees Lawal. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.552632
179
0.749124
9000ddacc932b18907abae79d2dee5fdae25218e
362
// // ContextPositionSeekable.swift // ExposurePlayback // // Created by Fredrik Sjöberg on 2018-02-07. // Copyright © 2018 emp. All rights reserved. // import Foundation import Player internal protocol ContextPositionSeekable { func handleSeek(toPosition position: Int64, for player: Player<HLSNative<ExposureContext>>, in context: ExposureContext) }
24.133333
124
0.765193
38abc9548105d2aeaf4ee9daf8ff5e1e4605d2bf
2,293
//: ## Phaser import AudioKitPlaygrounds import AudioKit import AudioKitUI let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true var phaser = AKPhaser(player) AudioKit.output = phaser try AudioKit.start() player.play() class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Phaser") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addView(AKSlider(property: "Feedback", value: phaser.feedback) { _ in phaser.feedback }) addView(AKSlider(property: "Depth", value: phaser.depth) { _ in phaser.depth }) addView(AKSlider(property: "Notch Minimum", value: phaser.notchMinimumFrequency, range: 20 ... 5_000, format: "%0.1f Hz" ) { sliderValue in phaser.notchMinimumFrequency = sliderValue }) addView(AKSlider(property: "Notch Maximum", value: phaser.notchMaximumFrequency, range: 20 ... 10_000, format: "%0.1f Hz" ) { sliderValue in phaser.notchMaximumFrequency = sliderValue }) addView(AKSlider(property: "Notch Width", value: phaser.notchWidth, range: 10 ... 5_000, format: "%0.1f Hz" ) { sliderValue in phaser.notchWidth = sliderValue }) addView(AKSlider(property: "Notch Frequency", value: phaser.notchFrequency, range: 1.1 ... 4, format: "%0.2f Hz" ) { sliderValue in phaser.notchFrequency = sliderValue }) addView(AKSlider(property: "LFO BPM", value: phaser.lfoBPM, range: 24 ... 360, format: "%0.2f Hz" ) { sliderValue in phaser.lfoBPM = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
29.025316
96
0.542521
fb8d9e440341b0487bb954c0ec2836f6cc87e496
1,268
// // EmotionKeyboardUITests.swift // EmotionKeyboardUITests // // Created by Hongpeng Yu on 2017/9/28. // Copyright © 2017年 Hongpeng Yu. All rights reserved. // import XCTest class EmotionKeyboardUITests: 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. } }
34.27027
182
0.66877
7641ce3f375b5e03593a4bb88d7708adf2c561f6
1,204
// // CommentCell.swift // HNReader // // Created by Mattia Righetti on 21/07/21. // import SwiftUI import HNScraper struct CommentCell: View { let comment: HNComment var highlightBorder: Bool @Environment(\.colorScheme) var colorScheme var body: some View { VStack(alignment: .leading) { Text(comment.username ?? "") .font(.system(.body, design: .rounded)) .foregroundColor(.yellow) .padding(.bottom, 3) HStack { Text(comment.text.htmlParsed) .opacity(comment.showType == .downvoted ? 0.5 : 1.0) Spacer() } } .padding() .background(colorScheme == .dark ? Color.black.opacity(0.3) : Color.white) .modifier(HighlightBorder(highlight: highlightBorder)) .cornerRadius(10) } } struct HighlightBorder: ViewModifier { var highlight: Bool func body(content: Content) -> some View { if highlight { content.overlay(RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 2).foregroundColor(.yellow)) } else { content } } }
25.617021
109
0.560631
0a5da2fd3e1c213c712b470216236d20590765d6
2,349
// // AppDelegate.swift // CardCollectionView // // Created by Kyle Zaragoza on 7/11/16. // Copyright © 2016 Kyle Zaragoza. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let transitionController = NavigationTransitionController() func applicationDidFinishLaunching(_ application: UIApplication) { UINavigationBar.appearance().tintColor = UIColor.black // setup navigation delegate let rootNavigationController = self.window!.rootViewController as! UINavigationController rootNavigationController.delegate = transitionController } 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:. } }
47.938776
285
0.758195
1e42b8c69e80e1922319cc6929e6c30c6c22ccbd
11,295
// // FSTargetingManagerTest.swift // FlagshipTests // // Created by Adel on 28/05/2020. // Copyright © 2020 FlagShip. All rights reserved. // import XCTest @testable import Flagship class FSTargetingManagerTest: XCTestCase { var targetingManager:FSTargetingManager! override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. targetingManager = FSTargetingManager() } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } 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. } } func testisTargetingGroupIsOkay(){ /// test with nil entry XCTAssertFalse(targetingManager.isTargetingGroupIsOkay(nil)) } /// func checkCondition(_ cuurentValue:Any, _ operation:FSoperator, _ audienceValue:Any)->Bool{ func testCheckCondition(){ XCTAssertTrue(targetingManager.checkCondition(12, .EQUAL, 12)) XCTAssertFalse(targetingManager.checkCondition(12, .EQUAL, 121)) XCTAssertTrue(targetingManager.checkCondition("aaaa", .EQUAL, "aaaa")) XCTAssertFalse(targetingManager.checkCondition("aaaa", .EQUAL, "aaaav")) XCTAssertTrue(targetingManager.isGreatherThan(type: Int.self, a: 13, b: 12)) XCTAssertFalse(targetingManager.isGreatherThan(type: Int.self, a: 10, b: 12)) XCTAssertTrue(targetingManager.isGreatherThanorEqual(type: Int.self, a: 12, b: 12)) XCTAssertFalse(targetingManager.isGreatherThanorEqual(type: Int.self, a: 10, b: 12)) XCTAssertTrue(targetingManager.isEqual(type: Int.self, a: 12, b: 12)) XCTAssertFalse(targetingManager.isEqual(type: Int.self, a: 14, b: 12)) XCTAssertTrue(targetingManager.isEqual(type: String.self, a: "abc", b: "abc")) do { try XCTAssertTrue(targetingManager.isCurrentValueContainAudience("121111111", "12111")) try XCTAssertFalse(targetingManager.isCurrentValueContainAudience("AZAZAZA", "12111")) } } func testcheckCondition(){ // func checkCondition(_ cuurentValue:Any, _ operation:FSoperator, _ audienceValue:Any)->Bool{ for itemOperator in FSoperator.allCases { let ret = targetingManager.checkCondition(12, itemOperator, 12) let retBis = targetingManager.checkCondition("12", itemOperator, "12") let retTer = targetingManager.checkCondition("12", itemOperator, 12) let retFour = targetingManager.checkCondition(Date(), itemOperator, Data()) let retDouble = targetingManager.checkCondition(0.123456789123456789, itemOperator, 0.923456789123456789) let retDoubleBis = targetingManager.checkCondition(0.923456789123456789, itemOperator, 0.123456789123456789) let retBool = targetingManager.checkCondition(true, itemOperator, true) let retObj = targetingManager.checkCondition(NSData(), itemOperator, NSData()) let retObjbis = targetingManager.checkCondition(NSData(), itemOperator, NSDate()) switch itemOperator { case .EQUAL: XCTAssertTrue(ret) XCTAssertTrue(retBis) XCTAssertFalse(retTer) XCTAssertFalse(retFour) XCTAssertFalse(retDouble) XCTAssertFalse(retDoubleBis) XCTAssertTrue(retBool) XCTAssertFalse(retObj) XCTAssertFalse(retObjbis) break case .GREATER_THAN: XCTAssertFalse(ret) XCTAssertFalse(retBis) XCTAssertFalse(retTer) XCTAssertFalse(retFour) XCTAssertFalse(retDouble) XCTAssertTrue(retDoubleBis) break case .GREATER_THAN_OR_EQUALS: XCTAssertTrue(ret) XCTAssertTrue(retBis) XCTAssertFalse(retTer) XCTAssertFalse(retFour) XCTAssertFalse(retDouble) XCTAssertTrue(retDoubleBis) break case .NOT_EQUAL: XCTAssertFalse(ret) XCTAssertFalse(retBis) XCTAssertTrue(retTer) XCTAssertFalse(retFour) XCTAssertTrue(retDouble) XCTAssertTrue(retDoubleBis) break case .LOWER_THAN: XCTAssertFalse(ret) XCTAssertFalse(retBis) XCTAssertFalse(retTer) XCTAssertFalse(retFour) XCTAssertTrue(retDouble) XCTAssertFalse(retDoubleBis) break case .LOWER_THAN_OR_EQUALS: XCTAssertTrue(retBis) XCTAssertTrue(ret) XCTAssertFalse(retTer) XCTAssertFalse(retFour) XCTAssertTrue(retDouble) XCTAssertFalse(retDoubleBis) break case .CONTAINS: XCTAssertTrue(retBis) XCTAssertFalse(ret) XCTAssertFalse(retTer) XCTAssertFalse(retFour) XCTAssertFalse(retDouble) XCTAssertFalse(retDoubleBis) break case .NOT_CONTAINS: XCTAssertFalse(retBis) XCTAssertFalse(ret) XCTAssertFalse(retTer) XCTAssertFalse(retFour) XCTAssertFalse(retDouble) XCTAssertFalse(retDoubleBis) break case .Unknown: break } } } func testSsCurrentValueIsGreaterThanAudience(){ do{ let ret = try targetingManager.isCurrentValueIsGreaterThanAudience("val", "val_audience") XCTAssertFalse(ret) let retbis = try targetingManager.isCurrentValueIsGreaterThanAudience(12, 10) XCTAssertTrue(retbis) let retTer = try targetingManager.isCurrentValueIsGreaterThanAudience(Data(), Data()) XCTAssertFalse(retTer) }catch{ } } func testIsCurrentValueIsGreaterThanOrEqualAudience(){ do{ let ret = try targetingManager.isCurrentValueIsGreaterThanOrEqualAudience("val", "val_audience") XCTAssertFalse(ret) let ret1 = try targetingManager.isCurrentValueIsGreaterThanOrEqualAudience("val", "val") XCTAssertTrue(ret1) let retbis = try targetingManager.isCurrentValueIsGreaterThanOrEqualAudience(12, 10) XCTAssertTrue(retbis) let ret2 = try targetingManager.isCurrentValueIsGreaterThanOrEqualAudience(12, 12) XCTAssertTrue(ret2) let retTer = try targetingManager.isCurrentValueIsGreaterThanOrEqualAudience(Data(), Data()) XCTAssertFalse(retTer) }catch{ } } func testIsCurrentValueContainAudience(){ do{ let ret = try targetingManager.isCurrentValueContainAudience("val", "val_audience") XCTAssertFalse(ret) let ret1 = try targetingManager.isCurrentValueContainAudience("val", "val") XCTAssertTrue(ret1) let retTer = try targetingManager.isCurrentValueContainAudience("value", "val") XCTAssertTrue(retTer) let retObj = try targetingManager.isCurrentValueContainAudience(Date(),Date()) XCTAssertFalse(retObj) do { try targetingManager.isCurrentValueContainAudience(12, 10) }catch{ XCTAssertEqual(error as! FStargetError, FStargetError.unknownType) } do { try targetingManager.isCurrentValueContainAudience(12, "12") }catch{ XCTAssertEqual(error as! FStargetError, FStargetError.unknownType) } }catch{ } } func testGetCurrentValueFromCtx(){ Flagship.sharedInstance.visitorId = "alias" if let ret = targetingManager.getCurrentValueFromCtx(FS_USERS) as? String{ XCTAssertTrue(ret == "alias") } } func testCheckTargetGroupIsOkay(){ /// read the data from the file and fill the campaigns do { let testBundle = Bundle(for: type(of: self)) guard let path = testBundle.url(forResource: "targetings", withExtension: "json") else { return } let data = try Data(contentsOf: path, options:.alwaysMapped) let targetObject = try JSONDecoder().decode(FSTargeting.self, from: data) print(targetObject) Flagship.sharedInstance.visitorId = "alias" /// Visitor id Flagship.sharedInstance.updateContext("basketNumber", 100) /// belong to first group Flagship.sharedInstance.updateContext("basketNumberBis", 200) /// belong to second group Flagship.sharedInstance.updateContext("testkey6", "gamaa") /// belong to second group Flagship.sharedInstance.updateContext("testkey7", "abbc") /// belong to second group Flagship.sharedInstance.updateContext("testkey8", "yahoo.fr") /// belong to second group if let item = targetObject.targetingGroups.first { let ret = targetingManager.checkTargetGroupIsOkay(item) XCTAssertFalse(ret) } if let itemBis = targetObject.targetingGroups.last { let retBis = targetingManager.checkTargetGroupIsOkay(itemBis) XCTAssertTrue(retBis) } }catch{ print("error") } } }
28.813776
120
0.54077
fee7aa555706276e54fa91d075b93dd0e08dbf97
20,652
import XCTest #if USING_SQLCIPHER import GRDBCipher #elseif USING_CUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif private struct Col { static let id = SQLColumn("id") static let name = SQLColumn("name") static let age = SQLColumn("age") static let readerId = SQLColumn("readerId") } private let tableRequest = QueryInterfaceRequest<Void>(tableName: "readers") class QueryInterfaceRequestTests: GRDBTestCase { var collation: DatabaseCollation! override func setUpDatabase(dbWriter: DatabaseWriter) throws { collation = DatabaseCollation("localized_case_insensitive") { (lhs, rhs) in return (lhs as NSString).localizedCaseInsensitiveCompare(rhs) } dbWriter.addCollation(collation) var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute( "CREATE TABLE readers (" + "id INTEGER PRIMARY KEY, " + "name TEXT NOT NULL, " + "age INT" + ")") } try migrator.migrate(dbWriter) } // MARK: - Fetch rows func testFetchRowFromRequest() { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) do { let rows = Row.fetchAll(db, tableRequest) XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].value(named: "id") as Int64, 1) XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur") XCTAssertEqual(rows[0].value(named: "age") as Int, 42) XCTAssertEqual(rows[1].value(named: "id") as Int64, 2) XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara") XCTAssertEqual(rows[1].value(named: "age") as Int, 36) } do { let row = Row.fetchOne(db, tableRequest)! XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(row.value(named: "id") as Int64, 1) XCTAssertEqual(row.value(named: "name") as String, "Arthur") XCTAssertEqual(row.value(named: "age") as Int, 42) } do { var names: [String] = [] for row in Row.fetch(db, tableRequest) { names.append(row.value(named: "name")) } XCTAssertEqual(self.lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(names, ["Arthur", "Barbara"]) } } } } // MARK: - Count func testFetchCount() { let dbQueue = try! makeDatabaseQueue() dbQueue.inDatabase { db in XCTAssertEqual(tableRequest.fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") XCTAssertEqual(tableRequest.reverse().fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") XCTAssertEqual(tableRequest.order(Col.name).fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") XCTAssertEqual(tableRequest.limit(10).fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM \"readers\" LIMIT 10)") XCTAssertEqual(tableRequest.filter(Col.age == 42).fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE (\"age\" = 42)") XCTAssertEqual(tableRequest.distinct.fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT * FROM \"readers\")") XCTAssertEqual(tableRequest.select(Col.name).fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") XCTAssertEqual(tableRequest.select(Col.name).distinct.fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT \"name\") FROM \"readers\"") XCTAssertEqual(tableRequest.select(Col.age * 2).distinct.fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT (\"age\" * 2)) FROM \"readers\"") XCTAssertEqual(tableRequest.select((Col.age * 2).aliased("ignored")).distinct.fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(DISTINCT (\"age\" * 2)) FROM \"readers\"") XCTAssertEqual(tableRequest.select(Col.name, Col.age).fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") XCTAssertEqual(tableRequest.select(Col.name, Col.age).distinct.fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"name\", \"age\" FROM \"readers\")") XCTAssertEqual(tableRequest.select(max(Col.age)).group(Col.name).fetchCount(db), 0) XCTAssertEqual(self.lastSQLQuery, "SELECT COUNT(*) FROM (SELECT MAX(\"age\") FROM \"readers\" GROUP BY \"name\")") } } // MARK: - Select func testSelectLiteral() { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(sql: "name, id - 1") let rows = Row.fetchAll(db, request) XCTAssertEqual(self.lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].value(atIndex: 0) as String, "Arthur") XCTAssertEqual(rows[0].value(atIndex: 1) as Int64, 0) XCTAssertEqual(rows[1].value(atIndex: 0) as String, "Barbara") XCTAssertEqual(rows[1].value(atIndex: 1) as Int64, 1) } } } func testSelectLiteralWithPositionalArguments() { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(sql: "name, id - ?", arguments: [1]) let rows = Row.fetchAll(db, request) XCTAssertEqual(self.lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].value(atIndex: 0) as String, "Arthur") XCTAssertEqual(rows[0].value(atIndex: 1) as Int64, 0) XCTAssertEqual(rows[1].value(atIndex: 0) as String, "Barbara") XCTAssertEqual(rows[1].value(atIndex: 1) as Int64, 1) } } } func testSelectLiteralWithNamedArguments() { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(sql: "name, id - :n", arguments: ["n": 1]) let rows = Row.fetchAll(db, request) XCTAssertEqual(self.lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].value(atIndex: 0) as String, "Arthur") XCTAssertEqual(rows[0].value(atIndex: 1) as Int64, 0) XCTAssertEqual(rows[1].value(atIndex: 0) as String, "Barbara") XCTAssertEqual(rows[1].value(atIndex: 1) as Int64, 1) } } } func testSelect() { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(Col.name, Col.id - 1) let rows = Row.fetchAll(db, request) XCTAssertEqual(self.lastSQLQuery, "SELECT \"name\", (\"id\" - 1) FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].value(atIndex: 0) as String, "Arthur") XCTAssertEqual(rows[0].value(atIndex: 1) as Int64, 0) XCTAssertEqual(rows[1].value(atIndex: 0) as String, "Barbara") XCTAssertEqual(rows[1].value(atIndex: 1) as Int64, 1) } } } func testSelectAliased() { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) let request = tableRequest.select(Col.name.aliased("nom"), (Col.age + 1).aliased("agePlusOne")) let row = Row.fetchOne(db, request)! XCTAssertEqual(self.lastSQLQuery, "SELECT \"name\" AS \"nom\", (\"age\" + 1) AS \"agePlusOne\" FROM \"readers\"") XCTAssertEqual(row.value(named: "nom") as String, "Arthur") XCTAssertEqual(row.value(named: "agePlusOne") as Int, 43) } } } func testMultipleSelect() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.select(Col.age).select(Col.name)), "SELECT \"name\" FROM \"readers\"") } // MARK: - Distinct func testDistinct() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.select(Col.name).distinct), "SELECT DISTINCT \"name\" FROM \"readers\"") } // MARK: - Filter func testFilterLiteral() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(sql: "id <> 1")), "SELECT * FROM \"readers\" WHERE id <> 1") } func testFilterLiteralWithPositionalArguments() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(sql: "id <> ?", arguments: [1])), "SELECT * FROM \"readers\" WHERE id <> 1") } func testFilterLiteralWithNamedArguments() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(sql: "id <> :id", arguments: ["id": 1])), "SELECT * FROM \"readers\" WHERE id <> 1") } func testFilter() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(true)), "SELECT * FROM \"readers\" WHERE 1") } func testMultipleFilter() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(true).filter(false)), "SELECT * FROM \"readers\" WHERE (1 AND 0)") } // MARK: - Group func testGroupLiteral() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(sql: "age, lower(name)")), "SELECT * FROM \"readers\" GROUP BY age, lower(name)") } func testGroupLiteralWithPositionalArguments() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(sql: "age + ?, lower(name)", arguments: [1])), "SELECT * FROM \"readers\" GROUP BY age + 1, lower(name)") } func testGroupLiteralWithNamedArguments() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(sql: "age + :n, lower(name)", arguments: ["n": 1])), "SELECT * FROM \"readers\" GROUP BY age + 1, lower(name)") } func testGroup() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.age)), "SELECT * FROM \"readers\" GROUP BY \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.age, Col.name)), "SELECT * FROM \"readers\" GROUP BY \"age\", \"name\"") } func testMultipleGroup() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.age).group(Col.name)), "SELECT * FROM \"readers\" GROUP BY \"name\"") } // MARK: - Having func testHavingLiteral() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > 18")), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") } func testHavingLiteralWithPositionalArguments() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > ?", arguments: [18])), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") } func testHavingLiteralWithNamedArguments() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > :age", arguments: ["age": 18])), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") } func testHaving() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(min(Col.age) > 18)), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (MIN(\"age\") > 18)") } func testMultipleHaving() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(min(Col.age) > 18).having(max(Col.age) < 50)), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING ((MIN(\"age\") > 18) AND (MAX(\"age\") < 50))") } // MARK: - Sort func testSortLiteral() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.order(sql: "lower(name) desc")), "SELECT * FROM \"readers\" ORDER BY lower(name) desc") } func testSortLiteralWithPositionalArguments() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.order(sql: "age + ?", arguments: [1])), "SELECT * FROM \"readers\" ORDER BY age + 1") } func testSortLiteralWithNamedArguments() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.order(sql: "age + :age", arguments: ["age": 1])), "SELECT * FROM \"readers\" ORDER BY age + 1") } func testSort() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age)), "SELECT * FROM \"readers\" ORDER BY \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age.asc)), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age.desc)), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age, Col.name.desc)), "SELECT * FROM \"readers\" ORDER BY \"age\", \"name\" DESC") XCTAssertEqual( sql(dbQueue, tableRequest.order(abs(Col.age))), "SELECT * FROM \"readers\" ORDER BY ABS(\"age\")") } func testSortWithCollation() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating("NOCASE"))), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating("NOCASE").asc)), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating(collation))), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE localized_case_insensitive") } func testMultipleSort() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age).order(Col.name)), "SELECT * FROM \"readers\" ORDER BY \"age\", \"name\"") } // MARK: - Reverse func testReverse() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.reverse()), "SELECT * FROM \"readers\" ORDER BY \"_rowid_\" DESC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age).reverse()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age.asc).reverse()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age.desc).reverse()), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age, Col.name.desc).reverse()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC, \"name\" ASC") XCTAssertEqual( sql(dbQueue, tableRequest.order(abs(Col.age)).reverse()), "SELECT * FROM \"readers\" ORDER BY ABS(\"age\") DESC") } func testReverseWithCollation() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating("NOCASE")).reverse()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating("NOCASE").asc).reverse()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating(collation)).reverse()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE localized_case_insensitive DESC") } func testMultipleReverse() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.reverse().reverse()), "SELECT * FROM \"readers\"") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age).order(Col.name).reverse().reverse()), "SELECT * FROM \"readers\" ORDER BY \"age\", \"name\"") } // MARK: - Limit func testLimit() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.limit(1)), "SELECT * FROM \"readers\" LIMIT 1") XCTAssertEqual( sql(dbQueue, tableRequest.limit(1, offset: 2)), "SELECT * FROM \"readers\" LIMIT 1 OFFSET 2") } func testMultipleLimit() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.limit(1, offset: 2).limit(3)), "SELECT * FROM \"readers\" LIMIT 3") } }
42.233129
129
0.559074
fc515455a44306d4cfd1fe674713357df9964b75
2,449
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-build-swift -Xfrontend -enable-experimental-property-behaviors %s -o %t/a.out // RUN: %target-run %t/a.out // REQUIRES: executable_test // REQUIRES: rdar24874073 import StdlibUnittest protocol delayedImmutable { associatedtype Value var storage: Value? { get set } } extension delayedImmutable { var value: Value { // The property can only be read after it's been initialized. get { guard let theValue = storage else { fatalError("delayedImmutable property read before initialization") } return theValue } // The property can only be written once to initialize it. set { guard storage == nil else { fatalError("delayedImmutable property rewritten after initialization") } storage = newValue } } static func initStorage() -> Value? { return nil } } protocol lazy { associatedtype Value var storage: Value? { get set } func parameter() -> Value } extension lazy { var value: Value { mutating get { if let existing = storage { return existing } let value = parameter() storage = value return value } set { storage = newValue } } static func initStorage() -> Value? { return nil } } var lazyEvaluated = false func evaluateLazy() -> Int { lazyEvaluated = true return 1738 } class Foo { var x: Int __behavior delayedImmutable var y: Int __behavior lazy { evaluateLazy() } } var DelayedImmutable = TestSuite("DelayedImmutable") DelayedImmutable.test("correct usage") { let foo = Foo() foo.x = 679 expectEqual(foo.x, 679) } DelayedImmutable.test("read before initialization") { let foo = Foo() expectCrashLater() _ = foo.x } DelayedImmutable.test("write after initialization") { let foo = Foo() foo.x = 679 expectCrashLater() foo.x = 680 } var Lazy = TestSuite("Lazy") Lazy.test("usage") { let foo = Foo() expectFalse(lazyEvaluated) expectEqual(foo.y, 1738) expectTrue(lazyEvaluated) lazyEvaluated = false expectEqual(foo.y, 1738) expectFalse(lazyEvaluated) foo.y = 36 expectEqual(foo.y, 36) expectFalse(lazyEvaluated) let foo2 = Foo() expectFalse(lazyEvaluated) foo2.y = 36 expectEqual(foo2.y, 36) expectFalse(lazyEvaluated) let foo3 = Foo() expectFalse(lazyEvaluated) expectEqual(foo3.y, 1738) expectTrue(lazyEvaluated) } runAllTests()
19.436508
93
0.664353
e06e83d9c068435efad0c09f4a8b7bf75d867e31
366
// // PauseStatus.swift // EngagementSDK // // Created by Jelzon Monzon on 5/29/19. // import Foundation enum PauseStatus { case paused case unpaused } extension PauseStatus { var analyticsName: String { switch self { case .paused: return "Paused" case .unpaused: return "Unpaused" } } }
14.64
40
0.57377
dd15e572f2ccfca969882b355d8bf5bc6beab07d
1,769
//: Playground - noun: a place where people can play import Cocoa class ConnectionManager : NSObject, NSURLConnectionDataDelegate { var m_buffer = NSMutableData() var responseStr: NSString? func HttpConnection(httpURL: String) { var url: NSURL? var requrst: NSURLRequest? var conn: NSURLConnection? url = NSURL(fileURLWithPath: httpURL) requrst = NSMutableURLRequest(URL: url!) //requrst?.timeoutInterval = 5.0 conn = NSURLConnection(request: requrst!, delegate: self) if((conn) != nil) { print("http连接成功!") conn!.start() } else { print("http连接失败!") } } func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { print("收到服务器响应") } func connection(connection: NSURLConnection, didFailWithError error: NSError) { print(error.localizedDescription) } func connection(cconnection: NSURLConnection, didReceiveData data: NSData){ m_buffer.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection) { // This will be called when the data loading is finished i.e. there is no data left to be received and now you can process the data. NSLog("connectionDidFinishLoading") responseStr = NSString(data: m_buffer, encoding:NSUTF8StringEncoding) print(responseStr) } func GetData() -> NSString? { return responseStr } } var conMgr = ConnectionManager() conMgr.HttpConnection("http://www.baidu.com")
24.915493
140
0.59299
9b8e642bdf57544b595a55510e9a9537af2111b5
381
// // Effect.swift // TransitKit // // Created by Andrew Finke on 8/5/17. // Copyright © 2017 Andrew Finke. All rights reserved. // import Foundation /// The effect of this problem on the affected entity. public enum TSTRTEffect: Int { case noService = 0, reducedService, significantDelays, detour case additionalService, modifiedService, other, unknown, stopMoved }
23.8125
70
0.727034
18386ecf7411d6e68eca0c25d0b6a91ab4eb42df
2,860
// // RedisHash.swift // PerfectRedis // // Created by Kyle Jessup on 2018-06-11. // import Foundation public struct RedisHash { public typealias Element = (key: KeyType, value: ValueType) public typealias KeyType = String public typealias ValueType = RedisClient.RedisValue let client: RedisClient let name: String public var exists: Bool { return 1 == (try? client.exists(keys: name))?.integer ?? 0 } public var count: Int { return (try? client.hashLength(key: name))?.integer ?? 0 } public var keys: [String] { guard let response = try? client.hashKeys(key: name), case .array(let a) = response else { return [] } return a.compactMap { $0.string } } public var values: [ValueType] { guard let response = try? client.hashValues(key: name), case .array(let a) = response else { return [] } return a.compactMap { $0.value } } public init(_ client: RedisClient, name: String) { self.client = client self.name = name } public subscript(_ key: KeyType) -> ValueType? { get { return (try? client.hashGet(key: name, field: key))?.value } set { if let newValue = newValue { _ = try? client.hashSet(key: name, field: key, value: newValue) } else { _ = try? client.hashDel(key: name, fields: key) } } } public func contains(_ key: KeyType) -> Bool { return 1 == (try? client.hashExists(key: name, field: key))?.integer ?? 0 } public func removeValue(forKey: KeyType) -> Bool { return 0 != (try? client.hashDel(key: name, fields: forKey))?.integer ?? 0 } public func removeAll() { let keys = self.keys guard !keys.isEmpty else { return } _ = try? client.hashDel(key: name, fields: keys) } public func increment(key: KeyType, by: Int) -> Int { return (try? client.hashIncrementBy(key: name, field: key, by: by))?.integer ?? 0 } public func increment(key: KeyType, by: Double) -> Double { guard let str = (try? client.hashIncrementBy(key: name, field: key, by: by))?.string, let d = Double(str) else { return 0.0 } return d } } extension RedisHash: Sequence { public func makeIterator() -> Iterator { guard let response = try? client.hashGetAll(key: name), case .array(let a) = response, !a.isEmpty, a.count % 2 == 0 else { return Iterator(items: []) } return Iterator(items: a.compactMap { $0.value }) } public struct Iterator: IteratorProtocol { public typealias Element = RedisHash.Element var index = 0 var items: Array<RedisHash.ValueType>.Iterator init(items: [RedisHash.ValueType]) { self.items = items.makeIterator() } public mutating func next() -> Element? { guard let name = items.next()?.string, let value = items.next() else { return nil } return (name, value) } } } public extension RedisClient { func hash(named: String) -> RedisHash { return RedisHash(self, name: named) } }
26.728972
94
0.66049
f85b74518f90334cbded81a55e9ad44d91be7a77
4,753
// // ImageWallCollectionViewController.swift // Longinus_Example // // Created by Qitao Yang on 2020/7/6. // // Copyright (c) 2020 KittenYang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Longinus private let reuseIdentifier = "Cell" class ImageWallCollectionViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 let cellWidth = view.bounds.width / 4 layout.itemSize = CGSize(width: cellWidth, height: cellWidth) self.collectionView!.collectionViewLayout = layout self.collectionView!.register(ImageWallCell.self, forCellWithReuseIdentifier: reuseIdentifier) if #available(iOS 10.0, *) { self.collectionView.prefetchDataSource = self } } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4000 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageWallCell if let url = ImageLinksPool.originLink(forIndex: indexPath.item + 1) { cell.updateUIWith(url) } return cell } } // MARK: UICollectionViewDataSourcePrefetching @available(iOS 10.0, *) extension ImageWallCollectionViewController: UICollectionViewDataSourcePrefetching { func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { let prefetechImageLinks = indexPaths.compactMap({ return ImageLinksPool.originLink(forIndex: $0.item + 1) }) LonginusManager.shared.preload(prefetechImageLinks, options: .none, progress: { (successCount, finishCount, total) in }) { (successCount, total) in } } func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) { indexPaths.forEach { (indexPath) in if let urlString = ImageLinksPool.originLink(forIndex: indexPath.item)?.absoluteString { LonginusManager.shared.cancelPreloading(url: urlString) } } } } class ImageWallCell: UICollectionViewCell { private var imageView: AnimatedImageView! override init(frame: CGRect) { super.init(frame: frame) imageView = AnimatedImageView(frame: CGRect(origin: .zero, size: frame.size)) imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true contentView.addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateUIWith(_ url: URL) { let transformer = ImageTransformer.imageTransformerCommon(with: imageView.frame.size, borderWidth: 2.0, borderColor: .white) // let flipTransformer = ImageTransformer.imageTransformerFlip(withHorizontal: true, vertical: true) imageView.lg.setImage(with: url, placeholder: UIImage(named: "placeholder"), options: [.imageWithFadeAnimation, .showNetworkActivity], transformer: transformer, progress: nil, completion: nil) } }
42.061947
200
0.698296
f4f29fa4b9c4839d374a46682d3d76769dadf571
4,788
// // UIDevice+Model.swift // GPUFingerprinting // // Copyright © 2019 Instituto de Pesquisas Eldorado. All rights reserved. // import Foundation import UIKit public extension UIDevice { static let modelName: String = { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity #if os(iOS) switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone XS" case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" case "iPhone11,8": return "iPhone XR" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad6,11", "iPad6,12": return "iPad 5" case "iPad7,5", "iPad7,6": return "iPad 6" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)" case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch)" case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)" case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)" case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch)" case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "AudioAccessory1,1": return "HomePod" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))" default: return identifier } #elseif os(tvOS) switch identifier { case "AppleTV5,3": return "Apple TV 4" case "AppleTV6,2": return "Apple TV 4K" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))" default: return identifier } #endif } return mapToDevice(identifier: identifier) }() }
58.390244
171
0.466374
ffc1c36f9fe5230a09b6a76356649bf9a503ba04
202
// Copyright 2019 The OmniTree Authors. import XCTest #if !os(macOS) public func allTests() -> [XCTestCaseEntry] { return [ testCase(JsonWireFormatEncoderTests.allTests), ] } #endif
16.833333
52
0.683168
1aa89e9e38a72da734fdaca5396c0af8b2a3f4df
9,797
// // BreakoutViewController.swift // Breakout // // Created by Hanzhou Shi on 1/18/16. // Copyright © 2016 USF. All rights reserved. // import UIKit class BreakoutViewController: UIViewController, UICollisionBehaviorDelegate { @IBOutlet weak var gameScene: BezierUIView! @IBAction func panPaddle(sender: UIPanGestureRecognizer) { let gesturePoint = sender.locationInView(gameScene) switch sender.state { case .Changed: var origin = paddleFrame.origin origin.x = min(max(gesturePoint.x, 0), gameScene.bounds.width-paddleSize.width) paddleFrame = CGRect(origin: origin, size: paddleSize) default: break } } @IBAction func shoot(sender: UITapGestureRecognizer) { gameStart() } // MARK: - API let numBricksPerRow = Int(Constants.DefaultBrickNumPerRow) let numBrickLevels = Int(Constants.DefaultBrickLevels) var numBalls = Constants.DefaultBallNum { didSet { clearBalls() createBalls() } } var gameInProgress = false // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() behavior.collisionDelegate = self createBalls() createBricks() animator.addBehavior(behavior) } override func viewDidLayoutSubviews() { // setup game scene after all predefined subviews // are settled. super.viewDidLayoutSubviews() // put bricks and paddle into their expected position // we layout bricks and do the setup here because in a // TabBarController we need to implement viewDidLayoutSubviews // in an idempotent way. layoutBricks() layoutPaddle(paddleFrame) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let stdDefaults = NSUserDefaults.standardUserDefaults() numBalls = Int(stdDefaults.doubleForKey(SettingConstants.NumberOfBallsDefaultKey)) behavior.itemBehavior.elasticity = CGFloat(stdDefaults.doubleForKey(SettingConstants.BouncinessDefaultKey)) behavior.itemBehavior.resistance = CGFloat(stdDefaults.doubleForKey(SettingConstants.ResistenceDefaultKey)) behavior.pushMagnitude = CGFloat(stdDefaults.doubleForKey(SettingConstants.BallSpeedDefaultKey)) } // MARK: - Collision Delegate func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, atPoint p: CGPoint) { if let id = identifier as? String { switch id { case Constants.PaddleIdentifier: break // collides on the paddle case Constants.LowerBoundIdentifier: restart() default: // collides on the brick removeBrickFromView(id) break } } } private var balls = [Ball]() private var bricks = [String:Brick]() // MARK: - Brick Related Properties /// width * num + (num - 1) * margin = frameSize /// width = (frameSize - (num-1) * margin) / num private var brickSize: CGSize { let boundSize = gameScene.bounds.width let width = (boundSize - (CGFloat(numBricksPerRow-1)) * Constants.DefaultBrickMarginX) / CGFloat(numBricksPerRow) let height = width / Constants.BrickAspectRatio return CGSize(width: width, height: height) } // MARK: - Paddle Related Properties private var paddleFrame: CGRect { get { let midX = gameScene.bounds.midX let x = midX - paddleSize.width / 2 let y = lowerBoundY - paddleSize.height let origin = CGPoint(x: x, y: y) return CGRect(origin: origin, size: paddleSize) } set { layoutPaddle(newValue) } } private var paddle: Paddle = Paddle(rect: CGRect.zero, color: Constants.DefaultPaddleColor) { didSet { updateBallsFrame() updateLowerBound() } } private var paddleSize: CGSize { let paddleWidth = gameScene.bounds.width / Constants.DefaultPaddleWidthRatio let paddleHeight = paddleWidth / Constants.DefaultPaddleRatio return CGSize(width: paddleWidth, height: paddleHeight) } // MARK: - Lower Bound Related private var lowerBound = CGRect(origin: CGPoint.zero, size: CGSize.zero) private var lowerBoundY: CGFloat { return gameScene.bounds.maxY - gameScene.bounds.maxY / Constants.DefaultLowerBoundHeightRatio } // MARK: - UIDynamicBehavior Related Properties private var behavior = BreakoutBehavior() private lazy var animator: UIDynamicAnimator = { let lazilyCreatedAnimator = UIDynamicAnimator(referenceView: self.gameScene) return lazilyCreatedAnimator }() // MARK: - Helper functions private func createBricks() { // create bricks only if there are no bricks guard bricks.count == 0 else { return } for index in 0..<(numBricksPerRow*numBrickLevels) { let identifier = Constants.BrickIdentifierPrefix + "\(index)" let brick = Brick(frame: CGRect.zero, color: Constants.DefaultBrickColor) bricks[identifier] = brick } } private func createBalls() { for _ in 0..<numBalls { let newBall = Ball(frame: CGRect.zero, color: Constants.DefaultBallColor) balls.append(newBall) newBall.attachedPaddle = paddle } } private func clearBalls() { _ = balls.map { self.behavior.removeItem($0) } balls.removeAll() } private func layoutBricks() { for rowNum in 0..<numBrickLevels { layoutBricksAtRow(rowNum) } } private func layoutBricksAtRow(rowNum: Int) { for offset in 0..<Int(numBricksPerRow) { let x = CGFloat(offset)*(brickSize.width + Constants.DefaultBrickMarginX) let y = CGFloat(rowNum)*(brickSize.height + Constants.DefaultBrickMarginY) let origin = CGPoint(x: x, y: y) let frame = CGRect(origin: origin, size: brickSize) let identifier = Constants.BrickIdentifierPrefix + "\(offset + rowNum * numBricksPerRow)" // make sure that the path exists if let brick = bricks[identifier] { if brick.alpha != 0.0 { brick.frame = frame gameScene.addSubview(brick) behavior.addBarrier(brick.boundary, named: identifier) } } } } private var firstOffsetXForBalls: CGFloat { let ballsCount = CGFloat(balls.count) let totalWidth = ballsCount*Constants.DefaultBallSize.width let offset = (paddleSize.width - totalWidth) / 2 return paddle.bounds.minX + offset } private func layoutBalls() { let ballScale = Constants.DefaultBallSize.width var ballX = firstOffsetXForBalls let ballY = lowerBoundY-paddleSize.height-ballScale for ball in balls.filter({ (b) -> Bool in b.attached }) { let origin = CGPoint(x: ballX, y: ballY) let frame = CGRect(origin: origin, size: Constants.DefaultBallSize) ball.frame = frame gameScene.addSubview(ball) // update the position for the next ball ballX += ballScale } } private func layoutLowerBound() { let from = CGPoint(x: gameScene.bounds.minX, y: lowerBoundY) lowerBound = CGRect(origin: from, size: CGSize(width: gameScene.bounds.width, height: 1)) let path = CustomUIBezierPath(rect: lowerBound) path.fillColor = Constants.DefaultLowerBoundColor gameScene.setPath(path, named: Constants.LowerBoundIdentifier) behavior.addBarrier(path, named: Constants.LowerBoundIdentifier) } private func layoutPaddle(rect: CGRect) { paddle = Paddle(rect: rect, color: Constants.DefaultPaddleColor) gameScene.setPath(paddle, named: Constants.PaddleIdentifier) behavior.addBarrier(paddle, named: Constants.PaddleIdentifier) } private func gameStart() { // add all views to behavior shootBalls() } private func shootBalls() { for ball in balls { ball.attached = false // we actually shoot the ball here behavior.addItem(ball) behavior.pushItem(ball) } } private func updateBallsFrame() { layoutBalls() } private func updateLowerBound() { layoutLowerBound() } private func removeBrickFromView(id: String) { if let brick = bricks[id] { behavior.removeBarrier(id) UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { brick.alpha = 0.0 }, completion: { if $0 { } }) } } private func restart() { // reset all bricks meaning they will appear and become barriers again. for index in 0..<(numBricksPerRow*numBrickLevels) { let identifier = Constants.BrickIdentifierPrefix + "\(index)" if let brick = bricks[identifier] { behavior.addBarrier(brick.boundary, named: identifier) brick.alpha = 1.0 } } // reset balls status such that they will be "re-attached" to paddle. let _ = balls.map { behavior.removeItem($0) $0.attached = true } // this will trigger balls' re-attachment. layoutPaddle(paddleFrame) } }
33.899654
167
0.622946
6aca9552d5e7d79e7ad3227d30bf19cccdc12a23
2,141
// // AppDelegate.swift // SimpleDice // // Created by JOE KAWAI on 22/2/16. // Copyright © 2016 TeamKarbon. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.553191
285
0.753853
1dd5c9fdc25911e87f6061cdfda0f12efe04ecb6
543
// // TextRemoteService.swift // TiyoNir // // Created by Mounir Ybanez on 12/28/17. // Copyright © 2017 Nir. All rights reserved. // public final class TextRemoteService { public let query: TextQuery public let writer: TextWriter public init(query: TextQuery, writer: TextWriter) { self.query = query self.writer = writer } public convenience init() { let query = TextRemoteQuery() let writer = TextRemoteWriter() self.init(query: query, writer: writer) } }
21.72
55
0.627993
d63172316d4c493a6ca603cf2712a4609feb7d48
14,137
// // MenuItemView.swift // PagingMenuController // // Created by Yusuke Kita on 5/9/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit open class MenuItemView: UIView { lazy public var titleLabel: UILabel = self.initLabel() lazy public var descriptionLabel: UILabel = self.initLabel() lazy public var menuImageView: UIImageView = { $0.isUserInteractionEnabled = true $0.translatesAutoresizingMaskIntoConstraints = false return $0 }(UIImageView(frame: .zero)) public fileprivate(set) var customView: UIView? { didSet { guard let customView = customView else { return } addSubview(customView) } } public internal(set) var isSelected: Bool = false { didSet { if case .roundRect = menuOptions.focusMode { backgroundColor = UIColor.clear } else { backgroundColor = isSelected ? menuOptions.selectedBackgroundColor : menuOptions.backgroundColor } switch menuItemOptions.displayMode { case .text(let title): updateLabel(titleLabel, text: title) // adjust label width if needed let labelSize = calculateLabelSize(titleLabel, maxWidth: maxWindowSize) widthConstraint.constant = labelSize.width case let .multilineText(title, description): updateLabel(titleLabel, text: title) updateLabel(descriptionLabel, text: description) // adjust label width if needed widthConstraint.constant = calculateLabelSize(titleLabel, maxWidth: maxWindowSize).width descriptionWidthConstraint.constant = calculateLabelSize(descriptionLabel, maxWidth: maxWindowSize).width case let .image(image, selectedImage): menuImageView.image = isSelected ? (selectedImage ?? image) : image case .custom: break } } } lazy public fileprivate(set) var dividerImageView: UIImageView? = { [unowned self] in guard let image = self.menuOptions.dividerImage else { return nil } let imageView = UIImageView(image: image) imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() fileprivate var menuOptions: MenuViewCustomizable! fileprivate var menuItemOptions: MenuItemViewCustomizable! fileprivate var widthConstraint: NSLayoutConstraint! fileprivate var descriptionWidthConstraint: NSLayoutConstraint! fileprivate var horizontalMargin: CGFloat { switch menuOptions.displayMode { case .segmentedControl: return 0.0 default: return menuItemOptions.horizontalMargin } } // MARK: - Lifecycle internal init(menuOptions: MenuViewCustomizable, menuItemOptions: MenuItemViewCustomizable, addDiveder: Bool) { super.init(frame: .zero) self.menuOptions = menuOptions self.menuItemOptions = menuItemOptions switch menuItemOptions.displayMode { case .text(let title): commonInit({ self.setupTitleLabel(title) self.layoutLabel() }) case let .multilineText(title, description): commonInit({ self.setupMultilineLabel(title, description: description) self.layoutMultiLineLabel() }) case .image(let image, _): commonInit({ self.setupImageView(image) self.layoutImageView() }) case .custom(let view): commonInit({ self.setupCustomView(view) self.layoutCustomView() }) } } fileprivate func commonInit(_ setupContentView: () -> Void) { setupView() setupContentView() setupDivider() layoutDivider() } fileprivate func initLabel() -> UILabel { let label = UILabel(frame: .zero) label.numberOfLines = 1 label.textAlignment = .center label.isUserInteractionEnabled = true label.translatesAutoresizingMaskIntoConstraints = false return label } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Constraints manager internal func updateConstraints(_ size: CGSize) { // set width manually to support ratotaion guard case .segmentedControl = menuOptions.displayMode else { return } switch menuItemOptions.displayMode { case .text: let labelSize = calculateLabelSize(titleLabel, maxWidth: size.width) widthConstraint.constant = labelSize.width case .multilineText: widthConstraint.constant = calculateLabelSize(titleLabel, maxWidth: size.width).width descriptionWidthConstraint.constant = calculateLabelSize(descriptionLabel, maxWidth: size.width).width case .image, .custom: widthConstraint.constant = size.width / CGFloat(menuOptions.itemsOptions.count) } } // MARK: - Constructor fileprivate func setupView() { if case .roundRect = menuOptions.focusMode { backgroundColor = UIColor.clear } else { backgroundColor = menuOptions.backgroundColor } translatesAutoresizingMaskIntoConstraints = false } fileprivate func setupTitleLabel(_ text: MenuItemText) { setupLabel(titleLabel, text: text) } fileprivate func setupMultilineLabel(_ text: MenuItemText, description: MenuItemText) { setupLabel(titleLabel, text: text) setupLabel(descriptionLabel, text: description) } fileprivate func setupLabel(_ label: UILabel, text: MenuItemText) { label.text = text.text updateLabel(label, text: text) addSubview(label) } fileprivate func updateLabel(_ label: UILabel, text: MenuItemText) { label.textColor = isSelected ? text.selectedColor : text.color label.font = isSelected ? text.selectedFont : text.font } fileprivate func setupImageView(_ image: UIImage) { menuImageView.image = image addSubview(menuImageView) } fileprivate func setupCustomView(_ view: UIView) { customView = view } fileprivate func setupDivider() { guard let dividerImageView = dividerImageView else { return } addSubview(dividerImageView) } fileprivate func layoutMultiLineLabel() { // H:|[titleLabel(==labelSize.width)]| // H:|[descriptionLabel(==labelSize.width)]| // V:|-margin-[titleLabel][descriptionLabel]-margin| let titleLabelSize = calculateLabelSize(titleLabel, maxWidth: maxWindowSize) let descriptionLabelSize = calculateLabelSize(descriptionLabel, maxWidth: maxWindowSize) let verticalMargin = max(menuOptions.height - (titleLabelSize.height + descriptionLabelSize.height), 0) / 2 widthConstraint = titleLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: titleLabelSize.width) descriptionWidthConstraint = descriptionLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: descriptionLabelSize.width) NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor), widthConstraint, descriptionLabel.leadingAnchor.constraint(equalTo: leadingAnchor), descriptionLabel.trailingAnchor.constraint(equalTo: trailingAnchor), descriptionWidthConstraint, titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: verticalMargin), titleLabel.bottomAnchor.constraint(equalTo: descriptionLabel.topAnchor, constant: 0), descriptionLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: verticalMargin), titleLabel.heightAnchor.constraint(equalToConstant: titleLabelSize.height), ]) } fileprivate func layoutLabel() { // H:|[titleLabel](==labelSize.width)| // V:|[titleLabel]| let titleLabelSize = calculateLabelSize(titleLabel, maxWidth: maxWindowSize) widthConstraint = titleLabel.widthAnchor.constraint(equalToConstant: titleLabelSize.width) NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor), widthConstraint, titleLabel.topAnchor.constraint(equalTo: topAnchor), titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor), ]) } fileprivate func layoutImageView() { guard let image = menuImageView.image else { return } let width: CGFloat switch menuOptions.displayMode { case .segmentedControl: if let windowWidth = UIApplication.shared.keyWindow?.bounds.size.width { width = windowWidth / CGFloat(menuOptions.itemsOptions.count) } else { width = UIScreen.main.bounds.width / CGFloat(menuOptions.itemsOptions.count) } default: width = image.size.width + horizontalMargin * 2 } widthConstraint = widthAnchor.constraint(equalToConstant: width) NSLayoutConstraint.activate([ menuImageView.centerXAnchor.constraint(equalTo: centerXAnchor), menuImageView.centerYAnchor.constraint(equalTo: centerYAnchor), menuImageView.widthAnchor.constraint(equalToConstant: image.size.width), menuImageView.heightAnchor.constraint(equalToConstant: image.size.height), widthConstraint ]) } fileprivate func layoutCustomView() { guard let customView = customView else { return } widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: customView.frame.width) NSLayoutConstraint.activate([ NSLayoutConstraint(item: customView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: customView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: customView.frame.width), NSLayoutConstraint(item: customView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: customView.frame.height), widthConstraint ]) } fileprivate func layoutDivider() { guard let dividerImageView = dividerImageView else { return } NSLayoutConstraint.activate([ dividerImageView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 1.0), dividerImageView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) } } extension MenuItemView { func cleanup() { switch menuItemOptions.displayMode { case .text: titleLabel.removeFromSuperview() case .multilineText: titleLabel.removeFromSuperview() descriptionLabel.removeFromSuperview() case .image: menuImageView.removeFromSuperview() case .custom: customView?.removeFromSuperview() } dividerImageView?.removeFromSuperview() } } // MARK: Lable Size extension MenuItemView { fileprivate func labelWidth(_ widthMode: MenuItemWidthMode, estimatedSize: CGSize) -> CGFloat { switch widthMode { case .flexible: return ceil(estimatedSize.width) case .fixed(let width): return width } } fileprivate func estimatedLabelSize(_ label: UILabel) -> CGSize { guard let text = label.text else { return .zero } return NSString(string: text).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): label.font]), context: nil).size } fileprivate func calculateLabelSize(_ label: UILabel, maxWidth: CGFloat) -> CGSize { guard let _ = label.text else { return .zero } let itemWidth: CGFloat switch menuOptions.displayMode { case .standard(let widthMode, _, _): itemWidth = labelWidth(widthMode, estimatedSize: estimatedLabelSize(label)) case .segmentedControl: itemWidth = maxWidth / CGFloat(menuOptions.itemsOptions.count) case .infinite(let widthMode, _): itemWidth = labelWidth(widthMode, estimatedSize: estimatedLabelSize(label)) } let itemHeight = floor(estimatedLabelSize(label).height) return CGSize(width: itemWidth + horizontalMargin * 2, height: itemHeight) } fileprivate var maxWindowSize: CGFloat { return UIApplication.shared.keyWindow?.bounds.width ?? UIScreen.main.bounds.width } } // 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)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue }
41.457478
337
0.657495
ef5958c971f51209afa7f8f33a3ecfc34c49f82a
3,004
import SwiftUI import Harvest import HarvestStore struct DebugRootView: View { private let store: Store<DebugRoot.Input, DebugRoot.State>.Proxy private let usesTimeTravel: Bool init(store: Store<DebugRoot.Input, DebugRoot.State>.Proxy, usesTimeTravel: Bool = true) { self.store = store self.usesTimeTravel = usesTimeTravel } var body: some View { let rootView = RootView( store: self.store.timeTravel.inner .contramapInput { DebugRoot.Input.timeTravel(.inner($0)) } ) return If(self.store.state.usesTimeTravel) { VStack { rootView Divider() self.debugBottomView() } } .else { rootView } } private func debugBottomView() -> some View { VStack(alignment: .leading) { // HStack { // Toggle("Debug", isOn: store.$state.isDebug) // } // // Divider() timeTravelHeader() HStack { timeTravelSlider() timeTravelStepper() } } .padding() } private func timeTravelHeader() -> some View { HStack { Text("⏱ TIME TRAVEL ⌛").bold() Spacer() Button("Reset", action: { self.store.send(.timeTravel(.resetHistories)) }) } } private func timeTravelSlider() -> some View { HStack { Slider( value: self.store.timeTravel.timeTravellingSliderValue .stateBinding(onChange: { DebugRoot.Input.timeTravel(.timeTravelSlider(sliderValue: $0)) }), in: self.store.state.timeTravel.timeTravellingSliderRange, step: 1 ) .disabled(!self.store.state.timeTravel.canTimeTravel) Text("\(self.store.state.timeTravel.timeTravellingIndex) / \(Int(self.store.state.timeTravel.timeTravellingSliderRange.upperBound))") .font(Font.body.monospacedDigit()) .frame(minWidth: 80, alignment: .center) } } private func timeTravelStepper() -> some View { Stepper( onIncrement: { self.store.send(.timeTravel(.timeTravelStepper(diff: 1))) }, onDecrement: { self.store.send(.timeTravel(.timeTravelStepper(diff: -1))) } ) { EmptyView() } .frame(width: 100) } } struct DebugRootView_Previews: PreviewProvider { static var previews: some View { return Group { DebugRootView( store: .init( state: .constant(DebugRoot.State(inner: Root.State(), usesTimeTravel: true)), send: { _ in } ) ) .previewLayout(.fixed(width: 320, height: 480)) .previewDisplayName("Root") } } }
27.309091
145
0.524634
ff5863790c78bf7c248401fe929b82d5f16456d4
1,467
// // ViewModel.swift // QBChat-MVVM // // Created by Paul Kraft on 30.10.19. // Copyright © 2019 QuickBird Studios. All rights reserved. // import Combine import Foundation protocol ViewModel: ObservableObject where ObjectWillChangePublisher.Output == Void { associatedtype State associatedtype Input var state: State { get } func trigger(_ input: Input) } extension AnyViewModel: Identifiable where State: Identifiable { var id: State.ID { state.id } } @dynamicMemberLookup final class AnyViewModel<State, Input>: ViewModel { // MARK: Stored properties private let wrappedObjectWillChange: () -> AnyPublisher<Void, Never> private let wrappedState: () -> State private let wrappedTrigger: (Input) -> Void // MARK: Computed properties var objectWillChange: AnyPublisher<Void, Never> { wrappedObjectWillChange() } var state: State { wrappedState() } // MARK: Methods func trigger(_ input: Input) { wrappedTrigger(input) } subscript<Value>(dynamicMember keyPath: KeyPath<State, Value>) -> Value { state[keyPath: keyPath] } // MARK: Initialization init<V: ViewModel>(_ viewModel: V) where V.State == State, V.Input == Input { self.wrappedObjectWillChange = { viewModel.objectWillChange.eraseToAnyPublisher() } self.wrappedState = { viewModel.state } self.wrappedTrigger = viewModel.trigger } }
22.921875
91
0.670757
edb546108fabe682f0571b430aedee56e85f5cbf
2,608
// // VideoDetailViewController.swift // YoutubeApp // // Created by Ramapriya Ranganath on 6/26/17. // Copyright © 2017 Ramapriya Ranganath. All rights reserved. // import UIKit class VideoDetailViewController: UIViewController { @IBOutlet weak var webView: UIWebView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! var selectedVideo:Video? @IBOutlet weak var webViewHeightConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { if let vid = self.selectedVideo{ self.titleLabel.text = vid.videoTitle self.descriptionLabel.text = vid.videoDescription let width = self.view.frame.size.width let height = width/320 * 180 self.webViewHeightConstraint.constant = height //let videoEmbedString = "<html><head><style type=\"text/css\">body {background-color: transparent;color: white;}</style></head><body style=\"margin:0\"><iframe frameBorder=\"0\" height=\"" + String(describing: height) + "\" width=\"" + String(describing: width) + "\" src=\"http://www.youtube.com/embed/" + vid.videoId + "?showinfo=0&modestbranding=1&frameborder=0&rel=0\"></iframe></body></html>" let videoEmbedString = "<html><head><style type=\"text/css\">body {background-color: transparent;color: white;}</style></head><body style=\"margin:0\"><iframe frameBorder=\"0\" height=\"" + String(describing: height) + "\" width=\"" + String(describing: width) + "\" src=\"https://www.youtube.com/embed/?listType=playlist&list=" + String(vid.videoId) + "&modestbranding=1&frameborder=0&rel=0\"></iframe></body></html>" self.webView.loadHTMLString(videoEmbedString, baseURL: nil) } } /* // 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. } */ }
35.243243
430
0.622316
f846cfd1cc5089502432c18d32a93bedb2c9da32
782
// // AppDelegate.swift // StNesEmu // // Created by paraches on 2018/10/31. // Copyright © 2018年 paraches lifestyle lab. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let rfDeviceMonitor = HIDDeviceMonitor([HIDMonitorData(vendorId: 1112, productId: 4098)], reportSize: 64) func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application let rfDeviceDaemon = Thread(target: self.rfDeviceMonitor, selector: #selector(self.rfDeviceMonitor.start), object: nil) rfDeviceDaemon.start() } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
26.965517
127
0.727621
014c7461224ff58b05d1102945f8cdf098ea1c59
4,650
// // ALKConversationViewControllerUITests.swift // ApplozicSwiftDemoTests // // Created by Mukesh Thawani on 17/06/18. // Copyright © 2018 Applozic. All rights reserved. // import Quick import Nimble import Nimble_Snapshots import Applozic @testable import ApplozicSwift class ALKConversationViewControllerListSnapShotTests: QuickSpec { override func spec() { describe("Conversation list") { var conversationVC: ALKConversationListViewController! var navigationController: UINavigationController! beforeEach { conversationVC = ALKConversationListViewController(configuration: ALKConfiguration()) ALMessageDBServiceMock.lastMessage.createdAtTime = NSNumber(value: Date().timeIntervalSince1970 * 1000) conversationVC.dbService = ALMessageDBServiceMock() let firstMessage = MockMessage().message firstMessage.message = "first message" let secondmessage = MockMessage().message secondmessage.message = "second message" ALKConversationViewModelMock.testMessages = [firstMessage.messageModel, secondmessage.messageModel] conversationVC.conversationViewModelType = ALKConversationViewModelMock.self navigationController = ALKBaseNavigationViewController(rootViewController: conversationVC) conversationVC.beginAppearanceTransition(true, animated: false) conversationVC.endAppearanceTransition() } it("Show list") { XCTAssertNotNil(navigationController.view) XCTAssertNotNil(conversationVC.view) expect(navigationController).to(haveValidSnapshot()) } it("Open chat thread") { XCTAssertNotNil(conversationVC.tableView) guard let tableView = conversationVC.tableView else { return } tableView.delegate?.tableView?(tableView, didSelectRowAt: IndexPath(row: 0, section: 0)) XCTAssertNotNil(conversationVC.navigationController?.view) expect(conversationVC.navigationController).toEventually(haveValidSnapshot()) } } context("Conversation list screen") { var conversationVC: ALKConversationListViewController! var navigationController: UINavigationController! beforeEach { conversationVC = ALKConversationListViewController(configuration: ALKConfiguration()) let mockMessage = ALMessageDBServiceMock.lastMessage! mockMessage.message = "Re: Subject" mockMessage.contentType = Int16(ALMESSAGE_CONTENT_TEXT_HTML) mockMessage.source = 7 mockMessage.createdAtTime = NSNumber(value: Date().timeIntervalSince1970 * 1000) conversationVC.dbService = ALMessageDBServiceMock() navigationController = ALKBaseNavigationViewController(rootViewController: conversationVC) } it("show email thread") { expect(navigationController).to(haveValidSnapshot()) } } describe("configure right nav bar icon") { var configuration: ALKConfiguration! var conversationVC: ALKConversationListViewController! var navigationController: UINavigationController! beforeEach { configuration = ALKConfiguration() configuration.rightNavBarImageForConversationListView = UIImage(named: "close", in: Bundle.applozic, compatibleWith: nil) conversationVC = ALKConversationListViewController(configuration: configuration) conversationVC.dbService = ALMessageDBServiceMock() conversationVC.conversationViewModelType = ALKConversationViewModelMock.self conversationVC.beginAppearanceTransition(true, animated: false) conversationVC.endAppearanceTransition() navigationController = ALKBaseNavigationViewController(rootViewController: conversationVC) } it("change icon image") { navigationController.navigationBar.snapshotView(afterScreenUpdates: true) expect(navigationController.navigationBar).to(haveValidSnapshot()) } } } func getApplicationKey() -> NSString { let appKey = ALUserDefaultsHandler.getApplicationKey() as NSString? let applicationKey = appKey return applicationKey! } }
42.66055
137
0.66
22f30628c9ade947504e2f0616ec9c1be495a782
1,446
// // tipcalculatorUITests.swift // tipcalculatorUITests // // Created by Kay Lab on 1/14/20. // Copyright © 2020 Meryl Marasigan. All rights reserved. // import XCTest class tipcalculatorUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
32.863636
182
0.656293
4674a92238b8d3eda115bb52a22ecba6902a463c
2,173
import Foundation import ProjectDescription import TSCBasic import TSCUtility import TuistCore import TuistSupport /// A protocol that defines an interface to generate the `DependenciesGraph` for the `Carthage` dependencies. public protocol CarthageGraphGenerating { /// Generates the `DependenciesGraph` for the `Carthage` dependencies. /// - Parameter path: The path to the directory that contains the `Carthage/Build` directory where `Carthage` installed dependencies. func generate(at path: AbsolutePath) throws -> DependenciesGraph } public final class CarthageGraphGenerator: CarthageGraphGenerating { public init() {} public func generate(at path: AbsolutePath) throws -> DependenciesGraph { let versionFilePaths = try FileHandler.shared .contentsOfDirectory(path) .filter { $0.extension == "version" } let jsonDecoder = JSONDecoder() let products = try versionFilePaths .map { try FileHandler.shared.readFile($0) } .map { try jsonDecoder.decode(CarthageVersionFile.self, from: $0) } .flatMap { $0.allProducts } let externalDependencies: [String: [TargetDependency]] = Dictionary(grouping: products, by: \.name) .compactMapValues { products in guard let product = products.first else { return nil } guard let xcFrameworkName = product.container else { logger.warning("\(product.name) was not added to the DependenciesGraph", metadata: .subsection) return nil } var pathString = "" pathString += Constants.tuistDirectoryName pathString += "/" pathString += Constants.DependenciesDirectory.name pathString += "/" pathString += Constants.DependenciesDirectory.carthageDirectoryName pathString += "/Build/" pathString += xcFrameworkName return [.xcframework(path: Path(pathString))] } return DependenciesGraph(externalDependencies: externalDependencies, externalProjects: [:]) } }
41
137
0.649793
ffe06fdf424e3bae08fc1420192657ce8a8860ff
860
// // TableCell.swift // GravityXR // // Created by Avinash Shetty on 4/25/20. // Copyright © 2020 GravityXR. All rights reserved. // import Foundation import UIKit public class TableCell: UITableViewCell { @IBOutlet private var titleLabel: UILabel! @IBOutlet private var subtitleLabel: UILabel! @IBOutlet private var thumbnailImageView: UIImageView! public override func prepareForReuse() { super.prepareForReuse() titleLabel.text = nil subtitleLabel.text = nil thumbnailImageView.image = nil } // MARK: Cell Configuration public func configurateTheCell(_ product: Product) { titleLabel.text = product.name subtitleLabel.text = product.description if let imgURL = product.thumbnails { thumbnailImageView.image = UIImage(named: imgURL) } } }
24.571429
61
0.676744
56af54f08b7f389d96e27ad792b52b6b98668954
2,880
import UIKit import QuartzCore @IBDesignable extension UIView { @IBInspectable open var borderColor: UIColor? { set { layer.borderColor = newValue!.cgColor } get { if let color = layer.borderColor { return UIColor(cgColor:color) } else { return nil } } } @IBInspectable open var borderWidth: CGFloat { set { layer.borderWidth = newValue } get { return layer.borderWidth } } @IBInspectable open var cornerRadius: CGFloat { set { layer.cornerRadius = newValue clipsToBounds = newValue > 0 } get { return layer.cornerRadius } } /// The color of the shadow. Defaults to opaque black. Colors created from patterns are currently NOT supported. Animatable. @IBInspectable open var shadowColor: UIColor? { get { return UIColor(cgColor: self.layer.shadowColor!) } set { self.layer.shadowColor = newValue?.cgColor } } /// The opacity of the shadow. Defaults to 0. Specifying a value outside the [0,1] range will give undefined results. Animatable. @IBInspectable open var shadowOpacity: Float { get { return self.layer.shadowOpacity } set { self.layer.shadowOpacity = newValue } } /// The shadow offset. Defaults to (0, -3). Animatable. @IBInspectable open var shadowOffset: CGSize { get { return self.layer.shadowOffset } set { self.layer.shadowOffset = newValue } } /// The blur radius used to create the shadow. Defaults to 3. Animatable. @IBInspectable open var shadowRadius: Double { get { return Double(self.layer.shadowRadius) } set { self.layer.shadowRadius = CGFloat(newValue) } } } // MARK: Dots & Shadows extension UIView { open func addDashedBorder(color: UIColor) { let color = color.cgColor let shapeLayer: CAShapeLayer = CAShapeLayer() let frameSize = self.frame.size let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height) shapeLayer.bounds = shapeRect shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2) shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = color shapeLayer.lineWidth = 2 shapeLayer.lineJoin = kCALineJoinRound shapeLayer.lineDashPattern = [6, 3] shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 0).cgPath self.layer.addSublayer(shapeLayer) } open func noShadow() { self.layer.shadowColor = UIColor.clear.cgColor self.layer.shadowOpacity = 0 self.layer.shadowOffset = CGSize(width: 0, height: 0) self.layer.shadowRadius = 0.0 } } // MARK: Subviews handler extension UIView { open func removeAllSubViews() { _ = self.subviews.map { $0.removeFromSuperview() } } }
24.827586
131
0.65625
719940d265e0ff87f9a7a2a2bfe243c07a324dbb
1,726
// // DetailViewController.swift // iOSApp // // Created by alvinwan on 1/4/16. // Copyright (c) 2016 TExBerkeley. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var labelName: UILabel! @IBOutlet weak var labelByline: UILabel! @IBOutlet weak var image: UIImageView! @IBOutlet weak var labelBio: UITextView! @IBOutlet weak var imageBG: UIImageView! var items = ["name": "loading...", "byline": "loading...", "bio": "loading..."] override func viewDidLoad() { super.viewDidLoad() updateLabels(); image.layer.cornerRadius = 75; image.clipsToBounds = true; image.layer.borderWidth = 10.0; image.layer.borderColor = UIColor.whiteColor().CGColor // Do any additional setup after loading the view. } func updateLabels() { labelName?.text = self.items["name"] labelByline?.text = self.items["byline"] labelBio?.text = self.items["bio"] image?.image = UIImage(named: String(self.items["image"]!+"")) imageBG?.image = UIImage(named: String(self.items["image"]!+"")) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
29.254237
106
0.63847
288e8f0c1da5f70de026990f40115f1aef20f8a5
4,146
// // AlgorandURI.swift // AlgorandKit // // Copyright (c) 2021 DD1F4B695C20D472FCA0333D524889C5B22A919268177D7F6E8B5EBB5B57427A // import Foundation /// Encapsulates the logic for creating a URL based on the Algorand URI spec, /// defined at https://developer.algorand.org/docs/reference/payment_prompts/ /// /// AlgorandURI is immutable by design, and enforces logic for parameter validation /// at compile-time through its type definitions. /// public struct AlgorandURI { private let uriScheme = "algorand" /// Wrapper around the transaction's receiver. public struct Receiver { /// /// Receiver's Algorand address. /// /// AlgorandURI treats addresses opaquely, and by design does not validate them. /// Addresses are encoded and passed through to the host wallet for validation. public let address: String /// /// Optional label for this address (e.g. name of receiver) public let label: String? /// /// Memberwise initializer public init(address: String, label: String?) { self.address = address self.label = label } } /// Receiver for the transaction represented by this AlgorandURI public let receiver: Receiver /// Wrapper around the transaction's asset. /// /// Explicitly define the case for Algos (in units of microAlgos) for convenience /// and to help avoid accidental misuse. /// /// See assetAmount parameter for more information on asset units. public enum AssetAmount { case algo(microAlgos: UInt) case ASA(assetID: UInt, amount: UInt) } /// The asset and corresponding amount of asset for the transaction represented /// by this AlgorandURI. /// /// If an amount is provided, it MUST be specified in basic unit of the asset. /// For example, if it’s Algos (Algorand native unit), the amount should be specified /// in microAlgos. /// /// e.g. for 100 Algos, the amount needs to be 100000000, for 54.1354 Algos the /// amount needs to be 54135400. public let assetAmount: AssetAmount? /// Wrapper around the transaction note. /// /// readonly (xnote): A URL-encoded notes field value that must not be modifiable by the /// user when displayed to users. /// editable (note): A URL-encoded default notes field value that the the user interface /// may optionally make editable by the user. public enum Note { case readonly(xnote: String) case editable(note: String) } /// Optional transaction note for this AlgorandURI, which may be specified to be either /// readonly or editable by the user. public let note: Note? /// Memberwise initializer public init(receiver: Receiver, assetAmount: AssetAmount?, note: Note?) { self.receiver = receiver self.assetAmount = assetAmount self.note = note } /// URL for this AlgorandURI /// /// After initialization, url() may be called to generate a runnable URL (NSURL) which, /// when requested, should be dispatched to the app registered to handle the "algorand:" /// URI scheme. public func url() -> URL? { var components = URLComponents() components.scheme = uriScheme components.host = receiver.address components.path = "" var queryItems: [URLQueryItem] = [] if let label = receiver.label { queryItems.append(URLQueryItem(name: "label", value: label)) } switch assetAmount { case .some(.algo(let microAlgos)): queryItems.append(URLQueryItem(name: "amount", value: String(microAlgos))) case .some(.ASA(let assetID, let amount)): queryItems.append(URLQueryItem(name: "asset", value: String(assetID))) queryItems.append(URLQueryItem(name: "amount", value: String(amount))) case .none: break } switch note { case .some(.readonly(let xnote)): queryItems.append(URLQueryItem(name: "xnote", value: xnote)) case .some(.editable(let note)): queryItems.append(URLQueryItem(name: "note", value: note)) case .none: break } if (queryItems.count > 0) { components.queryItems = queryItems } return components.url } }
32.645669
90
0.67945
7a851d9cf8e80738f6f6d5157784750ceec74b3e
4,645
/* This SDK is licensed under the MIT license (MIT) Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France) 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. */ // // TechnicalContextTests.swift // Tracker // import UIKit import XCTest class TechnicalContextTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } /* On test les différentes possiblités de récupération d'un id client */ func testIDFV() { let ref = UIDevice.current.identifierForVendor!.uuidString XCTAssertNotNil(ref, "IDFV shall not be nil") XCTAssertEqual(ref, TechnicalContext.userId("idfv"), "Unique identifier shall be equal to IDFV") } func testExistingUUID() { let ref = UUID().uuidString UserDefaults.standard.set(ref, forKey: "ATApplicationUniqueIdentifier") UserDefaults.standard.synchronize() XCTAssertNotNil(ref, "UUID shall not be nil") XCTAssertEqual(ref, TechnicalContext.userId("whatever"), "Unique identifier shall be equal to existing UUID") } func testNonExistingUUID() { UserDefaults.standard.removeObject(forKey: "ATApplicationUniqueIdentifier") UserDefaults.standard.synchronize() XCTAssertEqual(36, TechnicalContext.userId("whatever").characters.count, "Unique identifier shall be a new valid UUID") } func testUserIdWithNilConfiguration() { UserDefaults.standard.removeObject(forKey: "ATApplicationUniqueIdentifier") UserDefaults.standard.synchronize() XCTAssertEqual(36, TechnicalContext.userId(nil).characters.count, "Unique identifier shall be a new valid UUID") } func testSDKVersion() { XCTAssertNotNil(TechnicalContext.sdkVersion, "SDK version shall not be nil") XCTAssertNotEqual("", TechnicalContext.sdkVersion, "SDK version shall not have an empty string value") } func testLanguage() { XCTAssertNotNil(TechnicalContext.language, "Language shall not be nil") XCTAssertNotEqual("", TechnicalContext.language, "Language shall not have an empty string value") } func testDevice() { XCTAssertNotNil(TechnicalContext.device, "Device shall not be nil") XCTAssertNotEqual("", TechnicalContext.device, "Device shall not have an empty string value") } func testApplicationIdentifier() { XCTAssertNotNil(TechnicalContext.applicationIdentifier, "Application identifier shall not be nil") } func testApplicationVersion() { XCTAssertNotNil(TechnicalContext.applicationVersion, "Application version shall not be nil") } func testLocalHour() { XCTAssertNotNil(TechnicalContext.localHour, "Local hour shall not be nil") XCTAssertNotEqual("", TechnicalContext.localHour, "Local hour shall not have an empty string value") } func testScreenResolution() { XCTAssertNotNil(TechnicalContext.screenResolution, "Screen resolution shall not be nil") XCTAssertNotEqual("", TechnicalContext.screenResolution, "Screen resolution shall not have an empty string value") } func testCarrier() { XCTAssertNotNil(TechnicalContext.carrier, "Carrier shall not be nil") } func testConnectionType() { XCTAssertNotNil(TechnicalContext.connectionType.rawValue, "Connection type shall not be nil") XCTAssertNotEqual("", TechnicalContext.connectionType.rawValue, "Connection type shall not have an empty string value") } }
40.043103
141
0.725942
5dec15f0ed7434913c480b063e1ee933851d9b9c
7,574
// // SensorConnector.swift // LibreDirect // import Combine import Foundation func sensorConnectorMiddelware(_ infos: [SensorConnectionInfo]) -> Middleware<AppState, AppAction> { return sensorConnectorMiddelware(infos, subject: PassthroughSubject<AppAction, AppError>(), calibrationService: { CalibrationService() }()) } private func sensorConnectorMiddelware(_ infos: [SensorConnectionInfo], subject: PassthroughSubject<AppAction, AppError>, calibrationService: CalibrationService) -> Middleware<AppState, AppAction> { return { state, action, _ in switch action { case .startup: let registerConnectionInfo = Just(AppAction.registerConnectionInfo(infos: infos)) var selectConnection: Just<AppAction>? if let id = state.selectedConnectionId, let connectionInfo = infos.first(where: { $0.id == id }) { AppLog.info("Select startup connection: \(connectionInfo.name)") selectConnection = Just(.selectConnection(id: connectionInfo.id, connection: connectionInfo.connectionCreator(subject))) } else if infos.count == 1, let connectionInfo = infos.first { AppLog.info("Select single startup connection: \(connectionInfo.name)") selectConnection = Just(.selectConnection(id: connectionInfo.id, connection: connectionInfo.connectionCreator(subject))) } else if let connectionInfo = infos.first { AppLog.info("Select first startup connection: \(connectionInfo.name)") selectConnection = Just(.selectConnection(id: connectionInfo.id, connection: connectionInfo.connectionCreator(subject))) } if let selectConnection = selectConnection { return registerConnectionInfo .merge(with: selectConnection) .setFailureType(to: AppError.self) .merge(with: subject) .eraseToAnyPublisher() } return registerConnectionInfo .setFailureType(to: AppError.self) .merge(with: subject) .eraseToAnyPublisher() case .selectConnectionId(id: let id): if let connectionInfo = state.connectionInfos.first(where: { $0.id == id }) { let connection = connectionInfo.connectionCreator(subject) return Just(.selectConnection(id: id, connection: connection)) .setFailureType(to: AppError.self) .eraseToAnyPublisher() } case .selectConnection(id: _, connection: _): if state.isPaired, state.isConnectable { return Just(.connectSensor) .setFailureType(to: AppError.self) .eraseToAnyPublisher() } case .addSensorReadings(sensorSerial: _, trendReadings: let trendReadings, historyReadings: let historyReadings): if !trendReadings.isEmpty, !historyReadings.isEmpty { let missingHistory = historyReadings.filter { reading in if state.currentGlucose == nil || reading.timestamp > state.currentGlucose!.timestamp, reading.timestamp < trendReadings.first!.timestamp { return true } return false } let missingTrend = trendReadings .filter { reading in if state.currentGlucose == nil || reading.timestamp > state.currentGlucose!.timestamp { return true } return false } var previousGlucose = state.currentGlucose var missedGlucosValues: [Glucose] = [] missingHistory.forEach { reading in let glucose = calibrationService.calibrate(customCalibration: state.customCalibration, nextReading: reading, currentGlucose: previousGlucose) missedGlucosValues.append(glucose) if glucose.quality == .OK { previousGlucose = glucose } } missingTrend.forEach { reading in let glucose = calibrationService.calibrate(customCalibration: state.customCalibration, nextReading: reading, currentGlucose: previousGlucose) missedGlucosValues.append(glucose) if glucose.quality == .OK { previousGlucose = glucose } } return Just(.addGlucoseValues(glucoseValues: missedGlucosValues)) .setFailureType(to: AppError.self) .eraseToAnyPublisher() } case .scanSensor: guard let sensorConnection = state.selectedConnection else { AppLog.info("Guard: state.selectedConnection is nil") break } if let sensorConnection = sensorConnection as? SensorNFCConnection { AppLog.info("no Pairing: \(!state.isPaired)") sensorConnection.scanSensor(noPairing: state.isPaired) } case .pairSensor: guard let sensorConnection = state.selectedConnection else { AppLog.info("Guard: state.selectedConnection is nil") break } sensorConnection.pairSensor() case .setSensorInterval(interval: _): if state.isDisconnectable, let sensorConnection = state.selectedConnection { sensorConnection.disconnectSensor() return Just(.connectSensor) .setFailureType(to: AppError.self) .eraseToAnyPublisher() } case .connectSensor: guard let sensorConnection = state.selectedConnection else { AppLog.info("Guard: state.selectedConnection is nil") break } if let sensor = state.sensor { sensorConnection.connectSensor(sensor: sensor, sensorInterval: state.sensorInterval) } else { sensorConnection.pairSensor() } case .disconnectSensor: guard let sensorConnection = state.selectedConnection else { AppLog.info("Guard: state.selectedConnection is nil") break } sensorConnection.disconnectSensor() case .setSensor(sensor: _, wasPaired: let wasPaired): guard wasPaired else { AppLog.info("Guard: sensor was not paired, no auto connect") break } return Just(.connectSensor) .setFailureType(to: AppError.self) .eraseToAnyPublisher() default: break } return Empty().eraseToAnyPublisher() } } typealias SensorConnectionCreator = (PassthroughSubject<AppAction, AppError>) -> SensorBLEConnection // MARK: - SensorConnectionInfo class SensorConnectionInfo: Identifiable { // MARK: Lifecycle init(id: String, name: String, connectionCreator: @escaping SensorConnectionCreator) { self.id = id self.name = name self.connectionCreator = connectionCreator } // MARK: Internal let id: String let name: String let connectionCreator: SensorConnectionCreator }
39.041237
198
0.585028
db6e648e50b157bd1a20076a9b79f7625d06b6fd
2,578
// // ColorPicker.swift // Timmee // // Created by Ilya Kharabet on 22.10.17. // Copyright © 2017 Mesterra. All rights reserved. // import UIKit final class ColorPicker: UIView { var colors: [UIColor] = [] { didSet { colorsCollectionView?.reloadData() } } var onSelectColor: ((UIColor) -> Void)? @IBInspectable var selectedColorIndex: Int = 0 { didSet { guard selectedColorIndex >= 0 else { return } guard oldValue != selectedColorIndex else { return } if colors.indices.contains(selectedColorIndex) { let color = colors[selectedColorIndex] onSelectColor?(color) colorsCollectionView?.reloadItems(at: [IndexPath(item: oldValue, section: 0), IndexPath(item: selectedColorIndex, section: 0)]) } } } @IBOutlet fileprivate weak var colorsCollectionView: UICollectionView! { didSet { colorsCollectionView.reloadData() } } } extension ColorPicker: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return colors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorPickerCell", for: indexPath) as! ColorPickerCell cell.color = colors.item(at: indexPath.item) cell.isPicked = indexPath.item == selectedColorIndex return cell } } extension ColorPicker: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedColorIndex = indexPath.item } } final class ColorPickerCell: UICollectionViewCell { @IBOutlet fileprivate weak var pickedImageView: UIImageView! { didSet { pickedImageView.tintColor = AppTheme.current.foregroundColor } } @IBInspectable var isPicked: Bool = false { didSet { pickedImageView.isHidden = !isPicked } } var color: UIColor? { didSet { backgroundColor = color } } }
27.425532
121
0.596974
39450ecb35f30e692e886189b7c7d312fce2c076
968
// // PaginationCellViewModel.swift // Nearby // // Created by Mehul on 06/29/19. // Copyright © 2018 Demo. All rights reserved. // import Foundation class PaginationCellVM { // Output var numberOfPages = 0 var title = "" // Datasource private var dataSource = [Place]() // Events var placeSelected: (Place)->()? init(data: [Place], placeSelected: @escaping (Place)->()) { dataSource = data self.placeSelected = placeSelected configureOutput() } private func configureOutput() { numberOfPages = dataSource.count title = "Hot picks only for you" } func viewModelForPlaceView(position: Int)->PlaceViewVM { let place = dataSource[position] let placeViewVM = PlaceViewVM(place: place) placeViewVM.placesViewSelected = { [weak self] in self?.placeSelected(place) } return placeViewVM } }
22
63
0.600207
e58f2c7c15854710c84171a3c53cd2064df25062
160
// RUN: not --crash %target-swift-frontend %s -parse extension Collection { func f() -> [Generator.Element] { return Array(self.prefix(0)) } }
20
52
0.6125
bb141700f046df2014d02f793d65921e850dee30
6,674
// // ViewControllerInner.swift // Sundial_Example // // Created by Sergei Mikhan on 11/17/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import Astrolabe import Sundial import RxSwift import RxCocoa public class CollapsingCell: CollectionViewCell, Reusable { let title: UILabel = { let title = UILabel() title.textColor = .white title.textAlignment = .center return title }() open override func setup() { super.setup() contentView.backgroundColor = .orange contentView.addSubview(title) } open override func layoutSubviews() { super.layoutSubviews() title.frame = contentView.bounds title.text = "HEADER height is \(Int(self.frame.height))" } public static func size(for data: Void, containerSize: CGSize) -> CGSize { return CGSize(width: containerSize.width, height: 276) } } public class TestCell: CollectionViewCell, Reusable { let title: UILabel = { let title = UILabel() title.textColor = .white title.textAlignment = .center return title }() open override func setup() { super.setup() self.backgroundColor = .green contentView.addSubview(title) } open override func layoutSubviews() { super.layoutSubviews() title.frame = contentView.bounds } open func setup(with data: String) { title.text = data } public static func size(for data: String, containerSize: CGSize) -> CGSize { return CGSize(width: containerSize.width, height: containerSize.width * 0.35) } } class ColoredViewController: UIViewController, ReusedPageData, CollapsingItem { var scrollView: UIScrollView { return containerView } var visible = BehaviorRelay<Bool>(value: false) var data: UIColor? { didSet { containerView.backgroundColor = data } } let containerView = CollectionView<CollectionViewSource>() override func viewDidLoad() { super.viewDidLoad() containerView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 320.0, height: 640.0)) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumInteritemSpacing = 30.0 layout.minimumLineSpacing = 30.0 containerView.collectionViewLayout = layout containerView.backgroundColor = .red containerView.decelerationRate = .fast view.addSubview(containerView) let cells: [Cellable] = (1...50).map { "Item \($0)" }.map { CollectionCell<TestCell>(data: $0) } containerView.source.sections = [Section(cells: []), Section(cells: cells), Section(cells: []),] } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() containerView.frame = view.bounds } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) visible.accept(true) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) visible.accept(false) } } class ViewControllerInner: UIViewController { var inverted = false let anchor: Anchor var count: Int let margin: CGFloat init(_ anchor: Anchor, count: Int = 5, margin: CGFloat = 80) { self.anchor = anchor self.count = count self.margin = margin guard (1 ... 5).contains(count) else { fatalError() } super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let collectionView = CollectionView<CollectionViewReusedPagerSource>() class TestDeccoration: DecorationCollectionViewCell<String> { } override func viewDidLoad() { super.viewDidLoad() collectionView.source.hostViewController = self let margin: CGFloat switch anchor { case .fillEqual: margin = 0.0 default: margin = self.margin } let settings = Settings(stripHeight: 80.0, markerHeight: 5.5, itemMargin: 0.0, stripInsets: .init(top: 0.0, left: 0.0, bottom: 44.0, right: 0.0), backgroundColor: .white, anchor: anchor, inset: UIEdgeInsets(top: 0, left: margin, bottom: 0, right: margin), alignment: .bottom, jumpingPolicy: .skip(pages: 1), numberOfTitlesWhenHidden: 1) let layout = PagerHeaderCollectionViewLayout(hostPagerSource: collectionView.source, settings: settings) layout.register(emptyViewDecoration: TestDeccoration.self, emptyViewData: "", showEmptyView: BehaviorSubject<Bool>(value: true)) layout.headerHeight.accept(320.0) layout.minHeaderHeight.accept(80.0) layout.maxHeaderHeight.accept(320.0) collectionView.collectionViewLayout = layout view.addSubview(collectionView) collectionView.snp.remakeConstraints { $0.edges.equalToSuperview() } let colors: [UIColor] = [ .blue, .black, .green, .gray, .orange ] let cells: [Cellable] = colors.prefix(count).map { CollectionCell<ReusedPagerCollectionViewCell<ColoredViewController>>(data: $0, setup: { [weak layout] cellView in layout?.append(collapsingItems: [cellView.viewController]) }) } typealias Supplementary = PagerHeaderSupplementaryView<TitleCollectionViewCell, MarkerDecorationView<TitleCollectionViewCell.Data>> let supplementaryPager = CollectionCell<Supplementary>(data: titles, id: "", click: nil, type: .custom(kind: PagerHeaderSupplementaryViewKind), setup: nil) let supplementaryCollapsing = CollectionCell<CollapsingCell>(data: (), id: "", click: nil, type: .custom(kind: PagerHeaderCollapsingSupplementaryViewKind), setup: nil) let section = MultipleSupplementariesSection(supplementaries: [supplementaryPager, supplementaryCollapsing], cells: cells) collectionView.source.sections = [section] collectionView.reloadData() } } extension ViewControllerInner { var titles: [TitleCollectionViewCell.TitleViewModel] { return Array([ TitleCollectionViewCell.TitleViewModel(title: "1111111", id: "Inverted Mid Blue", indicatorColor: .magenta), TitleCollectionViewCell.TitleViewModel(title: "2222222", indicatorColor: .black), TitleCollectionViewCell.TitleViewModel(title: "3333333", indicatorColor: .green), TitleCollectionViewCell.TitleViewModel(title: "4444444", indicatorColor: .gray), TitleCollectionViewCell.TitleViewModel(title: "5555555", indicatorColor: .orange) ].prefix(count)) } }
30.614679
142
0.676206
7201551e4637784016c552ccafbeb957ecf21d0c
3,746
import CoreFoundation public extension CFArray { @inlinable static func create(allocator: CFAllocator = .default, values: UnsafeMutablePointer<UnsafeRawPointer?>?, count: CFIndex, pCallBacks: UnsafePointer<CFArrayCallBacks>? = pCFTypeArrayCallBacks) -> CFArray { return CFArrayCreate(allocator, values, count, pCallBacks) } static let empty: CFArray = CFArray.create(values: nil, count: 0) @inlinable var count: CFIndex { return CFArrayGetCount(self) } @inlinable var fullRange: CFRange { return CFRange(location: 0, length: count) } @inlinable func count(of value: CFTypeRef) -> CFIndex { return count(of: value, in: fullRange) } @inlinable func count(of value: CFTypeRef, in range: CFRange) -> CFIndex { return CFArrayGetCountOfValue(self, range, bridge(value)) } @inlinable func contains(_ value: CFTypeRef, in range: CFRange? = nil) -> Bool { return CFArrayContainsValue(self, range ?? fullRange, bridge(value)) } @inlinable func value(at index: CFIndex) -> CFTypeRef { return bridge(rawValue(at: index)) } @inlinable func rawValue(at index: CFIndex) -> UnsafeRawPointer { return CFArrayGetValueAtIndex(self, index)! } @inlinable func values(in range: CFRange) -> [CFTypeRef] { guard range.length > 0 else { return [] } return Array(unsafeUninitializedCapacity: range.length) { p, count in CFArrayGetValues(self, range, UnsafeMutablePointer(OpaquePointer(p.baseAddress))) count = range.length } } } extension CFArray: RandomAccessCollection { @inlinable public var startIndex: Int { return 0 } @inlinable public var endIndex: Int { return count } @inlinable public subscript(position: Int) -> CFTypeRef { return value(at: position) } } // MARK: - CFMutableArray public extension CFMutableArray { @inlinable static func create(allocator: CFAllocator = .default, capacity: CFIndex = 0, pCallBacks: UnsafePointer<CFArrayCallBacks>? = pCFTypeArrayCallBacks) -> CFMutableArray { return CFArrayCreateMutable(allocator, capacity, pCallBacks) } @inlinable func append(_ value: CFTypeRef) { append(rawValue: bridge(value)) } @inlinable func append(rawValue: UnsafeRawPointer) { CFArrayAppendValue(self, rawValue) } @inlinable func append(contentsOf array: CFArray, range: CFRange? = nil) { CFArrayAppendArray(self, array, range ?? array.fullRange) } @inlinable func insert(_ value: CFTypeRef, at index: CFIndex) { insert(rawValue: bridge(value), at: index) } @inlinable func insert(rawValue: UnsafeRawPointer, at index: CFIndex) { CFArrayInsertValueAtIndex(self, index, rawValue) } @inlinable func set(_ value: CFTypeRef, at index: CFIndex) { set(rawValue: bridge(value), at: index) } @inlinable func set(rawValue: UnsafeRawPointer, at index: CFIndex) { CFArraySetValueAtIndex(self, index, rawValue) } @inlinable func remove(at index: CFIndex) { CFArrayRemoveValueAtIndex(self, index) } @inlinable func removeAll() { CFArrayRemoveAllValues(self) } @inlinable func replace(range: CFRange, values: [CFTypeRef]) { values.withUnsafeBufferPointer { p in CFArrayReplaceValues(self, range, UnsafeMutablePointer(OpaquePointer(p.baseAddress)), values.count) } } @inlinable func swapAt(_ i: CFIndex, _ j: CFIndex) { CFArrayExchangeValuesAtIndices(self, i, j) } }
31.216667
217
0.648959
fe625b3bdad3ad0d8b84d505d32d40c6ce5ca14b
3,702
// // AppDelegate.swift // Twitter // // Created by Emmanuel Sarella on 4/13/17. // Copyright © 2017 Emmanuel Sarella. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. debugPrint("application did finish launching with options") if User.currentUser != nil { let storyboard = UIStoryboard(name: "Main", bundle: nil) let tweetsNavigationController = storyboard.instantiateViewController(withIdentifier: "TweetsNavigationController") let tweetsVC = tweetsNavigationController.childViewControllers[0] as! TweetsViewController tweetsVC.currentUser = User.currentUser window?.rootViewController = tweetsNavigationController } NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: User.userDidLogout), object: nil, queue: OperationQueue.main) { (notification: Notification) in let storyboard = UIStoryboard(name: "Main", bundle: nil) let loginViewController = storyboard.instantiateInitialViewController() // CAN ANIMATE THIS self.window?.rootViewController = loginViewController } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. debugPrint("application will resign active") } 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. debugPrint("application did enter background") } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. debugPrint("application will enter foreground") } 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. debugPrint("application did become active") } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. debugPrint("application will terminate") } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { TwitterClient.sharedInstance.openURL(url) return true } }
50.027027
285
0.71799
16395673423d43401c39c17d7e0881bf6f998a58
6,161
// // ViewController.swift // search // // Created by 彭盛凇 on 2016/11/1. // Copyright © 2016年 huangbaoche. All rights reserved. // import UIKit class ViewController: UIViewController { let cellID = "cellID" let allDataList:Array<String> = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"] //数据源数组 var resultDaraList:Array<String> = [] //搜索结果数组 lazy var searchBar:UISearchBar = { let bar = UISearchBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44)) bar.barStyle = .black //默认defalut bar.placeholder = "搜索" //提示文字 bar.showsCancelButton = true //显示右侧cancel按钮 bar.showsScopeBar = true //范围? bar.showsBookmarkButton = true //显示testField右侧书签按钮 // bar.showsSearchResultsButton = true //显示testField右侧蓝色按钮 bar.isSearchResultsButtonSelected = true bar.delegate = self return bar }() lazy var tableView: UITableView = { let tableview = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), style: .plain) tableview.register(UITableViewCell.self, forCellReuseIdentifier: self.cellID) tableview.showsVerticalScrollIndicator = false//隐藏 右侧滚动条 tableview.delegate = self tableview.dataSource = self tableview.tableHeaderView = self.searchBar return tableview }() override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = true//恢复自定义,关闭系统自适应 title = "我是title" resultDaraList = allDataList view.addSubview(tableView) } } extension ViewController: UISearchBarDelegate { @available(iOS 2.0, *) public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {//开始编辑,如果返回NO,则不成为第一响应者(显示键盘) return true }// return NO to not become first responder @available(iOS 2.0, *) public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {//当searchBar 开始编辑的时候 if searchBar.text == "" { //开始编辑,清空数组,刷新tableview,在此方法中写和返回布尔值得方法中写,效果一样 resultDaraList = allDataList tableView.reloadData() }else{//当搜索栏中有数据时,则不重置数据源,不刷新tableview return } }// called when text starts editing @available(iOS 2.0, *) public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {//结束编辑,如果返回NO,则不 取消第一响应者(隐藏键盘) return true }// return NO to not resign first responder @available(iOS 2.0, *) public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {//已经结束编辑 if searchBar.text == "" { //结束编辑,更新数组为数据源,刷新tableview,在此方法中写和返回布尔值得方法中写,效果一样 resultDaraList = allDataList tableView.reloadData() }else {//当搜索栏中有数据时,则不重置数据源,不刷新tableview return } }// called when text ends editing @available(iOS 2.0, *) public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {//当searchBar进行修改的时候(包括点击清除按钮) print(searchText) if searchText == "" { resultDaraList = allDataList }else { resultDaraList = [] for string in allDataList { if string.lowercased().hasPrefix(searchText.lowercased()) { resultDaraList.append(string) } } } tableView.reloadData() }// called when text changes (including clear)主要用这个!!! @available(iOS 3.0, *) public func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool{ return true }// called before text changes 在searchBar进行修改(textDidChange之前调用)之前,如果返回no,则不会调用textDidChange,并且输入文字不会显示在searchBar中 @available(iOS 2.0, *) public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {//当搜索按钮被点击时,(键盘中的搜索按钮)是否需要做操作,一般都是监测输入,下面tableview显示 }// called when keyboard search button pressed @available(iOS 2.0, *) public func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {//当书签被点击时 }// called when bookmark button pressed @available(iOS 2.0, *) public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {//当取消按钮被点击时 searchBar.text = "" searchBar.resignFirstResponder()//隐藏键盘 //结束编辑,更新数组为数据源,刷新tableview,在此方法中写和返回布尔值得方法中写,效果一样 resultDaraList = allDataList tableView.reloadData() }// called when cancel button pressed @available(iOS 3.2, *) public func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) {//当搜索 结果被点击时 }// called when search results button pressed @available(iOS 3.0, *) public func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {//当搜索索引被更改时 } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return resultDaraList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) cell.textLabel?.text = resultDaraList[indexPath.row] return cell } }
29.620192
149
0.599253
896069acb651497017424adcd12a3591317ffd2e
571
// // DetallesHorario.swift // Gents // // Created by Community Manager on 8/7/19. // Copyright © 2019 Rockyto Sánchez. All rights reserved. // import UIKit class DetallesHorario: NSObject { var idHorario: String? var elHorario: String? override init() { } init(idHorario: String, elHorario: String){ self.idHorario = idHorario self.elHorario = elHorario } override var description: String{ return "idHorario: \(idHorario), elHorario: \(elHorario)" } }
17.84375
65
0.58669
ffc6d564317db51a67b8e543a3357dd364ad5416
794
import XCTest @testable import Plugin class FirebaseMessagingTests: 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 testEcho() { // This is an example of a functional test case for a plugin. // Use XCTAssert and related functions to verify your tests produce the correct results. let implementation = FirebaseMessaging() let value = "Hello, World!" let result = implementation.echo(value) XCTAssertEqual(value, result) } }
30.538462
111
0.664987
87c1800625b91db1e3222a08ef584f6a0f6438fe
1,047
import XCTest import Shared @testable import TestShared @testable import XcodeSupport @testable import PeripheryKit class SwiftUIProjectTest: SourceGraphTestCase { override static func setUp() { super.setUp() let project = try! XcodeProject.make(path: SwiftUIProjectPath) let driver = XcodeProjectDriver( logger: inject(), configuration: configuration, xcodebuild: inject(), project: project, schemes: [try! XcodeScheme.make(project: project, name: "SwiftUIProject")], targets: project.targets ) try! driver.build() try! driver.index(graph: graph) try! Analyzer.perform(graph: graph) } func testRetainsMainAppEntryPoint() { assertReferenced(.struct("SwiftUIProjectApp")) } func testRetainsPreviewProvider() { assertReferenced(.struct("ContentView_Previews")) } func testRetainsLibraryContentProvider() { assertReferenced(.struct("LibraryViewContent")) } }
26.846154
87
0.65425
2fb182f5410ba916aa091404f641796fcde066ef
2,296
/** * Copyright IBM Corporation 2018 * * 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 Kitura import LoggerAPI func initializeAdditionalRoutes(app: App) { // Uses multiple handler blocks app.router.get("/multi", handler: { request, response, next in response.send("I'm here!\n") next() }, { request, response, next in response.send("Me too!\n") next() }) app.router.get("/multi") { request, response, next in try response.send("I come afterward..\n").end() } // Redirection example app.router.get("/redirect") { _, response, next in try response.redirect("https://www.kitura.io") next() } // Reading parameters // Accepts user as a parameter app.router.get("/users/:user") { request, response, next in response.headers["Content-Type"] = "text/html" let p1 = request.parameters["user"] ?? "(nil)" try response.send( "<!DOCTYPE html><html><body>" + "<b>User:</b> \(p1)" + "</body></html>\n\n").end() } app.router.get("/user/:id", allowPartialMatch: false, middleware: CustomParameterMiddleware()) app.router.get("/user/:id", handler: customParameterHandler) } let customParameterHandler: RouterHandler = { request, response, next in let id = request.parameters["id"] ?? "unknown" response.send("\(id)|").status(.OK) next() } class CustomParameterMiddleware: RouterMiddleware { func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) { do { try customParameterHandler(request, response, next) } catch { Log.error("customParameterHandler returned error: \(error)") } } }
31.888889
98
0.634146
f84cc64ff013abe5e265eaeec17a4b35637788bd
2,534
// // Stevia+Content.swift // LoginStevia // // Created by Sacha Durand Saint Omer on 01/10/15. // Copyright © 2015 Sacha Durand Saint Omer. All rights reserved. // import UIKit public extension UIButton { /** Sets the title of the button for normal State Essentially a shortcut for `setTitle("MyText", forState: .Normal)` - Returns: Itself for chaining purposes */ @discardableResult public func text(_ t: String) -> Self { setTitle(t, for: .normal) return self } /** Sets the localized key for the button's title in normal State Essentially a shortcut for `setTitle(NSLocalizedString("MyText", comment: "") , forState: .Normal)` - Returns: Itself for chaining purposes */ @discardableResult public func textKey(_ t: String) -> Self { text(NSLocalizedString(t, comment: "")) return self } /** Sets the image of the button in normal State Essentially a shortcut for `setImage(UIImage(named:"X"), forState: .Normal)` - Returns: Itself for chaining purposes */ @discardableResult public func image(_ s: String) -> Self { setImage(UIImage(named: s), for: .normal) return self } } public extension UITextField { /** Sets the textfield placeholder but in a chainable fashion - Returns: Itself for chaining purposes */ @discardableResult public func placeholder(_ t: String) -> Self { placeholder = t return self } } public extension UILabel { /** Sets the label text but in a chainable fashion - Returns: Itself for chaining purposes */ @discardableResult public func text(_ t: String) -> Self { text = t return self } /** Sets the label localization key but in a chainable fashion Essentially a shortcut for `text = NSLocalizedString("X", comment: "")` - Returns: Itself for chaining purposes */ @discardableResult public func textKey(_ t: String) -> Self { text(NSLocalizedString(t, comment: "")) return self } } extension UIImageView { /** Sets the image of the imageView but in a chainable fashion Essentially a shortcut for `image = UIImage(named: "X")` - Returns: Itself for chaining purposes */ @discardableResult public func image(_ t: String) -> Self { image = UIImage(named: t) return self } }
24.601942
82
0.612865
0acce5dfb1f65fd03fd44251ac75612e9689a5fc
747
// // ViewController.swift // buttonUpDown // // Created by 황정덕 on 2019/11/21. // Copyright © 2019 Gitbot. All rights reserved. // import UIKit class ViewController: UIViewController { var num = 0 @IBOutlet weak var number: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func minus(_ sender: Any) { num = Int(number.text ?? "0")! num -= 1 number.textColor = .red number.text = String(num) } @IBAction func plus(_ sender: Any) { num = Int(number.text ?? "0")! num += 1 number.textColor = .blue number.text = String(num) } }
19.657895
58
0.559572
5683573d486a6e10bc6709ddcd522bc11eeecbab
9,327
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // C Primitive Types //===----------------------------------------------------------------------===// /// The C 'char' type. /// /// This will be the same as either `CSignedChar` (in the common /// case) or `CUnsignedChar`, depending on the platform. public typealias CChar = Int8 /// The C 'unsigned char' type. public typealias CUnsignedChar = UInt8 /// The C 'unsigned short' type. public typealias CUnsignedShort = UInt16 /// The C 'unsigned int' type. public typealias CUnsignedInt = UInt32 /// The C 'unsigned long' type. #if os(Windows) && arch(x86_64) public typealias CUnsignedLong = UInt32 #else public typealias CUnsignedLong = UInt #endif /// The C 'unsigned long long' type. public typealias CUnsignedLongLong = UInt64 /// The C 'signed char' type. public typealias CSignedChar = Int8 /// The C 'short' type. public typealias CShort = Int16 /// The C 'int' type. public typealias CInt = Int32 /// The C 'long' type. #if os(Windows) && arch(x86_64) public typealias CLong = Int32 #else public typealias CLong = Int #endif /// The C 'long long' type. public typealias CLongLong = Int64 /// The C 'float' type. public typealias CFloat = Float /// The C 'double' type. public typealias CDouble = Double /// The C 'long double' type. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // On Darwin, long double is Float80 on x86, and Double otherwise. #if arch(x86_64) || arch(i386) public typealias CLongDouble = Float80 #else public typealias CLongDouble = Double #endif #elseif os(Windows) // On Windows, long double is always Double. public typealias CLongDouble = Double #elseif os(Linux) // On Linux/x86, long double is Float80. // TODO: Fill in definitions for additional architectures as needed. IIRC // armv7 should map to Double, but arm64 and ppc64le should map to Float128, // which we don't yet have in Swift. #if arch(x86_64) || arch(i386) public typealias CLongDouble = Float80 #endif // TODO: Fill in definitions for other OSes. #if arch(s390x) // On s390x '-mlong-double-64' option with size of 64-bits makes the // Long Double type equivalent to Double type. public typealias CLongDouble = Double #endif #elseif os(Android) // On Android, long double is Float128 for AAPCS64, which we don't have yet in // Swift (SR-9072); and Double for ARMv7. #if arch(arm) public typealias CLongDouble = Double #endif #elseif os(OpenBSD) public typealias CLongDouble = Float80 #endif // FIXME: Is it actually UTF-32 on Darwin? // /// The C++ 'wchar_t' type. public typealias CWideChar = Unicode.Scalar // FIXME: Swift should probably have a UTF-16 type other than UInt16. // /// The C++11 'char16_t' type, which has UTF-16 encoding. public typealias CChar16 = UInt16 /// The C++11 'char32_t' type, which has UTF-32 encoding. public typealias CChar32 = Unicode.Scalar /// The C '_Bool' and C++ 'bool' type. public typealias CBool = Bool /// A wrapper around an opaque C pointer. /// /// Opaque pointers are used to represent C pointers to types that /// cannot be represented in Swift, such as incomplete struct types. @frozen public struct OpaquePointer { @usableFromInline internal var _rawValue: Builtin.RawPointer @usableFromInline @_transparent internal init(_ v: Builtin.RawPointer) { self._rawValue = v } /// Creates an `OpaquePointer` from a given address in memory. @_transparent public init?(bitPattern: Int) { if bitPattern == 0 { return nil } self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Creates an `OpaquePointer` from a given address in memory. @_transparent public init?(bitPattern: UInt) { if bitPattern == 0 { return nil } self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Converts a typed `UnsafePointer` to an opaque C pointer. @_transparent public init<T>(@_nonEphemeral _ from: UnsafePointer<T>) { self._rawValue = from._rawValue } /// Converts a typed `UnsafePointer` to an opaque C pointer. /// /// The result is `nil` if `from` is `nil`. @_transparent public init?<T>(@_nonEphemeral _ from: UnsafePointer<T>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } /// Converts a typed `UnsafeMutablePointer` to an opaque C pointer. @_transparent public init<T>(@_nonEphemeral _ from: UnsafeMutablePointer<T>) { self._rawValue = from._rawValue } /// Converts a typed `UnsafeMutablePointer` to an opaque C pointer. /// /// The result is `nil` if `from` is `nil`. @_transparent public init?<T>(@_nonEphemeral _ from: UnsafeMutablePointer<T>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } } extension OpaquePointer: Equatable { @inlinable // unsafe-performance public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue)) } } extension OpaquePointer: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(Int(Builtin.ptrtoint_Word(_rawValue))) } } extension OpaquePointer: CustomDebugStringConvertible { /// A textual representation of the pointer, suitable for debugging. public var debugDescription: String { return _rawPointerToString(_rawValue) } } extension Int { /// Creates a new value with the bit pattern of the given pointer. /// /// The new value represents the address of the pointer passed as `pointer`. /// If `pointer` is `nil`, the result is `0`. /// /// - Parameter pointer: The pointer to use as the source for the new /// integer. @inlinable // unsafe-performance public init(bitPattern pointer: OpaquePointer?) { self.init(bitPattern: UnsafeRawPointer(pointer)) } } extension UInt { /// Creates a new value with the bit pattern of the given pointer. /// /// The new value represents the address of the pointer passed as `pointer`. /// If `pointer` is `nil`, the result is `0`. /// /// - Parameter pointer: The pointer to use as the source for the new /// integer. @inlinable // unsafe-performance public init(bitPattern pointer: OpaquePointer?) { self.init(bitPattern: UnsafeRawPointer(pointer)) } } /// A wrapper around a C `va_list` pointer. #if arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows)) @frozen public struct CVaListPointer { @usableFromInline // unsafe-performance internal var _value: (__stack: UnsafeMutablePointer<Int>?, __gr_top: UnsafeMutablePointer<Int>?, __vr_top: UnsafeMutablePointer<Int>?, __gr_off: Int32, __vr_off: Int32) @inlinable // unsafe-performance public // @testable init(__stack: UnsafeMutablePointer<Int>?, __gr_top: UnsafeMutablePointer<Int>?, __vr_top: UnsafeMutablePointer<Int>?, __gr_off: Int32, __vr_off: Int32) { _value = (__stack, __gr_top, __vr_top, __gr_off, __vr_off) } } extension CVaListPointer: CustomDebugStringConvertible { public var debugDescription: String { return "(\(_value.__stack.debugDescription), " + "\(_value.__gr_top.debugDescription), " + "\(_value.__vr_top.debugDescription), " + "\(_value.__gr_off), " + "\(_value.__vr_off))" } } #else @frozen public struct CVaListPointer { @usableFromInline // unsafe-performance internal var _value: UnsafeMutableRawPointer @inlinable // unsafe-performance public // @testable init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) { _value = from } } extension CVaListPointer: CustomDebugStringConvertible { /// A textual representation of the pointer, suitable for debugging. public var debugDescription: String { return _value.debugDescription } } #endif @inlinable internal func _memcpy( dest destination: UnsafeMutableRawPointer, src: UnsafeRawPointer, size: UInt ) { let dest = destination._rawValue let src = src._rawValue let size = UInt64(size)._value Builtin.int_memcpy_RawPointer_RawPointer_Int64( dest, src, size, /*volatile:*/ false._value) } /// Copy `count` bytes of memory from `src` into `dest`. /// /// The memory regions `source..<source + count` and /// `dest..<dest + count` may overlap. @inlinable internal func _memmove( dest destination: UnsafeMutableRawPointer, src: UnsafeRawPointer, size: UInt ) { let dest = destination._rawValue let src = src._rawValue let size = UInt64(size)._value Builtin.int_memmove_RawPointer_RawPointer_Int64( dest, src, size, /*volatile:*/ false._value) }
29.609524
84
0.685965
f78607ffc7e2fe992830231ec1500bda7999c406
1,375
// // quickSort.swift // // # Data Structures & Algorithms in Swift // Created by Loyi on 6/6/20. // extension Array where Element == Int { /// The function to perform quick sort on the array. /// - parameter left: The left end of the array. Usually `0`. /// - parameter right: The right end of the array. Usually `array.count - 1`. mutating func quickSort(left: Int, right: Int) { guard left >= 0 && right < self.count && left < right else { return } var i = left, j = right let standard = self[left] while i != j { while self[j] >= standard && i < j { j -= 1 } while self[i] <= standard && i < j { i += 1 } if i < j { (self[i], self[j]) = (self[j], self[i]) } } self[left] = self[i] self[i] = standard quickSort(left: left, right: i-1) quickSort(left: i+1, right: right) } /// The function to return the result of quick sort of the array. /// - parameter left: The left end of the array. Usually `0`. /// - parameter right: The right end of the array. Usually `array.count - 1`. func quickSorted(left: Int, right: Int) -> [Element] { var array = self array.quickSort(left: left, right: right) return array } }
31.25
81
0.525818
0a4e3ceb364081f8e292f0efa90f4b7800b69844
3,190
import Foundation class BaseballNumber : NSObject { public func printResult() -> String { var printValue : Int let arrangement = [[123, 1, 1], [356, 1, 0], [327, 2, 0], [489, 0, 1]] printValue = solution(arrangement) return String(printValue) } //1. 전체 경우의 수를 가져온다. //2. 입력한 값과 일치히지 않는 경우는 삭제 한다. //일치비교 //3. 남아있는 값의 카운트가 해당 답이다. func solution(_ baseball:[[Int]]) -> Int { let answerArr : Array<[Int]> = compare(baseball) return answerArr.count } //비교 func compare(_ baseball:[[Int]]) -> Array<[Int]> { var answerSystem = search () for item in baseball { for baseballItem in answerSystem { let number = item[0] let strike = item[1] let ball = item[2] if !filterBaseball(number: number, ball: ball, strike: strike, answer: baseballItem) { answerSystem = answerSystem.filter { $0 != baseballItem } } } } return answerSystem } //해당 카운터 체크 func filterBaseball(number:Int, ball:Int, strike:Int, answer:[Int]) -> Bool{ var check = true let numberString = String(number) let arrayString = Array(numberString.map {$0}) let numberArray = Array(arrayString.map { Int(String($0)) }) var ballCount = 0 var strikeCount = 0 let answerFilter = answer for (index,item) in answerFilter.enumerated() { for (offset, number) in numberArray.enumerated() { if item == number { if index == offset { strikeCount += 1 } else { ballCount += 1 } } } } if ball == ballCount && strike == strikeCount { //print(answer) check = true } else { check = false } return check } //전체 배열을 가저온다 func search() -> Array<[Int]>{ var array = Array<[Int]>() for a in 1...9 { for b in 1...9 { for c in 1...9 { if a==b || b==c || a==c { continue } array.append([a,b,c]) } } } return array } } //문제 설명 //숫자 야구 게임이란 2명이 서로가 생각한 숫자를 맞추는 게임입니다. 게임해보기 // //각자 서로 다른 1~9까지 3자리 임의의 숫자를 정한 뒤 서로에게 3자리의 숫자를 불러서 결과를 확인합니다. 그리고 그 결과를 토대로 상대가 정한 숫자를 예상한 뒤 맞힙니다. // //* 숫자는 맞지만, 위치가 틀렸을 때는 볼 //* 숫자와 위치가 모두 맞을 때는 스트라이크 //* 숫자와 위치가 모두 틀렸을 때는 아웃 //예를 들어, 아래의 경우가 있으면 // //A : 123 //B : 1스트라이크 1볼. //A : 356 //B : 1스트라이크 0볼. //A : 327 //B : 2스트라이크 0볼. //A : 489 //B : 0스트라이크 1볼. //이때 가능한 답은 324와 328 두 가지입니다. // //질문한 세 자리의 수, 스트라이크의 수, 볼의 수를 담은 2차원 배열 baseball이 매개변수로 주어질 때, 가능한 답의 개수를 return 하도록 solution 함수를 작성해주세요. // //제한사항 //질문의 수는 1 이상 100 이하의 자연수입니다. //baseball의 각 행은 [세 자리의 수, 스트라이크의 수, 볼의 수] 를 담고 있습니다. //입출력 예 //baseball return // [[123, 1, 1], [356, 1, 0], [327, 2, 0], [489, 0, 1]] 2 //입출력 예 설명 //문제에 나온 예와 같습니다.
26.806723
106
0.483072
6478e0ffa8c6bed105cb22c6ab2e4e0e55f8c072
7,722
import Foundation import SourceKittenFramework public struct OperatorUsageWhitespaceRule: OptInRule, CorrectableRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "operator_usage_whitespace", name: "Operator Usage Whitespace", description: "Operators should be surrounded by a single whitespace " + "when they are being used.", kind: .style, nonTriggeringExamples: [ "let foo = 1 + 2\n", "let foo = 1 > 2\n", "let foo = !false\n", "let foo: Int?\n", "let foo: Array<String>\n", "let model = CustomView<Container<Button>, NSAttributedString>()\n", "let foo: [String]\n", "let foo = 1 + \n 2\n", "let range = 1...3\n", "let range = 1 ... 3\n", "let range = 1..<3\n", "#if swift(>=3.0)\n foo()\n#endif\n", "array.removeAtIndex(-200)\n", "let name = \"image-1\"\n", "button.setImage(#imageLiteral(resourceName: \"image-1\"), for: .normal)\n", "let doubleValue = -9e-11\n", "let foo = GenericType<(UIViewController) -> Void>()\n", "let foo = Foo<Bar<T>, Baz>()\n", "let foo = SignalProducer<Signal<Value, Error>, Error>([ self.signal, next ]).flatten(.concat)\n" ], triggeringExamples: [ "let foo = 1↓+2\n", "let foo = 1↓ + 2\n", "let foo = 1↓ + 2\n", "let foo = 1↓ + 2\n", "let foo↓=1↓+2\n", "let foo↓=1 + 2\n", "let foo↓=bar\n", "let range = 1↓ ..< 3\n", "let foo = bar↓ ?? 0\n", "let foo = bar↓??0\n", "let foo = bar↓ != 0\n", "let foo = bar↓ !== bar2\n", "let v8 = Int8(1)↓ << 6\n", "let v8 = 1↓ << (6)\n", "let v8 = 1↓ << (6)\n let foo = 1 > 2\n" ], corrections: [ "let foo = 1↓+2\n": "let foo = 1 + 2\n", "let foo = 1↓ + 2\n": "let foo = 1 + 2\n", "let foo = 1↓ + 2\n": "let foo = 1 + 2\n", "let foo = 1↓ + 2\n": "let foo = 1 + 2\n", "let foo↓=1↓+2\n": "let foo = 1 + 2\n", "let foo↓=1 + 2\n": "let foo = 1 + 2\n", "let foo↓=bar\n": "let foo = bar\n", "let range = 1↓ ..< 3\n": "let range = 1..<3\n", "let foo = bar↓ ?? 0\n": "let foo = bar ?? 0\n", "let foo = bar↓??0\n": "let foo = bar ?? 0\n", "let foo = bar↓ != 0\n": "let foo = bar != 0\n", "let foo = bar↓ !== bar2\n": "let foo = bar !== bar2\n", "let v8 = Int8(1)↓ << 6\n": "let v8 = Int8(1) << 6\n", "let v8 = 1↓ << (6)\n": "let v8 = 1 << (6)\n", "let v8 = 1↓ << (6)\n let foo = 1 > 2\n": "let v8 = 1 << (6)\n let foo = 1 > 2\n" ] ) public func validate(file: File) -> [StyleViolation] { return violationRanges(file: file).map { range, _ in StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: range.location)) } } private func violationRanges(file: File) -> [(NSRange, String)] { let escapedOperators = ["/", "=", "-", "+", "*", "|", "^", "~"].map({ "\\\($0)" }).joined() let rangePattern = "\\.\\.(?:\\.|<)" // ... or ..< let notEqualsPattern = "\\!\\=\\=?" // != or !== let coalescingPattern = "\\?{2}" let operators = "(?:[\(escapedOperators)%<>&]+|\(rangePattern)|\(coalescingPattern)|" + "\(notEqualsPattern))" let oneSpace = "[^\\S\\r\\n]" // to allow lines ending with operators to be valid let zeroSpaces = oneSpace + "{0}" let manySpaces = oneSpace + "{2,}" let leadingVariableOrNumber = "(?:\\b|\\))" let trailingVariableOrNumber = "(?:\\b|\\()" let spaces = [(zeroSpaces, zeroSpaces), (oneSpace, manySpaces), (manySpaces, oneSpace), (manySpaces, manySpaces)] let patterns = spaces.map { first, second in leadingVariableOrNumber + first + operators + second + trailingVariableOrNumber } let pattern = "(?:\(patterns.joined(separator: "|")))" let genericPattern = "<(?:\(oneSpace)|\\S)*>" // not using dot to avoid matching new line let validRangePattern = leadingVariableOrNumber + zeroSpaces + rangePattern + zeroSpaces + trailingVariableOrNumber let excludingPattern = "(?:\(genericPattern)|\(validRangePattern))" let excludingKinds = SyntaxKind.commentAndStringKinds.union([.objectLiteral]) return file.match(pattern: pattern, excludingSyntaxKinds: excludingKinds, excludingPattern: excludingPattern).compactMap { range in // if it's only a number (i.e. -9e-11), it shouldn't trigger guard kinds(in: range, file: file) != [.number] else { return nil } let spacesPattern = oneSpace + "*" let rangeRegex = regex(spacesPattern + rangePattern + spacesPattern) // if it's a range operator, the correction shouldn't have spaces if let matchRange = rangeRegex.firstMatch(in: file.contents, options: [], range: range)?.range { let correction = operatorInRange(file: file, range: matchRange) return (matchRange, correction) } let pattern = spacesPattern + operators + spacesPattern let operatorsRegex = regex(pattern) guard let matchRange = operatorsRegex.firstMatch(in: file.contents, options: [], range: range)?.range else { return nil } let operatorContent = operatorInRange(file: file, range: matchRange) let correction = " " + operatorContent + " " return (matchRange, correction) } } private func kinds(in range: NSRange, file: File) -> [SyntaxKind] { let contents = file.contents.bridge() guard let byteRange = contents.NSRangeToByteRange(start: range.location, length: range.length) else { return [] } return file.syntaxMap.kinds(inByteRange: byteRange) } private func operatorInRange(file: File, range: NSRange) -> String { return file.contents.bridge().substring(with: range).trimmingCharacters(in: .whitespaces) } public func correct(file: File) -> [Correction] { let violatingRanges = violationRanges(file: file).filter { range, _ in return !file.ruleEnabled(violatingRanges: [range], for: self).isEmpty } var correctedContents = file.contents var adjustedLocations = [Int]() for (violatingRange, correction) in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents .replacingCharacters(in: indexRange, with: correction) adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: type(of: self).description, location: Location(file: file, characterOffset: $0)) } } }
43.139665
109
0.524994
5b558f8f9eaad17532885230d24f453d4631543a
520
import Foundation print("begin", CFAbsoluteTimeGetCurrent()) let url = URL(string: "http://www.apple.com/v/home/ek/images/heroes/watch-series-4/watch__csqqcayzqueu_large.jpg")! let data = try Data.init(contentsOf: url) print("recv", CFAbsoluteTimeGetCurrent()) print("done") var data2 : Data! print("begin2", CFAbsoluteTimeGetCurrent()) DispatchQueue.global().async { do { data2 = try Data.init(contentsOf: url) } catch { } } print("recv2", CFAbsoluteTimeGetCurrent()) print("done2")
23.636364
115
0.698077
62a438961490cc2310b80afd8a10367e4a6d044d
356
// // CharacterDetailHeaderTableViewCellDTO.swift // marvelapp // // Created by Felipe Antonio Cardoso on 07/04/19. // Copyright © 2019 Felipe Antonio Cardoso. All rights reserved. // import Foundation struct CharacterDetailHeaderTableViewCellDTO { let title: String? let description: String? let imageURL: URL? let favorited: Bool }
20.941176
65
0.733146
282a6a043d6f32150777fd852ef5d2c45fbefbfd
2,615
import ArgumentParser import Foundation import Sword import VirtualMansionLib struct VirtualMansion: ParsableCommand { static let configuration = CommandConfiguration(abstract: "If you have to ask you're not invited.", subcommands: []) @Option(help: "The path to the database.") var db: String? @Option(help: "The token for The Mirror bot.") var mirrorToken: String? @Option(help: "The token for Award Lord bot.") var awardToken: String? @Option(help: "The token for Force of Nature bot.") var forceToken: String? @Flag(help: "Enable verbose print statements.") var debug = false func validate() throws { guard mirrorToken != nil || awardToken != nil || forceToken != nil else { throw ValidationError("No token provided.") } guard [mirrorToken, awardToken, forceToken].filter({ $0 != nil }).count == 1 else { throw ValidationError("Only one token can be provided at a time.") } } func run() throws { verboseLoggingEnabled = debug let database = try Database(path: db) let dateFormatter = DateFormatter() dateFormatter.timeStyle = .short log("\nYou have entered the mansion. The clock reads \(dateFormatter.string(from: Date())).") let token: String if let mirrorToken = mirrorToken { token = mirrorToken } else if let awardToken = awardToken { token = awardToken } else if let forceToken = forceToken { token = forceToken } else { fatalError() } let sword = Sword(token: token) sword.getGuild(.publicHouse, rest: true) { (guild, error) in guard let guild = guild else { fatalError("Could not find public house guild: \(error.debugDescription)") } let bot: Bot if mirrorToken != nil { bot = TheMirror(sword: sword, guild: guild, database: database) } else if awardToken != nil { bot = AwardLord(sword: sword, guild: guild, database: database) } else if forceToken != nil { bot = ForceOfNature(sword: sword, guild: guild, database: database) } else { fatalError() } log("\(bot.botName) is here at your service.\n") bot.run() } sword.connect() } } VirtualMansion.main()
32.6875
103
0.553728
7a3486e19011b901a0bb64ebcb21482a18b4c1dc
4,429
// // Generated by SwagGen // https://github.com/pace/SwagGen // import Foundation public class PCPayPaymentMethodKindMinimal: APIModel { public enum PCPayType: String, Codable, Equatable, CaseIterable { case paymentMethodKind = "paymentMethodKind" } public var attributes: Attributes? public var id: ID? public var type: PCPayType? public class Attributes: APIModel { /** Indicates whether the payment method is a fuel card. Fuelcard `no` means no. */ public var fuelcard: Bool? /** Indicates whether the payment method can be onboarded/modified. Implict `true` means no. Otherwise yes. Most payment method kinds are no implicit, i.e., `implicit=false`. This field is optional and if not present should be assumed to indicate `implicit=false`. */ public var implicit: Bool? /** localized name */ public var name: String? /** indicates if the payment method kind requires two factors later on */ public var twoFactor: Bool? /** PACE resource name(s) to payment method vendors */ public var vendorPRNs: [String]? public init(fuelcard: Bool? = nil, implicit: Bool? = nil, name: String? = nil, twoFactor: Bool? = nil, vendorPRNs: [String]? = nil) { self.fuelcard = fuelcard self.implicit = implicit self.name = name self.twoFactor = twoFactor self.vendorPRNs = vendorPRNs } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) fuelcard = try container.decodeIfPresent("fuelcard") implicit = try container.decodeIfPresent("implicit") name = try container.decodeIfPresent("name") twoFactor = try container.decodeIfPresent("twoFactor") vendorPRNs = try container.decodeArrayIfPresent("vendorPRNs") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(fuelcard, forKey: "fuelcard") try container.encodeIfPresent(implicit, forKey: "implicit") try container.encodeIfPresent(name, forKey: "name") try container.encodeIfPresent(twoFactor, forKey: "twoFactor") try container.encodeIfPresent(vendorPRNs, forKey: "vendorPRNs") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Attributes else { return false } guard self.fuelcard == object.fuelcard else { return false } guard self.implicit == object.implicit else { return false } guard self.name == object.name else { return false } guard self.twoFactor == object.twoFactor else { return false } guard self.vendorPRNs == object.vendorPRNs else { return false } return true } public static func == (lhs: Attributes, rhs: Attributes) -> Bool { return lhs.isEqual(to: rhs) } } public init(attributes: Attributes? = nil, id: ID? = nil, type: PCPayType? = nil) { self.attributes = attributes self.id = id self.type = type } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) attributes = try container.decodeIfPresent("attributes") id = try container.decodeIfPresent("id") type = try container.decodeIfPresent("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(attributes, forKey: "attributes") try container.encodeIfPresent(id, forKey: "id") try container.encodeIfPresent(type, forKey: "type") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? PCPayPaymentMethodKindMinimal else { return false } guard self.attributes == object.attributes else { return false } guard self.id == object.id else { return false } guard self.type == object.type else { return false } return true } public static func == (lhs: PCPayPaymentMethodKindMinimal, rhs: PCPayPaymentMethodKindMinimal) -> Bool { return lhs.isEqual(to: rhs) } }
37.854701
141
0.646873
cc0f527bd2d533c6f7e31bfb38bb8c5aa1c38b68
53
@_exported import XCTest @_exported import WalletKit
17.666667
27
0.849057
6143513640770112dab352e28f335a28c4d5582e
303
// // DemoView.swift // FrameworkDemo // // Created by administrator on 24/07/20. // Copyright © 2020 administrator. All rights reserved. // import UIKit public class DemoView: UIView { public class func addBackgroundColor(view : UIView){ view.backgroundColor = .red } }
15.947368
56
0.660066
878f8d060f4d40301885414a4b0169f34a129180
2,085
// // ViewController.swift // Project2 // // Created by Keri Clowes on 3/18/16. // Copyright © 2016 Keri Clowes. All rights reserved. // import UIKit import GameplayKit class ViewController: UIViewController { @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! @IBOutlet weak var button3: UIButton! var countries = [String]() var correctAnswer = 0 var score = 0 @IBAction func buttonTapped(sender: UIButton) { if sender.tag == correctAnswer { title = "Correct" score += 1 } else { title = "Wrong" score -= 1 } let ac = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "Continue", style: .Default, handler: askQuestion)) presentViewController(ac, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() countries += [ "estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us" ] button1.layer.borderWidth = 1 button2.layer.borderWidth = 1 button3.layer.borderWidth = 1 button1.layer.borderColor = UIColor.lightGrayColor().CGColor button2.layer.borderColor = UIColor.lightGrayColor().CGColor button3.layer.borderColor = UIColor.lightGrayColor().CGColor askQuestion(nil) } func askQuestion(action: UIAlertAction!) { countries = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(countries) as! [String] button1.setImage(UIImage(named: countries[0]), forState: .Normal) button2.setImage(UIImage(named: countries[1]), forState: .Normal) button3.setImage(UIImage(named: countries[2]), forState: .Normal) correctAnswer = GKRandomSource.sharedRandom().nextIntWithUpperBound(3) title = countries[correctAnswer].uppercaseString } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
25.120482
104
0.674341
76625d76461181d84f0a9f903c13adbf1245260e
507
import DeclarativeUI class ActivityIndicatorView: DeclarativeViewController { lazy var viewController = ViewController(view: view) let navigator: Navigator lazy var activityIndicator = ActivityIndicator() .color(.black) public init(navigator: Navigator) { self.navigator = navigator activityIndicator.startAnimating() } lazy var view = StackView(.vertical) { Spacer(.medium) activityIndicator Spacer(.flexible) } }
24.142857
56
0.664694
ab9db5e762cf3bb276081e1f180df15721332d32
3,216
// // CategoryViewController.swift // Project // // Created by Kevin Sum on 10/7/2017. // Copyright © 2017 Kevin iShuHui. All rights reserved. // import UIKit class CategoryViewController: BaseTableController { var categoryId = 0 override func loadView() { super.loadView() api = ApiHelper.Name.getBook tableView.allowsSelectionDuringEditing = false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) tabBarController?.title = tabBarItem.title tableView.reloadData() } override func loadData() { parameter = ["ClassifyId":categoryId, "PageIndex":index] super.loadData() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "categoryId", for: indexPath) as! CategoryTableViewCell if let book = data[indexPath.row].dictionary { let title = book["Title"]?.string ?? "" let author = book["Author"]?.string ?? "" cell.title = "\(title) \(author)" if let chapter = book["LastChapter"]?.dictionary?["Sort"]?.int { cell.chapter = "第\(chapter)話" } cell.cover = book["FrontCover"]?.string cell.subscribed = Subscription.isSubscribe(bookId: book["Id"]?.int16) } return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if let cell = tableView.cellForRow(at: indexPath) as? CategoryTableViewCell { let title = cell.subscribed ? "退訂" : "訂閱" let action = UITableViewRowAction(style: .default, title: title, handler: { (action, indexPath) in if let bookId = self.data[indexPath.row].dictionary?["Id"]?.int16 { Subscription.subscribe(bookId: bookId, YesOrNo: !cell.subscribed) } cell.subscribed = !cell.subscribed tableView.setEditing(false, animated: true) }) action.backgroundColor = cell.subscribed ? .red : .orange return [action] } else { return [] } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "bookChapterTable", let table = segue.destination as? BookChapterTableController { if let selectedRow = tableView.indexPathForSelectedRow?.row { let book = data[selectedRow].dictionary table.cover = book?["FrontCover"]?.string table.name = book?["Title"]?.string table.author = book?["Author"]?.string table.status = book?["SerializedState"]?.string table.explain = book?["Explain"]?.string table.id = book?["Id"]?.int16 ?? 0 } } } }
36.965517
124
0.593905
335deb1de96f1d237e10f2403e8359fd0f717575
125
import UIKit public protocol HybridWebSceneFactory { func makeHybridWebScene() -> UIViewController & HybridWebScene }
15.625
66
0.784
1a7dbf62414eab3279ed167581b5ae46dae542bf
6,422
// // Copyright (c) 2020 Related Code - http://relatedcode.com // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit //------------------------------------------------------------------------------------------------------------------------------------------------- class Walkthrough4View: UIViewController { @IBOutlet var collectionView: UICollectionView! @IBOutlet var pageControl: UIPageControl! private var collections: [[String: String]] = [] //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() collectionView.register(UINib(nibName: "Walkthrough4Cell", bundle: nil), forCellWithReuseIdentifier: "Walkthrough4Cell") pageControl.pageIndicatorTintColor = UIColor.lightGray pageControl.currentPageIndicatorTintColor = AppColor.Theme loadCollections() } // MARK: - Collections methods //--------------------------------------------------------------------------------------------------------------------------------------------- func loadCollections() { collections.removeAll() var dict1: [String: String] = [:] dict1["title"] = "Get latest updates" dict1["description"] = "Keep updated with wide collection of news, article & more" collections.append(dict1) var dict2: [String: String] = [:] dict2["title"] = "News from every region" dict2["description"] = "Keep updated with wide collection of news, article & more" collections.append(dict2) collections.append(dict1) collections.append(dict1) collections.append(dict1) refreshCollectionView() } // MARK: - User actions //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionSkip(_ sender: UIButton) { dismiss(animated: true) } // MARK: - Refresh methods //--------------------------------------------------------------------------------------------------------------------------------------------- func refreshCollectionView() { collectionView.reloadData() } } // MARK:- UICollectionViewDataSource //------------------------------------------------------------------------------------------------------------------------------------------------- extension Walkthrough4View: UICollectionViewDataSource { //--------------------------------------------------------------------------------------------------------------------------------------------- func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } //--------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return collections.count } //--------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Walkthrough4Cell", for: indexPath) as! Walkthrough4Cell cell.bindData(index: indexPath.item, data: collections[indexPath.row]) return cell } } // MARK:- UICollectionViewDelegate //------------------------------------------------------------------------------------------------------------------------------------------------- extension Walkthrough4View: UICollectionViewDelegate { //--------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("didSelectItemAt \(indexPath.row)") } //--------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { pageControl.currentPage = indexPath.row } } // MARK:- UICollectionViewDelegateFlowLayout //------------------------------------------------------------------------------------------------------------------------------------------------- extension Walkthrough4View: UICollectionViewDelegateFlowLayout { //--------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = collectionView.frame.size.height let width = collectionView.frame.size.width return CGSize(width: width, height: height) } //--------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } //--------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } //--------------------------------------------------------------------------------------------------------------------------------------------- func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } }
43.986301
172
0.47602
4bfd46341d5db32f3d4689c7a546a372552e8a5e
2,745
// // Event.swift // Reactive // // Created by Jens Jakob Jensen on 25/08/14. // Copyright (c) 2014 Jayway. All rights reserved. // import class Foundation.NSError /// This maps a struct inside a class to get Hashable and Equatable (used by Splitter), and to avoid a bug in beta 6 (in the definition of Event) public class Box<T>: Hashable, Equatable { public let value: T init(_ value: T) { self.value = value } public func unbox() -> T { return value } public var hashValue: Int { return reflect(self).objectIdentifier!.hashValue } } public func ==<T>(lhs: Box<T>, rhs: Box<T>) -> Bool { return lhs === rhs } // MARK: - public enum Event<T> { /// A value. /// Box the value due to an unimplemented feature in beta 6: "unimplemented IR generation feature non-fixed multi-payload enum layout". case Value(Box<T>) /// Completed without error. This is an ending event: No more events will be emitted. case Completed /// Stopped prematurely without error (terminated). This is an ending event: No more events will be emitted. case Stopped /// Error. This is an ending event: No more events will be emitted. case Error(NSError) public func convertNonValue<U>() -> Event<U> { switch self { case .Value(_): fatalError("convertNonValue() cannot convert Event values!") case .Completed: return .Completed case .Stopped: return .Stopped case .Error(let error): return .Error(error) } } public var isValue: Bool { switch self { case .Value(_): return true default: return false } } public var isCompleted: Bool { switch self { case .Completed: return true default: return false } } public var isStopped: Bool { switch self { case .Stopped: return true default: return false } } public var isError: Bool { switch self { case .Error(_): return true default: return false } } public var isEnd: Bool { return !isValue } public var value: T? { switch self { case .Value(let valueBox): return valueBox.unbox() default: return nil } } public static func fromValue(value: T) -> Event { return .Value(Box(value)) } public var error: NSError? { switch self { case .Error(let error): return error default: return nil } } }
24.954545
145
0.553734
0acc8f55b78a66e7c5798041fd74eefd1addf5e4
1,519
// // CollectionViewBatchUpdatesTestCase.swift // DTCollectionViewManager // // Created by Denys Telezhkin on 02.12.17. // Copyright © 2017 Denys Telezhkin. All rights reserved. // import XCTest import XCTest import DTCollectionViewManager import DTModelStorage // This unit test shows problem, described in https://github.com/DenTelezhkin/DTCollectionViewManager/issues/23 and https://github.com/DenTelezhkin/DTCollectionViewManager/issues/27 private class Cell: UICollectionViewCell, ModelTransfer { func update(with model: Model) { } } private class Model { } class CollectionViewCrashTest: XCTestCase, DTCollectionViewManageable { var collectionView: UICollectionView? override func setUp() { collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), collectionViewLayout: UICollectionViewFlowLayout()) manager.registerNibless(Cell.self) } // func testThisWillCrash() { // manager.memoryStorage.setItems([Model(), Model()]) // manager.memoryStorage.addItems([Model(), Model(), Model()]) // // XCTAssertEqual(manager.memoryStorage.totalNumberOfItems, 5) // } func testSettingAndAddingItemsWithDeferredDatasourceUpdatesWorks() { manager.memoryStorage.defersDatasourceUpdates = true manager.memoryStorage.setItems([Model(), Model()]) manager.memoryStorage.addItems([Model(), Model(), Model()]) XCTAssertEqual(manager.memoryStorage.totalNumberOfItems, 5) } }
33.755556
181
0.726136
debe7edf81b4e70f08d4aa5ddb7a4a56f2ed8396
234
// // BadgeModel.swift // YoongYoong // // Created by 김태훈 on 2021/05/02. // import Foundation struct BadgeModel { let badgeId: Int let imagePath : String let title: String let discription: String let condition: String }
14.625
33
0.692308
21ab53b47c73711cbb871b3ece4bc402d589212c
5,189
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_Buttons_Buttons import third_party_objective_c_material_components_ios_components_Typography_Typography /// A button subclass for the record button to change accessibility labels when selected or not. class RecordButton: MDCFlatButton { override var isSelected: Bool { didSet { accessibilityLabel = isSelected ? String.btnStopDescription : String.btnRecordDescription } } } /// The record button view is a bar containing a record button. It has a snapshot button on the left /// and has a timer label on the right. class RecordButtonView: UIView { // MARK: - Properties /// The record button. let recordButton = RecordButton(type: .custom) /// The snapshot button. let snapshotButton = MDCFlatButton(type: .custom) /// The timer label. let timerLabel = UILabel() /// The elapsed time formatter. let timeFormatter = ElapsedTimeFormatter() // MARK: - Public override init(frame: CGRect) { super.init(frame: .zero) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: ViewConstants.toolbarHeight) } /// Updates `timerLabel.text` with a formatted version of `duration`. /// /// - Parameter duration: The duration to format and display. func updateTimerLabel(with duration: Int64) { let oneHour: Int64 = 1000 * 60 * 60 timeFormatter.shouldDisplayTenths = duration < oneHour timerLabel.text = timeFormatter.string(fromTimestamp: duration) } // MARK: - Private private func configureView() { // The snapshot button. let snapshotWrapper = UIView() snapshotWrapper.translatesAutoresizingMaskIntoConstraints = false snapshotWrapper.addSubview(snapshotButton) snapshotButton.setImage(UIImage(named: "ic_snapshot_action"), for: .normal) snapshotButton.tintColor = .white snapshotButton.translatesAutoresizingMaskIntoConstraints = false snapshotButton.inkStyle = .unbounded snapshotButton.inkMaxRippleRadius = 40.0 snapshotButton.hitAreaInsets = UIEdgeInsets(top: -10, left: -20, bottom: -10, right: -20) snapshotButton.pinToEdgesOfView(snapshotWrapper, withInsets: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: -20)) snapshotButton.accessibilityLabel = String.snapshotButtonText snapshotButton.accessibilityHint = String.snapshotButtonContentDetails // The record button. recordButton.setImage(UIImage(named: "record_button"), for: .normal) recordButton.setImage(UIImage(named: "stop_button"), for: .selected) recordButton.inkColor = .clear recordButton.autoresizesSubviews = false recordButton.contentEdgeInsets = .zero recordButton.imageEdgeInsets = .zero recordButton.translatesAutoresizingMaskIntoConstraints = false recordButton.hitAreaInsets = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10) recordButton.setContentHuggingPriority(.required, for: .horizontal) recordButton.setContentHuggingPriority(.required, for: .vertical) recordButton.isSelected = false // Calls the didSet on isSelected to update a11y label. // The timer label. let timerWrapper = UIView() timerWrapper.translatesAutoresizingMaskIntoConstraints = false timerWrapper.addSubview(timerLabel) timerLabel.font = MDCTypography.headlineFont() timerLabel.textAlignment = .left timerLabel.textColor = .white timerLabel.translatesAutoresizingMaskIntoConstraints = false timerLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal) timerLabel.leadingAnchor.constraint(equalTo: timerWrapper.leadingAnchor, constant: 16.0).isActive = true timerLabel.centerYAnchor.constraint(equalTo: timerWrapper.centerYAnchor).isActive = true timerLabel.isAccessibilityElement = true timerLabel.accessibilityTraits = .updatesFrequently let stackView = UIStackView(arrangedSubviews: [snapshotWrapper, recordButton, timerWrapper]) addSubview(stackView) stackView.distribution = .fillEqually stackView.alignment = .center stackView.translatesAutoresizingMaskIntoConstraints = false stackView.pinToEdgesOfView(self) } }
38.723881
100
0.71825
23a885a60d3dc46ba19f2191d0cbe066d46ebb40
4,081
// // PWC+Cache.swift // Aerial // This is the controller code for the Cache Tab // // Created by Guillaume Louel on 03/06/2019. // Copyright © 2019 John Coates. All rights reserved. // import Cocoa extension PreferencesWindowController { func setupCacheTab() { // Cache panel if preferences.neverStreamVideos { neverStreamVideosCheckbox.state = .on } if preferences.neverStreamPreviews { neverStreamPreviewsCheckbox.state = .on } if !preferences.cacheAerials { cacheAerialsAsTheyPlayCheckbox.state = .off } if let cacheDirectory = VideoCache.cacheDirectory { cacheLocation.url = URL(fileURLWithPath: cacheDirectory as String) } else { cacheLocation.url = nil } } func updateCacheSize() { // get your directory url, we now use App support let documentsDirectoryURL = URL(fileURLWithPath: VideoCache.appSupportDirectory!) // FileManager.default.urls(for: VideoCache.cacheDirectory, in: .userDomainMask).first! // check if the url is a directory if (try? documentsDirectoryURL.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true { var folderSize = 0 (FileManager.default.enumerator(at: documentsDirectoryURL, includingPropertiesForKeys: nil)?.allObjects as? [URL])?.lazy.forEach { folderSize += (try? $0.resourceValues(forKeys: [.totalFileAllocatedSizeKey]))?.totalFileAllocatedSize ?? 0 } let byteCountFormatter = ByteCountFormatter() byteCountFormatter.allowedUnits = .useGB byteCountFormatter.countStyle = .file let sizeToDisplay = byteCountFormatter.string(for: folderSize) ?? "" debugLog("Cache size : \(sizeToDisplay)") cacheSizeTextField.stringValue = "Cache all videos (Current cache size \(sizeToDisplay))" } } @IBAction func cacheAerialsAsTheyPlayClick(_ button: NSButton!) { let onState = button.state == .on preferences.cacheAerials = onState debugLog("UI cacheAerialAsTheyPlay: \(onState)") } @IBAction func neverStreamVideosClick(_ button: NSButton!) { let onState = button.state == .on preferences.neverStreamVideos = onState debugLog("UI neverStreamVideos: \(onState)") } @IBAction func neverStreamPreviewsClick(_ button: NSButton!) { let onState = button.state == .on preferences.neverStreamPreviews = onState debugLog("UI neverStreamPreviews: \(onState)") } @IBAction func showInFinder(_ button: NSButton!) { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: VideoCache.cacheDirectory!) } @IBAction func showAppSupportInFinder(_ sender: Any) { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: VideoCache.appSupportDirectory!) } @IBAction func userSetCacheLocation(_ button: NSButton?) { if #available(OSX 10.15, *) { // On Catalina, we can't use NSOpenPanel right now cacheFolderTextField.stringValue = VideoCache.cacheDirectory! changeCacheFolderPanel.makeKeyAndOrderFront(self) } else { let openPanel = NSOpenPanel() openPanel.canChooseDirectories = true openPanel.canChooseFiles = false openPanel.canCreateDirectories = true openPanel.allowsMultipleSelection = false openPanel.title = "Choose Aerial Cache Directory" openPanel.prompt = "Choose" openPanel.directoryURL = cacheLocation.url openPanel.begin { result in guard result.rawValue == NSFileHandlingPanelOKButton, !openPanel.urls.isEmpty else { return } let cacheDirectory = openPanel.urls[0] self.preferences.customCacheDirectory = cacheDirectory.path self.cacheLocation.url = cacheDirectory } } } }
38.140187
142
0.644695
506fd199c33a9431312ffe472852865ae9e78463
1,661
// // ViewController.swift // Tip Calculator // // Created by Cesa Salaam on 8/28/18. // Copyright © 2018 Cesa Salaam. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var tipController: UISegmentedControl! @IBOutlet weak var totalBill: UILabel! let tips = [0.1,0.2,0.3] override func viewDidLoad() { billField.becomeFirstResponder() } @IBAction func calculateBill(_ sender: Any) { let bill = Double(billField.text!) ?? 0 let tip = bill * tips[tipController.selectedSegmentIndex] as NSNumber let total = (bill + (bill * tips[tipController.selectedSegmentIndex])) as NSNumber //let newTotal = NumberFormatter.localizedString(from: NSNumber(value: total), number: NumberFormatter.Style.decimal) //let newTip = NumberFormatter.localizedString(from: NSNumber(value: tip), number: NumberFormatter.Style.decimal) //print(newTip) if (billField.text?.count)! < 8 { let formatter = NumberFormatter() formatter.numberStyle = .currency totalBill.text = formatter.string(from: total) tipLabel.text = formatter.string(from: tip) // totalBill.text = String(format: "$%.02f", newTotal) //tipLabel.text = String(format: "$%.02f", newTip) } else{ billField.deleteBackward() } } @IBAction func tapped(_ sender: Any) { view.endEditing(true) } }
29.660714
125
0.61469
2073a3c6647714345544cc8820f106520476fe89
4,998
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import Photos let StitchEditSegueID = "StitchEditSegue" class StitchDetailViewController: UIViewController, PHPhotoLibraryChangeObserver, AssetPickerDelegate { var asset: PHAsset! @IBOutlet private var imageView: UIImageView! @IBOutlet private var editButton: UIBarButtonItem! @IBOutlet private var favoriteButton: UIBarButtonItem! @IBOutlet private var deleteButton: UIBarButtonItem! private var stitchAssets:[PHAsset]? deinit { // Unregister observer } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Register observer } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) displayImage() editButton.enabled = asset.canPerformEditOperation(.Content) favoriteButton.enabled = asset.canPerformEditOperation(.Properties) deleteButton.enabled = asset.canPerformEditOperation(.Delete) updateFavoriteButton() // Update the interface buttons } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == StitchEditSegueID { let nav = segue.destinationViewController as! UINavigationController let dest = nav.viewControllers[0] as! AssetCollectionsViewController dest.delegate = self // Set up AssetPickerTableViewController if let assets = stitchAssets { dest.selectedAssets = SelectedAssets(assets: assets) }else{ dest.selectedAssets = nil } } } // MARK: Private private func displayImage() { // Load a high quality image to display let scale = UIScreen.mainScreen().scale let targetSize = CGSize(width: CGRectGetWidth(imageView.bounds) * scale, height: CGRectGetHeight(imageView.bounds) * scale) let options = PHImageRequestOptions() options.deliveryMode = .HighQualityFormat options.networkAccessAllowed = true PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: options) { result, info in // if result != nil { self.imageView.image = result // } } } private func updateFavoriteButton() { if asset.favorite { favoriteButton.title = "Favorite" } else { favoriteButton.title = "Unfavorite" } } // MARK: Actions @IBAction func favoritePressed(sender:AnyObject!) { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let request = PHAssetChangeRequest(forAsset: self.asset) request.favorite = !self.asset.favorite //为什么这个不生效 // request.hidden = !self.asset.hidden }, completionHandler: {success, error in dispatch_async(dispatch_get_main_queue(), { self.updateFavoriteButton() }) }) } @IBAction func deletePressed(sender:AnyObject!) { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ PHAssetChangeRequest.deleteAssets([self.asset]) }, completionHandler: {success, error in }) } @IBAction func editPressed(sender:AnyObject!) { // Load the selected stitches then perform the segue to the picker StitchHelper.loadAssetsInStitch(asset) { stichAssets in self.stitchAssets = stichAssets dispatch_async(dispatch_get_main_queue(), { () -> Void in self.performSegueWithIdentifier(StitchCellReuseIdentifier, sender: self) }) } } // MARK: AssetPickerDelegate func assetPickerDidCancel() { dismissViewControllerAnimated(true, completion: nil) } func assetPickerDidFinishPickingAssets(selectedAssets: [PHAsset]) { dismissViewControllerAnimated(true, completion: nil) // Update stitch with new assets } // MARK: PHPhotoLibraryChangeObserver func photoLibraryDidChange(changeInstance: PHChange) { // Respond to changes } }
31.834395
133
0.714686
164238e0e5ceb9dc7c899bb11ae4cb444ef9455d
2,058
// Created by Julian Dunskus import Foundation typealias Step = Character let dependencies: [(Step, Step)] = input().lines().map { let words = $0.split(separator: " ") return (words[1].first!, words[7].first!) } let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let requirements: [Step: Set<Step>] = Dictionary(uniqueKeysWithValues: zip(alphabet, repeatElement([]))) <- { requirements in for (dependency, dependent) in dependencies { requirements[dependent]!.insert(dependency) } } do { var order = "" var remaining = requirements while !remaining.isEmpty { let choice = remaining .filter { $0.value.isEmpty } .map { $0.key } .sorted() .first! order.append(choice) remaining.removeValue(forKey: choice) for dependent in remaining.keys { remaining[dependent]?.remove(choice) } } print(order) } let aValue = ("A" as Step).firstScalarValue func duration(for step: Step) -> Int { return 61 + aValue.distance(to: step.firstScalarValue) } struct Progress { var step: Step var remaining: Int init(_ step: Step) { self.step = step self.remaining = duration(for: step) } } do { var remaining = requirements var work = [Progress?](repeating: nil, count: 5) var time = 0 while !remaining.isEmpty { for index in work.indices { work[index] = work[index] <- { progress in progress?.remaining -= 1 if let existing = progress, existing.remaining == 0 { for dependent in remaining.keys { remaining[dependent]?.remove(existing.step) } progress = nil } if progress == nil { let choice = remaining .filter { $0.value.isEmpty } .map { $0.key } .sorted() .first if let choice = choice { progress = Progress(choice) remaining.removeValue(forKey: choice) } } } } time += 1 } time += work.compactMap { $0?.remaining }.max() ?? 0 print(time) // not 1121 } func minDuration(for step: Step) -> Int { return duration(for: step) + (requirements[step]!.map(minDuration).max() ?? 0) } print(alphabet.map(minDuration))
22.615385
125
0.652575
202ec7b8bbb6174fd8e5ae3456af3a74262faf5a
1,962
// // ButtonsViewController.swift // BEPureLayout_Example // // Created by Chung Tran on 5/25/20. // Copyright © 2020 CocoaPods. All rights reserved. // import Foundation import BEPureLayout class ButtonsLabelsViewController: BEViewController { override func setUp() { super.setUp() // Main stackViews let hStackView = UIStackView(axis: .horizontal, spacing: 10, alignment: .top, distribution: .fillEqually) view.addSubview(hStackView) hStackView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)) hStackView.addArrangedSubviews { UIStackView(axis: .vertical, spacing: 10, alignment: .center, distribution: .fill ) { UIButton(backgroundColor: .red, cornerRadius: 16, label: "first button", textColor: .white, contentInsets: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)) BEStackViewSpacing(20) UIButton(label: "second button", textColor: .systemBlue) } UIStackView(axis: .vertical, spacing: 10, alignment: .center, distribution: .fill ) { UILabel(text: "first label", textSize: 20, weight: .bold, textColor: .red, textAlignment: .right) UILabel(text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", textColor: .blue, numberOfLines: 0) } } } }
54.5
643
0.682467
646ee5ec08c7c85d2b1a5fad27a055446837fd3c
60,712
// // ModalPresenter.swift // ravenwallet // // Created by Adrian Corscadden on 2016-10-25. // Copyright © 2018 Ravenwallet Team. All rights reserved. // import UIKit import LocalAuthentication class ModalPresenter : Subscriber { //MARK: - Public let walletManager: WalletManager let supportCenter = SupportWebViewController() init(walletManager: WalletManager, window: UIWindow, apiClient: BRAPIClient) { self.window = window self.walletManager = walletManager self.modalTransitionDelegate = ModalTransitionDelegate(type: .regular) self.wipeNavigationDelegate = StartNavigationDelegate() self.noAuthApiClient = apiClient addSubscriptions() } deinit { Store.unsubscribe(self) } //MARK: - Private private let window: UIWindow private let alertHeight: CGFloat = 260.0 private let modalTransitionDelegate: ModalTransitionDelegate private let messagePresenter = MessageUIPresenter() private let securityCenterNavigationDelegate = SecurityCenterNavigationDelegate() let verifyPinTransitionDelegate = PinTransitioningDelegate() private let noAuthApiClient: BRAPIClient private var currentRequest: PaymentRequest? private var reachability = ReachabilityMonitor() private var notReachableAlert: InAppAlert? private let wipeNavigationDelegate: StartNavigationDelegate private func addSubscriptions() { Store.lazySubscribe(self, selector: { $0.rootModal != $1.rootModal}, callback: { [weak self] in self?.presentModal($0.rootModal) }) Store.lazySubscribe(self, selector: { $0.alert != $1.alert && $1.alert != .none }, callback: { [weak self] in self?.handleAlertChange($0.alert) }) Store.subscribe(self, name: .presentFaq(""), callback: { [weak self] in guard let trigger = $0 else { return } if case .presentFaq(let articleId) = trigger { self?.presentFaq(articleId: articleId) } }) //Subscribe to prompt actions Store.subscribe(self, name: .promptUpgradePin, callback: { [weak self] _ in self?.presentUpgradePin() }) Store.subscribe(self, name: .promptPaperKey, callback: { [weak self] _ in self?.presentWritePaperKey() }) Store.subscribe(self, name: .promptBiometrics, callback: { [weak self] _ in self?.presentBiometricsSetting() }) Store.subscribe(self, name: .promptShareData, callback: { [weak self] _ in self?.promptShareData() }) Store.subscribe(self, name: .openFile(Data()), callback: { [weak self] in guard let trigger = $0 else { return } if case .openFile(let file) = trigger { self?.handleFile(file) } }) Store.subscribe(self, name: .recommendRescan(walletManager.currency), callback: { [weak self] _ in guard let myself = self else { return } self?.presentRescan(currency: myself.walletManager.currency) }) Store.subscribe(self, name: .recommendRescanAsset, callback: { [weak self] _ in self?.presentRescanAsset() }) //URLs Store.subscribe(self, name: .receivedPaymentRequest(nil), callback: { [weak self] in guard let trigger = $0 else { return } if case let .receivedPaymentRequest(request) = trigger { if let request = request { self?.handlePaymentRequest(request: request) } } }) Store.subscribe(self, name: .scanQr, callback: { [weak self] _ in self?.handleScanQrURL() }) Store.subscribe(self, name: .copyWalletAddresses(nil, nil), callback: { [weak self] in guard let trigger = $0 else { return } if case .copyWalletAddresses(let success, let error) = trigger { self?.handleCopyAddresses(success: success, error: error) } }) Store.subscribe(self, name: .authenticateForBitId("", {_ in}), callback: { [weak self] in guard let trigger = $0 else { return } if case .authenticateForBitId(let prompt, let callback) = trigger { self?.authenticateForBitId(prompt: prompt, callback: callback) } }) reachability.didChange = { [weak self] isReachable in if isReachable { self?.hideNotReachable() } else { self?.showNotReachable() } } Store.subscribe(self, name: .lightWeightAlert(""), callback: { [weak self] in guard let trigger = $0 else { return } if case let .lightWeightAlert(message) = trigger { self?.showLightWeightAlert(message: message) } }) Store.subscribe(self, name: .showAlert(nil), callback: { [weak self] in guard let trigger = $0 else { return } if case let .showAlert(alert) = trigger { if let alert = alert { self?.topViewController?.present(alert, animated: true, completion: nil) } } }) Store.subscribe(self, name: .wipeWalletNoPrompt, callback: { [weak self] _ in self?.wipeWalletNoPrompt() }) Store.subscribe(self, name: .selectAddressBook(nil, nil), callback: { [weak self] in guard let trigger = $0 else { return } if case .selectAddressBook(let addressBookType, let callback) = trigger { self?.presentAddressBook(type: addressBookType, callback: callback) } }) } private func presentModal(_ type: RootModal, configuration: ((UIViewController) -> Void)? = nil) { guard type != .loginScan else { return presentLoginScan() } guard let vc = rootModalViewController(type) else { Store.perform(action: RootModalActions.Present(modal: .none)) return } vc.transitioningDelegate = modalTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true configuration?(vc) topViewController?.present(vc, animated: true) { Store.perform(action: RootModalActions.Present(modal: .none)) Store.trigger(name: .hideStatusBar) } } private func handleAlertChange(_ type: AlertType) { guard type != .none else { return } presentAlert(type, completion: { Store.perform(action: Alert.Hide()) }) } func presentAlert(_ type: AlertType, completion: @escaping ()->Void) { let alertView = AlertView(type: type) let window = UIApplication.shared.keyWindow! let size = window.bounds.size window.addSubview(alertView) let topConstraint = alertView.constraint(.top, toView: window, constant: size.height) alertView.constrain([ alertView.constraint(.width, constant: size.width), alertView.constraint(.height, constant: alertHeight + 25.0), alertView.constraint(.leading, toView: window, constant: nil), topConstraint ]) window.layoutIfNeeded() UIView.spring(0.6, animations: { topConstraint?.constant = size.height - self.alertHeight window.layoutIfNeeded() }, completion: { _ in alertView.animate() UIView.spring(0.6, delay: 2.0, animations: { topConstraint?.constant = size.height window.layoutIfNeeded() }, completion: { _ in //TODO - Make these callbacks generic if case .paperKeySet(let callback) = type { callback() } if case .pinSet(let callback) = type { callback() } if case .sweepSuccess(let callback) = type { callback() } completion() alertView.removeFromSuperview() }) }) } func presentFaq(articleId: String? = nil) { supportCenter.modalPresentationStyle = .overFullScreen supportCenter.modalPresentationCapturesStatusBarAppearance = true let url = articleId == nil ? "/support?" : "/support/\(articleId!)" supportCenter.navigate(to: url) topViewController?.present(supportCenter, animated: true, completion: {}) } private func rootModalViewController(_ type: RootModal) -> UIViewController? { print("perform rootModalViewController %@ called", type) switch type { case .none: return nil case .send(let currency): return makeSendView(currency: currency) case .sendWithAddress(let currency, let initialAddress)://BMEX return makeSendView(currency: currency, initialAddress: initialAddress) case .transferAsset(let asset, let initialAddress)://BMEX return makeTransferAssetView(asset: asset, initialAddress: initialAddress) case .createAsset(let initialAddress)://BMEX return makeCreateAssetView(initialAddress: initialAddress) case .subAsset(let rootAssetName, let initialAddress)://BMEX return makeSubAssetView(rootAssetName: rootAssetName, initialAddress: initialAddress) case .uniqueAsset(let rootAssetName, let initialAddress)://BMEX return makeUniqueAssetView(rootAssetName: rootAssetName, initialAddress: initialAddress) case .manageOwnedAsset(let asset, let initialAddress)://BMEX return makeManageOwnedAssetView(asset: asset, initialAddress: initialAddress) case .burnAsset(let asset)://BMEX return makeBurnAssetView(asset: asset) case .receive(let currency, let isRequestAmountVisible, let initialAddress): return receiveView(currency: currency, isRequestAmountVisible: isRequestAmountVisible, initialAddress: initialAddress) case .selectAsset(let asset): return selectAssetView(asset: asset)//BMEX case .addressBook(let currency, let initialAddress, let actionAddressType, let callback): return makeAddAddressBookView(currency: currency, initialAddress: initialAddress, type: actionAddressType, callback: callback) case .loginScan: return nil //The scan view needs a custom presentation case .loginAddress: return receiveView(currency: Currencies.rvn, isRequestAmountVisible: false) case .requestAmount(let currency): guard let wallet = walletManager.wallet else { return nil } let requestVc = RequestAmountViewController(currency: currency, wallet: wallet) requestVc.presentEmail = { [weak self] bitcoinURL, image in self?.messagePresenter.presenter = self?.topViewController self?.messagePresenter.presentMailCompose(bitcoinURL: bitcoinURL, image: image) } requestVc.presentText = { [weak self] bitcoinURL, image in self?.messagePresenter.presenter = self?.topViewController self?.messagePresenter.presentMessageCompose(bitcoinURL: bitcoinURL, image: image) } return ModalViewController(childViewController: requestVc) } } private func makeSendView(currency: CurrencyDef, initialAddress: String? = nil) -> UIViewController? { guard !currency.state.isRescanning else { let alert = UIAlertController(title: S.Alert.error, message: S.Send.isRescanning, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) return nil } let sendVC = SendViewController(sender: Sender(walletManager: walletManager, currency: currency), walletManager: walletManager, initialAddress: initialAddress,//BMEX initialRequest: currentRequest, currency: currency) currentRequest = nil if Store.state.isLoginRequired { sendVC.isPresentedFromLock = true } let root = ModalViewController(childViewController: sendVC) sendVC.presentScan = presentScan(parent: root, currency: currency) sendVC.presentVerifyPin = { [weak self, weak root] bodyText, success in guard let myself = self else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletManager: myself.walletManager, success: success) vc.transitioningDelegate = self?.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true root?.view.isFrameChangeBlocked = true root?.present(vc, animated: true, completion: nil) } sendVC.onPublishSuccess = { [weak self] in self?.presentAlert(.sendSuccess, completion: {}) } return root } private func makeTransferAssetView(asset: Asset, initialAddress: String? = nil) -> UIViewController? { guard !Currencies.rvn.state.isRescanning else { let alert = UIAlertController(title: S.Alert.error, message: S.Send.isRescanning, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) return nil } let transferAssetVC = TransferAssetVC(asset: asset, walletManager: walletManager, initialAddress: initialAddress, initialRequest: currentRequest) currentRequest = nil if Store.state.isLoginRequired { transferAssetVC.isPresentedFromLock = true } let root = ModalViewController(childViewController: transferAssetVC) transferAssetVC.presentScan = presentScan(parent: root, currency: Currencies.rvn) transferAssetVC.presentVerifyPin = { [weak self, weak root] bodyText, success in guard let myself = self else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletManager: myself.walletManager, success: success) vc.transitioningDelegate = self?.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true root?.view.isFrameChangeBlocked = true root?.present(vc, animated: true, completion: nil) } transferAssetVC.onPublishSuccess = { [weak self] in guard let myself = self else { return } self?.presentAlert(.sendAssetSuccess, completion: { if let allAssetVC = myself.topViewController as? AllAssetVC { self?.pushAccountView(currency: Currencies.rvn, animated: true, nc: allAssetVC.navigationController!) } else { self?.showAccountView(currency: Currencies.rvn, animated: true) } }) } return root } private func makeCreateAssetView(initialAddress: String? = nil) -> UIViewController? { guard !Currencies.rvn.state.isRescanning else { let alert = UIAlertController(title: S.Alert.error, message: S.Send.isRescanning, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) return nil } let createAssetVC = CreateAssetVC(walletManager: walletManager, initialAddress: initialAddress, initialRequest: currentRequest) currentRequest = nil if Store.state.isLoginRequired { createAssetVC.isPresentedFromLock = true } let root = ModalViewController(childViewController: createAssetVC) createAssetVC.presentScan = presentScan(parent: root, currency: Currencies.rvn) createAssetVC.presentVerifyPin = { [weak self, weak root] bodyText, success in guard let myself = self else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletManager: myself.walletManager, success: success) vc.transitioningDelegate = self?.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true root?.view.isFrameChangeBlocked = true root?.present(vc, animated: true, completion: nil) } createAssetVC.onPublishSuccess = { txHash in let qrImage = UIImage.qrCode(data: txHash.data(using: .utf8)!, color: CIColor(color: .black))?.resize(CGSize(width: 186, height: 186))! self.topViewController?.showImageAlert(title: S.Alerts.createSuccess, message: S.Alerts.createSuccessSubheader + txHash + S.Alerts.assetAppearance, image: qrImage!, buttonLabel: S.Button.copy, callback: { _ in Store.trigger(name: .lightWeightAlert(S.Receive.copied)) UIPasteboard.general.string = txHash }) } return root } private func makeSubAssetView(rootAssetName:String, initialAddress: String? = nil) -> UIViewController? { guard !Currencies.rvn.state.isRescanning else { let alert = UIAlertController(title: S.Alert.error, message: S.Send.isRescanning, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) return nil } let createAssetVC = CreateSubAssetVC(walletManager: walletManager, rootAssetName: rootAssetName, initialAddress: initialAddress, initialRequest: currentRequest) currentRequest = nil if Store.state.isLoginRequired { createAssetVC.isPresentedFromLock = true } let root = ModalViewController(childViewController: createAssetVC) createAssetVC.presentScan = presentScan(parent: root, currency: Currencies.rvn) createAssetVC.presentVerifyPin = { [weak self, weak root] bodyText, success in guard let myself = self else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletManager: myself.walletManager, success: success) vc.transitioningDelegate = self?.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true root?.view.isFrameChangeBlocked = true root?.present(vc, animated: true, completion: nil) } createAssetVC.onPublishSuccess = { txHash in let qrImage = UIImage.qrCode(data: txHash.data(using: .utf8)!, color: CIColor(color: .black))?.resize(CGSize(width: 186, height: 186))! self.topViewController?.showImageAlert(title: S.Alerts.createSuccess, message: S.Alerts.createSuccessSubheader + txHash + S.Alerts.assetAppearance, image: qrImage!, buttonLabel: S.Button.copy, callback: { _ in Store.trigger(name: .lightWeightAlert(S.Receive.copied)) UIPasteboard.general.string = txHash }) } return root } private func makeUniqueAssetView(rootAssetName:String, initialAddress: String? = nil) -> UIViewController? { guard !Currencies.rvn.state.isRescanning else { let alert = UIAlertController(title: S.Alert.error, message: S.Send.isRescanning, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) return nil } let createAssetVC = CreateUniqueAssetVC(walletManager: walletManager, rootAssetName: rootAssetName, initialAddress: initialAddress, initialRequest: currentRequest) currentRequest = nil if Store.state.isLoginRequired { createAssetVC.isPresentedFromLock = true } let root = ModalViewController(childViewController: createAssetVC) createAssetVC.presentScan = presentScan(parent: root, currency: Currencies.rvn) createAssetVC.presentVerifyPin = { [weak self, weak root] bodyText, success in guard let myself = self else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletManager: myself.walletManager, success: success) vc.transitioningDelegate = self?.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true root?.view.isFrameChangeBlocked = true root?.present(vc, animated: true, completion: nil) } createAssetVC.onPublishSuccess = { txHash in let qrImage = UIImage.qrCode(data: txHash.data(using: .utf8)!, color: CIColor(color: .black))?.resize(CGSize(width: 186, height: 186))! self.topViewController?.showImageAlert(title: S.Alerts.createSuccess, message: S.Alerts.createSuccessSubheader + txHash + S.Alerts.assetAppearance, image: qrImage!, buttonLabel: S.Button.copy, callback: { _ in Store.trigger(name: .lightWeightAlert(S.Receive.copied)) UIPasteboard.general.string = txHash }) } return root } private func makeManageOwnedAssetView(asset: Asset, initialAddress: String? = nil) -> UIViewController? { guard !Currencies.rvn.state.isRescanning else { let alert = UIAlertController(title: S.Alert.error, message: S.Send.isRescanning, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) return nil } let manageOwnedAssetVC = ManageOwnedAssetVC(asset: asset, walletManager: walletManager, initialAddress: initialAddress, initialRequest: currentRequest) currentRequest = nil if Store.state.isLoginRequired { manageOwnedAssetVC.isPresentedFromLock = true } let root = ModalViewController(childViewController: manageOwnedAssetVC) manageOwnedAssetVC.presentScan = presentScan(parent: root, currency: Currencies.rvn) manageOwnedAssetVC.presentVerifyPin = { [weak self, weak root] bodyText, success in guard let myself = self else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletManager: myself.walletManager, success: success) vc.transitioningDelegate = self?.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true root?.view.isFrameChangeBlocked = true root?.present(vc, animated: true, completion: nil) } manageOwnedAssetVC.onPublishSuccess = { [weak self] in self?.presentAlert(.reissueAssetSuccess, completion: {}) } return root } private func makeBurnAssetView(asset: Asset) -> UIViewController? { guard !Currencies.rvn.state.isRescanning else { let alert = UIAlertController(title: S.Alert.error, message: S.Send.isRescanning, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) return nil } let burnAssetVC = BurnAssetVC(asset: asset, walletManager: walletManager) currentRequest = nil if Store.state.isLoginRequired { burnAssetVC.isPresentedFromLock = true } let root = ModalViewController(childViewController: burnAssetVC) burnAssetVC.presentVerifyPin = { [weak self, weak root] bodyText, success in guard let myself = self else { return } let vc = VerifyPinViewController(bodyText: bodyText, pinLength: Store.state.pinLength, walletManager: myself.walletManager, success: success) vc.didCancel = { DispatchQueue.main.async { burnAssetVC.dismiss(animated: true, completion: nil) } } vc.transitioningDelegate = self?.verifyPinTransitionDelegate vc.modalPresentationStyle = .overFullScreen vc.modalPresentationCapturesStatusBarAppearance = true root?.view.isFrameChangeBlocked = true root?.present(vc, animated: true, completion: nil) } burnAssetVC.onPublishSuccess = { [weak self] in guard let myself = self else { return } self?.presentAlert(.burnAssetSuccess, completion: { if let allAssetVC = myself.topViewController as? AllAssetVC { self?.pushAccountView(currency: Currencies.rvn, animated: true, nc: allAssetVC.navigationController!) } else { self?.showAccountView(currency: Currencies.rvn, animated: true) } }) } return root } private func receiveView(currency: CurrencyDef, isRequestAmountVisible: Bool, initialAddress: String? = nil) -> UIViewController? { let receiveVC = ReceiveViewController(currency: currency, isRequestAmountVisible: isRequestAmountVisible, initialAddress: initialAddress) let root = ModalViewController(childViewController: receiveVC) receiveVC.presentEmail = { [weak self, weak root] address, image in guard let root = root, let uri = currency.addressURI(address) else { return } self?.messagePresenter.presenter = root self?.messagePresenter.presentMailCompose(uri: uri, image: image) } receiveVC.presentText = { [weak self, weak root] address, image in guard let root = root, let uri = currency.addressURI(address) else { return } self?.messagePresenter.presenter = root self?.messagePresenter.presentMessageCompose(uri: uri, image: image) } return root } private func selectAssetView(asset: Asset) -> UIViewController? { let assetPopUpVC = AssetPopUpVC(walletManager: walletManager, asset: asset) let root = ModalViewController(childViewController: assetPopUpVC) assetPopUpVC.parentVC = root assetPopUpVC.modalPresenter = self return root } private func makeAddAddressBookView(currency: CurrencyDef, initialAddress: String? = nil, type:ActionAddressType, callback: @escaping () -> Void) -> UIViewController? {//BMEX let addAddressVC = AddAddressBookVC(currency: currency, initialAddress: initialAddress, type: type, callback: callback) let root = ModalViewController(childViewController: addAddressVC) addAddressVC.presentScan = presentScan(parent: root, currency: currency) return root } private func presentLoginScan() { guard let top = topViewController else { return } let present = presentScan(parent: top, currency: Currencies.rvn) Store.perform(action: RootModalActions.Present(modal: .none)) present({ paymentRequest in guard let request = paymentRequest else { return } self.currentRequest = request self.presentModal(.send(currency: Currencies.rvn)) }) } func presentSettings() { guard let top = topViewController else { return } let settingsNav = UINavigationController() settingsNav.setGrayStyle() let sections: [SettingsSections] = [.wallet, .preferences, .currencies, .assets, .other] let rows = [ SettingsSections.wallet: [ Setting(title: S.Settings.wipe, callback: { [weak self] in guard let `self` = self else { return } let nc = ModalNavigationController() nc.setClearNavbar() nc.setWhiteStyle() nc.delegate = self.wipeNavigationDelegate let start = StartWipeWalletViewController { [weak self] in guard let myself = self else { return } let recover = EnterPhraseViewController(walletManager: myself.walletManager, reason: .validateForWipingWallet( { self?.wipeWallet() })) nc.pushViewController(recover, animated: true) } start.addCloseNavigationItem(tintColor: .white) start.navigationItem.title = S.WipeWallet.title let faqButton = UIButton.buildFaqButton(articleId: ArticleIds.wipeWallet) faqButton.tintColor = .white start.navigationItem.rightBarButtonItems = [UIBarButtonItem.negativePadding, UIBarButtonItem(customView: faqButton)] nc.viewControllers = [start] settingsNav.dismiss(animated: true, completion: { [weak self] in self?.topViewController?.present(nc, animated: true, completion: nil) }) }) ], SettingsSections.preferences: [ Setting(title: LAContext.biometricType() == .face ? S.Settings.faceIdLimit : S.Settings.touchIdLimit, accessoryText: { guard let rate = Currencies.rvn.state.currentRate else { return "" } let amount = Amount(amount: self.walletManager.spendingLimit, rate: rate, maxDigits: Currencies.rvn.state.maxDigits, currency: Currencies.rvn) return amount.localCurrency }, callback: { [weak self] in self?.pushBiometricsSpendingLimit(onNc: settingsNav) }), Setting(title: S.UpdatePin.updateTitle, callback: strongify(self) { myself in let updatePin = UpdatePinViewController(walletManager: self.walletManager, type: .update) settingsNav.pushViewController(updatePin, animated: true) }), Setting(title: S.Settings.currency, accessoryText: { let code = Store.state.defaultCurrencyCode let components: [String : String] = [NSLocale.Key.currencyCode.rawValue : code] let identifier = Locale.identifier(fromComponents: components) return Locale(identifier: identifier).currencyCode ?? "" }, callback: { settingsNav.pushViewController(DefaultCurrencyViewController(walletManager: self.walletManager), animated: true) }), ], SettingsSections.currencies: [ Setting(title: S.Settings.importTile, callback: { settingsNav.dismiss(animated: true, completion: { [weak self] in guard let myself = self else { return } self?.presentKeyImport(walletManager: myself.walletManager) }) }), Setting(title: S.Settings.sync, callback: { settingsNav.pushViewController(ReScanViewController(currency: Currencies.rvn), animated: true) }), ], SettingsSections.assets: [ Setting(title: S.Asset.settingTitle, callback: { [weak self] in guard let `self` = self else { return } let nc = ModalNavigationController() nc.setClearNavbar() nc.setWhiteStyle() nc.delegate = self.wipeNavigationDelegate let start = ManageAssetDisplayVC () start.addCloseNavigationItem(tintColor: .white) start.navigationItem.rightBarButtonItems = [UIBarButtonItem.negativePadding] nc.viewControllers = [start] settingsNav.dismiss(animated: true, completion: { [weak self] in self?.topViewController?.present(nc, animated: true, completion: nil) }) }), ], SettingsSections.other: [ Setting(title: S.Settings.shareData, callback: { settingsNav.pushViewController(ShareDataViewController(), animated: true) }), Setting(title: S.Settings.review, callback: { [weak self] in guard let `self` = self else { return } let alert = UIAlertController(title: S.Settings.review, message: S.Settings.enjoying, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.no, style: .default, handler: { _ in self.messagePresenter.presenter = self.topViewController self.messagePresenter.presentFeedbackCompose() })) alert.addAction(UIAlertAction(title: S.Button.yes, style: .default, handler: { _ in if let url = URL(string: C.reviewLink) { UIApplication.shared.open(url) } })) self.topViewController?.present(alert, animated: true, completion: nil) }), Setting(title: S.Settings.about, callback: { settingsNav.pushViewController(AboutViewController(), animated: true) }), Setting(title: S.Settings.advanced, callback: { var sections = [SettingsSections.network] var advancedSettings = [ SettingsSections.network: [ Setting(title: S.NodeSelector.title, callback: { let nodeSelector = NodeSelectorViewController(walletManager: self.walletManager) settingsNav.pushViewController(nodeSelector, animated: true) }), Setting(title: S.Settings.usedAddresses, isHidden: !UserDefaults.hasActivatedExpertMode, callback: { [weak self] in guard let `self` = self else { return } let nc = ModalNavigationController() nc.setClearNavbar() nc.setWhiteStyle() nc.delegate = self.wipeNavigationDelegate let start = AllAddressesVC(walletManager: self.walletManager) start.addCloseNavigationItem(tintColor: .white) start.navigationItem.rightBarButtonItems = [UIBarButtonItem.negativePadding] nc.viewControllers = [start] settingsNav.dismiss(animated: true, completion: { [weak self] in self?.topViewController?.present(nc, animated: true, completion: nil) }) }), Setting(title: S.WipeSetting.title, isHidden: !UserDefaults.hasActivatedExpertMode, callback: { self.wipeWallet() }), Setting(title: S.Settings.expertMode, toggle: UISwitch(), toggleDefaultValue: UserDefaults.hasActivatedExpertMode, toggleCallback: { isOn in UserDefaults.hasActivatedExpertMode = isOn Store.trigger(name: .reloadSettings) }) ], ] if E.isTestFlight { advancedSettings[SettingsSections.other] = [ Setting(title: S.Settings.sendLogs, callback: { [weak self] in self?.showEmailLogsModal() }) ] sections.append(SettingsSections.other) } let advancedSettingsVC = SettingsViewController(sections: sections, rows: advancedSettings, optionalTitle: S.Settings.advancedTitle) settingsNav.pushViewController(advancedSettingsVC, animated: true) }) ] ] let settings = SettingsViewController(sections: sections, rows: rows) settings.addCloseNavigationItem(tintColor: .mediumGray, side: .right) settingsNav.viewControllers = [settings] top.present(settingsNav, animated: true, completion: nil) } private func presentScan(parent: UIViewController, currency: CurrencyDef) -> PresentScan { return { [weak parent] scanCompletion in guard ScanViewController.isCameraAllowed else { if let parent = parent { ScanViewController.presentCameraUnavailableAlert(fromRoot: parent) } return } let vc = ScanViewController(currency: currency, completion: { paymentRequest in scanCompletion(paymentRequest) parent?.view.isFrameChangeBlocked = false }) parent?.view.isFrameChangeBlocked = true parent?.present(vc, animated: true, completion: {}) } } func presentSecurityCenter() { let securityCenter = SecurityCenterViewController(walletManager: walletManager) let nc = ModalNavigationController(rootViewController: securityCenter) nc.setDefaultStyle() nc.isNavigationBarHidden = true nc.delegate = securityCenterNavigationDelegate securityCenter.didTapPin = { let updatePin = UpdatePinViewController(walletManager: self.walletManager, type: .update) nc.pushViewController(updatePin, animated: true) } securityCenter.didTapBiometrics = strongify(self) { myself in let biometricsSettings = BiometricsSettingsViewController(walletManager: self.walletManager) biometricsSettings.presentSpendingLimit = { myself.pushBiometricsSpendingLimit(onNc: nc) } nc.pushViewController(biometricsSettings, animated: true) } securityCenter.didTapPaperKey = { [weak self] in self?.presentWritePaperKey(fromViewController: nc) } window.rootViewController?.present(nc, animated: true, completion: nil) } func presentAddressBook(type: AddressBookType? = .normal, callback: ((String) -> Void)? = nil) { let addressBookVC = AddressBookVC(walletManager: walletManager, addressBookType: type, callback: callback) let nc = ModalNavigationController(rootViewController: addressBookVC) nc.setClearNavbar() addressBookVC.addCloseNavigationItem(tintColor: .white) topViewController?.present(nc, animated: true, completion: nil) } func presentTutorial() { let tutorialVC = TutorialVC() let nc = ModalNavigationController(rootViewController: tutorialVC) nc.setNavigationBarHidden(false, animated: false) nc.setClearNavbar() tutorialVC.addCloseNavigationItem(tintColor: .white) window.rootViewController?.present(nc, animated: true, completion: nil) } private func pushBiometricsSpendingLimit(onNc: UINavigationController) { let verify = VerifyPinViewController(bodyText: S.VerifyPin.continueBody, pinLength: Store.state.pinLength, walletManager: walletManager, success: { pin in let spendingLimit = BiometricsSpendingLimitViewController(walletManager: self.walletManager) onNc.pushViewController(spendingLimit, animated: true) }) verify.transitioningDelegate = verifyPinTransitionDelegate verify.modalPresentationStyle = .overFullScreen verify.modalPresentationCapturesStatusBarAppearance = true onNc.present(verify, animated: true, completion: nil) } private func presentWritePaperKey(fromViewController vc: UIViewController) { let paperPhraseNavigationController = UINavigationController() paperPhraseNavigationController.setClearNavbar() paperPhraseNavigationController.setWhiteStyle() paperPhraseNavigationController.modalPresentationStyle = .overFullScreen let start = StartPaperPhraseViewController(callback: { [weak self] in guard let `self` = self else { return } let verify = VerifyPinViewController(bodyText: S.VerifyPin.continueBody, pinLength: Store.state.pinLength, walletManager: self.walletManager, success: { pin in self.pushWritePaperPhrase(navigationController: paperPhraseNavigationController, pin: pin) }) verify.transitioningDelegate = self.verifyPinTransitionDelegate verify.modalPresentationStyle = .overFullScreen verify.modalPresentationCapturesStatusBarAppearance = true paperPhraseNavigationController.present(verify, animated: true, completion: nil) }) start.addCloseNavigationItem(tintColor: .white) start.navigationItem.title = S.SecurityCenter.Cells.paperKeyTitle let faqButton = UIButton.buildFaqButton(articleId: ArticleIds.paperKey) faqButton.tintColor = .white start.navigationItem.rightBarButtonItems = [UIBarButtonItem.negativePadding, UIBarButtonItem(customView: faqButton)] paperPhraseNavigationController.viewControllers = [start] vc.present(paperPhraseNavigationController, animated: true, completion: nil) } private func pushWritePaperPhrase(navigationController: UINavigationController, pin: String) { var writeViewController: WritePaperPhraseViewController? writeViewController = WritePaperPhraseViewController(walletManager: walletManager, pin: pin, callback: { var confirm: ConfirmPaperPhraseViewController? confirm = ConfirmPaperPhraseViewController(walletManager: self.walletManager, pin: pin, callback: { confirm?.dismiss(animated: true, completion: { Store.perform(action: Alert.Show(.paperKeySet(callback: { Store.perform(action: HideStartFlow()) }))) }) }) writeViewController?.navigationItem.title = S.SecurityCenter.Cells.paperKeyTitle if let confirm = confirm { navigationController.pushViewController(confirm, animated: true) } }) writeViewController?.addCloseNavigationItem(tintColor: .white) writeViewController?.navigationItem.title = S.SecurityCenter.Cells.paperKeyTitle guard let writeVC = writeViewController else { return } navigationController.pushViewController(writeVC, animated: true) } private func presentBuyController(_ mountPoint: String) { let vc: BRWebViewController #if Debug || Testflight vc = BRWebViewController(bundleName: "bread-frontend-staging", mountPoint: mountPoint, walletManager: walletManager) #else vc = BRWebViewController(bundleName: "bread-frontend", mountPoint: mountPoint, walletManager: walletManager) #endif vc.startServer() vc.preload() self.topViewController?.present(vc, animated: true, completion: nil) } private func presentRescan(currency: CurrencyDef) { let vc = ReScanViewController(currency: currency) let nc = UINavigationController(rootViewController: vc) nc.setClearNavbar() vc.addCloseNavigationItem() topViewController?.present(nc, animated: true, completion: nil) } private func presentRescanAsset() { let vc = ReScanAssetVC(currency: Currencies.rvn) let nc = UINavigationController(rootViewController: vc) nc.setClearNavbar() vc.addCloseNavigationItem() topViewController?.present(nc, animated: true, completion: nil) } public func wipeWallet() { let alert = UIAlertController(title: S.WipeWallet.alertTitle, message: S.WipeWallet.alertMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .default, handler: nil)) alert.addAction(UIAlertAction(title: S.WipeWallet.wipe, style: .destructive, handler: { _ in // self.topViewController?.dismiss(animated: true, completion: { Store.trigger(name: .wipeWalletNoPrompt) // }) })) topViewController?.present(alert, animated: true, completion: nil) } public func wipeWalletNoPrompt() { let activity = BRActivityViewController(message: S.WipeWallet.wiping) self.topViewController?.present(activity, animated: true, completion: nil) DispatchQueue.walletQueue.async { self.walletManager.peerManager?.disconnect() DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: { activity.dismiss(animated: true, completion: { if self.walletManager.wipeWallet(pin: "forceWipe") { Store.trigger(name: .reinitWalletManager({})) } else { let failure = UIAlertController(title: S.WipeWallet.failedTitle, message: S.WipeWallet.failedMessage, preferredStyle: .alert) failure.addAction(UIAlertAction(title: S.Button.ok, style: .default, handler: nil)) self.topViewController?.present(failure, animated: true, completion: nil) } }) }) } } private func presentKeyImport(walletManager: WalletManager) { let nc = ModalNavigationController() nc.setClearNavbar() nc.setWhiteStyle() let start = StartImportViewController(walletManager: walletManager) start.addCloseNavigationItem(tintColor: .white) start.navigationItem.title = S.Import.title let faqButton = UIButton.buildFaqButton(articleId: ArticleIds.importWallet) faqButton.tintColor = .white start.navigationItem.rightBarButtonItems = [UIBarButtonItem.negativePadding, UIBarButtonItem(customView: faqButton)] nc.viewControllers = [start] topViewController?.present(nc, animated: true, completion: nil) } //MARK: - Prompts func presentBiometricsSetting() { let biometricsSettings = BiometricsSettingsViewController(walletManager: walletManager) biometricsSettings.addCloseNavigationItem(tintColor: .white) let nc = ModalNavigationController(rootViewController: biometricsSettings) biometricsSettings.presentSpendingLimit = strongify(self) { myself in myself.pushBiometricsSpendingLimit(onNc: nc) } nc.setDefaultStyle() nc.isNavigationBarHidden = true nc.delegate = securityCenterNavigationDelegate topViewController?.present(nc, animated: true, completion: nil) } private func promptShareData() { let shareData = ShareDataViewController() let nc = ModalNavigationController(rootViewController: shareData) nc.setDefaultStyle() nc.isNavigationBarHidden = true nc.delegate = securityCenterNavigationDelegate shareData.addCloseNavigationItem() topViewController?.present(nc, animated: true, completion: nil) } func presentWritePaperKey() { guard let vc = topViewController else { return } presentWritePaperKey(fromViewController: vc) } func presentUpgradePin() { let updatePin = UpdatePinViewController(walletManager: walletManager, type: .update) let nc = ModalNavigationController(rootViewController: updatePin) nc.setDefaultStyle() nc.isNavigationBarHidden = true nc.delegate = securityCenterNavigationDelegate updatePin.addCloseNavigationItem() topViewController?.present(nc, animated: true, completion: nil) } private func handleFile(_ file: Data) { if let request = PaymentProtocolRequest(data: file) { if let topVC = topViewController as? ModalViewController { let attemptConfirmRequest: () -> Bool = { if let send = topVC.childViewController as? SendViewController { send.confirmProtocolRequest(protoReq: request) return true } return false } if !attemptConfirmRequest() { modalTransitionDelegate.reset() topVC.dismiss(animated: true, completion: { Store.perform(action: RootModalActions.Present(modal: .send(currency: Currencies.rvn))) DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { //This is a hack because present has no callback let _ = attemptConfirmRequest() }) }) } } } else if let ack = PaymentProtocolACK(data: file) { if let memo = ack.memo { let alert = UIAlertController(title: "", message: memo, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) } //TODO - handle payment type } else { let alert = UIAlertController(title: S.Alert.error, message: S.PaymentProtocol.Errors.corruptedDocument, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.ok, style: .cancel, handler: nil)) topViewController?.present(alert, animated: true, completion: nil) } } private func handlePaymentRequest(request: PaymentRequest) { self.currentRequest = request guard !Store.state.isLoginRequired else { presentModal(.send(currency: request.currency)); return } if let accountVC = topViewController as? AccountViewController { if accountVC.currency.matches(request.currency) { presentModal(.send(currency: request.currency)) } else { // switch currencies accountVC.navigationController?.popToRootViewController(animated: false) showAccountView(currency: request.currency, animated: false) presentModal(.send(currency: request.currency)) } } else if topViewController is HomeScreenViewController { showAccountView(currency: request.currency, animated: false) presentModal(.send(currency: request.currency)) } else { if let presented = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController { presented.dismiss(animated: true, completion: { self.showAccountView(currency: request.currency, animated: false) self.presentModal(.send(currency: request.currency)) }) } } } func showAccountView(currency: CurrencyDef, animated: Bool) { guard let nc = topViewController?.navigationController as? RootNavigationController, nc.viewControllers.count == 1 else { return } let accountViewController = AccountViewController(walletManager: walletManager) nc.pushViewController(accountViewController, animated: animated) } func pushAccountView(currency: CurrencyDef, animated: Bool, nc:UINavigationController) { let accountViewController = AccountViewController(walletManager: walletManager) nc.pushViewController(accountViewController, animated: animated) } private func handleScanQrURL() { guard !Store.state.isLoginRequired else { presentLoginScan(); return } if topViewController is AccountViewController || topViewController is LoginViewController { presentLoginScan() } else { if let presented = UIApplication.shared.keyWindow?.rootViewController?.presentedViewController { presented.dismiss(animated: true, completion: { self.presentLoginScan() }) } } } private func handleCopyAddresses(success: String?, error: String?) { let alert = UIAlertController(title: S.URLHandling.addressListAlertTitle, message: S.URLHandling.addressListAlertMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: S.URLHandling.copy, style: .default, handler: { [weak self] _ in guard let myself = self else { return } let verify = VerifyPinViewController(bodyText: S.URLHandling.addressListVerifyPrompt, pinLength: Store.state.pinLength, walletManager: myself.walletManager, success: { [weak self] pin in self?.copyAllAddressesToClipboard() Store.perform(action: Alert.Show(.addressesCopied)) if let success = success, let url = URL(string: success) { UIApplication.shared.open(url) } }) verify.transitioningDelegate = self?.verifyPinTransitionDelegate verify.modalPresentationStyle = .overFullScreen verify.modalPresentationCapturesStatusBarAppearance = true self?.topViewController?.present(verify, animated: true, completion: nil) })) topViewController?.present(alert, animated: true, completion: nil) } private func authenticateForBitId(prompt: String, callback: @escaping (BitIdAuthResult) -> Void) { if UserDefaults.isBiometricsEnabled { walletManager.authenticate(biometricsPrompt: prompt, completion: { result in switch result { case .success: return callback(.success) case .cancel: return callback(.cancelled) case .failure: self.verifyPinForBitId(prompt: prompt, callback: callback) case .fallback: self.verifyPinForBitId(prompt: prompt, callback: callback) } }) } else { self.verifyPinForBitId(prompt: prompt, callback: callback) } } private func verifyPinForBitId(prompt: String, callback: @escaping (BitIdAuthResult) -> Void) { let verify = VerifyPinViewController(bodyText: prompt, pinLength: Store.state.pinLength, walletManager: walletManager, success: { pin in callback(.success) }) verify.didCancel = { callback(.cancelled) } verify.transitioningDelegate = verifyPinTransitionDelegate verify.modalPresentationStyle = .overFullScreen verify.modalPresentationCapturesStatusBarAppearance = true topViewController?.present(verify, animated: true, completion: nil) } private func copyAllAddressesToClipboard() { guard let wallet = walletManager.wallet else { return } let addresses = wallet.allAddresses.filter({wallet.addressIsUsed($0)}) UIPasteboard.general.string = addresses.joined(separator: "\n") } var topViewController: UIViewController? { var viewController = window.rootViewController if let nc = viewController as? UINavigationController { viewController = nc.topViewController } while viewController?.presentedViewController != nil { viewController = viewController?.presentedViewController } return viewController } private func showNotReachable() { guard notReachableAlert == nil else { return } let alert = InAppAlert(message: S.Alert.noInternet, image: #imageLiteral(resourceName: "BrokenCloud")) notReachableAlert = alert let window = UIApplication.shared.keyWindow! let size = window.bounds.size window.addSubview(alert) let bottomConstraint = alert.bottomAnchor.constraint(equalTo: window.topAnchor, constant: 0.0) alert.constrain([ alert.constraint(.width, constant: size.width), alert.constraint(.height, constant: InAppAlert.height), alert.constraint(.leading, toView: window, constant: nil), bottomConstraint ]) window.layoutIfNeeded() alert.bottomConstraint = bottomConstraint alert.hide = { self.hideNotReachable() } UIView.spring(C.animationDuration, animations: { alert.bottomConstraint?.constant = InAppAlert.height window.layoutIfNeeded() }, completion: {_ in}) } private func hideNotReachable() { UIView.animate(withDuration: C.animationDuration, animations: { self.notReachableAlert?.bottomConstraint?.constant = 0.0 self.notReachableAlert?.superview?.layoutIfNeeded() }, completion: { _ in self.notReachableAlert?.removeFromSuperview() self.notReachableAlert = nil }) } private func showLightWeightAlert(message: String) { let alert = LightWeightAlert(message: message) let view = UIApplication.shared.keyWindow! view.addSubview(alert) alert.constrain([ alert.centerXAnchor.constraint(equalTo: view.centerXAnchor), alert.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) alert.background.effect = nil UIView.animate(withDuration: 0.6, animations: { alert.background.effect = alert.effect }, completion: { _ in UIView.animate(withDuration: 0.6, delay: 1.0, options: [], animations: { alert.background.effect = nil }, completion: { _ in alert.removeFromSuperview() }) }) } private func showEmailLogsModal() { self.messagePresenter.presenter = self.topViewController self.messagePresenter.presentEmailLogs() } } class SecurityCenterNavigationDelegate : NSObject, UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { guard let coordinator = navigationController.topViewController?.transitionCoordinator else { return } if coordinator.isInteractive { coordinator.notifyWhenInteractionChanges { context in //We only want to style the view controller if the //pop animation wasn't cancelled if !context.isCancelled { self.setStyle(navigationController: navigationController, viewController: viewController) } } } else { setStyle(navigationController: navigationController, viewController: viewController) } } func setStyle(navigationController: UINavigationController, viewController: UIViewController) { if viewController is SecurityCenterViewController { navigationController.isNavigationBarHidden = true } else { navigationController.isNavigationBarHidden = false } if viewController is BiometricsSettingsViewController { navigationController.setWhiteStyle() } else { navigationController.setDefaultStyle() } } }
51.104377
221
0.632346
fb6f0bfc7a762c860e8ca1ab869c5ac41ba9b1cc
452
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -emit-ir extension a{protocol P{}}class a<a{var f=a a{}func a:P&
45.2
79
0.743363
b9997142d33e29ff8d7522614df2319cdb3b6d8a
1,346
// // SupportUtilsGenerator.swift // LucidCodeGen // // Created by Stephane Magne on 9/18/19. // import Meta import PathKit import LucidCodeGenCore public final class SupportUtilsGenerator: Generator { public let name = "support utils" private let filename = "SupportUtils.swift" public let outputDirectory = OutputDirectory.support public let targetName = TargetName.app private let parameters: GeneratorParameters public init(_ parameters: GeneratorParameters) { self.parameters = parameters } public func generate(for element: Description, in directory: Path, organizationName: String) throws -> SwiftFile? { guard element == .all else { return nil } let header = MetaHeader(filename: filename, organizationName: organizationName) let localStoreCleanup = MetaSupportUtils( descriptions: parameters.currentDescriptions, reactiveKit: parameters.reactiveKit, moduleName: parameters.currentDescriptions.targets.app.moduleName ) return Meta.File(name: filename) .with(header: header.meta) .adding(import: .lucid) .adding(import: parameters.reactiveKit ? .reactiveKit : .combine) .with(body: [try localStoreCleanup.meta()]) .swiftFile(in: directory) } }
28.638298
119
0.682764
762ddd7476e11f641b57bb1e9b1a067ff6d12dfd
11,632
// // MockManager.swift // Cuckoo // // Created by Filip Dolnik on 29.05.16. // Copyright © 2016 Brightify. All rights reserved. // import XCTest #if !swift(>=4.1) private extension Array { func compactMap<O>(_ transform: (Element) -> O?) -> [O] { return self.flatMap(transform) } } #endif public class MockManager { public static var fail: ((message: String, sourceLocation: SourceLocation)) -> () = { (arg) in let (message, sourceLocation) = arg; XCTFail(message, file: sourceLocation.file, line: sourceLocation.line) } private var stubs: [Stub] = [] private var stubCalls: [StubCall] = [] private var unverifiedStubCallsIndexes: [Int] = [] // TODO Add either enum or OptionSet for these behavior modifiers and add proper validation private var isSuperclassSpyEnabled = false private var isDefaultImplementationEnabled = false private let hasParent: Bool public init(hasParent: Bool) { self.hasParent = hasParent } private func callInternal<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: () -> OUT, defaultCall: () -> OUT) -> OUT { return callRethrowsInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } private func callRethrowsInternal<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: () throws -> OUT, defaultCall: () throws -> OUT) rethrows -> OUT { let stubCall = ConcreteStubCall(method: method, parameters: escapingParameters) stubCalls.append(stubCall) unverifiedStubCallsIndexes.append(stubCalls.count - 1) if let stub = (stubs.filter { $0.method == method }.compactMap { $0 as? ConcreteStub<IN, OUT> }.filter { $0.parameterMatchers.reduce(true) { $0 && $1.matches(parameters) } }.first) { if let action = stub.actions.first { if stub.actions.count > 1 { // Bug in Swift, this expression resolves as uncalled function _ = stub.actions.removeFirst() } switch action { case .callImplementation(let implementation): return try DispatchQueue(label: "No-care?").sync(execute: { return try implementation(parameters) }) case .returnValue(let value): return value case .throwError(let error): return try DispatchQueue(label: "No-care?").sync(execute: { throw error }) case .callRealImplementation where hasParent: return try superclassCall() default: failAndCrash("No real implementation found for method `\(method)`. This is probably caused by stubbed object being a mock of a protocol.") } } else { failAndCrash("Stubbing of method `\(method)` using parameters \(parameters) wasn't finished (missing thenReturn()).") } } else if isSuperclassSpyEnabled { return try superclassCall() } else if isDefaultImplementationEnabled { return try defaultCall() } else { failAndCrash("No stub for method `\(method)` using parameters \(parameters).") } } private func callThrowsInternal<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: () throws -> OUT, defaultCall: () throws -> OUT) throws -> OUT { let stubCall = ConcreteStubCall(method: method, parameters: escapingParameters) stubCalls.append(stubCall) unverifiedStubCallsIndexes.append(stubCalls.count - 1) if let stub = (stubs.filter { $0.method == method }.compactMap { $0 as? ConcreteStub<IN, OUT> }.filter { $0.parameterMatchers.reduce(true) { $0 && $1.matches(parameters) } }.first) { if let action = stub.actions.first { if stub.actions.count > 1 { // Bug in Swift, this expression resolves as uncalled function _ = stub.actions.removeFirst() } switch action { case .callImplementation(let implementation): return try implementation(parameters) case .returnValue(let value): return value case .throwError(let error): throw error case .callRealImplementation where hasParent: return try superclassCall() default: failAndCrash("No real implementation found for method `\(method)`. This is probably caused by stubbed object being a mock of a protocol.") } } else { failAndCrash("Stubbing of method `\(method)` using parameters \(parameters) wasn't finished (missing thenReturn()).") } } else if isSuperclassSpyEnabled { return try superclassCall() } else if isDefaultImplementationEnabled { return try defaultCall() } else { failAndCrash("No stub for method `\(method)` using parameters \(parameters).") } } public func createStub<MOCK: ClassMock, IN, OUT>(for _: MOCK.Type, method: String, parameterMatchers: [ParameterMatcher<IN>]) -> ClassConcreteStub<IN, OUT> { let stub = ClassConcreteStub<IN, OUT>(method: method, parameterMatchers: parameterMatchers) stubs.insert(stub, at: 0) return stub } public func createStub<MOCK: ProtocolMock, IN, OUT>(for _: MOCK.Type, method: String, parameterMatchers: [ParameterMatcher<IN>]) -> ConcreteStub<IN, OUT> { let stub = ConcreteStub<IN, OUT>(method: method, parameterMatchers: parameterMatchers) stubs.insert(stub, at: 0) return stub } public func verify<IN, OUT>(_ method: String, callMatcher: CallMatcher, parameterMatchers: [ParameterMatcher<IN>], sourceLocation: SourceLocation) -> __DoNotUse<IN, OUT> { var calls: [StubCall] = [] var indexesToRemove: [Int] = [] for (i, stubCall) in stubCalls.enumerated() { if let stubCall = stubCall as? ConcreteStubCall<IN> , (parameterMatchers.reduce(stubCall.method == method) { $0 && $1.matches(stubCall.parameters) }) { calls.append(stubCall) indexesToRemove.append(i) } } unverifiedStubCallsIndexes = unverifiedStubCallsIndexes.filter { !indexesToRemove.contains($0) } if callMatcher.matches(calls) == false { let message = "Wanted \(callMatcher.name) but \(calls.count == 0 ? "not invoked" : "invoked \(calls.count) times")." MockManager.fail((message, sourceLocation)) } return __DoNotUse() } public func enableSuperclassSpy() { guard stubCalls.isEmpty else { failAndCrash("Enabling superclass spy is not allowed after stubbing! Please do that right after creating the mock.") } guard !isDefaultImplementationEnabled else { failAndCrash("Enabling superclass spy is not allowed with the default stub implementation enabled.") } isSuperclassSpyEnabled = true } public func enableDefaultStubImplementation() { guard stubCalls.isEmpty else { failAndCrash("Enabling default stub implementation is not allowed after stubbing! Please do that right after creating the mock.") } guard !isSuperclassSpyEnabled else { failAndCrash("Enabling default stub implementation is not allowed with superclass spy enabled.") } isDefaultImplementationEnabled = true } func reset() { clearStubs() clearInvocations() } func clearStubs() { stubs.removeAll() } func clearInvocations() { stubCalls.removeAll() unverifiedStubCallsIndexes.removeAll() } func verifyNoMoreInteractions(_ sourceLocation: SourceLocation) { if unverifiedStubCallsIndexes.isEmpty == false { let unverifiedCalls = unverifiedStubCallsIndexes.map { stubCalls[$0] }.map { call in if let bracketIndex = call.method.range(of: "(")?.lowerBound { let name = call.method[..<bracketIndex] return name + call.parametersAsString } else { if call.method.hasSuffix("#set") { return call.method + call.parametersAsString } else { return call.method } } }.enumerated().map { "\($0 + 1). " + $1 }.joined(separator: "\n") let message = "No more interactions wanted but some found:\n" MockManager.fail((message + unverifiedCalls, sourceLocation)) } } private func failAndCrash(_ message: String, file: StaticString = #file, line: UInt = #line) -> Never { MockManager.fail((message, (file, line))) #if _runtime(_ObjC) NSException(name: .internalInconsistencyException, reason:message, userInfo: nil).raise() #endif fatalError(message) } } extension MockManager { public static func callOrCrash<T, OUT>(_ value: T?, call: (T) throws -> OUT) rethrows -> OUT { guard let value = value else { return crashOnProtocolSuperclassCall() } return try call(value) } public static func crashOnProtocolSuperclassCall<OUT>() -> OUT { fatalError("This should never get called. If it does, please report an issue to Cuckoo repository.") } } extension MockManager { public func getter<T>(_ property: String, superclassCall: @autoclosure () -> T, defaultCall: @autoclosure () -> T) -> T { return call(getterName(property), parameters: Void(), escapingParameters: Void(), superclassCall: superclassCall(), defaultCall: defaultCall()) } public func setter<T>(_ property: String, value: T, superclassCall: @autoclosure () -> Void, defaultCall: @autoclosure () -> Void) { return call(setterName(property), parameters: value, escapingParameters: value, superclassCall: superclassCall(), defaultCall: defaultCall()) } } extension MockManager { public func call<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: @autoclosure () -> OUT, defaultCall: @autoclosure () -> OUT) -> OUT { return callInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } } extension MockManager { public func callThrows<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: @autoclosure () throws -> OUT, defaultCall: @autoclosure () throws -> OUT) throws -> OUT { return try callThrowsInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } } extension MockManager { public func callRethrows<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: @autoclosure () throws -> OUT, defaultCall: @autoclosure () throws -> OUT) rethrows -> OUT { return try callRethrowsInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } }
47.284553
208
0.626891