hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
f9d25104b00bbbe9bb5dee801a02a1f92b115736
1,656
// // RouteComposer // SquareViewController.swift // https://github.com/ekazaev/route-composer // // Created by Eugene Kazaev in 2018-2022. // Distributed under the MIT license. // import RouteComposer import UIKit class SquareViewController: UIViewController, ExampleAnalyticsSupport { let screenType = ExampleScreenTypes.square override func viewDidLoad() { super.viewDidLoad() title = "Square" } @IBAction func goToCircleTapped() { try? router.navigate(to: ConfigurationHolder.configuration.circleScreen, with: nil) } @IBAction func goToHomeTapped() { try? router.navigate(to: ConfigurationHolder.configuration.figuresScreen, with: nil) } @IBAction func goToSplitTapped() { try? router.navigate(to: CitiesConfiguration.citiesList()) } @IBAction func goToLoginTapped() { try? router.navigate(to: LoginConfiguration.login()) } @IBAction func goToStarTapped() { try? router.navigate(to: ConfigurationHolder.configuration.starScreen, with: "Test Context") } @IBAction func goToFakeContainerTapped() { try? router.navigate(to: WishListConfiguration.collections()) } @IBAction func goEmptyAndProductTapped() { try? router.navigate(to: ConfigurationHolder.configuration.figuresAndProductScreen, with: ProductContext(productId: "03")) } @IBAction func switchValueChanged(sender: UISwitch) { if sender.isOn { ConfigurationHolder.configuration = AlternativeExampleConfiguration() } else { ConfigurationHolder.configuration = ExampleConfiguration() } } }
28.067797
130
0.696256
266030bdef4ebfff59decbba8ae4f74cbe6b2736
205
// // Note.swift // Watch-Notes WatchKit Extension // // Created by jigar dave on 14/06/21. // import Foundation struct Note: Identifiable , Codable{ let id: UUID let text: String }
12.8125
38
0.629268
262ce0484e925bfc6e8a4d7196c1edc7cffe9010
10,777
// RUN: %target-typecheck-verify-swift // Leaf expression patterns are matched to corresponding pieces of a switch // subject (TODO: or ~= expression) using ~= overload resolution. switch (1, 2.5, "three") { case (1, _, _): () // Double is ExpressibleByIntegerLiteral case (_, 2, _), (_, 2.5, _), (_, _, "three"): () // ~= overloaded for (Range<Int>, Int) case (0..<10, _, _), (0..<10, 2.5, "three"), (0...9, _, _), (0...9, 2.5, "three"): () default: () } switch (1, 2) { case (var a, a): // expected-error {{use of unresolved identifier 'a'}} () } // 'is' patterns can perform the same checks that 'is' expressions do. protocol P { func p() } class B : P { init() {} func p() {} func b() {} } class D : B { override init() { super.init() } func d() {} } class E { init() {} func e() {} } struct S : P { func p() {} func s() {} } // Existential-to-concrete. var bp : P = B() switch bp { case is B, is D, is S: () case is E: () default: () } switch bp { case let b as B: b.b() case let d as D: d.b() d.d() case let s as S: s.s() case let e as E: e.e() default: () } // Super-to-subclass. var db : B = D() switch db { case is D: () case is E: // expected-warning {{always fails}} () default: () } // Raise an error if pattern productions are used in expressions. var b = var x // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // TODO: Bad recovery in these cases. Although patterns are never valid // expr-unary productions, it would be good to parse them anyway for recovery. //var e = 2 + var y //var e = var y + 2 // 'E.Case' can be used in a dynamic type context as an equivalent to // '.Case as E'. protocol HairType {} enum MacbookHair: HairType { case HairSupply(S) } enum iPadHair<T>: HairType { case HairForceOne } enum Watch { case Sport, Watch, Edition } let hair: HairType = MacbookHair.HairSupply(S()) switch hair { case MacbookHair.HairSupply(let s): s.s() case iPadHair<S>.HairForceOne: () case iPadHair<E>.HairForceOne: () case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}} () case Watch.Edition: // expected-warning {{cast from 'HairType' to unrelated type 'Watch' always fails}} () case .HairForceOne: // expected-error{{type 'HairType' has no member 'HairForceOne'}} () default: break } // <rdar://problem/19382878> Introduce new x? pattern switch Optional(42) { case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}} case nil: break } func SR2066(x: Int?) { // nil literals should still work when wrapped in parentheses switch x { case (nil): break case _?: break } switch x { case ((nil)): break case _?: break } switch (x, x) { case ((nil), _): break case (_?, _): break } } // Test x???? patterns. switch (nil as Int???) { case let x???: print(x, terminator: "") case let x??: print(x as Any, terminator: "") case let x?: print(x as Any, terminator: "") case 4???: break case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}} default: break } switch ("foo" as String?) { case "what": break default: break } // Test some value patterns. let x : Int? extension Int { func method() -> Int { return 42 } } func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } switch 4 as Int? { case x?.method(): break // match value default: break } switch 4 { case x ?? 42: break // match value default: break } for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}} var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} // Crash when re-typechecking EnumElementPattern. // FIXME: This should actually type-check -- the diagnostics are bogus. But // at least we don't crash anymore. protocol PP { associatedtype E } struct A<T> : PP { typealias E = T } extension PP { func map<T>(_ f: (Self.E) -> T) -> T {} } enum EE { case A case B } func good(_ a: A<EE>) -> Int { return a.map { switch $0 { case .A: return 1 default: return 2 } } } func bad(_ a: A<EE>) { a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{none}} let _: EE = $0 return 1 } } func ugly(_ a: A<EE>) { a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{none}} switch $0 { case .A: return 1 default: return 2 } } } // SR-2057 enum SR2057 { case foo } let sr2057: SR2057? if case .foo = sr2057 { } // Ok // Invalid 'is' pattern class SomeClass {} if case let doesNotExist as SomeClass:AlsoDoesNotExist {} // expected-error@-1 {{use of undeclared type 'AlsoDoesNotExist'}} // expected-error@-2 {{variable binding in a condition requires an initializer}} // `.foo` and `.bar(...)` pattern syntax should also be able to match // static members as expr patterns struct StaticMembers: Equatable { init() {} init(_: Int) {} init?(opt: Int) {} static var prop = StaticMembers() static var optProp: Optional = StaticMembers() static func method(_: Int) -> StaticMembers { return prop } // expected-note@-1 {{found candidate with type '(Int) -> StaticMembers'}} static func method(withLabel: Int) -> StaticMembers { return prop } // expected-note@-1 {{found candidate with type '(Int) -> StaticMembers'}} static func optMethod(_: Int) -> StaticMembers? { return optProp } static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true } } let staticMembers = StaticMembers() let optStaticMembers: Optional = StaticMembers() switch staticMembers { case .init: break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(opt:): break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(): break case .init(0): break case .init(_): break // expected-error{{'_' can only appear in a pattern}} case .init(let x): break // expected-error{{cannot appear in an expression}} case .init(opt: 0): break // expected-error{{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}} // expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} // expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} case .prop: break // TODO: repeated error message case .optProp: break // expected-error* {{not unwrapped}} case .method: break // expected-error{{no exact matches in reference to static method 'method'}} case .method(0): break case .method(_): break // expected-error{{'_' can only appear in a pattern}} case .method(let x): break // expected-error{{cannot appear in an expression}} case .method(withLabel:): break // expected-error{{member 'method(withLabel:)' expects argument of type 'Int'}} case .method(withLabel: 0): break case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}} case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}} case .optMethod: break // expected-error{{member 'optMethod' expects argument of type 'Int'}} case .optMethod(0): break // expected-error@-1 {{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}} // expected-note@-2 {{coalesce}} // expected-note@-3 {{force-unwrap}} } _ = 0 // rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining struct S_32241441 { enum E_32241441 { case foo case bar } var type: E_32241441 = E_32241441.foo } func rdar32241441() { let s: S_32241441? = S_32241441() switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}} case .foo: // Ok break; case .bar: // Ok break; } } // SR-6100 struct One<Two> { // expected-note{{'Two' declared as parameter to type 'One'}} public enum E: Error { // if you remove associated value, everything works case SomeError(String) } } func testOne() { do { } catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}} if case One.E.SomeError = error {} // expected-error{{generic parameter 'Two' could not be inferred}} } } // SR-8347 // constrain initializer expressions of optional some pattern bindings to be optional func test8347() -> String { struct C { subscript (s: String) -> String? { return "" } subscript (s: String) -> [String] { return [""] } func f() -> String? { return "" } func f() -> Int { return 3 } func g() -> String { return "" } func h() -> String { return "" } func h() -> Double { return 3.0 } func h() -> Int? { //expected-note{{found this candidate}} return 2 } func h() -> Float? { //expected-note{{found this candidate}} return nil } } let c = C() if let s = c[""] { return s } if let s = c.f() { return s } if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}} return s } if let s = c.h() { //expected-error{{ambiguous use of 'h()'}} return s } } enum SR_7799 { case baz case bar } let sr7799: SR_7799? = .bar switch sr7799 { case .bar?: break // Ok case .baz: break // Ok default: break } let sr7799_1: SR_7799?? = .baz switch sr7799_1 { case .bar?: break // Ok case .baz: break // Ok default: break } if case .baz = sr7799_1 {} // Ok if case .bar? = sr7799_1 {} // Ok
24.71789
208
0.639324
f863f19e2ae1abbda16c42588ee75bde48a35ad6
2,326
// // UIImageViewExtension.swift // SwiftDemo // // Created by weixb on 2018/3/7. // Copyright © 2018年 weixb. All rights reserved. // import UIKit // MARK: - Methods public extension UIImageView { /// SwifterSwift: Set image from a URL. /// /// - Parameters: /// - url: URL of image. /// - contentMode: imageView content mode (default is .scaleAspectFit). /// - placeHolder: optional placeholder image /// - completionHandler: optional completion handler to run when download finishs (default is nil). func download( from url: URL, contentMode: UIView.ContentMode = .scaleAspectFit, placeholder: UIImage? = nil, completionHandler: ((UIImage?) -> Void)? = nil) { image = placeholder self.contentMode = contentMode URLSession.shared.dataTask(with: url) { (data, response, _) in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, let image = UIImage(data: data) else { completionHandler?(nil) return } DispatchQueue.main.async { self.image = image completionHandler?(image) } }.resume() } /// SwifterSwift: Make image view blurry /// /// - Parameter style: UIBlurEffectStyle (default is .light). func blur(withStyle style: UIBlurEffect.Style = .light) { let blurEffect = UIBlurEffect(style: style) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation addSubview(blurEffectView) clipsToBounds = true } /// SwifterSwift: Blurred version of an image view /// /// - Parameter style: UIBlurEffectStyle (default is .light). /// - Returns: blurred version of self. func blurred(withStyle style: UIBlurEffect.Style = .light) -> UIImageView { let imgView = self imgView.blur(withStyle: style) return imgView } }
33.228571
109
0.598452
72acad688412e8c6c7ef08e518f4878b12335cf0
405
// // ReactNativeBridgeDelegate.swift // ReactNativeMultipleRCTRootView // // Created by Fabrizio Duroni on 08.12.17. // import Foundation import React class ReactNativeBridgeDelegate: NSObject, RCTBridgeDelegate { func sourceURL(for bridge: RCTBridge!) -> URL! { return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index.bundle", fallbackResource: nil) } }
23.823529
118
0.74321
fb0d17fde64930d760729180fcd4c520794d1997
2,475
import Foundation import RobinHood protocol SubscanOperationFactoryProtocol { func fetchPriceOperation(_ url: URL, time: Int64) -> BaseOperation<PriceData> func fetchHistoryOperation(_ url: URL, info: HistoryInfo) -> BaseOperation<SubscanHistoryData> } final class SubscanOperationFactory: SubscanOperationFactoryProtocol { func fetchPriceOperation(_ url: URL, time: Int64) -> BaseOperation<PriceData> { let requestFactory = BlockNetworkRequestFactory { var request = URLRequest(url: url) request.httpBody = try JSONEncoder().encode(PriceInfo(time: time)) request.setValue(HttpContentType.json.rawValue, forHTTPHeaderField: HttpHeaderKey.contentType.rawValue) request.httpMethod = HttpMethod.post.rawValue return request } let resultFactory = AnyNetworkResultFactory<PriceData> { data in let resultData = try JSONDecoder().decode(SubscanStatusData<PriceData>.self, from: data) guard resultData.isSuccess, let price = resultData.data else { throw SubscanError(statusData: resultData) } return price } let operation = NetworkOperation(requestFactory: requestFactory, resultFactory: resultFactory) return operation } func fetchHistoryOperation(_ url: URL, info: HistoryInfo) -> BaseOperation<SubscanHistoryData> { let requestFactory = BlockNetworkRequestFactory { var request = URLRequest(url: url) request.httpBody = try JSONEncoder().encode(info) request.setValue(HttpContentType.json.rawValue, forHTTPHeaderField: HttpHeaderKey.contentType.rawValue) request.httpMethod = HttpMethod.post.rawValue return request } let resultFactory = AnyNetworkResultFactory<SubscanHistoryData> { data in let resultData = try JSONDecoder().decode(SubscanStatusData<SubscanHistoryData>.self, from: data) guard resultData.isSuccess, let history = resultData.data else { throw SubscanError(statusData: resultData) } return history } let operation = NetworkOperation(requestFactory: requestFactory, resultFactory: resultFactory) return operation } }
39.919355
102
0.642828
167633540d9af922a1d41a517e4cbd33c847bd97
4,126
import UIKit import tmdb_swift typealias TableDataSource = UITableViewDataSource & UITableViewDelegate struct Pages { var current: Int let total: Int var nextPage: Int? { if current + 1 <= total { return current + 1 } return nil } } protocol DataRetrievable { var dataPages: Pages? { get set } func retrieveData(page: UInt, completionHandler: @escaping (Bool) -> Void) func retrieveNextPage(completionHandler: @escaping (Bool) -> Void) } extension DataRetrievable { func retrieveNextPage(completionHandler: @escaping (Bool) -> Void) { guard let pages = dataPages else { //retrieve 1st page retrieveData(page: 1, completionHandler: completionHandler) return } guard let nextPageIndex = pages.nextPage else { return ///?????? } retrieveData(page: UInt(nextPageIndex), completionHandler: completionHandler) // TODO: fix types } } typealias ExampleDataSource = TableDataSource & DataRetrievable enum MediaType { case movie case tv } protocol Media { var id: Int64 { get } var title: String { get } var imagePath: URL? { get } var overview: String { get } var votes: UInt { get } var averageVote: Double { get } var type: MediaType {get} } extension TMDB.Movies.Movie: Media { var imagePath: URL? { return posterURL() } var type: MediaType { return .movie } } extension TMDB.TV.TVShow: Media { var imagePath: URL? { return posterURL() } var type: MediaType { return .tv } } protocol ExampleDataSourceDelegate: class { func selectItem(item: Media) } class ParentDataSource: NSObject, TableDataSource { var items = [Media]() weak var delegate: ExampleDataSourceDelegate? weak var vc: ViewController? func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ItemTableViewCell.self), for: indexPath) as? ItemTableViewCell else { fatalError() } cell.configure(with: items[indexPath.row]) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.selectItem(item: items[indexPath.row]) } } class MovieDataSource: ParentDataSource, DataRetrievable { var dataPages: Pages? func retrieveData(page: UInt = 1, completionHandler: @escaping (Bool) -> Void) { TMDB.Movies.getPopular(page: page) { [weak self] (result) in guard let strongSelf = self else { return } switch result { case .failure: completionHandler(false) case .success(let pagedResponse): strongSelf.dataPages = Pages(current: pagedResponse.page, total: pagedResponse.totalPages) strongSelf.items.append(contentsOf: pagedResponse.results) completionHandler(true) } } } } class TVShowsDataSource: ParentDataSource, DataRetrievable { var dataPages: Pages? func retrieveData(page: UInt = 1, completionHandler: @escaping (Bool) -> Void) { TMDB.TV.getPopular(page: page) { [weak self] (result) in guard let strongSelf = self else { return } switch result { case .failure: completionHandler(false) case .success(let pagedResponse): strongSelf.dataPages = Pages(current: pagedResponse.page, total: pagedResponse.totalPages) strongSelf.items.append(contentsOf: pagedResponse.results) completionHandler(true) } } } }
28.455172
159
0.636209
224d60942d84f44d93068c4a0ed2119a8797c853
766
// // QueueConversationVideoEventTopicAfterCallWork.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class QueueConversationVideoEventTopicAfterCallWork: Codable { public enum State: String, Codable { case unknown = "UNKNOWN" case skipped = "SKIPPED" case pending = "PENDING" case complete = "COMPLETE" case notApplicable = "NOT_APPLICABLE" } public var state: State? public var startTime: Date? public var endTime: Date? public init(state: State?, startTime: Date?, endTime: Date?) { self.state = state self.startTime = startTime self.endTime = endTime } }
20.157895
69
0.631854
1da281711f3ad1ba65eb2adae009a7fe244ab50f
2,353
// // BRESelectTrackPushTransition.swift // BeaconRangingExample // // Created by Sam Piggott on 09/04/2017. // Copyright © 2017 Sam Piggott. All rights reserved. // import UIKit class BRESelectTrackPushTransition: NSObject, UIViewControllerAnimatedTransitioning { private let transitionDuration:TimeInterval = 1.25 func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return transitionDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? BRESelectTrackViewController else { transitionContext.completeTransition(true); return } let containerView = transitionContext.containerView fromVC.view.frame = transitionContext.initialFrame(for: fromVC) toVC.view.frame = transitionContext.finalFrame(for: toVC) containerView.addSubview(toVC.view) // View setup fromVC.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) fromVC.view.alpha = 1.0 toVC.view.alpha = 0.0 UIView.animate(withDuration: transitionDuration/2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: [.curveEaseOut, .allowUserInteraction], animations: { fromVC.view.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) fromVC.view.alpha = 0.0 }, completion: nil) UIView.animate(withDuration: transitionDuration/2, delay: transitionDuration/4, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: [.curveEaseOut, .allowUserInteraction], animations: { toVC.view.alpha = 1.0 }) { (complete:Bool) in // Reset previous view fromVC.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) fromVC.view.alpha = 1.0 transitionContext.completeTransition(true) } } }
34.602941
207
0.638334
62eb7870aadaef66448ac0b132bd897ebfacb07c
1,469
// // CodeSystems.swift // HealthRecords // // Generated from FHIR 4.5.0-a621ed4bdc // Copyright 2020 Apple 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 FMCore /** Codes for why the study ended prematurely. URL: http://terminology.hl7.org/CodeSystem/research-study-reason-stopped ValueSet: http://hl7.org/fhir/ValueSet/research-study-reason-stopped */ public enum ResearchStudyReasonStopped: String, FHIRPrimitiveType { /// The study prematurely ended because the accrual goal was met. case accrualGoalMet = "accrual-goal-met" /// The study prematurely ended due to toxicity. case closedDueToToxicity = "closed-due-to-toxicity" /// The study prematurely ended due to lack of study progress. case closedDueToLackOfStudyProgress = "closed-due-to-lack-of-study-progress" /// The study prematurely ended temporarily per study design. case temporarilyClosedPerStudyDesign = "temporarily-closed-per-study-design" }
34.97619
77
0.753574
5bd6ada628381b93fe9b5a525e9cb49dc37b2f1c
1,091
class Bank { static var coinsInBank = 10_000 static func distribute(coins numberOfCoinsRequested: Int) -> Int { let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank) coinsInBank -= numberOfCoinsToVend return numberOfCoinsToVend } static func receive(coins: Int) { coinsInBank += coins } } class Player { var coinsInPurse: Int init(coins: Int) { coinsInPurse = Bank.distribute(coins: coins) } func win(coins: Int) { coinsInPurse += Bank.distribute(coins: coins) } deinit { Bank.receive(coins: coinsInPurse) } } var playerOne: Player? = Player(coins: 100) print("A new player has joined the game with \(playerOne!.coinsInPurse) coins") print("There are now \(Bank.coinsInBank) coins left in the bank") playerOne!.win(coins: 2_000) print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins") print("The bank now only has \(Bank.coinsInBank) coins left") playerOne = nil print("PlayerOne has left the game") print("The bank now has \(Bank.coinsInBank) coins")
32.088235
79
0.687443
9be8d3349e2a358c2230694b2d7e06024a64c4e9
461
// // ComicsWireframe.swift // Example // // Created by Davide Mendolia on 03/12/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation class SeriesWireframe: ExampleWireframe { func presentSeriesDetailViewController(_ seriesName: String) { let viewController = serviceLocator.provideSeriesDetailViewController(seriesName) serviceLocator.provideSeriesNavigator()?.push(viewController: viewController) } }
25.611111
89
0.750542
28b78638db2bfd2f5e6b860c0fc24f2080c750ed
4,843
// // EventsCell.swift // Tuned // // Created by Ravikiran Pathade on 4/16/18. // Copyright © 2018 Ravikiran Pathade. All rights reserved. // import Foundation import UIKit import EventKit class EventsCell:UITableViewCell{ @IBOutlet weak var calendarButton: UIButton! @IBOutlet weak var eventNameLabel: UILabel! @IBOutlet weak var bookOnlineButton: UIButton! var parentController:EventsContainer! var currentEvent = [String:AnyObject]() var delegate: UIViewController? var eventPresent:Bool = false var delegateTap: CustomCellDelegate? var delegateEvent: EventPress? @IBAction func bookOnlineTapped(_ sender: Any) { let url = currentEvent["uri"] as? String delegateTap?.sharePressed(cell: self,string:url!) } @IBOutlet weak var subTitle: UILabel! @IBAction func calendarButtonTapped(_ sender: Any) { let status = EKEventStore.authorizationStatus(for: .event) == EKAuthorizationStatus.authorized if status { let eventStore = EKEventStore() let eDate = currentEvent["date"] as? Date let eLocation = currentEvent["location"] as? String let event:EKEvent = EKEvent(eventStore: eventStore) event.title = currentEvent["location"] as? String event.startDate = currentEvent["date"] as? Date event.endDate = currentEvent["date"] as? Date event.notes = "Tunies / SongKick" event.calendar = eventStore.defaultCalendarForNewEvents if !eventPresent { do { try eventStore.save(event, span: .thisEvent) DispatchQueue.main.async { self.calendarButton.imageView?.image = nil self.calendarButton.imageView?.image = #imageLiteral(resourceName: "calendar_tick") self.eventPresent = true } parentController.calendarEvents[eLocation!] = eDate! //Event Has Been Added Alert showAlert(title: "Event Added", message: "Event has been added to your calendar.") }catch let e { print(e.localizedDescription) } }else{ let calendar = eventStore.calendars(for: .event) let endDate = Date(timeIntervalSinceNow: 60*60*24*365*2*2) var eventToDelete = EKEvent(eventStore: eventStore) DispatchQueue.global(qos: .userInitiated).async { for c in calendar{ let eventPredicate = eventStore.predicateForEvents(withStart: Date() - (60*60*24), end: endDate, calendars: [c]) let events = eventStore.events(matching: eventPredicate) for e in events{ if e.startDate == eDate { // Add More conditions eventToDelete = e continue } } } do { try eventStore.remove(eventToDelete, span: .thisEvent, commit:true) self.parentController.calendarEvents.removeValue(forKey: eLocation!) self.showAlert(title: "Event Removed", message: "Event has been removed from your calendar.") DispatchQueue.main.async { self.calendarButton.imageView?.image = nil self.calendarButton.imageView?.image = #imageLiteral(resourceName: "calendar_add") self.eventPresent = false } }catch let e { print(e.localizedDescription) } } } }else{ // Please Grant Access to add event to the calendar delegateEvent?.eventPressed(cell:self) } } func showAlert(title:String,message:String){ let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: {(action) in alert.dismiss(animated: true, completion: nil) })) UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil) //present(alert, animated: true, completion: nil) } } protocol CustomCellDelegate: class { func sharePressed(cell: EventsCell,string:String) } protocol EventPress: class{ func eventPressed(cell: EventsCell) }
41.042373
136
0.562255
294019ae091ae1c5580dedab2ca74d03b3802143
294
// // GCDBlackbox.swift // On The Map // // Created by Christopher Weaver on 8/5/16. // Copyright © 2016 Christopher Weaver. All rights reserved. // import Foundation func performUIUpdatesOnMain(_ updates: @escaping () -> Void) { DispatchQueue.main.async { updates() } }
17.294118
62
0.659864
234328ae49a89a6680ae027fbe9d3a5899ef72f6
1,052
// // CurrencyListResponse.swift // CurrencyConverter // // Created by Abdullah Bayraktar on 02/12/2018. // Copyright © 2018 AB. All rights reserved. // import Foundation struct CurrencyListResponse: Decodable { private enum CodingKeys: String, CodingKey { case baseCurrency = "base" case date = "date" case exchangeRates = "rates" } /// Base currency private(set) var baseCurrency: String /// date private(set) var date: String /// List of exchange rates private(set) var exchangeRates: [String: Double] init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let baseCurrency = try container.decode(String.self, forKey: .baseCurrency) let date = try container.decode(String.self, forKey: .date) let exchangeRates = try container.decode([String: Double].self, forKey: .exchangeRates) self.baseCurrency = baseCurrency self.date = date self.exchangeRates = exchangeRates } }
26.3
95
0.668251
f4902a7f2b3a5a5823f4dd0c1bf0f2a49cf1f9c4
2,446
// // CoinManager.swift // ByteCoin // // Created by Angela Yu on 11/09/2019. // Copyright © 2019 The App Brewery. All rights reserved. // import Foundation import CoreLocation protocol CoinManagerDelegate { func didUpdateCoin(price: String, currency: String) func didFailWithError(error: Error) } struct CoinManager { let baseURL = "https://rest.coinapi.io/v1/exchangerate/BTC" let apiKey = "17885A96-0E7F-4DC3-BBBB-ABC10F5C5386" let currencyArray = ["AUD", "BRL","CAD","CNY","EUR","GBP","HKD","IDR","ILS","INR","JPY","MXN","NOK","NZD","PLN","RON","RUB","SEK","SGD","USD","ZAR"] var delegate: CoinManagerDelegate? func getCoinPrice(for currency: String) { let urlString = "\(baseURL)/\(currency)?apikey=\(apiKey)" print(urlString) //1. Create a URL if let url = URL(string: urlString) { //2. Create a URLSession let session = URLSession(configuration: .default) //3. Give URLSession on a task let task = session.dataTask(with: url) { (data, response, error) in if error != nil { //self.delegate?.didFailWithError(error: error!) print(error!) return } if let safeData = data { if let bitcoinPrice = self.parseJSON(safeData) { let priceString = String(format: "%.2f", bitcoinPrice) self.delegate?.didUpdateCoin(price: priceString, currency: currency) } } //Отформатируем данные, которые мы получили обратно, как строку, чтобы иметь возможность распечатать их /*let dataString = String(data: data!, encoding: .utf8) print(dataString!)*/ } //4. Start the task task.resume() } } func parseJSON(_ data: Data) -> Double? { let decoder = JSONDecoder() do { let decodedData = try decoder.decode(CoinData.self, from: data) let lastPrice = decodedData.rate print(lastPrice) return lastPrice } catch { delegate?.didFailWithError(error: error) //print(error) return nil } } }
30.197531
152
0.524939
7a76c2bf313c98708d58794f994039f055b28571
621
// // CategoryListInteractor.swift // DemoViper // // Created by Crstian T. on 1/22/19. // Copyright © 2021 Cristian T. All rights reserved. // import Foundation // MARK: - CategoryListInteractorProtocol protocol CategoryListInteractorProtocol { var entity: CategoryEntityProtocol? { get set } func getAllCategories(completion: Completion?) } // MARK: - CategoryListInteractor final class CategoryListInteractor: CategoryListInteractorProtocol { var entity: CategoryEntityProtocol? func getAllCategories(completion: Completion?) { entity?.getAllCategories(completion: completion) } }
23.884615
68
0.748792
f8380bccd58ad1908ac9632e97f9099938cb38ca
773
// // Musics.swift // BaiduMusic_swift // // Created by jason on 15/6/30. // Copyright (c) 2015年 JasoneIo. All rights reserved. // import UIKit class Musics: NSObject { /**歌曲名 */ var name:String! /**歌曲大图 */ var icon:String! /**歌曲文件名 */ var fileName:String! /**歌词文件名 */ var lrcName:String! /**歌手 */ var singer:String! /**歌手图标 */ var singerIcon:String! init(musicsDict:Dictionary<String,String>){ name = musicsDict["name"] icon = musicsDict["icon"] fileName = musicsDict["filename"] lrcName = musicsDict["lrcname"] singer = musicsDict["singer"] singerIcon = musicsDict["singerIcon"] } }
17.177778
54
0.527814
f71eeb16afc5b9b95576c952552e46688f00b3fb
17,767
// Generated by the protocol buffer compiler. DO NOT EDIT! // Source file delete_post.proto import Foundation public extension Services.Post.Actions{ public struct DeletePost { }} public func == (lhs: Services.Post.Actions.DeletePost.RequestV1, rhs: Services.Post.Actions.DeletePost.RequestV1) -> Bool { if (lhs === rhs) { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) fieldCheck = fieldCheck && (lhs.hasId == rhs.hasId) && (!lhs.hasId || lhs.id == rhs.id) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } public func == (lhs: Services.Post.Actions.DeletePost.ResponseV1, rhs: Services.Post.Actions.DeletePost.ResponseV1) -> Bool { if (lhs === rhs) { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } public extension Services.Post.Actions.DeletePost { public struct DeletePostRoot { public static var sharedInstance : DeletePostRoot { struct Static { static let instance : DeletePostRoot = DeletePostRoot() } return Static.instance } public var extensionRegistry:ExtensionRegistry init() { extensionRegistry = ExtensionRegistry() registerAllExtensions(extensionRegistry) } public func registerAllExtensions(registry:ExtensionRegistry) { } } final public class RequestV1 : GeneratedMessage, GeneratedMessageProtocol { public private(set) var hasId:Bool = false public private(set) var id:String = "" required public init() { super.init() } override public func isInitialized() -> Bool { return true } override public func writeToCodedOutputStream(output:CodedOutputStream) throws { if hasId { try output.writeString(1, value:id) } try unknownFields.writeToCodedOutputStream(output) } override public func serializedSize() -> Int32 { var serialize_size:Int32 = memoizedSerializedSize if serialize_size != -1 { return serialize_size } serialize_size = 0 if hasId { serialize_size += id.computeStringSize(1) } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Services.Post.Actions.DeletePost.RequestV1> { var mergedArray = Array<Services.Post.Actions.DeletePost.RequestV1>() while let value = try parseFromDelimitedFromInputStream(input) { mergedArray += [value] } return mergedArray } public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.DeletePost.RequestV1? { return try Services.Post.Actions.DeletePost.RequestV1.Builder().mergeDelimitedFromInputStream(input)?.build() } public class func parseFromData(data:NSData) throws -> Services.Post.Actions.DeletePost.RequestV1 { return try Services.Post.Actions.DeletePost.RequestV1.Builder().mergeFromData(data, extensionRegistry:Services.Post.Actions.DeletePost.DeletePostRoot.sharedInstance.extensionRegistry).build() } public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.DeletePost.RequestV1 { return try Services.Post.Actions.DeletePost.RequestV1.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build() } public class func parseFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.DeletePost.RequestV1 { return try Services.Post.Actions.DeletePost.RequestV1.Builder().mergeFromInputStream(input).build() } public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.DeletePost.RequestV1 { return try Services.Post.Actions.DeletePost.RequestV1.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build() } public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.DeletePost.RequestV1 { return try Services.Post.Actions.DeletePost.RequestV1.Builder().mergeFromCodedInputStream(input).build() } public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.DeletePost.RequestV1 { return try Services.Post.Actions.DeletePost.RequestV1.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build() } public class func getBuilder() -> Services.Post.Actions.DeletePost.RequestV1.Builder { return Services.Post.Actions.DeletePost.RequestV1.classBuilder() as! Services.Post.Actions.DeletePost.RequestV1.Builder } public func getBuilder() -> Services.Post.Actions.DeletePost.RequestV1.Builder { return classBuilder() as! Services.Post.Actions.DeletePost.RequestV1.Builder } public override class func classBuilder() -> MessageBuilder { return Services.Post.Actions.DeletePost.RequestV1.Builder() } public override func classBuilder() -> MessageBuilder { return Services.Post.Actions.DeletePost.RequestV1.Builder() } public func toBuilder() throws -> Services.Post.Actions.DeletePost.RequestV1.Builder { return try Services.Post.Actions.DeletePost.RequestV1.builderWithPrototype(self) } public class func builderWithPrototype(prototype:Services.Post.Actions.DeletePost.RequestV1) throws -> Services.Post.Actions.DeletePost.RequestV1.Builder { return try Services.Post.Actions.DeletePost.RequestV1.Builder().mergeFrom(prototype) } override public func writeDescriptionTo(inout output:String, indent:String) throws { if hasId { output += "\(indent) id: \(id) \n" } unknownFields.writeDescriptionTo(&output, indent:indent) } override public var hashValue:Int { get { var hashCode:Int = 7 if hasId { hashCode = (hashCode &* 31) &+ id.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode } } //Meta information declaration start override public class func className() -> String { return "Services.Post.Actions.DeletePost.RequestV1" } override public func className() -> String { return "Services.Post.Actions.DeletePost.RequestV1" } override public func classMetaType() -> GeneratedMessage.Type { return Services.Post.Actions.DeletePost.RequestV1.self } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { private var builderResult:Services.Post.Actions.DeletePost.RequestV1 = Services.Post.Actions.DeletePost.RequestV1() public func getMessage() -> Services.Post.Actions.DeletePost.RequestV1 { return builderResult } required override public init () { super.init() } public var hasId:Bool { get { return builderResult.hasId } } public var id:String { get { return builderResult.id } set (value) { builderResult.hasId = true builderResult.id = value } } public func setId(value:String) -> Services.Post.Actions.DeletePost.RequestV1.Builder { self.id = value return self } public func clearId() -> Services.Post.Actions.DeletePost.RequestV1.Builder{ builderResult.hasId = false builderResult.id = "" return self } override public var internalGetResult:GeneratedMessage { get { return builderResult } } public override func clear() -> Services.Post.Actions.DeletePost.RequestV1.Builder { builderResult = Services.Post.Actions.DeletePost.RequestV1() return self } public override func clone() throws -> Services.Post.Actions.DeletePost.RequestV1.Builder { return try Services.Post.Actions.DeletePost.RequestV1.builderWithPrototype(builderResult) } public override func build() throws -> Services.Post.Actions.DeletePost.RequestV1 { try checkInitialized() return buildPartial() } public func buildPartial() -> Services.Post.Actions.DeletePost.RequestV1 { let returnMe:Services.Post.Actions.DeletePost.RequestV1 = builderResult return returnMe } public func mergeFrom(other:Services.Post.Actions.DeletePost.RequestV1) throws -> Services.Post.Actions.DeletePost.RequestV1.Builder { if other == Services.Post.Actions.DeletePost.RequestV1() { return self } if other.hasId { id = other.id } try mergeUnknownFields(other.unknownFields) return self } public override func mergeFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.DeletePost.RequestV1.Builder { return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry()) } public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.DeletePost.RequestV1.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields) while (true) { let tag = try input.readTag() switch tag { case 0: self.unknownFields = try unknownFieldsBuilder.build() return self case 10 : id = try input.readString() default: if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) { unknownFields = try unknownFieldsBuilder.build() return self } } } } } } final public class ResponseV1 : GeneratedMessage, GeneratedMessageProtocol { required public init() { super.init() } override public func isInitialized() -> Bool { return true } override public func writeToCodedOutputStream(output:CodedOutputStream) throws { try unknownFields.writeToCodedOutputStream(output) } override public func serializedSize() -> Int32 { var serialize_size:Int32 = memoizedSerializedSize if serialize_size != -1 { return serialize_size } serialize_size = 0 serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Services.Post.Actions.DeletePost.ResponseV1> { var mergedArray = Array<Services.Post.Actions.DeletePost.ResponseV1>() while let value = try parseFromDelimitedFromInputStream(input) { mergedArray += [value] } return mergedArray } public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.DeletePost.ResponseV1? { return try Services.Post.Actions.DeletePost.ResponseV1.Builder().mergeDelimitedFromInputStream(input)?.build() } public class func parseFromData(data:NSData) throws -> Services.Post.Actions.DeletePost.ResponseV1 { return try Services.Post.Actions.DeletePost.ResponseV1.Builder().mergeFromData(data, extensionRegistry:Services.Post.Actions.DeletePost.DeletePostRoot.sharedInstance.extensionRegistry).build() } public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.DeletePost.ResponseV1 { return try Services.Post.Actions.DeletePost.ResponseV1.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build() } public class func parseFromInputStream(input:NSInputStream) throws -> Services.Post.Actions.DeletePost.ResponseV1 { return try Services.Post.Actions.DeletePost.ResponseV1.Builder().mergeFromInputStream(input).build() } public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.DeletePost.ResponseV1 { return try Services.Post.Actions.DeletePost.ResponseV1.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build() } public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.DeletePost.ResponseV1 { return try Services.Post.Actions.DeletePost.ResponseV1.Builder().mergeFromCodedInputStream(input).build() } public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.DeletePost.ResponseV1 { return try Services.Post.Actions.DeletePost.ResponseV1.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build() } public class func getBuilder() -> Services.Post.Actions.DeletePost.ResponseV1.Builder { return Services.Post.Actions.DeletePost.ResponseV1.classBuilder() as! Services.Post.Actions.DeletePost.ResponseV1.Builder } public func getBuilder() -> Services.Post.Actions.DeletePost.ResponseV1.Builder { return classBuilder() as! Services.Post.Actions.DeletePost.ResponseV1.Builder } public override class func classBuilder() -> MessageBuilder { return Services.Post.Actions.DeletePost.ResponseV1.Builder() } public override func classBuilder() -> MessageBuilder { return Services.Post.Actions.DeletePost.ResponseV1.Builder() } public func toBuilder() throws -> Services.Post.Actions.DeletePost.ResponseV1.Builder { return try Services.Post.Actions.DeletePost.ResponseV1.builderWithPrototype(self) } public class func builderWithPrototype(prototype:Services.Post.Actions.DeletePost.ResponseV1) throws -> Services.Post.Actions.DeletePost.ResponseV1.Builder { return try Services.Post.Actions.DeletePost.ResponseV1.Builder().mergeFrom(prototype) } override public func writeDescriptionTo(inout output:String, indent:String) throws { unknownFields.writeDescriptionTo(&output, indent:indent) } override public var hashValue:Int { get { var hashCode:Int = 7 hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode } } //Meta information declaration start override public class func className() -> String { return "Services.Post.Actions.DeletePost.ResponseV1" } override public func className() -> String { return "Services.Post.Actions.DeletePost.ResponseV1" } override public func classMetaType() -> GeneratedMessage.Type { return Services.Post.Actions.DeletePost.ResponseV1.self } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { private var builderResult:Services.Post.Actions.DeletePost.ResponseV1 = Services.Post.Actions.DeletePost.ResponseV1() public func getMessage() -> Services.Post.Actions.DeletePost.ResponseV1 { return builderResult } required override public init () { super.init() } override public var internalGetResult:GeneratedMessage { get { return builderResult } } public override func clear() -> Services.Post.Actions.DeletePost.ResponseV1.Builder { builderResult = Services.Post.Actions.DeletePost.ResponseV1() return self } public override func clone() throws -> Services.Post.Actions.DeletePost.ResponseV1.Builder { return try Services.Post.Actions.DeletePost.ResponseV1.builderWithPrototype(builderResult) } public override func build() throws -> Services.Post.Actions.DeletePost.ResponseV1 { try checkInitialized() return buildPartial() } public func buildPartial() -> Services.Post.Actions.DeletePost.ResponseV1 { let returnMe:Services.Post.Actions.DeletePost.ResponseV1 = builderResult return returnMe } public func mergeFrom(other:Services.Post.Actions.DeletePost.ResponseV1) throws -> Services.Post.Actions.DeletePost.ResponseV1.Builder { if other == Services.Post.Actions.DeletePost.ResponseV1() { return self } try mergeUnknownFields(other.unknownFields) return self } public override func mergeFromCodedInputStream(input:CodedInputStream) throws -> Services.Post.Actions.DeletePost.ResponseV1.Builder { return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry()) } public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.Post.Actions.DeletePost.ResponseV1.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields) while (true) { let tag = try input.readTag() switch tag { case 0: self.unknownFields = try unknownFieldsBuilder.build() return self default: if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) { unknownFields = try unknownFieldsBuilder.build() return self } } } } } } } // @@protoc_insertion_point(global_scope)
44.866162
198
0.708505
1c09351c36e44142c2bd790f09636923bba82098
4,239
// // ViewController.swift // KBAdjust // // Created by Don Mag on 10/26/18. // Copyright © 2018 DonMag. All rights reserved. // import UIKit // scrollToBottomRow UITableView extension from // John Rogers // https://stackoverflow.com/a/51940222/6257435 extension UITableView { func scrollToBottomRow() { DispatchQueue.main.async { guard self.numberOfSections > 0 else { return } // Make an attempt to use the bottom-most section with at least one row var section = max(self.numberOfSections - 1, 0) var row = max(self.numberOfRows(inSection: section) - 1, 0) var indexPath = IndexPath(row: row, section: section) // Ensure the index path is valid, otherwise use the section above (sections can // contain 0 rows which leads to an invalid index path) while !self.indexPathIsValid(indexPath) { section = max(section - 1, 0) row = max(self.numberOfRows(inSection: section) - 1, 0) indexPath = IndexPath(row: row, section: section) // If we're down to the last section, attempt to use the first row if indexPath.section == 0 { indexPath = IndexPath(row: 0, section: 0) break } } // In the case that [0, 0] is valid (perhaps no data source?), ensure we don't encounter an // exception here guard self.indexPathIsValid(indexPath) else { return } self.scrollToRow(at: indexPath, at: .bottom, animated: true) } } func indexPathIsValid(_ indexPath: IndexPath) -> Bool { let section = indexPath.section let row = indexPath.row return section < self.numberOfSections && row < self.numberOfRows(inSection: section) } } class KBCell: UITableViewCell { @IBOutlet var theLabel: UILabel! } class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { @IBOutlet var theTableView: UITableView! @IBOutlet var theTextField: UITextField! @IBOutlet var textViewBottomConstraint: NSLayoutConstraint! var theData: [String] = [] override func viewDidLoad() { super.viewDidLoad() theTableView.dataSource = self theTableView.delegate = self theTextField.delegate = self theTableView.tableFooterView = UIView() // use 1...20 to see scrollToBottom functionality // use 1...4 to see functionality with only a few rows for i in 1...4 { theData.append("Row \(i)") } NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) } @objc func keyboardNotification(notification: NSNotification) { if let userInfo = notification.userInfo { let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue let endFrameY = endFrame?.origin.y ?? 0 let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw) if endFrameY >= UIScreen.main.bounds.size.height { self.textViewBottomConstraint?.constant = 0.0 } else { self.textViewBottomConstraint?.constant = endFrame?.size.height ?? 0.0 } self.theTableView.scrollToBottomRow() UIView.animate(withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: { self.view.layoutIfNeeded() }, completion: nil ) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return theData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "KBCell", for: indexPath) as! KBCell cell.theLabel.text = theData[indexPath.row] return cell } }
30.941606
112
0.71715
e23826c5df20a013270d72386f26f4d72b99ac7d
2,022
// // AriadneTests-macOS.swift // Tests // // Created by Denys Telezhkin on 2/7/19. // Copyright © 2019 Denys Telezhkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest @testable import Ariadne #if canImport(AppKit) import AppKit class Tests_AppKit: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } } #endif
36.763636
111
0.718595
f8d2fe1423a676a5dd03fb1c7b835ca76edde759
72,337
#!/usr/bin/env xcrun -sdk macosx swift import Foundation /* Required for setlocale(3) */ #if os(OSX) import Darwin #elseif os(Linux) import Glibc #endif let ShortOptionPrefix = "-" let LongOptionPrefix = "--" /* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt * convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html */ let ArgumentStopper = "--" /* Allow arguments to be attached to flags when separated by this character. * --flag=argument is equivalent to --flag argument */ let ArgumentAttacher: Character = "=" /* An output stream to stderr; used by CommandLine.printUsage(). */ private struct StderrOutputStream: TextOutputStream { static let stream = StderrOutputStream() func write(_ s: String) { fputs(s, stderr) } } /** * The CommandLine class implements a command-line interface for your app. * * To use it, define one or more Options (see Option.swift) and add them to your * CommandLine object, then invoke `parse()`. Each Option object will be populated with * the value given by the user. * * If any required options are missing or if an invalid value is found, `parse()` will throw * a `ParseError`. You can then call `printUsage()` to output an automatically-generated usage * message. */ open class CommandLine { fileprivate var _arguments: [String] fileprivate var _options: [Option] = [Option]() fileprivate var _maxFlagDescriptionWidth: Int = 0 fileprivate var _usedFlags: Set<String> { var usedFlags = Set<String>(minimumCapacity: _options.count * 2) for option in _options { for case let flag? in [option.shortFlag, option.longFlag] { usedFlags.insert(flag) } } return usedFlags } /** * After calling `parse()`, this property will contain any values that weren't captured * by an Option. For example: * * ``` * let cli = CommandLine() * let fileType = StringOption(shortFlag: "t", longFlag: "type", required: true, helpMessage: "Type of file") * * do { * try cli.parse() * print("File type is \(type), files are \(cli.unparsedArguments)") * catch { * cli.printUsage(error) * exit(EX_USAGE) * } * * --- * * $ ./readfiles --type=pdf ~/file1.pdf ~/file2.pdf * File type is pdf, files are ["~/file1.pdf", "~/file2.pdf"] * ``` */ open fileprivate(set) var unparsedArguments: [String] = [String]() /** * If supplied, this function will be called when printing usage messages. * * You can use the `defaultFormat` function to get the normally-formatted * output, either before or after modifying the provided string. For example: * * ``` * let cli = CommandLine() * cli.formatOutput = { str, type in * switch(type) { * case .Error: * // Make errors shouty * return defaultFormat(str.uppercaseString, type: type) * case .OptionHelp: * // Don't use the default indenting * return ">> \(s)\n" * default: * return defaultFormat(str, type: type) * } * } * ``` * * - note: Newlines are not appended to the result of this function. If you don't use * `defaultFormat()`, be sure to add them before returning. */ open var formatOutput: ((String, OutputType) -> String)? /** * The maximum width of all options' `flagDescription` properties; provided for use by * output formatters. * * - seealso: `defaultFormat`, `formatOutput` */ open var maxFlagDescriptionWidth: Int { if _maxFlagDescriptionWidth == 0 { _maxFlagDescriptionWidth = _options.map { $0.flagDescription.count }.sorted().first ?? 0 } return _maxFlagDescriptionWidth } /** * The type of output being supplied to an output formatter. * * - seealso: `formatOutput` */ public enum OutputType { /** About text: `Usage: command-example [options]` and the like */ case about /** An error message: `Missing required option --extract` */ case error /** An Option's `flagDescription`: `-h, --help:` */ case optionFlag /** An Option's help message */ case optionHelp } /** A ParseError is thrown if the `parse()` method fails. */ public enum ParseError: Error, CustomStringConvertible { /** Thrown if an unrecognized argument is passed to `parse()` in strict mode */ case InvalidArgument(String) /** Thrown if the value for an Option is invalid (e.g. a string is passed to an IntOption) */ case InvalidValueForOption(Option, [String]) /** Thrown if an Option with required: true is missing */ case MissingRequiredOptions([Option]) public var description: String { switch self { case let .InvalidArgument(arg): return "Invalid argument: \(arg)" case let .InvalidValueForOption(opt, vals): let vs = vals.joined(separator: ", ") return "Invalid value(s) for option \(opt.flagDescription): \(vs)" case let .MissingRequiredOptions(opts): return "Missing required options: \(opts.map { return $0.flagDescription })" } } } /** * Initializes a CommandLine object. * * - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app * on the command line will automatically be used. * * - returns: An initalized CommandLine object. */ public init(arguments: [String] = Swift.CommandLine.arguments) { self._arguments = arguments /* Initialize locale settings from the environment */ setlocale(LC_ALL, "") } /* Returns all argument values from flagIndex to the next flag or the end of the argument array. */ private func _getFlagValues(_ flagIndex: Int, _ attachedArg: String? = nil) -> [String] { var args: [String] = [String]() var skipFlagChecks = false if let a = attachedArg { args.append(a) } for i in flagIndex + 1 ..< _arguments.count { if !skipFlagChecks { if _arguments[i] == ArgumentStopper { skipFlagChecks = true continue } if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil && Double(_arguments[i]) == nil { break } } args.append(_arguments[i]) } return args } /** * Adds an Option to the command line. * * - parameter option: The option to add. */ public func addOption(_ option: Option) { let uf = _usedFlags for case let flag? in [option.shortFlag, option.longFlag] { assert(!uf.contains(flag), "Flag '\(flag)' already in use") } _options.append(option) _maxFlagDescriptionWidth = 0 } /** * Adds one or more Options to the command line. * * - parameter options: An array containing the options to add. */ public func addOptions(_ options: [Option]) { for o in options { addOption(o) } } /** * Adds one or more Options to the command line. * * - parameter options: The options to add. */ public func addOptions(_ options: Option...) { for o in options { addOption(o) } } /** * Sets the command line Options. Any existing options will be overwritten. * * - parameter options: An array containing the options to set. */ public func setOptions(_ options: [Option]) { _options = [Option]() addOptions(options) } /** * Sets the command line Options. Any existing options will be overwritten. * * - parameter options: The options to set. */ public func setOptions(_ options: Option...) { _options = [Option]() addOptions(options) } /** * Parses command-line arguments into their matching Option values. * * - parameter strict: Fail if any unrecognized flags are present (default: false). * * - throws: A `ParseError` if argument parsing fails: * - `.InvalidArgument` if an unrecognized flag is present and `strict` is true * - `.InvalidValueForOption` if the value supplied to an option is not valid (for * example, a string is supplied for an IntOption) * - `.MissingRequiredOptions` if a required option isn't present */ open func parse(strict: Bool = false) throws { var strays = _arguments /* Nuke executable name */ strays[0] = "" let argumentsEnumerator = _arguments.enumerated() for (idx, arg) in argumentsEnumerator { if arg == ArgumentStopper { break } if !arg.hasPrefix(ShortOptionPrefix) { continue } let skipChars = arg.hasPrefix(LongOptionPrefix) ? LongOptionPrefix.count : ShortOptionPrefix.count let flagWithArg = arg[arg.index(arg.startIndex, offsetBy: skipChars)..<arg.endIndex] /* The argument contained nothing but ShortOptionPrefix or LongOptionPrefix */ if flagWithArg.isEmpty { continue } /* Remove attached argument from flag */ let splitFlag = flagWithArg.split(separator: ArgumentAttacher, maxSplits: 1) let flag = String(splitFlag[0]) let attachedArg: String? = splitFlag.count == 2 ? String(splitFlag[1]) : nil var flagMatched = false for option in _options where option.flagMatch(flag) { let vals = self._getFlagValues(idx, attachedArg) guard option.setValue(vals) else { throw ParseError.InvalidValueForOption(option, vals) } var claimedIdx = idx + option.claimedValues if attachedArg != nil { claimedIdx -= 1 } for i in idx...claimedIdx { strays[i] = "" } flagMatched = true break } /* Flags that do not take any arguments can be concatenated */ let flagLength = flag.count if !flagMatched && !arg.hasPrefix(LongOptionPrefix) { let flagCharactersEnumerator = flag.enumerated() for (i, c) in flagCharactersEnumerator { for option in _options where option.flagMatch(String(c)) { /* Values are allowed at the end of the concatenated flags, e.g. * -xvf <file1> <file2> */ let vals = (i == flagLength - 1) ? self._getFlagValues(idx, attachedArg) : [String]() guard option.setValue(vals) else { throw ParseError.InvalidValueForOption(option, vals) } var claimedIdx = idx + option.claimedValues if attachedArg != nil { claimedIdx -= 1 } for i in idx...claimedIdx { strays[i] = "" } flagMatched = true break } } } /* Invalid flag */ guard !strict || flagMatched else { throw ParseError.InvalidArgument(arg) } } /* Check to see if any required options were not matched */ let missingOptions = _options.filter { $0.required && !$0.wasSet } guard missingOptions.count == 0 else { throw ParseError.MissingRequiredOptions(missingOptions) } unparsedArguments = strays.filter { $0 != "" } } /** * Provides the default formatting of `printUsage()` output. * * - parameter s: The string to format. * - parameter type: Type of output. * * - returns: The formatted string. * - seealso: `formatOutput` */ open func defaultFormat(_ s: String, type: OutputType) -> String { switch type { case .about: return "\(s)\n" case .error: return "\(s)\n\n" case .optionFlag: return " \(s.padding(toLength: maxFlagDescriptionWidth, withPad: " ", startingAt: 0)):\n" case .optionHelp: return " \(s)\n" } } /* printUsage() is generic for OutputStreamType because the Swift compiler crashes * on inout protocol function parameters in Xcode 7 beta 1 (rdar://21372694). */ /** * Prints a usage message. * * - parameter to: An OutputStreamType to write the error message to. */ public func printUsage<TargetStream: TextOutputStream>(_ to: inout TargetStream) { /* Nil coalescing operator (??) doesn't work on closures :( */ let format = formatOutput != nil ? formatOutput! : defaultFormat let name = _arguments[0] print(format("Usage: \(name) [options]", .about), terminator: "", to: &to) for opt in _options { print(format(opt.flagDescription, .optionFlag), terminator: "", to: &to) print(format(opt.helpMessage, .optionHelp), terminator: "", to: &to) } } /** * Prints a usage message. * * - parameter error: An error thrown from `parse()`. A description of the error * (e.g. "Missing required option --extract") will be printed before the usage message. * - parameter to: An OutputStreamType to write the error message to. */ public func printUsage<TargetStream: TextOutputStream>(_ error: Error, to: inout TargetStream) { let format = formatOutput != nil ? formatOutput! : defaultFormat print(format("\(error)", .error), terminator: "", to: &to) printUsage(&to) } /** * Prints a usage message. * * - parameter error: An error thrown from `parse()`. A description of the error * (e.g. "Missing required option --extract") will be printed before the usage message. */ public func printUsage(_ error: Error) { var out = StderrOutputStream.stream printUsage(error, to: &out) } /** * Prints a usage message. */ open func printUsage() { var out = StderrOutputStream.stream printUsage(&out) } } /* * Option.swift * Copyright (c) 2014 Ben Gollmer. * * 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. */ /** * The base class for a command-line option. */ open class Option { open let shortFlag: String? open let longFlag: String? open let required: Bool open let helpMessage: String /** True if the option was set when parsing command-line arguments */ open var wasSet: Bool { return false } open var claimedValues: Int { return 0 } open var flagDescription: String { switch (shortFlag, longFlag) { case let (sf?, lf?): return "\(ShortOptionPrefix)\(sf), \(LongOptionPrefix)\(lf)" case (nil, let lf?): return "\(LongOptionPrefix)\(lf)" case (let sf?, nil): return "\(ShortOptionPrefix)\(sf)" default: return "" } } internal init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) { if let sf = shortFlag { assert(sf.count == 1, "Short flag must be a single character") assert(Int(sf) == nil && Double(sf) == nil, "Short flag cannot be a numeric value") } if let lf = longFlag { assert(Int(lf) == nil && Double(lf) == nil, "Long flag cannot be a numeric value") } self.shortFlag = shortFlag self.longFlag = longFlag self.helpMessage = helpMessage self.required = required } /* The optional casts in these initalizers force them to call the private initializer. Without * the casts, they recursively call themselves. */ /** Initializes a new Option that has both long and short flags. */ public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) { self.init(shortFlag as String?, longFlag, required, helpMessage) } /** Initializes a new Option that has only a short flag. */ public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) { self.init(shortFlag as String?, nil, required, helpMessage) } /** Initializes a new Option that has only a long flag. */ public convenience init(longFlag: String, required: Bool = false, helpMessage: String) { self.init(nil, longFlag as String?, required, helpMessage) } func flagMatch(_ flag: String) -> Bool { return flag == shortFlag || flag == longFlag } func setValue(_ values: [String]) -> Bool { return false } } /** * A boolean option. The presence of either the short or long flag will set the value to true; * absence of the flag(s) is equivalent to false. */ open class BoolOption: Option { fileprivate var _value: Bool = false open var value: Bool { return _value } override open var wasSet: Bool { return _value } override func setValue(_ values: [String]) -> Bool { _value = true return true } } /** An option that accepts a positive or negative integer value. */ open class IntOption: Option { fileprivate var _value: Int? open var value: Int? { return _value } override open var wasSet: Bool { return _value != nil } override open var claimedValues: Int { return _value != nil ? 1 : 0 } override func setValue(_ values: [String]) -> Bool { if values.count == 0 { return false } if let val = Int(values[0]) { _value = val return true } return false } } /** * An option that represents an integer counter. Each time the short or long flag is found * on the command-line, the counter will be incremented. */ open class CounterOption: Option { fileprivate var _value: Int = 0 open var value: Int { return _value } override open var wasSet: Bool { return _value > 0 } open func reset() { _value = 0 } override func setValue(_ values: [String]) -> Bool { _value += 1 return true } } /** An option that accepts a positive or negative floating-point value. */ open class DoubleOption: Option { fileprivate var _value: Double? open var value: Double? { return _value } override open var wasSet: Bool { return _value != nil } override open var claimedValues: Int { return _value != nil ? 1 : 0 } override func setValue(_ values: [String]) -> Bool { if values.count == 0 { return false } if let val = values[0].toDouble() { _value = val return true } return false } } /** An option that accepts a string value. */ open class StringOption: Option { fileprivate var _value: String? = nil open var value: String? { return _value } override open var wasSet: Bool { return _value != nil } override open var claimedValues: Int { return _value != nil ? 1 : 0 } override func setValue(_ values: [String]) -> Bool { if values.count == 0 { return false } _value = values[0] return true } } /** An option that accepts one or more string values. */ open class MultiStringOption: Option { fileprivate var _value: [String]? open var value: [String]? { return _value } override open var wasSet: Bool { return _value != nil } override open var claimedValues: Int { if let v = _value { return v.count } return 0 } override func setValue(_ values: [String]) -> Bool { if values.count == 0 { return false } _value = values return true } } /** An option that represents an enum value. */ public class EnumOption<T:RawRepresentable>: Option where T.RawValue == String { private var _value: T? public var value: T? { return _value } override public var wasSet: Bool { return _value != nil } override public var claimedValues: Int { return _value != nil ? 1 : 0 } /* Re-defining the intializers is necessary to make the Swift 2 compiler happy, as * of Xcode 7 beta 2. */ internal override init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) { super.init(shortFlag, longFlag, required, helpMessage) } /** Initializes a new Option that has both long and short flags. */ public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) { self.init(shortFlag as String?, longFlag, required, helpMessage) } /** Initializes a new Option that has only a short flag. */ public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) { self.init(shortFlag as String?, nil, required, helpMessage) } /** Initializes a new Option that has only a long flag. */ public convenience init(longFlag: String, required: Bool = false, helpMessage: String) { self.init(nil, longFlag as String?, required, helpMessage) } override func setValue(_ values: [String]) -> Bool { if values.count == 0 { return false } if let v = T(rawValue: values[0]) { _value = v return true } return false } } /* * StringExtensions.swift * Copyright (c) 2014 Ben Gollmer. * * 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. */ internal extension String { /* Retrieves locale-specified decimal separator from the environment * using localeconv(3). */ fileprivate func _localDecimalPoint() -> Character { let locale = localeconv() if locale != nil { if let decimalPoint = locale?.pointee.decimal_point { return Character(UnicodeScalar(UInt32(decimalPoint.pointee))!) } } return "." } /** * Attempts to parse the string value into a Double. * * - returns: A Double if the string can be parsed, nil otherwise. */ func toDouble() -> Double? { var characteristic: String = "0" var mantissa: String = "0" var inMantissa: Bool = false var isNegative: Bool = false let decimalPoint = self._localDecimalPoint() #if swift(>=3.0) let charactersEnumerator = self.enumerated() #else let charactersEnumerator = self.enumerated() #endif for (i, c) in charactersEnumerator { if i == 0 && c == "-" { isNegative = true continue } if c == decimalPoint { inMantissa = true continue } if Int(String(c)) != nil { if !inMantissa { characteristic.append(c) } else { mantissa.append(c) } } else { /* Non-numeric character found, bail */ return nil } } let doubleCharacteristic = Double(Int(characteristic)!) return (doubleCharacteristic + Double(Int(mantissa)!) / pow(Double(10), Double(mantissa.count - 1))) * (isNegative ? -1 : 1) } /** * Splits a string into an array of string components. * * - parameter by: The character to split on. * - parameter maxSplits: The maximum number of splits to perform. If 0, all possible splits are made. * * - returns: An array of string components. */ func split(by: Character, maxSplits: Int = 0) -> [String] { var s = [String]() var numSplits = 0 var curIdx = self.startIndex for i in self.indices { let c = self[i] if c == by && (maxSplits == 0 || numSplits < maxSplits) { let str = String(self[curIdx..<i]) s.append(str) curIdx = self.index(after: i) numSplits += 1 } } if curIdx != self.endIndex { let str = String(self[curIdx..<self.endIndex]) s.append(str) } return s } /** * Pads a string to the specified width. * * - parameter toWidth: The width to pad the string to. * - parameter by: The character to use for padding. * * - returns: A new string, padded to the given width. */ func padded(toWidth width: Int, with padChar: Character = " ") -> String { var s = self var currentLength = self.count while currentLength < width { s.append(padChar) currentLength += 1 } return s } /** * Wraps a string to the specified width. * * This just does simple greedy word-packing, it doesn't go full Knuth-Plass. * If a single word is longer than the line width, it will be placed (unsplit) * on a line by itself. * * - parameter atWidth: The maximum length of a line. * - parameter wrapBy: The line break character to use. * - parameter splitBy: The character to use when splitting the string into words. * * - returns: A new string, wrapped at the given width. */ func wrapped(atWidth width: Int, wrapBy: Character = "\n", splitBy: Character = " ") -> String { var s = "" var currentLineWidth = 0 for word in self.split(by: splitBy) { let wordLength = word.count if currentLineWidth + wordLength + 1 > width { /* Word length is greater than line length, can't wrap */ if wordLength >= width { s += word } s.append(wrapBy) currentLineWidth = 0 } currentLineWidth += wordLength + 1 s += word s.append(splitBy) } return s } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Import import Foundation // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Definitions private var BASE_CLASS_NAME : String = "Localizations" private let OBJC_CLASS_PREFIX : String = "_" private var OBJC_CUSTOM_SUPERCLASS: String? // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Extensions private extension String { func alphanumericString(exceptionCharactersFromString: String = "") -> String { // removes diacritic marks var copy = self.folding(options: .diacriticInsensitive, locale: NSLocale.current) // removes all non alphanumeric characters var characterSet = CharacterSet.alphanumerics.inverted // don't remove the characters that are given characterSet.remove(charactersIn: exceptionCharactersFromString) copy = copy.components(separatedBy: characterSet).reduce("") { $0 + $1 } return copy } func replacedNonAlphaNumericCharacters(replacement: UnicodeScalar) -> String { return String(describing: UnicodeScalarView(self.unicodeScalars.map { CharacterSet.alphanumerics.contains(($0)) ? $0 : replacement })) } } private extension NSCharacterSet { // thanks to http://stackoverflow.com/a/27698155/354018 func containsCharacter(c: Character) -> Bool { let s = String(c) let ix = s.startIndex let ix2 = s.endIndex let result = s.rangeOfCharacter(from: self as CharacterSet, options: [], range: ix..<ix2) return result != nil } } private extension NSMutableDictionary { func setObject(object : AnyObject!, forKeyPath : String, delimiter : String = ".") { self.setObject(object: object, onObject : self, forKeyPath: forKeyPath, createIntermediates: true, replaceIntermediates: true, delimiter: delimiter) } func setObject(object : AnyObject, onObject : AnyObject, forKeyPath keyPath : String, createIntermediates: Bool, replaceIntermediates: Bool, delimiter: String) { // Make keypath mutable var primaryKeypath = keyPath // Replace delimiter with dot delimiter - otherwise key value observing does not work properly let baseDelimiter = "." primaryKeypath = primaryKeypath.replacingOccurrences(of: delimiter, with: baseDelimiter, options: NSString.CompareOptions.literal, range: nil) // Create path components separated by delimiter (. by default) and get key for root object // filter empty path components, these can be caused by delimiter at beginning/end, or multiple consecutive delimiters in the middle let pathComponents : Array<String> = primaryKeypath.components(separatedBy: baseDelimiter).filter({ $0.count > 0 }) primaryKeypath = pathComponents.joined(separator: baseDelimiter) let rootKey : String = pathComponents[0] if pathComponents.count == 1 { onObject.set(object, forKey: rootKey) } let replacementDictionary : NSMutableDictionary = NSMutableDictionary() // Store current state for further replacement var previousObject : AnyObject? = onObject; var previousReplacement : NSMutableDictionary = replacementDictionary var reachedDictionaryLeaf : Bool = false; // Traverse through path from root to deepest level for path : String in pathComponents { let currentObject : AnyObject? = reachedDictionaryLeaf ? nil : previousObject?.object(forKey: path) as AnyObject? // Check if object already exists. If not, create new level, if allowed, or end if currentObject == nil { reachedDictionaryLeaf = true; if createIntermediates { let newNode : NSMutableDictionary = NSMutableDictionary() previousReplacement.setObject(newNode, forKey: path as NSString) previousReplacement = newNode; } else { return; } // If it does and it is dictionary, create mutable copy and assign new node there } else if currentObject is NSDictionary { let newNode : NSMutableDictionary = NSMutableDictionary(dictionary: currentObject as! [NSObject : AnyObject]) previousReplacement.setObject(newNode, forKey: path as NSString) previousReplacement = newNode // It exists but it is not NSDictionary, so we replace it, if allowed, or end } else { reachedDictionaryLeaf = true; if replaceIntermediates { let newNode : NSMutableDictionary = NSMutableDictionary() previousReplacement.setObject(newNode, forKey: path as NSString) previousReplacement = newNode; } else { return; } } // Replace previous object with the new one previousObject = currentObject; } // Replace root object with newly created n-level dictionary replacementDictionary.setValue(object, forKeyPath: primaryKeypath); onObject.set(replacementDictionary.object(forKey: rootKey), forKey: rootKey); } } private extension FileManager { func isDirectoryAtPath(path : String) -> Bool { let manager = FileManager.default do { let attribs: [FileAttributeKey : Any]? = try manager.attributesOfItem(atPath: path) if let attributes = attribs { let type = attributes[FileAttributeKey.type] as? String return type == FileAttributeType.typeDirectory.rawValue } } catch _ { return false } } } private extension String { var camelCasedString: String { let inputArray = self.components(separatedBy: (CharacterSet.alphanumerics.inverted)) return inputArray.reduce("", {$0 + $1.capitalized}) } var nolineString: String { let set = CharacterSet.newlines let components = self.components(separatedBy: set) return components.joined(separator: " ") } func isFirstLetterDigit() -> Bool { guard let c : Character = self.first else { return false } let s = String(c).unicodeScalars let uni = s[s.startIndex] return (uni.value >= 48 && uni.value <= 57) // return String(describing: UnicodeScalarView(self.unicodeScalars.map { CharacterSet.alphanumerics.contains(($0)) ? $0 : replacement })) } func isReservedKeyword(lang : Runtime.ExportLanguage) -> Bool { // Define keywords for each language var keywords : [String] = [] if lang == .ObjC { keywords = ["auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short", "signed", "sizeof", "static", "struct", "swift", "typedef", "union", "unsigned", "void", "volatile", "while", "BOOL", "Class", "bycopy", "byref", "id", "IMP", "in", "inout", "nil", "NO", "NULL", "oneway", "out", "Protocol", "SEL", "self", "super", "YES"] } else if lang == .Swift { keywords = ["class", "deinit", "enum", "extension", "func", "import", "init", "inout", "internal", "let", "operator", "private", "protocol", "public", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "defer", "do", "else", "fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch", "where", "while", "as", "catch", "dynamicType", "false", "is", "nil", "rethrows", "super", "self", "Self", "throw", "throws", "true", "try", "type", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__"] } // Check if it contains that keyword return keywords.index(of: self) != nil } } private enum SpecialCharacter { case String case Double case Int case Int64 case UInt } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Localization Class implementation class Localization { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Properties var flatStructure = NSDictionary() var objectStructure = NSMutableDictionary() var autocapitalize : Bool = true var table: String? // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Setup convenience init(inputFile : URL, delimiter : String, autocapitalize : Bool, table: String? = nil) { self.init() self.table = table // Load localization file self.processInputFromFile(file: inputFile, delimiter: delimiter, autocapitalize: autocapitalize) } func processInputFromFile(file : URL, delimiter : String, autocapitalize : Bool) { guard let dictionary = NSDictionary(contentsOfFile: file.path) else { print("Bad format of input file") exit(EX_IOERR) } self.flatStructure = dictionary self.autocapitalize = autocapitalize self.expandFlatStructure(flatStructure: dictionary, delimiter: delimiter) } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Public func writerWithSwiftImplementation() -> StreamWriter { let writer = StreamWriter() // Generate header writer.writeHeader() // Imports writer.writeMarkWithName(name: "Imports") writer.writeSwiftImports() // Generate actual localization structures writer.writeMarkWithName(name: "Localizations") writer.writeCodeStructure(structure: self.swiftStructWithContent(content: self.codifySwift(expandedStructure: self.objectStructure), structName: BASE_CLASS_NAME, contentLevel: 0)) return writer } func writerWithObjCImplementationWithFilename(filename : String) -> StreamWriter { let writer = StreamWriter() // Generate header writer.writeHeader() // Imports writer.writeMarkWithName(name: "Imports") writer.writeObjCImportsWithFileName(name: filename) // Generate actual localization structures writer.writeMarkWithName(name: "Header") writer.writeCodeStructure(structure: self.codifyObjC(expandedStructure: self.objectStructure, baseClass: BASE_CLASS_NAME, header: false)) return writer } func writerWithObjCHeader() -> StreamWriter { let writer = StreamWriter() // Generate header writer.writeHeader() // Imports writer.writeMarkWithName(name: "Imports") writer.writeObjCHeaderImports() // Generate actual localization structures writer.writeMarkWithName(name: "Header") writer.writeCodeStructure(structure: self.codifyObjC(expandedStructure: self.objectStructure, baseClass: BASE_CLASS_NAME, header: true)) // Generate macros writer.writeMarkWithName(name: "Macros") writer.writeObjCHeaderMacros() return writer } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Private private func expandFlatStructure(flatStructure : NSDictionary, delimiter: String) { // Writes values to dictionary and also for (key, _) in flatStructure { guard let key = key as? String else { continue } objectStructure.setObject(object: key as NSString, forKeyPath: key, delimiter: delimiter) } } private func codifySwift(expandedStructure : NSDictionary, contentLevel : Int = 0) -> String { // Increase content level let contentLevel = contentLevel + 1 // Prepare output structure var outputStructure : [String] = [] // First iterate through properties for (key, value) in expandedStructure { if let value = value as? String { let comment = (self.flatStructure.object(forKey: value) as! String).nolineString let methodParams = self.methodParamsForString(string: comment) let staticString: String if methodParams.count > 0 { staticString = self.swiftLocalizationFuncFromLocalizationKey(key: value, methodName: key as! String, baseTranslation: comment, methodSpecification: methodParams, contentLevel: contentLevel) } else { staticString = self.swiftLocalizationStaticVarFromLocalizationKey(key: value, variableName: key as! String, baseTranslation: comment, contentLevel: contentLevel) } outputStructure.append(staticString) } } // Then iterate through nested structures for (key, value) in expandedStructure { if let value = value as? NSDictionary { outputStructure.append(self.swiftStructWithContent(content: self.codifySwift(expandedStructure: value, contentLevel: contentLevel), structName: key as! String, contentLevel: contentLevel)) } } // At the end, return everything merged together return outputStructure.joined(separator: "\n") } private func codifyObjC(expandedStructure : NSDictionary, baseClass : String, header : Bool) -> String { // Prepare output structure var outputStructure : [String] = [] var contentStructure : [String] = [] // First iterate through properties for (key, value) in expandedStructure { if let value = value as? String { let comment = (self.flatStructure.object(forKey: value) as! String).nolineString let methodParams = self.methodParamsForString(string: comment) let staticString : String if methodParams.count > 0 { staticString = self.objcLocalizationFuncFromLocalizationKey(key: value, methodName: self.variableName(string: key as! String, lang: .ObjC), baseTranslation: comment, methodSpecification: methodParams, header: header) } else { staticString = self.objcLocalizationStaticVarFromLocalizationKey(key: value, variableName: self.variableName(string: key as! String, lang: .ObjC), baseTranslation: comment, header: header) } contentStructure.append(staticString) } } // Then iterate through nested structures for (key, value) in expandedStructure { if let value = value as? NSDictionary { outputStructure.append(self.codifyObjC(expandedStructure: value, baseClass : baseClass + self.variableName(string: key as! String, lang: .ObjC), header: header)) contentStructure.insert(self.objcClassVarWithName(name: self.variableName(string: key as! String, lang: .ObjC), className: baseClass + self.variableName(string: key as! String, lang: .ObjC), header: header), at: 0) } } if baseClass == BASE_CLASS_NAME { if header { contentStructure.append(TemplateFactory.templateForObjCBaseClassHeader(name: OBJC_CLASS_PREFIX + BASE_CLASS_NAME)) } else { contentStructure.append(TemplateFactory.templateForObjCBaseClassImplementation(name: OBJC_CLASS_PREFIX + BASE_CLASS_NAME)) } } // Generate class code for current class outputStructure.append(self.objcClassWithContent(content: contentStructure.joined(separator: "\n"), className: OBJC_CLASS_PREFIX + baseClass, header: header)) // At the end, return everything merged together return outputStructure.joined(separator: "\n") } private func methodParamsForString(string : String) -> [SpecialCharacter] { // Split the string into pieces by % let matches = self.matchesForRegexInText(regex: "%([0-9]*.[0-9]*(d|i|u|f|ld)|(\\d\\$)?@|d|i|u|f|ld)", text: string) var characters : [SpecialCharacter] = [] for match in matches { characters.append(self.propertyTypeForMatch(string: match)) } return characters } private func propertyTypeForMatch(string : String) -> SpecialCharacter { if string.contains("ld") { return .Int64 } else if string.contains("d") || string.contains("i") { return .Int } else if string.contains("u") { return .UInt } else if string.contains("f") { return .Double } else { return .String } } private func variableName(string : String, lang : Runtime.ExportLanguage) -> String { // . is not allowed, nested structure expanding must take place before calling this function let legalCharacterString = string.replacedNonAlphaNumericCharacters(replacement: "_") if self.autocapitalize { return (legalCharacterString.isFirstLetterDigit() || legalCharacterString.isReservedKeyword(lang: lang) ? "_" + legalCharacterString.camelCasedString : legalCharacterString.camelCasedString) } else { return (legalCharacterString.isFirstLetterDigit() || legalCharacterString.isReservedKeyword(lang: lang) ? "_" + string : legalCharacterString) } } private func matchesForRegexInText(regex: String!, text: String!) -> [String] { do { let regex = try NSRegularExpression(pattern: regex, options: []) let nsString = text as NSString let results = regex.matches(in: text, options: [], range: NSMakeRange(0, nsString.length)) return results.map { nsString.substring(with: $0.range)} } catch let error as NSError { print("invalid regex: \(error.localizedDescription)") return [] } } private func dataTypeFromSpecialCharacter(char : SpecialCharacter, language : Runtime.ExportLanguage) -> String { switch char { case .String: return language == .Swift ? "String" : "NSString *" case .Double: return language == .Swift ? "Double" : "double" case .Int: return language == .Swift ? "Int" : "int" case .Int64: return language == .Swift ? "Int64" : "long" case .UInt: return language == .Swift ? "UInt" : "unsigned int" } } private func swiftStructWithContent(content : String, structName : String, contentLevel : Int = 0) -> String { return TemplateFactory.templateForSwiftStructWithName(name: self.variableName(string: structName, lang: .Swift), content: content, contentLevel: contentLevel) } private func swiftLocalizationStaticVarFromLocalizationKey(key : String, variableName : String, baseTranslation : String, contentLevel : Int = 0) -> String { return TemplateFactory.templateForSwiftStaticVarWithName(name: self.variableName(string: variableName, lang: .Swift), key: key, table: table, baseTranslation : baseTranslation, contentLevel: contentLevel) } private func swiftLocalizationFuncFromLocalizationKey(key : String, methodName : String, baseTranslation : String, methodSpecification : [SpecialCharacter], contentLevel : Int = 0) -> String { var counter = 0 var methodHeaderParams = methodSpecification.reduce("") { (string, character) -> String in counter += 1 return "\(string), _ value\(counter) : \(self.dataTypeFromSpecialCharacter(char: character, language: .Swift))" } var methodParams : [String] = [] for (index, _) in methodSpecification.enumerated() { methodParams.append("value\(index + 1)") } let methodParamsString = methodParams.joined(separator: ", ") methodHeaderParams = methodHeaderParams.trimmingCharacters(in: CharacterSet(charactersIn: ", ")) return TemplateFactory.templateForSwiftFuncWithName(name: self.variableName(string: methodName, lang: .Swift), key: key, table: table, baseTranslation : baseTranslation, methodHeader: methodHeaderParams, params: methodParamsString, contentLevel: contentLevel) } private func objcClassWithContent(content : String, className : String, header : Bool, contentLevel : Int = 0) -> String { if header { return TemplateFactory.templateForObjCClassHeaderWithName(name: className, content: content, contentLevel: contentLevel) } else { return TemplateFactory.templateForObjCClassImplementationWithName(name: className, content: content, contentLevel: contentLevel) } } private func objcClassVarWithName(name : String, className : String, header : Bool, contentLevel : Int = 0) -> String { if header { return TemplateFactory.templateForObjCClassVarHeaderWithName(name: name, className: className, contentLevel: contentLevel) } else { return TemplateFactory.templateForObjCClassVarImplementationWithName(name: name, className: className, contentLevel: contentLevel) } } private func objcLocalizationStaticVarFromLocalizationKey(key : String, variableName : String, baseTranslation : String, header : Bool, contentLevel : Int = 0) -> String { if header { return TemplateFactory.templateForObjCStaticVarHeaderWithName(name: variableName, key: key, baseTranslation : baseTranslation, contentLevel: contentLevel) } else { return TemplateFactory.templateForObjCStaticVarImplementationWithName(name: variableName, key: key, table: table, baseTranslation : baseTranslation, contentLevel: contentLevel) } } private func objcLocalizationFuncFromLocalizationKey(key : String, methodName : String, baseTranslation : String, methodSpecification : [SpecialCharacter], header : Bool, contentLevel : Int = 0) -> String { var counter = 0 var methodHeader = methodSpecification.reduce("") { (string, character) -> String in counter += 1 return "\(string), \(self.dataTypeFromSpecialCharacter(char: character, language: .ObjC))" } counter = 0 var blockHeader = methodSpecification.reduce("") { (string, character) -> String in counter += 1 return "\(string), \(self.dataTypeFromSpecialCharacter(char: character, language: .ObjC)) value\(counter) " } var blockParamComponent : [String] = [] for (index, _) in methodSpecification.enumerated() { blockParamComponent.append("value\(index + 1)") } let blockParams = blockParamComponent.joined(separator: ", ") methodHeader = methodHeader.trimmingCharacters(in: CharacterSet(charactersIn: ", ")) blockHeader = blockHeader.trimmingCharacters(in: CharacterSet(charactersIn: ", ")) if header { return TemplateFactory.templateForObjCMethodHeaderWithName(name: methodName, key: key, baseTranslation: baseTranslation, methodHeader: methodHeader, contentLevel: contentLevel) } else { return TemplateFactory.templateForObjCMethodImplementationWithName(name: methodName, key: key, table: table, baseTranslation: baseTranslation, methodHeader: methodHeader, blockHeader: blockHeader, blockParams: blockParams, contentLevel: contentLevel) } } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Runtime Class implementation class Runtime { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Properties enum ExportLanguage : String { case Swift = "swift" case ObjC = "objc" } enum ExportStream : String { case Standard = "stdout" case File = "file" } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Properties var localizationFilePathToRead : URL! var localizationFilePathToWriteTo : URL! var localizationFileHeaderPathToWriteTo : URL? var localizationDelimiter = "." var localizationDebug = false var localizationCore : Localization! var localizationExportLanguage : ExportLanguage = .Swift var localizationExportStream : ExportStream = .File var localizationAutocapitalize = false var localizationStringsTable: String? // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Public func run() { // Initialize command line tool if self.checkCLI() { // Process files if self.checkIO() { // Generate input -> output based on user configuration self.processOutput() } } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Private private func checkCLI() -> Bool { // Define CLI options let inputFilePath = StringOption(shortFlag: "i", longFlag: "input", required: true, helpMessage: "Required | String | Path to the localization file") let outputFilePath = StringOption(shortFlag: "o", longFlag: "output", required: false, helpMessage: "Optional | String | Path to output file (.swift or .m, depending on your configuration. If you are using ObjC, header will be created on that location. If ommited, output will be sent to stdout instead.") let outputLanguage = StringOption(shortFlag: "l", longFlag: "language", required: false, helpMessage: "Optional | String | [swift | objc] | Specifies language of generated output files | Defaults to [swift]") let delimiter = StringOption(shortFlag: "d", longFlag: "delimiter", required: false, helpMessage: "Optional | String | String delimiter to separate segments of each string | Defaults to [.]") let autocapitalize = BoolOption(shortFlag: "c", longFlag: "capitalize", required: false, helpMessage: "Optional | Bool | When enabled, name of all structures / methods / properties are automatically CamelCased | Defaults to false") let baseClassName = StringOption(shortFlag: "b", longFlag: "baseClassName", required: false, helpMessage: "Optional | String | Name of the base class | Defaults to \"Localizations\"") let stringsTableName = StringOption(shortFlag: "t", longFlag: "stringsTableName", required: false, helpMessage: "Optional | String | Name of strings table | Defaults to nil") let customSuperclass = StringOption(shortFlag: "s", longFlag: "customSuperclass", required: false, helpMessage: "Optional | String | A custom superclass name | Defaults to NSObject (only applicable in ObjC)") let cli = CommandLine() cli.addOptions(inputFilePath, outputFilePath, outputLanguage, delimiter, autocapitalize, baseClassName, stringsTableName, customSuperclass) // TODOX: make output file path NOT optional when print output stream is selected do { // Parse user input try cli.parse(strict: true) // It passed, now process input self.localizationFilePathToRead = URL(fileURLWithPath: inputFilePath.value!) if let value = delimiter.value { self.localizationDelimiter = value } self.localizationAutocapitalize = autocapitalize.wasSet ? true : false if let value = outputLanguage.value, let type = ExportLanguage(rawValue: value) { self.localizationExportLanguage = type } if let value = outputFilePath.value { self.localizationFilePathToWriteTo = URL(fileURLWithPath: value) self.localizationExportStream = .File } else { self.localizationExportStream = .Standard } if let bcn = baseClassName.value { BASE_CLASS_NAME = bcn } self.localizationStringsTable = stringsTableName.value OBJC_CUSTOM_SUPERCLASS = customSuperclass.value return true } catch { cli.printUsage(error) exit(EX_USAGE) } return false } private func checkIO() -> Bool { // Check if we have input file if !FileManager.default.fileExists(atPath: self.localizationFilePathToRead.path) { // TODOX: Better error handling exit(EX_IOERR) } // Handle output file checks only if we are writing to file if self.localizationExportStream == .File { // Remove output file first _ = try? FileManager.default.removeItem(atPath: self.localizationFilePathToWriteTo.path) if !FileManager.default.createFile(atPath: self.localizationFilePathToWriteTo.path, contents: Data(), attributes: nil) { // TODOX: Better error handling exit(EX_IOERR) } // ObjC - we also need header file for ObjC code if self.localizationExportLanguage == .ObjC { // Create header file name self.localizationFileHeaderPathToWriteTo = self.localizationFilePathToWriteTo.deletingPathExtension().appendingPathExtension("h") // Remove file at path and replace it with new one _ = try? FileManager.default.removeItem(atPath: self.localizationFileHeaderPathToWriteTo!.path) if !FileManager.default.createFile(atPath: self.localizationFileHeaderPathToWriteTo!.path, contents: Data(), attributes: nil) { // TODOX: Better error handling exit(EX_IOERR) } } } return true } private func processOutput() { // Create translation core which will process all required data self.localizationCore = Localization(inputFile: self.localizationFilePathToRead, delimiter: self.localizationDelimiter, autocapitalize: self.localizationAutocapitalize, table: self.localizationStringsTable) // Write output for swift if self.localizationExportLanguage == .Swift { let implementation = self.localizationCore.writerWithSwiftImplementation() // Write swift file if self.localizationExportStream == .Standard { implementation.writeToSTD(clearBuffer: true) } else if self.localizationExportStream == .File { implementation.writeToOutputFileAtPath(path: self.localizationFilePathToWriteTo) } // or write output for objc, based on user configuration } else if self.localizationExportLanguage == .ObjC { let implementation = self.localizationCore.writerWithObjCImplementationWithFilename(filename: self.localizationFilePathToWriteTo.deletingPathExtension().lastPathComponent) let header = self.localizationCore.writerWithObjCHeader() // Write .h and .m file if self.localizationExportStream == .Standard { header.writeToSTD(clearBuffer: true) implementation.writeToSTD(clearBuffer: true) } else if self.localizationExportStream == .File { implementation.writeToOutputFileAtPath(path: self.localizationFilePathToWriteTo) header.writeToOutputFileAtPath(path: self.localizationFileHeaderPathToWriteTo!) } } } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - LocalizationPrinter Class implementation class StreamWriter { var outputBuffer : String = "" // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Public func writeHeader() { // let formatter = NSDateFormatter() // formatter.dateFormat = "yyyy-MM-dd 'at' h:mm a" self.store(string: "//\n") self.store(string: "// Autogenerated by Satish Babariya \n") self.store(string: "// Do not change this file manually!\n") self.store(string: "//\n") // self.store("// \(formatter.stringFromDate(NSDate()))\n") // self.store("//\n") } func writeMarkWithName(name : String, contentLevel : Int = 0) { self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "\n") self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "\n") self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n") self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "// MARK: - \(name)\n") self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "\n") } func writeSwiftImports() { self.store(string: "import Foundation\n") } func writeObjCImportsWithFileName(name : String) { self.store(string: "#import \"\(name).h\"\n") } func writeObjCHeaderImports() { self.store(string: "@import Foundation;\n") if let csc = OBJC_CUSTOM_SUPERCLASS { self.store(string: "#import \"\(csc).h\"\n") } } func writeObjCHeaderMacros() { self.store(string: "// Make localization to be easily accessible\n") self.store(string: "#define \(BASE_CLASS_NAME) [\(OBJC_CLASS_PREFIX)\(BASE_CLASS_NAME) sharedInstance]\n") } func writeCodeStructure(structure : String) { self.store(string: structure) } func writeToOutputFileAtPath(path : URL, clearBuffer : Bool = true) { _ = try? self.outputBuffer.write(toFile: path.path, atomically: true, encoding: String.Encoding.utf8) if clearBuffer { self.outputBuffer = "" } } func writeToSTD(clearBuffer : Bool = true) { print(self.outputBuffer) if clearBuffer { self.outputBuffer = "" } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Private private func store(string : String) { self.outputBuffer += string } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - TemplateFactory Class implementation class TemplateFactory { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Public - Swift Templates class func templateForSwiftStructWithName(name : String, content : String, contentLevel : Int) -> String { return "\n" + TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "public struct \(name) {\n" + "\n" + "\(content)\n" + TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "}" } class func templateForSwiftStaticVarWithName(name : String, key : String, table: String?, baseTranslation : String, contentLevel : Int) -> String { let tableName: String if let table = table { tableName = "tableName: \"\(table)\", " } else { tableName = "" } return TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "/// Base translation: \(baseTranslation)\n" + TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "public static var \(name) : String = NSLocalizedString(\"\(key)\", \(tableName)comment: \"\")\n" } class func templateForSwiftFuncWithName(name : String, key : String, table: String?, baseTranslation : String, methodHeader : String, params : String, contentLevel : Int) -> String { let tableName: String if let table = table { tableName = "tableName: \"\(table)\", " } else { tableName = "" } return TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "/// Base translation: \(baseTranslation)\n" + TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "public static func \(name)(\(methodHeader)) -> String {\n" + TemplateFactory.contentIndentForLevel(contentLevel: contentLevel + 1) + "return String(format: NSLocalizedString(\"\(key)\", \(tableName)comment: \"\"), \(params))\n" + TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "}\n" } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Public - ObjC templates class func templateForObjCClassImplementationWithName(name : String, content : String, contentLevel : Int) -> String { return "@implementation \(name)\n\n" + "\(content)\n" + "@end\n\n" } class func templateForObjCStaticVarImplementationWithName(name : String, key : String, table: String?, baseTranslation : String, contentLevel : Int) -> String { let tableName = table != nil ? "@\"\(table!)\"" : "nil" return "- (NSString *)\(name) {\n" + TemplateFactory.contentIndentForLevel(contentLevel: 1) + "return NSLocalizedStringFromTable(@\"\(key)\", \(tableName), nil);\n" + "}\n" } class func templateForObjCClassVarImplementationWithName(name : String, className : String, contentLevel : Int) -> String { return "- (_\(className) *)\(name) {\n" + TemplateFactory.contentIndentForLevel(contentLevel: 1) + "return [\(OBJC_CLASS_PREFIX)\(className) new];\n" + "}\n" } class func templateForObjCMethodImplementationWithName(name : String, key : String, table: String?, baseTranslation : String, methodHeader : String, blockHeader : String, blockParams : String, contentLevel : Int) -> String { let tableName = table != nil ? "@\"\(table!)\"" : "nil" return "- (NSString *(^)(\(methodHeader)))\(name) {\n" + TemplateFactory.contentIndentForLevel(contentLevel: 1) + "return ^(\(blockHeader)) {\n" + TemplateFactory.contentIndentForLevel(contentLevel: 2) + "return [NSString stringWithFormat: NSLocalizedStringFromTable(@\"\(key)\", \(tableName), nil), \(blockParams)];\n" + TemplateFactory.contentIndentForLevel(contentLevel: 1) + "};\n" + "}\n" } class func templateForObjCClassHeaderWithName(name : String, content : String, contentLevel : Int) -> String { return "@interface \(name) : \(OBJC_CUSTOM_SUPERCLASS ?? "NSObject")\n\n" + "\(content)\n" + "@end\n" } class func templateForObjCStaticVarHeaderWithName(name : String, key : String, baseTranslation : String, contentLevel : Int) -> String { return "/// Base translation: \(baseTranslation)\n" + "- (NSString *)\(name);\n" } class func templateForObjCClassVarHeaderWithName(name : String, className : String, contentLevel : Int) -> String { return "- (_\(className) *)\(name);\n" } class func templateForObjCMethodHeaderWithName(name : String, key : String, baseTranslation : String, methodHeader : String, contentLevel : Int) -> String { return "/// Base translation: \(baseTranslation)\n" + "- (NSString *(^)(\(methodHeader)))\(name);" } class func templateForObjCBaseClassHeader(name: String) -> String { return "+ (\(name) *)sharedInstance;\n" } class func templateForObjCBaseClassImplementation(name : String) -> String { return "+ (\(name) *)sharedInstance {\n" + "\n" + TemplateFactory.contentIndentForLevel(contentLevel: 1) + "static dispatch_once_t once;\n" + TemplateFactory.contentIndentForLevel(contentLevel: 1) + "static \(name) *instance;\n" + TemplateFactory.contentIndentForLevel(contentLevel: 1) + "dispatch_once(&once, ^{\n" + TemplateFactory.contentIndentForLevel(contentLevel: 2) + "instance = [[\(name) alloc] init];\n" + TemplateFactory.contentIndentForLevel(contentLevel: 1) + "});\n" + TemplateFactory.contentIndentForLevel(contentLevel: 1) + "return instance;\n" + "}" } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Public - Helpers class func contentIndentForLevel(contentLevel : Int) -> String { var outputString = "" for _ in 0 ..< contentLevel { outputString += " " } return outputString } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Actual processing let runtime = Runtime() runtime.run()
37.248713
554
0.572985
e5796f736b80b55b6fc8b7e264fff5e8f3be69ec
138
// // File.swift // // // Created by Oleksii Moisieienko on 16.04.2021. // import Foundation public protocol CoordinatorAction { }
10.615385
49
0.673913
ff632dfab308e7bc81be7cbbaf937973f0fe305e
8,111
// // CustomUIPickerView.swift // LybiaApp // // Created by MedBeji on 25/02/2018. // Copyright © 2018 unfpa. All rights reserved. // import UIKit import Tweener public typealias PickedAction = (Int)->Void class CustomUIPickerView: UIPickerView,UIPickerViewDataSource, UIPickerViewDelegate { // var model = [String]() // var model = [FilterType]() var modelImage:[UIImage] = []{ didSet { if modelImage != oldValue { DispatchQueue.main.async { self.setNeedsLayout() } } } } override var isHidden: Bool{ didSet { if(isHidden){ print("CustomUIPickerView-A显示\(isHidden)") }else{ print("CustomUIPickerView-B显示\(isHidden)") } } } let semaphoreFilter = DispatchSemaphore(value: 1) var rotationAngle: CGFloat! var height:CGFloat = 60{ didSet { if height != oldValue { self.setNeedsLayout() } } } var width:CGFloat = 60{ didSet { if width != oldValue { self.setNeedsLayout() } } } var pickedActionVar:PickedAction? init(parentView:UIView,y: CGFloat = 0,selectedIndex: Int = 1) { super.init(frame: parentView.frame) setupPickerView(parentView,y, selectedIndex) } public func getPickedItem(ac:@escaping PickedAction){ self.pickedActionVar = ac } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } var filterName:[FilterType]! func setupPickerView(_ parentView:UIView,_ y: CGFloat,_ selectedIndex: Int){ // pickerView.widthComponent = self.view.frame.width self.delegate = self self.dataSource = self self.transformToHorizontale() parentView.addSubview(self) //坐标控制弧度,300-600基本无弧度,200-400微 self.frame = CGRect(x: 0-320, y: y+10, width: parentView.frame.width+600, height: height * 1.3) if(Global.isIphoneX()){ self.frame = CGRect(x: 0-320, y: y, width: parentView.frame.width+600, height: height * 1.5) } // self.backgroundColor = UIColor.red self.selectRow(selectedIndex, inComponent: 0, animated: true) filterName = defaultFilters if(!filterName.contains(FilterType.none)){ filterName.insert(FilterType.none, at: 0) } self.clearSeparatorWithView() } // var widthComponent: CGFloat? func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return modelImage.count } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return height } func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return width } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let view = UIView() view.frame = CGRect(x: 0, y: 0, width: width , height: height * 1.3) if(modelImage.count > 0){ let image = modelImage[row] let imageView = UIImageView(image: image) imageView.frame = CGRect(x: 0, y: height/3, width: width, height: height) imageView.contentMode = .scaleAspectFill let imageViewMask = UILabel.init(frame: CGRect(x: 0, y: height, width: width, height: height/3)) imageViewMask.backgroundColor = #colorLiteral(red: 0.8374180198, green: 0.8374378085, blue: 0.8374271393, alpha: 1) imageViewMask.text = filterName[row].name_zh() imageViewMask.font = UIFont.systemFont(ofSize: 12) imageViewMask.textColor = UIColor.black imageViewMask.textAlignment = .center // setTextLayer(centerStr: filterName[row].name_zh(), imgView: imageViewMask) view.addSubview(imageView) view.addSubview(imageViewMask) // view.backgroundColor = UIColor.gray // view rotation view.transform = CGAffineTransform(rotationAngle: 90 * (.pi/180)) } return view } func setTextLayer(centerStr:String,imgView:UIView){ //字符蒙版 let txtMask = CATextLayer() // txtMask.bounds = imgView.bounds //加上不显示 txtMask.alignmentMode = CATextLayerAlignmentMode.center // txtMask.anchorPoint = CGPoint(x: 0, y: 0) // txtMask.bounds.size = txtBounds.size // txtMask.bounds.size = imgView.bounds.size // txtMask.frame = imgView.frame txtMask.frame = CGRect.init(x: 0, y: imgView.bounds.size.height*2/3, width: imgView.bounds.size.width, height: imgView.bounds.size.height/3) // txtMask.position = center txtMask.contentsScale = UIScreen.main.scale txtMask.fontSize = 12 txtMask.string = centerStr // txtMask.contents = "progress_dialog_saving".localize() txtMask.foregroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) txtMask.backgroundColor = #colorLiteral(red: 0.8374180198, green: 0.8374378085, blue: 0.8374271393, alpha: 0.6953392551) imgView.layer.addSublayer(txtMask) } var tempRow = 0 //to do some stuff when row is selected, in our case we set picked image into our imageView func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let tempView = pickerView.view(forRow: row, forComponent: component) let tempViewByRow = pickerView.view(forRow: tempRow, forComponent: component) if let mask = tempView?.subviews[1] as? UILabel{ let t = Tween(target:mask,//Target duration:0.3,//One second ease:Ease.none, to:[.key(\UILabel.alpha,1), .key(\UILabel.transform,mask.transform.translatedBy(x: 0, y: -(mask.frame.width))), // \UILabel.textColor:UIColor.green,无用 //This property is an optional. // \UIView.backgroundColor!:UIColor.red ]) t.onComplete = { mask.textColor = Theme_COLOR } t.play() } if let maskTemp = tempViewByRow?.subviews[1] as? UILabel{ if(tempRow != row){ let r = Tween(target:maskTemp,//Target duration:0.3,//One second ease:Ease.none, to:[.key(\UILabel.alpha,1), .key(\UILabel.transform,maskTemp.transform.translatedBy(x: 0, y: (maskTemp.frame.width))), // \UILabel.textColor:UIColor.black,无用 //This property is an optional. // \UIView.backgroundColor!:UIColor.red ]) r.onComplete = { maskTemp.textColor = UIColor.black } r.play() } } if let pickAction = self.pickedActionVar{ pickAction(row) } // self.setNeedsLayout() tempRow = row } func transformToHorizontale(){ rotationAngle = -90 * (.pi/180) self.transform = CGAffineTransform(rotationAngle: rotationAngle) } }
34.662393
148
0.548391
fb371b8d5aed8fcbe87e84ff64ee8f0f1bf83c24
2,990
// // Constants.swift // TTBaseModel // // Created by Remzi YILDIRIM on 17.02.2020. // Copyright © 2020 Turkish Technic. All rights reserved. // import Foundation class Constants { static var lang = "tr-TR" static let applicationScheme = "ttasistan" static let applicationDisplayName = Bundle.main.infoDictionary?[kCFBundleNameKey as String] as! String static let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String static let build = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as! String static let os = "IOS" static var isBeta : Bool { get { #if DEVELOPMENT return true #else return false #endif } } static var isRealDevice: Bool { get { #if targetEnvironment(simulator) return false #else return true #endif } } static let empty = "" static let dash = "-" static let yes = "YES" static let no = "NO" static let confirm = "CONFIRM" static let spare = "SPARE" static let employeeIDPrefix = "E" static let underNavigationBarHeight: CGFloat = 64 static let ongoing = "ONGOING" static let closed = "CLOSED" static let defectTroubleShootingStatuses: [String] = [Constants.ongoing, Constants.closed] static let defectTroubleShootingTypes: [String] = ["AMM", "TSM", "FIM", "SRM"] static let mostUsedLocations: [String] = ["IST", "ISL", "SAW", "ESB"] static let fleets = ["A320", "A330", "A350", "B737", "B747", "B777", "B787"] static let flightScheduleOrigin = "IST" static let grandType = "password" static let nrcPrefix = "NRC" static let contactEmail = "[email protected] - [email protected]" static let userManualUrl = "https://mobileupdate.thyteknik.com.tr/usermanual/ttasistan.pdf" static let mobilineProjectId = 18 struct Countly { static let key = "29023df0a301c15f1999be4939b8f125d3ed7042" static let host = "http://10.9.102.205/" } struct Chars { static let n = "N" static let y = "Y" } struct Defect { static let minDefectItem: Int = 1 static let maxDefectItem: Int = 10 static let minManRequired: Double = 1 static let minManHour: Double = 1 static let open = "OPEN" static let hold = "HOLD" static let closed = "CLOSED" } struct WorkOrder { static let line = "LINE" static let base = "OPEN" static let statusClosed = "CLOSED" static let statusCancel = "CANCEL" static let statusDefer = "DEFER" static let tcNrcStatus = ["OPEN","CLOSED","CANCEL","DEFER","DELAYED","HOLD","ON CONDITION"] static let tcNrcStatusForRoster = ["OPEN",Constants.WorkOrder.statusClosed, Constants.WorkOrder.statusCancel, Constants.WorkOrder.statusDefer] } }
33.595506
150
0.627425
8a99898fa81dcabf207ec5010241212be1d54682
502
// // UserDetailsViewController.swift // POC // // Created by Chris Nevin on 09/03/2019. // Copyright © 2019 Chris Nevin. All rights reserved. // import UIKit class UserDetailsViewController: ViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white } override func bind() { super.bind() subscribe(to: \.selectedUser) { [unowned self] user in self.navigationItem.title = user?.name } } }
20.916667
62
0.629482
1a469ccf414a49c604f18ce84da9026e09f9be62
557
// // Zap // // Created by Otto Suess on 23.05.18. // Copyright © 2018 Zap. All rights reserved. // import Foundation enum Environment { static var allowFakeMnemonicConfirmation: Bool { return ProcessInfo.processInfo.environment["FAKE_MNEMONIC_CONF"] == "1" } static var skipPinFlow: Bool { return ProcessInfo.processInfo.environment["SKIP_PIN_FLOW"] == "1" } static var fakeBiometricAuthentication: Bool { return ProcessInfo.processInfo.environment["FAKE_BIOMETRIC_AUTHENTICATION"] == "1" } }
24.217391
90
0.680431
b97714a24ff0937c97a3db848ffbb80223d18243
1,226
// // LocalViewTestHelpers.swift // localview // // Created by Zach Freeman on 1/24/16. // Copyright © 2016 sparkwing. All rights reserved. // import Foundation import SwiftyJSON open class LocalViewTestsHelpers { static func bundleFileContentsAsData(_ filename: String, filetype: String) -> Data { let bundle = Bundle(for: object_getClass(self)!) let filePath = bundle.path(forResource: filename, ofType: filetype) do { let fileContents: Data = try Data(contentsOf: URL(fileURLWithPath: filePath!)) return fileContents } catch { print("unable to get file contents of \(filename)") return Data() } } static func fileContentsAsJson(_ fileContents: NSData) -> JSON { var fileContentsJson: JSON = JSON.null do { let fileContentJsonObject = try JSONSerialization .jsonObject(with: fileContents as Data, options: JSONSerialization.ReadingOptions.mutableContainers) fileContentsJson = JSON(fileContentJsonObject) } catch { print("unable to convert file contents to json") } return fileContentsJson } }
33.135135
90
0.632953
11b0ff81ad5a3aaf6b66716f6a76135cba82c71c
622
// // MovieCell.swift // flix // // Created by Stephanie Angulo on 6/15/16. // Copyright © 2016 Stephanie Angulo. All rights reserved. // import UIKit class MovieCell: UITableViewCell { @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var posterView: 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 } }
21.448276
63
0.672026
14b57889ee44114c36c37922275148f651905ff0
456
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // StorageAccountListKeysResultProtocol is the response from the ListKeys operation. public protocol StorageAccountListKeysResultProtocol : Codable { var keys: [StorageAccountKeyProtocol?]? { get set } }
45.6
96
0.774123
c196ef665777373d9c03db4132cddff8a05b2d04
2,295
// The MIT License (MIT) // Copyright © 2022 Ivan Vorobei ([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 FirebaseMessaging public enum SPFirebaseMessaging { public static func addFCMTokenDidChangeListener(_ listner: @escaping ( _ fcmToken: String?) -> Void) { MessagingService.shared.listenerClouser = listner } public static func removeFCMTokenDidChangeListener() { MessagingService.shared.listenerClouser = nil } private class MessagingService: NSObject, MessagingDelegate { // MARK: - MessagingDelegate func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { listenerClouser?(fcmToken) } // MARK: - Singltone internal var listenerClouser: ((String?) -> Void)? = nil { didSet { if listenerClouser == nil { Messaging.messaging().delegate = nil } else { Messaging.messaging().delegate = MessagingService.shared } } } internal static var shared = MessagingService() private override init() { super.init() } } }
38.898305
106
0.671895
5b4436f5aed93c6cb54cc0a7ecc2b35593f1030b
1,215
// // WeSplit_Tests.swift // WeSplit-Tests // // Created by Shreemit on 27/01/22. // import XCTest @testable import WeSplit_ class WeSplit_Tests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
32.837838
130
0.682305
28d9ca6bd551a9288521ac09b8395fd4bebd2468
2,894
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // SSLCertificateTest+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension SSLCertificateTest { static var allTests : [(String, (SSLCertificateTest) -> () throws -> Void)] { return [ ("testLoadingPemCertFromFile", testLoadingPemCertFromFile), ("testLoadingDerCertFromFile", testLoadingDerCertFromFile), ("testDerAndPemAreIdentical", testDerAndPemAreIdentical), ("testLoadingPemCertFromMemory", testLoadingPemCertFromMemory), ("testPemLoadingMechanismsAreIdentical", testPemLoadingMechanismsAreIdentical), ("testLoadingPemCertsFromMemory", testLoadingPemCertsFromMemory), ("testLoadingPemCertsFromFile", testLoadingPemCertsFromFile), ("testLoadingDerCertFromMemory", testLoadingDerCertFromMemory), ("testLoadingGibberishFromMemoryAsPemFails", testLoadingGibberishFromMemoryAsPemFails), ("testLoadingGibberishFromPEMBufferFails", testLoadingGibberishFromPEMBufferFails), ("testLoadingGibberishFromMemoryAsDerFails", testLoadingGibberishFromMemoryAsDerFails), ("testLoadingGibberishFromFileAsPemFails", testLoadingGibberishFromFileAsPemFails), ("testLoadingGibberishFromPEMFileFails", testLoadingGibberishFromPEMFileFails), ("testLoadingGibberishFromFileAsDerFails", testLoadingGibberishFromFileAsDerFails), ("testLoadingNonexistentFileAsPem", testLoadingNonexistentFileAsPem), ("testLoadingNonexistentPEMFile", testLoadingNonexistentPEMFile), ("testLoadingNonexistentFileAsDer", testLoadingNonexistentFileAsDer), ("testEnumeratingSanFields", testEnumeratingSanFields), ("testNonexistentSan", testNonexistentSan), ("testCommonName", testCommonName), ("testCommonNameForGeneratedCert", testCommonNameForGeneratedCert), ("testMultipleCommonNames", testMultipleCommonNames), ("testNoCommonName", testNoCommonName), ("testUnicodeCommonName", testUnicodeCommonName), ("testExtractingPublicKey", testExtractingPublicKey), ] } }
49.896552
103
0.663442
294ef0aa9b855a707dc47f87dad76c90d9aa4f29
546
// // DurationTableViewCell.swift // MetabolicCompass // // Created by Artem Usachov on 6/6/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import UIKit class DurationTableViewCell: BaseAddEventTableViewCell { @IBOutlet weak var durationLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
21.84
65
0.690476
14929679cc2901142bbf6f81e09fd4247da17ecf
3,591
// Copyright (c) 2015-2016. Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. All rights reserved. import Foundation import UIKit @objc internal protocol Context: NSCoding { var entries : [ContextEntry] { get set } var name: String { get set } var devices : [Device] { get set } func add() func load(index: Int) func save(index: Int) func deserialize() } class AppContext: NSObject, Context { var client: Client! var current: ContextEntry = ContextEntry(name: "Default", devices: []) var entries: [ContextEntry] = [] var name: String { get { return current.name } set(value) { current.name = value } } var devices : [Device] { get { return current.devices } set(value) { current.devices = value } } override init() { super.init() self.name = "" self.devices = [] } required convenience init(coder aDecoder: NSCoder) { self.init() if let name = aDecoder.decodeObjectForKey("name") as? String { self.name = name } if let devices = aDecoder.decodeObjectForKey("devices") as? [Device] { self.devices = devices } if let entries = aDecoder.decodeObjectForKey("entries") as? [ContextEntry] { self.entries = entries } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(devices, forKey: "devices") aCoder.encodeObject(entries, forKey: "entries") } func clear() { NSUserDefaults.standardUserDefaults().removeObjectForKey("appContext") } func deserialize() { if let appContextData = NSUserDefaults.standardUserDefaults().objectForKey("appContext") as? NSData { if let context = NSKeyedUnarchiver.unarchiveObjectWithData(appContextData) as? AppContext { self.name = context.name self.devices = context.devices self.entries = context.entries } } } func add() { entries.append(ContextEntry(name: "Context \(entries.count + 1)", devices: [])) } func load(index: Int) { current.name = entries[index].name current.devices = [Device]() if(entries[index].devices.count == 0) { return } for i in 0...entries[index].devices.count-1 { let device = entries[index].devices[i] current.devices.append(Device(name: device.name, topic: device.topic, color: device.color, state: device.state)!) } } func save(index: Int) { if current.devices.count > 0 { entries[index].devices = [Device]() for i in 0...current.devices.count-1 { let device = current.devices[i] entries[index].devices.append(Device(name: device.name, topic: device.topic, color: device.color, state: device.state)!) } } serialize() } private func serialize() { let data = NSKeyedArchiver.archivedDataWithRootObject(self) NSUserDefaults.standardUserDefaults().setObject(data, forKey: "appContext") } }
24.765517
143
0.544138
fe1ab8f026be58fb63bc731405cbe33ab6c64c01
2,201
// // AppDelegate.swift // TestExample // // Created by [email protected] on 08/21/2018. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.829787
285
0.755111
d5b287ea969cfe990534057276571f504f2205a4
9,355
// // ParamsEmbedTableViewController.swift // EZPlayerExample // // Created by yangjun zhu on 2016/12/28. // Copyright © 2016年 yangjun zhu. All rights reserved. // import UIKit import EZPlayer import AVFoundation class ParamsEmbedTableViewController: UITableViewController { weak var paramsViewController: ParamsViewController! override func viewDidLoad() { super.viewDidLoad() let volume = AVAudioSession.sharedInstance().outputVolume//其他会获取不到,比如:EZPlayerUtils.systemVolumeSlider.value volumeLabel.text = String(format:"%.2f", volume) volumeSilder.value = volume NotificationCenter.default.addObserver(self, selector: #selector(ParamsEmbedTableViewController.volumeChange(_:)) , name:Notification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification") , object: nil) // 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() } deinit { NotificationCenter.default.removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - url //http://www.cnblogs.com/linr/p/6185172.html @IBOutlet weak var urlTextField: UITextField! @IBAction func playButtonTap(_ sender: UIButton) { self.view.endEditing(true) if let text = self.urlTextField.text,let url = URL(string: text){ MediaManager.sharedInstance.playEmbeddedVideo(url: url, embeddedContentView: self.paramsViewController.dlView) } } // MARK: - local @IBAction func localMP4ButtonTap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView) } // MARK: - remote @IBAction func remoteT1Tap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url: URL.Test.apple_0, embeddedContentView: self.paramsViewController.dlView) } @IBAction func remoteT2Tap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url: URL.Test.apple_1, embeddedContentView: self.paramsViewController.dlView) } @IBAction func remoteT3Tap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url: URL.Test.remoteMP4_0, embeddedContentView: self.paramsViewController.dlView) } // MARK: - rate @IBAction func rateSlowTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.rate = 0.5 } @IBAction func rateNormalTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.rate = 1 } @IBAction func rateFastTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.rate = 1.5 } // MARK: - videoGravity @IBAction func aspectTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.videoGravity = .aspect } @IBAction func aspectFillTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.videoGravity = .aspectFill } @IBAction func scaleFillTap(_ sender: UIButton) { MediaManager.sharedInstance.player?.videoGravity = .scaleFill } // MARK: - displayMode @IBAction func embeddedTap(_ sender: UIButton) { // MediaManager.sharedInstance.hiddenFloatVideo() if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.toEmbedded() }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView) } } @IBAction func fullscreenPortraitTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.fullScreenMode = .portrait MediaManager.sharedInstance.player?.toFull() }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: nil, userinfo: ["fullScreenMode" :EZPlayerFullScreenMode.portrait]) } } @IBAction func fullscreenLandscapeTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.fullScreenMode = .landscape MediaManager.sharedInstance.player?.toFull() }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0) } } @IBAction func floatTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.toFloat() }else{ } } // MARK: - skin @IBAction func noneSkinTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.controlViewForIntercept = UIView() }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView, userinfo: ["skin" : UIView()]) } } @IBAction func yellowSkinTap(_ sender: UIButton) { let yellow = UIView() yellow.backgroundColor = UIColor.yellow.withAlphaComponent(0.3) if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.controlViewForIntercept = yellow }else{ let yellow = UIView() yellow.backgroundColor = UIColor.yellow.withAlphaComponent(0.3) MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView, userinfo: ["skin" :yellow]) } } @IBAction func defaultSkinTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.controlViewForIntercept = nil }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView) } } // MARK: - Continued: @IBAction func firstVideoTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.replaceToPlayWithURL(URL.Test.apple_0) }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.apple_0, embeddedContentView: self.paramsViewController.dlView) } } @IBAction func secondTap(_ sender: UIButton) { if MediaManager.sharedInstance.player != nil { MediaManager.sharedInstance.player?.replaceToPlayWithURL(URL.Test.localMP4_0) }else{ MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_0, embeddedContentView: self.paramsViewController.dlView) } } // MARK: - autoPlay: @IBAction func autoPlayTap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_1, embeddedContentView: self.paramsViewController.dlView) } @IBAction func nonautoPlayTap(_ sender: UIButton) { MediaManager.sharedInstance.playEmbeddedVideo(url:URL.Test.localMP4_2, embeddedContentView: self.paramsViewController.dlView , userinfo: ["autoPlay" :false]) } // MARK: - fairPlay: @IBAction func onlineTap(_ sender: UIButton) { } @IBAction func offlineTap(_ sender: UIButton) { } // MARK: - Volume: @IBOutlet weak var volumeSilder: UISlider! @IBOutlet weak var volumeLabel: UILabel! @IBAction func volumeChanged(_ sender: UISlider) { if let player = MediaManager.sharedInstance.player { player.systemVolume = sender.value volumeLabel.text = String(format:"%.2f", sender.value) } } @objc func volumeChange(_ notification:NSNotification) { if let userInfo = notification.userInfo{ let volume = userInfo["AVSystemController_AudioVolumeNotificationParameter"] as! Float volumeLabel.text = String(format:"%.2f", volume) volumeSilder.value = volume } } // MARK: - snapshot: @IBOutlet weak var snapshotImageView: UIImageView! @IBAction func snapshotWithoutM3u8(_ sender: Any) { if let player = MediaManager.sharedInstance.player { let width = UIScreen.main.scale * 100; player.generateThumbnails(times: [player.currentTime ?? 0], maximumSize: CGSize(width:width,height:width)) { [weak self] items in self?.snapshotImageView.image = items[0].image } } } @IBAction func snapshotWithM3u8(_ sender: Any) { if let player = MediaManager.sharedInstance.player ,let image = player.snapshotImage() { self.snapshotImageView.image = image } } // MARK: - pip: @IBAction func startPIP(_ sender: Any) { if let player = MediaManager.sharedInstance.player { player.startPIP() } } @IBAction func stopPIP(_ sender: Any) { if let player = MediaManager.sharedInstance.player { player.stopPIP() } } }
34.142336
227
0.683271
260bd17ca8a34889f605b56e2cd4a4901b855459
476
// // IsOne.swift // Quelbo // // Created by Chris Sessions on 4/9/22. // import Foundation extension Factories { /// A symbol factory for the Zil /// [isOne](https://docs.google.com/document/d/11Kz3tknK05hb0Cw41HmaHHkgR9eh0qNLAbE9TzZe--c/edit#heading=h.4gjguf0) /// function. class IsOne: IsZero { override class var zilNames: [String] { ["1?"] } override var function: String { "isOne" } } }
19.833333
119
0.586134
4803c3de5fa24d46968b2a4c4275d4e7009727cf
121
import XCTest import SlackKitTests var tests = [XCTestCaseEntry]() tests += SlackKitTests.__allTests() XCTMain(tests)
13.444444
35
0.77686
0834dfefeb3dd471e6536f00657eac9cae4898b0
1,509
// // VoidErrorResult.swift // SwiftySimpleKeychain // // Copyright (c) 2022 Ezequiel (Kimi) Aceto (https://eaceto.dev). Based on Auth0's SimpleKeychain // // 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. #if canImport(Foundation) import Foundation #endif /** * VoidErrorResult is an alias of a Result that returns **Void** on success * and a **SwiftySimpleKeychainError** (error) when a failure occurs */ public typealias VoidErrorResult = Result<Void, SwiftySimpleKeychainError>
44.382353
97
0.764745
e9eee8aa31be64ead34fc8954f46fd6a81220853
3,043
// // ViewController.swift // YJMiracleView // // Created by Zyj163 on 08/23/2017. // Copyright (c) 2017 Zyj163. All rights reserved. // import UIKit import YJMiracleView class ViewController: UIViewController { lazy var miracleView: YJMiracleView = YJMiracleView(CGRect(x: 0, y: self.view.bounds.height - 30, width: 30, height: 30), autoTranslucentable: true, movable: true) var type: Int = 0 { didSet { switch type { case 0: miracleView.animateDriver.animateType = .lineH(10) case 1: miracleView.animateDriver.animateType = .circle(100, 0, CGFloat.pi / 2) default: break } } } override func viewDidLoad() { super.viewDidLoad() miracleView.dataSource = self miracleView.delegate = self miracleView.backgroundColor = .red miracleView.layer.cornerRadius = 15 miracleView.layer.masksToBounds = true miracleView.clickOn = { [weak miracleView] in miracleView?.isOpened ?? false ? miracleView?.close() : miracleView?.open() } view.addSubview(miracleView) miracleView.textLabel.text = "0-0" miracleView.textLabel.textColor = .white type = 0 } } extension ViewController: YJMiracleViewDataSource { func numbersOfItem(in miracleView: YJMiracleView) -> Int { return 3 } func miracleView(miracleView: YJMiracleView, itemAt position: YJMiracleItemPosition) -> YJMiracleView { let item = YJMiracleView() item.backgroundColor = UIColor(red: CGFloat(arc4random()%256)/255.0, green: CGFloat(arc4random()%256)/255.0, blue: CGFloat(arc4random()%256)/255.0, alpha: 1) item.clickOn = { [weak item] in item?.isOpened ?? false ? item?.close() : item?.open() } item.dataSource = self item.textLabel.text = "\(position.lane)-\(position.index)" item.textLabel.textColor = .white item.layer.cornerRadius = 15 item.layer.masksToBounds = true switch miracleView.animateDriver.animateType { case .lineH(let space): item.animateDriver.animateType = .lineV(space) case .lineV(let space): item.animateDriver.animateType = .lineH(space) default: item.animateDriver.animateType = miracleView.animateDriver.animateType break } return item } func miracleView(_ miracleView: YJMiracleView, sizeOfItemAt position: YJMiracleItemPosition) -> CGSize{ return CGSize(width: 30, height: 30) } } extension ViewController: YJMiracleViewDelegate { func miracleViewDidOpened(_ miracleView: YJMiracleView) { print("did open position \(miracleView.position)") // miracleView.alpha = 0.1 } func miracleViewDidClosed(_ miracleView: YJMiracleView) { if miracleView == self.miracleView { switch type { case 0: type = 1 default: type = 0 } } } }
28.707547
164
0.62767
0a26e81e995319ea66260deead0d87dc74424870
9,201
// Copyright 2018, Oath Inc. // Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms. public enum VideoKind { case ad, content } public struct Rate { public let contentRate: Value public let adRate: Value public let isAttachedToViewPort: Bool public let currentKind: VideoKind public struct Value { public let player: Bool public let stream: Bool } } func reduce(state: Rate, action: Action) -> Rate { switch (action, state.currentKind) { case (let action as SelectVideoAtIdx, _): if action.hasPrerollAds { return Rate(contentRate: .init(player: false, stream: false), adRate: .init(player: true, stream: false), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: .ad) } else { return Rate(contentRate: .init(player: true, stream: false), adRate: .init(player: false, stream: false), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: .content) } case (is Play, .content): return Rate(contentRate: .init(player: true, stream: state.contentRate.stream), adRate: .init(player: false, stream: state.adRate.stream), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is Play, .ad): return Rate(contentRate: .init(player: false, stream: state.contentRate.stream), adRate: .init(player: true, stream: state.adRate.stream), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is Pause, _): return Rate(contentRate: .init(player: false, stream: state.contentRate.stream), adRate: .init(player: false, stream: state.adRate.stream), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is ShowContent, .ad), (is DropAd, .ad): return Rate(contentRate: .init(player: true, stream: state.contentRate.stream), adRate: .init(player: false, stream: state.adRate.stream), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: .content) case (is ShowMP4Ad, .content), (is ShowVPAIDAd, .content): return Rate(contentRate: .init(player: false, stream: state.contentRate.stream), adRate: .init(player: true, stream: state.adRate.stream), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: .ad) case (let action as UpdateContentStreamRate, .content): return Rate(contentRate: .init(player: state.contentRate.player, stream: action.rate), adRate: state.adRate, isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (let action as UpdateAdStreamRate, .ad): return Rate(contentRate: state.contentRate, adRate: .init(player: state.adRate.player, stream: action.rate), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is CompletePlaybackSession, _): return Rate(contentRate: .init(player: false, stream: false), adRate: .init(player: false, stream: false), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is AdPlaybackFailed, .ad): return Rate(contentRate: .init(player: true, stream: false), adRate: .init(player: false, stream: false), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: .content) case (is ContentDidPlay, .content): return Rate(contentRate: .init(player: true, stream: state.contentRate.stream), adRate: .init(player: false, stream: false), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is ContentDidPause, .content) where state.isAttachedToViewPort: return Rate(contentRate: .init(player: false, stream: state.contentRate.stream), adRate: .init(player: false, stream: false), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is AdDidPlay, .ad): return Rate(contentRate: .init(player: false, stream: false), adRate: .init(player: true, stream: state.adRate.stream), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is AdDidPause, .ad) where state.isAttachedToViewPort: return Rate(contentRate: .init(player: false, stream: false), adRate: .init(player: false, stream: state.adRate.stream), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is AttachToViewport, _): return Rate(contentRate: state.contentRate, adRate: state.adRate, isAttachedToViewPort: true, currentKind: state.currentKind) case (is DetachFromViewport, _): return Rate(contentRate: state.contentRate, adRate: state.adRate, isAttachedToViewPort: false, currentKind: state.currentKind) case (is VRMCore.NoGroupsToProcess, .ad) where state.isAttachedToViewPort: return Rate(contentRate: .init(player: true, stream: state.contentRate.stream), adRate: .init(player: false, stream: false), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: .content) case (is VPAIDActions.AdStarted, .ad) where state.isAttachedToViewPort: return Rate(contentRate: .init(player: false, stream: false), adRate: .init(player: true, stream: state.adRate.stream), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is VPAIDActions.AdImpression, .ad) where state.isAttachedToViewPort: return Rate(contentRate: .init(player: false, stream: false), adRate: .init(player: state.adRate.player, stream: true), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is VPAIDActions.AdPaused, .ad) where state.isAttachedToViewPort: return Rate(contentRate: .init(player: false, stream: false), adRate: .init(player: false, stream: false), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is VPAIDActions.AdResumed, .ad) where state.isAttachedToViewPort: return Rate(contentRate: .init(player: false, stream: false), adRate: .init(player: true, stream: true), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (let action as DidHideAdClickthrough, .ad): let streamRate = action.isAdVPAID ? true : state.adRate.stream return Rate(contentRate: .init(player: false, stream: false), adRate: .init(player: true, stream: streamRate), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: state.currentKind) case (is VPAIDActions.AdStopped, .ad), (is VPAIDActions.AdNotSupported, .ad), (is VPAIDActions.AdSkipped, .ad), (is VPAIDActions.AdError, .ad), (is SkipAd, .ad), (is MP4AdStartTimeout, .ad), (is AdMaxShowTimeout, .ad): return Rate(contentRate: .init(player: true, stream: state.contentRate.stream), adRate: .init(player: false, stream: false), isAttachedToViewPort: state.isAttachedToViewPort, currentKind: .content) default: return state } }
48.172775
95
0.560157
1448a43bd019cfc6edb74e90acfe3fb06e1694cf
7,928
// // Anagrams.swift // MineBleeper // // Created by Wikipedia Brown on 12/12/19. // Copyright © 2019 IamGoodBad. All rights reserved. // import Foundation class WordTracker { let charactersRecord: [Character: Int] let characterCount: Int var checkCount = 0 var exhausted: Bool { checkCount == characterCount} var characters: [Character: Int] init(word: String) { var characterDict: [Character: Int] = [:] for character in word { if let count = characterDict[character] { characterDict[character] = count + 1 } else { characterDict[character] = 1 } } characters = characterDict characterCount = word.count charactersRecord = characterDict } func checkCharacter(character: Character) -> Bool { guard let count = characters[character] else { return false } switch count { case 0: characters[character] = nil; return false default: characters[character] = count - 1; return true } } func reset() { characters = charactersRecord checkCount = 0 } } class Node { let value: Character var children: [Character: Node] var word: (string: String, count: Int)? var furtherWords: [String] init(value: Character) { self.value = value self.children = [:] self.furtherWords = [] } } class Trie { private var rootNode: Node = Node(value: "*") func addWord(word: String) { let characters: [Character] = Array(word) var currentNode = rootNode for character in characters { currentNode.furtherWords.append(word) if let node = currentNode.children[character] { currentNode = node } else { let node = Node(value: character) currentNode.children[character] = node currentNode = node } } if let wordCount = currentNode.word { currentNode.word = (string: wordCount.string, count: wordCount.count + 1) } else { currentNode.word = (string: word, count: 1) } } func removeInstanceOfWord(word: String) { let characters: [Character] = Array(word) var currentNode = rootNode for character in characters { if let node = currentNode.children[character] { currentNode = node } else { return } } if let wordCount = currentNode.word, wordCount.count > 1 { currentNode.word = (string: wordCount.string, count: wordCount.count - 1) } else { currentNode.word = nil } } func removeWord(word: String) { let characters: [Character] = Array(word) var currentNode = rootNode for character in characters { if let node = currentNode.children[character] { currentNode = node } else { return } } currentNode.word = nil } func checkWordExists(word: String) -> (includedWords: [String], wordExists: Bool, wordsIncludedIn: [String]) { let characters: [Character] = Array(word) var currentNode = rootNode var includedWords: [String] = [] let wordExists: Bool var wordsIncludedIn: [String]? = nil for character in characters { if let node = currentNode.children[character] { currentNode = node if let string = currentNode.word?.string { includedWords.append(string) } } else { return (includedWords, false, []) } } wordExists = (currentNode.word?.string == word) if wordExists { wordsIncludedIn = currentNode.furtherWords } return (includedWords, wordExists, wordsIncludedIn ?? []) } func checkAnagramExists(word: String) { let wordTracker = WordTracker(word: word) var nodesToCheck = rootNode.children.values var includedWords: [String] = [] let wordExists: Bool var wordsIncludedIn: [String]? = nil for node in nodesToCheck { } } func test(wordTracker: WordTracker, node: Node, includedWords: [(string: String, count: Int)] = [], anagrams: [(string: String, count: Int)] = [], furtherWords: [String] = []) -> ([(string: String, count: Int)], [(string: String, count: Int)], [String]) { guard wordTracker.exhausted == false else { var _anagrams = anagrams var _furtherWords = furtherWords if let word = node.word {_anagrams.append(word)} _furtherWords.append(contentsOf: node.furtherWords) return (includedWords, _anagrams, _furtherWords) } guard wordTracker.checkCharacter(character: node.value) == true else { return (includedWords, [], []) } var _includedWords = includedWords if let word = node.word {_includedWords.append(word)} // var _includedWords: [String] = includedWords // let _anagrams: [String] = anagrams // if let string = node.word // for child in node.children { // return test(wordTracker: wordTracker, node: child.value) // } return ([], [], []) } } // // // //class easy { // class Node { // let value: Character // var children: [Character: Node] // var words: [String] // // // init(value: Character) { // self.value = value // self.children = [:] // self.words = [] // } // } // // class trie { // private var rootNode: Node = Node(value: "*") // // func addWord(word: String) { // let characters: [Character] = Array(word).sorted() // var currentNode = rootNode // // for character in characters { // if let node = currentNode.children[character] { // currentNode = node // } else { // let node = Node(value: character) // currentNode.children[character] = node // currentNode = node // } // } // currentNode.words.append(word) // } // // func removeWord(word: String) { // // let characters: [Character] = Array(word).sorted() // var currentNode = rootNode // // for character in characters { // if let node = currentNode.children[character] { // currentNode = node // } else { // return // } // } // // currentNode.words = currentNode.words.filter {$0 == word} // } // // func checkAnagram(word: String) -> [String] { // let characters: [Character] = Array(word).sorted() // var currentNode = rootNode // // for character in characters { // if let node = currentNode.children[character] { // currentNode = node // } else { // return [] // } // } // // return currentNode.words // } // // // } //}
28.724638
115
0.496973
5dd6e348d5efcfe36993cf0df574971b1fe40c35
351
class Solution { func checkIfExist(_ arr: [Int]) -> Bool { var table : Set<Int> = [] for ele in arr { if table.contains(ele) { return true } if ele % 2 == 0 { table.insert(ele/2) } table.insert(ele*2) } return false } }
23.4
45
0.401709
d64e6557e7652b5d82ceb407e8b65439c36cdf93
175
import Foundation public enum HTTPRequestError: Error { case badRequest(String) case unauthorized(String) case serverError(String) case invalidPath(String) }
19.444444
37
0.748571
d7c6c18c13b90413318eea3b1065ce5465a59843
1,371
// // TranscriptAdapter.swift // WWDC // // Created by Guilherme Rambo on 07/06/16. // Copyright © 2016 Guilherme Rambo. All rights reserved. // import Foundation import SwiftyJSON class TranscriptLineAdapter: JSONAdapter { typealias ModelType = TranscriptLine static func adapt(json: JSON) -> ModelType { let line = TranscriptLine() line.timecode = json["timecode"].doubleValue line.text = json["annotation"].stringValue return line } } class TranscriptAdapter: JSONAdapter { typealias ModelType = Transcript static func adapt(json: JSON) -> ModelType { let transcript = Transcript() transcript.fullText = json["transcript"].stringValue if let annotations = json["annotations"].arrayObject as? [String], timecodes = json["timecodes"].arrayObject as? [Double] { let transcriptData = annotations.map { annotations.indexOf($0)! >= timecodes.count ? nil : JSON(["annotation": $0, "timecode": timecodes[annotations.indexOf($0)!]]) }.filter({ $0 != nil }).map({$0!}) transcriptData.map(TranscriptLineAdapter.adapt).forEach { line in line.transcript = transcript transcript.lines.append(line) } } return transcript } }
28.5625
211
0.609774
6720aee1e66695a1c16605b2dd9a32b914b8c168
2,502
/*: # H-Index II https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/541/week-3-june-15th-june-21st/3364/ --- ### Problem Statement: Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." https://en.wikipedia.org/wiki/H-index ### Example: ``` Input: citations = [0,1,3,5,6] Output: 3 Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, her h-index is 3. ``` ### Follow up: + This is a follow up problem to H-Index(https://leetcode.com/problems/h-index/description/), where `citations` is now guaranteed to be sorted in ascending order. + Could you solve it in logarithmic time complexity? ### Notes: + If there are several possible values for h, the maximum one is taken as the h-index. */ import UIKit class Solution { /* -> 84 / 84 test cases passed. -> Status: Accepted -> Runtime: 132 ms -> Memory Usage: 22.2 MB */ func hIndex(_ citations: [Int]) -> Int { let totalPapers = citations.count for i in 0..<totalPapers { if citations[i] >= totalPapers - i { return totalPapers - i } } return 0 } /* -> 84 / 84 test cases passed. -> Status: Accepted -> Runtime: 124 ms -> Memory Usage: 22.2 MB */ func hIndexRevised(_ citations: [Int]) -> Int { let total = citations.count var left = 0, right = citations.count - 1 while left <= right { let middle = (left + right) / 2 let val = total - middle if citations[middle] == val { return val } else if citations[middle] > val { right = middle - 1 }else { left = middle + 1 } } return total - left } } let obj = Solution() obj.hIndex([0,1,3,5,6]) // 3 obj.hIndexRevised([0,1,3,5,6]) // 3
28.11236
199
0.585132
f7420069f9a4586507a1b4a7bc8c65666c65c9cf
13,297
// // TaskViewController.swift // Star // // Created by 杜进新 on 2018/7/4. // Copyright © 2018年 dujinxin. All rights reserved. // import UIKit private let reuseIdentifier = "reuseIdentifier" private let reuseIndentifierHeader = "reuseIndentifierHeader" private let headViewHeight : CGFloat = 278 class TaskViewController: UICollectionViewController { let taskVM = TaskVM() let vm = IdentifyVM() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.isHidden = true self.navigationController?.navigationBar.barStyle = .blackTranslucent self.taskVM.taskList { (_, msg, isSuc) in if isSuc { self.collectionView?.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() UIApplication.shared.statusBarStyle = .lightContent self.view.backgroundColor = JXF1f1f1Color self.automaticallyAdjustsScrollViewInsets = false self.navigationController?.navigationBar.isHidden = true let leftButton = UIButton() leftButton.setImage(UIImage(named: "imgBack"), for: .normal) leftButton.imageEdgeInsets = UIEdgeInsetsMake(5, 9, 5, 9) //leftButton.setTitle("up", for: .normal) leftButton.addTarget(self, action: #selector(backTo), for: .touchUpInside) let rightButton = UIButton() rightButton.setImage(UIImage(named: "iconInfo"), for: .normal) rightButton.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5) rightButton.addTarget(self, action: #selector(checkDetail), for: .touchUpInside) let navigationBar = self.setClearNavigationBar(title: "提升智慧", leftItem: leftButton,rightItem: rightButton) self.view.addSubview(navigationBar) let width = (kScreenWidth - 0.5 * 2) / 3 //let height = width * kPercent let height : CGFloat = 122 //self.collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight), collectionViewLayout: layout) let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSize.init(width: width, height: height) layout.sectionInset = UIEdgeInsetsMake(0.5, 0, 0, 0) layout.minimumLineSpacing = 0.5 layout.minimumInteritemSpacing = 0.5 layout.headerReferenceSize = CGSize(width: kScreenWidth, height: 212 + kNavStatusHeight + 60 * 2) self.collectionView?.collectionViewLayout = layout // Register cell classes self.collectionView?.register(UINib.init(nibName: "TaskCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier) self.collectionView?.register(UINib.init(nibName: "TaskReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reuseIndentifierHeader) if #available(iOS 11.0, *) { self.collectionView?.contentInsetAdjustmentBehavior = .never self.collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(kNavStatusHeight, 0, 0, 0) } else { self.automaticallyAdjustsScrollViewInsets = false } } @objc func backTo() { self.navigationController?.popViewController(animated: true) } @objc func checkDetail() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let login = storyboard.instantiateViewController(withIdentifier: "HelpVC") as! HelpViewController login.hidesBottomBarWhenPushed = true //let login = TaskViewController() self.navigationController?.pushViewController(login, animated: true) } func setClearNavigationBar(title:String,leftItem:UIView,rightItem:UIView? = nil) -> UIView { let navigiationBar = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kNavStatusHeight)) let backgroudView = UIView(frame: navigiationBar.bounds) let titleView = UILabel(frame: CGRect(x: 80, y: kStatusBarHeight, width: kScreenWidth - 160, height: 44)) titleView.text = title titleView.textColor = UIColor.white titleView.textAlignment = .center titleView.font = UIFont.systemFont(ofSize: 17) leftItem.frame = CGRect(x: 10, y: kStatusBarHeight + 7, width: 30, height: 30) navigiationBar.addSubview(backgroudView) navigiationBar.addSubview(titleView) navigiationBar.addSubview(leftItem) if let right = rightItem { right.frame = CGRect(x: kScreenWidth - 10 - 30, y: kStatusBarHeight + 7, width: 30, height: 30) navigiationBar.addSubview(right) } return navigiationBar } func imageWithColor(_ color:UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.taskVM.taskListEntity.tasks.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! TaskCell let taskEntity = self.taskVM.taskListEntity.tasks[indexPath.item] cell.entity = taskEntity return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reuseIndentifierHeader, for: indexPath) as! TaskReusableView if kind == UICollectionElementKindSectionHeader { reusableView.klLable.text = "\(self.taskVM.taskListEntity.power)" reusableView.powerRecordBlock = { let vc = PowerRecordController() self.navigationController?.pushViewController(vc, animated: true) } reusableView.dayArticleBlock = { let storyboard = UIStoryboard(name: "Smart", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "ArticleVC") as! ArticleListController vc.hidesBottomBarWhenPushed = true vc.type = .tab self.navigationController?.pushViewController(vc, animated: true) } reusableView.dayPaperBlock = { let vc = PaperListController() vc.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } } return reusableView } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let entity = self.taskVM.taskListEntity.tasks[indexPath.item] if entity.finishStatus == 1 { return } switch entity.id { case 3: self.performSegue(withIdentifier: "attention", sender: nil) case 4: self.identifyUserLiveness() case 5: let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "WalletVC") as! MyWalletViewController vc.hidesBottomBarWhenPushed = true vc.urlStr = kHtmlUrl + "createWallet" self.navigationController?.pushViewController(vc, animated: true) case 6: let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "WalletVC") as! MyWalletViewController vc.hidesBottomBarWhenPushed = true vc.urlStr = kHtmlUrl + "exportWallet" self.navigationController?.pushViewController(vc, animated: true) case 7: self.performSegue(withIdentifier: "modifyImage", sender: nil) default: print("未知任务") } } func identifyUserLiveness() { let licenseFile = Bundle.main.path(forResource: FACE_LICENSE_NAME, ofType: FACE_LICENSE_SUFFIX) if let filePath = licenseFile, FileManager.default.fileExists(atPath: filePath) == true { print("liveness = ",FaceSDKManager.sharedInstance().canWork()) FaceSDKManager.sharedInstance().setLicenseID(FACE_LICENSE_ID, andLocalLicenceFile: filePath) } let vc = LivenessViewController() let model = LivingConfigModel() vc.livenesswithList(model.liveActionArray as! [Any]?, order: model.isByOrder, numberOfLiveness: model.numOfLiveness) vc.completion = {(images,image) in guard let imageDict = images else { return } let bestImage = imageDict["bestImage"] as? Array<Any> //let data = Data(base64Encoded: bestImage?.last, options:Data.Base64DecodingOptions.ignoreUnknownCharacters) var data = UIImageJPEGRepresentation(image!, 0.6) if data == nil { data = UIImagePNGRepresentation(image!) } // let imageStr = data?.base64EncodedString(options: .endLineWithLineFeed) let _ = UIImage.insert(image: image!, name: "facePhoto.jpg") self.vm.identifyInfo(param: [:], completion: { (_, msg, isSuc) in ViewManager.showNotice(msg) if isSuc { let _ = UIImage.delete(name: "facePhoto.jpg") self.taskVM.taskList { (_, msg, isSuc) in if isSuc { self.collectionView?.reloadData() } } } self.dismiss(animated: true, completion: {}) }) // // self.vm.ocr(imageStr: imageStr ?? "", completion: { (data, msg, isSuccess) in // // DispatchQueue.main.async(execute: { // var isSucc = false // var tip = "验证分数" // var score = "0" // if isSuccess { // guard // let dict = data as? Dictionary<String,Any> // else{ // return // } // if // let result = dict["result"] as? Dictionary<String,Any>, // let s = result["score"] as? Double{ // score = String(format: "%.4f", s) // if s > 80.0 { // isSucc = true // } // } else if // let i = dict["error_code"] as? Int, let message = dict["error_msg"] as? String{ // // if i == 216600 { // // tip = "身份证号码错误" // // } else if i == 216601 { // // tip = "身份证号码与姓名不匹配" // // } // tip = message // } else { // // } // // } else { // // } // let dict = ["isSucc":isSucc,"tip":tip,"score":score] as [String:Any] // self.performSegue(withIdentifier: "result", sender: dict) // }) // // }) } let nvc = UINavigationController(rootViewController: vc) nvc.isNavigationBarHidden = true self.present(nvc, animated: true, completion: nil) } }
45.851724
202
0.571557
e98419fa0d4d620e0c4febfe6abc252a078198db
7,468
// // NXWebViewController.swift // NXKit // // Created by niegaotao on 2020/5/30. // Copyright © 2020年 TIMESCAPE. All rights reserved. // import UIKit import WebKit open class NXBackbarWrappedView: NXLCRView<NXButton, UIView, NXButton> { open var isAutoable = true override open func setupSubviews() { super.setupSubviews() self.lhsView.frame = CGRect(x: 0, y: 0, width: 32, height: 44) self.lhsView.setImage(NX.image(named:"navi-back.png"), for: .normal) self.lhsView.contentHorizontalAlignment = .left self.centerView.frame = CGRect(x: 32, y: 14, width: NXDevice.pixel, height: 16) self.centerView.backgroundColor = UIColor.black.withAlphaComponent(0.6) self.rhsView.frame = CGRect(x: 33, y: 0, width: 32, height: 44) self.rhsView.setImage(NX.image(named:"navi-close.png"), for: .normal) self.rhsView.contentHorizontalAlignment = .right } open override func updateSubviews(_ action: String, _ value: Any?) { let __isHidden = (value as? Bool) ?? true self.centerView.isHidden = __isHidden self.rhsView.isHidden = __isHidden } } open class NXWebViewController: NXViewController { open var url: String = "" open var html : String = "" open var HTTPMethed : String = "GET" open var cachePolicy = URLRequest.CachePolicy.useProtocolCachePolicy open var timeoutInterval: TimeInterval = 60.0 open var webView = NXWebView(frame: CGRect.zero) open var progressView = UIProgressView(progressViewStyle: .bar) open var backbarView = NXBackbarWrappedView(frame: CGRect(x: 0, y: 0, width: 65, height: 44)) lazy var observer : NXKVOObserver = { return NXKVOObserver(observer: self) }() override open func viewDidLoad() { super.viewDidLoad() self.naviView.title = "加载中..." self.setupSubviews() if url.count > 0 { self.updateSubviews("update", ["url":self.url]) } else if html.count > 0 { if let HTMLURL = Bundle.main.url(forResource: html, withExtension: "") { self.webView.updateSubviews("update", URLRequest(url: HTMLURL)) } } } open override func setupSubviews() { self.webView.attachedViewController = self self.webView.frame = self.contentView.bounds self.webView.backgroundColor = UIColor.white self.webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.observer.add(object:self.webView, key: "title", options: [.new, .old], context: nil, completion: nil) self.observer.add(object:self.webView, key: "estimatedProgress", options: [.new, .old], context: nil, completion: nil) self.webView.callbackWithNavigation = {[weak self](navigation, action, isCompleted, error) -> () in if action == "result" { self?.callbackWithCompletion(isCompleted, error) } } self.webView.callbackWithValue = {[weak self] (value:[String:Any]) in self?.callbackWithValue(value) } self.contentView.addSubview(self.webView) if #available(iOS 11.0, *) { self.webView.scrollView.contentInsetAdjustmentBehavior = .never } self.backbarView.frame = CGRect(x: 0, y: 0, width: 65, height: 44) self.backbarView.lhsView.addTarget(self, action: #selector(onBackAction), for: .touchUpInside) self.backbarView.rhsView.addTarget(self, action: #selector(onCloseAction), for: .touchUpInside) self.backbarView.updateSubviews("", true) self.naviView.backView = backbarView self.naviView.titleView.x = 15.0 + 44.0 + 1.0 self.naviView.titleView.w = self.naviView.w - self.naviView.titleView.x * 2.0 self.progressView.frame = CGRect(x: 0, y: 0, width: self.contentView.frame.size.width, height: self.progressView.frame.size.height) self.progressView.autoresizingMask = [.flexibleWidth] self.progressView.progressTintColor = NX.mainColor self.progressView.trackTintColor = UIColor.clear self.progressView.alpha = 0.0 self.contentView.addSubview(self.progressView) } open override func updateSubviews(_ action: String, _ value: Any?) { guard let value = value as? [String:Any], let _url = value["url"] as? String else { return } if let __url = URL(string: _url) { var HTTPRequest = URLRequest(url: __url) HTTPRequest.httpMethod = self.HTTPMethed HTTPRequest.cachePolicy = self.cachePolicy HTTPRequest.timeoutInterval = self.timeoutInterval HTTPRequest.setValue("no-cache", forHTTPHeaderField: "Cache-Control") //将网页需要的请求头数据在这里添加 //HTTPRequest.setValue("user.id", forHTTPHeaderField: "userid") self.webView.updateSubviews("update", HTTPRequest) } } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let targetView = object as? WKWebView, let accessKey = keyPath else { return } if targetView == self.webView { if accessKey == "title" { self.naviView.title = self.webView.title ?? "" } else if accessKey == "estimatedProgress" { self.progressView.alpha = 1.0 let currentValue : Float = Float(self.webView.estimatedProgress) let isAnimated : Bool = (currentValue > self.progressView.progress) self.progressView.setProgress(currentValue, animated: isAnimated) if currentValue >= 1.0 { UIView.animate(withDuration: 0.3, delay: 0.2, options: [.curveEaseOut], animations: {[weak self] in self?.progressView.alpha = 0.0 }, completion: nil) } } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } @objc open func onBackAction(){ if self.webView.canGoBack { self.webView.goBack() } else{ self.close() } } @objc open func onCloseAction(){ self.close() } open func callbackWithCompletion(_ isCompleted: Bool, _ error:Error?){ NX.log { return "isCompleted = \(isCompleted)"} //在这里做导航栏返回按钮 if isCompleted && self.backbarView.isAutoable { if self.webView.canGoBack { self.backbarView.updateSubviews("", false) self.naviView.titleView.x = 15.0 + 65.0 + 8.0 self.naviView.titleView.w = self.naviView.w - self.naviView.titleView.x * 2.0 } else{ self.backbarView.updateSubviews("", true) self.naviView.titleView.x = 15.0 + 44.0 + 1.0 self.naviView.titleView.w = self.naviView.w - self.naviView.titleView.x * 2.0 } } } open func callbackWithValue(_ value:[String:Any]){ } deinit { self.webView.stopLoading() self.observer.removeAll() } }
38.694301
156
0.601901
1ac94753a5dcc13f7d5ec84af305526ae3a2c8a5
237
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension A { class A { func a { enum b { protocol P { class case ,
18.230769
87
0.738397
61fc08d7b4746bc5a370b27341fb754815e02623
1,457
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2020-2021 Datadog, Inc. */ import Foundation internal struct InternalError: Error, CustomStringConvertible { let description: String } /// Common representation of Swift `Error` used by different features. internal struct DDError { let title: String let message: String let details: String init(error: Error) { if isNSErrorOrItsSubclass(error) { let nsError = error as NSError self.title = "\(nsError.domain) - \(nsError.code)" if nsError.userInfo[NSLocalizedDescriptionKey] != nil { self.message = nsError.localizedDescription } else { self.message = nsError.description } self.details = "\(nsError)" } else { let swiftError = error self.title = "\(type(of: swiftError))" self.message = "\(swiftError)" self.details = "\(swiftError)" } } } private func isNSErrorOrItsSubclass(_ error: Error) -> Bool { var mirror: Mirror? = Mirror(reflecting: error) while mirror != nil { if mirror?.subjectType == NSError.self { return true } mirror = mirror?.superclassMirror } return false }
29.734694
117
0.618394
03bcbd22332830061800a3769e634baa8c422a7e
816
import XCTest class day4_1_tests: XCTestCase { func test_parse_input() { let input = [ "bkwzkqsxq-tovvilokx-nozvyiwoxd-172[fstek]", "wifilzof-wbiwifuny-yhachyylcha-526[qrazx]", ] let expected = [ Room(enc_name: "bkwzkqsxqtovvilokxnozvyiwoxd", sector: 172, checksum: "fstek"), Room(enc_name: "wifilzofwbiwifunyyhachyylcha", sector: 526, checksum: "qrazx"), ] XCTAssertEqual(expected, parse_input(input)); } func test_is_real() { XCTAssertTrue(is_real(Room(enc_name: "aaaaabbbzyx", sector: 123, checksum: "abxyz"))) XCTAssertTrue(is_real(Room(enc_name: "abcdefgh", sector: 987, checksum: "abcde"))) XCTAssertTrue(is_real(Room(enc_name: "notarealroom", sector: 404, checksum: "oarel"))) XCTAssertFalse(is_real(Room(enc_name: "totallyrealroom", sector: 200, checksum: "decoy"))) } }
35.478261
92
0.724265
ed6e070b9cbf769fd28594c2eddc2473fc4debc2
203
import Debugging import Vapor public struct JWTProviderError: Debuggable, AbortError, Error { public let identifier: String public let reason: String public let status: HTTPResponseStatus }
22.555556
63
0.778325
22cba1928da5d1b982176131b01d349f6e9678a9
3,098
// Copyright (c) 2019 Razeware LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, // distribute, sublicense, create a derivative work, and/or sell copies of the // Software in any work that is designed, intended, or marketed for pedagogical or // instructional purposes related to programming, coding, application development, // or information technology. Permission for such use, copying, modification, // merger, publication, distribution, sublicensing, creation of derivative works, // or sale is expressly withheld. // // 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 CryptoKit import Foundation struct SingleSignOnRequest { // MARK: - Properties private let callbackURL: String let secret: String let nonce: String private let endpoint: String var url: URL? { var components = URLComponents(string: endpoint) components?.queryItems = payload return components?.url } // MARK: - Initializers init(endpoint: String, secret: String, callbackURL: String) { self.endpoint = endpoint self.secret = secret self.callbackURL = callbackURL nonce = randomHexString(length: 40) } } // MARK: - Private private extension SingleSignOnRequest { var payload: [URLQueryItem]? { guard let unsignedPayload = unsignedPayload else { return nil } let contents = unsignedPayload.toBase64() let symmetricKey = SymmetricKey(data: Data(secret.utf8)) let signature = HMAC<SHA256>.authenticationCode(for: Data(contents.utf8), using: symmetricKey) .description .replacingOccurrences(of: String.hmacToRemove, with: "") return [ URLQueryItem(name: "sso", value: contents), URLQueryItem(name: "sig", value: signature) ] } var unsignedPayload: String? { var components = URLComponents() components.queryItems = [ URLQueryItem(name: "callback_url", value: callbackURL), URLQueryItem(name: "nonce", value: nonce) ] return components.query } }
36.023256
82
0.717883
d75e43816f2d34fc56d462f5e603b12d0fb47a9a
2,752
// // PaletteChooser.swift // EmojiArt // // Created by Manuel Lorenzo (@noloman) on 02/07/2021. // import SwiftUI struct PaletteChooser: View { var emojiFontSize: CGFloat = 40 var emojiFont: Font { .system(size: emojiFontSize) } @EnvironmentObject var store: PaletteStore @State private var chosenPaletteIndex = 0 @State private var paletteToEdit: Palette? @State private var managing = false var body: some View { HStack { paletteControlButton body(for: store.palette(at: chosenPaletteIndex)) }.clipped() } var paletteControlButton: some View { Button { chosenPaletteIndex = (chosenPaletteIndex + 1) % store.palettes.count } label : { Image(systemName: "paintpalette") } .font(emojiFont) .contextMenu { contextMenu } } @ViewBuilder var contextMenu: some View { AnimatedActionButton(title: "Edit", systemImage: "pencil") { paletteToEdit = store.palette(at: chosenPaletteIndex) } AnimatedActionButton(title: "New", systemImage: "plus") { store.insertPalette(named: "New", emojis: "", at: chosenPaletteIndex) paletteToEdit = store.palette(at: chosenPaletteIndex) } AnimatedActionButton(title: "Delete", systemImage: "minus.circle") { chosenPaletteIndex = store.removePalette(at: chosenPaletteIndex) } AnimatedActionButton(title: "Manage", systemImage: "slider.vertical.3") { managing = true } goToMenu } var goToMenu: some View { Menu { ForEach(store.palettes) { palette in AnimatedActionButton(title: palette.name) { if let index = store.palettes.index(matching: palette) { chosenPaletteIndex = index } } } } label: { Label("Go To", systemImage: "text.insert") } } var rollTransition: AnyTransition { AnyTransition.asymmetric( insertion: .offset(x: 0, y: emojiFontSize), removal: .offset(x: 0, y: -emojiFontSize) ) } func body(for palette: Palette) -> some View { HStack { Text(palette.name) ScrollingEmojisView(emojis: palette.emojis) .font(.system(size: emojiFontSize)) } .id(palette.id) .transition(rollTransition) .popover(item: $paletteToEdit) { palette in PaletteEditor(palette: $store.palettes[palette]) } .sheet(isPresented: $managing) { PaletteManager() } } }
29.913043
81
0.568314
79bbb877de0283137d8d77ac9f4c4ff96421151c
408
/* * Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ import UIKit @UIApplicationMain class AppDelegate: NSObject, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { return true } }
25.5
151
0.72549
fcba0ecbe85273526a803bca548a07d3b794b92b
1,580
// // AppDelegate.swift // todo // // Created by Guillaume LAURES on 10/04/2020. // Copyright © 2020 Baguette Soft. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. configureDependencies() return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } func configureDependencies() { Container.shared.register(protocol: NetworkProvider.self, value: Network()) } }
35.111111
179
0.740506
036b60f867b1d435d875318b2d5dd60988b45b8a
6,505
import UIKit // UICollection View Classes public class KeyCollectionViewCell: UICollectionViewCell { // MARK:- Properties var clearBlurEffectView: UIVisualEffectView? var greenBlurEffectView: UIVisualEffectView? //MARK:- Cell separation override public func draw(_ rect: CGRect) { let cgContext = UIGraphicsGetCurrentContext() cgContext?.move(to: CGPoint(x: rect.minX, y: rect.minY)) cgContext?.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) cgContext?.setStrokeColor(Content.silverColor.cgColor) cgContext?.setLineWidth(4.0) cgContext?.strokePath() } // MARK:- Highlighting public func addBlurEffectViews() { clearBlurEffectView = addBlurEffectView(.clear, alpha: 1.0) greenBlurEffectView = addBlurEffectView(Content.highlightColor, alpha: 0.0) } private func addBlurEffectView(_ color: UIColor?, alpha: CGFloat) -> UIVisualEffectView { let blurEffect = UIBlurEffect(style: .light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.backgroundColor = Content.highlightColor blurEffectView.frame = self.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] blurEffectView.backgroundColor = color blurEffectView.alpha = alpha self.addSubview(blurEffectView) return blurEffectView } public func removeBlurs() { clearBlurEffectView?.removeFromSuperview() greenBlurEffectView?.removeFromSuperview() } } public class TitleCollectionViewCell: UICollectionViewCell { public var title = "" { didSet { titleLabel.text = title } } private lazy var titleLabel: UILabel = { let lbl = UILabel() lbl.font = UIFont(name: "Avenir-Light", size: self.frame.height * 0.5) lbl.textAlignment = .center lbl.textColor = .white return lbl }() // MARK:- Initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.addSubview(titleLabel) titleLabel.translatesAutoresizingMaskIntoConstraints = false activateConstraints() } private func activateConstraints() { NSLayoutConstraint.activate([ titleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor), titleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor), titleLabel.topAnchor.constraint(equalTo: self.topAnchor), titleLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) } } public class DotCollectionViewCell: UICollectionViewCell { public func createDot() { let circle = UIView() circle.backgroundColor = .white circle.translatesAutoresizingMaskIntoConstraints = false self.addSubview(circle) let constant = self.frame.height * 0.2 NSLayoutConstraint.activate([ circle.heightAnchor.constraint(equalToConstant: constant), circle.widthAnchor.constraint(equalToConstant: constant), circle.centerXAnchor.constraint(equalTo: self.centerXAnchor), circle.centerYAnchor.constraint(equalTo: self.centerYAnchor) ]) circle.layer.cornerRadius = constant * 0.5 } } public class ImageCollectionViewCell: UICollectionViewCell { // MARK:- Properties public var imageName = "" { didSet { imageView.image = UIImage(named: imageName) } } private var imageView: UIImageView = { let iv = UIImageView() iv.translatesAutoresizingMaskIntoConstraints = false return iv }() // MARK:- Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override init(frame: CGRect) { super.init(frame: frame) self.addSubview(imageView) activateConstraints() } private func activateConstraints() { NSLayoutConstraint.activate([ imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor), imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor), imageView.topAnchor.constraint(equalTo: self.topAnchor), imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) } } public class ContainerView: UIView { // MARK:- Properties weak var playBtn: UIButton! private lazy var leftDot: UIView = { let view = UIView() setupDot(view) return view }() private lazy var rightDot: UIView = { let view = UIView() setupDot(view) return view }() private func setupDot(_ view: UIView) { view.backgroundColor = .gray view.layer.borderWidth = 2 view.layer.borderColor = UIColor.white.cgColor view.layer.cornerRadius = 15 view.layer.masksToBounds = false view.translatesAutoresizingMaskIntoConstraints = false view.clipsToBounds = true } // MARK:- Constraints func setupLayout(_ playBtn: UIButton) { self.playBtn = playBtn self.addSubview(leftDot) self.addSubview(rightDot) activateConstraints() } private func activateConstraints() { NSLayoutConstraint.activate([ leftDot.trailingAnchor.constraint(equalTo: playBtn.leadingAnchor, constant: 4), leftDot.topAnchor.constraint(equalTo: self.topAnchor), leftDot.bottomAnchor.constraint(equalTo: self.bottomAnchor), leftDot.widthAnchor.constraint(equalTo: leftDot.heightAnchor), rightDot.leadingAnchor.constraint(equalTo: playBtn.trailingAnchor, constant: -4), rightDot.topAnchor.constraint(equalTo: self.topAnchor), rightDot.bottomAnchor.constraint(equalTo: self.bottomAnchor), rightDot.widthAnchor.constraint(equalTo: rightDot.heightAnchor), ]) } // MARK:- Helpful methods func clearAllDots() { for subview in self.subviews { subview.backgroundColor = .gray } } func fillLeftDot() { leftDot.backgroundColor = .green } func fillRightDot() { rightDot.backgroundColor = .green } }
31.731707
93
0.643966
2f4c525b44844ee7b4df7e569562cd5a7e66a0e3
692
// // HomeViewController.swift // demo_Git // // Created by Srinivas on 10/12/18. // Copyright © 2018 Srinivas. All rights reserved. // import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
22.322581
106
0.663295
1a4fd70c083d63478a0d081442681dc991558449
870
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "remove-unused-fluent-icons", platforms: [ .macOS(.v10_13), ], products: [ .executable(name: "remove-unused-fluent-icons", targets: ["remove-unused-fluent-icons"]), ], dependencies: [ .package(url: "https://github.com/apple/swift-argument-parser", from: "0.0.5"), ], targets: [ .target( name: "RemoveUnusedIcons", dependencies: [] ), .testTarget( name: "RemoveUnusedIconsTests", dependencies: ["RemoveUnusedIcons"] ), .target( name: "remove-unused-fluent-icons", dependencies: [ .product(name: "ArgumentParser", package: "swift-argument-parser"), "RemoveUnusedIcons", ] ), ] )
24.857143
96
0.633333
1ed9f36be0d95e4cb07109796c6e9f20bef7e87b
339
// // TimerRepositoryType.swift // SwiftUiCleanArchitecture // // Created by Nikolay Fiantsev on 16.12.2020. // import Foundation import Combine protocol TimerRepositoryType: class { func startTimer() -> AnyPublisher<TimeInterval, Never> } protocol TimerRepositoryHolderType { var timerRepository: TimerRepositoryType { get } }
18.833333
56
0.764012
e0d5466bb345036f46c905db75520468daf23788
7,405
// // AddAccountControllerTests.swift // TempBoxTests // // Created by Waseem Akram on 22/09/21. // import Foundation import XCTest import MailTMSwift @testable import TempBox class AddAccountViewControllerTests: XCTestCase { var peristenceManager: TestPersistenceManager! var mtAccountService: FakeMTAccountService! var mtDomainService: FakeMTDomainService! var accountRepo: FakeAccountRepository! var accountService: AccountService! var sut: AddAccountViewController! override func setUp() { super.setUp() peristenceManager = TestPersistenceManager() accountRepo = FakeAccountRepository() mtDomainService = FakeMTDomainService() mtAccountService = FakeMTAccountService() accountService = AccountService(persistenceManager: peristenceManager, repository: accountRepo, accountService: mtAccountService, domainService: mtDomainService) sut = AddAccountViewController(accountService: accountService) } override func tearDown() { super.tearDown() peristenceManager = nil accountRepo = nil mtDomainService = nil mtAccountService = nil accountService = nil sut = nil } // MARK: - Helper function func getDomain(id: String = UUID().uuidString, domain: String, isActive: Bool, isPrivate: Bool) -> MTDomain { MTDomain(id: id, domain: domain, isActive: isActive, isPrivate: isPrivate, createdAt: .init(), updatedAt: .init()) } func getAccount() -> MTAccount { MTAccount(id: "1230-123-123", address: "[email protected]", quotaLimit: 0, quotaUsed: 100, isDisabled: false, isDeleted: false, createdAt: .init(), updatedAt: .init()) } // MARK: - Init tests cases func test_init_whenSuccessfullyRetreivedDomain_setsInitialProperties() { XCTAssertFalse(sut.isDomainsLoading) XCTAssertEqual(sut.availableDomains.count, 1) XCTAssertTrue(sut.selectedDomain != "") } // MARK: - Other tests cases func test_addressText_whenAddressEntered_convertsToLowerCase() { let givenAddress = "123abcDEF" sut.addressText = givenAddress XCTAssertEqual(sut.addressText, "123abcdef") } func test_canCreate_whenValidSituation_returnsTrue() { // when sut.selectedDomain = "example.com" sut.addressText = "12345" sut.shouldGenerateRandomPassword = true // then XCTAssertTrue(sut.canCreate, "isCreateButtonEnabled should be true") } func test_generateRandomAddress_assignsRandomAddress() { XCTAssertEqual(sut.addressText, "") // when sut.generateRandomAddress() // then XCTAssertNotEqual(sut.addressText, "") XCTAssertEqual(sut.addressText.count, 10) } func test_isPasswordValid_shouldReturnTrueForValidPassword() { // when sut.shouldGenerateRandomPassword = false sut.passwordText = "123456" // then XCTAssertTrue(sut.isPasswordValid, "isPassword should be True") } func test_isPasswordValid_shouldReturnFalseForInValidPassword() { // when sut.shouldGenerateRandomPassword = false sut.passwordText = "12" // then XCTAssertFalse(sut.isPasswordValid, "isPassword should be False") } func test_createNewAddress_whenRandomPassword_createsAccountAndClosesWindow() { // given sut.selectedDomain = "example.com" sut.addressText = "12345" sut.shouldGenerateRandomPassword = true // when XCTAssertTrue(sut.canCreate) sut.createNewAddress() // then XCTAssertNil(sut.alertMessage) XCTAssertFalse(sut.isAddAccountWindowOpen) } func test_createNewAddress_whenManualPassword_createsAccountAndClosesWindow() { // given sut.selectedDomain = "example.com" sut.addressText = "12345" sut.passwordText = "123456" sut.shouldGenerateRandomPassword = false // when XCTAssertTrue(sut.canCreate) sut.createNewAddress() // then XCTAssertNil(sut.alertMessage) XCTAssertFalse(sut.isAddAccountWindowOpen) } func test_createNewAddress_whenCanCreateIsFalse_doNothing() { sut.createNewAddress() XCTAssertFalse(sut.canCreate) } func test_createNewAddress_whenAddressAlreadyExists_setsErrorMessage() { // given let givenAddressAlreadyExistsMessage = "address: This value is already used." sut.isAddAccountWindowOpen = true sut.selectedDomain = "example.com" sut.addressText = "12345" sut.shouldGenerateRandomPassword = true mtAccountService.error = .mtError(givenAddressAlreadyExistsMessage) mtAccountService.accounts = [ getAccount(), MTAccount(id: "123", address: "[email protected]", quotaLimit: 100, quotaUsed: 0, isDisabled: false, isDeleted: false, createdAt: .init(), updatedAt: .init()) ] XCTAssertTrue(sut.canCreate) sut.createNewAddress() XCTAssertFalse(sut.isCreatingAccount) XCTAssertNotNil(sut.alertMessage) XCTAssertEqual(sut.alertMessage?.title, "This address already exists! Please choose a different address") XCTAssertTrue(sut.isAddAccountWindowOpen, "The window is closed. The window should stay open if an error is occured") } func test_createNewAddress_whenServerReturnsError_setsErrorMessage() { // given let givenErrorMessage = "Test Error: Server Error" sut.isAddAccountWindowOpen = true sut.selectedDomain = "example.com" sut.addressText = "12345" sut.shouldGenerateRandomPassword = true mtAccountService.error = .mtError(givenErrorMessage) mtAccountService.forceError = true sut.createNewAddress() XCTAssertFalse(sut.isCreatingAccount) XCTAssertNotNil(sut.alertMessage) XCTAssertEqual(sut.alertMessage?.title, givenErrorMessage) XCTAssertTrue(sut.isAddAccountWindowOpen, "The window is closed. The window should stay open if an error is occured") } func test_createNewAddress_whenNetworkOrOtherError_setsCustomErrorMessage() { let givenErrorMessage = "Test Error: Server Error" sut.isAddAccountWindowOpen = true sut.selectedDomain = "example.com" sut.addressText = "12345" sut.shouldGenerateRandomPassword = true mtAccountService.error = .networkError(givenErrorMessage) mtAccountService.forceError = true sut.createNewAddress() XCTAssertFalse(sut.isCreatingAccount) XCTAssertNotNil(sut.alertMessage) XCTAssertEqual(sut.alertMessage?.title, "Something went wrong while creating a new address") XCTAssertTrue(sut.isAddAccountWindowOpen, "The window is closed. The window should stay open if an error is occured") } }
33.506787
125
0.6474
202638114552f1c80dd515196651040789c4a761
4,549
// // DiscoverCreditCardFormatTests.swift // CreditCardFormatterTests // // Created by barbarity on 14/12/2019. // Copyright (c) 2019 Barbarity Apps // // 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 CreditCardFormatter import XCTest final class DiscoverCreditCardFormatTests: XCTestCase { private var sut: DiscoverCreditCardFormat! private let nonDiscoverCards: [String] = [ "4844454142127365", "3538684728624673", "5168441223630339", "5080741549588144561", "3529348020648944" ] private let invalidCheckDigitCards: [String] = [ "6011790961194351", "6011790961194352", "6011790961194353", "6011790961194355", "6011790961194356", "6011790961194357", "6011790961194358", "6011790961194359" ] private let invalidCheckDigitCardsFormatted: [String] = [ "6011 7909 6119 4351", "6011 7909 6119 4352", "6011 7909 6119 4353", "6011 7909 6119 4355", "6011 7909 6119 4356", "6011 7909 6119 4357", "6011 7909 6119 4358", "6011 7909 6119 4359" ] private let validCreditCards = [ "6011790961194354", "6011792456358809", "6011983134104166839", "6011989994603890", "6011635959685097", "6445678975565584" ] private let validCreditCardsFormatted = [ "6011 7909 6119 4354", "6011 7924 5635 8809", "6011 9831 3410 4166 839", "6011 9899 9460 3890", "6011 6359 5968 5097", "6445 6789 7556 5584" ] private let shortCreditCards = [ "60117909611943 ", "60117924563588", "601198313410", "60119899946", "601163595", "644567" ] override func setUp() { super.setUp() sut = DiscoverCreditCardFormat() } override func tearDown() { sut = nil super.tearDown() } func testDiscoverBrandIsCorrect() { XCTAssert(sut.brand == CreditCardBrands.discover) } func testNonDiscoverCreditCardsAreInvalid() { nonDiscoverCards.forEach { XCTAssertFalse(sut.isValid($0)) } } func testNonDiscoverCardsShouldntBeFormatted() { nonDiscoverCards.forEach { XCTAssertFalse(sut.shouldFormat($0)) } } func testDiscoverCardsWithWrongCheckDigitAreInvalid() { invalidCheckDigitCards.forEach { XCTAssertFalse(sut.isValid($0)) } } func testDiscoverCardsWithWrongCheckDigitShouldFormat() { invalidCheckDigitCards.forEach { XCTAssert(sut.shouldFormat($0)) } } func testDiscoverCardsWithWrongCheckDigitFormat() { for (formattedCard, card) in zip(invalidCheckDigitCardsFormatted, invalidCheckDigitCards) { XCTAssert(formattedCard == sut.formattedString(from: card, delimiter: " ")) } } // MARK: Valid Credit Cards func testCorrectDiscoverCardsShouldFormat() { validCreditCards.forEach { XCTAssert(sut.shouldFormat($0)) } } func testCorrectDiscoverCardsAreValid() { validCreditCards.forEach { XCTAssert(sut.isValid($0)) } } // MARK: Short Credit Cards func testShortCreditCardsShouldFormat() { shortCreditCards.forEach { XCTAssert(sut.shouldFormat($0)) } } func testShortCreditCardsAreInvalid() { shortCreditCards.forEach { XCTAssertFalse(sut.isValid($0)) } } }
31.157534
99
0.655309
23b974ee4c6ce5fd3afc4e74c2a02277c9dcdd3c
2,413
// // ClientHander.swift // GameServer // // Created by Nguyen Dung on 9/30/16. // // import Dispatch import Foundation import Socks class ClientHander: NSObject { private var client : TCPClient! private var close : Bool = false private var ClientMessage : Array<Array<UInt8>>! var uuid : String! convenience init(client : TCPClient) { self.init() self.client = client self.uuid = UUID().uuidString self.ClientMessage = Array<Array<UInt8>>() print("Client: \(self.client.socket.address)") DispatchQueue(label: "\(self.client.ipAddress()) : \(self.client.socket.address.port) : receive").async { while !self.close{ do{ let data = try self.client.receiveAll() if(data.count == 0){ print("Client disconnect and remove form connect list") self.close = true }else{ self.ClientMessage.append(data) if(data.count == 61){ DispatchQueue.main.async { //Timer.scheduledTimer(timeInterval: 45, target: self, selector: #selector(ClientHander.onSendTest), userInfo: nil, repeats: true) self.sendMessage(msg: "DONE"); } } } }catch{ print(error) self.close = true } } do{ try self.client.close() GSShare.sharedInstance.removeClient(client: self) }catch{ print(error) } } } deinit { self.client = nil self.uuid = nil self.ClientMessage = nil print("REMOVE CLASS") } func onSendTest(){ print("Send Test Message") self.sendMessage(msg: "test \n") } func sendMessage(msg : String){ sendMessage(data: msg.data(using: String.Encoding.utf8)!) } func sendMessage(data : Data){ sendMessage(data: data.bytes) } func sendMessage(bytes : [UInt8]){ do{ try self.client.send(bytes: Data) }catch{ print(error) } } }
28.388235
162
0.479486
bf89f57f6d3bea81410625ed47c38151fe692322
8,833
// // RxAppState_ExampleTests.swift // RxAppState_ExampleTests // // Created by Jörn Schoppe on 19.03.16. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest import RxSwift import RxCocoa @testable import RxAppState_Example @testable import RxAppState class RxAppStateTests: XCTestCase { fileprivate var isFirstLaunchKey:String { return "RxAppState_isFirstLaunch" } fileprivate var firstLaunchOnlyKey:String { return "RxAppState_firstLaunchOnly" } fileprivate var numDidOpenAppKey:String { return "RxAppState_numDidOpenApp" } fileprivate var lastAppVersionKey: String { return "RxAppState_lastAppVersion" } let application = UIApplication.shared var disposeBag = DisposeBag() override func tearDown() { super.tearDown() let userDefaults = UserDefaults.standard userDefaults.removeObject(forKey: isFirstLaunchKey) userDefaults.removeObject(forKey: firstLaunchOnlyKey) userDefaults.removeObject(forKey: numDidOpenAppKey) userDefaults.removeObject(forKey: lastAppVersionKey) RxAppState.clearSharedObservables() disposeBag = DisposeBag() } func testAppStates() { // Given var appStates: [AppState] = [] application.rx.appState .subscribe(onNext: { appState in appStates.append(appState) }) .disposed(by: disposeBag) // When application.delegate?.applicationDidBecomeActive!(application) application.delegate?.applicationWillResignActive!(application) application.delegate?.applicationDidEnterBackground!(application) application.delegate?.applicationWillTerminate!(application) // Then XCTAssertEqual(appStates, [AppState.active, AppState.inactive, AppState.background, AppState.terminated]) } func testDidOpenApp() { // Given var didOpenAppCalledCount = 0 application.rx.didOpenApp .subscribe(onNext: { _ in didOpenAppCalledCount += 1 }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(didOpenAppCalledCount, 3) } func testDidOpenAppCount() { // Given var didOpenAppCounts: [Int] = [] application.rx.didOpenAppCount .subscribe(onNext: { count in didOpenAppCounts.append(count) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(didOpenAppCounts, [1,2,3]) } func testIsFirstLaunch() { // Given var firstLaunchArray: [Bool] = [] application.rx.isFirstLaunch .subscribe(onNext: { isFirstLaunch in firstLaunchArray.append(isFirstLaunch) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(firstLaunchArray, [true, false, false]) } func testFirstLaunchOnly() { // Given var firstLaunchArray: [Bool] = [] application.rx.firstLaunchOnly .subscribe(onNext: { _ in firstLaunchArray.append(true) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(firstLaunchArray, [true]) // And XCTAssertEqual(UserDefaults.standard.bool(forKey: self.isFirstLaunchKey), true) } func testIsFirstLaunchOfNewVersionNewInstall() { // Given var firstLaunchArray: [Bool] = [] application.rx.isFirstLaunchOfNewVersion .subscribe(onNext: { isFirstLaunchOfNewVersion in firstLaunchArray.append(isFirstLaunchOfNewVersion) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(firstLaunchArray, [false, false, false]) } func testIsFirstLaunchOfNewVersionUpdate() { // Given var firstLaunchArray: [Bool] = [] UserDefaults.standard.set("3.2", forKey: self.lastAppVersionKey) UserDefaults.standard.synchronize() RxAppState.currentAppVersion = "4.2" application.rx.isFirstLaunchOfNewVersion .subscribe(onNext: { isFirstLaunchOfNewVersion in firstLaunchArray.append(isFirstLaunchOfNewVersion) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(firstLaunchArray, [true, false, false]) } func testIsFirstLaunchOfNewVersionUpdateMultipleSubscription() { // Given var firstLaunchArray: [Bool] = [] var anotherFirstLaunchArray: [Bool] = [] UserDefaults.standard.set("3.2", forKey: self.lastAppVersionKey) UserDefaults.standard.synchronize() RxAppState.currentAppVersion = "4.2" application.rx.isFirstLaunchOfNewVersion .subscribe(onNext: { isFirstLaunchOfNewVersion in firstLaunchArray.append(isFirstLaunchOfNewVersion) }) .disposed(by: disposeBag) application.rx.isFirstLaunchOfNewVersion .subscribe(onNext: { isFirstLaunchOfNewVersion in anotherFirstLaunchArray.append(isFirstLaunchOfNewVersion) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(firstLaunchArray, [true, false, false]) XCTAssertEqual(anotherFirstLaunchArray, [true, false, false]) } func testIsFirstLaunchOfNewVersionExisting() { // Given var firstLaunchArray: [Bool] = [] UserDefaults.standard.set("4.2", forKey: self.lastAppVersionKey) UserDefaults.standard.synchronize() RxAppState.currentAppVersion = "4.2" application.rx.isFirstLaunchOfNewVersion .subscribe(onNext: { isFirstLaunchOfNewVersion in firstLaunchArray.append(isFirstLaunchOfNewVersion) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(firstLaunchArray, [false, false, false]) } func testFirstLaunchOfNewVersionOnlyNewInstall() { // Given var firstLaunchArray: [Bool] = [] application.rx.firstLaunchOfNewVersionOnly .subscribe(onNext: { _ in firstLaunchArray.append(true) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(firstLaunchArray, []) } func testFirstLaunchOfNewVersionOnlyNewUpdate() { // Given var firstLaunchArray: [Bool] = [] UserDefaults.standard.set("3.2", forKey: self.lastAppVersionKey) UserDefaults.standard.synchronize() RxAppState.currentAppVersion = "4.2" application.rx.firstLaunchOfNewVersionOnly .subscribe(onNext: { _ in firstLaunchArray.append(true) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(firstLaunchArray, [true]) // And XCTAssertEqual(UserDefaults.standard.string(forKey: self.lastAppVersionKey), "4.2") } func testFirstLaunchOfNewVersionOnlyExisting() { // Given var firstLaunchArray: [Bool] = [] UserDefaults.standard.set("4.2", forKey: self.lastAppVersionKey) UserDefaults.standard.synchronize() RxAppState.currentAppVersion = "4.2" application.rx.firstLaunchOfNewVersionOnly .subscribe(onNext: { _ in firstLaunchArray.append(true) }) .disposed(by: disposeBag) // When runAppStateSequence() // Then XCTAssertEqual(firstLaunchArray, []) } func runAppStateSequence() { application.delegate?.applicationDidBecomeActive!(application) application.delegate?.applicationWillResignActive!(application) application.delegate?.applicationDidBecomeActive!(application) application.delegate?.applicationDidEnterBackground!(application) application.delegate?.applicationDidBecomeActive!(application) application.delegate?.applicationDidEnterBackground!(application) application.delegate?.applicationDidBecomeActive!(application) } }
32.12
113
0.610891
cc87c296b09d346ee31a71a6b8f0f35c8699a09a
1,358
// // RecommendController.swift // DemoDirectory // // Created by Vladislav Fitc on 24/03/2022. // Copyright © 2022 Algolia. All rights reserved. // import Foundation import UIKit import AlgoliaSearchClient class RecommendController { let recommendClient: RecommendClient init(recommendClient: RecommendClient) { self.recommendClient = recommendClient } func presentRelatedItems(for objectID: ObjectID, from sourceViewController: UIViewController, animated: Bool = true) { recommendClient.getRelatedProducts(options: [.init(indexName: .recommend, objectID: objectID)]) { result in DispatchQueue.main.async { switch result { case .failure(let error): let alertController = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .cancel)) sourceViewController.present(alertController, animated: animated) case .success(let response): let viewController = StoreItemsTableViewController.with(response.results.first!) viewController.title = "Related items" let navigationController = UINavigationController(rootViewController: viewController) sourceViewController.present(navigationController, animated: animated) } } } } }
33.121951
120
0.715758
75f585a036c7ba81af8296d616912f00e5860c97
10,578
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSPluginsCore class GraphQLRequestAnyModelWithSyncTests: XCTestCase { override func setUp() { ModelRegistry.register(modelType: Comment.self) ModelRegistry.register(modelType: Post.self) } override func tearDown() { ModelRegistry.reset() } func testQueryGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(id: post.id)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ query GetPost($id: ID!) { getPost(id: $id) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult?>.query(modelName: post.modelName, byId: post.id) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult?.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } XCTAssertEqual(variables["id"] as? String, post.id) } func testCreateMutationGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: ModelDecorator(model: post)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult>.createMutation(of: post, modelSchema: post.schema) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } guard let input = variables["input"] as? [String: Any] else { XCTFail("The document variables property doesn't contain a valid input") return } XCTAssert(input["title"] as? String == post.title) XCTAssert(input["content"] as? String == post.content) } func testUpdateMutationGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: ModelDecorator(model: post)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ mutation UpdatePost($input: UpdatePostInput!) { updatePost(input: $input) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult>.updateMutation(of: post, modelSchema: post.schema) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } guard let input = variables["input"] as? [String: Any] else { XCTFail("The document variables property doesn't contain a valid input") return } XCTAssert(input["title"] as? String == post.title) XCTAssert(input["content"] as? String == post.content) } func testDeleteMutationGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: ModelIdDecorator(id: post.id)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ mutation DeletePost($input: DeletePostInput!) { deletePost(input: $input) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult>.deleteMutation(modelName: post.modelName, id: post.id) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } guard let input = variables["input"] as? [String: Any] else { XCTFail("The document variables property doesn't contain a valid input") return } XCTAssertEqual(input["id"] as? String, post.id) } func testCreateSubscriptionGraphQLRequest() throws { let modelType = Post.self as Model.Type var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .subscription) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ subscription OnCreatePost { onCreatePost { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult>.subscription(to: modelType.schema, subscriptionType: .onCreate) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) XCTAssertNil(request.variables) } func testSyncQueryGraphQLRequest() throws { let modelType = Post.self as Model.Type let nextToken = "nextToken" let limit = 100 let lastSync = 123 var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator(limit: limit, nextToken: nextToken)) documentBuilder.add(decorator: ConflictResolutionDecorator(lastSync: lastSync)) let document = documentBuilder.build() let documentStringValue = """ query SyncPosts($lastSync: AWSTimestamp, $limit: Int, $nextToken: String) { syncPosts(lastSync: $lastSync, limit: $limit, nextToken: $nextToken) { items { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } nextToken startedAt } } """ let request = GraphQLRequest<SyncQueryResult>.syncQuery(modelSchema: modelType.schema, limit: limit, nextToken: nextToken, lastSync: lastSync) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == SyncQueryResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } XCTAssertNotNil(variables["limit"]) XCTAssertEqual(variables["limit"] as? Int, limit) XCTAssertNotNil(variables["nextToken"]) XCTAssertEqual(variables["nextToken"] as? String, nextToken) XCTAssertNotNil(variables["lastSync"]) XCTAssertEqual(variables["lastSync"] as? Int, lastSync) } }
38.05036
116
0.594063
abecba301c458fb4bbc77ef86ee6d87f6468aa69
11,819
// // AppleSpeechRecognizer.swift // Spokestack // // Created by Cory D. Wiles on 1/10/19. // Copyright © 2020 Spokestack, Inc. All rights reserved. // import Foundation import Speech /** This pipeline component uses the Apple `SFSpeech` API to stream audio samples for speech recognition. Once speech pipeline coordination via `startStreaming` is received, the recognizer begins streaming buffered frames to the Apple ASR API for recognition. Once speech pipeline coordination via `stopStreaming` is received, or when the Apple ASR API indicates a completed speech event, the recognizer completes the API request and either sends a `timeout` or `didRecognize` event with the updated global speech context (including the speech transcript and confidence). */ @objc public class AppleSpeechRecognizer: NSObject { // MARK: Public properties /// Configuration for the recognizer. @objc public var configuration: SpeechConfiguration /// Global state for the speech pipeline. @objc public var context: SpeechContext /// Streaming start and stop involve the retention and releasing of external resources, which creates potential race conditions if done rapidly or during a dleay from the external resources. This semaphore allows for operations to complete (or timeout) before attempting to retain/release. internal let recognizingSemaphore = DispatchSemaphore(value: 1) // MARK: Private properties private let speechRecognizer: SFSpeechRecognizer = SFSpeechRecognizer(locale: NSLocale.current)! private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? private var recognitionTask: SFSpeechRecognitionTask? private let audioEngine: AVAudioEngine = AVAudioEngine() private var vadFallWorker: DispatchWorkItem? private var wakeActiveMaxWorker: DispatchWorkItem? private var isActive = false // MARK: NSObject implementation deinit { if recognizingSemaphore.wait(timeout: .now() + self.configuration.semaphoreTimeout) == .timedOut { self.context.dispatch { $0.failure(error: SpeechPipelineError.illegalState("Could not start recognizer, timed out waiting on another thread.")) } } defer { recognizingSemaphore.signal() } self.audioEngine.stop() self.audioEngine.inputNode.removeTap(onBus: 0) speechRecognizer.delegate = nil } /// Initializes a AppleSpeechRecognizer instance. /// /// A recognizer is initialized by, and receives `startStreaming` and `stopStreaming` events from, an instance of `SpeechPipeline`. /// /// The AppleSpeechRecognizer receives audio data frames to `process` from a tap into the system `AudioEngine`. /// - Parameters: /// - configuration: Configuration for the recognizer. /// - context: Global state for the speech pipeline. @objc public init(_ configuration: SpeechConfiguration, context: SpeechContext) { self.configuration = configuration self.context = context super.init() } // MARK: Private functions private func prepare() { if recognizingSemaphore.wait(timeout: .now() + self.configuration.semaphoreTimeout) == .timedOut { self.context.dispatch { $0.failure(error: SpeechPipelineError.illegalState("Could not start recognizer, timed out waiting on another thread.")) } return } defer { recognizingSemaphore.signal() } self.audioEngine.inputNode.removeTap(onBus: 0) // a belt-and-suspenders approach to fixing https://github.com/wenkesj/react-native-voice/issues/46 self.audioEngine.inputNode.installTap( onBus: 0, bufferSize: AVAudioFrameCount(self.configuration.audioEngineBufferSize), format: self.audioEngine.inputNode.inputFormat(forBus: 0)) {[weak self] buffer, when in guard let strongSelf = self else { return } strongSelf.recognitionRequest?.append(buffer) } self.audioEngine.prepare() self.wakeActiveMaxWorker = DispatchWorkItem {[weak self] in self?.context.dispatch { $0.didTimeout?() } self?.deactivate() } } private func activate() { if recognizingSemaphore.wait(timeout: .now() + self.configuration.semaphoreTimeout) == .timedOut { self.context.dispatch { $0.failure(error: SpeechPipelineError.illegalState("Could not start recognizer, timed out waiting on another thread.")) } return } defer { recognizingSemaphore.signal() } do { // Accessing debug information is costly and we don't want to do it unnecessarily, so make a duplicate level check beforehand. if self.configuration.tracing.rawValue <= Trace.Level.DEBUG.rawValue { Trace.trace(.DEBUG, message: "inputSampleRate: \(self.audioEngine.inputNode.inputFormat(forBus: 0).sampleRate) inputChannels: \(self.audioEngine.inputNode.inputFormat(forBus: 0).channelCount) bufferSize \(self.configuration.audioEngineBufferSize)", config: self.configuration, context: self.context, caller: self) } try self.audioEngine.start() self.recognitionRequest = SFSpeechAudioBufferRecognitionRequest() self.recognitionRequest?.shouldReportPartialResults = true try self.createRecognitionTask() self.isActive = true // Automatically end recognition task if it goes over the activiation max DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .milliseconds(self.configuration.wakeActiveMax), execute: self.wakeActiveMaxWorker!) } catch let error { self.context.dispatch { $0.failure(error: error) } } } private func deactivate() { if recognizingSemaphore.wait(timeout: .now() + self.configuration.semaphoreTimeout) == .timedOut { self.context.dispatch { $0.failure(error: SpeechPipelineError.illegalState("Could not start recognizer, timed out waiting on another thread.")) } return } defer { recognizingSemaphore.signal() } if self.isActive { self.isActive = false self.context.isActive = false self.vadFallWorker?.cancel() self.wakeActiveMaxWorker?.cancel() self.recognitionTask?.finish() self.recognitionTask = nil self.recognitionRequest?.endAudio() self.recognitionRequest = nil self.audioEngine.stop() self.context.dispatch { $0.didDeactivate?() } } } private func createRecognitionTask() throws -> Void { self.recognitionTask = self.speechRecognizer.recognitionTask( with: recognitionRequest!, resultHandler: { [weak self] result, error in guard let strongSelf = self else { // the callback has been orphaned by stopStreaming, so just end things here. return } if !strongSelf.isActive { return } strongSelf.vadFallWorker?.cancel() strongSelf.vadFallWorker = nil if let e = error { if let nse: NSError = error as NSError? { if nse.domain == "kAFAssistantErrorDomain" { switch nse.code { case 0..<200: // Apple retry error: https://developer.nuance.com/public/Help/DragonMobileSDKReference_iOS/Error-codes.html break case 203: // request timed out, retry Trace.trace(Trace.Level.INFO, message: "resultHandler error 203", config: strongSelf.configuration, context: strongSelf.context, caller: strongSelf) strongSelf.deactivate() break case 209: // ¯\_(ツ)_/¯ Trace.trace(Trace.Level.INFO, message: "resultHandler error 209", config: strongSelf.configuration, context: strongSelf.context, caller: strongSelf) break case 216: // Apple internal error: https://stackoverflow.com/questions/53037789/sfspeechrecognizer-216-error-with-multiple-requests?noredirect=1&lq=1) Trace.trace(Trace.Level.INFO, message: "resultHandler error 216", config: strongSelf.configuration, context: strongSelf.context, caller: strongSelf) break case 300..<603: // Apple retry error: https://developer.nuance.com/public/Help/DragonMobileSDKReference_iOS/Error-codes.html break default: strongSelf.context.dispatch { $0.failure(error: e) } } } } else { strongSelf.context.dispatch { $0.failure(error: e) } } } if let r = result { Trace.trace(Trace.Level.DEBUG, message: "recognized \(r.bestTranscription.formattedString)", config: strongSelf.configuration, context: strongSelf.context, caller: strongSelf) strongSelf.wakeActiveMaxWorker?.cancel() let confidence = r.transcriptions.first?.segments.sorted( by: { (a, b) -> Bool in a.confidence <= b.confidence }).first?.confidence ?? 0.0 strongSelf.context.transcript = r.bestTranscription.formattedString strongSelf.context.confidence = confidence strongSelf.context.dispatch { $0.didRecognizePartial?(strongSelf.context)} strongSelf.vadFallWorker = DispatchWorkItem {[weak self] in self?.context.dispatch { $0.didRecognize?(strongSelf.context) } self?.deactivate() } DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .milliseconds(strongSelf.configuration.vadFallDelay), execute: strongSelf.vadFallWorker!) } } ) } } extension AppleSpeechRecognizer: SpeechProcessor { /// Triggered by the speech pipeline, instructing the recognizer to begin streaming and processing audio. @objc public func startStreaming() { } /// Triggered by the speech pipeline, instructing the recognizer to stop streaming audio and complete processing. @objc public func stopStreaming() { if self.isActive { self.deactivate() self.recognitionTask?.cancel() self.recognitionTask = nil self.recognitionRequest?.endAudio() self.recognitionRequest = nil } } /// Processes an audio frame, recognizing speech. /// - Note: Processes audio in an async thread. /// - Remark: The Apple ASR hooks up directly to its own audio tap for processing audio frames. When the `AudioController` calls this `process`, it checks to see if the pipeline is activated, and if so kicks off its own VAD and ASR independently of any other components in the speech pipeline. /// - Parameter frame: Audio frame of samples. @objc public func process(_ frame: Data) { if self.context.isActive { if !self.isActive { self.prepare() self.activate() } } else if self.isActive { self.deactivate() } } }
52.29646
466
0.627295
efee5adc92ce5ca944dbcaf4834b83f7b4c49843
3,305
// // YourAccountTableView.swift // YC // // Created by VeveCorp on 7/13/16. // Copyright © 2016 VeveCorp. All rights reserved. // import UIKit import IBAnimatable import DropDown class PostHaverest : UITableViewCell { @IBOutlet weak var question: AnimatableLabel! @IBOutlet weak var food_drop_down_menu: AnimatableButton! @IBOutlet weak var post_window: UIView! let dropDown = DropDown() // The view to which the drop down will appear on override func awakeFromNib() { super.awakeFromNib() // Initialization code dropDown.anchorView = post_window dropDown.dataSource = ["Tomatoes", "Apple", "Apricot", "Avocado", "Banana", "Bilberry", "Blackberry", "Blackcurrant", "Blueberry", "Boysenberry", "Buddha's hand", "Crab apples", "Currant", "Cherry", "Cherimoya", "Chico fruit", "Cloudberry", "Coconut", "Cranberry", "Cucumber", "Custard apple", "Damson", "Date", "Dragonfruit", "Durian", "Elderberry", "Feijoa", "Fig", "Goji berry", "Gooseberry", "Grape"] // Action triggered on selection dropDown.selectionAction = { [unowned self] (index: Int, item: String) in print("Selected item: \(item) at index: \(index)") self.dropDown.hide() } self.dropDown.show() self.dropDown.width = 20 } // The list of items to display. Can be changed dynamically // Will set a custom width instead of the anchor view width override func prepareForReuse() { } } class FoodBank_Table_cell: UITableViewCell { @IBOutlet weak var logo: UIImageView! @IBOutlet weak var icon1: UIImageView! @IBOutlet weak var icon2: UIImageView! @IBOutlet weak var icon3: UIImageView! @IBOutlet weak var companyname: UILabel! @IBOutlet weak var detailview: UIButton! override func awakeFromNib() { } override func prepareForReuse() { } } class Garden_Table_cell: UITableViewCell { @IBOutlet weak var logo: UIImageView! @IBOutlet weak var icon1: UIImageView! @IBOutlet weak var icon2: UIImageView! @IBOutlet weak var icon3: UIImageView! @IBOutlet weak var companyname: UILabel! @IBOutlet weak var detailview: UIButton! override func awakeFromNib() { } override func prepareForReuse() { } }
28.008475
81
0.465053
f5704da64e089bb147545f79ceb2e48ff4fcfa87
1,365
import XCTest import class Foundation.Bundle final class hiTests: XCTestCase { func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. // Some of the APIs that we use below are available in macOS 10.13 and above. guard #available(macOS 10.13, *) else { return } let fooBinary = productsDirectory.appendingPathComponent("hi") let process = Process() process.executableURL = fooBinary let pipe = Pipe() process.standardOutput = pipe try process.run() process.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: .utf8) XCTAssertEqual(output, "Hello, world!\n") } /// Returns path to the built products directory. var productsDirectory: URL { #if os(macOS) for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") { return bundle.bundleURL.deletingLastPathComponent() } fatalError("couldn't find the products directory") #else return Bundle.main.bundleURL #endif } static var allTests = [ ("testExample", testExample), ] }
28.4375
87
0.632234
61a628358939da9649b156d5cd1c93c4338accea
1,406
// // OP_TUCK.swift // // Copyright © 2018 BitcoinKit developers // // 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 // The item at the top of the stack is copied and inserted before the second-to-top item. public struct OpTuck: OpCodeProtocol { public var value: UInt8 { return 0x7d } public var name: String { return "OP_TUCK" } }
42.606061
89
0.745377
9b24e5ec07e9278873846a2e0c7136f24f491b64
811
// // AnchorViewModel.swift // Live // // Created by lieon on 2017/7/11. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // swiftlint:disable variable_name import Foundation import PromiseKit class AnchorViewModel { lazy var anchorInfo: AnchorDetail = AnchorDetail() /// 主播信息 func requestAnchorDetail(with id: Int) -> Promise<Bool> { AnchorRequestParm.anchorId = id let req: Promise<AnchorDetailResponse> = RequestManager.request(.endpoint(AnchorPath.getInfo, param: nil), needToken: .true) return req.then { [unowned self] (response) -> Bool in if let object = response.object, let userInfo = object.result { self.anchorInfo = userInfo return true } return false } } }
28.964286
132
0.639951
64335cd56176410ce47fcbef090ac87f27914709
16,757
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest import SQLite import Combine @testable import Amplify @testable import AmplifyTestCommon @testable import AWSPluginsCore @testable import AWSDataStoreCategoryPlugin class OutgoingMutationQueueNetworkTests: SyncEngineTestBase { var cancellables: Set<AnyCancellable>! var reachabilitySubject: CurrentValueSubject<ReachabilityUpdate, Never>! let dbFile: URL = { let tempDir = FileManager.default.temporaryDirectory let dbName = "OutgoingMutationQueueNetworkTests.db" let dbFile = tempDir.appendingPathComponent(dbName) return dbFile }() func getDBConnection(inMemory: Bool) throws -> Connection { if inMemory { return try Connection(.inMemory) } else { return try Connection(dbFile.path) } } let connectionError: APIError = { APIError.networkError( "TEST: Network not available", nil, URLError(.notConnectedToInternet) ) }() override func setUpWithError() throws { cancellables = [] // For this test, we want the network to be initially available. We'll set it to unavailable // later in the test to simulate a loss of connectivity after the initial create mutation. reachabilitySubject = CurrentValueSubject(ReachabilityUpdate(isOnline: true)) reachabilityPublisher = reachabilitySubject.eraseToAnyPublisher() try super.setUpWithError() // Ignore failures -- we don't care if the file didn't exist prior to this test, and if // it can't write, the tests will fail elsewhere try? FileManager.default.removeItem(at: dbFile) let connection = try getDBConnection(inMemory: true) try setUpStorageAdapter(connection: connection) let mutationQueue = OutgoingMutationQueue( storageAdapter: storageAdapter, dataStoreConfiguration: .default, authModeStrategy: AWSDefaultAuthModeStrategy() ) try setUpDataStore(mutationQueue: mutationQueue) } override func tearDownWithError() throws { cancellables = [] try super.tearDownWithError() } /// - Given: A sync-configured DataStore, running without a network connection /// - When: /// - I make multiple mutations to a single model /// - I wait long enough for the first mutation to be in a "scheduledRetry" state /// - I make a final update /// - I restore the network /// - Then: /// - The sync engine submits the most recent update to the service func testLastMutationSentWhenNoNetwork() throws { // NOTE: The state descriptions in this test are approximate, especially as regards the // values of the MutationEvent table. Processing happens asynchronously, so it is important // to only assert the behavior we care about (which is that the final update happens after // network is restored). var post = Post(title: "Test", content: "Newly created", createdAt: .now()) let expectedFinalContent = "FINAL UPDATE" let version = AtomicValue(initialValue: 0) let networkUnavailable = expectation(description: "networkUnavailable") let networkAvailableAgain = expectation(description: "networkAvailableAgain") setUpNetworkStatusListener( fulfillingWhenNetworkUnavailable: networkUnavailable, fulfillingWhenNetworkAvailableAgain: networkAvailableAgain ) // Set up API responder chain // The first response is a success for the initial "Create" mutation let apiRespondedWithSuccess = expectation(description: "apiRespondedWithSuccess") let acceptInitialMutation = setUpInitialMutationRequestResponder( for: try post.eraseToAnyModel(), fulfilling: apiRespondedWithSuccess, incrementing: version ) // This response rejects mutations with a retriable error. This will cause the // SyncMutationToCloudOperation to schedule a retry for some future date (a few dozen // milliseconds in the future, for the first one). By that time, we will have enqueued new // mutations, at which point we can resume internet connectivity and ensure the API gets // called with the latest mutation. The delay simulates network time--this is to allow us // to add mutations to the pending queue while there is one in process. let rejectMutationsWithRetriableError = setUpRetriableErrorRequestResponder( listenerDelay: 0.25 ) // Once we've rejected some mutations due to an unreachable network, we'll allow the final // mutation to succeed. This is where we will assert that we've seen the last mutation // to be processed let expectedFinalContentReceived = expectation(description: "expectedFinalContentReceived") let acceptSubsequentMutations = setUpSubsequentMutationRequestResponder( for: try post.eraseToAnyModel(), fulfilling: expectedFinalContentReceived, whenContentContains: expectedFinalContent, incrementing: version ) // Start by accepting the initial "create" mutation apiPlugin.responders = [.mutateRequestListener: acceptInitialMutation] try startAmplifyAndWaitForSync() // Save initial model let createdNewItem = expectation(description: "createdNewItem") Amplify.DataStore.save(post) { if case .failure(let error) = $0 { XCTAssertNil(error) } else { createdNewItem.fulfill() } } wait(for: [createdNewItem, apiRespondedWithSuccess], timeout: 0.1) // Set the responder to reject the mutation. Make sure to push a retry advice before sending // a new mutation. apiPlugin.responders = [.mutateRequestListener: rejectMutationsWithRetriableError] // NOTE: This policy is not used by the SyncMutationToCloudOperation, only by the // RemoteSyncEngine. requestRetryablePolicy .pushOnRetryRequestAdvice( response: RequestRetryAdvice( shouldRetry: true, retryInterval: .seconds(100) ) ) // We expect this to be picked up by the OutgoingMutationQueue since the network is still // available. However, the mutation will be rejected with a retriable error. That retry // will be scheduled and probably in "waiting" mode when we send the network unavailable // notification below. post.content = "Update 1" let savedUpdate1 = expectation(description: "savedUpdate1") Amplify.DataStore.save(post) { if case .failure(let error) = $0 { XCTAssertNil(error) } else { savedUpdate1.fulfill() } } wait(for: [savedUpdate1], timeout: 0.1) // At this point, the MutationEvent table (the backing store for the outgoing mutation // queue) has only a record for the interim update. It is marked as `inProcess: true`, // because the mutation queue is operational and will have picked up the item and attempted // to sync it to the cloud. // "Turn off" network. The `mockSendCompletion` notifies each subscription listener of a // connection error, which will cause the state machine to clean up. As part of cleanup, // the RemoteSyncEngine will stop the outgoing mutation queue. We will set the retry // advice interval to be very high, so it will be preempted by the "network available" // message we send later. reachabilitySubject.send(ReachabilityUpdate(isOnline: false)) let noNetworkCompletion = Subscribers .Completion<DataStoreError> .failure(.sync("Test", "test", connectionError)) MockAWSIncomingEventReconciliationQueue.mockSendCompletion(completion: noNetworkCompletion) // Assert that DataStore has pushed the no-network event. This isn't strictly necessary for // correct operation of the queue. wait(for: [networkUnavailable], timeout: 0.1) // At this point, the MutationEvent table has only a record for update1. It is marked as // `inProcess: false`, because the mutation queue has been fully cancelled by the cleanup // process. // Submit two more mutations. The second mutation will overwrite the "initial updated // content" record with new "interim" content. Neither of those will be processed by the // outgoing mutation queue, since the network is not available and the OutgoingMutationQueue // was stopped during cleanup above. // We expect this to be written to the queue, overwriting the existing initial update. We // also expect that it will be overwritten by the next mutation, without ever being synced // to the service. post.content = "Update 2" let savedUpdate2 = expectation(description: "savedUpdate2") Amplify.DataStore.save(post) { if case .failure(let error) = $0 { XCTAssertNil(error) } else { savedUpdate2.fulfill() } } wait(for: [savedUpdate2], timeout: 0.1) // At this point, the MutationEvent table has only a record for update2. It is marked as // `inProcess: false`, because the mutation queue has been fully cancelled. // Write another mutation. The current disposition behavior is that the system detects // a not-in-process mutation in the queue, and overwrites it with this data. The // reconciliation logic drops all but the oldest not-in-process mutations, which means that // even if there were multiple not-in-process mutations, after the reconciliation completes // there would only be one record in the MutationEvent table. post.content = expectedFinalContent let savedFinalUpdate = expectation(description: "savedFinalUpdate") Amplify.DataStore.save(post) { if case .failure(let error) = $0 { XCTAssertNil(error) } else { savedFinalUpdate.fulfill() } } wait(for: [savedFinalUpdate], timeout: 0.1) let syncStarted = expectation(description: "syncStarted") setUpSyncStartedListener( fulfillingWhenSyncStarted: syncStarted ) let outboxEmpty = expectation(description: "outboxEmpty") setUpOutboxEmptyListener( fulfillingWhenOutboxEmpty: outboxEmpty ) // Turn on network. This will preempt the retry timer and immediately start processing // the queue. We expect the mutation queue to restart, poll the MutationEvent table, pick // up the final update, and process it. apiPlugin.responders = [.mutateRequestListener: acceptSubsequentMutations] reachabilitySubject.send(ReachabilityUpdate(isOnline: true)) wait(for: [networkAvailableAgain, syncStarted, outboxEmpty, expectedFinalContentReceived], timeout: 5.0) } // MARK: - Utilities private func setUpInitialMutationRequestResponder( for model: AnyModel, fulfilling expectation: XCTestExpectation, incrementing version: AtomicValue<Int> ) -> MutateRequestListenerResponder<MutationSync<AnyModel>> { MutateRequestListenerResponder<MutationSync<AnyModel>> { _, eventListener in let mockResponse = MutationSync( model: model, syncMetadata: MutationSyncMetadata( id: model.id, deleted: false, lastChangedAt: Date().unixSeconds, version: version.increment() ) ) DispatchQueue.global().async { eventListener?(.success(.success(mockResponse))) expectation.fulfill() } return nil } } /// Returns a responder that executes the eventListener after a delay, to simulate network lag private func setUpRetriableErrorRequestResponder( listenerDelay: TimeInterval ) -> MutateRequestListenerResponder<MutationSync<AnyModel>> { MutateRequestListenerResponder<MutationSync<AnyModel>> { _, eventListener in DispatchQueue.global().asyncAfter(deadline: .now() + listenerDelay) { eventListener?(.failure(self.connectionError)) } return nil } } private func setUpSubsequentMutationRequestResponder( for model: AnyModel, fulfilling expectation: XCTestExpectation, whenContentContains expectedFinalContent: String, incrementing version: AtomicValue<Int> ) -> MutateRequestListenerResponder<MutationSync<AnyModel>> { MutateRequestListenerResponder<MutationSync<AnyModel>> { request, eventListener in guard let input = request.variables?["input"] as? [String: Any], let content = input["content"] as? String else { XCTFail("Unexpected request structure: no `content` in variables.") return nil } let mockResponse = MutationSync( model: model, syncMetadata: MutationSyncMetadata( id: model.id, deleted: false, lastChangedAt: Date().unixSeconds, version: version.increment() ) ) eventListener?(.success(.success(mockResponse))) if content == expectedFinalContent { expectation.fulfill() } return nil } } private func setUpNetworkStatusListener( fulfillingWhenNetworkUnavailable networkUnavailable: XCTestExpectation, fulfillingWhenNetworkAvailableAgain networkAvailableAgain: XCTestExpectation ) { // We expect 2 "network available" notifications: the initial notification sent from the // RemoteSyncEngine when it first `start()`s and subscribes to the reachability publisher, // and the notification after we restore connectivity later in the test. let shouldFulfillNetworkAvailableAgain = AtomicValue(initialValue: false) Amplify .Hub .publisher(for: .dataStore) .print("### DataStore listener \(Date()) - ") .filter { $0.eventName == HubPayload.EventName.DataStore.networkStatus } .sink { payload in guard let networkStatusEvent = payload.data as? NetworkStatusEvent else { XCTFail("Failed to cast payload data as NetworkStatusEvent") return } if networkStatusEvent.active { if shouldFulfillNetworkAvailableAgain.get() { networkAvailableAgain.fulfill() } } else { // If the received event is an "unavailable" message, we should fulfill the // "network available" expectation the next time we receive an "available" message. shouldFulfillNetworkAvailableAgain.set(true) networkUnavailable.fulfill() } } .store(in: &cancellables) } private func setUpSyncStartedListener( fulfillingWhenSyncStarted syncStarted: XCTestExpectation ) { Amplify .Hub .publisher(for: .dataStore) .filter { $0.eventName == HubPayload.EventName.DataStore.syncStarted } .sink { _ in syncStarted.fulfill() } .store(in: &cancellables) } private func setUpOutboxEmptyListener( fulfillingWhenOutboxEmpty outboxEmpty: XCTestExpectation ) { Amplify .Hub .publisher(for: .dataStore) .filter { $0.eventName == HubPayload.EventName.DataStore.outboxStatus } .sink { payload in guard let outboxStatusEvent = payload.data as? OutboxStatusEvent else { XCTFail("Failed to cast payload data as OutboxStatusEvent") return } if outboxStatusEvent.isEmpty { outboxEmpty.fulfill() } } .store(in: &cancellables) } }
42.209068
112
0.640628
0958090faaf26dd67608e64918cb55b3f23c884c
195
import XCTest @testable import SwiftyMatrix final class SwiftyMatrixTests: XCTestCase { func testExample() { } static var allTests = [ ("testExample", testExample), ] }
16.25
43
0.661538
4a40bfd1e920aa2ba9569d39bfc3276c819233ac
2,345
// // OmetriaDefaults.swift // Ometria // // Created by Cata on 7/24/20. // Copyright © 2020 Cata. All rights reserved. // import Foundation @propertyWrapper struct UserDefault<T> { let key: String let defaultValue: T var wrappedValue: T { get { let value = UserDefaults.standard.object(forKey: key) as? T switch value as Any { case Optional<Any>.some(let containedValue): return containedValue as! T case Optional<Any>.none: return defaultValue default: return value ?? defaultValue } } set { switch newValue as Any { case Optional<Any>.some(let containedValue): UserDefaults.standard.set(containedValue, forKey: key) case Optional<Any>.none: UserDefaults.standard.removeObject(forKey: key) default: UserDefaults.standard.set(newValue, forKey: key) } } } } struct OmetriaDefaults { @UserDefault(key: "com.ometria.is_first_launch", defaultValue: true) static var isFirstLaunch: Bool @UserDefault(key: "com.ometria.apple_push_token", defaultValue: nil) static var applePushToken: String? @UserDefault(key: "com.ometria.fcm_token", defaultValue: nil) static var fcmToken: String? @UserDefault(key: "com.ometria.last_launch_date", defaultValue: nil) static var lastLaunchDate: Date? @UserDefault(key: "com.ometria.installment_id", defaultValue: nil) static var installationID: String? @UserDefault(key: "com.ometria.notification_process_date", defaultValue: Date(timeIntervalSince1970: 0)) static var notificationProcessDate: Date @UserDefault(key: "com.ometria.pushNotificationSettings", defaultValue: 0) static var lastKnownNotificationAuthorizationStatus: Int @UserDefault(key: "com.ometria.networkTimedOutUntilDate", defaultValue: Date(timeIntervalSince1970: 0)) static var networkTimedOutUntilDate: Date @UserDefault(key: "com.ometria.identifiedCustomerEmail", defaultValue: nil) static var identifiedCustomerEmail: String? @UserDefault(key: "com.ometria.identifiedCustomerID", defaultValue: nil) static var identifiedCustomerID: String? @UserDefault(key: Constants.UserDefaultsKeys.sdkVersionRN, defaultValue: nil) internal static var sdkVersionRN: String? }
35.530303
108
0.704051
913c5ce68f74bec4c4a1bc22042bc4fd6bcfbbb3
11,630
// // MNBannerView.swift // MonoFake // // Created by tommy on 2017/12/21. // Copyright © 2017年 TommyStudio. All rights reserved. // import UIKit import SnapKit import Kingfisher import AVFoundation import ObjectMapper public protocol EvaBannerViewDelegate: NSObjectProtocol { func clickedBannerView(item: EvaBannerModel) } public class EvaBannerModel: NSObject, Mappable { // banner类型 // // - URL: url链接类型 public enum EvaBannerType { case URL case GoodsDetail } public var bannerImage: String = "" public var bannerTitle: String = "" public var bannerLink: String = "" public var goodId: String? public var testImage: UIImage? public var bannerType: EvaBannerType = EvaBannerType.URL public override init() { super.init() } required public init?(map: Map) { } public func mapping(map: Map) { bannerImage <- map["image"] bannerTitle <- map["title"] bannerLink <- map["link"] goodId <- map["goodId"] } } public class EvaBannerImageView: UIImageView { //MARK: - 属性 public var bannerItem: EvaBannerModel? { didSet { if let _ = bannerItem { if self.bannerItem?.testImage != nil { self.image = self.bannerItem?.testImage } else { // 设置图片显示 self.kf.setImage(with: URL.init(string: bannerItem!.bannerImage), placeholder: UIImage.init(named: "banner_placeholder"), options: nil) { (result) in switch result { case .success(let retriveResult): //切割图片 let height = GlobalProperties.SCREEN_WIDTH * retriveResult.image.size.height / retriveResult.image.size.width let resultImage = retriveResult.image.scale(toSize: CGSize.init(width: GlobalProperties.SCREEN_WIDTH, height: height))! self.image = resultImage KingfisherManager.shared.cache.clearMemoryCache() case .failure(_): break } } } //设置标题 self.titleLabel.text = bannerItem!.bannerTitle } } } public override init(frame: CGRect) { super.init(frame: frame) self.contentMode = UIView.ContentMode.scaleAspectFill // 添加黑色标题背景 let titleBgView = UIView.init() titleBgView.isHidden = true titleBgView.backgroundColor = UIColor.init(white: 0.0, alpha: 0.4) self.addSubview(titleBgView) titleBgView.snp.makeConstraints { (make: ConstraintMaker) in make.left.bottom.equalTo(self) make.size.equalTo(CGSize.init(width: GlobalProperties.SCREEN_WIDTH, height: UIView.lf_sizeFromIphone6(size: 40))) } titleBgView.addSubview(self.titleLabel) self.titleLabel.snp.makeConstraints { (make: ConstraintMaker) in make.left.equalTo(titleBgView).offset(UIView.lf_sizeFromIphone6(size: 15)) make.centerY.equalTo(titleBgView) make.width.lessThanOrEqualTo(GlobalProperties.SCREEN_WIDTH - UIView.lf_sizeFromIphone6(size: 30)) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: - lazy load let titleLabel = UILabel.init().then { label in label.font = UIFont.lf_systemFont(size: 16) label.textColor = UIColor.white label.text = "" } } public class EvaBannerView: UIView, UIScrollViewDelegate { public var lastOffset: CGFloat = 0.0 public var bannerItemArray: [EvaBannerModel] = [] { //设置完毕之后,更新banner显示 didSet { self.pageControl.currentPage = 0 if bannerItemArray.count == 0 { return } for bannerImageView in self.bannerScrollView.subviews { if bannerImageView.isKind(of: EvaBannerImageView.self) { bannerImageView.removeFromSuperview() } } self.scrollTimer?.invalidate() self.scrollTimer = nil; let lastModel = Mapper<EvaBannerModel>().map(JSON: (self.bannerItemArray.last!).toJSON()) lastModel?.testImage = self.bannerItemArray.last?.testImage let firstModel = Mapper<EvaBannerModel>().map(JSON: (self.bannerItemArray.first!).toJSON()) firstModel?.testImage = self.bannerItemArray.first?.testImage var tempImageArray = [EvaBannerModel]() tempImageArray.append(lastModel!) tempImageArray.append(contentsOf: self.bannerItemArray) tempImageArray.append(firstModel!) for index in 0..<tempImageArray.count { let bannerItem = tempImageArray[index] let bannerImageView = EvaBannerImageView.init(frame: CGRect.init(x: CGFloat(index) * GlobalProperties.SCREEN_WIDTH, y: 0, width: GlobalProperties.SCREEN_WIDTH, height: self.height)) bannerImageView.isUserInteractionEnabled = true bannerImageView.backgroundColor = UIColor.lightGray bannerImageView.layer.masksToBounds = true bannerImageView.bannerItem = bannerItem bannerImageView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(handleClickedBanner(recognizer:)))) self.bannerScrollView.addSubview(bannerImageView) } if self.bannerItemArray.count > 1 { self.bannerScrollView.isScrollEnabled = true self.bannerScrollView.contentSize = CGSize.init(width: GlobalProperties.SCREEN_WIDTH * CGFloat(tempImageArray.count), height: self.height) self.bannerScrollView.contentOffset = CGPoint.init(x: GlobalProperties.SCREEN_WIDTH, y: 0) self.scrollTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(timerEvent), userInfo: nil, repeats: true) self.pageControl.isHidden = !self.showPageControl self.pageControl.numberOfPages = bannerItemArray.count self.lastOffset = GlobalProperties.SCREEN_WIDTH } else { //只有一个banner,则不再允许滑动 self.bannerScrollView.isScrollEnabled = false self.scrollTimer?.invalidate() self.scrollTimer = nil self.pageControl.isHidden = self.showPageControl self.pageControl.numberOfPages = bannerItemArray.count } } } public var showPageControl: Bool = true { didSet { self.pageControl.isHidden = !self.showPageControl } } public var scrollTimer: Timer? public weak var delegate: EvaBannerViewDelegate? public override init(frame: CGRect) { super.init(frame: frame) //添加scrollView self.bannerScrollView.delegate = self self.addSubview(self.bannerScrollView) self.bannerScrollView.snp.makeConstraints { (make: ConstraintMaker) in make.edges.equalTo(self).inset(UIEdgeInsets.zero) } //添加pageControl self.addSubview(self.pageControl) self.pageControl.snp.makeConstraints { (make: ConstraintMaker) in make.bottom.equalTo(self.bannerScrollView).offset(-UIView.lf_sizeFromIphone6(size: 5)) make.centerX.equalTo(self.bannerScrollView); make.height.equalTo(25) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } //MARK: - Timer事件 @objc func timerEvent() { if self.bannerScrollView.contentOffset.x > GlobalProperties.SCREEN_WIDTH * CGFloat(self.bannerItemArray.count + 1) { //滚动到第一张图片 self.bannerScrollView.contentOffset = CGPoint.init(x: GlobalProperties.SCREEN_WIDTH, y: 0) } else { UIView.animate(withDuration: 0.6, animations: { let offset: CGFloat = self.bannerScrollView.contentOffset.x + GlobalProperties.SCREEN_WIDTH self.bannerScrollView.contentOffset = CGPoint.init(x: offset, y: 0) }, completion: { (finished: Bool) in if self.bannerScrollView.contentOffset.x == CGFloat(self.bannerItemArray.count) * GlobalProperties.SCREEN_WIDTH { //滚动到最后一张图片 self.pageControl.currentPage = self.bannerItemArray.count - 1 } else if self.bannerScrollView.contentOffset.x == CGFloat(self.bannerItemArray.count + 1) * GlobalProperties.SCREEN_WIDTH { //滚动到第一张图片 self.bannerScrollView.contentOffset = CGPoint.init(x: GlobalProperties.SCREEN_WIDTH, y: 0); self.pageControl.currentPage = 0; } else { let offset: CGFloat = (self.bannerScrollView.contentOffset.x - GlobalProperties.SCREEN_WIDTH) / GlobalProperties.SCREEN_WIDTH + 0.5 let currentPage = Int(offset); self.pageControl.currentPage = currentPage; } }) } } //MARK: - UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { if self.bannerItemArray.count == 0 || self.scrollTimer != nil { return; } let scrollRight = (scrollView.contentOffset.x - self.lastOffset > 0) if scrollRight && scrollView.contentOffset.x > CGFloat(self.bannerItemArray.count) * GlobalProperties.SCREEN_WIDTH { let deltaOffset = scrollView.contentOffset.x - CGFloat(self.bannerItemArray.count) * GlobalProperties.SCREEN_WIDTH if deltaOffset > 0.5 * GlobalProperties.SCREEN_WIDTH { scrollView.contentOffset = CGPoint.init(x: deltaOffset, y: 0) } } else if !scrollRight && scrollView.contentOffset.x < GlobalProperties.SCREEN_WIDTH { let deltaOffset = GlobalProperties.SCREEN_WIDTH - scrollView.contentOffset.x if deltaOffset > 0.5 * GlobalProperties.SCREEN_WIDTH { scrollView.contentOffset = CGPoint.init(x: CGFloat(self.bannerItemArray.count + 1) * GlobalProperties.SCREEN_WIDTH - deltaOffset, y: 0) } } let currentPage = Int(self.bannerScrollView.contentOffset.x / GlobalProperties.SCREEN_WIDTH - 0.5) self.pageControl.currentPage = currentPage self.lastOffset = scrollView.contentOffset.x; } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.scrollTimer?.invalidate() self.scrollTimer = nil } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.scrollTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(timerEvent), userInfo: nil, repeats: true) } //MARK: - 点击事件 @objc func handleClickedBanner(recognizer: UITapGestureRecognizer) { self.delegate?.clickedBannerView(item: (recognizer.view as! EvaBannerImageView).bannerItem!) } //MARK: - lazy load let bannerScrollView = UIScrollView.init().then { scrollView in scrollView.isPagingEnabled = true scrollView.showsHorizontalScrollIndicator = false } let pageControl = UIPageControl.init().then { control in control.pageIndicatorTintColor = UIColor.init(white: 1.0, alpha: 0.4) control.currentPageIndicatorTintColor = GlobalProperties.COLOR_MAIN_1 } }
37.882736
197
0.629579
14e59812aa1c3268b95b17586ab0aa472476901f
12,470
// // QuickTableViewDelegateSpec.swift // QuickTableViewControllerTests // // Created by Ben on 31/12/2017. // Copyright © 2017 bcylin. // // 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 Nimble import Quick @testable import QuickTableViewController internal final class QuickTableViewDelegateSpec: QuickSpec { override func spec() { // MARK: tableView(_:shouldHighlightRowAt:) describe("tableView(_:shouldHighlightRowAt:)") { let controller = QuickTableViewController() _ = controller.view controller.tableContents = [ Section(title: "NavigationRow", rows: [ NavigationRow(text: "", detailText: .none), CustomNavigationRow(text: "", detailText: .none), NavigationRow<CustomCell>(text: "", detailText: .none), CustomNavigationRow<CustomCell>(text: "", detailText: .none) ]), Section(title: "NavigationRow", rows: [ NavigationRow(text: "", detailText: .none, action: { _ in }), CustomNavigationRow(text: "", detailText: .none, action: { _ in }), NavigationRow<CustomCell>(text: "", detailText: .none, action: { _ in }), CustomNavigationRow<CustomCell>(text: "", detailText: .none, action: { _ in }) ]), Section(title: "SwitchRow", rows: [ SwitchRow(text: "", switchValue: true, action: nil), CustomSwitchRow(text: "", switchValue: true, action: nil), SwitchRow<CustomSwitchCell>(text: "", switchValue: true, action: nil), CustomSwitchRow<CustomSwitchCell>(text: "", switchValue: true, action: nil) ]), Section(title: "TapActionRow", rows: [ TapActionRow(text: "", action: { _ in }), CustomTapActionRow(text: "", action: { _ in }), TapActionRow<CustomTapActionCell>(text: "", action: { _ in }), CustomTapActionRow<CustomTapActionCell>(text: "", action: { _ in }) ]), Section(title: "OptionRow", rows: [ OptionRow(text: "", isSelected: false, action: nil), CustomOptionRow(text: "", isSelected: false, action: nil), OptionRow<CustomCell>(text: "", isSelected: false, action: nil), CustomOptionRow<CustomCell>(text: "", isSelected: false, action: nil) ]), RadioSection(title: "RadioSection", options: [ OptionRow(text: "", isSelected: false, action: { _ in }), CustomOptionRow(text: "", isSelected: false, action: { _ in }), OptionRow<CustomCell>(text: "", isSelected: false, action: { _ in }), CustomOptionRow<CustomCell>(text: "", isSelected: false, action: { _ in }) ]) ] it("should not highlight NavigationRow without an action") { for index in 0...3 { let highlight = controller.tableView(controller.tableView, shouldHighlightRowAt: IndexPath(row: index, section: 0)) expect(highlight) == false } } it("should highlight NavigationRow with an action") { for index in 0...3 { let highlight = controller.tableView(controller.tableView, shouldHighlightRowAt: IndexPath(row: index, section: 1)) expect(highlight) == true } } it("should not highlight SwitchRow") { for index in 0...3 { let highlight = controller.tableView(controller.tableView, shouldHighlightRowAt: IndexPath(row: index, section: 2)) #if os(iOS) expect(highlight) == false #elseif os(tvOS) expect(highlight) == true #endif } } it("should highlight TapActionRow") { for index in 0...3 { let highlight = controller.tableView(controller.tableView, shouldHighlightRowAt: IndexPath(row: index, section: 3)) expect(highlight) == true } } it("should highlight OptionRow without an action") { for index in 0...3 { let highlight = controller.tableView(controller.tableView, shouldHighlightRowAt: IndexPath(row: index, section: 4)) expect(highlight) == true } } it("should highlight OptionRow with an action") { for index in 0...3 { let highlight = controller.tableView(controller.tableView, shouldHighlightRowAt: IndexPath(row: index, section: 5)) expect(highlight) == true } } } // MARK: - tableView(_:didSelectRowAt:) describe("tableView(_:didSelectRowAt:)") { // MARK: Section context("Section") { context("NavigationRow") { let controller = QuickTableViewController() _ = controller.view var selectedIndex = -1 controller.tableContents = [ Section(title: "NavigationRow", rows: [ NavigationRow(text: "", detailText: .none, action: { _ in selectedIndex = 0 }), CustomNavigationRow(text: "", detailText: .none, action: { _ in selectedIndex = 1 }), NavigationRow<CustomCell>(text: "", detailText: .none, action: { _ in selectedIndex = 2 }), CustomNavigationRow<CustomCell>(text: "", detailText: .none, action: { _ in selectedIndex = 3 }) ]) ] for index in 0...3 { it("should invoke action when \(index) is selected") { controller.tableView(controller.tableView, didSelectRowAt: IndexPath(row: index, section: 0)) expect(selectedIndex).toEventually(equal(index)) } } } context("TapActionRow") { let controller = QuickTableViewController() _ = controller.view var selectedIndex = -1 controller.tableContents = [ Section(title: "TapActionRow", rows: [ TapActionRow(text: "", action: { _ in selectedIndex = 0 }), CustomTapActionRow(text: "", action: { _ in selectedIndex = 1 }), TapActionRow<CustomTapActionCell>(text: "", action: { _ in selectedIndex = 2 }), CustomTapActionRow<CustomTapActionCell>(text: "", action: { _ in selectedIndex = 3 }) ]) ] for index in 0...3 { it("should invoke action when \(index) is selected") { controller.tableView(controller.tableView, didSelectRowAt: IndexPath(row: index, section: 0)) expect(selectedIndex).toEventually(equal(index)) } } } context("OptionRow") { let controller = QuickTableViewController() _ = controller.view var toggledIndex = -1 let section = Section(title: "OptionRow", rows: [ OptionRow(text: "", isSelected: false, action: { _ in toggledIndex = 0 }), CustomOptionRow(text: "", isSelected: false, action: { _ in toggledIndex = 1 }), OptionRow<CustomCell>(text: "", isSelected: false, action: { _ in toggledIndex = 2 }), CustomOptionRow<CustomCell>(text: "", isSelected: false, action: { _ in toggledIndex = 3 }) ]) controller.tableContents = [section] for index in 0...3 { it("should invoke action when \(index) is selected") { controller.tableView(controller.tableView, didSelectRowAt: IndexPath(row: index, section: 0)) expect(toggledIndex).toEventually(equal(index)) let option = section.rows[index] as? OptionRowCompatible expect(option?.isSelected) == true } } } } // MARK: Radio Section context("RadioSection") { context("default") { let controller = QuickTableViewController() _ = controller.view var toggledIndex = -1 let radio = RadioSection(title: "alwaysSelectsOneOption = false", options: [ OptionRow(text: "", isSelected: false, action: { _ in toggledIndex = 0 }), CustomOptionRow(text: "", isSelected: false, action: { _ in toggledIndex = 1 }), OptionRow<CustomCell>(text: "", isSelected: false, action: { _ in toggledIndex = 2 }), CustomOptionRow<CustomCell>(text: "", isSelected: false, action: { _ in toggledIndex = 3 }) ]) controller.tableContents = [radio] for index in 0...3 { it("should invoke action when \(index) is selected") { controller.tableView(controller.tableView, didSelectRowAt: IndexPath(row: index, section: 0)) expect(toggledIndex).toEventually(equal(index)) let option = radio.rows[index] as? OptionRowCompatible expect(option?.isSelected) == true controller.tableView(controller.tableView, didSelectRowAt: IndexPath(row: index, section: 0)) expect(option?.isSelected) == false } } } context("alwaysSelectsOneOption") { let controller = QuickTableViewController() _ = controller.view var toggledIndex = -1 let radio = RadioSection(title: "alwaysSelectsOneOption = true", options: [ OptionRow(text: "", isSelected: false, action: { _ in toggledIndex = 0 }), CustomOptionRow(text: "", isSelected: false, action: { _ in toggledIndex = 1 }), OptionRow<CustomCell>(text: "", isSelected: false, action: { _ in toggledIndex = 2 }), CustomOptionRow<CustomCell>(text: "", isSelected: false, action: { _ in toggledIndex = 3 }) ]) radio.alwaysSelectsOneOption = true controller.tableContents = [radio] for index in 0...3 { it("should invoke action when \(index) is selected") { controller.tableView(controller.tableView, didSelectRowAt: IndexPath(row: index, section: 0)) expect(toggledIndex).toEventually(equal(index)) let option = controller.tableContents[0].rows[index] as? OptionRowCompatible expect(option?.isSelected) == true controller.tableView(controller.tableView, didSelectRowAt: IndexPath(row: index, section: 0)) expect(option?.isSelected) == true expect(radio.indexOfSelectedOption) == index } } } } #if os(iOS) // MARK: - tableView(_:accessoryButtonTappedForRowWith:) describe("tableView(_:accessoryButtonTappedForRowWith:)") { let controller = QuickTableViewController() _ = controller.view var selectedIndex = -1 controller.tableContents = [ Section(title: "NavigationRow", rows: [ NavigationRow(text: "", detailText: .none, accessoryButtonAction: { _ in selectedIndex = 0 }), CustomNavigationRow(text: "", detailText: .none, accessoryButtonAction: { _ in selectedIndex = 1 }), NavigationRow<CustomCell>(text: "", detailText: .none, accessoryButtonAction: { _ in selectedIndex = 2 }), CustomNavigationRow<CustomCell>(text: "", detailText: .none, accessoryButtonAction: { _ in selectedIndex = 3 }) ]) ] for index in 0...3 { it("should invoke action when accessory button at \(index) is selected") { controller.tableView(controller.tableView, accessoryButtonTappedForRowWith: IndexPath(row: index, section: 0)) expect(selectedIndex).toEventually(equal(index)) } } } #endif } } }
41.705686
125
0.608741
217a3bfeacb4b63e2513042458ab49330720c69e
524
// // BuyerDetails.swift // Chat Bot // // Created by Adarsh on 05/01/19. // Copyright © 2019 Pallav Trivedi. All rights reserved. // import Foundation class CustomerDetails: NSObject { var name:String? var location:String? var vehicleModel:String? var ownership:String? var targetPrice:Int? var kilometres:Int? var carType:String? var engineType:engineType? = nil var yearOfManufacture:Int = 0 var brand: String? override init() { super.init() } }
16.903226
57
0.64313
48de3eed686394cdf1716b2366809c86edf6b81f
5,140
// // UserProfileController.swift // Movinder // // Created by Max on 09.03.21. // import UIKit protocol UserProfileControllerDelegate: class { func userProfileController(_ controller: UserProfileController, didLikeMovie user: User) func userProfileController(_ controller: UserProfileController, didDislikeMovie user: User) } class UserProfileController: UIViewController { //MARK: Properties private let user: User weak var delegate: UserProfileControllerDelegate? private lazy var imageView: UIView = { let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.width) let v = UIView(frame: frame) v.backgroundColor = .systemGroupedBackground let imageView = UIImageView(frame: frame) let imageURL = NSURL(string: user.profileImageUrl) let imagedData = NSData(contentsOf: imageURL! as URL)! imageView.image = UIImage(data: imagedData as Data)?.withRenderingMode(.alwaysOriginal) imageView.contentMode = .scaleToFill return imageView }() private let dissmissButton: UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "dismiss_down_arrow").withRenderingMode(.alwaysOriginal), for: .normal) // button.addTarget(self, action: #selector(handleDismiss), for: .touchUpInside) return button }() //MARK: LABELS let nameLabel : UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 24,weight: .semibold) return label }() private let infoLabel : UILabel = { let label = UILabel() label.numberOfLines = 5 label.font = UIFont.systemFont(ofSize: 20) return label }() private let lengthLabel : UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 20) return label }() private let ratingLabel : UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 20) return label }() private let releasedLabel : UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 20) return label }() //MARK: BUTTONS private lazy var likeButton: UIButton = { let button = createButton(withImage: #imageLiteral(resourceName: "like_circle")) // button.addTarget(self, action: #selector(handleLike), for: .touchUpInside) return button }() private lazy var superlikeButton: UIButton = { let button = createButton(withImage: #imageLiteral(resourceName: "super_like_circle")) // button.addTarget(self, action: #selector(handleSuperlike), for: .touchUpInside) return button }() private lazy var dislikeButton: UIButton = { let button = createButton(withImage: #imageLiteral(resourceName: "dismiss_circle")) // button.addTarget(self, action: #selector(handleDislike), for: .touchUpInside) return button }() //MARK: Lifecycle init(user: User){ self.user = user self.userName = user.name self.userBio = user.bio self.userUsername = user.username super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configureUI() } //MARK: Helpers let userName : String let userBio : String let userUsername : String func configureUI(){ view.backgroundColor = .white view.addSubview(imageView) view.addSubview(dissmissButton) dissmissButton.setDimensions(height: 40, width: 40) dissmissButton.anchor(top: imageView.bottomAnchor,right: view.rightAnchor, paddingTop: -20 , paddingRight: 16) nameLabel.text = "" + userName lengthLabel.text = "Bio: " + userBio infoLabel.text = "Usernane: " + userUsername let infoStack = UIStackView(arrangedSubviews: [nameLabel,infoLabel,lengthLabel]) infoStack.axis = .vertical infoStack.spacing = 4 view.addSubview(infoStack) infoStack.anchor(top: imageView.bottomAnchor , left: view.leftAnchor, right: view.rightAnchor, paddingTop: 12, paddingLeft: 12,paddingRight: 12) configureBottomControls() } func configureBottomControls(){ let stack = UIStackView(arrangedSubviews: [likeButton,superlikeButton,dislikeButton]) stack.distribution = .fillEqually view.addSubview(stack) stack.spacing = -32 stack.setDimensions(height: 80, width: 300) stack.centerX(inView: view) stack.anchor(bottom: view.safeAreaLayoutGuide.bottomAnchor, paddingBottom: 32) } func createButton(withImage image: UIImage) -> UIButton { let button = UIButton(type: .system) button.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal) button.imageView?.contentMode = .scaleAspectFill return button } }
35.205479
152
0.650973
5bae3cfd5bf0efd51918d35ece58c50b8eeba13b
4,073
// // ViewController.swift // Calculator // // Created by Marcin Obolewicz on 24/11/2021. // import UIKit import Combine import SwiftUI final class CalculatorViewController: UIViewController { @IBOutlet private weak var firstValueTitleLabel: UILabel! @IBOutlet private weak var firstValueStepper: UIStepper! @IBOutlet private weak var operationsSegment: UISegmentedControl! @IBOutlet private weak var secondValueTitleLabel: UILabel! @IBOutlet private weak var secondValueStepper: UIStepper! @IBOutlet private weak var equationLabel: UILabel! @IBOutlet private weak var calculateButton: UIButton! private var spinnerViewController: SpinnerViewController? private var cancellables = Set<AnyCancellable>() private var viewModel: CalculatorViewModel? private let networker = Networker() private let service = ShiftsService(networker: Networker()) override func viewDidLoad() { super.viewDidLoad() title = "Calculator" setupControls() setupBindings() setupInitialValues() } private func setupBindings() { let firstValuePublisher = firstValueStepper.publisher(for: .valueChanged) .map { ($0 as? UIStepper)?.value } .eraseToAnyPublisher() let secondValuePublisher = secondValueStepper.publisher(for: .valueChanged) .map { ($0 as? UIStepper)?.value } .eraseToAnyPublisher() let operationPublisher = operationsSegment.publisher(for: .valueChanged) .map { segment -> Operation? in if let index = (segment as? UISegmentedControl)?.selectedSegmentIndex { return Operation(rawValue: index) } return nil } .eraseToAnyPublisher() let service = ShiftsService(networker: Networker()) viewModel = CalculatorViewModel( service: service, firstValuePublisher: firstValuePublisher, secondValuePublisher: secondValuePublisher, operationPublisher: operationPublisher ) viewModel?.$equation.assign(to: \.text, on: equationLabel) .store(in: &cancellables) viewModel?.validationPublisher .sink { [weak self] valid in self?.calculateButton.isEnabled = valid } .store(in: &cancellables) } @IBAction private func calculateButtonAction(_ sender: Any) { getResult() } @IBAction func aboutButtonAction(_ sender: Any) { let aboutView = AboutView() let vc = UIHostingController(rootView: aboutView) present(vc, animated: true, completion: nil) } private func setupControls() { secondValueStepper.maximumValue = Double.infinity } private func setupInitialValues() { firstValueStepper.value = 0 firstValueStepper.sendActions(for: .valueChanged) operationsSegment.selectedSegmentIndex = 0 operationsSegment.sendActions(for: .valueChanged) secondValueStepper.value = 0 secondValueStepper.sendActions(for: .valueChanged) } private func getResult() { spinnerViewController = showSpinnerView() viewModel?.fetchResult() .sink { [weak self] completion in self?.removeSpinerView(spiner: self?.spinnerViewController) switch completion { case .failure(let error): self?.showPopup(title: "Request Failed", message: error.localizedDescription) case .finished: break } } receiveValue: { [weak self] result in self?.showResultView(with: result) } .store(in: &cancellables) } private func showResultView(with result: String) { let vc = ResultViewController() vc.setup(with: result) navigationController?.pushViewController(vc, animated: true) } }
34.516949
97
0.628529
561a25db6eec5ff41cd2569d36e84012ee2e6f8a
1,578
// // MainTabBarViewController.swift // Weather // // Created by Erid Bardhaj on 5/3/15. // Copyright (c) 2015 STRV. All rights reserved. // import UIKit class MainTabBarViewController: UITabBarController { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.changeTabBarItems() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //Keep original image, not gray default mode changeTabBarItems() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Configuration func changeTabBarItems() { var imageNames = ["fc-today", "tod-forecast", "tod-settings"] var count = 0 for imageName in imageNames { var m_tabBarItem: UITabBarItem = self.tabBar.items![count] as! UITabBarItem var image = UIImage(named: imageName) m_tabBarItem.image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) count++ } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
26.745763
106
0.640051
dba023e75cd917faf25ddc48ceff3dcbf3643f0d
3,733
// // File.swift // WiproWeather // // Created by Iain Frame on 11/02/2019. // Copyright © 2019 PointPixel. All rights reserved. // import Foundation ///Forecast fraction /// - Represents a 3h view of one days weather struct ForecastFraction: Decodable { struct Main: Decodable { let temperature: Double let minimumTemperature: Double let maximumTemperature: Double let pressure: Double let seaLevel: Double let groundLevel: Double let humidity: Int init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: MainKeys.self) self.temperature = try container.decode(Double.self, forKey: .temperature) self.minimumTemperature = try container.decode(Double.self, forKey: .minimumTemperature) self.maximumTemperature = try container.decode(Double.self, forKey: .maximumTemperature) self.pressure = try container.decode(Double.self, forKey: .pressure) self.seaLevel = try container.decode(Double.self, forKey: .seaLevel) self.groundLevel = try container.decode(Double.self, forKey: .groundLevel) self.humidity = try container.decode(Int.self, forKey: .humidity) } enum MainKeys: String, CodingKey { case temperature = "temp" case minimumTemperature = "temp_min" case maximumTemperature = "temp_max" case pressure = "pressure" case seaLevel = "sea_level" case groundLevel = "grnd_level" case humidity = "humidity" } } struct Overview: Decodable { let main: String let description: String let icon: String } struct Wind: Decodable { let speed: Double let direction: Double init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: WindKeys.self) self.speed = try container.decode(Double.self, forKey: .speed) self.direction = try container.decode(Double.self, forKey: .direction) } enum WindKeys: String, CodingKey { case speed = "speed" case direction = "deg" } } struct Rain: Decodable { let amount: Double? init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: RainKeys.self) self.amount = try container.decodeIfPresent(Double.self, forKey: .amount) } enum RainKeys: String, CodingKey { case amount = "3h" } } let forecastDate: Date let main: Main let overview: [Overview] let wind: Wind let rain: Rain? init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ForecastKeys.self) let dateString = try container.decode(String.self, forKey: .forecastDate) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" self.forecastDate = dateFormatter.date(from: dateString) ?? Date() self.main = try container.decode(Main.self, forKey: .main) self.overview = try container.decode([Overview].self, forKey: .overview) self.wind = try container.decode(Wind.self, forKey: .wind) self.rain = try container.decodeIfPresent(Rain.self, forKey: .rain) } enum ForecastKeys: String, CodingKey { case forecastDate = "dt_txt" case main = "main" case overview = "weather" case wind = "wind" case rain = "rain" } }
33.330357
100
0.601661
505a5cc9ea6d76c0929c6fe73c68756210f10e9b
830
// // TextFieldFactory.swift // ExchangeApp // // Created by Юрий Нориков on 08.12.2019. // Copyright © 2019 norikoff. All rights reserved. // import UIKit class TextFieldFactory { static func createTextField(title: String) -> UITextField { let textField = UITextField() textField.backgroundColor = .black textField.textColor = .white textField.textAlignment = .center textField.attributedPlaceholder = NSAttributedString(string: title, attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]) textField.layer.borderWidth = 1.0 textField.layer.borderColor = UIColor.orange.cgColor textField.layer.cornerRadius = 20 textField.translatesAutoresizingMaskIntoConstraints = false return textField } }
26.774194
114
0.685542
18ec8d1597cfaa444980db479cd4f1cc6eb6e6fa
493
// // ViewController.swift // FooApp // // Created by Tran Duc on 12/4/19. // Copyright © 2019 David. All rights reserved. // import UIKit import S1 import D1 class ViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() print("Start...") SBob.setCount(10) SBob.printMe() DAlice.printS1() titleLabel.text = "S1: \(SBob.count)\nS1's value from D1: \(DAlice.getS1Count())" } }
15.903226
85
0.649087
e90383c98cce0584b7eab4b0bb02887b8f412367
2,716
// // TableViewController.swift // PhoneFit 3-4 // // Created by Matthew Pileggi on 12/5/16. // Copyright © 2016 Matthew Pileggi. All rights reserved. // import UIKit class FileTableViewController: UITableViewController { var model: FileModel! @IBAction func close(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() if model == nil { model = FileModel() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return model.items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "file row", for: indexPath) as! FileTableViewCell let row = indexPath.row let item = model.items[row] cell.loadCell(item: item) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 45 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = model.items[indexPath.row] if let directory = item as? Directory { let vc = SwiftyFileExplorerUtility.getFileViewController() vc.model = FileModel(path: directory.path) self.navigationController?.pushViewController(vc, animated: true) } } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ }
29.521739
136
0.649853
2822e6281aaec9fd5fdecdfa6fb4707aff0be84d
1,854
// // NativeLocationService.swift // OnTheMap // // Created by Luke Van In on 2017/01/16. // Copyright © 2017 Luke Van In. All rights reserved. // // Location service providing reverse geocoding using the native OS CoreLocation framework. // import Foundation import CoreLocation enum LocationError: Swift.Error { // Another geo location request is already executing. case busy } // extension LocationError: LocalizedError { var errorDescription: String? { switch self { case .busy: return "Cannot perform geo location request while another request is in progress. Wait for the other request to finish then try again." } } } struct NativeLocationService: LocationService { private let geocoder = CLGeocoder() // // Stop any geocoding operation which is currently in progress. // func cancelAddressLookup() { if geocoder.isGeocoding { geocoder.cancelGeocode() } } // // Obtain geocoded location coordinates from a given address string. Only one geocoding operation may execute at // a time. It is an error to try to execute more than one geocoding operation concurrently. // func lookupAddress(_ address: String, completion: @escaping LocationLookupCompletion) { guard !geocoder.isGeocoding else { completion(Result.failure(LocationError.busy)) return } geocoder.geocodeAddressString(address) { (placemarks, error) in if let placemarks = placemarks { completion(Result.success(placemarks)) } else if let error = error { completion(Result.failure(error)) } else { completion(Result.failure(ServiceError.server)) } } } }
28.523077
147
0.635383
d54369f19e5adb92f10188e62b3a13b52077b4e7
944
// Copyright 2019 Hotspring Ventures Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import TWUITests enum Stub { enum Authentication { static let success = APIStubInfo(statusCode: 200, url: "/api/authentication", jsonFilename: "authentication", method: .POST) static let failure = APIStubInfo(statusCode: 200, url: "/api/authentication", jsonFilename: "authentication-failed", method: .POST) } }
41.043478
139
0.728814
d60758cb42155926dc8552bde0f89b6a1dcdb2f0
453
// // Defaults.swift // XXTouchApp // // Created by mcy on 16/7/5. // Copyright © 2016年 mcy. All rights reserved. // import Foundation class Defaults { class func configure() { if let defaultsPath = NSBundle.mainBundle().pathForResource("Defaults", ofType: "plist") { let defaults = NSDictionary(contentsOfFile: defaultsPath)! as! [String : AnyObject] NSUserDefaults.standardUserDefaults().registerDefaults(defaults) } } }
23.842105
94
0.695364
ff9fece8b27074b3ad3ffd335b9b6b705e9fc448
1,676
import XCTest @testable import SHLModelEvaluation class PreprocessingTests: DataTest { /// Test that the preprocessors were ported correctly. func testPreprocessors() throws { guard let datasets = datasets else { XCTFail(); return } let sensorPreprocessors = Dictionary(uniqueKeysWithValues: try Sensor.order.map { sensor throws -> (Sensor, [Preprocessor]) in let preprocessors: [Preprocessor] = [ try PowerTransformer(configFileName: sensor.configFileName), try StandardScaler(configFileName: sensor.configFileName), ] return (sensor, preprocessors) }) for sensor in Sensor.order { var maxDiff: Parameter = 0 for sample in datasets.values.flatMap({ s in s }) { guard let preprocessors = sensorPreprocessors[sensor] else { XCTFail(); return } let xFeatureSensor = sample.xFeature .map { features in features[sensor.sampleIndex] } let xRawSensor = sample.xRaw .map { features in features[sensor.sampleIndex] } var xPreprocessed = xRawSensor for preprocessor in preprocessors { xPreprocessed = preprocessor.transform(xPreprocessed) } let xDiffs = Array((0..<500)).map { i in xFeatureSensor[i] - xPreprocessed[i] } for diff in xDiffs { maxDiff = max(diff, maxDiff) XCTAssert(diff < 0.00001) } } } } }
37.244444
134
0.552506
0a2005323df60f60c1646f2c56fb322cf66769af
1,240
// // UserMock.swift // FluxCapacitorSample // // Created by marty-suzuki on 2017/08/22. // Copyright © 2017年 marty-suzuki. All rights reserved. // import Foundation @testable import FluxCapacitorSample import GithubKit extension User { static func mock(id: String = "abcdef", avatarUrl: String = "https://github.com/marty-suzuki", followerCount: Int = 100, followingCount: Int = 50, repositoryCount: Int = 10, login: String = "marty-suzuki", url: String = "https://github.com/marty-suzuki") -> User { let json: [AnyHashable: Any] = [ "id" : id, "avatarUrl" : avatarUrl, "followers" : ["totalCount" : followerCount], "following" : ["totalCount" : followingCount], "repositories" : ["totalCount" : repositoryCount], "login" : login, "url" : url, ] do { let data = try JSONSerialization.data(withJSONObject: json, options: []) return try JSONDecoder().decode(User.self, from: data) } catch let e { fatalError(e.localizedDescription) } } }
30.243902
84
0.53871
03209d7131050f297a7c0ec63cd3b600e1e792cb
4,329
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the FilterUtilities class. FilterUtilities objects contain functions and data that is used by both the SimpleTunnel UI and the SimpleTunnel content filter providers. */ import Foundation import NetworkExtension /// Content Filter actions. public enum FilterRuleAction : Int, CustomStringConvertible { case block = 1 case allow = 2 case needMoreRulesAndBlock = 3 case needMoreRulesAndAllow = 4 case needMoreRulesFromDataAndBlock = 5 case needMoreRulesFromDataAndAllow = 6 case examineData = 7 case redirectToSafeURL = 8 case remediate = 9 public var description: String { switch self { case .block: return "Block" case .examineData: return "Examine Data" case .needMoreRulesAndAllow: return "Ask for more rules, then allow" case .needMoreRulesAndBlock: return "Ask for more rules, then block" case .needMoreRulesFromDataAndAllow: return "Ask for more rules, examine data, then allow" case .needMoreRulesFromDataAndBlock: return "Ask for more rules, examine data, then block" case .redirectToSafeURL: return "Redirect" case .remediate: return "Remediate" case .allow: return "Allow" } } } /// A class containing utility properties and functions for Content Filtering. open class FilterUtilities { // MARK: Properties /// A reference to the SimpleTunnel user defaults. public static let defaults = UserDefaults(suiteName: "group.com.example.apple-samplecode.SimpleTunnel") // MARK: Initializers /// Get rule parameters for a flow from the SimpleTunnel user defaults. open class func getRule(_ flow: NEFilterFlow) -> (FilterRuleAction, String, [String: AnyObject]) { let hostname = FilterUtilities.getFlowHostname(flow) guard !hostname.isEmpty else { return (.allow, hostname, [:]) } guard let hostNameRule = (defaults?.object(forKey: "rules") as AnyObject).object(forKey: hostname) as? [String: AnyObject] else { simpleTunnelLog("\(hostname) is set for NO RULES") return (.allow, hostname, [:]) } guard let ruleTypeInt = hostNameRule["kRule"] as? Int, let ruleType = FilterRuleAction(rawValue: ruleTypeInt) else { return (.allow, hostname, [:]) } return (ruleType, hostname, hostNameRule) } /// Get the hostname from a browser flow. open class func getFlowHostname(_ flow: NEFilterFlow) -> String { guard let browserFlow : NEFilterBrowserFlow = flow as? NEFilterBrowserFlow, let url = browserFlow.url, let hostname = url.host , flow is NEFilterBrowserFlow else { return "" } return hostname } /// Download a fresh set of rules from the rules server. open class func fetchRulesFromServer(_ serverAddress: String?) { simpleTunnelLog("fetch rules called") guard serverAddress != nil else { return } simpleTunnelLog("Fetching rules from \(serverAddress!)") guard let infoURL = URL(string: "http://\(serverAddress!)/rules/") else { return } simpleTunnelLog("Rules url is \(infoURL)") let content: String do { content = try String(contentsOf: infoURL, encoding: String.Encoding.utf8) } catch { simpleTunnelLog("Failed to fetch the rules from \(infoURL)") return } let contentArray = content.components(separatedBy: "<br/>") simpleTunnelLog("Content array is \(contentArray)") var urlRules = [String: [String: AnyObject]]() for rule in contentArray { if rule.isEmpty { continue } let ruleArray = rule.components(separatedBy: " ") guard !ruleArray.isEmpty else { continue } var redirectKey = "SafeYes" var remediateKey = "Remediate1" var remediateButtonKey = "RemediateButton1" var actionString = "9" let urlString = ruleArray[0] let ruleArrayCount = ruleArray.count if ruleArrayCount > 1 { actionString = ruleArray[1] } if ruleArrayCount > 2 { redirectKey = ruleArray[2] } if ruleArrayCount > 3 { remediateKey = ruleArray[3] } if ruleArrayCount > 4 { remediateButtonKey = ruleArray[4] } urlRules[urlString] = [ "kRule" : actionString as AnyObject, "kRedirectKey" : redirectKey as AnyObject, "kRemediateKey" : remediateKey as AnyObject, "kRemediateButtonKey" : remediateButtonKey as AnyObject, ] } defaults?.setValue(urlRules, forKey:"rules") } }
30.921429
185
0.724879
f968387087ce70a2152cce938b5577f9d719defc
1,178
// // This source file is part of the Web3Swift.io open source project // Copyright 2019 The Web3Swift Authors // Licensed under Apache License v2.0 // // NormalizedDecimalFromHexTests.swift // // Created by Vadim Koleoshkin on 10/05/2019 // import Nimble import Quick @testable import Web3Swift class NormalizedDecimalFromHexTests: XCTestCase { func testUInt256MaxConvertsToAValidDecimal() { expect{ try NormalizedDecimalFromHex( hex: EthNumber( hex: SimpleBytes( bytes: Array<UInt8>( repeating: 0xff, count: 32 ) ) ), power: 27 // Maker PETH precision ).value() }.to( // swiftlint:disable force_unwrapping equal( Decimal(string: "115792089237316195423570985008687907853269984665640.564039457584007913129639935")! ), description: "Max UInt256 with precision 27 should expected to be encoded correctly" // swiftlint:enable force_unwrapping ) } }
28.731707
115
0.567063
0acfc744473620c14e01caf1980d71ccb660e196
1,097
// // ResponseLoggingInterceptor.swift // Github-Profile // // Created by Marcos González on 2021. // // import Apollo final class ResponseLoggingInterceptor: ApolloInterceptor { enum ResponseLoggingError: Error { case notYetReceived } func interceptAsync<Operation: GraphQLOperation>( chain: RequestChain, request: HTTPRequest<Operation>, response: HTTPResponse<Operation>?, completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void ) { defer { chain.proceedAsync( request: request, response: response, completion: completion ) } guard let receivedResponse = response else { chain.handleErrorAsync( ResponseLoggingError.notYetReceived, request: request, response: response, completion: completion ) return } // TODO: change with debugLog DLog("HTTP Response: \(receivedResponse.httpResponse)") guard let stringData = String(bytes: receivedResponse.rawData, encoding: .utf8) else { DLog("HTTP Response Error: Could not convert data to string!") return } DLog("Data: \(stringData)") } }
21.096154
88
0.715588
bb6c741303cd18c3119f49712fd9b8ff76eb5643
10,172
// // MacToggle.swift // RichAppz // // Copyright © 2016-2017 RichAppz Limited. All rights reserved. // richappz.com - ([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 Cocoa // @IBDesignable class MacToggle: NSView { // MARK: Lifecycle //================================================================================ // MARK: Initialization //================================================================================ required init?(coder: NSCoder) { super.init(coder: coder) drawView() } required init(height: CGFloat = 44) { self.height = height super.init(frame: .zero) drawView() } // MARK: Public //================================================================================ // MARK: Properties //================================================================================ public var isEnabled: Bool = true { didSet { mainThread { if isEnabled { alphaValue = 1.0 backVw.bg = backColor circle.bg = toggleColor circle.layer?.borderColor = white.cgColor } else { alphaValue = 0.6 backVw.bg = darkMauve circle.bg = .darkGray circle.layer?.borderColor = NSColor.darkGray.cgColor } } } } //================================================================================ // MARK: Public Parameters //================================================================================ @IBInspectable public var isOn = false { didSet { animate() } } /// Change the toggle border on and off @IBInspectable public var hasToggleBorder = true { didSet { circle.layer?.borderWidth = hasToggleBorder ? toggleBorderWidth : 0 } } /// Change the width of the outline border @IBInspectable public var outlineWidth: CGFloat = 2 { didSet { backVw.layer?.borderWidth = outlineWidth layoutSwitch(resetingLayout: true) } } /// Change the width of the border on the toggle @IBInspectable public var toggleBorderWidth: CGFloat = 2 { didSet { circle.layer?.borderWidth = hasToggleBorder ? toggleBorderWidth : 0 } } /// Change the radius of the complete toggle @IBInspectable public var toggleRadius: CGFloat { get { if let r = _radius { return r } return (height - (outlineWidth * 2)) / 2 } set { _radius = newValue layoutSwitch() } } /// Change the color of the outline border @IBInspectable public var outlineColor: NSColor = .lightGray { didSet { backVw.layer?.borderColor = outlineColor.cgColor } } /// Change the color of the fill when the toggle is on @IBInspectable public var fillColor: NSColor = .lightGray { didSet { if isOn { backVw.layer?.borderColor = fillColor.cgColor } } } /// Change the color of the toggle center @IBInspectable public var toggleColor: NSColor = .white { didSet { circle.bg = toggleColor } } /// Change the background color of the complete toggle (visible when switch is off) @IBInspectable public var backColor: NSColor = .white { didSet { backVw.bg = backColor } } // MARK: Internal //================================================================================ // MARK: Callback //================================================================================ var callback: ((_ isOn: Bool) -> Void)? override func mouseDown(with _: NSEvent) { guard isEnabled else { return } let push = Double(outlineWidth + width) - Double(height) NSAnimationContext.runAnimationGroup { context in context.duration = 0.3 context.allowsImplicitAnimation = true let adjustment = (toggleSize / 4) widthConstraint?.isActive = false widthConstraint = circle.widthAnchor.constraint(equalToConstant: toggleSize + adjustment) widthConstraint?.isActive = true if isOn { leftConstraint?.constant = CGFloat(push) - adjustment } animator().layoutSubtreeIfNeeded() } } override func mouseUp(with _: NSEvent) { guard isEnabled else { return } isOn = !isOn } // MARK: Fileprivate fileprivate var height: CGFloat = 26 fileprivate var leftConstraint: NSLayoutConstraint? fileprivate var heightConstraint: NSLayoutConstraint? fileprivate var widthConstraint: NSLayoutConstraint? fileprivate let backVw: NSView = { let view = NSView() view.wantsLayer = true view.layer?.masksToBounds = false return view }() fileprivate let circle: NSView = { let view = NSView() let shadow = NSShadow() shadow.shadowColor = NSColor.black.withAlphaComponent(0.4) shadow.shadowOffset = CGSize(width: 0, height: -2) shadow.shadowBlurRadius = 2 view.bg = .white view.wantsLayer = true view.shadow = shadow view.layer?.borderWidth = 2 view.layer?.borderColor = NSColor.white.cgColor return view }() fileprivate var _radius: CGFloat? fileprivate var width: CGFloat { height + (height * 0.6) } fileprivate var backRadius: CGFloat { if let r = _radius { return r } return height / 2 } fileprivate var circleRadius: CGFloat { if let r = _radius { return r - outlineWidth } return (height - (outlineWidth * 2)) / 2 } fileprivate var toggleSize: CGFloat { height - (outlineWidth * 2) } //================================================================================ // MARK: Helpers //================================================================================ fileprivate func drawView() { backVw.bg = backColor addSubview(backVw) backVw.translatesAutoresizingMaskIntoConstraints = false backVw.leftAnchor.constraint(equalTo: leftAnchor).isActive = true backVw.widthAnchor.constraint(equalToConstant: width).isActive = true backVw.heightAnchor.constraint(equalToConstant: height).isActive = true addSubview(circle) circle.translatesAutoresizingMaskIntoConstraints = false leftConstraint = circle.leftAnchor.constraint(equalTo: backVw.leftAnchor, constant: outlineWidth) circle.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true widthConstraint = circle.widthAnchor.constraint(equalToConstant: height - (outlineWidth * 2)) heightConstraint = circle.heightAnchor.constraint(equalToConstant: height - (outlineWidth * 2)) leftConstraint?.isActive = true widthConstraint?.isActive = true heightConstraint?.isActive = true translatesAutoresizingMaskIntoConstraints = false rightAnchor.constraint(equalTo: backVw.rightAnchor).isActive = true heightAnchor.constraint(equalToConstant: height).isActive = true layoutSwitch() } fileprivate func layoutSwitch(resetingLayout: Bool = false) { if resetingLayout { leftConstraint?.constant = outlineWidth widthConstraint?.isActive = false widthConstraint = circle.widthAnchor.constraint(equalToConstant: height - (outlineWidth * 2)) widthConstraint?.isActive = true heightConstraint?.isActive = false heightConstraint = circle.heightAnchor.constraint(equalToConstant: height - (outlineWidth * 2)) heightConstraint?.isActive = true layoutSubtreeIfNeeded() } backVw.radius = backRadius.ns backVw.layer?.borderWidth = isOn ? (height / 2) : outlineWidth backVw.layer?.borderColor = outlineColor.cgColor circle.radius = circleRadius.ns } fileprivate func animate() { allowedTouchTypes = [] let push = Double(outlineWidth + width) - Double(height) let callback = self.callback NSAnimationContext.runAnimationGroup({ context in context.duration = 0.3 context.allowsImplicitAnimation = true backVw.animator().layer?.borderWidth = isOn ? (height / 2) : outlineWidth backVw.animator().layer?.borderColor = isOn ? fillColor.cgColor : outlineColor.cgColor widthConstraint?.isActive = false widthConstraint = circle.widthAnchor.constraint(equalToConstant: toggleSize) widthConstraint?.isActive = true leftConstraint?.constant = isOn ? CGFloat(push) : outlineWidth animator().layoutSubtreeIfNeeded() }) { [weak self] in guard let self = self else { return } self.allowedTouchTypes = [.direct, .indirect] callback?(self.isOn) } } }
34.364865
107
0.581695
1d9433153a8a0ad3343806d6e9dbf9e22375a4ea
4,045
import Foundation import CoinKit import RxSwift import RxRelay import EthereumKit import BigInt class SendEvmService { let sendCoin: Coin private let adapter: ISendEthereumAdapter private let stateRelay = PublishRelay<State>() private(set) var state: State = .notReady { didSet { stateRelay.accept(state) } } private var evmAmount: BigUInt? private var addressData: AddressData? private let amountErrorRelay = PublishRelay<Error?>() private var amountError: Error? { didSet { amountErrorRelay.accept(amountError) } } private let addressErrorRelay = PublishRelay<Error?>() private var addressError: Error? { didSet { addressErrorRelay.accept(addressError) } } init(coin: Coin, adapter: ISendEthereumAdapter) { sendCoin = coin self.adapter = adapter } private func syncState() { if amountError == nil, addressError == nil, let evmAmount = evmAmount, let addressData = addressData { let transactionData = adapter.transactionData(amount: evmAmount, address: addressData.evmAddress) let sendInfo = SendEvmData.SendInfo(domain: addressData.domain) let sendData = SendEvmData(transactionData: transactionData, additionalInfo: .send(info: sendInfo)) state = .ready(sendData: sendData) } else { state = .notReady } } private func validEvmAmount(amount: Decimal) throws -> BigUInt { guard let evmAmount = BigUInt(amount.roundedString(decimal: sendCoin.decimal)) else { throw AmountError.invalidDecimal } guard amount <= adapter.balance else { throw AmountError.insufficientBalance } return evmAmount } } extension SendEvmService { var stateObservable: Observable<State> { stateRelay.asObservable() } var amountErrorObservable: Observable<Error?> { amountErrorRelay.asObservable() } } extension SendEvmService: IAvailableBalanceService { var availableBalance: Decimal { adapter.balance } } extension SendEvmService: IAmountInputService { var amount: Decimal { 0 } var coin: Coin? { sendCoin } var balance: Decimal? { adapter.balance } var amountObservable: Observable<Decimal> { .empty() } var coinObservable: Observable<Coin?> { .empty() } func onChange(amount: Decimal) { if amount > 0 { do { evmAmount = try validEvmAmount(amount: amount) amountError = nil } catch { evmAmount = nil amountError = error } } else { evmAmount = nil amountError = nil } syncState() } } extension SendEvmService: IRecipientAddressService { var initialAddress: Address? { nil } var error: Error? { addressError } var errorObservable: Observable<Error?> { addressErrorRelay.asObservable() } func set(address: Address?) { if let address = address, !address.raw.isEmpty { do { addressData = AddressData(evmAddress: try EthereumKit.Address(hex: address.raw), domain: address.domain) addressError = nil } catch { addressData = nil addressError = error.convertedError } } else { addressData = nil addressError = nil } syncState() } func set(amount: Decimal) { // todo } } extension SendEvmService { enum State { case ready(sendData: SendEvmData) case notReady } enum AmountError: Error { case invalidDecimal case insufficientBalance } private struct AddressData { let evmAddress: EthereumKit.Address let domain: String? } }
22.103825
120
0.593572
564579f5549090682847ab21f7cbf63f86d239bf
1,784
// // ModuleVersionTests.swift // VCoreTests // // Created by Vakhtang Kontridze on 17.06.22. // import XCTest @testable import VCore // MARK: - Tests final class ModuleVersionTests: XCTestCase { // MARK: Test Data private let version1: ModuleVersion = .init(string: "1")! private let version2: ModuleVersion = .init(string: "1.0")! private let version3: ModuleVersion = .init(string: "1.0.0")! // MARK: Tests func testStringInit() { XCTAssertNil(ModuleVersion(string: nil)) XCTAssertNil(ModuleVersion(string: "")) XCTAssertNil(ModuleVersion(string: "A")) XCTAssertNil(ModuleVersion(string: "1.0.A")) XCTAssertNil(ModuleVersion(string: "1.0.0.0")) XCTAssertEqual(version1.major, 1) XCTAssertEqual(version1.minor, 0) XCTAssertEqual(version1.patch, nil) XCTAssertEqual(version2.major, 1) XCTAssertEqual(version2.minor, 0) XCTAssertEqual(version2.patch, nil) XCTAssertEqual(version3.major, 1) XCTAssertEqual(version3.minor, 0) XCTAssertEqual(version3.patch, 0) } func testEquatable() { let versions: [ModuleVersion] = [ .init(1, 0), .init(1, 0, 1), .init(1, 0, 2), .init(1, 1), .init(2, 0) ] for i in 0..<versions.count { for j in 0..<versions.count - i - 1 { if i < j { XCTAssertTrue(versions[i] < versions[j]) } } } } func testDescription() { XCTAssertEqual(version1.description, "1.0") XCTAssertEqual(version2.description, "1.0") XCTAssertEqual(version3.description, "1.0.0") } }
28.31746
65
0.566143
2228720bd0ba99ea7a8815af26441fdb3fcda292
1,560
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct SourceControlUpdateParametersData : SourceControlUpdateParametersProtocol { public var properties: SourceControlUpdatePropertiesProtocol? enum CodingKeys: String, CodingKey {case properties = "properties" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.properties) { self.properties = try container.decode(SourceControlUpdatePropertiesData?.self, forKey: .properties) } if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if self.properties != nil {try container.encode(self.properties as! SourceControlUpdatePropertiesData?, forKey: .properties)} } } extension DataFactory { public static func createSourceControlUpdateParametersProtocol() -> SourceControlUpdateParametersProtocol { return SourceControlUpdateParametersData() } }
39
130
0.735256
d5e2a5d9501b7f40166d3163421eb4f6678d1f23
333
// // SelectBasalProfileMessageBody.swift // MinimedKit // // Copyright © 2017 Pete Schwamb. All rights reserved. // import Foundation public class SelectBasalProfileMessageBody: CarelinkLongMessageBody { public convenience init(newProfile: BasalProfile) { self.init(rxData: Data([1, newProfile.rawValue]))! } }
22.2
69
0.732733
e4a69fe90968de7866223cec80778e04fce7375b
3,712
// // Extensions.swift // JSON2SWIFT // // Created by Conrado Mateu Gisbert on 02/03/2018. // Copyright © 2018 conradomateu. All rights reserved. // extension String { var isNumeric: Bool { guard self.count > 0 else { return false } let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "-"] return Set(self).isSubset(of: nums) } var cleaned: String { return self.replacingOccurrences(of: "\t", with: "") .replacingOccurrences(of: "\"", with: "") .replacingOccurrences(of: "\n", with: "") .replacingOccurrences(of: ",", with: "") .replacingOccurrences(of: " ", with: "") } var firsLetterCapitalized: String { return prefix(1).uppercased() + dropFirst() } func cleanValue() -> String { var res = self.replacingOccurrences(of: "\t", with: "") .replacingOccurrences(of: "\n", with: "") .replacingOccurrences(of: "##isArray##", with: "") if res.last == " " { res = String(res.dropLast()) } if res.last == "," { res = String(res.dropLast()) } return res } func cleanObject() -> String { var res = self.replacingOccurrences(of: "\t", with: "") .replacingOccurrences(of: "\n", with: "") return res } func cleanFirstBrace() -> String{ return self.stringByReplacingLastOccurrenceOfString(target: "}\n", withString: "") .stringByReplacingFirstOccurrenceOfString(target: "{\n", withString: "") } func firstKeyCleaned() -> String{ return self.stringByReplacingLastOccurrenceOfString(target: ":", withString: "") .replacingOccurrences(of: " ", with: "") } func cleanArrayValue() -> String{ return self.stringByReplacingFirstOccurrenceOfString(target: ": [", withString: "") .stringByReplacingLastOccurrenceOfString(target: "]", withString: "") } func cleanBrackets() -> String{ return self.stringByReplacingFirstOccurrenceOfString(target: "[", withString: "") .stringByReplacingLastOccurrenceOfString(target: "]", withString: "") } func cleanBraces() -> String{ return self.stringByReplacingFirstOccurrenceOfString(target: "{", withString: "") .stringByReplacingLastOccurrenceOfString(target: "}", withString: "") } func cleanObjectValue() -> String { return self.stringByReplacingFirstOccurrenceOfString(target: ": {", withString: "") .stringByReplacingLastOccurrenceOfString(target: "}", withString: "") } func stringByReplacingLastOccurrenceOfString( target: String, withString replaceString: String) -> String { if let range = self.range(of: target, options: [.backwards]) { return self.replacingCharacters(in: range, with: replaceString) } return self } func stringByReplacingFirstOccurrenceOfString( target: String, withString replaceString: String) -> String { if let range = self.range(of: target) { return self.replacingCharacters(in: range, with: replaceString) } return self } func toBool() -> Bool? { switch self { case "True", "true", "yes", "1": return true case "False", "false", "no", "0": return false default: return nil } } func isBool() -> Bool { if let _ = self.toBool() { return true } else { return false } } func isObject() -> Bool { return self == Primitives.object.rawValue } }
30.933333
95
0.576239
9c690b121d42bc928c8ccc3976c8d1e1ae210ff2
3,910
// // Forecast.swift // RainyShinyCloudy // // Created by David Sternheim on 8/5/17. // Copyright © 2017 David Sternheim. All rights reserved. // import UIKit import Alamofire class Forecast{ var _date: String! var _weatherType: String! var _highTemp: String! var _lowTemp: String! var forecasts = [Forecast]() var date: String{ if _date == nil{ _date = "" } return _date } var weatherType: String{ if _weatherType == nil { _weatherType = "" } return _weatherType } var highTemp: String{ if _highTemp == nil{ _highTemp = "" } return _highTemp } var lowTemp: String{ if _lowTemp == nil { _lowTemp = "" } return _lowTemp } init(){ } init(weatherDict: Dictionary<String, AnyObject>) { if let temp = weatherDict["temp"] as? Dictionary<String, AnyObject>{ if let min = temp["min"] as? Double{ let kelvinToFahrenheitPreDiv = (min * (9/5) - 459.67) let kelvinToFahrenheit = Double(round(10 * kelvinToFahrenheitPreDiv/10)) self._lowTemp = "\(kelvinToFahrenheit)" } if let max = temp["max"] as? Double{ let kelvinToFahrenheitPreDiv = (max * (9/5) - 459.67) let kelvinToFahrenheit = Double(round(10 * kelvinToFahrenheitPreDiv/10)) self._highTemp = "\(kelvinToFahrenheit)" } if let weather = weatherDict["weather"] as? [Dictionary<String, AnyObject>]{ if let main = weather[0]["main"] as? String { self._weatherType = main.capitalized } } if let date = weatherDict["dt"] as? Double{ let unixConvertedDate = Date(timeIntervalSince1970: date) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full dateFormatter.dateFormat = "EEEE" dateFormatter.timeStyle = .none self._date = unixConvertedDate.dayOfTheWeek() } } } func getForecastArray() -> [Forecast]{ return forecasts } func downloadForecastData(completed:@escaping DownloadComplete){ //Downloads the forecast data to be placed in the TableView let forecastURL = URL(string: FORECAST_URL)! Alamofire.request(forecastURL).responseJSON{ response in let result = response.result if let dict = result.value as? Dictionary<String, AnyObject>{ if let list = dict["list"] as? [Dictionary<String, AnyObject>]{ var count = 0 for obj in list{ if count > 0{ let forecast = Forecast(weatherDict: obj) self.forecasts.append(forecast) print(obj) } count += 1 } } completed() } //self.forecasts.removeFirst() completed() } } } extension Date { func dayOfTheWeek() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE" return dateFormatter.string(from: self) } }
25.89404
88
0.459335