label
int64
0
1
text
stringlengths
0
2.8M
0
import Foundation import SwiftTalkServerLib import Base while true { do { try run() } catch { log(error) } }
0
import XCTest import LDSwiftEventSourceTests var tests = [XCTestCaseEntry]() tests += LDSwiftEventSourceTests.__allTests() XCTMain(tests)
0
// // TipSliderTableViewCell.swift // Splitz // // Created by Mit Amin on 5/25/21. // import UIKit class TipSliderTableViewCell: UITableViewCell { let identifier = "TipSliderTableViewCell" @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var tipSlider: UISlider! @IBOutlet weak var tipValueLabel: UILabel! var model = TipSliderCellViewModel() override func awakeFromNib() { super.awakeFromNib() configureTipSlider() configuretipValueLabel() titleLabel.text = model.title titleLabel.textColor = App.Colors.textColor tipValueLabel.textColor = App.Colors.accentColor } @IBAction func tipSliderValueDidChange(_ sender: UISlider) { model.sliderValue = Int(sender.value) updatetipValueLabel() } func updatetipValueLabel() { tipValueLabel.text = "\(Int(model.sliderValue)) %" } func configuretipValueLabel() { updatetipValueLabel() } func configureTipSlider() { tipSlider.minimumValue = 0 tipSlider.maximumValue = 100 tipSlider.value = Float(model.sliderValue) tipSlider.tintColor = App.Colors.accentColor } }
0
import UIKit import NaturalLanguage class ViewController: UIViewController { @IBOutlet var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() textView.layer.cornerRadius = 6 textView.layer.borderColor = UIColor.lightGray.cgColor textView.layer.borderWidth = 1 } @IBAction func analyze() { let wordCount = getWordCounts(from: textView.text) let model = SentimentPolarity() guard let prediction = try? model.prediction(input: wordCount) else { return } let alert = UIAlertController(title: nil, message: "Your text is rated: \(prediction.classLabel)", preferredStyle: .alert) let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil) alert.addAction(okayAction) present(alert, animated: true, completion: nil) } func getWordCounts(from string: String) -> [String: Double] { let tokenizer = NLTokenizer(unit: .word) tokenizer.string = string var wordCount = [String: Double]() tokenizer.enumerateTokens(in: string.startIndex..<string.endIndex) { range, attributes in let word = String(string[range]) wordCount[word] = (wordCount[word] ?? 0) + 1 return true } return wordCount } }
0
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(WorkoutDecodersTests.allTests), ] } #endif
1
struct B< {}
0
// // AppDelegate.swift // Swift_Bluetooth_Manager // // Created by Dmytro Chumakov on 17.08.2021. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var rootWindow: UIWindow! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { self.rootWindow = RootWindow.rootWindow return true } }
0
// // EventMonitor.swift // OnlySwitch // // Created by Jacklandrin on 2021/11/29. // import Cocoa class EventMonitor { private var monitor:Any? private var mask : NSEvent.EventTypeMask private let handler:(NSEvent?) -> Void init(mask:NSEvent.EventTypeMask, handler:@escaping (NSEvent?) -> Void) { self.mask = mask self.handler = handler } deinit { stop() } func start() { monitor = NSEvent.addGlobalMonitorForEvents(matching: mask,handler:handler) as! NSObject } func stop() { if monitor != nil { NSEvent.removeMonitor(monitor!) monitor = nil } } }
0
// // TouchIDAuthenticatorUtlity.swift // TouchIDAuthenticationDemo // // Created by Jayesh Kawli on 7/31/17. // Copyright © 2017 Jayesh Kawli. All rights reserved. // import LocalAuthentication let defaultUserName = "[email protected]" let defaultPassword = "password" let lastSeenOrdersTimestampKey = "lastSeenOrdersTimestampKey" let touchIDAuthenticationtimeout = 15 protocol AlertDisplayable { func showAlert() func authneticationSuccssful() } class TouchIDAuthenticatorUtlity { let presenter: AlertDisplayable init(presenter: AlertDisplayable) { self.presenter = presenter } func authenticateUser() { if !isAuthenticationRequired() { self.presenter.authneticationSuccssful() return } let context = LAContext() var error: NSError? let reasonString = "Authentication is needed to access orders" if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success, evalPolicyError) in if success { self.presenter.authneticationSuccssful() } else { if let error = evalPolicyError as NSError? { switch error.code { case LAError.systemCancel.rawValue: print("Authentication was cancelled by the system") case LAError.userCancel.rawValue: print("Authentication was cancelled by the user") case LAError.userFallback.rawValue: print("User selected to enter custom password") self.presenter.showAlert() default: print("Authentication failed") self.presenter.showAlert() } } } }) } else { switch error!.code { case LAError.touchIDNotEnrolled.rawValue: print("TouchID is not enrolled") case LAError.passcodeNotSet.rawValue: print("A passcode has not been set") default: print("TouchID not available") } self.presenter.showAlert() } } func isAuthenticationRequired() -> Bool { let lastSeenTimestamp = (UserDefaults.standard.value(forKey: lastSeenOrdersTimestampKey) as? TimeInterval) ?? 0.0 let currentTimestamp = Date().timeIntervalSince1970 UserDefaults.standard.setValue(currentTimestamp, forKey: lastSeenOrdersTimestampKey) print("Current timestamp \(currentTimestamp)") print("Last seen timestamp \(lastSeenTimestamp)") return currentTimestamp - lastSeenTimestamp > 15 } }
0
// RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-concurrency // REQUIRES: concurrency @available(SwiftStdlib 5.1, *) actor A { func f() { } // expected-note 5{{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}} } @available(SwiftStdlib 5.1, *) extension Actor { func g() { } } @MainActor func mainActorFn() {} @available(SwiftStdlib 5.1, *) func testA<T: Actor>( a: isolated A, // expected-note{{previous 'isolated' parameter 'a'}} b: isolated T, // expected-warning{{cannot have more than one 'isolated' parameter; this is an error in Swift 6}} c: isolated Int // expected-error {{'isolated' parameter has non-actor type 'Int'}} ) { a.f() a.g() b.g() } actor Other { func inc() {} func pass(_ f: @Sendable (Self) async -> Void) {} } actor Counter { func inc() {} func pass(_ f: @Sendable (Self) async -> Void) {} } @available(SwiftStdlib 5.1, *) // expected-note@+2 {{previous 'isolated' parameter 'a'}} // expected-warning@+1 {{cannot have more than one 'isolated' parameter; this is an error in Swift 6}} func testDoubleIsolatedParams(a: isolated Counter, b: isolated Other) async { a.inc() b.inc() } func taaaa() async { await Counter().pass { isoC in await Other().pass { isoO in await testDoubleIsolatedParams(a: isoC, b: isoO) } } } @available(SwiftStdlib 5.1, *) typealias Fn = (isolated A) -> Void @available(SwiftStdlib 5.1, *) func globalFunc(_ a: A) { } @available(SwiftStdlib 5.1, *) func globalFuncIsolated(_: isolated A) { // expected-note{{calls to global function 'globalFuncIsolated' from outside of its actor context are implicitly asynchronous}} let _: Int = globalFuncIsolated // expected-error{{cannot convert value of type '(isolated A) -> ()' to specified type 'Int'}} let _: (A) -> Void = globalFuncIsolated // expected-error{{cannot convert value of type '(isolated A) -> ()' to specified type '(A) -> Void'}} let _: Fn = globalFunc // okay } @available(SwiftStdlib 5.1, *) // expected-warning@+1 {{global function with 'isolated' parameter cannot have a global actor; this is an error in Swift 6}}{{1-12=}} @MainActor func testIsolatedParamCalls(a: isolated A, b: A) { globalFunc(a) globalFunc(b) globalFuncIsolated(a) globalFuncIsolated(b) // expected-error{{call to actor-isolated global function 'globalFuncIsolated' in a synchronous actor-isolated context}} } @available(SwiftStdlib 5.1, *) func testIsolatedParamCallsAsync(a: isolated A, b: A) async { globalFunc(a) globalFunc(b) globalFuncIsolated(a) globalFuncIsolated(b) // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1{{calls to global function 'globalFuncIsolated' from outside of its actor context are implicitly asynchronous}} await globalFuncIsolated(b) } @available(SwiftStdlib 5.1, *) func testIsolatedParamCaptures(a: isolated A) async { let _ = { @MainActor in a.f() // expected-error {{actor-isolated instance method 'f()' can not be referenced from the main actor}} } let _: @MainActor () -> () = { a.f() // expected-error {{actor-isolated instance method 'f()' can not be referenced from the main actor}} } let _ = { a.f() } let _ = { @Sendable in a.f() // expected-error {{actor-isolated instance method 'f()' can not be referenced from a Sendable closure}} } } actor MyActor { func hello() {} // expected-note {{calls to instance method 'hello()' from outside of its actor context are implicitly asynchronous}} } typealias MyFn = (isolated: Int) -> Void // expected-error {{function types cannot have argument labels; use '_' before 'isolated'}} typealias MyFnFixed = (_: isolated MyActor) -> Void func standalone(_: isolated MyActor) {} func check() { let _: MyFnFixed = standalone let _: MyFnFixed = { (_: isolated MyActor) in () } } @available(SwiftStdlib 5.1, *) protocol P { func f(isolated: MyActor) async func g(isolated x: MyActor) async func h(isolated MyActor: isolated MyActor) func i(isolated: isolated MyActor) func j(isolated: Int) -> Int func k(isolated y: Int) -> Int func l(isolated _: Int) -> Int func m(thing: isolated MyActor) } @available(SwiftStdlib 5.1, *) struct S: P { func f(isolated: MyActor) async { await isolated.hello() } func g(isolated x: MyActor) async { await x.hello() } func h(isolated MyActor: isolated MyActor) { i(isolated: MyActor) } func i(isolated: isolated MyActor) { isolated.hello() } func j(isolated: Int) -> Int { return isolated } func k(isolated y: Int) -> Int { return j(isolated: y) } func l(isolated _: Int) -> Int { return k(isolated: 0) } func m(thing: MyActor) { thing.hello() } // expected-error {{actor-isolated instance method 'hello()' can not be referenced from a non-isolated context}} } func checkConformer(_ s: S, _ p: any P, _ ma: MyActor) async { s.m(thing: ma) await p.m(thing: ma) } // Redeclaration checking actor TestActor { func test() { // expected-note{{'test()' previously declared here}} } nonisolated func test() { // expected-error{{invalid redeclaration of 'test()'}} } } func redecl(_: TestActor) { } // expected-note{{'redecl' previously declared here}} func redecl(_: isolated TestActor) { } // expected-error{{invalid redeclaration of 'redecl'}} func tuplify<Ts>(_ fn: (Ts) -> Void) {} // expected-note {{in call to function 'tuplify'}} @available(SwiftStdlib 5.1, *) func testTuplingIsolated( _ a: isolated A, // expected-note {{previous 'isolated' parameter 'a'}} _ b: isolated A // expected-warning {{cannot have more than one 'isolated' parameter; this is an error in Swift 6}} ) { tuplify(testTuplingIsolated) // expected-error@-1 {{generic parameter 'Ts' could not be inferred}} // expected-error@-2 {{cannot convert value of type '(isolated A, isolated A) -> ()' to expected argument type '(Ts) -> Void'}} } // Inference of "isolated" on closure parameters. @available(SwiftStdlib 5.1, *) func testIsolatedClosureInference(one: A, two: A) async { let _: (isolated A) -> Void = { $0.f() } let _: (isolated A) -> Void = { $0.f() } let _: (isolated A) -> Void = { a2 in a2.f() } let _: (isolated A) -> Void = { (a2: isolated A) in a2.f() } let f: (isolated A, isolated A) -> Void = // expected-warning {{function type cannot have more than one 'isolated' parameter; this is an error in Swift 6}} // expected-note@+2 {{previous 'isolated' parameter 'a1'}} // expected-warning@+1 {{cannot have more than one 'isolated' parameter; this is an error in Swift 6}} { (a1, a2) in a1.f() a2.f() } await f(one, two) let g: (isolated A, isolated A) -> Void = // expected-warning {{function type cannot have more than one 'isolated' parameter; this is an error in Swift 6}} // expected-note@+2 {{previous 'isolated' parameter '$0'}} // expected-warning@+1 {{cannot have more than one 'isolated' parameter; this is an error in Swift 6}} { $0.f() $1.f() } await g(one, two) } struct CheckIsolatedFunctionTypes { // expected-warning@+2 {{function type cannot have global actor and 'isolated' parameter; this is an error in Swift 6}} // expected-warning@+1 {{function type cannot have more than one 'isolated' parameter; this is an error in Swift 6}} func a(_ f: @MainActor @Sendable (isolated A, isolated A) -> ()) {} // expected-note@+2 {{calls to parameter 'callback' from outside of its actor context are implicitly asynchronous}} // expected-warning@+1 {{function type cannot have global actor and 'isolated' parameter; this is an error in Swift 6}} @MainActor func update<R>(_ callback: @Sendable @escaping @MainActor (isolated A) -> R) -> R { callback(A()) // expected-error {{call to actor-isolated parameter 'callback' in a synchronous main actor-isolated context}} } } @available(SwiftStdlib 5.1, *) func checkIsolatedAndGlobalClosures(_ a: A) { let _: @MainActor (isolated A) -> Void // expected-warning {{function type cannot have global actor and 'isolated' parameter; this is an error in Swift 6}} = { $0.f() mainActorFn() } let _: @MainActor (isolated A) -> Void // expected-warning {{function type cannot have global actor and 'isolated' parameter; this is an error in Swift 6}} = { @MainActor in // expected-warning {{closure with 'isolated' parameter '$0' cannot have a global actor; this is an error in Swift 6}}{{11-22=}} $0.f() mainActorFn() } let _ = { @MainActor (a: isolated A, // expected-warning {{closure with 'isolated' parameter 'a' cannot have a global actor; this is an error in Swift 6}}{{13-24=}} // expected-note@-1 {{previous 'isolated' parameter 'a'}} b: isolated A, // expected-warning {{cannot have more than one 'isolated' parameter; this is an error in Swift 6}} c: isolated A) async in a.f() mainActorFn() } } // "isolated" existential parameters. protocol P2: Actor { func m() } @available(SwiftStdlib 5.1, *) func testExistentialIsolated(a: isolated P2, b: P2) async { a.m() await b.m() b.m() // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1{{calls to instance method 'm()' from outside of its actor context are implicitly asynchronous}} } // "isolated" parameters of closures make the closure itself isolated. extension TestActor { func isolatedMethod() { } // expected-note@-1{{calls to instance method 'isolatedMethod()' from outside of its actor context are implicitly asynchronous}} // expected-warning@+1 {{instance method with 'isolated' parameter cannot be 'nonisolated'; this is an error in Swift 6}}{{3-15=}} nonisolated func isolatedToParameter(_ other: isolated TestActor) { isolatedMethod() // expected-error@-1{{actor-isolated instance method 'isolatedMethod()' can not be referenced on a non-isolated actor instance}} other.isolatedMethod() } } @available(SwiftStdlib 5.1, *) func isolatedClosures() { let _: (isolated TestActor) -> Void = { (ta: isolated TestActor) in ta.isolatedMethod() // okay, isolated to ta _ = { ta.isolatedMethod() // okay, isolated to ta } } } // expected-warning@+2 {{global function with 'isolated' parameter cannot be 'nonisolated'; this is an error in Swift 6}}{{12-24=}} // expected-warning@+1 {{global function with 'isolated' parameter cannot have a global actor; this is an error in Swift 6}}{{1-12=}} @MainActor nonisolated func allOfEm(_ a: isolated A) { a.f() } @MainActor class MAClass { // expected-note@+2 {{previous 'isolated' parameter 'a'}} // expected-warning@+1 {{cannot have more than one 'isolated' parameter; this is an error in Swift 6}} init(_ a: isolated A, _ b: isolated A) { // FIXME: wrong isolation. should be isolated to `a` only! a.f() b.f() } // expected-note@+3 {{previous 'isolated' parameter 'a'}} // expected-warning@+2 {{cannot have more than one 'isolated' parameter; this is an error in Swift 6}} // expected-warning@+1 {{subscript with 'isolated' parameter cannot be 'nonisolated'; this is an error in Swift 6}}{{3-15=}} nonisolated subscript(_ a: isolated A, _ b: isolated A) -> Int { // FIXME: wrong isolation. should be isolated to `a`. a.f() // expected-error {{actor-isolated instance method 'f()' can not be referenced on a non-isolated actor instance}} b.f() // expected-error {{actor-isolated instance method 'f()' can not be referenced on a non-isolated actor instance}} return 0 } // expected-warning@+1 {{instance method with 'isolated' parameter cannot be 'nonisolated'; this is an error in Swift 6}}{{3-15=}} nonisolated func millionDollars(_ a: isolated A) { a.f() } }
0
import BigInt typealias BalanceInfoModuleCreationResult = (view: BalanceInfoViewInput, input: BalanceInfoModuleInput) protocol BalanceInfoViewInput: ControllerBackedProtocol { func didReceiveViewModel(_ viewModel: BalanceInfoViewModel) } protocol BalanceInfoViewOutput: AnyObject { func didLoad(view: BalanceInfoViewInput) func didTapInfoButton() } protocol BalanceInfoInteractorInput: AnyObject { func setup(with output: BalanceInfoInteractorOutput, for type: BalanceInfoType) func fetchBalanceInfo(for type: BalanceInfoType) } protocol BalanceInfoInteractorOutput: AnyObject { func didReceiveWalletBalancesResult(_ result: WalletBalancesResult) func didReceiveMinimumBalance(result: Result<BigUInt, Error>) func didReceiveBalanceLocks(result: Result<BalanceLocks?, Error>) } protocol BalanceInfoRouterInput: AnyObject { func presentLockedInfo( from view: ControllerBackedProtocol?, balanceContext: BalanceContext, info: AssetBalanceDisplayInfo, currency: Currency ) } protocol BalanceInfoModuleInput: AnyObject { func replace(infoType: BalanceInfoType) } protocol BalanceInfoModuleOutput: AnyObject {}
0
// // File.swift // Dark // // Created by surendra kumar on 11/12/17. // Copyright © 2017 weza. All rights reserved. // import Foundation import FirebaseAuth import Firebase class UserWithCr { private static let _sharedInstanse = UserWithCr() static var sharedInstanse : UserWithCr{ return _sharedInstanse } func SignIn(with credentials : AuthCredential, completion : @escaping (User?,Error?)->()){ Auth.auth().signIn(with: credentials, completion: { (user, error) in guard error == nil else { completion(user,error) return} let uid = Auth.auth().currentUser?.uid guard uid != nil else { completion(user,error) return} completion(user,error) }) } func isUserExist(withUID id : String , completion: @escaping (Bool)->()){ REF_USER.child(id).observeSingleEvent(of: .value) { snapshot in if snapshot.exists(){ completion(true) //self.performSegueTomainPage() }else{ //self.requestFacebookGraphAPI() completion(false) } } } }
0
/// Converts a input value into an output value using a given converter. Throws if the converter returns nil (or throws). /// - Parameters: /// - input: The input value to convert. /// - converter: The converter to use for the conversion. /// - error: The error to throw in case `converter` returns nil. /// - Returns: The output of the converter. /// - Throws: `error` in case the `converter` returns nil or any error thrown by `converter`. @inlinable func _convert<Input, Output, Error>(_ input: Input, using converter: (Input) throws -> Output?, failingWith error: @autoclosure () -> Error) throws -> Output where Error: Swift.Error { guard let converted = try converter(input) else { throw error() } return converted } extension RawRepresentable where RawValue: LosslessStringConvertible { /// Creates an instance of self from the description of the `RawValue`. Returns nil if nil is returned by `RawValue.init(_:)` /// - Parameter rawValueDescription: The description of the `RawValue` to use to try to create an instance. @usableFromInline init?(rawValueDescription: String) { guard let rawValue = RawValue(rawValueDescription) else { return nil } self.init(rawValue: rawValue) } } extension Dictionary where Key == XMLElement.Attributes.Key.RawValue, Value == XMLElement.Attributes.Content.RawValue { /// Converts the receiver to the ``XMLElement/Attributes`` type. @inlinable var asAttributes: XMLElement.Attributes { .init(storage: .init(uniqueKeysWithValues: lazy.map { (.init(rawValue: $0.key), .init(rawValue: $0.value)) })) } } extension RandomAccessCollection { /// Returns the last safe subscript index. @inlinable var indexBeforeEndIndex: Index { index(before: endIndex) } }
0
// // ViewController.swift // MultiCompartmentModel // // Created by Luiz Rodrigo Martins Barbosa on 12.07.17. // Copyright © 2017 Luiz Rodrigo Martins Barbosa. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
0
import libc import MediaType import Foundation import Socks public let VERSION = "0.11" public class Application { /** The router driver is responsible for returning registered `Route` handlers for a given request. */ public let router: RouterDriver /** The server that will accept requesting connections and return the desired response. */ public let server: ServerDriver.Type /** The session driver is responsible for storing and reading values written to the users session. */ public let session: SessionDriver /** Provides access to config settings. */ public let config: Config /** Provides access to config settings. */ public let localization: Localization /** Provides access to the underlying `HashDriver`. */ public let hash: Hash /** The base host to serve for a given application. Set through Config Command Line Argument: `--config:app.host=127.0.0.1` Config: Set "host" key in app.json file */ public let host: String /** The port the application should listen to. Set through Config Command Line Argument: `--config:app.port=8080` Config: Set "port" key in app.json file */ public let port: Int /** The work directory of your application is the directory in which your Resources, Public, etc folders are stored. This is normally `./` if you are running Vapor using `.build/xxx/App` */ public let workDir: String /** `Middleware` will be applied in the order it is set in this array. Make sure to append your custom `Middleware` if you don't want to overwrite default behavior. */ public var globalMiddleware: [Middleware] /** Available Commands to use when starting the application. */ public var commands: [Command.Type] /** Send output and receive input from the console using the underlying `ConsoleDriver`. */ public let console: Console /** Resources directory relative to workDir */ public var resourcesDir: String { return workDir + "Resources/" } /** The arguments passed to the application. */ public let arguments: [String] var routes: [Route] /** Initialize the Application. */ public init( workDir: String? = nil, config: Config? = nil, localization: Localization? = nil, hash: HashDriver? = nil, console: ConsoleDriver? = nil, server: ServerDriver.Type? = nil, router: RouterDriver? = nil, session: SessionDriver? = nil, providers: [Provider] = [], arguments: [String]? = nil ) { var serverProvided: ServerDriver.Type? = server var routerProvided: RouterDriver? = router var sessionProvided: SessionDriver? = session var hashProvided: HashDriver? = hash var consoleProvided: ConsoleDriver? = console for provider in providers { serverProvided = provider.server ?? serverProvided routerProvided = provider.router ?? routerProvided sessionProvided = provider.session ?? sessionProvided hashProvided = provider.hash ?? hashProvided consoleProvided = provider.console ?? consoleProvided } let arguments = arguments ?? NSProcessInfo.processInfo().arguments self.arguments = arguments let workDir = workDir ?? arguments.value(for: "workdir") ?? arguments.value(for: "workDir") ?? "./" self.workDir = workDir.finish("/") let localization = localization ?? Localization(workingDirectory: workDir) self.localization = localization let config = config ?? Config(workingDirectory: workDir, arguments: arguments) self.config = config let host = config["app", "host"].string ?? "0.0.0.0" let port = config["app", "port"].int ?? 8080 self.host = host self.port = port let key = config["app", "key"].string let hash = Hash(key: key, driver: hashProvided) self.hash = hash let session = sessionProvided ?? MemorySessionDriver(hash: hash) self.session = session self.globalMiddleware = [ CookiesMiddleware(), JSONMiddleware(), FormURLEncodedMiddleware(), MultipartMiddleware(), ContentMiddleware(), AbortMiddleware(), ValidationMiddleware(), SessionMiddleware(session: session) ] self.router = routerProvided ?? BranchRouter() self.server = serverProvided ?? StreamServer< SynchronousTCPServer, HTTPParser, HTTPSerializer >.self routes = [] commands = [] let console = Console(driver: consoleProvided ?? Terminal()) self.console = console Log.driver = ConsoleLogger(console: console) commands.append(Help.self) commands.append(Serve.self) restrictLogging(for: config.environment) for provider in providers { provider.boot(with: self) } } private func restrictLogging(for environment: Environment) { guard config.environment == .production else { return } Log.info("Production environment detected, disabling information logs.") Log.enabledLevels = [.error, .fatal] } } extension Application { enum ExecutionError: ErrorProtocol { case insufficientArguments, noCommandFound } /** Starts console */ @noreturn public func start() { do { try execute() exit(0) } catch let error as ExecutionError { switch error { case .insufficientArguments: console.output("Insufficient arguments.", style: .error) case .noCommandFound: console.output("Command not recognized. Run 'help' for a list of available commands.", style: .error) } } catch let error as CommandError { switch error { case .insufficientArguments: console.output("Insufficient arguments.", style: .error) case .invalidArgument(let name): console.output("Invalid argument name '\(name)'.", style: .error) case .custom(let error): console.output(error) } } catch { console.output("Error: \(error)", style: .error) } exit(1) } func execute() throws { // options prefixed w/ `--` are accessible through `app.config["app", "argument"]` var iterator = self.arguments.filter { item in return !item.hasPrefix("--") }.makeIterator() _ = iterator.next() // pop location arg let commandId: String if let next = iterator.next() { commandId = next } else { commandId = "serve" console.output("No command supplied, defaulting to 'serve'.", style: .warning) } let arguments = Array(iterator) for commandType in commands { if commandType.id == commandId { let command = commandType.init(app: self) let requiredArguments = command.dynamicType.signature.filter { signature in return signature is Argument } if arguments.count < requiredArguments.count { let signature = command.dynamicType.signature() console.output(signature) throw ExecutionError.insufficientArguments } try command.run() return } } throw ExecutionError.noCommandFound } } extension Sequence where Iterator.Element == String { func value(for string: String) -> String? { for item in self { let search = "--\(string)=" if item.hasPrefix(search) { var item = item item.replace(string: search, with: "") return item } } return nil } } extension Application { internal func serve() { do { Log.info("Server starting at \(host):\(port)") // noreturn let server = try self.server.init(host: host, port: port, responder: self) try server.start() } catch { Log.error("Server start error: \(error)") } } } extension Application { func checkFileSystem(for request: Request) -> Request.Handler? { // Check in file system let filePath = self.workDir + "Public" + (request.uri.path ?? "") guard FileManager.fileAtPath(filePath).exists else { return nil } // File exists if let fileBody = try? FileManager.readBytesFromFile(filePath) { return Request.Handler { _ in var headers: Response.Headers = [:] if let fileExtension = filePath.components(separatedBy: ".").last, let type = mediaType(forFileExtension: fileExtension) { headers["Content-Type"] = type.description } return Response(status: .ok, headers: headers, body: Data(fileBody)) } } else { return Request.Handler { _ in Log.warning("Could not open file, returning 404") return Response(status: .notFound, text: "Page not found") } } } } extension Application { public func add(_ middleware: Middleware...) { middleware.forEach { globalMiddleware.append($0) } } public func add(_ middleware: [Middleware]) { middleware.forEach { globalMiddleware.append($0) } } } extension Application: Responder { /** Returns a response to the given request - parameter request: received request - throws: error if something fails in finding response - returns: response if possible */ public func respond(to request: Request) throws -> Response { Log.info("\(request.method) \(request.uri.path ?? "/")") var responder: Responder var request = request /* The HEAD method is identical to GET. https://tools.ietf.org/html/rfc2616#section-9.4 */ let originalMethod = request.method if case .head = request.method { request.method = .get } // Check in routes if let (parameters, routerHandler) = router.route(request) { request.parameters = parameters responder = routerHandler } else if let fileHander = self.checkFileSystem(for: request) { responder = fileHander } else { // Default not found handler responder = Request.Handler { _ in let normal: [Request.Method] = [.get, .post, .put, .patch, .delete] if normal.contains(request.method) { return Response(status: .notFound, text: "Page not found") } else if case .options = request.method { return Response(status: .ok, headers: [ "Allow": "OPTIONS" ], data: []) } else { return Response(status: .notImplemented, data: []) } } } // Loop through middlewares in order for middleware in self.globalMiddleware.reversed() { responder = middleware.chain(to: responder) } var response: Response do { response = try responder.respond(to: request) if response.headers["Content-Type"] == nil { Log.warning("Response had no 'Content-Type' header.") } } catch { var error = "Server Error: \(error)" if config.environment == .production { error = "Something went wrong" } response = Response(error: error) } response.headers["Date"] = Response.date response.headers["Server"] = "Vapor \(Vapor.VERSION)" /** The server MUST NOT return a message-body in the response for HEAD. https://tools.ietf.org/html/rfc2616#section-9.4 */ if case .head = originalMethod { response.body = .buffer([]) } return response } }
0
// // NetworkErrorTests.swift // FramesIosTests // // Created by Daven.Gomes on 02/12/2020. // Copyright © 2020 Checkout. All rights reserved. // import XCTest @testable import Frames final class NetworkErrorTests: XCTestCase { func test_init_allValuesExist_checkoutErrorReturned() { let responseJSON = makeResponseJSON( requestID: "stubRequestID", errorType: "stubErrorType", errorCodes: ["stubErrorCode1", "stubErrorCode2"] ) do { let data = try JSONSerialization.data(withJSONObject: responseJSON, options: .prettyPrinted) let snakeCaseDecoder = JSONDecoder() snakeCaseDecoder.keyDecodingStrategy = .convertFromSnakeCase let result = try snakeCaseDecoder.decode(NetworkError.self, from: data) guard case .checkout(let requestId, let errorType, let errorCodes) = result else { return XCTFail("Unexpected NetworkError type.") } XCTAssertEqual(requestId, "stubRequestID") XCTAssertEqual(errorType, "stubErrorType") XCTAssertEqual(errorCodes, ["stubErrorCode1", "stubErrorCode2"]) } catch { XCTFail(error.localizedDescription) } } func test_init_requestIDNil_returnUnknown() { let responseJSON = makeResponseJSON( requestID: nil, errorType: "stubErrorType", errorCodes: ["stubErrorCode1", "stubErrorCode2"] ) do { let data = try JSONSerialization.data(withJSONObject: responseJSON, options: .prettyPrinted) let result = try JSONDecoder().decode(NetworkError.self, from: data) guard case .unknown = result else { return XCTFail("Unexpected NetworkError type.") } } catch { XCTFail(error.localizedDescription) } } func test_init_errorTypeNil_returnUnknown() { let responseJSON = makeResponseJSON( requestID: "stubRequestID", errorType: nil, errorCodes: ["stubErrorCode1", "stubErrorCode2"] ) do { let data = try JSONSerialization.data(withJSONObject: responseJSON, options: .prettyPrinted) let result = try JSONDecoder().decode(NetworkError.self, from: data) guard case .unknown = result else { return XCTFail("Unexpected NetworkError type.") } } catch { XCTFail(error.localizedDescription) } } func test_init_errorTypeErrorCodes_returnUnknown() { let responseJSON = makeResponseJSON( requestID: "stubRequestID", errorType: "stubErrorType", errorCodes: nil ) do { let data = try JSONSerialization.data(withJSONObject: responseJSON, options: .prettyPrinted) let result = try JSONDecoder().decode(NetworkError.self, from: data) guard case .unknown = result else { return XCTFail("Unexpected NetworkError type.") } } catch { XCTFail(error.localizedDescription) } } private func makeResponseJSON(requestID: String? = nil, errorType: String? = nil, errorCodes: [String]? = nil) -> [String: Any?] { return ["request_id": requestID, "error_type": errorType, "error_codes": errorCodes] } }
0
// // Deli.swift // ArrayChallengeDeuce2 // // Created by Jim Campagno on 9/17/16. // Copyright © 2016 Flatiron School. All rights reserved. // class Deli { var line: [String] = [] // 1 func addNameToLine(name: String) -> String { switch name { case "Billy Crystal", "Meg Ryan": line.insert(name, at: 0) return "Welcome \(name)! You can sit wherever you like." default: if line.isEmpty { line.append(name) return "Welcome \(name), you're first in line!" } else { line.append(name) return "Welcome \(name), you're number \(line.count) in line." } } } // 2 func nowServing() -> String { if line.isEmpty { return "There is no one to be served." } else { var currentCustomer = line[0] line.remove(at: 0) return "Now serving \(currentCustomer)!" } } // 3 func lineDescription() -> String { if line.isEmpty { return "The line is currently empty." } else { print("The line is:") for (position, name) in line.enumerated() { print("\n \(position+1). \(name)") } return "The line is:\n1. Rob\n2. Catherine\n3. Paul\n4. Dom" } } }
0
// // HelloController.swift // App // // Created by WeiRuJian on 2020/3/24. // import Vapor import Crypto final class HelloController { func greet(_ req: Request) throws -> User { return User(name: "Choshim丶Wy", email: "[email protected]", passwordHash: "12346") } }
0
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. #if compiler(>=5.5) && canImport(_Concurrency) import SotoCore @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) extension SagemakerEdge { // MARK: Async API Calls /// Use to check if a device is registered with SageMaker Edge Manager. public func getDeviceRegistration(_ input: GetDeviceRegistrationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> GetDeviceRegistrationResult { return try await self.client.execute(operation: "GetDeviceRegistration", path: "/GetDeviceRegistration", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Use to get the current status of devices registered on SageMaker Edge Manager. public func sendHeartbeat(_ input: SendHeartbeatRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws { return try await self.client.execute(operation: "SendHeartbeat", path: "/SendHeartbeat", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } #endif // compiler(>=5.5) && canImport(_Concurrency)
0
import Argo import Ogra /// A content block type. public enum BlockType: String { case Audio = "audio" case Article = "article" case Code = "code" case CTA = "cta" case H1 = "h1" case H2 = "h2" case H3 = "h3" case H4 = "h4" case H5 = "h5" case H6 = "h6" case Image = "image" case Location = "location" case Quote = "quote" case Text = "text" case Video = "video" } // MARK: - Decodable extension BlockType: Decodable {} // MARK: - Encodable extension BlockType: Encodable {}
0
// // RestClient+Article.swift // SwiftSeedProject // // Created by Brian Sztamfater on 21/4/17. // Copyright © 2017 Making Sense. All rights reserved. // import Foundation import SwiftyJSON extension RestClient { func getArticles(source: Source, sortBy: String? = nil, completion: @escaping (DataResult<[Article]>) -> Void) { self.execute(target: NewsApiTarget.GetArticles(source: source, sortBy: sortBy), completion: completion) { [weak self] json in guard let strongSelf = self else { return nil } let articles = json["articles"].arrayValue.map { (json: JSON) -> Article in let article = strongSelf.persistence.add(attributes: nil, entityName: Source.EntityName) as! Article article.updateWithJSON(json: json) return article } return articles } } }
0
import UIKit class IndiaWorldCupLooserViewController: UIViewController { @IBOutlet weak var toggle: UISwitch! }
1
// RUN: not %target-swift-frontend %s -typecheck class b<T where H:a{class c{func S{{}struct D{var:{struct I{{}var b=c}}}b D{
0
// // test_projectUITests.swift // test-projectUITests // // Created by Chris Bishop on 2016-01-11. // Copyright © 2016 Chris Bishop. All rights reserved. // import XCTest class test_projectUITests: 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. } }
0
// // ViewController.swift // TweetMoodWithCoreML // // Created by Douglas Barreto on 17/09/17. // Copyright © 2017 Douglas. All rights reserved. // import UIKit import TwitterKit final class ViewController: UIViewController { @IBOutlet private weak var tableView: UITableView! let twitterGateway = TwitterGateway() let userMoodService = UserMoodService() var tweets: [TWTRTweet] = [] { didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() setupTableView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) twitterGateway.startTwitterSession(onComplete: { self.fetchData() }) } private func fetchData() { twitterGateway.getTweets(onComplete: { (tweets) in self.tweets = tweets }) } private func setupTableView() { tableView.estimatedRowHeight = 200 tableView.rowHeight = UITableViewAutomaticDimension tableView.allowsSelection = false tableView.register(TWTRTweetTableViewCell.self, forCellReuseIdentifier: "TweetCell") tableView.delegate = self tableView.dataSource = self } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TweetCell", for: indexPath) as! TWTRTweetTableViewCell let tweet = tweets[indexPath.row] cell.configure(with: tweet) cell.tweetView.showBorder = true cell.tweetView.showActionButtons = true return cell } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let tweetCell = cell as! TWTRTweetTableViewCell let tweet = tweets[indexPath.row] let cellBackgroundCollor = userMoodService.predictMoodWith(string: tweet.text).asColor() tweetCell.tweetView.backgroundColor = cellBackgroundCollor } }
0
// // LoginViewController.swift // PunchIn // // Created by Nilesh Agrawal on 10/20/15. // Copyright © 2015 Nilesh Agrawal. All rights reserved. // import UIKit import Parse class LoginViewController: UIViewController { static let loginSegueName = "loginSegue" static let userTypes = [ "Student", "Instructor" ] private let initialEmailAddress = "[email protected]" private let initialPassword = "password" private static let noUserProvidedText = "Please provide an email address" private static let noPasswordProvidedText = "Please provide a password" private static let badUserText = "Email and/or Password is not valid" private static let notInstructorText = " is not an Instructor" private static let notStudentText = " is not a Student" @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var invalidEntryLabel: UILabel! @IBOutlet var studentIndicatorTapGesture: UITapGestureRecognizer! @IBOutlet weak var studentIndicatorImage: UIImageView! private var isStudent: Bool = false deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: ParseDB.BadLoginNotificationName, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: ParseDB.BadTypeNotificationName, object:nil) } override func viewDidLoad() { super.viewDidLoad() setupUI() setupGestureRecognizer() isStudent = false studentIndicatorImage.image = UIImage(named: "unselected_button_login.png") // Do any additional setup after loading the view. invalidEntryLabel.hidden = true NSNotificationCenter.defaultCenter().addObserver(self, selector: "badUser", name:ParseDB.BadLoginNotificationName, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "badType", name:ParseDB.BadTypeNotificationName, object:nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func setupUI() { // set color schemes, etc // set background color self.view.backgroundColor = ThemeManager.theme().primaryDarkBlueColor() // set background color for email address & password field nameTextField.backgroundColor = ThemeManager.theme().primaryBlueColor() nameTextField.textColor = UIColor.whiteColor() nameTextField.placeholder = initialEmailAddress passwordTextField.backgroundColor = ThemeManager.theme().primaryBlueColor() passwordTextField.textColor = UIColor.whiteColor() passwordTextField.placeholder = initialPassword // set login loginButton.layer.borderColor = UIColor.whiteColor().CGColor loginButton.layer.borderWidth = 1.0 loginButton.tintColor = UIColor.whiteColor() // set color for invalid entry invalidEntryLabel.textColor = ThemeManager.theme().primaryYellowColor() } private func setupGestureRecognizer() { studentIndicatorTapGesture.addTarget(self, action: "didTapStudentIndicator") } func didTapStudentIndicator() { if isStudent { // change to not student isStudent = false studentIndicatorImage.image = UIImage(named: "unselected_button_login.png") }else{ // change to student isStudent = true studentIndicatorImage.image = UIImage(named: "selected_button_login.png") } } func validateInput() -> Bool { var goodInput: Bool = true goodInput = goodInput && !nameTextField.text!.isEmpty goodInput = goodInput && !passwordTextField.text!.isEmpty goodInput = goodInput && !(nameTextField.text==initialEmailAddress) goodInput = goodInput && !(passwordTextField.text==initialPassword) return goodInput } private func updateInvalidDataText(status: String) { self.invalidEntryLabel.alpha = 0 self.invalidEntryLabel.hidden = false self.invalidEntryLabel.text = status UIView.animateWithDuration(0.5) { () -> Void in self.invalidEntryLabel.alpha = 1 } } func badUser() { updateInvalidDataText(LoginViewController.badUserText) } func badType() { let errorText = isStudent ? LoginViewController.notStudentText : LoginViewController.notInstructorText updateInvalidDataText(self.nameTextField.text! + errorText) } @IBAction func accountLogin(sender: AnyObject) { guard !nameTextField.text!.isEmpty else { updateInvalidDataText(LoginViewController.noUserProvidedText) return } guard !passwordTextField.text!.isEmpty else { updateInvalidDataText(LoginViewController.noPasswordProvidedText) return } self.invalidEntryLabel.hidden = true ParseDB.login(nameTextField!.text!, password: passwordTextField!.text!, type: isStudent ? LoginViewController.userTypes[0] : LoginViewController.userTypes[1]) } // 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. } }
0
// // AnimationViewController // Demo // // Created by Mac Gallagher on 5/25/18. // Copyright © 2018 Mac Gallagher. All rights reserved. // import UIKit import PopBounceButton class AnimationDemoViewController: UIViewController { private lazy var resetButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Reset", for: .normal) button.addTarget(self, action: #selector(reset), for: .touchUpInside) return button }() private let stackView: UIStackView = { let sv = UIStackView() sv.axis = .vertical sv.distribution = .equalSpacing return sv }() private let bounceButton: PopBounceButton = { let button = PopBounceButton() button.backgroundColor = .orange button.layer.masksToBounds = true return button }() private let defaultButton = PopBounceButton() //for initial settings private let bouncinessLabel = ResizingLabel() private let speedLabel = ResizingLabel() private let velocityLabel = ResizingLabel() private let cancelDurationLabel = ResizingLabel() private let scaleFactorLabel = ResizingLabel() private let scaleDurationLabel = ResizingLabel() private let minimumLongPressDurationLabel = ResizingLabel() private lazy var bouncinessSlider: Slider = { let slider = Slider(minimumValue: 0, maximumValue: 20) slider.tag = 1 slider.addTarget(self, action: #selector(handleSlider), for: .valueChanged) return slider }() private lazy var speedSlider: Slider = { let slider = Slider(minimumValue: 0, maximumValue: 20) slider.tag = 2 slider.addTarget(self, action: #selector(handleSlider), for: .valueChanged) return slider }() private lazy var velocitySlider: Slider = { let slider = Slider(minimumValue: 0, maximumValue: 30) slider.tag = 3 slider.addTarget(self, action: #selector(handleSlider), for: .valueChanged) return slider }() private lazy var cancelDurationSlider: Slider = { let slider = Slider(minimumValue: 0, maximumValue: 1) slider.tag = 4 slider.addTarget(self, action: #selector(handleSlider), for: .valueChanged) return slider }() private lazy var scaleFactorSlider: Slider = { let slider = Slider(minimumValue: 0.5, maximumValue: 1) slider.tag = 5 slider.addTarget(self, action: #selector(handleSlider), for: .valueChanged) return slider }() private lazy var scaleDurationSlider: Slider = { let slider = Slider(minimumValue: 0, maximumValue: 0.5) slider.tag = 6 slider.addTarget(self, action: #selector(handleSlider), for: .valueChanged) return slider }() private lazy var minimumLongPressDurationSlider: Slider = { let slider = Slider(minimumValue: 0, maximumValue: 1) slider.tag = 7 slider.addTarget(self, action: #selector(handleSlider), for: .valueChanged) return slider }() //MARK: - Initialization override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Animation Demo" view.backgroundColor = UIColor(red: 243/255, green: 245/255, blue: 248/255, alpha: 1) additionalSafeAreaInsets = UIEdgeInsets(top: 2, left: 10, bottom: 10, right: 10) layoutSubviews() reset() } //MARK: - Layout private func layoutSubviews() { view.addSubview(resetButton) resetButton.anchor(top: view.safeAreaLayoutGuide.topAnchor, left: nil, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor) layoutBounceButton() layoutStackView() } private func layoutBounceButton() { view.addSubview(bounceButton) bounceButton.translatesAutoresizingMaskIntoConstraints = false bounceButton.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.25).isActive = true bounceButton.widthAnchor.constraint(equalTo: bounceButton.heightAnchor).isActive = true bounceButton.topAnchor.constraint(equalTo: resetButton.bottomAnchor).isActive = true bounceButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true } private func layoutStackView() { let minimumSpacing: CGFloat = 10 let bouncinessStackView = horizontalStackView(subviews: [bouncinessLabel, bouncinessSlider], spacing: minimumSpacing) let speedStackView = horizontalStackView(subviews: [speedLabel, speedSlider], spacing: minimumSpacing) let velocityStackView = horizontalStackView(subviews: [velocityLabel, velocitySlider], spacing: minimumSpacing) let cancelDurationStackView = horizontalStackView(subviews: [cancelDurationLabel, cancelDurationSlider], spacing: minimumSpacing) let scaleFactorStackView = horizontalStackView(subviews: [scaleFactorLabel, scaleFactorSlider], spacing: minimumSpacing) let scaleDurationStackView = horizontalStackView(subviews: [scaleDurationLabel, scaleDurationSlider], spacing: minimumSpacing) let minimumLongPressDurationStackView = horizontalStackView(subviews: [minimumLongPressDurationLabel, minimumLongPressDurationSlider], spacing: minimumSpacing) view.addSubview(stackView) stackView.anchor(top: bounceButton.bottomAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: view.safeAreaLayoutGuide.bottomAnchor, right: view.safeAreaLayoutGuide.rightAnchor) stackView.addArrangedSubview(UIView()) stackView.addArrangedSubview(bouncinessStackView) stackView.addArrangedSubview(speedStackView) stackView.addArrangedSubview(velocityStackView) stackView.addArrangedSubview(cancelDurationStackView) stackView.addArrangedSubview(scaleFactorStackView) stackView.addArrangedSubview(scaleDurationStackView) stackView.addArrangedSubview(minimumLongPressDurationStackView) } private func horizontalStackView(subviews: [UIView], spacing: CGFloat) -> UIStackView { let stack = UIStackView() stack.distribution = .fillEqually stack.spacing = spacing for subview in subviews { stack.addArrangedSubview(subview) } return stack } override func viewDidLayoutSubviews() { bounceButton.layer.cornerRadius = bounceButton.bounds.width / 2 } //MARK: - Slider Handling @objc func reset() { bounceButton.springBounciness = defaultButton.springBounciness bounceButton.springSpeed = defaultButton.springSpeed bounceButton.springVelocity = defaultButton.springVelocity bounceButton.cancelTapScaleDuration = defaultButton.cancelTapScaleDuration bounceButton.longPressScaleFactor = defaultButton.longPressScaleFactor bounceButton.longPressScaleDuration = defaultButton.longPressScaleDuration bounceButton.minimumPressDuration = defaultButton.minimumPressDuration updateLabels() updateSliders() } private func updateLabels() { bouncinessLabel.text = "Bounciness = \(Int(bounceButton.springBounciness))" speedLabel.text = "Speed = \(Int(bounceButton.springSpeed))" velocityLabel.text = "Velocity = \(Int(bounceButton.springVelocity))" cancelDurationLabel.text = "Cancel Duration = " + String(format: "%.2f", bounceButton.cancelTapScaleDuration) + " s" scaleFactorLabel.text = "Scale Factor = " + String(format: "%.2f", bounceButton.longPressScaleFactor) scaleDurationLabel.text = "Scale Duration = " + String(format: "%.2f", bounceButton.longPressScaleDuration) + " s" minimumLongPressDurationLabel.text = "Min Press Duration = " + String(format: "%.2f", bounceButton.minimumPressDuration) + " s" } private func updateSliders() { bouncinessSlider.setValue(Float(bounceButton.springBounciness), animated: true) speedSlider.setValue(Float(bounceButton.springSpeed), animated: true) velocitySlider.setValue(Float(bounceButton.springVelocity), animated: true) cancelDurationSlider.setValue(Float(bounceButton.cancelTapScaleDuration), animated: true) scaleFactorSlider.setValue(Float(bounceButton.longPressScaleFactor), animated: true) scaleDurationSlider.setValue(Float(bounceButton.longPressScaleDuration), animated: true) minimumLongPressDurationSlider.setValue(Float(bounceButton.minimumPressDuration), animated: true) } @objc private func handleSlider(_ sender: UISlider) { switch sender.tag { case 1: bounceButton.springBounciness = CGFloat(sender.value.rounded(toPlaces: 0)) case 2: bounceButton.springSpeed = CGFloat(sender.value.rounded(toPlaces: 0)) case 3: bounceButton.springVelocity = CGFloat(sender.value.rounded(toPlaces: 0)) case 4: bounceButton.cancelTapScaleDuration = TimeInterval(sender.value.rounded(toPlaces: 2)) case 5: bounceButton.longPressScaleFactor = CGFloat(sender.value.rounded(toPlaces: 2)) case 6: bounceButton.longPressScaleDuration = TimeInterval(sender.value.rounded(toPlaces: 2)) case 7: bounceButton.minimumPressDuration = TimeInterval(sender.value.rounded(toPlaces: 2)) default: break } updateLabels() updateSliders() } }
0
// // MBPointerButton.swift // MockBob // // Created by Jonathan Grider on 8/23/20. // Copyright © 2020 Jonathan Grider. All rights reserved. // // Simple subclass to add a cursor pointer effect to buttons // import Cocoa class MBPointerButton: NSButton { private var originalTemplateFlag: Bool = false var cursor = NSCursor() override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) if let image = self.image { image.isTemplate = true } // Add tracking area for hover effects on OS X 10.14 and later // Could also include the cursor updates in this tracking but kept it separate for the sake of recording examples if #available(OSX 10.14, *) { let trackingArea = NSTrackingArea(rect: bounds, options: [.activeAlways, .mouseEnteredAndExited], owner: self, userInfo: nil) self.addTrackingArea(trackingArea) } } override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) if #available(OSX 10.14, *) { if effectiveAppearance.name == .darkAqua || effectiveAppearance.name == .vibrantDark { self.contentTintColor = .white } else { self.contentTintColor = .black } } } override func mouseExited(with event: NSEvent) { super.mouseExited(with: event) if #available(OSX 10.14, *) { self.contentTintColor = .none } } override func resetCursorRects() { addCursorRect(bounds, cursor: .pointingHand) } }
0
// // SettingsTableViewController.swift // HNR // // Created by Tiago Alves on 13/09/2017. // Copyright © 2017 Tiago Alves. All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source // override func numberOfSections(in tableView: UITableView) -> Int { // return 1 // } // // override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return 1 // } // // override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: "settingsCell", for: indexPath) // // cell.textLabel?.text = "Licenses" // // return cell // } // // override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // switch indexPath.row { // case 0: // self.performSegue(withIdentifier: "licenses", sender: nil) // default: // return // } // } /* // 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. } */ }
0
// // Module.swift // SwiftLogger // // // Created by Madimo on 2019/12/11. // Copyright © 2019 Madimo. All rights reserved. // import Foundation public struct Module: Codable, Hashable { public var name: String public init(name: String) { self.name = name } } extension Module: Equatable { public static func ==(lhs: Module, rhs: Module) -> Bool { lhs.name == rhs.name } } extension Module { public static let `default` = Module(name: "Default") }
0
// // AnswerController.swift // App // // Created by Martin Lasek on 16.04.19. // import Vapor final class AnswerController { var questionController: QuestionController init(questionController: QuestionController) { self.questionController = questionController } func fourAnswer(req: Request) throws -> Future<Response> { return try req.content.decode(FourAnswerForm.self).flatMap { answerForm in FourAnswer(from: answerForm).save(on: req).map { _ in req.redirect(to: self.getRedirect(for: answerForm.questionNumber)) } } } func rangeAnswer(req: Request) throws -> Future<Response> { return try req.content.decode(RangeAnswerForm.self).flatMap { answerForm in RangeAnswer.init(from: answerForm).save(on: req).map { _ in req.redirect(to: self.getRedirect(for: answerForm.questionNumber)) } } } func freeAnswer(req: Request) throws -> Future<Response> { return try req.content.decode(FreeAnswerForm.self).flatMap { answerForm in FreeAnswer.init(from: answerForm).save(on: req).map { _ in req.redirect(to: self.getRedirect(for: answerForm.questionNumber)) } } } func twoAnswer(req: Request) throws -> Future<Response> { return try req.content.decode(TwoAnswerForm.self).flatMap { answerForm in TwoAnswer.init(from: answerForm).save(on: req).map { _ in req.redirect(to: self.getRedirect(for: answerForm.questionNumber)) } } } func threeAnswer(req: Request) throws -> Future<Response> { debugPrint(req.content) return try req.content.decode(ThreeAnswerForm.self).flatMap { answerForm in ThreeAnswer.init(from: answerForm).save(on: req).map { _ in req.redirect(to: self.getRedirect(for: answerForm.questionNumber)) } } } private func getRedirect(for number: Int) -> String { switch number { case 1: return Routes.q2 case 2: return Routes.q3 case 3: return Routes.q4 case 4: return Routes.q5 case 5: return Routes.q6 case 6: return Routes.q7 case 7: return Routes.q8 case 8: return Routes.q9 case 9: return Routes.q10 case 10: return Routes.q11 default: return Routes.index } } }
0
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import Foundation class m<j>: NSObject { var h: j g -> k = l $n } b f: _ = j() { } } func k<g { enum k { func l var _ = l c j) func c<k>() -> (k, > k) -> k { d h d.f 1, k(j, i))) class k { typealias h = h protocol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { } } protocol a { typealias d typealias e = d typealias f = d } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { typealias g } class l { func f((k, l() -> f } class d } class i: d, g { l func d() -> f { m "" } } } func m<j n j: g, j: d let l = h l() f protocol l : f { func f protocol g import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g struct c<d : SequenceType> { var b: [c<d>] { return [] } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() func f<T : BooleanType>(b: T) { } f(true as BooleanType) func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type func e() { d.e() } } b protocol c : b { func b otocol A { E == F>(f: B<T>) } struct } } struct l<e : SequenceType> { l g: e } func h<e>() -> [l<e>] { f [] } func i(e: g) -> <j>(() -> j) -> k func b(c) -> <d>(() -> d) { } func k<q>() -> [n<q>] { r [] } func k(l: Int = 0) { } n n = k n() func n<q { l n { func o o _ = o } } func ^(k: m, q) -> q { r !(k) } protocol k { j q j o = q j f = q } class l<r : n, l : n p r.q == l> : k { } class l<r, l> { } protocol n { j q } protocol k : k { } class k<f : l, q : l p f.q == q> { } protocol l { j q j o } struct n<r : l> struct c<d: SequenceType, b where Optional<b> == d.Generator.Element> } class p { u _ = q() { } } u l = r u s: k -> k = { n $h: m.j) { } } o l() { ({}) } struct m<t> { let p: [(t, () -> ())] = [] } protocol p : p { } protocol m { o u() -> String } class j { o m() -> String { n "" } } class h
0
/*: # Graph You can show the value of a variable that changes over time. For example when you create a simple **for-loop** where you update the value of a variable. */ var j = 2 for i in 0 ..< 5 { j += j * i } /*: ### Import data You can now load some JSON data from a resource file. In this case we will fetch the weather predictions for a special place somewhere in Thailand. */ import UIKit let forecasts: [[String: AnyObject]] = { let fileURL = NSBundle.mainBundle().URLForResource("weather", withExtension: "json")! if let data = NSData(contentsOfURL: fileURL), json = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments), forecasts = json["hourly_forecast"] as? [[String: AnyObject]] { return forecasts } return [] }() //: [➡️](@next)
0
// // ButterflyViewController.swift // Butterfly // // Created by Zhijie Huang on 15/6/20. // // Copyright (c) 2015 Zhijie Huang <[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 /// MARK: - Protocol of `ButterflyViewController protocol ButterflyViewControllerDelegate: class { func ButterflyViewControllerDidPressedSendButton(_ drawView: ButterflyDrawView?) } /// This is the viewController combined Butterfly modules. open class ButterflyViewController: UIViewController { /// The image reported by users that will upload to server. internal var imageWillUpload: UIImage? /// The text reported by users that will upload to server. internal var textWillUpload: String? var topBar: ButterflyTopBar? var bottomBar: ButterflyBottomBar? var drawView: ButterflyDrawView? lazy var textView: ButterflyTextView = { let view = ButterflyTextView() return view }() weak var delegate: ButterflyViewControllerDelegate? var drawColor: UIColor? var drawLineWidth: Float? var imageView: UIImageView? var image: UIImage? var colors: [UIColor]? var textViewIsShowing: Bool? override open func viewDidLoad() { super.viewDidLoad() setup() self.view.backgroundColor = UIColor.clear self.navigationController?.isNavigationBarHidden = true } /// Set up the view fileprivate func setup() { imageView = UIImageView(frame: UIScreen.main.bounds) imageView?.image = self.image imageView?.autoresizingMask = UIViewAutoresizing([.flexibleWidth, .flexibleHeight]) imageView?.contentMode = UIViewContentMode.center self.view.addSubview(imageView!) drawView = ButterflyDrawView() drawView?.delegate = self self.view.addSubview(drawView!) topBar = ButterflyTopBar() self.view.addSubview(topBar!) bottomBar = ButterflyBottomBar() self.view.addSubview(bottomBar!) topBar?.sendButton?.addTarget(self, action: #selector(sendButtonPressed), for: UIControlEvents.touchUpInside) topBar?.cancelButton?.addTarget(self, action: #selector(cancelButtonPressed), for: UIControlEvents.touchUpInside) bottomBar?.colorChangedButton?.addTarget(self, action: #selector(colorChangedButtonPressed), for: UIControlEvents.touchUpInside) bottomBar?.descriptionButton?.addTarget(self, action: #selector(inputDescriptionButtonPressed), for: UIControlEvents.touchUpInside) bottomBar?.clearPathButton?.addTarget(self, action: #selector(clearButtonPressed), for: UIControlEvents.touchUpInside) textView.delegate = self view.addSubview(self.textView) } @objc open func cancelButtonPressed(_ sender: UIButton?) { drawView?.enable() dismiss(animated: false, completion: nil) } /// Note: Always access or upload `imageWillUpload` and `textWillUpload` only after send button has been pressed, otherwise, these two optional properties may be nil. /// After that, you can upload image and text manually and properly. @objc open func sendButtonPressed(_ sender: UIButton?) { drawView?.enable() delegate?.ButterflyViewControllerDidPressedSendButton(drawView) imageWillUpload = ButterflyManager.sharedManager.takeScreenshot() textWillUpload = textView.text if let textViewIsShowing = textView.isShowing { if textViewIsShowing == true { textView.hide() } } showAlertViewController() print(self.imageWillUpload!) print(self.textWillUpload!) } func showAlertViewController() { self.dismiss(animated: false, completion: nil) let alert = UIAlertController(title: "Success", message: "Report Success", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)) self.presentingViewController?.present(alert, animated: true, completion: nil) } @objc internal func colorChangedButtonPressed(_ sender: UIButton?) { if drawView?.lineColor != UIColor.yellow { drawView?.lineColor = UIColor.yellow } else { drawView?.lineColor = UIColor.red } } @objc internal func inputDescriptionButtonPressed(_ sender: UIButton?) { textView.show() drawView?.disable() } @objc internal func clearButtonPressed(_ sender: UIButton?) { drawView?.clear() } /// MARK: - deinit deinit{ drawView?.delegate = nil } } extension ButterflyViewController: ButterflyDrawViewDelegate { func drawViewDidEndDrawingInView(_ drawView: ButterflyDrawView?) { topBar?.show() bottomBar?.show() } func drawViewDidStartDrawingInView(_ drawView: ButterflyDrawView?) { topBar?.hide() bottomBar?.hide() } } extension ButterflyViewController: UITextViewDelegate { /// Placeholder trick /// /// Changed if statements to compare tags rather than text. If the user deleted their text it was possible to also /// accidentally delete a portion of the place holder. This meant if the user re-entered the textView the following /// delegate method, `- textViewShouldBeginEditing` , it would not work as expected. /// /// http://stackoverflow.com/questions/1328638/placeholder-in-uitextview/7091503#7091503 /// DO NOT OVERRIDE THESE METHODS BELOW EXCEPTED YOU NEED INDEED. /// public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { if textView.tag == 0 { textView.text = ""; textView.textColor = UIColor.black; textView.tag = 1; } return true; } public func textViewDidEndEditing(_ textView: UITextView) { if textView.text.count == 0 { textView.text = "Please enter your feedback." textView.textColor = UIColor.lightGray textView.tag = 0 } self.textView.hide() drawView?.enable() textWillUpload = textView.text } public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { textView.resignFirstResponder() return false } return true } }
0
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import UIKit import RealmSwift let kPersonDetailSegue = "personDetailSegue" class PeopleViewController: UITableViewController { var realm = try! Realm() var notificationToken: NotificationToken? = nil var myIdentity = SyncUser.current?.identity! let genericAvatarImage = UIImage(named: "Circled User Male_30") var thePersonRecord: Person? var people: Results<Person>? var token : NotificationToken? var roleSignifier = "" override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self self.navigationItem.title = NSLocalizedString("People", comment: "People") people = realm.objects(Person.self) notificationToken = people?.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in guard let tableView = self?.tableView else { return } switch changes { case .initial: // Results are now populated and can be accessed without blocking the UI tableView.reloadData() break case .update(_, let deletions, let insertions, let modifications): // Query results have changed, so apply them to the UITableView tableView.beginUpdates() tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }), with: .automatic) tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}), with: .automatic) tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }), with: .automatic) tableView.endUpdates() break case .error(let error): // An error occurred while opening the Realm file on the background worker thread fatalError("\(error)") break } } } // When this controller is disposed, of we want to make sure we stop the notifications deinit { notificationToken?.stop() } override func viewWillAppear(_ animated: Bool) { tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (people?.count)! } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 125.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // things we need to display let person = people![indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "personCell", for: indexPath as IndexPath) as! PersonTableViewCell switch person.role { case .Admin: roleSignifier = NSLocalizedString("[admin]", comment: "admin") case .Manager: roleSignifier = NSLocalizedString("[manager]", comment: "manager") default: roleSignifier = "" } if person.firstName.isEmpty || person.lastName.isEmpty { cell.nameLabel.text = NSLocalizedString("(No Name) id:\(String(describing: myIdentity)) ", comment:"No name available") + roleSignifier } else { cell.nameLabel.text = "\(person.firstName) \(person.lastName)" + roleSignifier } switch true { case person.teams.count == 1: cell.totalTasksLabel.text = NSLocalizedString("\(person.teams.count) Team", comment: "1 team") case person.teams.count == 0: cell.totalTasksLabel.text = NSLocalizedString("No Teams", comment: "No Teams") default: cell.totalTasksLabel.text = NSLocalizedString("\(person.teams.count) Teams", comment: "team count") } // @FIXME: Need to have class util methods that grab summary info frm TeamtasRealms for each team the user is on. // let tasks = person.tasks.filter( "isCompleted == false" ).sorted(byKeyPath: "dueDate") // Note that this will return an empty list if the user has no tasks // let overdueCount = tasks.filter( "isCompleted == false AND dueDate < %@", Date() ).count cell.overdueTasksLabel.text = "TBD: task summary" cell.avatarImage.layer.cornerRadius = cell.avatarImage.frame.size.width / 2 cell.avatarImage.clipsToBounds = true cell.avatarImage.backgroundColor = UIColor.white if person.avatar != nil { cell.avatarImage.image = UIImage(data: person.avatar! as Data)!.scaleToSize(size: cell.avatarImage.frame.size) } return cell } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == kPersonDetailSegue { let indexPath = tableView.indexPathForSelectedRow self.navigationController?.setNavigationBarHidden(false, animated: false) let vc = segue.destination as? PersonDetails2ViewController vc!.personId = people![indexPath!.row].id vc!.hidesBottomBarWhenPushed = true } } }
0
// // Common.swift // DYZB // // Created by Kitty on 2017/4/20. // Copyright © 2017年 RM. All rights reserved. // import UIKit let kStatusBarH : CGFloat = 20 let kNavigationBarH : CGFloat = 44 let kTabbarH : CGFloat = 49 let kScreenW = UIScreen.main.bounds.width let kScreenH = UIScreen.main.bounds.height let kHomeTitleViewFont : CGFloat = 16
0
// // ProductTableViewController.swift // RetailVision // // Created by Colby L Williams on 4/22/18. // Copyright © 2018 Colby L Williams. All rights reserved. // import Foundation import UIKit import Whisper class ProductTableViewController : UITableViewController { @IBOutlet var addButton: UIBarButtonItem! @IBOutlet var activityButton: UIView! @IBOutlet weak var cameraButton: UIBarButtonItem! @IBOutlet weak var refreshButton: UIBarButtonItem! var activityButtonItem: UIBarButtonItem! var currencyFormatter: CurrencyFormatter { return ProductManager.shared.currencyFormatter } var products: [Product] { return ProductManager.shared.products } override func viewDidLoad() { super.viewDidLoad() title = "Products" activityButtonItem = UIBarButtonItem(customView: activityButton) if let refreshControl = refreshControl { refreshControl.tintColor = #colorLiteral(red: 1, green: 0.1764705882, blue: 0.3333333333, alpha: 1) tableView.contentOffset = CGPoint(x:0, y:-refreshControl.frame.size.height) refreshControl.beginRefreshing() refreshData() } navigationItem.setLeftBarButtonItems([cameraButton, refreshButton], animated: false) navigationItem.setRightBarButtonItems([addButton, editButtonItem], animated: false) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) ProductManager.shared.clearSelectedProduct() } func refreshData() { ProductManager.shared.refresh { self.refreshControl?.endRefreshing() self.tableView.reloadData() } } @IBAction func refreshControlValueChanged(_ sender: Any) { refreshData() } @IBAction func refreshModelButtonTouched(_ sender: Any) { navigationItem.setLeftBarButtonItems([cameraButton, activityButtonItem], animated: true) ProductManager.shared.trainAndDownloadCoreMLModel(withName: "kwjewelry", progressUpdate: self.displayUpdateMessage, self.displayFinalMessage) } func displayUpdateMessage(message: String) { displayMessage(message: message) } func displayFinalMessage(success: Bool, message: String) { displayMessage(message: message, thenHide: true) } func displayMessage(message: String, thenHide: Bool = false) { guard let navController = navigationController else { return } DispatchQueue.main.async { Whisper.show(whisper: Message(title: message, backgroundColor: #colorLiteral(red: 1, green: 0.1764705882, blue: 0.3333333333, alpha: 1)), to: navController, action: .present) if thenHide { Whisper.hide(whisperFrom: navController, after: 4) self.navigationItem.setLeftBarButtonItems([self.cameraButton, self.refreshButton], animated: true) } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return products.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "productCell", for: indexPath) let product = products[indexPath.row] cell.textLabel?.text = product.name ?? product.id cell.detailTextLabel?.text = currencyFormatter.string(from: NSNumber(value: product.price ?? 0)) return cell } override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let action = UIContextualAction.init(style: .destructive, title: "Delete") { (action, view, callback) in self.deleteResource(at: indexPath, from: tableView, callback: callback) } return UISwipeActionsConfiguration(actions: [ action ] ); } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { deleteResource(at: indexPath, from: tableView) } } func deleteResource(at indexPath: IndexPath, from tableView: UITableView, callback: ((Bool) -> Void)? = nil) { ProductManager.shared.delete(productAt: indexPath.row) { success in if success { tableView.deleteRows(at: [indexPath], with: .automatic) } callback?(success) } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? UITableViewCell, let index = tableView.indexPath(for: cell) { ProductManager.shared.selectedProduct = products[index.row] } } }
0
// // RestClient.swift // CPOutfitters // // Created by Aditya Purandare on 12/03/16. // Copyright © 2016 SnazzyLLama. All rights reserved. // /* Params of User Class: var friends: [User]? var profileImage: PFFile? var bio: String? var sharedWith: [User]? */ import UIKit import Parse class ParseClient: NSObject { static let sharedInstance = ParseClient() func fetchArticles(params: NSDictionary, completion:([Article]?, NSError?) -> ()) { let query = PFQuery(className: "Article") for (key, value) in params { query.whereKey(key as! String, containsString: value as? String) } query.whereKey("owner", equalTo: PFUser.currentUser()!) query.limit = 40 query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in if let articles = objects as? [Article] { completion(articles, nil) } else { print("Parse Client: \(error?.localizedDescription)") } } } func countArticles(params: NSDictionary, completion:(Int32?, NSError?) -> ()) { let query = PFQuery(className:"Article") let obj = params var userName: PFUser? for (key, value) in obj { userName = value as? PFUser } query.whereKey("owner", equalTo: userName!) query.countObjectsInBackgroundWithBlock { (count: Int32, error: NSError?) -> Void in if error == nil { completion(count, nil) } else { print(error?.localizedDescription) } } } func loadProfileImageWithCompletion(params: NSDictionary, completion:([PFObject]?, NSError?) -> ()) { let obj = params var userName: String? for (key, value) in obj { userName = value as? String } let query = PFQuery(className: "_User") query.whereKey("username", equalTo: userName!) query.limit = 20 query.findObjectsInBackgroundWithBlock(completion) } func getArticle(articleId: String, completion:(Article?, NSError?) -> ()) { let article = Article(className: articleId) article.fetchInBackgroundWithBlock { (result, error) -> Void in completion(result as? Article, error) } } func saveArticle(article: Article, completion:(success: Bool, error: NSError?) -> ()) { article.mediaImage.saveInBackgroundWithBlock { (success, error: NSError?) in if success { article.saveInBackgroundWithBlock { (success: Bool?, error: NSError?) -> Void in if (success == true ) { print("Parse Client: An article stored") completion(success: true, error: nil) } else { print("Parse Client: \(error?.localizedDescription)") completion(success: false, error: error) } } } else { print("Parse Client: \(error?.localizedDescription)") completion(success: false, error: error) } } } func fetchOutfit(completion:([PFObject]?, NSError?) -> ()) { let query = PFQuery(className: "Outfit") query.limit = 40 query.findObjectsInBackgroundWithBlock(completion) } func saveOutfit(outfit: Outfit, completion:(success: Bool, error: NSError?) -> ()) { outfit.saveInBackgroundWithBlock(completion) } func getRecommendedOutfit(params: NSDictionary, completion:(String, Article?, NSError?) -> ()) { // Retrieve top var query = PFQuery(className: "Article") query.whereKey("type", equalTo: "top") query.whereKey("owner", equalTo: PFUser.currentUser()!) for (key, value) in params { query.whereKey(key as! String, equalTo: value) } query.limit = 1 query.findObjectsInBackgroundWithBlock { (articles, error) -> Void in completion("top", articles?.first as? Article, error) } // retrieve bottom query = PFQuery(className: "Article") query.whereKey("type", equalTo: "bottom") query.whereKey("owner", equalTo: PFUser.currentUser()!) for (key, value) in params { query.whereKey(key as! String, equalTo: value) } query.limit = 1 query.findObjectsInBackgroundWithBlock { (articles, error) -> Void in completion("bottom", articles?.first as? Article, error) } // retrieve footwear query = PFQuery(className: "Article") query.whereKey("type", equalTo: "footwear") query.whereKey("owner", equalTo: PFUser.currentUser()!) for (key, value) in params { query.whereKey(key as! String, equalTo: value) } query.limit = 1 query.findObjectsInBackgroundWithBlock { (articles, error) -> Void in completion("footwear", articles?.first as? Article, error) } } // Function for deletion of article from server func deleteArticle(article: Article, completion:(success: Bool, error: NSError?) -> ()) { article.deleteInBackgroundWithBlock(completion) } func getUser(params: NSDictionary, completion:(PFUser?, NSError?) -> ()) { let query = PFQuery(className: "_User") let username = PFUser.currentUser()?.username query.whereKey("username", equalTo: username!) query.limit = 1 query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in if let objects = objects as? [PFUser] { let user = objects[0] completion(user, nil) } else { print(error?.localizedDescription) } } } func logoutUser() { PFUser.logOutInBackgroundWithBlock { (error:NSError?) in if let error = error { print(error.localizedDescription) } else { print("User logged out") NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil) } } } func updateInfo(params: NSDictionary, completion:(success: Bool, error: NSError?) -> ()) { let obj = params var userName: String? for (key, value) in obj { userName = value as? String } let query = PFQuery(className: "_User") let username = PFUser.currentUser()?.username query.whereKey("username", equalTo: username!) } }
0
/*--------------------------------------------------------------------------*/ /* /\/\/\__/\/\/\ MooseFactory SwiftMidi */ /* \/\/\/..\/\/\/ */ /* | | (c)2021 Tristan Leblanc */ /* (oo) [email protected] */ /* MooseFactory Software */ /*--------------------------------------------------------------------------*/ /* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*--------------------------------------------------------------------------*/ // File.swift // Created by Tristan Leblanc on 09/01/2021. import Foundation import CoreMIDI public class MidiPacketsFilter { public var settings: MidiFilterSettings public var filterState: FilterState /// A tap to receive midi events as MidiEvent objects public var eventsTap: ((MidiEvent)->Void)? /// A tap to receive midiInputBuffers /// /// MidiInputBuffer is an intermediary between raw packets and midi events. /// /// It represents the midi input in a more convenient format. /// It does not create events objects, but rather stores events by types in a primitive format ( Array of Ints ) /// This is usefull for recording, to catch events with an accurate timing public var midiInputBufferTap: ((MidiInputBuffer)->Void)? /// writePacketsToOutput /// If this is true, the filter will allocate a MidiPacketList containing only filtered packets. public var writePacketsToOutput: Bool = true public init(settings: MidiFilterSettings) { self.settings = settings self.filterState = FilterState() } /// Some devices send one packet per midi event ( Like Kurzweil PC3K ) - By the way it is wrong /// So we keep some usefull information from previous packet public struct FilterState { var lsbValue: UInt8 = 0xFF var msbValue: UInt8 = 0xFF // Initial bank is 0 - so real program number won't be correct until a bank select is received on each channel var bank: MidiChannelsValues = .empty } /// The filter output contains the filtered packets, but it also keeps some relevant values that the client can use public class Output { /// The filtered packets public fileprivate(set) var packets: MIDIPacketList? /// Last packet timestamp public fileprivate(set) var timeStamp: MIDITimeStamp = 0 /// Will contains channels that have received musical events public fileprivate(set) var activatedChannels = MidiChannelMask.none /// Will contains lower and higher notes triggered per channel. /// If channel bit is not set in activated channels, this has no meaning public fileprivate(set) var higherAndLowerNotes = [MidiRange].init(repeating: MidiRange(lower: 127 , higher: 0), count: 16) /// Last control values public fileprivate(set) var controlValues: MidiChannelsControlValues = .empty /// Last Real Time Message public fileprivate(set) var realTimeMessage: RealTimeMessageType = .none /// Last ProgramChange public fileprivate(set) var programChanges: MidiChannelsValues = .empty /// Last BankSelect public fileprivate(set) var bankSelect: MidiChannelsValues = .empty /// Last PitchBend public fileprivate(set) var pitchBend: MidiChannelsValues = .empty /// The time spent in the filter public fileprivate(set) var filteringTime: TimeInterval = 0 /// Ticks received. /// If everything runs smoothly, there is always one tick, but if a stall occurs, buffer can contains several ticks public fileprivate(set) var ticks: UInt8 = 0 /// Returns the fractionnal pitch bend ( [-1.0..+1.0] ) public func pitchBend(for channel: Int) -> Float { return Float(pitchBend.value(for: channel)) / Float(0x3FFF) * 2 - 1 } /// Returns the program number as displayed on the device ( > to 127 if bank > 0 ) public func programNumber(for channel: Int) -> Int { let bank = bankSelect.values[Int(channel)] let pgm = programChanges.value(for: channel) return Int(bank) * 128 + Int(pgm) } init(packets: MIDIPacketList?) { self.packets = packets } } /// Returns the number of events with the given types, channels and range /// /// This function code is quite long, but performant. private func preflight(in packetList: UnsafePointer<MIDIPacketList>) -> (UInt32, UInt32, UInt32) { var numberOfEvents: UInt32 = 0 var dataSize: UInt32 = 0 var p = packetList.pointee.packet let numberOfPackets = min(packetList.pointee.numPackets, 1024) // Scan the midi data and cut if necessary var currentStatus: UInt8 = 0 var type: UInt8 = 0 var channel: UInt8 = 0 // true if current byte is velocity var byteSelector: Bool = false // true if the whole event is skipped var skipTrain = false var skipNote: Bool = false var byte: UInt8 = 0 var checkedStatus: Bool = false var keepStatus: Bool = false for _ in 0 ..< numberOfPackets { withUnsafeBytes(of: p.data) { bytes in // In some cases, like pausing xCode, it looks like the packet size can grow far beyond the limit // so we only process the first 256 bytes. I'm not sure of what I am doing here, // but I'm sure it crashes if i >= 256 for i in 0..<min(bytes.count, Int(p.length)) { byte = UInt8(bytes[i]) // Read Status Byte if needed // 1 - read status if byte & 0xF0 >= 0x80 { // We keep status only if subsequent events are kept keepStatus = false currentStatus = byte type = currentStatus & 0xF0 channel = currentStatus & 0x0F skipNote = false // Reset the skip flag skipTrain = false byteSelector = false checkedStatus = false if type == MidiEventType.realTimeMessage.rawValue { if !settings.eventTypes.contains(rawEventType: type) { continue } dataSize += 1 numberOfEvents += 1 } continue } // 2 - If not status, then check if we are skipping this event if skipTrain { continue } // 3 - We have an event - filter by channel and type // Continue skip if status has already be checked if !checkedStatus { checkedStatus = true // filter events if !settings.eventTypes.contains(rawEventType: type) { skipTrain = true continue } // filter channel if (settings.channels & (0x0001 << channel)) == 0 { skipTrain = true continue } } else { if skipTrain { continue } } // 4 - So far so good, now we are in potentially kept events data. // We only filter notes switch type { // 2 data byte events // If we deal with noteOns, then we filter range and velocity case MidiEventType.noteOn.rawValue: // Check if current byte is note or velocity if byteSelector { if !skipNote { skipNote = byte < settings.velocityRange.lower || byte > settings.velocityRange.higher // Still not skip the note, we count it to if !skipNote { dataSize += 2 numberOfEvents += 1 if (!keepStatus) { keepStatus = true dataSize += 1 } } else { // reset skipNote for the next note skipNote = false } } else { // reset skipNote for the next note skipNote = false } // Next byte will be note number byteSelector = false } else { skipNote = byte < settings.noteRange.lower || byte > settings.noteRange.higher // Next byte will be velocity byteSelector = true } case MidiEventType.noteOff.rawValue: // Check if current byte is note or velocity ( no meaning on note off, but still there ) if byteSelector { dataSize += 2 numberOfEvents += 1 byteSelector = false if (!keepStatus) { keepStatus = true dataSize += 1 } } else { byteSelector = true } case MidiEventType.control.rawValue: // Check if current byte is control number or value if byteSelector { dataSize += 2 numberOfEvents += 1 byteSelector = false if (!keepStatus) { keepStatus = true dataSize += 1 } } else { byteSelector = true } case MidiEventType.pitchBend.rawValue: // Check if current byte is control number or value if byteSelector { dataSize += 2 numberOfEvents += 1 byteSelector = false if (!keepStatus) { keepStatus = true dataSize += 1 } } else { byteSelector = true } case MidiEventType.polyAfterTouch.rawValue: if byteSelector { dataSize += 2 numberOfEvents += 1 byteSelector = false if (!keepStatus) { keepStatus = true dataSize += 1 } } else { byteSelector = true } // 1 data byte events case MidiEventType.afterTouch.rawValue: if (!keepStatus) { keepStatus = true dataSize += 1 } dataSize += 1 numberOfEvents += 1 case MidiEventType.programChange.rawValue: if (!keepStatus) { keepStatus = true dataSize += 1 } dataSize += 1 numberOfEvents += 1 // 0 data byte events case MidiEventType.realTimeMessage.rawValue: break default: break } // End switch } // End scan } // Go to next packet ( should never happen for musical events ) p = MIDIPacketNext(&p).pointee } return (numberOfPackets, numberOfEvents, dataSize) } // MARK: - Filtering /// filter /// /// Returns a filtered list of MIDI Packets /// /// THIS ONLY WORK WITH ONE MIDI PACKET - DO NOT PASS SYSEX THROUGH THIS public func filter(packetList: UnsafePointer<MIDIPacketList>) -> MidiPacketsFilter.Output { if settings.willPassThrough { return Output(packets: packetList.pointee) } let chrono = Date() // Get final number of events let (numberOfPackets, count, dataSize) = preflight(in: packetList) guard count > 0 else { return Output(packets: nil) } var outPackets = MIDIPacketList() let writePacketPtr = MIDIPacketListInit(&outPackets) let output = Output(packets: outPackets) // The size needed for output packets // If we don't write output, we allocate a single byte to run the loop let outDataSize = writePacketsToOutput ? Int(dataSize) : 1 let midiInputBuffer: MidiInputBuffer? = midiInputBufferTap == nil ? nil : MidiInputBuffer() let targetBytes = [UInt8].init(unsafeUninitializedCapacity: outDataSize) { (targetBytes, count) in count = Int(targetBytes.count) var writeIndex = 0 var p = packetList.pointee.packet func writeByte(byte: UInt8) { if writeIndex >= count { print("[MIDI FILTER] Wrong write index \(writeIndex) ( size: \(outDataSize) )- line \(#line) in \(#file)") } else { targetBytes[writeIndex] = byte writeIndex += 1 } } // Scan the midi data and cut if necessary var currentStatus: UInt8 = 0 var type: UInt8 = 0 var channel: UInt8 = 0 // true if current byte is velocity var byteSelector: Bool = false // Special control byte selector, to handle bank changes var controlByteSelector: Bool = false // true if the whole event is skipped var skipTrain = false // the length of data bytes following the status byte // if 0, then we can remove the status byte var skipNote: Bool = false var byte: UInt8 = 0 var data1: UInt8 = 0 var note: Int16 = 0 // Tells if the status byte has already been written we keep an event // ( running status requires only one status byte before a train of events of the same type ) var wroteStatus: Bool = false // The control number being scanned. We need it to capture 2 significant bytes controls var controlNumber: UInt8 = 0 for _ in 0 ..< numberOfPackets { output.timeStamp = p.timeStamp withUnsafeBytes(of: p.data) { bytes in for i in 0..<min(bytes.count, Int(p.length)) { byte = UInt8(bytes[i]) // Read Status Byte if needed // 1 - read status if byte & 0xF0 >= 0x80 { currentStatus = byte type = currentStatus & 0xF0 channel = currentStatus & 0x0F skipNote = false // Reset the skip flag skipTrain = false byteSelector = false /// We write status only if some data are kept wroteStatus = false data1 = 0 controlNumber = 0 // Process data-less types // Clock - if clock are not filtered and clock channel match, we process clock if type == MidiEventType.realTimeMessage.rawValue { if !settings.eventTypes.contains(rawEventType: type) { continue } if currentStatus == RealTimeMessageType.clock.rawValue { output.ticks += 1 } else { output.realTimeMessage = RealTimeMessageType(rawValue: currentStatus) ?? .none } // --- WRITE ---- if writePacketsToOutput { writeByte(byte: byte) } } else { if settings.tracksActivatedChannels { output.activatedChannels |= (0x0001 << channel) } } continue } // 2 - If not status, then check if we are skipping this event if skipTrain { continue } // 3 - We have an event - filter by channel and type // Process bank select. We process it apart since the type is a control, but the real event type is a program change if type == MidiEventType.control.rawValue { // If we filter control we skip this, unless we receve a program change // If we filter program changes, we skip this too unless we have a control if !settings.eventTypes.contains(.control) && (byte != 00 || byte != 32) { skipTrain = true continue } else if !settings.eventTypes.contains(.programChange) && (byte == 00 || byte == 32) { skipTrain = true continue } if controlByteSelector == false { controlNumber = byte controlByteSelector = true } // We process two values controls ( number < 64 ) else if controlNumber < 120 { if controlNumber < 64 { controlByteSelector = false if controlNumber >= 32 && controlNumber < 64 && filterState.lsbValue == 0xFF { filterState.lsbValue = byte } else if controlNumber >= 0 && controlNumber < 32 && filterState.msbValue == 0xFF { filterState.msbValue = byte } if filterState.msbValue != 0xFF && filterState.lsbValue != 0xFF { if controlNumber == 0 || controlNumber == 32 { let shiftedMSB = settings.limitTo127Banks ? 0 : Int16(filterState.msbValue << 7) let bankNumber = shiftedMSB | Int16(filterState.lsbValue) filterState.lsbValue = 0xFF filterState.msbValue = 0xFF filterState.bank.values[Int(channel)] = bankNumber } } } else { output.controlValues.controlStates[Int(channel)].values[Int(controlNumber)] = Int16(byte) controlNumber = 0 } } } else { // If a control in the 0..63 range has been caught without msb or lsb, we store the value if controlNumber > 0 { output.controlValues.controlStates[Int(channel)].values[Int(controlNumber)] = Int16(byte) controlNumber = 0 } } // filter events if !settings.eventTypes.contains(rawEventType: type) { skipTrain = true continue } // filter channel if (settings.channels & (0x0001 << channel)) == 0 { skipTrain = true continue } // 4 - So far so good, now we are in potentially kept events data. // We only filter notes switch type { // 2 data byte events // If we deal with noteOns, then we filter range and velocity case MidiEventType.noteOn.rawValue: // Check if current byte is note or velocity if byteSelector { if !skipNote { skipNote = byte < settings.velocityRange.lower || byte > settings.velocityRange.higher // Still not skip the note, we count it if !skipNote { // Transpose note = Int16(data1) if settings.globalTranspose != 0 { note = note + settings.globalTranspose } if settings.channelsTranspose.transpose[Int(channel)] != 0 { note = note + settings.channelsTranspose.transpose[Int(channel)] } if note <= 0 { data1 = 0 } else if note >= 127 { data1 = 127 } else { data1 = UInt8(note) } // Record higher and lower notes if settings.tracksHigherAndLowerNotes { if data1 < output.higherAndLowerNotes[Int(channel)].lower { output.higherAndLowerNotes[Int(channel)].lower = data1 } if data1 > output.higherAndLowerNotes[Int(channel)].higher { output.higherAndLowerNotes[Int(channel)].higher = data1 } } // --- WRITE ---- if writePacketsToOutput { if !wroteStatus { wroteStatus = true writeByte(byte: (currentStatus & 0xF0) | (settings.channelsMap.channels[Int(channel)] & 0x0F)) } writeByte(byte: data1) writeByte(byte: byte) } if let tap = eventsTap { tap(MidiEvent(type: .noteOn, timestamp: p.timeStamp, channel: settings.channelsMap.channels[Int(channel)] & 0x0F, value1: data1, value2: byte)) } if let mib = midiInputBuffer { mib.addNoteOn(pitch: data1, velocity: byte) } // ------------- } else { // reset skipNote for the next note skipNote = false } } else { // reset skipNote for the next note skipNote = false } // Next byte will be note number byteSelector = false } else { skipNote = byte < settings.noteRange.lower || byte > settings.noteRange.higher // Will be written if velocity is accepted data1 = byte // Next byte will be velocity byteSelector = true } case MidiEventType.noteOff.rawValue: // Check if current byte is note or velocity ( no meaning on note off, but still there ) if byteSelector { // Transpose note = Int16(data1) if settings.globalTranspose != 0 { note = note + settings.globalTranspose } if settings.channelsTranspose.transpose[Int(channel)] != 0 { note = note + settings.channelsTranspose.transpose[Int(channel)] } if note <= 0 { data1 = 0 } else if note >= 127 { data1 = 127 } else { data1 = UInt8(note) } // --- WRITE ---- if writePacketsToOutput { if !wroteStatus { wroteStatus = true writeByte(byte: (currentStatus & 0xF0) | (settings.channelsMap.channels[Int(channel)] & 0x0F)) } writeByte(byte: data1) writeByte(byte: byte) } // ------------- if let tap = eventsTap { tap(MidiEvent(type: .noteOff, timestamp: p.timeStamp, channel: settings.channelsMap.channels[Int(channel)] & 0x0F, value1: data1, value2: byte)) } if let mib = midiInputBuffer { mib.addNoteOff(pitch: data1, velocity: byte) } byteSelector = false } else { data1 = byte byteSelector = true } case MidiEventType.control.rawValue: // Check if current byte is control number or value if byteSelector { // --- WRITE ---- if writePacketsToOutput { if !wroteStatus { wroteStatus = true writeByte(byte: (currentStatus & 0xF0) | (settings.channelsMap.channels[Int(channel)] & 0x0F)) } writeByte(byte: data1) writeByte(byte: byte) } // ------------- byteSelector = false } else { data1 = byte byteSelector = true } case MidiEventType.pitchBend.rawValue: // Check if current byte is control number or value if byteSelector { // --- WRITE ---- if writePacketsToOutput { if !wroteStatus { wroteStatus = true writeByte(byte: (currentStatus & 0xF0) | (settings.channelsMap.channels[Int(channel)] & 0x0F)) } writeByte(byte: data1) writeByte(byte: byte) } // ------------- output.pitchBend.values[Int(channel)] = ( Int16(data1) + Int16(byte) << 7) byteSelector = false } else { data1 = byte byteSelector = true } case MidiEventType.polyAfterTouch.rawValue: if byteSelector { // --- WRITE ---- if writePacketsToOutput { if !wroteStatus { wroteStatus = true writeByte(byte: (currentStatus & 0xF0) | (settings.channelsMap.channels[Int(channel)] & 0x0F)) } writeByte(byte: data1) writeByte(byte: byte) } // ------------- byteSelector = false } else { data1 = byte byteSelector = true } // 1 data byte events case MidiEventType.afterTouch.rawValue: // --- WRITE ---- if writePacketsToOutput { if !wroteStatus { wroteStatus = true writeByte(byte: (currentStatus & 0xF0) | (settings.channelsMap.channels[Int(channel)] & 0x0F)) } writeByte(byte: byte) } // ------------- case MidiEventType.programChange.rawValue: output.programChanges.values[Int(channel)] = Int16(byte) // --- WRITE ---- if writePacketsToOutput { if !wroteStatus { wroteStatus = true writeByte(byte: (currentStatus & 0xF0) | (settings.channelsMap.channels[Int(channel)] & 0x0F)) } writeByte(byte: byte) } // ------------- // 0 data byte events case MidiEventType.realTimeMessage.rawValue: break default: break } // End switch } // End scan } // If a controlNumber that potentially takes 2 bytes is set and has not be completed, we store the value if controlNumber > 0 && controlNumber < 64 { output.controlValues.controlStates[Int(channel)].values[Int(controlNumber)] = Int16(byte) controlNumber = 0 } // Go to next packet ( should never happen for musical events ) p = MIDIPacketNext(&p).pointee } if let mib = midiInputBuffer, let tap = midiInputBufferTap { tap(mib) } } MIDIPacketListAdd(&outPackets, Int(14 + dataSize), writePacketPtr, output.timeStamp, Int(dataSize), targetBytes) output.bankSelect = filterState.bank output.filteringTime = -chrono.timeIntervalSinceNow output.packets = outPackets return output } }
0
// // AUIBar.swift // AppUIKit // // Created by Jae Young Choi on 2017. 1. 30.. // Copyright © 2017년 appcid. All rights reserved. // import Cocoa open class AUIBar: AUIView { let contentView = AUIView() open var barTintColor: NSColor? { didSet { invalidateBackground() } } open var barStyle: AUIBarStyle = .default { didSet { invalidateBackground() } } var backgroundEffectColor: VibrantColor { if let barTintColor = barTintColor { return VibrantColor.color(barTintColor.darkenColor) } else if barStyle == .black { return VibrantColor.vibrantDark } else { return VibrantColor.vibrantLight } } func invalidateBackground() { removeVisualEffectView() switch backgroundEffectColor { case .color(let color): backgroundColor = color case .vibrantLight: backgroundColor = NSColor.white.withAlphaComponent(0.75) let visualEffectView = NSVisualEffectView() visualEffectView.appearance = NSAppearance(named: NSAppearance.Name.vibrantLight) visualEffectView.blendingMode = .withinWindow addSubview(visualEffectView, positioned: .below, relativeTo: contentView) visualEffectView.fillToSuperview() case .vibrantDark: backgroundColor = NSColor.clear let visualEffectView = NSVisualEffectView() visualEffectView.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark) visualEffectView.blendingMode = .withinWindow visualEffectView.material = .ultraDark addSubview(visualEffectView, positioned: .below, relativeTo: contentView) visualEffectView.fillToSuperview() } } func removeVisualEffectView() { for subview in subviews { if let vev = subview as? NSVisualEffectView { vev.removeFromSuperview() } } } }
0
// // XUCloudKitDeviceRegistry.swift // XUCore // // Created by Charlie Monroe on 3/9/18. // Copyright © 2018 Charlie Monroe Software. All rights reserved. // import CloudKit import Foundation #if os(iOS) import UIKit // For UIDevice #endif /// Class that registers the device in iCloud as Synchronized Device. It also keeps /// the subscription. @available(iOSApplicationExtension, unavailable) internal class XUCloudKitDeviceRegistry { /// A subscription ID. Each document has its own subscription which is encoded /// in the ID. This structure allows encoding it forth and back. struct SubscriptionID: RawRepresentable { /// Device ID. let deviceID: String /// Document ID. let documentID: String /// Raw value of the subscription ID. let rawValue: String init?(rawValue: String) { let regex = "XU_SYNC_SUBSCRIPTION_(?P<DOC>.*)_DEVICE_(?P<DEVICE>.*)" guard let documentID = rawValue.value(of: "DOC", inRegex: regex), let deviceID = rawValue.value(of: "DEVICE", inRegex: regex) else { XULog("Can't decode subscription ID with raw value \(rawValue).") return nil } self.rawValue = rawValue self.deviceID = deviceID self.documentID = documentID } /// Initialize from documentID and deviceID. init(documentID: String, deviceID: String = XUSyncManagerPathUtilities.currentDeviceIdentifier) { self.rawValue = "XU_SYNC_SUBSCRIPTION_\(documentID)_DEVICE_\(deviceID)" self.deviceID = deviceID self.documentID = documentID } } /// Database. let database: CKDatabase /// Document ID. let documentID: String /// Marked as true when we find the device in iCloud. private(set) var isRegistered: Bool = false { didSet { if self.isRegistered { self._checkSubscription() } } } /// Zone. let recordZone: CKRecordZone /// Subscription ID. let subscriptionID: String init(database: CKDatabase, recordZone: CKRecordZone, documentID: String) { self.database = database self.documentID = documentID self.recordZone = recordZone self.subscriptionID = SubscriptionID(documentID: documentID).rawValue self.register() } private func _checkDeviceExistence() { let query = CKQuery(recordType: XUCloudKitSynchronization.SynchronizedDevice.recordType, predicate: NSPredicate(format: "uuid == %@", XUSyncManagerPathUtilities.currentDeviceIdentifier)) self.database.perform(query, inZoneWith: self.recordZone.zoneID) { (records, error) in if let error = error { XULog("Failed to fetch current device from CloudKit: \(error).") } else { XULog("Found device records: \(records.descriptionWithDefaultValue())") self.isRegistered = !records.isNilOrEmpty if !self.isRegistered { self._registerDevice() } } } } private func _checkSubscription() { XULog("Checking subscription.") self.database.fetch(withSubscriptionID: self.subscriptionID) { (subscriptionOptional, errorOptional) in if let subscription = subscriptionOptional { XULog("Already subscribed to: \(subscription)") } else if let error = errorOptional, (error as NSError).code != CKError.unknownItem.rawValue { XULog("Could not list subscription: \(error)") } else { XULog("Not subscribed, subscribing.") self._subscribeToChanges() } } } /// Actually registers self. private func _registerDevice() { let record = CKRecord(recordType: XUCloudKitSynchronization.SynchronizedDevice.recordType, recordID: CKRecord.ID(zoneID: self.recordZone.zoneID)) #if os(macOS) record["name"] = (Host.current().localizedName ?? "unknown") as NSString #else record["name"] = UIDevice.current.name as NSString #endif record["uuid"] = XUSyncManagerPathUtilities.currentDeviceIdentifier as NSString self.database.save(record) { (record, error) in if let error = error { XULog("Failed to register current device with CloudKit: \(error).") } else if let record = record { XULog("Register current device with CloudKit: \(record).") self.isRegistered = true } else { XULog("Both record and error are nil... ¯\\_(ツ)_/¯") } } } private func _registerZone() { let zoneOperation = CKModifyRecordZonesOperation(recordZonesToSave: [self.recordZone], recordZoneIDsToDelete: nil) zoneOperation.modifyRecordZonesCompletionBlock = { (zonesAdded, _, errorOptional) in if let error = errorOptional { XULog("Failed to create zone in CloudKit: \(error).") } else { XULog("Created zones: \(zonesAdded.descriptionWithDefaultValue())") self._registerDevice() } } self.database.add(zoneOperation) } private func _subscribeToChanges() { let predicate = NSPredicate(format: "documentID = %@ AND deviceID != %@", self.documentID, XUSyncManagerPathUtilities.currentDeviceIdentifier) let subscription = CKQuerySubscription(recordType: XUCloudKitSynchronization.ChangeSet.recordType, predicate: predicate, subscriptionID: self.subscriptionID, options: CKQuerySubscription.Options.firesOnRecordCreation) let info = CKSubscription.NotificationInfo() subscription.notificationInfo = info self.database.save(subscription) { (subscriptionOptional, errorOptional) in if let subscription = subscriptionOptional { XULog("Successfully subscribed: \(subscription)") } else { XULog("Could not subscribe: \(errorOptional.descriptionWithDefaultValue())") } } } /// Registers self in the CloudKit if necessary. func register() { guard !self.isRegistered else { return } self.database.fetch(withRecordZoneID: self.recordZone.zoneID, completionHandler: { (zone, errorOptional) in if let error = errorOptional, (error as NSError).code != CKError.zoneNotFound.rawValue { XULog("Failed to fetch zones from CloudKit: \(error).") } else { XULog("Found zone: \(zone.descriptionWithDefaultValue())") if zone != nil { self._checkDeviceExistence() } else { self._registerZone() } } }) } }
0
// // FavoritesView.swift // iosApp // // Created by Zsolt Boldizsar on 9/10/20. // Copyright © 2020 Halcyon Mobile. All rights reserved. // import SwiftUI import common struct FavoritesView: View { @ObservedObject var state: FavoritesState init() { state = FavoritesState() } var body: some View { NavigationView { StatefulView(state: state.state, error: { PlaceholderView(message: MR.strings().general_error.localize()) { state.viewModel.loadFavourites() } }, empty: { EmptyView() }, content: { List(state.favourites, id: \.id){ favourite in NavigationLink(destination: ApplicationDetailView(applicationId: favourite.id)){ ApplicationView(application: favourite) } } }) .navigationTitle(MR.strings().favourites.localize()) } } } struct FavoritesView_Previews: PreviewProvider { static var previews: some View { FavoritesView() } }
0
/* * -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose"> * Copyright (c) 2020 Aspose.Slides for Cloud * </copyright> * <summary> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * </summary> * -------------------------------------------------------------------------------------------------------------------- */ import Foundation /** Save slide task. */ public class Save: Task { public enum Format: String, Codable { case pdf = "Pdf" case xps = "Xps" case tiff = "Tiff" case pptx = "Pptx" case odp = "Odp" case otp = "Otp" case ppt = "Ppt" case pps = "Pps" case ppsx = "Ppsx" case pptm = "Pptm" case ppsm = "Ppsm" case pot = "Pot" case potx = "Potx" case potm = "Potm" case html = "Html" case swf = "Swf" case svg = "Svg" case jpeg = "Jpeg" case png = "Png" case gif = "Gif" case bmp = "Bmp" case fodp = "Fodp" } /** Format. */ public var format: Format? /** Output file. */ public var output: OutputFile? /** Save options. */ public var options: ExportOptions? private enum CodingKeys: String, CodingKey { case format case output case options } public init(type: ModelType? = nil, format: Format? = nil, output: OutputFile? = nil, options: ExportOptions? = nil) { super.init(type: type) self.format = format self.output = output self.options = options } required init(from decoder: Decoder) throws { try super.init(from: decoder) let values = try decoder.container(keyedBy: CodingKeys.self) format = try values.decode(Format?.self, forKey: .format) output = try values.decode(OutputFile?.self, forKey: .output) options = try values.decode(ExportOptions?.self, forKey: .options) } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(format, forKey: .format) try container.encode(output, forKey: .output) try container.encode(options, forKey: .options) } }
0
/* Copyright 2021 macoonshine Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation /** encapsulates dates for encoding and decoding. */ public struct Timestamp: Codable, CustomStringConvertible { private static let formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] return formatter }() public let date: Date public init() { self.init(date: Date()) } public init(date: Date) { self.date = date } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let value = try container.decode(String.self) if let date = Self.formatter.date(from: value) { self.date = date } else { throw CocoaError(.formatting) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(description) } public var description: String { return Self.formatter.string(from: date) } }
0
// // CountriesCachingManager.swift // iOS_Bootstrap_Example // // Created by Ahmad Mahmoud on 12/15/18. // Copyright © 2018 CocoaPods. All rights reserved. // import iOS_Bootstrap import CoreData import RxSwift @available(iOS 10.0, *) class CountriesCachingManager: CoreDataManager<CountryEntity> {}
0
// Logger.swift // Copyright (c) 2017 Nyx0uf // // 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 final class Logger { class func dlog(_ items: Any..., separator: String = " ", terminator: String = "\n", _ file: String = #file, _ function: String = #function, _ line: Int = #line) { #if NYX_DEBUG let stringItem = items.map{"\($0)"}.joined(separator: separator) Swift.print("[\(function)]:\(line) \(stringItem)", terminator: terminator) #endif } class func alog(_ items: Any..., separator: String = " ", terminator: String = "\n", _ file: String = #file, _ function: String = #function, _ line: Int = #line) { let stringItem = items.map{"\($0)"}.joined(separator: separator) Swift.print("\(stringItem)", terminator: terminator) } }
0
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let start = [Void{ if true { protocol c { class case c,
0
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse print(Any) { } struct c { class a(start: T A")) func a<l : a {
0
// // BaseSegmentedViewController.swift // SwiftLeeTools_Example // // Created by 李桂盛 on 2019/11/30. // Copyright © 2019 李桂盛. All rights reserved. // import UIKit import JXSegmentedView //MARK:-数据源类型 public enum DataSourceType { case title //纯文字 case titleAndImage //文字和图片 case dot//红点 case number//数字 } //MARK:-指示器类型 public enum IndicatorType { case line //固定宽 case autoLine //同cell等宽 case lengthen //延长 } open class BaseSegmentedViewController: BaseUIViewViewController { open var dataSourceType:DataSourceType = .title open var indicatorType:IndicatorType = .line private var jxSegmentedBaseDataSource:JXSegmentedBaseDataSource! private var jxSegmentedIndicatorBaseView:JXSegmentedIndicatorBaseView! open var titleSelectedColor:UIColor = .black open var indicatorColor:UIColor = .black open var segmentTitles:[String] = [] open var segmentImages:[String] = [] open var dotStates:[Bool] = [] open var numbers:[Int] = [] open var indicatorWidth:CGFloat = 20 private let segmentedView = JXSegmentedView() open var listContainViewControllerStringArr:[String] = [] lazy var listContainerView: JXSegmentedListContainerView! = { return JXSegmentedListContainerView(dataSource: self) }() override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //处于第一个item的时候,才允许屏幕边缘手势返回 navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0) setupSegmentConfig() } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) //离开页面的时候,需要恢复屏幕边缘手势,不能影响其他页面 navigationController?.interactivePopGestureRecognizer?.isEnabled = true } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() segmentedView.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 50) listContainerView.frame = CGRect(x: 0, y: 50, width: view.bounds.size.width, height: view.bounds.size.height - 50) } override open func viewDidLoad() { super.viewDidLoad() } open func setupSegmentConfig(){ switch self.dataSourceType { case .title: let dataSource = JXSegmentedTitleDataSource() dataSource.titleSelectedColor = titleSelectedColor dataSource.isTitleZoomEnabled = true dataSource.titleSelectedZoomScale = 1.3 dataSource.titles = segmentTitles self.jxSegmentedBaseDataSource = dataSource case .titleAndImage: let dataSource = JXSegmentedTitleImageDataSource() dataSource.titleSelectedColor = titleSelectedColor dataSource.isTitleColorGradientEnabled = true dataSource.titles = segmentTitles dataSource.titleImageType = .rightImage dataSource.isImageZoomEnabled = true dataSource.normalImageInfos = segmentImages dataSource.loadImageClosure = {(imageView, normalImageInfo) in //如果normalImageInfo传递的是图片的地址,你需要借助SDWebImage等第三方库进行图片加载。 //加载bundle内的图片,就用下面的方式,内部默认也采用该方法。 imageView.image = UIImage(named: normalImageInfo) } self.jxSegmentedBaseDataSource = dataSource case .dot: let dataSource = JXSegmentedDotDataSource() dataSource.titleSelectedColor = titleSelectedColor dataSource.isTitleColorGradientEnabled = true dataSource.titles = segmentTitles dataSource.dotStates = dotStates self.jxSegmentedBaseDataSource = dataSource case .number: let dataSource = JXSegmentedNumberDataSource() dataSource.titleSelectedColor = titleSelectedColor dataSource.isTitleColorGradientEnabled = true dataSource.titles = segmentTitles dataSource.numbers = numbers dataSource.numberStringFormatterClosure = {(number) -> String in if number > 999 { return "999+" } return "\(number)" } self.jxSegmentedBaseDataSource = dataSource } switch self.indicatorType { case .line: let indicator = JXSegmentedIndicatorLineView() indicator.indicatorWidth = indicatorWidth indicator.indicatorColor = indicatorColor self.jxSegmentedIndicatorBaseView = indicator case .autoLine: let indicator = JXSegmentedIndicatorLineView() indicator.indicatorWidth = JXSegmentedViewAutomaticDimension indicator.indicatorColor = indicatorColor self.jxSegmentedIndicatorBaseView = indicator case .lengthen: let indicator = JXSegmentedIndicatorLineView() indicator.indicatorWidth = JXSegmentedViewAutomaticDimension indicator.lineStyle = .lengthen indicator.indicatorColor = indicatorColor self.jxSegmentedIndicatorBaseView = indicator } segmentedView.dataSource = self.jxSegmentedBaseDataSource segmentedView.delegate = self baseView.addSubview(segmentedView) segmentedView.listContainer = listContainerView baseView.addSubview(listContainerView) segmentedView.indicators = [jxSegmentedIndicatorBaseView] } } extension BaseSegmentedViewController: JXSegmentedViewDelegate { public func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) { if let dotDataSource = jxSegmentedBaseDataSource as? JXSegmentedDotDataSource { //先更新数据源的数据 dotDataSource.dotStates[index] = false //再调用reloadItem(at: index) segmentedView.reloadItem(at: index) } navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0) } } extension BaseSegmentedViewController: JXSegmentedListContainerViewDataSource { public func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int { if let titleDataSource = segmentedView.dataSource as? JXSegmentedBaseDataSource { return titleDataSource.dataSource.count } return 0 } public func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate { let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String guard let viewcontrollerType = NSClassFromString(namespace + "." + listContainViewControllerStringArr[index]) as? BaseUIViewViewController.Type else{ return BaseUIViewViewController() } let viewcontroller = viewcontrollerType.init() return viewcontroller } }
0
// // ContactsViewController.swift // PhoneBook // // Created by Sameer Khavanekar on 6/23/18. // Copyright © 2018 Sameer Khavanekar. All rights reserved. // import UIKit class ContactsViewController: UIViewController { @IBOutlet weak var contactTableView: UITableView! private var _contacts: [] } extension ContactsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { <#code#> } }
0
// // WebRTCService.swift // WebRTC // // Created by Zaporozhchenko Oleksandr on 4/25/20. // Copyright © 2020 maxatma. All rights reserved. // import WebRTC final class WebRTCClient: NSObject { private static let factory: RTCPeerConnectionFactory = { RTCInitializeSSL() let videoEncoderFactory = RTCDefaultVideoEncoderFactory() let codec = RTCVideoCodecInfo(name: "VP8") // this is coz ios 13.3.1 screen is red videoEncoderFactory.preferredCodec = codec let videoDecoderFactory = RTCDefaultVideoDecoderFactory() videoDecoderFactory.createDecoder(codec) return RTCPeerConnectionFactory(encoderFactory: videoEncoderFactory, decoderFactory: videoDecoderFactory) }() weak var delegate: WebRTCClientDelegate? var peerConnection: RTCPeerConnection! let rtcAudioSession = RTCAudioSession.sharedInstance() private let mediaConstrains = [kRTCMediaConstraintsOfferToReceiveAudio: kRTCMediaConstraintsValueTrue, kRTCMediaConstraintsOfferToReceiveVideo: kRTCMediaConstraintsValueTrue] private var videoCapturer: RTCVideoCapturer? private var localVideoTrack: RTCVideoTrack? private var localAudioTrack: RTCAudioTrack? private var remoteVideoTrack: RTCVideoTrack? private let config: RTCConfiguration! private let constraints = RTCMediaConstraints(optional: ["DtlsSrtpKeyAgreement": kRTCMediaConstraintsValueTrue]) //MARK: - Initialize @available(*, unavailable) override init() { fatalError("WebRTCService init is unavailable") } convenience init(iceServers: [String]) { let config = RTCConfiguration() config.iceServers = [RTCIceServer(urlStrings: iceServers)] config.sdpSemantics = .unifiedPlan config.continualGatheringPolicy = .gatherContinually self.init(config: config) } init(config: RTCConfiguration) { self.config = config super.init() createMediaSenders() configureAudioSession() startCall() } // MARK:- Signaling func offer(completion: @escaping (_ sdp: RTCSessionDescription) -> Void) { print("WebRTCClient offer") let constrains = RTCMediaConstraints(mandatoryConstraints: mediaConstrains, optionalConstraints: nil) peerConnection.offer(for: constrains) { sdp, error in guard let sdp = sdp else { print("WebRTCService offer no sdp, error ", error) return } self.peerConnection.setLocalDescription(sdp) { error in if let error = error { print("WebRTCService setLocalDescription error ", error) return } completion(sdp) } } } func answer(completion: @escaping (_ sdp: RTCSessionDescription) -> Void) { print("WebRTCClient answer") let constrains = RTCMediaConstraints(mandatoryConstraints: mediaConstrains, optionalConstraints: nil) peerConnection.answer(for: constrains) { sdp, error in guard let sdp = sdp else { print("WebRTCService answer no sdp ") return } self.peerConnection.setLocalDescription(sdp) { error in if let error = error { print("WebRTCService setLocalDescription error ", error) return } completion(sdp) } } } func set(remoteSdp: RTCSessionDescription, completion: @escaping (Error?) -> ()) { peerConnection.setRemoteDescription(remoteSdp, completionHandler: completion) } func set(remoteCandidate: RTCIceCandidate) { peerConnection.add(remoteCandidate) } var localRenderer: RTCVideoRenderer! func change(localVideoSource: LocalVideoSource) { change(localVideoSource: localVideoSource, renderer: localRenderer) } func change(localVideoSource: LocalVideoSource, renderer: RTCVideoRenderer) { print("change local source") self.localVideoSource = localVideoSource switch localVideoSource { case .camera: startCaptureLocalCameraVideo(renderer: renderer) case let .file(name): startCaptureLocalVideoFile(name: name, renderer: renderer) } } var localVideoSource: LocalVideoSource! enum LocalVideoSource { case camera case file(name: String) } // MARK: - Media public func startCaptureLocalCameraVideo(renderer: RTCVideoRenderer) { print("startCaptureLocalCameraVideo") localRenderer = renderer stopLocalCapture() videoCapturer = RTCCameraVideoCapturer(delegate: videoSource) guard let capturer = videoCapturer as? RTCCameraVideoCapturer else { print("WebRTCService can't get capturer") return } guard let frontCamera = (RTCCameraVideoCapturer.captureDevices().first { $0.position == .front }), // choose highest res let format = (RTCCameraVideoCapturer.supportedFormats(for: frontCamera).sorted { (f1, f2) -> Bool in let width1 = CMVideoFormatDescriptionGetDimensions(f1.formatDescription).width let width2 = CMVideoFormatDescriptionGetDimensions(f2.formatDescription).width return width1 < width2 }).last, // choose highest fps let frameRateRange = (format.videoSupportedFrameRateRanges.sorted { return $0.maxFrameRate < $1.maxFrameRate }.last) else { print("WebRTCService can't get frontCamera") return } let fps = Int(frameRateRange.maxFrameRate) capturer.startCapture(with: frontCamera, format: format, fps: fps) localVideoTrack?.add(renderer) } public func startCaptureLocalVideoFile(name: String, renderer: RTCVideoRenderer) { print("startCaptureLocalVideoFile") stopLocalCapture() localRenderer = renderer videoCapturer = RTCFileVideoCapturer(delegate: videoSource) guard let capturer = videoCapturer as? RTCFileVideoCapturer else { print("WebRTCService can't get capturer") return } capturer.startCapturing(fromFileNamed: name) { error in print("startCapturing error ", error) return } localVideoTrack?.add(renderer) } private func stopLocalCapture() { if let capt = videoCapturer as? RTCCameraVideoCapturer { capt.stopCapture() } if let capt = videoCapturer as? RTCFileVideoCapturer { capt.stopCapture() } } func renderRemoteVideo(to renderer: RTCVideoRenderer) { remoteVideoTrack?.add(renderer) } func startCall() { print("WebRTCService startCall") peerConnection = Self.factory.peerConnection(with: config, constraints: constraints, delegate: nil) let streamID = "stream" peerConnection.add(localAudioTrack!, streamIds: [streamID]) peerConnection.add(localVideoTrack!, streamIds: [streamID]) peerConnection.delegate = self remoteVideoTrack = peerConnection.transceivers .first { $0.mediaType == .video }? .receiver .track as? RTCVideoTrack } func hangup() { print("WebRTCService hangup") peerConnection.close() } //MARK: - Private private func configureAudioSession() { rtcAudioSession.lockForConfiguration() do { try rtcAudioSession.setCategory(AVAudioSession.Category.playAndRecord.rawValue) try rtcAudioSession.setMode(AVAudioSession.Mode.voiceChat.rawValue) } catch let error { debugPrint("WebRTCService Error changeing AVAudioSession category: \(error)") } rtcAudioSession.unlockForConfiguration() } private func createMediaSenders() { localAudioTrack = createAudioTrack() localVideoTrack = createVideoTrack() } private func createAudioTrack() -> RTCAudioTrack { let audioConstrains = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil) let audioSource = WebRTCClient.factory.audioSource(with: audioConstrains) let audioTrack = WebRTCClient.factory.audioTrack(with: audioSource, trackId: "audio0") return audioTrack } private let videoSource = WebRTCClient.factory.videoSource() private func createVideoTrack() -> RTCVideoTrack { let videoTrack = WebRTCClient.factory.videoTrack(with: videoSource, trackId: "video0") return videoTrack } } extension RTCMediaConstraints { convenience init(constraints mandatory: [String : String]? = nil, optional: [String : String]? = nil) { self.init(mandatoryConstraints: mandatory, optionalConstraints: optional) } }
0
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // // swiftlint:disable all import Amplify import Foundation public struct User5: Model { public let id: String public var username: String public var posts: List<PostEditor5>? public init(id: String = UUID().uuidString, username: String, posts: List<PostEditor5>? = []) { self.id = id self.username = username self.posts = posts } }
0
// Copyright DApps Platform Inc. All rights reserved. import UIKit import Kingfisher protocol EditTokenTableViewCellDelegate: class { func didChangeState(state: Bool, in cell: EditTokenTableViewCell) } final class EditTokenTableViewCell: UITableViewCell { @IBOutlet weak var tokenImageView: TokenImageView! @IBOutlet weak var tokenLabel: UILabel! @IBOutlet weak var tokenEnableSwitch: UISwitch! @IBOutlet weak var tokenContractLabel: UILabel! weak var delegate: EditTokenTableViewCellDelegate? var viewModel: EditTokenTableCellViewModel? { didSet { guard let viewModel = viewModel else { return } tokenLabel.text = viewModel.title tokenLabel.font = viewModel.titleFont tokenLabel.textColor = viewModel.titleTextColor tokenEnableSwitch.isOn = viewModel.isEnabled tokenEnableSwitch.isHidden = viewModel.isSwitchHidden tokenContractLabel.text = viewModel.contractText tokenContractLabel.isHidden = viewModel.isTokenContractLabelHidden tokenImageView.kf.setImage( with: viewModel.imageUrl, placeholder: viewModel.placeholderImage ) } } override func layoutSubviews() { super.layoutSubviews() updateSeparatorInset() } private func updateSeparatorInset() { separatorInset = UIEdgeInsets( top: 0, left: layoutInsets.left + EditTokenStyleLayout.sideMargin + EditTokenStyleLayout.preferedImageSize + EditTokenStyleLayout.sideMargin, bottom: 0, right: 0 ) } @IBAction func didChangeSwitch(_ sender: UISwitch) { delegate?.didChangeState(state: sender.isOn, in: self) } }
0
// // Created by Martin Anderson on 2019-03-10. // import HealthKit extension String: LocalizedError { public var errorDescription: String? { return self } } extension HKSampleType { public static func fromDartType(type: String) -> (sampleType: HKSampleType?, unit: HKUnit)? { switch type { case "heart_rate": return ( HKSampleType.quantityType(forIdentifier: .heartRate), HKUnit.init(from: "count/min") ) case "step_count": return ( HKSampleType.quantityType(forIdentifier: .stepCount), HKUnit.count() ) case "stand_time": if #available(iOS 13.0, *) { return ( HKSampleType.quantityType(forIdentifier: .appleStandTime), HKUnit.minute() ) } else { return nil } case "exercise_time": if #available(iOS 9.3, *) { return ( HKSampleType.quantityType(forIdentifier: .appleExerciseTime), HKUnit.minute() ) } else { return nil } case "height": return ( HKSampleType.quantityType(forIdentifier: .height), HKUnit.meter() ) case "weight": return ( HKSampleType.quantityType(forIdentifier: .bodyMass), HKUnit.gramUnit(with: .kilo) ) case "distance": return ( HKSampleType.quantityType(forIdentifier: .distanceWalkingRunning), HKUnit.meter() ) case "energy": return ( HKSampleType.quantityType(forIdentifier: .activeEnergyBurned), HKUnit.kilocalorie() ) case "water": if #available(iOS 9, *) { return ( HKSampleType.quantityType(forIdentifier: .dietaryWater), HKUnit.liter() ) } else { return nil } case "sleep": return ( HKSampleType.categoryType(forIdentifier: .sleepAnalysis), HKUnit.minute() // this is ignored ) case "mindfullness": if #available(iOS 10, *) { return ( HKSampleType.categoryType(forIdentifier: .mindfulSession), HKUnit.minute() ) } else { return nil } default: return nil } } } public struct UnsupportedError: Error { let message: String }
0
// Copyright 2019 Algorand, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // NodeSettingsHeaderView.swift import UIKit class NodeSettingsHeaderView: BaseView { private let layout = Layout<LayoutConstants>() private lazy var imageView = UIImageView(image: img("icon-settings-node")) private(set) lazy var titleLabel: UILabel = { UILabel() .withAttributedText("node-settings-subtitle".localized.attributed([.lineSpacing(1.2)])) .withFont(UIFont.font(withWeight: .medium(size: 16.0))) .withTextColor(Colors.Text.primary) .withAlignment(.center) .withLine(.contained) }() override func prepareLayout() { setupImageViewLayout() setupTitleLabelLayout() } } extension NodeSettingsHeaderView { private func setupImageViewLayout() { addSubview(imageView) imageView.snp.makeConstraints { make in make.top.equalToSuperview().inset(layout.current.imageTopInset) make.centerX.equalToSuperview() make.size.equalTo(layout.current.imageSize) } } private func setupTitleLabelLayout() { addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.top.equalTo(imageView.snp.bottom).offset(layout.current.titleTopInset) make.leading.trailing.equalToSuperview().inset(layout.current.horizontalInset) } } } extension NodeSettingsHeaderView { private struct LayoutConstants: AdaptiveLayoutConstants { let imageTopInset: CGFloat = 50.0 let imageSize = CGSize(width: 48.0, height: 48.0) let titleTopInset: CGFloat = 16.0 let horizontalInset: CGFloat = 32.0 let topInset: CGFloat = 26.0 } }
0
// // QuranViewController.swift // Quran // // Created by Mohamed Afifi on 4/28/16. // Copyright © 2016 Quran.com. All rights reserved. // import UIKit import KVOController_Swift private let cellReuseId = "cell" class QuranViewController: UIViewController, AudioBannerViewPresenterDelegate { let persistence: SimplePersistence let dataRetriever: AnyDataRetriever<[QuranPage]> let pageDataSource: QuranPagesDataSource let audioViewPresenter: AudioBannerViewPresenter let qarisControllerCreator: AnyCreator<QariTableViewController> let scrollToPageToken = Once() let didLayoutSubviewToken = Once() init(persistence: SimplePersistence, imageService: QuranImageService, dataRetriever: AnyDataRetriever<[QuranPage]>, ayahInfoRetriever: AyahInfoRetriever, audioViewPresenter: AudioBannerViewPresenter, qarisControllerCreator: AnyCreator<QariTableViewController>) { self.persistence = persistence self.dataRetriever = dataRetriever self.audioViewPresenter = audioViewPresenter self.qarisControllerCreator = qarisControllerCreator self.pageDataSource = QuranPagesDataSource(reuseIdentifier: cellReuseId, imageService: imageService, ayahInfoRetriever: ayahInfoRetriever) super.init(nibName: nil, bundle: nil) audioViewPresenter.delegate = self automaticallyAdjustsScrollViewInsets = false // page behavior let pageBehavior = ScrollViewPageBehavior() pageDataSource.scrollViewDelegate = pageBehavior observe(retainedObservable: pageBehavior, keyPath: "currentPage", options: [.New]) { [weak self] (observable, change: ChangeData<Int>) in self?.onPageChanged() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var initialPage: Int = 0 { didSet { title = Quran.nameForSura(Quran.PageSuraStart[initialPage - 1]) } } weak var audioView: DefaultAudioBannerView? { didSet { audioView?.onTouchesBegan = { [weak self] in self?.stopBarHiddenTimer() } audioViewPresenter.view = audioView audioView?.delegate = audioViewPresenter } } weak var collectionView: UICollectionView? weak var layout: UICollectionViewFlowLayout? weak var bottomBarConstraint: NSLayoutConstraint? var timer: Timer? var statusBarHidden = false { didSet { setNeedsStatusBarAppearanceUpdate() } } override func prefersStatusBarHidden() -> Bool { return statusBarHidden || traitCollection.containsTraitsInCollection(UITraitCollection(verticalSizeClass: .Compact)) } override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return .Slide } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func loadView() { view = QuranView() createCollectionView() createAudioBanner() // hide bars on tap view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onViewTapped(_:)))) } private func createAudioBanner() { let audioView = DefaultAudioBannerView() view.addAutoLayoutSubview(audioView) view.pinParentHorizontal(audioView) bottomBarConstraint = view.addParentBottomConstraint(audioView) self.audioView = audioView } private func createCollectionView() { let layout = QuranPageFlowLayout() layout.scrollDirection = .Horizontal layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout) if #available(iOS 9.0, *) { collectionView.semanticContentAttribute = .ForceRightToLeft } view.addAutoLayoutSubview(collectionView) view.pinParentAllDirections(collectionView) collectionView.backgroundColor = UIColor.readingBackground() collectionView.pagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.registerNib(UINib(nibName: "QuranPageCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cellReuseId) collectionView.ds_useDataSource(pageDataSource) self.layout = layout self.collectionView = collectionView } override func viewDidLoad() { super.viewDidLoad() dataRetriever.retrieve { [weak self] (data: [QuranPage]) in self?.pageDataSource.items = data self?.collectionView?.reloadData() self?.scrollToFirstPage() } audioViewPresenter.onViewDidLoad() // start hidding bars timer startHiddenBarsTimer() } private var interactivePopGestureOldEnabled: Bool? override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIApplication.sharedApplication().idleTimerDisabled = true navigationController?.setNavigationBarHidden(false, animated: animated) interactivePopGestureOldEnabled = navigationController?.interactivePopGestureRecognizer?.enabled navigationController?.interactivePopGestureRecognizer?.enabled = false } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) UIApplication.sharedApplication().idleTimerDisabled = false navigationController?.interactivePopGestureRecognizer?.enabled = interactivePopGestureOldEnabled ?? true } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() didLayoutSubviewToken.once {} scrollToFirstPage() } private func scrollToFirstPage() { guard let index = pageDataSource.items.indexOf({ $0.pageNumber == initialPage }) where didLayoutSubviewToken.executed else { return } scrollToPageToken.once { let indexPath = NSIndexPath(forItem: index, inSection: 0) scrollToIndexPath(indexPath, animated: false) onPageChangedToPage(pageDataSource.itemAtIndexPath(indexPath)) } } func stopBarHiddenTimer() { timer?.cancel() timer = nil } func onViewTapped(sender: UITapGestureRecognizer) { guard let audioView = audioView where !audioView.bounds.contains(sender.locationInView(audioView)) else { return } setBarsHidden(navigationController?.navigationBarHidden == false) } private func setBarsHidden(hidden: Bool) { navigationController?.setNavigationBarHidden(hidden, animated: true) if let bottomBarConstraint = bottomBarConstraint { view.removeConstraint(bottomBarConstraint) } if let audioView = audioView { if hidden { bottomBarConstraint = view.addSiblingVerticalContiguous(top: view, bottom: audioView) } else { bottomBarConstraint = view.addParentBottomConstraint(audioView) } } UIView.animateWithDuration(0.3) { self.statusBarHidden = hidden self.view.layoutIfNeeded() } // remove the timer stopBarHiddenTimer() } private func startHiddenBarsTimer() { timer = Timer(interval: 3) { [weak self] in self?.setBarsHidden(true) } } private func scrollToIndexPath(indexPath: NSIndexPath, animated: Bool) { collectionView?.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: false) } private func onPageChanged() { guard let page = currentPage() else { return } onPageChangedToPage(page) } private func onPageChangedToPage(page: QuranPage) { updateBarToPage(page) } private func updateBarToPage(page: QuranPage) { title = Quran.nameForSura(page.startAyah.sura) // only persist if active if UIApplication.sharedApplication().applicationState == .Active { persistence.setValue(page.pageNumber, forKey: PersistenceKeyBase.LastViewedPage) Crash.setValue(page.pageNumber, forKey: .QuranPage) } } func showQariListSelectionWithQari(qaris: [Qari], selectedIndex: Int) { let controller = qarisControllerCreator.create() controller.setQaris(qaris) controller.selectedIndex = selectedIndex controller.onSelectedIndexChanged = { [weak self] index in self?.audioViewPresenter.setQariIndex(index) } controller.preferredContentSize = CGSize(width: 400, height: 500) controller.modalPresentationStyle = .Popover controller.popoverPresentationController?.delegate = self controller.popoverPresentationController?.sourceView = audioView controller.popoverPresentationController?.sourceRect = audioView?.bounds ?? CGRect.zero controller.popoverPresentationController?.permittedArrowDirections = .Down presentViewController(controller, animated: true, completion: nil) } func highlightAyah(ayah: AyahNumber) { var set = Set<AyahNumber>() set.insert(ayah) pageDataSource.highlightAyaht(set) // persist if not active guard UIApplication.sharedApplication().applicationState != .Active else { return } Queue.background.async { let page = ayah.getStartPage() self.persistence.setValue(page, forKey: PersistenceKeyBase.LastViewedPage) Crash.setValue(page, forKey: .QuranPage) } } func removeHighlighting() { pageDataSource.highlightAyaht(Set()) } func currentPage() -> QuranPage? { guard let offset = collectionView?.contentOffset, let indexPath = collectionView?.indexPathForItemAtPoint(CGPoint(x: offset.x + view.bounds.width / 2, y: 0)) else { return nil } let page = pageDataSource.itemAtIndexPath(indexPath) return page } } extension QuranViewController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .FullScreen } func presentationController(controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? { return QariNavigationController(rootViewController: controller.presentedViewController) } }
0
/* * -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose"> * Copyright (c) 2020 Aspose.Slides for Cloud * </copyright> * <summary> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * </summary> * -------------------------------------------------------------------------------------------------------------------- */ import Foundation /** Provides options that control how a presentation is saved in TIFF format. */ public class TiffExportOptions: ExportOptions { public enum Compression: String, Codable { case _default = "Default" case _none = "None" case ccitt3 = "CCITT3" case ccitt4 = "CCITT4" case lzw = "LZW" case rle = "RLE" } public enum PixelFormat: String, Codable { case format1bppIndexed = "Format1bppIndexed" case format4bppIndexed = "Format4bppIndexed" case format8bppIndexed = "Format8bppIndexed" case format24bppRgb = "Format24bppRgb" case format32bppArgb = "Format32bppArgb" } public enum NotesPosition: String, Codable { case _none = "None" case bottomFull = "BottomFull" case bottomTruncated = "BottomTruncated" } public enum CommentsPosition: String, Codable { case _none = "None" case bottom = "Bottom" case _right = "Right" } /** Compression type. */ public var compression: Compression? /** Width. */ public var width: Int? /** Height. */ public var height: Int? /** Horizontal resolution, in dots per inch. */ public var dpiX: Int? /** Vertical resolution, in dots per inch. */ public var dpiY: Int? /** Specifies whether the generated document should include hidden slides or not. Default is false. */ public var showHiddenSlides: Bool? /** Specifies the pixel format for the generated images. Read/write ImagePixelFormat. */ public var pixelFormat: PixelFormat? /** Gets or sets the position of the notes on the page. */ public var notesPosition: NotesPosition? /** Gets or sets the position of the comments on the page. */ public var commentsPosition: CommentsPosition? /** Gets or sets the width of the comment output area in pixels (Applies only if comments are displayed on the right). */ public var commentsAreaWidth: Int? /** Gets or sets the color of comments area (Applies only if comments are displayed on the right). */ public var commentsAreaColor: String? /** True if comments that have no author are displayed. (Applies only if comments are displayed). */ public var showCommentsByNoAuthor: Bool? private enum CodingKeys: String, CodingKey { case compression case width case height case dpiX case dpiY case showHiddenSlides case pixelFormat case notesPosition case commentsPosition case commentsAreaWidth case commentsAreaColor case showCommentsByNoAuthor } public init(defaultRegularFont: String? = nil, format: String? = nil, compression: Compression? = nil, width: Int? = nil, height: Int? = nil, dpiX: Int? = nil, dpiY: Int? = nil, showHiddenSlides: Bool? = nil, pixelFormat: PixelFormat? = nil, notesPosition: NotesPosition? = nil, commentsPosition: CommentsPosition? = nil, commentsAreaWidth: Int? = nil, commentsAreaColor: String? = nil, showCommentsByNoAuthor: Bool? = nil) { super.init(defaultRegularFont: defaultRegularFont, format: format) self.compression = compression self.width = width self.height = height self.dpiX = dpiX self.dpiY = dpiY self.showHiddenSlides = showHiddenSlides self.pixelFormat = pixelFormat self.notesPosition = notesPosition self.commentsPosition = commentsPosition self.commentsAreaWidth = commentsAreaWidth self.commentsAreaColor = commentsAreaColor self.showCommentsByNoAuthor = showCommentsByNoAuthor } required init(from decoder: Decoder) throws { try super.init(from: decoder) let values = try decoder.container(keyedBy: CodingKeys.self) compression = try values.decode(Compression?.self, forKey: .compression) width = try values.decode(Int?.self, forKey: .width) height = try values.decode(Int?.self, forKey: .height) dpiX = try values.decode(Int?.self, forKey: .dpiX) dpiY = try values.decode(Int?.self, forKey: .dpiY) showHiddenSlides = try values.decode(Bool?.self, forKey: .showHiddenSlides) pixelFormat = try values.decode(PixelFormat?.self, forKey: .pixelFormat) notesPosition = try values.decode(NotesPosition?.self, forKey: .notesPosition) commentsPosition = try values.decode(CommentsPosition?.self, forKey: .commentsPosition) commentsAreaWidth = try values.decode(Int?.self, forKey: .commentsAreaWidth) commentsAreaColor = try values.decode(String?.self, forKey: .commentsAreaColor) showCommentsByNoAuthor = try values.decode(Bool?.self, forKey: .showCommentsByNoAuthor) } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(compression, forKey: .compression) try container.encode(width, forKey: .width) try container.encode(height, forKey: .height) try container.encode(dpiX, forKey: .dpiX) try container.encode(dpiY, forKey: .dpiY) try container.encode(showHiddenSlides, forKey: .showHiddenSlides) try container.encode(pixelFormat, forKey: .pixelFormat) try container.encode(notesPosition, forKey: .notesPosition) try container.encode(commentsPosition, forKey: .commentsPosition) try container.encode(commentsAreaWidth, forKey: .commentsAreaWidth) try container.encode(commentsAreaColor, forKey: .commentsAreaColor) try container.encode(showCommentsByNoAuthor, forKey: .showCommentsByNoAuthor) } }
0
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // Set+Extensions.swift // // Created by Nacho Soto on 12/15/21. import Foundation extension Set { /// Creates a `Dictionary` with the keys in the receiver `Set`, and the values provided by `value`. func dictionaryWithValues<Value>(_ value: @escaping (Element) -> Value) -> [Element: Value] { return Dictionary(uniqueKeysWithValues: self.lazy.map { ($0, value($0)) }) } }
0
// // RulesParser.swift // DomainParser // // Created by Jason Akakpo on 04/09/2018. // Copyright © 2018 Dashlane. All rights reserved. // import Foundation class RulesParser { var exceptions = [Rule]() var wildcardRules = [Rule]() /// Set of suffixes var basicRules = Set<String>() /// Parse the Data to extract an array of Rules. The array is sorted by importance. func parse(raw: Data) throws -> ParsedRules { guard let rulesText = String(data: raw, encoding: .utf8) else { throw DomainParserError.parsingError(details: nil) } rulesText .components(separatedBy: .newlines) .forEach(parseRule) return ParsedRules.init(exceptions: exceptions, wildcardRules: wildcardRules, basicRules: basicRules) } private func parseRule(line: String) { guard let trimmedLine = line.components(separatedBy: .whitespaces).first, !trimmedLine.isComment && !trimmedLine.isEmpty else { return } /// From `publicsuffix.org/list/` Each line is only read up to the first whitespace; entire lines can also be commented using //. if trimmedLine.contains("*") { wildcardRules.append(Rule(raw: trimmedLine)) } else if trimmedLine.starts(with: "!") { exceptions.append(Rule(raw: trimmedLine)) } else { basicRules.insert(trimmedLine) } } } private extension String { /// A line starting by "//" is a comment and should be ignored var isComment: Bool { return self.starts(with: C.commentMarker) } }
0
// // PagerStripTests.swift // PagerStripTests // // Created by Lothar Mödl on 13.02.18. // Copyright © 2018 Lothar Mödl. All rights reserved. // import XCTest @testable import PagerStrip class PagerStripTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
0
import UIKit class SettingsViewController : UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource { let tapGestureRecognizer = UITapGestureRecognizer() let defaults = UserDefaults.standard @IBOutlet weak var defaultTipSegmentControl: UISegmentedControl! @IBOutlet weak var customTextField: UITextField! @IBOutlet weak var customTipPicker: UIPickerView! @IBOutlet weak var darkThemeSwitch: UISwitch! var tipPercentage = [15, 20, 25] let customTipArray = Array(stride(from: 30, through: 100, by: 5)) override func viewDidLoad() { super.viewDidLoad() customTextField.delegate = self customTipPicker.delegate = self setUpView() tapGestureRecognizer.addTarget(self, action: #selector(onSingleTap(_:))) // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) DataManager.setThemeColors(self, isDarkTheme: DataManager.isDarkThemeEnabled()) setDefaultTip() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } func setUpView() { customTextField.placeholder = PlaceHolder.CustomTip.rawValue customTextField.isHidden = true customTipPicker.isHidden = true darkThemeSwitch.isOn = DataManager.isDarkThemeEnabled() } func isDefaultTipSet() -> Bool { return defaults.bool(forKey: Constant.hasDefaultTip.rawValue) } func isCustomTipSet() -> Bool { return defaults.bool(forKey: Constant.hasCustomTip.rawValue) } func getDefaultTipPercent() -> Int { return defaults.integer(forKey: Constant.defaultTip.rawValue) } func tipSegmentIndex() -> Int? { let selectedTipPercent = getDefaultTipPercent() return tipPercentage.index(of: selectedTipPercent) } func setDefaultTip() { if isCustomTipSet() { defaultTipSegmentControl.selectedSegmentIndex = tipPercentage.count customTextField.isHidden = false customTipPicker.isHidden = false customTextField.text = String(getDefaultTipPercent()) + "%" } else if isDefaultTipSet(), let segmentIndex = tipSegmentIndex() { defaultTipSegmentControl.selectedSegmentIndex = segmentIndex } else { defaultTipSegmentControl.selectedSegmentIndex = 0 } } @IBAction func userDidSelectDefaultTip(_ sender: UISegmentedControl) { userDidSelectDefaultTip(selectedIndex: sender.selectedSegmentIndex) } @IBAction func userDidSwitchToDarkTheme(_ sender: UISwitch) { DataManager.setDarkThemeEnabled(sender.isOn) DataManager.setThemeColors(self, isDarkTheme: sender.isOn) customTipPicker.reloadAllComponents() } func userDidSelectDefaultTip(selectedIndex: Int) { if selectedIndex < tipPercentage.count { customTextField.isHidden = true customTipPicker.isHidden = true defaults.set(true, forKey: Constant.hasDefaultTip.rawValue) defaults.set(false, forKey: Constant.hasCustomTip.rawValue) defaults.set(tipPercentage[selectedIndex], forKey: Constant.defaultTip.rawValue) defaults.synchronize() } else { userDidSelectCustomTip() } } func userDidSelectCustomTip() { customTextField.isHidden = false customTextField.becomeFirstResponder() } @IBAction func onSingleTap(_ sender: UITapGestureRecognizer) { if let tappedView = sender.view { tappedView.endEditing(true) } } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { customTipPicker.isHidden = false customTextField.text = String(customTipArray[0]) return false } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return customTipArray.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { defaults.set(false, forKey: Constant.hasDefaultTip.rawValue) defaults.set(true, forKey: Constant.hasCustomTip.rawValue) defaults.set(customTipArray[row], forKey: Constant.defaultTip.rawValue) defaults.synchronize() customTextField.text = String(customTipArray[row]) + "%" } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let title = String(customTipArray[row]) let attributedTitle = NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: DataManager.pickerTitleColor(forTheme: DataManager.isDarkThemeEnabled())]) return attributedTitle } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
0
// // UIImage+Extension.swift // YWLiwuShuo // // Created by Mac on 2017/5/18. // Copyright © 2017年 Mac. All rights reserved. // import UIKit extension UIImage { class func imageWithColor(color: UIColor, size: CGSize) -> UIImage { let rect = CGRectMake(0, 0, size.width == 0 ? 1.0 : size.width, size.height == 0 ? 1.0 : size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } func resetImageSize(newWidth: CGFloat) -> UIImage { let scale = newWidth / self.size.width let newHeight = self.size.height * scale UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight)) self.drawInRect(CGRectMake(0, 0, newWidth, newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
0
// // COBezierTableViewEditor.swift // COBezierTableView // // Created by Knut Inge Grosland on 2015-02-24. // Copyright (c) 2015 Knut Inge Grosland // //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 Darwin class COBezierEditorView: UIView { var pointSelector : UISegmentedControl! var startLocation : CGPoint? // MARK: Init and setup required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupEditorView() } override init(frame: CGRect) { super.init(frame: frame) setupEditorView() } private final func setupEditorView() { addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))) pointSelector = UISegmentedControl(frame: CGRectMake(10, CGRectGetMaxY(bounds) - 40, CGRectGetWidth(bounds) - 20, 30)) pointSelector.autoresizingMask = [.FlexibleWidth, .FlexibleTopMargin] pointSelector.insertSegmentWithTitle(NSStringFromCGPoint(bezierStaticPoint(0)), atIndex: 0, animated: false) pointSelector.insertSegmentWithTitle(NSStringFromCGPoint(bezierStaticPoint(1)), atIndex: 1, animated: false) pointSelector.insertSegmentWithTitle(NSStringFromCGPoint(bezierStaticPoint(2)), atIndex: 2, animated: false) pointSelector.insertSegmentWithTitle(NSStringFromCGPoint(bezierStaticPoint(3)), atIndex: 3, animated: false) pointSelector.selectedSegmentIndex = 0 addSubview(pointSelector) } override func layoutSubviews() { super.layoutSubviews() updateBezierPointsIfNeeded(bounds) } // MARK: Drawing override func drawRect(rect: CGRect) { // Draw background if let backgroundColor = self.backgroundColor { backgroundColor.set() } else { UIColor.blackColor().set() } UIBezierPath(rect: rect).fill() // Draw line UIColor.brownColor().setStroke() let path = UIBezierPath() path.moveToPoint(bezierStaticPoint(0)) path.addCurveToPoint(bezierStaticPoint(3), controlPoint1: bezierStaticPoint(1), controlPoint2: bezierStaticPoint(2)) path.stroke() // Draw circles UIColor.redColor().setStroke() for (var t : CGFloat = 0.0; t <= 1.00001; t += 0.05) { let point = bezierPointFor(t) let radius : CGFloat = 5.0 let endAngle : CGFloat = 2.0 * CGFloat(M_PI) let pointPath = UIBezierPath(arcCenter: point, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true) pointPath.stroke() } } // MARK: UIPanGestureRecognizer func handlePan(recognizer:UIPanGestureRecognizer) { if recognizer.state == .Began { startLocation = bezierStaticPoint(pointSelector.selectedSegmentIndex) } else if recognizer.state == .Changed { let translation = recognizer.translationInView(self) if let startLocationUnWrapped = startLocation { var pointToMove = startLocationUnWrapped pointToMove.x += floor(translation.x) pointToMove.y += floor(translation.y) if pointSelector.selectedSegmentIndex == 0 || pointSelector.selectedSegmentIndex == 3 { if (pointToMove.x > bounds.width) { pointToMove.x = bounds.width } if (pointToMove.x < 0) { pointToMove.x = 0 } if pointSelector.selectedSegmentIndex == 0 { pointToMove.y = 0 } else { pointToMove.y = bounds.size.height } } setBezierStaticPoint(pointToMove, forIndex: pointSelector.selectedSegmentIndex) pointSelector.setTitle(NSStringFromCGPoint(bezierStaticPoint(pointSelector.selectedSegmentIndex)), forSegmentAtIndex: pointSelector.selectedSegmentIndex) setNeedsDisplay() } } else if recognizer.state == .Ended { recognizer.setTranslation(CGPointZero, inView: self) } } }
0
// // NexusManager.swift // Demo // // Created by yupao_ios_macmini05 on 2021/12/2. // import RxSwift import RxCocoa import UIKit // MARK: 刷新管理器 public class NexusRefreshManager { /// 单例 public static let shared = NexusRefreshManager() private init() {} /// 可用刷新池 private var availableRefreshPool = NSMapTable<AnyObject, Observer>(keyOptions: .weakMemory, valueOptions: .strongMemory) /// 等待刷新池 private var waitRefreshPool = NSHashTable<AnyObject>.init(options: .weakMemory) // MARK: 添加刷新监听 /// 添加刷新监听 /// - Parameters: /// - target: 刷新目标 /// - tags: 标签列表 /// - refreshBlock: 刷新回调 public func add(_ target: AnyObject, tags: Set<Tag>, refreshBlock: @escaping () -> Void) { let observerModel = Observer(target: target, tags: tags, refreshBlock: refreshBlock) NexusRefreshManager.shared.availableRefreshPool.setObject(observerModel, forKey: target) // 如果是VC进行特殊处理 if let vc = target as? UIViewController { // VC出现时再刷新 vc.rx.nr_viewDidAppear.subscribe(onNext: { [weak target] _ in guard let target = target else { return } // 判断刷新池是否存在 if NexusRefreshManager.shared.waitRefreshPool.contains(target), let observerModel = NexusRefreshManager.shared.availableRefreshPool.object(forKey: target) { // 刷新 observerModel.refreshBlock() // 移除等待刷新池 NexusRefreshManager.shared.waitRefreshPool.remove(observerModel.target) } }).disposed(by: vc.rx.nr_disposeBag) } } // MARK: 刷新 /// 刷新 /// - Parameters: /// - tags: 标签列表 /// - filtObjects: 过滤列表 /// - force: 强制刷新,会直接刷新,不会等待出现(仅对VC有用) public func refresh(tags: Set<Tag>, filtObjects: [AnyObject] = [], force: Bool = false) { // 遍历可刷新池 NexusRefreshManager.shared.availableRefreshPool.objectEnumerator()?.forEach { object in // 判断是否可以刷新 if let observerModel = object as? Observer, tags.intersection(observerModel.tags).count > 0, !filtObjects.contains(where: { $0.isEqual(observerModel) }) { if !force, let vc = observerModel.target as? UIViewController { // 不可见VC加入等待刷新池;可见VC直接刷新。 if vc.isViewLoaded, vc.view.window != nil { observerModel.refreshBlock() } else { NexusRefreshManager.shared.waitRefreshPool.add(observerModel.target) } } else { // 不是VC直接刷新 observerModel.refreshBlock() } } } } // MARK: 移除监听 /// 移除监听 /// - Parameter target: 观察者 public func remove(_ target: AnyObject) { NexusRefreshManager.shared.availableRefreshPool.removeObject(forKey: target) NexusRefreshManager.shared.waitRefreshPool.remove(target) } } // MARK: 刷新管理器扩展 extension NexusRefreshManager { // MARK: 标签 public struct Tag: Hashable, Equatable, RawRepresentable { public var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } } // MARK: 纽带观察模型 class Observer { /// 观察者 weak var target: AnyObject? /// 标签列表 var tags: Set<Tag> = [] /// 刷新回调 var refreshBlock: () -> Void init(target: AnyObject, tags: Set<Tag>, refreshBlock: @escaping () -> Void) { self.target = target self.tags = tags self.refreshBlock = refreshBlock } } // MARK: 纽带刷新数据模型 public class Object { /// 标签列表 public var tags: Set<Tag> = [] /// 数据 public var data: Any? init(tags: Set<Tag>, data: Any?) { self.tags = tags self.data = data } } } // MARK: UIViewController扩展 public extension Reactive where Base: UIViewController { /// UIViewController将要出现 var nr_viewDidAppear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewDidAppear)).map { $0.first as? Bool ?? false } return ControlEvent(events: source) } } // MARK: DisposeBag扩展 fileprivate var nr_disposeBagContext: UInt8 = 0 extension Reactive where Base: AnyObject { func nr_synchronizedBag<T>( _ action: () -> T) -> T { objc_sync_enter(self.base) let result = action() objc_sync_exit(self.base) return result } } extension Reactive where Base: AnyObject { /// a unique DisposeBag that is related to the Reactive.Base instance only for Reference type var nr_disposeBag: DisposeBag { get { return nr_synchronizedBag { if let disposeObject = objc_getAssociatedObject(base, &nr_disposeBagContext) as? DisposeBag { return disposeObject } let disposeObject = DisposeBag() objc_setAssociatedObject(base, &nr_disposeBagContext, disposeObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return disposeObject } } set { nr_synchronizedBag { objc_setAssociatedObject(base, &nr_disposeBagContext, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } }
0
// // Responder.swift // Nano // // Created by John on 14/06/2016. // Copyright © 2016 Formal Technology. All rights reserved. // import Foundation public class Responder : Equatable, Hashable { public var hashValue : Int { return self.identifier.hashValue } private var internalIdentifier : ObjectIdentifier? public var identifier : ObjectIdentifier { if let id = internalIdentifier { return id } else { internalIdentifier = ObjectIdentifier(self) return internalIdentifier! } } public var acceptsFirstResponder = false; public var nextResponder : Responder? { return nil } public func becomeFirstResponder() -> Bool { return false } public func resignFirstResponder() -> Bool { return true } public func mouseDown(event: Event) { if !event.cancelled { nextResponder?.mouseDown(event) } } public func mouseDragged(event: Event) { if !event.cancelled { nextResponder?.mouseDragged(event) } } public func mouseUp(event: Event) { if !event.cancelled { nextResponder?.mouseUp(event) } } public func mouseMoved(event: Event) { if !event.cancelled { nextResponder?.mouseMoved(event) } } public func mouseEntered(event: Event) { if !event.cancelled { nextResponder?.mouseEntered(event) } } public func mouseExited(event: Event) { if !event.cancelled { nextResponder?.mouseExited(event) } } public func keyDown(event: Event) { if !event.cancelled { nextResponder?.keyDown(event) } } public func keyUp(event: Event) { if !event.cancelled { nextResponder?.keyUp(event) } } } public func == (lhs: Responder, rhs: Responder) -> Bool { return lhs.identifier == rhs.identifier }
0
// // HelpAndFeedbackTableViewController.swift // // iMast https://github.com/cinderella-project/iMast // // Created by user on 2019/11/24. // // ------------------------------------------------------------------------ // // Copyright 2017-2019 rinsuki and other contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import SafariServices class HelpAndFeedbackTableViewController: UITableViewController { init() { super.init(style: .grouped) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } enum Section { case one } enum Item: Hashable { case web(title: String, url: URL) case feedback } lazy var dataSource = UITableViewDiffableDataSource<Section, Item>(tableView: self.tableView, cellProvider: self.cellProvider) override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem var snapshot = dataSource.plainSnapshot() snapshot.appendSections([.one]) snapshot.appendItems([ .web(title: L10n.Localizable.Help.title, url: URL(string: "https://cinderella-project.github.io/iMast/help/")!), .feedback, .web(title: "GitHub Issues", url: URL(string: "https://github.com/cinderella-project/iMast/issues")!), ], toSection: .one) dataSource.apply(snapshot, animatingDifferences: false) title = L10n.Localizable.helpAndFeedback } // MARK: - Table view data source func cellProvider(_ tableView: UITableView, indexPath: IndexPath, item: Item) -> UITableViewCell? { let cell: UITableViewCell switch item { case .web(let title, let url): cell = .init(style: .subtitle, reuseIdentifier: nil) cell.textLabel?.text = title cell.detailTextLabel?.text = url.absoluteString case .feedback: cell = .init(style: .default, reuseIdentifier: nil) cell.textLabel?.text = "Feedback" } cell.accessoryType = .disclosureIndicator return cell } // MARK: - Table view Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let item = dataSource.itemIdentifier(for: indexPath) else { return } switch item { case .web(_, let url): let vc = SFSafariViewController(url: url) self.present(vc, animated: true, completion: nil) case .feedback: let vc = FeedbackViewController() self.show(vc, sender: self) } } }
0
// // ImagePicker.swift // Instafilter // // Created by Ramsey on 2020/6/22. // Copyright © 2020 Ramsey. All rights reserved. // import Foundation import SwiftUI struct ImagePicker: UIViewControllerRepresentable { @Binding var image: UIImage? @Environment(\.presentationMode) var presentationMode class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var parent: ImagePicker init(_ parent: ImagePicker) { self.parent = parent } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let uiImage = info[.originalImage] as? UIImage { parent.image = uiImage } parent.presentationMode.wrappedValue.dismiss() } } func makeCoordinator() -> Coordinator { return Coordinator(self) } func makeUIViewController(context: Context) -> UIImagePickerController { let picker = UIImagePickerController() picker.delegate = context.coordinator return picker } func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) { } }
0
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func c{ func c<Int> (v: A } protocol A { struct S<T : S<Int>
0
// // NSImage+PCH.swift // PodcastChapters // // Created by Szabolcs Toth on 2016. 10. 10.. // Copyright © 2016. Szabolcs Toth. All rights reserved. // import AppKit import Foundation extension NSImage { static func pch_loadImage(named name: String, ofType type: String = "png") -> NSImage { let bundle = Bundle(for: iTunesMock.self) guard let path = bundle.path(forResource: name, ofType: type) else { fatalError("Could not find the \(name).\(type) in the test bundle") } return NSImage(contentsOfFile: path)! } }
0
// Copyright (c) 2021 Pedro Almeida // // 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 UniformTypeIdentifiers extension ViewHierarchyElement { struct Snapshot: ViewHierarchyElementRepresentable, ExpirableProtocol, Equatable { static func == (lhs: ViewHierarchyElement.Snapshot, rhs: ViewHierarchyElement.Snapshot) -> Bool { lhs.identifier == rhs.identifier } let identifier = UUID() let objectIdentifier: ObjectIdentifier let parent: ViewHierarchyElementReference? = nil var accessibilityIdentifier: String? var canHostInspectorView: Bool var canHostContextMenuInteraction: Bool var canPresentOnTop: Bool var className: String var classNameWithoutQualifiers: String var constraintElements: [LayoutConstraintElement] var depth: Int var displayName: String var elementDescription: String var elementName: String var expirationDate: Date = makeExpirationDate() var frame: CGRect var iconImage: UIImage? var isContainer: Bool var isHidden: Bool var isInternalView: Bool var isSystemContainer: Bool var isUserInteractionEnabled: Bool var issues: [ViewHierarchyIssue] var overrideViewHierarchyInterfaceStyle: ViewHierarchyInterfaceStyle var shortElementDescription: String var traitCollection: UITraitCollection init(view: UIView, icon: UIImage?, depth: Int) { self.depth = depth accessibilityIdentifier = view.accessibilityIdentifier canHostContextMenuInteraction = view.canHostContextMenuInteraction canHostInspectorView = view.canHostInspectorView canPresentOnTop = view.canPresentOnTop className = view._className classNameWithoutQualifiers = view._classNameWithoutQualifiers constraintElements = view.constraintElements displayName = view.displayName elementDescription = view.elementDescription elementName = view.elementName frame = view.frame iconImage = icon isContainer = !view.children.isEmpty isHidden = view.isHidden isInternalView = view.isInternalView isSystemContainer = view.isSystemContainer isUserInteractionEnabled = view.isUserInteractionEnabled issues = view.issues objectIdentifier = view.objectIdentifier overrideViewHierarchyInterfaceStyle = view.overrideViewHierarchyInterfaceStyle shortElementDescription = view.shortElementDescription traitCollection = view.traitCollection } private static func makeExpirationDate() -> Date { let expiration = Inspector.sharedInstance.configuration.snapshotExpirationTimeInterval let expirationDate = Date().addingTimeInterval(expiration) return expirationDate } } } final class ViewHierarchyElement: CustomDebugStringConvertible { var debugDescription: String { String(describing: store.latest) } weak var underlyingView: UIView? weak var parent: ViewHierarchyElementReference? let iconProvider: ViewHierarchyElementIconProvider? private var store: SnapshotStore<Snapshot> var isCollapsed: Bool var depth: Int { didSet { children.forEach { $0.depth = depth + 1 } } } lazy var children: [ViewHierarchyElementReference] = makeChildren() private(set) lazy var allChildren: [ViewHierarchyElementReference] = children.flatMap(\.viewHierarchy) // MARK: - Computed Properties var deepestAbsoulteLevel: Int { children.map(\.depth).max() ?? depth } var deepestRelativeLevel: Int { deepestAbsoulteLevel - depth } // MARK: - Init init( with view: UIView, iconProvider: ViewHierarchyElementIconProvider? = .none, depth: Int = .zero, isCollapsed: Bool = false, parent: ViewHierarchyElementReference? = .none ) { underlyingView = view self.depth = depth self.parent = parent self.iconProvider = iconProvider self.isCollapsed = isCollapsed isUnderlyingViewUserInteractionEnabled = view.isUserInteractionEnabled let initialSnapshot = Snapshot( view: view, icon: iconProvider?.resizedIcon(for: view), depth: depth ) store = SnapshotStore(initialSnapshot) } var latestSnapshot: Snapshot { store.latest } var isUnderlyingViewUserInteractionEnabled: Bool private func makeChildren() -> [ViewHierarchyElementReference] { guard let underlyingView = underlyingView else { return [] } return underlyingView .children .compactMap { ViewHierarchyElement( with: $0, iconProvider: iconProvider, depth: depth + 1, parent: self ) } } } // MARK: - ViewHierarchyElementReference { extension ViewHierarchyElement: ViewHierarchyElementReference { var canHostContextMenuInteraction: Bool { store.latest.canHostContextMenuInteraction } var isSystemContainer: Bool { store.first.isSystemContainer } var underlyingObject: NSObject? { underlyingView } var underlyingViewController: UIViewController? { nil } var isHidden: Bool { get { underlyingView?.isHidden ?? false } set { underlyingView?.isHidden = newValue } } func hasChanges(inRelationTo identifier: UUID) -> Bool { latestSnapshotIdentifier != identifier } var latestSnapshotIdentifier: UUID { latestSnapshot.identifier } var isUserInteractionEnabled: Bool { isUnderlyingViewUserInteractionEnabled } var overrideViewHierarchyInterfaceStyle: ViewHierarchyInterfaceStyle { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.overrideViewHierarchyInterfaceStyle } if rootView.overrideViewHierarchyInterfaceStyle != store.latest.overrideViewHierarchyInterfaceStyle { scheduleSnapshot() } return rootView.overrideViewHierarchyInterfaceStyle } var traitCollection: UITraitCollection { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.traitCollection } if rootView.traitCollection != store.latest.traitCollection { scheduleSnapshot() } return rootView.traitCollection } var iconImage: UIImage? { iconProvider?.resizedIcon(for: underlyingView) } // MARK: - Cached properties var cachedIconImage: UIImage? { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.iconImage } let currentIcon = iconProvider?.resizedIcon(for: rootView) if currentIcon?.pngData() != store.latest.iconImage?.pngData() { scheduleSnapshot() } return currentIcon } var isContainer: Bool { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.isContainer } if rootView.isContainer != store.latest.isContainer { scheduleSnapshot() } return rootView.isContainer } var shortElementDescription: String { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.shortElementDescription } if rootView.shortElementDescription != store.latest.shortElementDescription { scheduleSnapshot() } return rootView.shortElementDescription } var elementDescription: String { guard let rootView = underlyingView else { return store.latest.elementDescription } if rootView.canHostInspectorView != store.latest.canHostInspectorView { scheduleSnapshot() } return rootView.elementDescription } var canHostInspectorView: Bool { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.canHostInspectorView } if rootView.canHostInspectorView != store.latest.canHostInspectorView { scheduleSnapshot() } return rootView.canHostInspectorView } var isInternalView: Bool { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.isInternalView } if rootView.isInternalView != store.latest.isInternalView { scheduleSnapshot() } return rootView.isInternalView } var elementName: String { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.elementName } if rootView.elementName != store.latest.elementName { scheduleSnapshot() } return rootView.elementName } var displayName: String { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.displayName } if rootView.displayName != store.latest.displayName { scheduleSnapshot() } return rootView.displayName } var frame: CGRect { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.frame } if rootView.frame != store.latest.frame { scheduleSnapshot() } return rootView.frame } var accessibilityIdentifier: String? { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.accessibilityIdentifier } if rootView.accessibilityIdentifier != store.latest.accessibilityIdentifier { scheduleSnapshot() } return rootView.accessibilityIdentifier } var constraintElements: [LayoutConstraintElement] { guard store.latest.isExpired, let rootView = underlyingView else { return store.latest.constraintElements } if rootView.constraintElements != store.latest.constraintElements { scheduleSnapshot() } return rootView.constraintElements } enum SnapshotSchedulingError: Error { case dealocatedSelf, lostConnectionToView } private func scheduleSnapshot(_ handler: ((Result<Snapshot, SnapshotSchedulingError>) -> Void)? = nil) { store.scheduleSnapshot( .init(closure: { [weak self] in guard let self = self else { handler?(.failure(.dealocatedSelf)) return nil } guard let rootView = self.underlyingView else { handler?(.failure(.lostConnectionToView)) return nil } let snapshot = Snapshot( view: rootView, icon: self.iconProvider?.resizedIcon(for: rootView), depth: self.depth ) handler?(.success(snapshot)) return snapshot } ) ) } // MARK: - Live Properties var canPresentOnTop: Bool { store.first.canPresentOnTop } var className: String { store.first.className } var classNameWithoutQualifiers: String { store.first.classNameWithoutQualifiers } var issues: [ViewHierarchyIssue] { guard let rootView = underlyingView else { var issues = store.latest.issues issues.append(.lostConnection) return issues } if rootView.issues != store.latest.issues { scheduleSnapshot() } return rootView.issues } var objectIdentifier: ObjectIdentifier { store.first.objectIdentifier } } // MARK: - Hashable extension ViewHierarchyElement: Hashable { static func == (lhs: ViewHierarchyElement, rhs: ViewHierarchyElement) -> Bool { lhs.objectIdentifier == rhs.objectIdentifier } func hash(into hasher: inout Hasher) { hasher.combine(objectIdentifier) } } private extension ViewHierarchyElementIconProvider { func resizedIcon(for view: UIView?) -> UIImage? { autoreleasepool { value(for: view)?.resized(.elementIconSize) } } }
0
// // CardModuleLaunchOptions.swift // AptoUISDK // // Created by Ivan Oliver Martínez on 04/11/2020. // import AptoSDK import Foundation @objc public enum AptoUISDKMode: Int { case standalone case embedded } enum CardModuleInitialFlow { case newCardApplication case manageCard(cardId: String) case fullSDK } struct CardModuleLaunchOptions { let mode: AptoUISDKMode let initialUserData: DataPointList? let initializationData: InitializationData? let googleMapsApiKey: String? let cardOptions: CardOptions? let initialFlow: CardModuleInitialFlow }
0
// // MVCModel.swift // architecturesDemo // // Created by ac on 2019/1/19. // Copyright © 2019年 ac. All rights reserved. // import UIKit class MVCModel: Codable { var avatarURL: URL var nickname: String var repositories: [Repository] init(avatarURL: URL, nickname: String, repositories: [Repository]) { self.avatarURL = avatarURL self.nickname = nickname self.repositories = repositories } } class Repository: Codable { var id: String var title: String var isStar: Bool func tapStar() { isStar = !isStar } init(title: String, isStar: Bool) { self.id = UUID().uuidString self.title = title self.isStar = isStar } } extension MVCModel { static func mock() -> MVCModel { let repositories = [ Repository(title: "ArchitecturesDemo", isStar: true), Repository(title: "Octopus", isStar: false), Repository(title: "SoapBubble", isStar: true), Repository(title: "MonkeyKing", isStar: true), Repository(title: "ACTagView", isStar: false), Repository(title: "FancyAlert", isStar: false) ] return MVCModel(avatarURL: URL(string: "https://raw.githubusercontent.com/ChaselAn/iOSArchitecturesDemo/master/architecturesDemo/timg.jpeg")!, nickname: "ChaselAn", repositories: repositories) } } // MARK: - MVC extension MVCModel { static let changeReasonKey = "reason" enum ChangeReasonKey { case starChanged(index: Int) case addRepo case deleteRepo(index: Int) } func tapStarRepo(id: String) { for (index, repo) in repositories.enumerated() where repo.id == id { repo.tapStar() MVCStore.shared.save(self, userInfo: [ MVCModel.changeReasonKey: ChangeReasonKey.starChanged(index: index) ] ) } } func addRepo(title: String) { repositories.insert(Repository(title: title, isStar: false), at: 0) MVCStore.shared.save(self, userInfo: [ MVCModel.changeReasonKey: ChangeReasonKey.addRepo ] ) } func removeRepo(id: String) { if let index = repositories.firstIndex(where: { $0.id == id }) { repositories.remove(at: index) MVCStore.shared.save(self, userInfo: [ MVCModel.changeReasonKey: ChangeReasonKey.deleteRepo(index: index) ] ) } } } // MARK: - MVC extension MVCModel { func tapStarRepoForReducer(id: String) { for (index, repo) in repositories.enumerated() where repo.id == id { repo.tapStar() mvcStateStore.dispatch(.starChanged(index: index)) } } func addRepoForReducer(title: String) { repositories.insert(Repository(title: title, isStar: false), at: 0) mvcStateStore.dispatch(.addRepo) } func removeRepoForReducer(id: String) { if let index = repositories.firstIndex(where: { $0.id == id }) { repositories.remove(at: index) mvcStateStore.dispatch(.deleteRepo(index: index)) } } }
0
// // CallSignSSID.swift // AX.25 // // Created by Jeremy Kitchen on 5/29/19. // Copyright © 2019 Jeremy Kitchen. All rights reserved. // import Foundation public struct CallSignSSID: Equatable { let CallSign: String let SSID: UInt8 // UInt4 if I end up pulling in that library, perhaps public init?(_ bytes: Data) { guard bytes.count == 7 else { return nil } let callSignBytes = bytes[bytes.startIndex..<(bytes.endIndex - 1)] CallSign = String(bytes: callSignBytes.map({ $0 >> 1 }), encoding: String.Encoding.ascii)!.replacingOccurrences(of: " ", with: "") SSID = (0b00011110 & bytes[bytes.endIndex - 1]) >> 1 } public init?(callSign CallSign: String, ssid SSID: UInt8) { guard SSID <= 15 else { return nil } self.CallSign = CallSign self.SSID = SSID } public func field() -> Data { var bytes = CallSign.padding(toLength: 6, withPad: " ", startingAt: 0).data(using: .ascii)!.map({ $0 << 1 }) bytes.append(SSID << 1) return Data(bytes) } }
0
// // UnitFieldTextRange.swift // WLUnitField // // Created by Zoneyet on 2020/9/21. // Copyright © 2020 wayne. All rights reserved. // import Foundation class UnitFieldTextRange: UITextRange { override var start: UnitFieldTextPosition { get { return _start } } override var end: UnitFieldTextPosition { get { return _end } } let _start: UnitFieldTextPosition let _end: UnitFieldTextPosition init(start: UnitFieldTextPosition, end: UnitFieldTextPosition) { self._start = start self._end = end assert(start.offset <= end.offset); super.init() } convenience init?(range: NSRange) { if range.location == NSNotFound { return nil } let start = UnitFieldTextPosition(offset: range.location) let end = UnitFieldTextPosition(offset: range.location + range.length) self.init(start: start, end: end) } // - (NSRange)range { // return NSMakeRange(_start.offset, _end.offset - _start.offset); // } } extension UnitFieldTextRange: NSCopying { func copy(with zone: NSZone? = nil) -> Any { return UnitFieldTextRange(start: self._start, end: self._end) } }
0
import UIKit public extension CGImagePropertyOrientation { init(_ orientation: UIImage.Orientation) { switch orientation { case .up: self = .up case .upMirrored: self = .upMirrored case .down: self = .down case .downMirrored: self = .downMirrored case .left: self = .left case .leftMirrored: self = .leftMirrored case .right: self = .right case .rightMirrored: self = .rightMirrored @unknown default: fatalError() } } }
0
// // WatchNet+Rx.swift // WatchNet+Rx // // Created by Ilya Senchukov on 01.08.2021. // import UIKit import WatchNet import RxSwift import Foundation public extension Reactive where Base: RestService { func fetch<T: Decodable>(force: Bool = true, decodingTo: T.Type) -> Single<T> { Single.create { single in let task = base.execute(decodingTo: T.self, force: force) { res in switch res { case .success(let obj): single(.success(obj)) case .failure(let error): single(.failure(error)) } } return Disposables.create { task?.cancel() } } .observe(on: ConcurrentDispatchQueueScheduler(qos: .background)) } func fetch(force: Bool = true) -> Single<Data> { Single.create { single in let task = base.execute(force: force) { res in switch res { case .success(let data): single(.success(data)) case .failure(let error): single(.failure(error)) } } return Disposables.create { task?.cancel() } } .observe(on: ConcurrentDispatchQueueScheduler(qos: .background)) } } public extension Reactive where Base: ImageService { func fetch(path: String) -> Single<UIImage> { Single.create { single in let task = base.image(for: path) { res in switch res { case .success(let image): single(.success(image)) case .failure(let error): single(.failure(error)) } } return Disposables.create { task?.cancel() } } } } public extension Reactive where Base: RestService { func fetch<T: Decodable>(force: Bool = true, decodingTo: T.Type, errorHandler: @escaping (Base.ErrorResponse) -> Void) -> Single<T> { fetch(force: force, decodingTo: decodingTo) .catch { error in if let error = error as? Base.ErrorResponse { errorHandler(error) } return .error(error) } } func fetch(force: Bool = true, errorHandler: @escaping (Base.ErrorResponse) -> Void) -> Single<Data> { fetch(force: force) .catch { error in if let error = error as? Base.ErrorResponse { errorHandler(error) } return .error(error) } } } public extension ObservableType { func `catch`<T: Error>(error: T.Type, handler: @escaping (T) -> Void) -> Observable<Self.Element> { self.catch { e in if let error = e as? T { handler(error) return .error(e) } return .error(e) } } } public extension ObservableType { func `catch`<E: Error, T>(error: E.Type, handler: @escaping (E) -> Void) -> Observable<Self.Element> where Element == Event<T> { self.do(onNext: { e in if let error = e.error as? E { handler(error) } }) } }
0
/* * Copyright (c) 2020 Elastos Foundation * * 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 /// Create a credential builder. @objc(VerifiableCredentialBuilder) public class VerifiableCredentialBuilder: NSObject { private let TAG = NSStringFromClass(VerifiableCredentialBuilder.self) private var _issuer: VerifiableCredentialIssuer private var _target: DID private var _credential: VerifiableCredential? private var _signKey: DIDURL private var _forDoc: DIDDocument static let CONTEXT = "@context" public static let DEFAULT_CREDENTIAL_TYPE = "VerifiableCredential"// The default verifiable credential type. init(_ issuer: VerifiableCredentialIssuer, _ target: DID, _ doc: DIDDocument, _ signKey: DIDURL) throws { _issuer = issuer _target = target _forDoc = doc _signKey = signKey _credential = VerifiableCredential() _credential?.setIssuer(issuer.did) _credential?.setSubject(VerifiableCredentialSubject(target)) super.init() try setDefaultType() } private func checkNotSealed() throws { guard let _ = _credential else { throw DIDError.UncheckedError.IllegalStateError.AlreadySealedError() } } /// Set the credential id. /// - Parameter id: the credential id /// - Throws: if an error occurred, throw error. /// - Returns: VerifiableCredentialBuilder object. @objc public func withId(_ id: DIDURL) throws -> VerifiableCredentialBuilder { try checkNotSealed() try checkArgument(id.did != nil || id.did != _target, "Invalid id") var _id = id if id.did == nil { _id = DIDURL(_target, id) } _credential!.setId(_id) return self } /// Set the credential id. /// - Parameter id: the credential id /// - Throws: if an error occurred, throw error. /// - Returns: VerifiableCredentialBuilder object. @objc(withIdString:error:) public func withId(_ id: String) throws -> VerifiableCredentialBuilder { try checkArgument(!id.isEmpty , "id is nil") return try withId(DIDURL(_target, id)) } /// Add a new credential type. /// - Parameters: /// - type: the type name /// - context: the JSON-LD context for type, or null if not enabled the JSON-LD feature /// - Returns: the VerifiableCredentialBuilder instance for method chaining @objc(withType:context:error:) public func withType(_ type: String, _ context: String) throws -> VerifiableCredentialBuilder{ try checkNotSealed() try checkArgument(!type.isEmpty, "Invalid type: \(type)") if (Features.isEnabledJsonLdContext()) { try checkArgument(!context.isEmpty, "Invalid context: \(context)") if !_credential!._context.contains(context) { _credential!._context.append(context) } } else { Log.w(TAG, "JSON-LD context support not enabled, the context ", context, " will be ignored") } if (!_credential!.getTypes().contains(type)) { _credential?.appendType(type) } return self } /// Add a new credential type. /// If enabled the JSON-LD feature, the type should be a full type URI: /// [scheme:]scheme-specific-part#fragment, /// [scheme:]scheme-specific-part should be the context URL, /// the fragment should be the type name. /// /// Otherwise, the context URL part and # symbol could be omitted or /// ignored. /// - Parameter type: the type name /// - Returns: the VerifiableCredentialBuilder instance for method chaining public func withType(_ type: String) throws -> VerifiableCredentialBuilder { try checkNotSealed() try checkArgument(!type.isEmpty, "Invalid type: \(type)") if type.index(of: "#") == nil { return try withType(type, "") } else { let content_type = type.split(separator: "#") return try withType(String(content_type[1]), String(content_type[0])) } } /// Add a new credential type. /// If enabled the JSON-LD feature, the type should be a full type URI: /// [scheme:]scheme-specific-part#fragment, /// [scheme:]scheme-specific-part should be the context URL, /// the fragment should be the type name. /// /// Otherwise, the context URL part and # symbol could be omitted or /// ignored. /// - Parameter type: the type names /// - Returns: the VerifiableCredentialBuilder instance for method chaining public func withTypes(_ types: String...) throws -> VerifiableCredentialBuilder { return try withTypes(types) } /// Add a new credential type. /// If enabled the JSON-LD feature, the type should be a full type URI: /// [scheme:]scheme-specific-part#fragment, /// [scheme:]scheme-specific-part should be the context URL, /// the fragment should be the type name. /// /// Otherwise, the context URL part and # symbol could be omitted or /// ignored. /// - Parameter type: the type names /// - Returns: the VerifiableCredentialBuilder instance for method chaining @objc public func withTypes(_ types: Array<String>) throws -> VerifiableCredentialBuilder { if types.count == 0 { return self } try checkNotSealed() try types.forEach { item in try _ = withType(item) } return self } /// Set credential default expiration date /// - Throws: if an error occurred, throw error. /// - Returns: VerifiableCredentialBuilder object. @objc public func withDefaultExpirationDate() throws -> VerifiableCredentialBuilder { try checkNotSealed() _credential!.setExpirationDate(maxExpirationDate()) return self } /// Set expire time for the credential. /// - Parameter expirationDate: the expires time /// - Throws: if an error occurred, throw error. /// - Returns: VerifiableCredentialBuilder object. @objc public func withExpirationDate(_ expirationDate: Date) throws -> VerifiableCredentialBuilder { try checkNotSealed() var _expirationDate = expirationDate if _expirationDate > maxExpirationDate() { _expirationDate = maxExpirationDate() } _credential!.setExpirationDate(expirationDate) return self } /// Set the claim properties to the credential subject from a dictionary object. /// - Parameter properites: a dictionary include the claims: If you need to set the value to nil in the properties, use NSNull(), for example: /// ["abc": "helloworld", /// "foo": 123, /// "bar": "foobar", /// "foobar": "lalala...", /// "empty": "", /// "nil": NSNull()] as [String : Any] /// /// - Throws: if an error occurred, throw error. /// - Returns: VerifiableCredentialBuilder object. @objc public func withProperties(_ properites: Dictionary<String, Any>) throws -> VerifiableCredentialBuilder { try checkNotSealed() guard !properites.isEmpty else { return self } // TODO: CHECK let jsonNode = JsonNode(properites) let subject = VerifiableCredentialSubject(_target) subject.setProperties(jsonNode) _credential!.setSubject(subject) return self } /// Set the claim properties to the credential subject from JSON string. /// - Parameter json: Credential dictionary string /// - Throws: if an error occurred, throw error. /// - Returns: VerifiableCredentialBuilder object. @objc(withPropertiesWithJson:error:) public func withProperties(_ json: String) throws -> VerifiableCredentialBuilder { try checkNotSealed() try checkArgument(!json.isEmpty, "properties is nil") // TODO: CHECK let dic = try (JSONSerialization.jsonObject(with: json.data(using: .utf8)!, options: [JSONSerialization.ReadingOptions.init(rawValue: 0)]) as? [String: Any]) guard let _ = dic else { throw DIDError.CheckedError.DIDSyntaxError.MalformedCredentialError("properties data formed error.") } let jsonNode = JsonNode(dic!) let subject = VerifiableCredentialSubject(_target) subject.setProperties(jsonNode) _credential!.setSubject(subject) return self } /// Add new claim property to the credential subject. /// - Parameters: /// - key: the property name /// - value: the property value: If you need to set the value to nil, use NSNull(), for example: /// let vc = try issuer.editingVerifiableCredentialFor(did: user.subject).withId("#test") /// .withProperties("hello", "world") /// .withProperties("empty", "") /// .withProperties("nil", NSNull()) /// .seal(using: storePassword) /// /// - Returns: VerifiableCredentialBuilder object. @objc(withPropertiesWith::error:) public func withProperties(_ key: String, _ value: Any) throws -> VerifiableCredentialBuilder { try checkNotSealed() try checkArgument(!key.isEmpty && key != "id", "Invalid name") _credential?.subject?.setProperties(key, value) return self } /// Set claims about the subject of the credential. /// - Parameter properties: Credential dictionary JsonNode /// - Throws: if an error occurred, throw error. /// - Returns: VerifiableCredentialBuilder object. @objc(withPropertiesWithJsonNode:errro:) public func withProperties(_ properties: JsonNode) throws -> VerifiableCredentialBuilder { try checkNotSealed() try checkArgument(properties.count > 0, "properties is nil ") let subject = VerifiableCredentialSubject(_target) subject.setProperties(properties) _credential!.setSubject(subject) return self } private func sanitize() throws { guard _credential?.id != nil else { throw DIDError.CheckedError.DIDSyntaxError.MalformedCredentialError("Missing credential id") } guard _credential?.getTypes() != nil, _credential!.getTypes().count != 0 else { throw DIDError.CheckedError.DIDSyntaxError.MalformedCredentialError("Missing credential type") } _credential?.setIssuanceDate(DateFormatter.currentDate()) if _credential!.hasExpirationDate() { _ = try withDefaultExpirationDate() } // TODO: CHECK _credential!._types = _credential!._types.sorted() _credential?.setProof(nil) } /// Seal the credential object, attach the generated proof to the /// credential. /// - Parameter storePassword: the password for DIDStore /// - Throws: if an error occurred, throw error. /// - Returns: the sealed credential object @objc public func seal(using storePassword: String) throws -> VerifiableCredential { try checkNotSealed() try checkArgument(!storePassword.isEmpty, "Invalid storePassword") guard _credential!.checkIntegrity() else { throw DIDError.CheckedError.DIDSyntaxError.MalformedCredentialError("imcomplete credential") } try sanitize() _credential!.setIssuanceDate(DateFormatter.currentDate()) if try _credential!.getExpirationDate() == nil { _ = try withDefaultExpirationDate() } guard let data = _credential!.toJson(true, true).data(using: .utf8) else { throw DIDError.UncheckedError.IllegalArgumentErrors.IllegalArgumentError("credential is nil") } let signature = try _forDoc.sign(_signKey, storePassword, [data]) let proof = VerifiableCredentialProof(_signKey, signature) _credential!.setProof(proof) // invalidate builder let sealed = self._credential! self._credential = nil return sealed } func setDefaultType() throws { try checkNotSealed() if (Features.isEnabledJsonLdContext()) { if !_credential!._context.contains(VerifiableCredential.W3C_CREDENTIAL_CONTEXT) { _credential!._context.append(VerifiableCredential.W3C_CREDENTIAL_CONTEXT) } if !_credential!._context.contains(VerifiableCredential.ELASTOS_CREDENTIAL_CONTEXT) { _credential!._context.append(VerifiableCredential.ELASTOS_CREDENTIAL_CONTEXT) } } if !_credential!.getTypes().contains(VerifiableCredentialBuilder.DEFAULT_CREDENTIAL_TYPE) { _credential!.appendType(VerifiableCredentialBuilder.DEFAULT_CREDENTIAL_TYPE) } } private func maxExpirationDate() -> Date { guard _credential?.issuanceDate == nil else { return DateFormatter.convertToWantDate(_credential!.issuanceDate!, Constants.MAX_VALID_YEARS) } return DateFormatter.convertToWantDate(Date(), Constants.MAX_VALID_YEARS) } }
0
import Foundation public protocol ExpressibleByDictionary: ExpressibleByDictionaryLiteral { init(dictionaryElements: [(Key, Value)]) } extension ExpressibleByDictionary { public init(dictionaryLiteral elements: (Key, Value)...) { self.init(dictionaryElements: elements) } }
0
#!/usr/bin/env xcrun swift // Created by John Liu on 2014/10/02. // Modified by fgatherlet import Foundation import ApplicationServices import CoreVideo // Swift String is quite powerless at the moment // http://stackoverflow.com/questions/24044851 // http://openradar.appspot.com/radar?id=6373877630369792 extension String { func substringFromLastOcurrenceOf(needle:String) -> String { let str = self while let range = str.range(of: needle) { let index2 = str.index(range.lowerBound, offsetBy:1) return String(str[index2 ..< str.endIndex]) } return str } func toUInt() -> UInt? { if let num = Int(self) { return UInt(num) } return nil } } var display_num_max:UInt32 = 8 var display_num_:UInt32 = 0 var display_ids = UnsafeMutablePointer<CGDirectDisplayID>.allocate(capacity:Int(display_num_max)) func main () -> Void { let error:CGError = CGGetOnlineDisplayList(display_num_max, display_ids, &display_num_) if (error != .success) { print("ERROR. cannot get online display list.") return } let display_num:Int = Int(display_num_) let argc = CommandLine.arguments.count let argv = CommandLine.arguments if argc <= 1 || argv[1] == "-h" { help() return } if argv[1] == "-l" { for i in 0 ..< display_num { let di = display_info(display_id:display_ids[i], mode:nil) print("Display \(i): \(di.width) * \(di.height) @ \(di.rr)Hz") } return } if argv[1] == "-m" && argc == 3 { let _di = Int(argv[2]) if _di == nil || _di! >= display_num { help() return } let di = _di! let _modes = modes(display_ids[di]) let display_id = display_ids[di] if _modes == nil { return } let modes = _modes! print("Supported Modes for Display \(di):") let nf = NumberFormatter() nf.paddingPosition = NumberFormatter.PadPosition.beforePrefix nf.paddingCharacter = " " // XXX: Swift does not support padding yet nf.minimumIntegerDigits = 3 // XXX for i in 0..<modes.count { let di = display_info(display_id:display_id, mode:modes[i]) print(" \(nf.string(from:NSNumber(value:di.width))!) * \(nf.string(from:NSNumber(value:di.height))!) @ \(di.rr)Hz") } //} return } if argv[1] == "-s" && argc == 4 { let _di = Int(argv[2]) let _designated_width = argv[3].toUInt() if (_di == nil || _designated_width == nil || _di! >= display_num) { help() return } let di = _di! let designated_width = _designated_width! if let modes = modes(display_ids[di]) { var mode_index:Int? for i in 0..<modes.count { let di = display_info(display_id:display_ids[di], mode:modes[i]) if di.width == designated_width { mode_index = i break } } if mode_index == nil { print("this mode is unavailable for current desktop") return } print("setting display mode") let display = display_ids[di] let mode = modes[mode_index!] if !mode.isUsableForDesktopGUI() { print("this mode is unavailable for current desktop") return } let config = UnsafeMutablePointer<CGDisplayConfigRef?>.allocate(capacity:1); let result = CGBeginDisplayConfiguration(config) if result != .success { return } let option:CGConfigureOption = CGConfigureOption(rawValue:2) CGConfigureDisplayWithDisplayMode(config.pointee, display, mode, nil) let check_result = CGCompleteDisplayConfiguration(config.pointee, option) if check_result != .success { CGCancelDisplayConfiguration(config.pointee) } } return } help() } func modes(_ display_id:CGDirectDisplayID?) -> [CGDisplayMode]? { if display_id == nil { return nil } if let mode_list = CGDisplayCopyAllDisplayModes(display_id!, nil) { var mode_array = [CGDisplayMode]() let count = CFArrayGetCount(mode_list) for i in 0..<count { let mode_raw = CFArrayGetValueAtIndex(mode_list, i) // https://github.com/FUKUZAWA-Tadashi/FHCCommander let mode = unsafeBitCast(mode_raw, to:CGDisplayMode.self) mode_array.append(mode) } return mode_array } return nil } struct DisplayInfo { var width:UInt, height:UInt, rr:UInt } func display_info(display_id:CGDirectDisplayID, mode:CGDisplayMode?) -> DisplayInfo { let mode = (mode == nil) ? CGDisplayCopyDisplayMode(display_id)! : mode! let width = UInt(mode.width) let height = UInt(mode.height) var rr = UInt(mode.refreshRate) if rr == 0 { var link:CVDisplayLink? CVDisplayLinkCreateWithCGDisplay(display_id, &link) let time:CVTime = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link!) let time_value = time.timeValue as Int64 let time_scale = Int64(time.timeScale) + time_value / 2 rr = UInt( time_scale / time_value ) } return DisplayInfo(width:width, height:height, rr:rr) } func help() { print(""" usage: command [-h] [-l] [-m display_index] [-s display_index width] Here are some examples: -h get help -l list displays -m 0 list all mode from a certain display -s 0 800 set resolution of display 0 to 800*600 """) } // run it main()
0
// // OMDbObject.swift // OMDbSearch // // Created by Galo Paz on 3/1/15. // Copyright (c) 2015 Galo Paz. All rights reserved. // import UIKit class OMDbObject { var title: String? var year: Int? var rated: String? var releaseDate: NSDate? var runtimeMins: Int? var genres: [String]? var directors: [String]? var writers: [String]? var actors: [String]? var plot: String? var languages: [String]? var countries: [String]? var awards: String? var poster: String? var metascore: Int? var imdbRating: Float? var imdbVotes: Int? var imdbId: String? var type: String? var response: Bool? var error: String? var tomatoRatings: RottenTomatoRatings init(jsonDict: NSDictionary) { title = jsonDict["Title"] as String? if var s = jsonDict["Year"] as String? { year = s.toInt() } rated = jsonDict["Rated"] as String? if var s = jsonDict["Released"] as String? { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd LLL yyyy" releaseDate = dateFormatter.dateFromString(s) } if var s = jsonDict["Runtime"] as String? { var parts = s.componentsSeparatedByString(" ") if parts.count > 0 { runtimeMins = parts[0].toInt() } } if var s = jsonDict["Genre"] as String? { genres = s.componentsSeparatedByString(", ") } if var s = jsonDict["Director"] as String? { directors = s.componentsSeparatedByString(", ") } if var s = jsonDict["Writer"] as String? { writers = s.componentsSeparatedByString(", ") } if var s = jsonDict["Actors"] as String? { actors = s.componentsSeparatedByString(", ") } plot = jsonDict["Plot"] as String? if var s = jsonDict["Language"] as String? { languages = s.componentsSeparatedByString(", ") } if var s = jsonDict["Country"] as String? { countries = s.componentsSeparatedByString(", ") } awards = jsonDict["Awards"] as String? poster = jsonDict["Poster"] as String? if var s = jsonDict["Metascore"] as String? { metascore = s.toInt() } if var s = jsonDict["imdbRating"] as String? { imdbRating = (s as NSString).floatValue } if var s = jsonDict["imdbVotes"] as String? { imdbVotes = s.stringByReplacingOccurrencesOfString(",", withString: "", options: nil, range: nil).toInt() } imdbId = jsonDict["imdbID"] as String? type = jsonDict["Type"] as String? if var s = jsonDict["Response"] as String? { response = (s as NSString).boolValue } error = jsonDict["Error"] as String? tomatoRatings = RottenTomatoRatings(jsonDict: jsonDict) } } class RottenTomatoRatings { var tomatoMeter: Int? var tomatoImage: String? var tomatoRating: Float? var tomatoReviews: Int? var tomatoFresh: Int? var tomatoRotten: Int? var tomatoConsensus: String? var tomatoUserMeter: Int? var tomatoUserRating: Float? var tomatoUserReviews: Int? var dvdReleaseDate: NSDate? var boxOfficeRevenueMillions: Float? var production: String? var website: String? init(jsonDict: NSDictionary) { if var s = jsonDict["tomatoMeter"] as String? { tomatoMeter = s.toInt() } tomatoImage = jsonDict["tomatoImage"] as String? if var s = jsonDict["tomatoRating"] as String? { tomatoRating = (s as NSString).floatValue } if var s = jsonDict["tomatoReviews"] as String? { tomatoReviews = s.stringByReplacingOccurrencesOfString(",", withString: "", options: nil, range: nil).toInt() } if var s = jsonDict["tomatoFresh"] as String? { tomatoFresh = s.stringByReplacingOccurrencesOfString(",", withString: "", options: nil, range: nil).toInt() } if var s = jsonDict["tomatoRotten"] as String? { tomatoRotten = s.stringByReplacingOccurrencesOfString(",", withString: "", options: nil, range: nil).toInt() } tomatoConsensus = jsonDict["tomatoConsensus"] as String? if let s = jsonDict["tomatoUserMeter"] as String? { tomatoUserMeter = s.toInt() } if let s = jsonDict["tomatoUserRating"] as String? { tomatoUserRating = (s as NSString).floatValue } if let s = jsonDict["tomatoUserReviews"] as String? { tomatoUserReviews = s.stringByReplacingOccurrencesOfString(",", withString: "", options: nil, range: nil).toInt() } if let s = jsonDict["DVD"] as String? { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd LLL yyyy" dvdReleaseDate = dateFormatter.dateFromString(s) } if let s = jsonDict["BoxOffice"] as String? { let floatStr = s.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "$M")) boxOfficeRevenueMillions = (floatStr as NSString).floatValue } production = jsonDict["Production"] as String? website = jsonDict["Website"] as String? } }
0
import Foundation public extension PlatformClient { /* Model: DepartmentCreateResponse Used By: Catalog */ class DepartmentCreateResponse: Codable { public var uid: Int public var message: String public enum CodingKeys: String, CodingKey { case uid case message } public init(message: String, uid: Int) { self.uid = uid self.message = message } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) uid = try container.decode(Int.self, forKey: .uid) message = try container.decode(String.self, forKey: .message) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try? container.encodeIfPresent(uid, forKey: .uid) try? container.encodeIfPresent(message, forKey: .message) } } }
0
import SwiftUI import os.log import Looping private extension OSLog { private static var subsystem = Bundle.main.bundleIdentifier! static let viewCycle = OSLog(subsystem: subsystem, category: "viewcycle") } struct AssetCell: View { private let name: String @State private var isPlaying: Bool = true init(_ name: String) { self.name = name } var body: some View { VStack(alignment: .center) { Loop(name, isPlaying: $isPlaying) { Text("Image is loading...") } .onPlay { os_log("%{PUBLIC}@(1) > play", log: OSLog.viewCycle, type: .info, self.name) } .onPause { os_log("%{PUBLIC}@(1) > pause", log: OSLog.viewCycle, type: .info, self.name) } .onRender { (index, fromCache) in os_log("%{PUBLIC}@(1) > render %{PUBLIC}@", log: OSLog.viewCycle, type: .info, self.name, fromCache ? "from cache" : "from context") } .onComplete { loopMode in os_log("%{PUBLIC}@(1) > complete %{PUBLIC}@", log: OSLog.viewCycle, type: .info, self.name, loopMode.description) } .playBackSpeedRate(0.5) .resizable() .antialiased(true) .scaledToFit() Loop(try! LoopImage(named: name), isPlaying: $isPlaying) { EmptyView() } .onPlay { os_log("%{PUBLIC}@(2) > play", log: OSLog.viewCycle, type: .info, self.name) } .onPause { os_log("%{PUBLIC}@(2) > pause", log: OSLog.viewCycle, type: .info, self.name) } .onRender { (index, fromCache) in os_log("%{PUBLIC}@(2) > render %{PUBLIC}@", log: OSLog.viewCycle, type: .info, self.name, fromCache ? "from cache" : "from context") } .onComplete { loopMode in os_log("%{PUBLIC}@(2) > complete %{PUBLIC}@", log: OSLog.viewCycle, type: .info, self.name, loopMode.description) } .loopMode(.infinite) .playBackSpeedRate(4) .resizable() .interpolation(.high) .antialiased(true) .renderingMode(.template) .foregroundColor(.blue) .background(Color.red.opacity(0.1)) .scaledToFit() .frame(width: 200, height: 200) .clipped(antialiased: true) Loop(name, isPlaying: $isPlaying) { EmptyView() } .onPlay { os_log("%{PUBLIC}@(3) > play", log: OSLog.viewCycle, type: .info, self.name) } .onPause { os_log("%{PUBLIC}@(3) > pause", log: OSLog.viewCycle, type: .info, self.name) } .onRender { (index, fromCache) in os_log("%{PUBLIC}@(3) > render %{PUBLIC}@", log: OSLog.viewCycle, type: .info, self.name, fromCache ? "from cache" : "from context") } .onComplete { loopMode in os_log("%{PUBLIC}@(3) > complete %{PUBLIC}@", log: OSLog.viewCycle, type: .info, self.name, loopMode.description) } .loopMode(.infinite) .playBackSpeedRate(4) .resizable() .scaledToFill() .frame(width: 200, height: 200) .clipped(antialiased: true) } .onAppear(perform: { os_log("%{PUBLIC}@ > appear", log: OSLog.viewCycle, type: .info, self.name); self.isPlaying = true }) .onDisappear(perform: { os_log("%{PUBLIC}@ > disappear", log: OSLog.viewCycle, type: .info, self.name); self.isPlaying = false }) } } struct AssetsSection: View { let title: String let assets: [ImageAsset] var body: some View { Section(header: Text(title)) { ForEach(assets.compactMap { $0.filename }, id: \.self) { filename in NavigationLink(destination: AssetCell(filename!)) { Text(filename!) } } } } } struct ContentView: View { var body: some View { NavigationView { List { AssetsSection(title: "Animations", assets: ImageAsset.animations) AssetsSection(title: "Stills", assets: ImageAsset.stills) } .navigationBarTitle("Looping") .listStyle(GroupedListStyle()) } } } #if DEBUG struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } #endif
0
// // SearchData.swift // turntable // // Created by Mark Brown on 20/04/2019. // Copyright © 2019 Mark Brown. All rights reserved. // import LBTAComponents // Set the search results as the datasource for the search results collection view. class SearchData: Datasource { override func cellClasses() -> [DatasourceCell.Type] { return [SearchResultCell.self] } override func item(_ indexPath: IndexPath) -> Any? { return SearchResultsManager.shared().searchResults[indexPath.item] } override func numberOfItems(_ section: Int) -> Int { return SearchResultsManager.shared().searchResults.count } }
0
// // Transition+AnimoInternals.swift // Animo // // Copyright © 2016 eureka, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import QuartzCore // MARK: - Transition internal extension Transition { // MARK: Internal internal func applyTo(_ object: CATransition) { func subtypeForCATransition(_ direction: Direction) -> CATransitionSubtype { switch direction { case .leftToRight: return CATransitionSubtype.fromLeft case .rightToLeft: return CATransitionSubtype.fromRight case .topToBottom: return CATransitionSubtype.fromTop case .bottomToTop: return CATransitionSubtype.fromBottom } } switch self { case .fade: object.type = CATransitionType.fade object.subtype = nil case .moveIn(let direction): object.type = CATransitionType.moveIn object.subtype = subtypeForCATransition(direction) case .push(let direction): object.type = CATransitionType.push object.subtype = subtypeForCATransition(direction) case .reveal(let direction): object.type = CATransitionType.reveal object.subtype = subtypeForCATransition(direction) } } }
0
// // AlbumListViewController.swift // LastFm // // Created by Tiago Valente on 28/05/2019. // Copyright © 2019 Tiago Valente. All rights reserved. // import UIKit class AlbumListViewController: UIViewController { var viewModel: AlbumListViewModel init() { self.viewModel = AlbumListViewModel.init() super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() view.backgroundColor = .white let tableView = UITableView.init(frame: CGRect.zero, style: .plain) view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false let tableViewTopConstraint = tableView.topAnchor.constraint(equalTo: view.topAnchor) let tableViewLeadingConstraint = tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor) let tableViewTrailingConstraint = tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor) let tableViewBottomConstraint = tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) viewModel.tableView = tableView view.addConstraints([tableViewTopConstraint, tableViewLeadingConstraint, tableViewTrailingConstraint, tableViewBottomConstraint]) viewModel.onAlbumSelectionEvent = { [weak self] album in let detailController = AlbumDetailViewController.init() detailController.viewModel.selectedAlbum = album self?.navigationController?.pushViewController(detailController, animated: true) } } override func viewDidLoad() { super.viewDidLoad() viewModel.fetchData() } }
0
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "CupcakeCorner", dependencies: [ // 💧 A server-side Swift web framework. .package(url: "https://github.com/vapor/vapor.git", .upToNextMinor(from: "3.1.0")),.package(url: "https://github.com/vapor/leaf.git", .upToNextMinor(from: "3.0.0")),.package(url: "https://github.com/vapor/fluent-sqlite.git", .upToNextMinor(from: "3.0.0")) ], targets: [ .target(name: "App", dependencies: ["Vapor","Leaf","FluentSQLite"]), .target(name: "Run", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App"]), ] )
0
// // CreatePostAssembly.swift // Lemmy-iOS // // Created by uuttff8 on 20.11.2020. // Copyright © 2020 Anton Kuzmin. All rights reserved. // import UIKit final class CreatePostAssembly: Assembly { private let predefinedCommunity: LMModels.Views.CommunityView? init(predefinedCommunity: LMModels.Views.CommunityView? = nil) { self.predefinedCommunity = predefinedCommunity } func makeModule() -> CreatePostScreenViewController { let viewModel = CreatePostViewModel() let vc = CreatePostScreenViewController( viewModel: viewModel, predefinedCommunity: self.predefinedCommunity ) viewModel.viewController = vc return vc } }
0
@testable import Fosdem import SnapshotTesting import XCTest final class WelcomeViewControllerTests: XCTestCase { func testAppearance() throws { let welcomeViewController = WelcomeViewController(year: 2021) welcomeViewController.view.tintColor = .fos_label assertSnapshot(matching: welcomeViewController, as: .image(on: .iPhone8Plus)) welcomeViewController.showsContinue = true assertSnapshot(matching: welcomeViewController, as: .image(on: .iPhone8Plus)) welcomeViewController.showsContinue = false assertSnapshot(matching: welcomeViewController, as: .image(on: .iPhone8Plus)) } func testEvents() throws { let delegate = WelcomeViewControllerDelegateMock() let welcomeViewController = WelcomeViewController(year: 2021) welcomeViewController.showsContinue = true welcomeViewController.delegate = delegate let continueButton = welcomeViewController.view.findSubview(ofType: UIButton.self, accessibilityIdentifier: "continue") continueButton?.sendActions(for: .touchUpInside) XCTAssertEqual(delegate.welcomeViewControllerDidTapContinueArgValues, [welcomeViewController]) } }
0
// // PhotoCell.swift // TumblrFeed // // Created by user143252 on 8/4/18. // Copyright © 2018 notserpp. All rights reserved. // import UIKit class PhotoCell: UITableViewCell { @IBOutlet weak var photoView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
0
// // ImagesCollectionViewCell.swift // FourSquare // // Created by Duy Linh on 5/4/17. // Copyright © 2017 Duy Linh. All rights reserved. // import UIKit class ImagesCollectionViewCell: UICollectionViewCell { // MARK: Properties @IBOutlet private weak var venueImageView: UIImageView! // MARK: Lifecycle override func awakeFromNib() { super.awakeFromNib() } // MARK: Public func setupData(photo: Photo) { venueImageView.sd_setImage(with: photo.photoPathString) } }
0
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [ f : { protocol A { class A { class case ,
0
// // Device.swift // Sure-Fi-Chat // // Created by Sure-Fi Inc. on 12/6/17. // Copyright © 2017 Sure-Fi Inc. All rights reserved. // import Foundation struct PropertyKey { static let id = "id" static let name = "name" static let device_id = "device_id" static let advertisement_state = "advertisement_state" static let paired_id = "paired_id" static let bluetooth_connection = "bluetooth_connection" } /* static let id: String! static let name: String! static let device_id: String! static let advertisement_state : String! static let paired_id : String! static let bluetooth_connection : Int! { */ /* class used to save the bridge like a persistent data */ import UIKit import os.log class Device : NSObject, NSCoding { var id: String! var name: String! var device_id: String! var advertisement_state : String! var paired_id : String! var bluetooth_connection : Int! static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! static let ArchiveURL = DocumentsDirectory.appendingPathComponent("devices") init(id:String, name:String?, device_id:String?,advertisement_state:String?,paired_id:String?,bluetooth_connection: Int?){ self.id = id self.name = name self.device_id = device_id self.advertisement_state = advertisement_state self.paired_id = paired_id self.bluetooth_connection = bluetooth_connection } //MARK: NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(id,forKey: PropertyKey.id) aCoder.encode(name,forKey: PropertyKey.name) aCoder.encode(device_id,forKey: PropertyKey.device_id) aCoder.encode(advertisement_state,forKey: PropertyKey.advertisement_state) aCoder.encode(paired_id,forKey: PropertyKey.paired_id) aCoder.encode(bluetooth_connection,forKey: PropertyKey.bluetooth_connection) } required convenience init?(coder aDecoder: NSCoder) { guard let id = aDecoder.decodeObject(forKey: PropertyKey.id) as? String else { os_log("Unable to decode the id for a Decoder object.", log: OSLog.default, type: .debug) return nil } guard let device_id = aDecoder.decodeObject(forKey: PropertyKey.device_id) as? String else{ os_log("Unable to decode the device_id for Device object.", log: OSLog.default, type : .debug) return nil } let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String let advertisement_state = aDecoder.decodeObject(forKey: PropertyKey.advertisement_state) as? String let paired_id = aDecoder.decodeObject(forKey : PropertyKey.paired_id) as? String //let bluetooth_connection = aDecoder.decodeInteger(forKey: PropertyKey.bluetooth_connection) self.init( id:id, name:name, device_id: device_id, advertisement_state:advertisement_state, paired_id:paired_id, bluetooth_connection : 0 ) } }
0
// // TweetCard.swift // brain-marks // // Created by Shloak Aggarwal on 11/04/21. // import SwiftUI struct TweetCard: View { @State var tweet: AWSTweet var body: some View { VStack(alignment: .leading) { TweetHeaderView(tweet: tweet) if (tweet.text!.removingUrls() != "") { TweetBodyView(tweetBody: tweet.text!.removingUrls()) } TweetPhotosView(width: 60, maxWidth: 400, photosURL: tweet.photosURL ?? [String]()) if let timeStamp = tweet.timeStamp { TimeStampView(timeStamp: timeStamp) } } } } struct TweetHeaderView: View { let tweet: AWSTweet var body: some View { HStack { UserIconView(url: tweet.profileImageURL ?? "", size: 55) UserInfoView(authorName: tweet.authorName ?? "", authorUsername: tweet.authorUsername ?? "", userVerified: tweet.userVerified ?? false) Spacer() } .padding(EdgeInsets(top: 18, leading: 18, bottom: 18, trailing: 18)) } } struct TweetBodyView: View { let tweetBody: String var body: some View { TextHighlightingHashtags(tweetBody) .font(.body) .lineSpacing(8.0) .padding(EdgeInsets(top: 0, leading: 18, bottom: 18, trailing: 18)) .fixedSize(horizontal: false, vertical: true) } } struct TweetFooterView: View { var body: some View { VStack(alignment: .leading) { TweetInfoView() Divider().padding(EdgeInsets(top: 0, leading: 18, bottom: 6, trailing: 18)) InteractionsView() Divider().padding(EdgeInsets(top: 4, leading: 18, bottom: 0, trailing: 18)) } } } struct UserIconView: View { @State var url: String var size: CGFloat var body: some View { ZStack { AsyncImage(url: URL(string: url)!, placeholder: { Image(systemName: "person.fill").accentColor(Color(UIColor.label)) }) .aspectRatio(contentMode: .fit) .frame(width: size, height: size) .clipShape(Circle()) } } } struct UserInfoView: View { let authorName: String let authorUsername: String let userVerified: Bool var body: some View { HStack(alignment: .firstTextBaseline) { VStack(alignment: .leading, spacing: 0) { HStack(spacing: 4) { Text(authorName) .font(.headline) .fontWeight(.semibold) if userVerified { Image("verified") .resizable() .frame(width: 14, height: 14, alignment: .center) } } Text("@\(authorUsername)") .font(.callout) .foregroundColor(.secondary) } Spacer() } } } struct TweetInfoView: View { var body: some View { HStack(spacing: 0) { Text("9:58 PM・9/5/20・") .font(.callout) .foregroundColor(.secondary) Text("Twitter for iPhone") .font(.callout) .foregroundColor(Color(UIColor(named: "twitter")!)) } .padding(EdgeInsets(top: 18, leading: 18, bottom: 6, trailing: 18)) } } struct InteractionsView: View { var body: some View { HStack { HStack(spacing: 4) { Text("501K") .font(.system(size: 16, weight: .semibold, design: .default)) Text("Retweets") .font(.callout) .foregroundColor(.secondary) } HStack(spacing: 4) { Text("9,847") .font(.system(size: 16, weight: .semibold, design: .default)) Text("Quote Tweets") .font(.callout) .foregroundColor(.secondary) } HStack(spacing: 4) { Text("1M") .font(.system(size: 16, weight: .semibold, design: .default)) Text("Likes") .font(.callout) .foregroundColor(.secondary) } }.padding(.horizontal) } } struct TimeStampView: View { let timeStamp: String var body: some View { Text(timeStamp.formatTimestamp()) .font(.callout) .foregroundColor(.secondary) .padding(.horizontal, 18) } } // swiftlint:disable shorthand_operator private extension TweetBodyView { /// Use this Text View to highlight and #s in tweets following Twitter's hashtag rules. /// Only alphanumeric characters directly after a # symbol will be highlighted. /// Any other symbols before or after a # will not be highlighted. /// - Parameter tweet: The string to have occurances of hashtags highlighted. /// - Returns: A text view where words preceeded by "#" are highlighted. func TextHighlightingHashtags(_ tweet: String) -> Text { guard tweet.contains("#") else { return Text(tweet) } var output = Text("") let words = tweet.split(separator: " ") for word in words { if let hashtagIndex = word.firstIndex(of: "#") { // Avoid highlighting the first part of a word preceeding a # let prefixString = word.prefix(upTo: hashtagIndex) output = output + Text(" ") + Text(prefixString) let hashtagIndexPlusOne = word.index(hashtagIndex, offsetBy: 1) let hashtagPlusSuffixString = word.suffix( from: hashtagIndexPlusOne) if let suffixIndex = hashtagPlusSuffixString.firstIndex( where: {!$0.isNumber && !$0.isLetter}) { // If the # word is followed by non-alphanumeric symbols do not highlight the symbols let hashtagString = hashtagPlusSuffixString.prefix( upTo: suffixIndex) if hashtagString.count < 1 { // If # is on its own or followed by symbols do not highlight. output = output + Text("#") } else { let hashtagText = Text("#" + hashtagString) .foregroundColor(Color("twitter")) output = output + hashtagText } let suffixString = hashtagPlusSuffixString[suffixIndex...] output = output + Text(suffixString) } else { // If there are no symbols at the end of a string highlight the whole string after the # output = output + Text("#" + hashtagPlusSuffixString).foregroundColor(Color("twitter")) } } else { // If word does not contain # do not highlight output = output + Text(" ") + Text(String(word)) } } return output } } struct TweetCard_Previews: PreviewProvider { static var previews: some View { Group { TweetCard(tweet: AWSTweet.exampleAWSTweets[0]) TweetCard(tweet: AWSTweet.exampleAWSTweets[1]) TweetCard(tweet: AWSTweet.exampleAWSTweets[2]) TweetCard(tweet: AWSTweet.exampleAWSTweets[3]) TweetCard(tweet: AWSTweet.exampleAWSTweets[4]) } .previewLayout(PreviewLayout.sizeThatFits) } }
0
// // KGNSpriteKitTests.swift // KGNSpriteKitTests // // Created by David Keegan on 10/12/15. // Copyright © 2015 David Keegan. All rights reserved. // import XCTest @testable import KGNSpriteKit class KGNSpriteKitTests: XCTestCase { }
0
// // SupportViewController.swift // AlphaWallet // // Created by Vladyslav Shepitko on 04.06.2020. // import UIKit protocol SupportViewControllerDelegate: class, CanOpenURL { } class SupportViewController: UIViewController { private lazy var viewModel: SupportViewModel = SupportViewModel() private let tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .plain) tableView.tableFooterView = UIView() tableView.register(SettingViewHeader.self, forHeaderFooterViewReuseIdentifier: SettingViewHeader.reuseIdentifier) tableView.register(SettingTableViewCell.self, forCellReuseIdentifier: SettingTableViewCell.reuseIdentifier) tableView.separatorStyle = .singleLine tableView.backgroundColor = GroupedTable.Color.background return tableView }() weak var delegate: SupportViewControllerDelegate? override func loadView() { view = tableView } init() { super.init(nibName: nil, bundle: nil) tableView.dataSource = self tableView.delegate = self } override func viewDidLoad() { super.viewDidLoad() title = viewModel.title view.backgroundColor = Screen.Setting.Color.background navigationItem.largeTitleDisplayMode = .never tableView.backgroundColor = GroupedTable.Color.background } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension SupportViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.rows.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SettingTableViewCell.reuseIdentifier, for: indexPath) as! SettingTableViewCell cell.configure(viewModel: viewModel.cellViewModel(indexPath: indexPath)) return cell } } extension SupportViewController: HelpViewControllerDelegate { } extension SupportViewController: CanOpenURL { func didPressViewContractWebPage(forContract contract: AlphaWallet.Address, server: RPCServer, in viewController: UIViewController) { delegate?.didPressViewContractWebPage(forContract: contract, server: server, in: viewController) } func didPressViewContractWebPage(_ url: URL, in viewController: UIViewController) { delegate?.didPressViewContractWebPage(url, in: viewController) } func didPressOpenWebPage(_ url: URL, in viewController: UIViewController) { delegate?.didPressOpenWebPage(url, in: viewController) } } extension SupportViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return nil } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.01 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch viewModel.rows[indexPath.row] { case .faq: let viewController = HelpViewController(delegate: self) viewController.navigationItem.largeTitleDisplayMode = .never viewController.hidesBottomBarWhenPushed = true navigationController?.pushViewController(viewController, animated: true) case .telegram: openURL(.telegram) case .twitter: openURL(.twitter) case .reddit: openURL(.reddit) case .facebook: openURL(.facebook) case .blog: break } } private func openURL(_ provider: URLServiceProvider) { if let localURL = provider.localURL, UIApplication.shared.canOpenURL(localURL) { UIApplication.shared.open(localURL, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: .none) } else { self.delegate?.didPressOpenWebPage(provider.remoteURL, in: self) } } } // Helper function inserted by Swift 4.2 migrator. private func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value) } ) }
0
// // GuestPointer.swift // PsychopompNX // // Created by Sera Brocious on 12/4/20. // import Foundation infix operator ~+: AdditionPrecedence prefix operator * class GuestPointer<T> { let address: UInt64 init(_ address: UInt64) { self.address = address } subscript(index: Int) -> T { get { try! Vmm.instance!.readVirtMem(address + UInt64(index * MemoryLayout<T>.size)) } set { try! Vmm.instance!.writeVirtMem(address + UInt64(index * MemoryLayout<T>.size), newValue) } } subscript(range: Range<Int>) -> [T] { get { range.map { self[$0] } } set { newValue.enumerated().forEach { self[$0.offset] = $0.element } } } func to<T2>() -> GuestPointer<T2> { GuestPointer<T2>(address) } static func +(left: GuestPointer<T>, right: Int) -> GuestPointer<T> { GuestPointer<T>(left.address + UInt64(right * MemoryLayout<T>.size)) } static func +(left: GuestPointer<T>, right: UInt64) -> GuestPointer<T> { GuestPointer<T>(left.address + right * UInt64(MemoryLayout<T>.size)) } static func ~+(left: GuestPointer<T>, right: Int) -> GuestPointer<T> { GuestPointer<T>(left.address + UInt64(right)) } static func ~+(left: GuestPointer<T>, right: UInt64) -> GuestPointer<T> { GuestPointer<T>(left.address + right) } static prefix func *(left: GuestPointer<T>) throws -> T { try Vmm.instance!.readVirtMem(left.address) } } class GuestPhysicalPointer<T> { let address: UInt64 init(_ address: UInt64) { self.address = address } subscript(index: Int) -> T { get { try! Vmm.instance!.readPhysMem(address + UInt64(index * MemoryLayout<T>.size)) } set { try! Vmm.instance!.writePhysMem(address + UInt64(index * MemoryLayout<T>.size), newValue) } } subscript(range: Range<Int>) -> [T] { get { range.map { self[$0] } } } func to<T2>() -> GuestPhysicalPointer<T2> { GuestPhysicalPointer<T2>(address) } static func +(left: GuestPhysicalPointer<T>, right: Int) -> GuestPhysicalPointer<T> { GuestPhysicalPointer<T>(left.address + UInt64(right * MemoryLayout<T>.size)) } static func +(left: GuestPhysicalPointer<T>, right: UInt64) -> GuestPhysicalPointer<T> { GuestPhysicalPointer<T>(left.address + right * UInt64(MemoryLayout<T>.size)) } static func ~+(left: GuestPhysicalPointer<T>, right: Int) -> GuestPhysicalPointer<T> { GuestPhysicalPointer<T>(left.address + UInt64(right)) } static func ~+(left: GuestPhysicalPointer<T>, right: UInt64) -> GuestPhysicalPointer<T> { GuestPhysicalPointer<T>(left.address + right) } static prefix func *(left: GuestPhysicalPointer<T>) throws -> T { try Vmm.instance!.readPhysMem(left.address) } }
0
import RxSwift import EthereumKit import Erc20Kit import NftKit import UniswapKit import OneInchKit import HdWalletKit class Manager { static let shared = Manager() private let keyWords = "mnemonic_words" private let keyAddress = "address" var signer: EthereumKit.Signer! var evmKit: EthereumKit.Kit! var nftKit: NftKit.Kit! var uniswapKit: UniswapKit.Kit? var oneInchKit: OneInchKit.Kit? var ethereumAdapter: IAdapter! var erc20Adapters = [IAdapter]() var erc20Tokens = [String: String]() init() { if let words = savedWords { initEthereumKit(words: words) } } func login(words: [String]) { try! EthereumKit.Kit.clear(exceptFor: ["walletId"]) try! NftKit.Kit.clear(exceptFor: ["walletId"]) save(words: words) initEthereumKit(words: words) } func watch(address: Address) { try! EthereumKit.Kit.clear(exceptFor: ["walletId"]) try! NftKit.Kit.clear(exceptFor: ["walletId"]) save(address: address.hex) initEthereumKit(address: address) } func logout() { clearWords() signer = nil evmKit = nil nftKit = nil uniswapKit = nil oneInchKit = nil ethereumAdapter = nil erc20Adapters = [] } private func initEthereumKit(words: [String]) { let configuration = Configuration.shared let seed = Mnemonic.seed(mnemonic: words) let signer = try! Signer.instance( seed: seed, chain: configuration.chain ) let evmKit = try! EthereumKit.Kit.instance( address: Signer.address(seed: seed, chain: configuration.chain), chain: configuration.chain, rpcSource: configuration.rpcSource, transactionSource: configuration.transactionSource, walletId: "walletId", minLogLevel: configuration.minLogLevel ) nftKit = try! NftKit.Kit.instance(evmKit: evmKit) uniswapKit = try! UniswapKit.Kit.instance(evmKit: evmKit) oneInchKit = try! OneInchKit.Kit.instance(evmKit: evmKit) ethereumAdapter = EthereumAdapter(signer: signer, ethereumKit: evmKit) for token in configuration.erc20Tokens { let adapter = Erc20Adapter(signer: signer, ethereumKit: evmKit, token: token) erc20Adapters.append(adapter) erc20Tokens[token.contractAddress.eip55] = token.coin } self.signer = signer self.evmKit = evmKit Erc20Kit.Kit.addDecorators(to: evmKit) Erc20Kit.Kit.addTransactionSyncer(to: evmKit) nftKit.addEip721TransactionSyncer() nftKit.addEip1155TransactionSyncer() nftKit.addEip721Decorators() nftKit.addEip1155Decorators() UniswapKit.Kit.addDecorators(to: evmKit) OneInchKit.Kit.addDecorators(to: evmKit) evmKit.start() nftKit.sync() for adapter in erc20Adapters { adapter.start() } } private func initEthereumKit(address: Address) { let configuration = Configuration.shared let evmKit = try! Kit.instance(address: address, chain: configuration.chain, rpcSource: configuration.rpcSource, transactionSource: configuration.transactionSource, walletId: "walletId", minLogLevel: configuration.minLogLevel ) nftKit = try! NftKit.Kit.instance(evmKit: evmKit) uniswapKit = try! UniswapKit.Kit.instance(evmKit: evmKit) oneInchKit = try! OneInchKit.Kit.instance(evmKit: evmKit) ethereumAdapter = EthereumBaseAdapter(ethereumKit: evmKit) for token in configuration.erc20Tokens { let adapter = Erc20BaseAdapter(ethereumKit: evmKit, token: token) erc20Adapters.append(adapter) erc20Tokens[token.contractAddress.eip55] = token.coin } self.evmKit = evmKit Erc20Kit.Kit.addDecorators(to: evmKit) Erc20Kit.Kit.addTransactionSyncer(to: evmKit) nftKit.addEip721TransactionSyncer() nftKit.addEip1155TransactionSyncer() nftKit.addEip721Decorators() nftKit.addEip1155Decorators() UniswapKit.Kit.addDecorators(to: evmKit) OneInchKit.Kit.addDecorators(to: evmKit) evmKit.start() nftKit.sync() for adapter in erc20Adapters { adapter.start() } } private var savedWords: [String]? { if let wordsString = UserDefaults.standard.value(forKey: keyWords) as? String { return wordsString.split(separator: " ").map(String.init) } return nil } private func save(words: [String]) { UserDefaults.standard.set(words.joined(separator: " "), forKey: keyWords) UserDefaults.standard.synchronize() } private func save(address: String) { UserDefaults.standard.set(address, forKey: keyAddress) UserDefaults.standard.synchronize() } private func clearWords() { UserDefaults.standard.removeObject(forKey: keyWords) UserDefaults.standard.synchronize() } }
0
// // NotificationSignalTests.swift // SignalKit // // Created by Yanko Dimitrov on 8/12/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import XCTest class NotificationSignalTests: XCTestCase { let center = NSNotificationCenter.defaultCenter() let notificationName = "TestNotification" func testObserveForNotification() { let signal = NotificationSignal(center: center, name: notificationName) var called = false signal.addObserver { _ in called = true } center.postNotificationName(notificationName, object: nil) XCTAssertEqual(called, true, "Should observe for a given notification name") } func testObserveForNotificationFromObject() { let person = Person(name: "Jack") let signal = NotificationSignal(center: center, name: notificationName, fromObject: person) var called = false signal.addObserver { _ in called = true } center.postNotificationName(notificationName, object: person) XCTAssertEqual(called, true, "Should observe for a given notification send by a certain object") } func testDispose() { let signal = NotificationSignal(center: center, name: notificationName) var called = false signal.addObserver { _ in called = true } signal.dispose() center.postNotificationName(notificationName, object: nil) XCTAssertEqual(called, false, "Should dispose the observation") } func testDisposeTheDisposableSource() { let disposableSource = MockDisposable() let signal = NotificationSignal(center: center, name: notificationName) signal.disposableSource = disposableSource signal.dispose() XCTAssertEqual(disposableSource.isDisposeCalled, true, "Should call the disposable source to dispose") } func testDispatchesOnlyNewNotifications() { let notification = NSNotification(name: notificationName, object: nil) let signal = NotificationSignal(center: center, name: notificationName) var result: NSNotification? center.postNotification(notification) signal.addObserver { result = $0 } XCTAssertEqual(result, nil, "The dispatch rule should dispatch only new notifications") } }
0
// // TestSCUpdateOperator.swift // SC // // Created by Alexey Kuznetsov on 27/12/2016. // Copyright © 2016 Prof-IT Group OOO. All rights reserved. // import XCTest class TestSCUpdateOperator: 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 testName() { let set = SCUpdateOperator.set(["fieldName": SCString("ABCD")]) XCTAssertEqual(set.name, "$set") let push = SCUpdateOperator.push(name: "fieldName", value: SCString("A"), each: false) XCTAssertEqual(push.name, "$push") let pull = SCUpdateOperator.pull("fieldName", SCString("A")) XCTAssertEqual(pull.name, "$pull") let pullAll = SCUpdateOperator.pullAll("fieldName", SCString("A")) XCTAssertEqual(pullAll.name, "$pullAll") let addToSet = SCUpdateOperator.addToSet(name: "fieldName", value: SCString("A"), each: false) XCTAssertEqual(addToSet.name, "$addToSet") let pop = SCUpdateOperator.pop("fieldName", 1) XCTAssertEqual(pop.name, "$pop") let inc = SCUpdateOperator.inc("fieldName", SCInt(5)) XCTAssertEqual(inc.name, "$inc") let currentDate = SCUpdateOperator.currentDate("fieldName", "timestamp") XCTAssertEqual(currentDate.name, "$currentDate") let mul = SCUpdateOperator.mul("fieldName", SCInt(5)) XCTAssertEqual(mul.name, "$mul") let min = SCUpdateOperator.min("fieldName", SCInt(5)) XCTAssertEqual(min.name, "$min") let max = SCUpdateOperator.max("fieldName", SCInt(5)) XCTAssertEqual(max.name, "$max") } func testDic() { let set = SCUpdateOperator.set(["fieldName": SCString("ABCD")]) XCTAssertEqual(set.dic as! [String : String], ["fieldName" : "ABCD"]) let push = SCUpdateOperator.push(name: "fieldName", value: SCString("A"), each: false) XCTAssertEqual(push.dic as! [String : String], ["fieldName" : "A"]) let pushEach = SCUpdateOperator.push(name: "fieldName", value: SCString("A"), each: true) XCTAssertEqual((pushEach.dic as! Dictionary)["fieldName"]! , ["$each" : "A"]) let pullValue = SCUpdateOperator.pull("fieldName", SCString("A")) XCTAssertEqual(pullValue.dic as! [String: String], ["fieldName" : "A"]) let pullCondition = SCUpdateOperator.pull("fieldName", SCOperator.notEqualTo("fieldName", SCString("A"))) XCTAssertEqual((pullCondition.dic as! Dictionary)["fieldName"]!, ["$ne" : "A"]) let pullAll = SCUpdateOperator.pullAll("fieldName", SCString("A")) XCTAssertEqual(pullAll.dic as! [String: String], ["fieldName" : "A"]) let addToSet = SCUpdateOperator.addToSet(name: "fieldName", value: SCString("A"), each: false) XCTAssertEqual(addToSet.dic as! [String: String], ["fieldName" : "A"]) let addToSetEach = SCUpdateOperator.addToSet(name: "fieldName", value: SCString("A"), each: true) XCTAssertEqual((addToSetEach.dic as! Dictionary)["fieldName"]!, ["$each": "A"]) let pop = SCUpdateOperator.pop("fieldName", 1) XCTAssertEqual(pop.dic as! [String: Int], ["fieldName" : 1]) let inc = SCUpdateOperator.inc("fieldName", SCInt(5)) XCTAssertEqual(inc.dic as! [String: Int], ["fieldName" : 5]) let currentDate = SCUpdateOperator.currentDate("fieldName", "timestamp") XCTAssertEqual((currentDate.dic as! Dictionary)["fieldName"]!, ["$type" : "timestamp"]) let mul = SCUpdateOperator.mul("fieldName", SCInt(5)) XCTAssertEqual(mul.dic as! [String: Int], ["fieldName" : 5]) let min = SCUpdateOperator.min("fieldName", SCInt(5)) XCTAssertEqual(min.dic as! [String: Int], ["fieldName" : 5]) let max = SCUpdateOperator.max("fieldName", SCInt(5)) XCTAssertEqual(max.dic as! [String: Int], ["fieldName" : 5]) } func testNotEqual() { let push = SCUpdateOperator.push(name: "fieldName", value: SCString("A"), each: false) let pop = SCUpdateOperator.pop("fieldName", 1) XCTAssertEqual(false, push == pop) } }
0
// // SearchFriendsViewController.swift // Blink // // Created by Remi Robert on 22/09/15. // Copyright © 2015 Remi Robert. All rights reserved. // import UIKit import Parse import ReactiveCocoa class SearchFriendsViewController: UIViewController { @IBOutlet var searchBar: UISearchBar! @IBOutlet var tableView: UITableView! var resultSearch = Array<PFObject>() var currentFriends = Array<PFObject>() func searchFriend(searchString: String) { let searchSignal = Friend.searchFriends(searchString) searchSignal.subscribeNext({ (next: AnyObject!) -> Void in self.resultSearch.removeAll() if let users = next as? [PFObject] { self.resultSearch = users self.tableView.reloadData() } }, error: { (error: NSError!) -> Void in }) { () -> Void in } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { searchBar.endEditing(true) } override func viewDidLoad() { super.viewDidLoad() loadCurrentFriends() searchBar.delegate = self self.tableView.dataSource = self tableView.tableFooterView = UIView() tableView.registerNib(UINib(nibName: "SearchUserTableViewCell", bundle: nil), forCellReuseIdentifier: "searchCell") } } //MARK: //MARK: UISearchBar dataSource extension SearchFriendsViewController: UISearchBarDelegate { func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.text = nil searchBar.endEditing(true) } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.endEditing(true) if let searchString = searchBar.text { searchFriend(searchString) } } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchText.characters.count < 2 { return } searchFriend(searchText) } } //MARK: //MARK: UITableView dataSource extension SearchFriendsViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.resultSearch.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("searchCell") as! SearchUserTableViewCell cell.actionSwitchBlock = {(state: Bool) -> Void in if state { self.addFriend(self.resultSearch[indexPath.row]) } else { self.removeFriend(self.resultSearch[indexPath.row]) } } let isFriend = Friend.isFriend(resultSearch[indexPath.row], friends: currentFriends) cell.selectionStyle = UITableViewCellSelectionStyle.None cell.initCellForUser(resultSearch[indexPath.row], isFriend: isFriend) return cell } } //MARK: //MARK: Friends management extension SearchFriendsViewController { func loadCurrentFriends() { Friend.friends(.NetworkOnly).subscribeNext({ (next: AnyObject!) -> Void in self.currentFriends.removeAll() if let friendsList = next as? [PFObject] { self.currentFriends = friendsList print("current friends : \(self.currentFriends)") } self.tableView.reloadData() }, error: { (error: NSError!) -> Void in }) { () -> Void in } } func addFriend(friend: PFObject) { Friend.addFriend(friend).subscribeNext({ (next: AnyObject!) -> Void in }, error: { (error: NSError!) -> Void in print("error add friend : \(error)") }) { () -> Void in self.loadCurrentFriends() } } func removeFriend(friend: PFObject) { Friend.removeFriend(friend).subscribeNext({ (next: AnyObject!) -> Void in }, error: { (error: NSError!) -> Void in print("error remove friend : \(error)") }) {() -> Void in self.loadCurrentFriends() } } }