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
5093e158e60f5e62ffb71c21b2c1c2a3aea96569
1,312
// // Copyright © 2020 NHSX. All rights reserved. // import Combine import Foundation class ExperimentJoiner: ObservableObject, Identifiable { private var cancellables = [AnyCancellable]() @Published private(set) var isCreatingExperiment = false @Published private(set) var error: Error? init() {} func joinExperiment(storeIn experimentManager: ExperimentManager, complete: @escaping () -> Void) { isCreatingExperiment = true error = nil cancellables.append( experimentManager.exposureManager .enabledManager() .flatMap { experimentManager.joinExperiment(manager: $0) } .receive(on: RunLoop.main) .sink( receiveCompletion: { completion in switch completion { case .finished: complete() case .failure(let error): self.error = error } self.isCreatingExperiment = false }, receiveValue: { experiment in experimentManager.set(experiment) } ) ) } }
28.521739
103
0.500762
bf73bcafadd87114dcf7b0cf6f2a5afaff0eb466
2,205
// // AppDelegate.swift // GraphView iOS // // Created by Vegard Solheim Theriault on 29/08/2017. // Copyright © 2017 Vegard Solheim Theriault. 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.914894
285
0.75737
bf503bf2849690d446b38b14684e7f080c57ba3d
1,221
// // JTSCalendarScrollManager.swift // JTCalendarSwift // // Created by 刘振兴 on 2018/1/7. // Copyright © 2018年 zoneland. All rights reserved. // import UIKit open class JTSCalendarScrollManager:NSObject { weak var manager:JTSCalendarManager? weak var menuView:JTSCalendarMenuView? weak var horizontalContentView:JTSHorizontalCalendarView? func setMenuPreviousDate(previousDate:Date,currentDate:Date,nextDate:Date){ if menuView == nil { return } menuView?.setPreviousDate(previousDate: previousDate, currentDate: currentDate, nextDate: nextDate) } func updateMenuContentOffset(percentage:CGFloat,pageMode:JTSCalendarPageMode){ if menuView == nil { return } menuView?.updatePageMode(pageMode: pageMode) menuView?.scrollView?.contentOffset = CGPoint(x: percentage * (menuView?.scrollView?.contentSize.width)!, y: 0) } func updateHorizontalContentOffset(percentage:CGFloat){ if horizontalContentView == nil { return } horizontalContentView?.contentOffset = CGPoint(x: percentage * (horizontalContentView?.contentSize.width)!, y: 0) } }
29.780488
121
0.679771
1c17e17e0417753d3b3adc8231f2c5516c2b6334
2,060
// // LYGradientView.swift // LYGradientView // // Created by 阿卡丽 on 2019/12/25. // import UIKit /// 渐变的view,方便使用而已 open class LYGradientView: UIView { open var colors: [UIColor]? { get { guard let cgColors = gLayer.colors as? [CGColor] else { return nil } return cgColors.map { (cgColor) -> UIColor in return UIColor.init(cgColor: cgColor) } } set { guard let colors = newValue else { gLayer.colors = nil return } gLayer.colors = colors.map({ (color) -> CGColor in return color.cgColor }) } } /// [0,1] open var locations: [Double]? { get { guard let gLocations = gLayer.locations else { return nil } return gLocations.map { (number) -> Double in return number.doubleValue } } set { guard let locations = newValue else { gLayer.locations = nil return } gLayer.locations = locations.map({ (doubleValue) -> NSNumber in return NSNumber(value: doubleValue) }) } } open var startPoint: CGPoint { get { return gLayer.startPoint } set { gLayer.startPoint = newValue } } open var endPoint: CGPoint { get { return gLayer.endPoint } set { gLayer.endPoint = newValue } } public let gLayer = CAGradientLayer() public override init(frame: CGRect) { super.init(frame: frame) layer.addSublayer(gLayer) } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() gLayer.frame = layer.bounds } }
22.888889
75
0.484466
1a09f99df42f6ff72568e7bdf045842e4702e706
23,275
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Basic import PackageLoading import PackageModel @testable import PackageGraph import SourceControl public typealias _MockPackageConstraint = PackageContainerConstraint<PackageReference> public class _MockPackageContainer: PackageContainer { public typealias Identifier = PackageReference public typealias Dependency = (container: Identifier, requirement: PackageRequirement) let name: Identifier let dependencies: [String: [Dependency]] public var unversionedDeps: [_MockPackageConstraint] = [] /// Contains the versions for which the dependencies were requested by resolver using getDependencies(). public var requestedVersions: Set<Version> = [] public var identifier: Identifier { return name } public let _versions: [Version] public func versions(filter isIncluded: (Version) -> Bool) -> AnySequence<Version> { return AnySequence(_versions.filter(isIncluded)) } public func getDependencies(at version: Version) -> [_MockPackageConstraint] { requestedVersions.insert(version) return getDependencies(at: version.description) } public func getDependencies(at revision: String) -> [_MockPackageConstraint] { return dependencies[revision]!.map({ value in let (name, requirement) = value return _MockPackageConstraint(container: name, requirement: requirement) }) } public func getUnversionedDependencies() -> [_MockPackageConstraint] { return unversionedDeps } public func getUpdatedIdentifier(at boundVersion: BoundVersion) throws -> PackageReference { return name } public convenience init( name: Identifier, dependenciesByVersion: [Version: [(container: Identifier, versionRequirement: VersionSetSpecifier)]] ) { var dependencies: [String: [Dependency]] = [:] for (version, deps) in dependenciesByVersion { dependencies[version.description] = deps.map({ ($0.container, .versionSet($0.versionRequirement)) }) } self.init(name: name, dependencies: dependencies) } public init( name: Identifier, dependencies: [String: [Dependency]] = [:] ) { self.name = name let versions = dependencies.keys.compactMap(Version.init(string:)) self._versions = versions.sorted().reversed() self.dependencies = dependencies } } public enum _MockLoadingError: Error { case unknownModule } public struct _MockPackageProvider: PackageContainerProvider { public typealias Container = _MockPackageContainer public let containers: [Container] public let containersByIdentifier: [Container.Identifier: Container] public init(containers: [_MockPackageContainer]) { self.containers = containers self.containersByIdentifier = Dictionary(items: containers.map({ ($0.identifier, $0) })) } public func getContainer( for identifier: Container.Identifier, skipUpdate: Bool, completion: @escaping (Result<Container, AnyError> ) -> Void) { DispatchQueue.global().async { completion(self.containersByIdentifier[identifier].map(Result.init) ?? Result(_MockLoadingError.unknownModule)) } } } public class _MockResolverDelegate: DependencyResolverDelegate { public typealias Identifier = _MockPackageContainer.Identifier public init() {} var traceSteps: [TraceStep] = [] public func trace(_ step: TraceStep) { traceSteps.append(step) } func traceDescription() -> String { let headers = ["Step", "Value", "Type", "Location", "Cause", "Dec. Lvl."] let values = traceSteps.enumerated().map { val -> [String] in let (idx, s) = val return [ "\(idx + 1)", s.value.description, s.type.rawValue, s.location.rawValue, s.cause ?? "", String(s.decisionLevel) ] } return textTable([headers] + values) } func textTable(_ data: [[String]]) -> String { guard let firstRow = data.first, !firstRow.isEmpty else { return "" } func maxWidth(_ array: [String]) -> Int { guard let maxElement = array.max(by: { $0.count < $1.count }) else { return 0 } return maxElement.count } func pad(_ string: String, _ padding: Int) -> String { let padding = padding - (string.count - 1) guard padding >= 0 else { return string } return " " + string + Array(repeating: " ", count: padding).joined() } var columns = [[String]]() for i in 0..<firstRow.count { columns.append(data.map { $0[i] }) } let dividerLine = columns .map { Array(repeating: "-", count: maxWidth($0) + 2).joined() } .reduce("+") { $0 + $1 + "+" } return data .reduce([dividerLine]) { result, row -> [String] in let rowString = zip(row, columns) .map { pad(String(describing: $0), maxWidth($1)) } .reduce("|") { $0 + $1 + "|" } return result + [rowString, dividerLine]} .joined(separator: "\n") } } private let emptyProvider = _MockPackageProvider(containers: []) private let delegate = _MockResolverDelegate() private let v1: Version = "1.0.0" private let v1_1: Version = "1.1.0" private let v2: Version = "2.0.0" private let v0_0_0Range: VersionSetSpecifier = .range("0.0.0" ..< "0.0.1") private let v1Range: VersionSetSpecifier = .range("1.0.0" ..< "2.0.0") private let v1to3Range: VersionSetSpecifier = .range("1.0.0" ..< "3.0.0") private let v2Range: VersionSetSpecifier = .range("2.0.0" ..< "3.0.0") private let v1_to_3Range: VersionSetSpecifier = .range("1.0.0" ..< "3.0.0") private let v2_to_4Range: VersionSetSpecifier = .range("2.0.0" ..< "4.0.0") private let v1_0Range: VersionSetSpecifier = .range("1.0.0" ..< "1.1.0") private let v1_1Range: VersionSetSpecifier = .range("1.1.0" ..< "1.2.0") private let v1_1_0Range: VersionSetSpecifier = .range("1.1.0" ..< "1.1.1") private let v2_0_0Range: VersionSetSpecifier = .range("2.0.0" ..< "2.0.1") let aRef = PackageReference(identity: "a", path: "") let bRef = PackageReference(identity: "b", path: "") let rootRef = PackageReference(identity: "root", path: "") let rootCause = Incompatibility(Term(rootRef, .versionSet(.exact("1.0.0")))) let _cause = Incompatibility<PackageReference>("[email protected]") fileprivate func term(_ literal: String) -> Term<PackageReference> { return Term(stringLiteral: literal) } final class PubgrubTests: XCTestCase { func testTermInverse() { let a = term("[email protected]") XCTAssertFalse(a.inverse.isPositive) XCTAssertTrue(a.inverse.inverse.isPositive) } func testTermSatisfies() { let a100 = term("[email protected]") XCTAssertTrue(a100.satisfies(a100)) XCTAssertFalse(a100.satisfies("¬[email protected]")) XCTAssertTrue(a100.satisfies("a^1.0.0")) XCTAssertFalse(a100.satisfies("¬a^1.0.0")) XCTAssertFalse(a100.satisfies("a^2.0.0")) XCTAssertFalse(a100.satisfies(Term(bRef, .unversioned))) XCTAssertTrue(term("¬[email protected]").satisfies("¬a^1.0.0")) XCTAssertTrue(term("¬[email protected]").satisfies("a^2.0.0")) XCTAssertTrue(term("a^1.0.0").satisfies("¬[email protected]")) XCTAssertTrue(term("a^1.0.0").satisfies("¬a^2.0.0")) XCTAssertTrue(term("a^1.0.0").satisfies(term("a^1.0.0"))) XCTAssertTrue(term("a-1.0.0-1.1.0").satisfies(term("a^1.0.0"))) XCTAssertFalse(term("a-1.0.0-1.1.0").satisfies(term("a^2.0.0"))) XCTAssertTrue( Term(aRef, .revision("ab")).satisfies( Term(aRef, .revision("ab")))) XCTAssertFalse( Term(aRef, .revision("ab")).satisfies( Term(aRef, .revision("ba")))) } func testTermIntersection() { // a^1.0.0 ∩ ¬[email protected] → a >=1.0.0 <1.5.0 XCTAssertEqual( term("a^1.0.0").intersect(with: term("¬[email protected]")), term("a-1.0.0-1.5.0")) // a^1.0.0 ∩ a >=1.5.0 <3.0.0 → a^1.5.0 XCTAssertEqual( term("a^1.0.0").intersect(with: term("a-1.5.0-3.0.0")), term("a^1.5.0")) // ¬a^1.0.0 ∩ ¬a >=1.5.0 <3.0.0 → ¬a >=1.0.0 <3.0.0 XCTAssertEqual( term("¬a^1.0.0").intersect(with: term("¬a-1.5.0-3.0.0")), term("¬a-1.0.0-3.0.0")) } func testTermIsValidDecision() { let solution100_150 = PartialSolution(assignments: [ .derivation("a^1.0.0", cause: _cause, decisionLevel: 1), .derivation("a^1.5.0", cause: _cause, decisionLevel: 2) ]) let allSatisfied = term("[email protected]") XCTAssertTrue(allSatisfied.isValidDecision(for: solution100_150)) let partiallySatisfied = term("[email protected]") XCTAssertFalse(partiallySatisfied.isValidDecision(for: solution100_150)) } func testIncompatibilityNormalizeTermsOnInit() { let i = Incompatibility(term("a^1.0.0"), term("a^1.5.0"), term("¬[email protected]")) XCTAssertEqual(i.terms.count, 2) let a = i.terms.first { $0.package == "a" } let b = i.terms.first { $0.package == "b" } XCTAssertEqual(a?.requirement, .versionSet(.range("1.5.0"..<"2.0.0"))) XCTAssertEqual(b?.requirement, .versionSet(.exact("1.0.0"))) } func testSolutionPositive() { let s1 = PartialSolution(assignments:[ .derivation("a^1.5.0", cause: _cause, decisionLevel: 0), .derivation("[email protected]", cause: _cause, decisionLevel: 0), .derivation("a^1.0.0", cause: _cause, decisionLevel: 0) ]) let a1 = s1.positive.first { $0.key.identity == "a" }?.value XCTAssertEqual(a1?.requirement, .versionSet(.range("1.5.0"..<"2.0.0"))) let b1 = s1.positive.first { $0.key.identity == "b" }?.value XCTAssertEqual(b1?.requirement, .versionSet(.exact("2.0.0"))) let s2 = PartialSolution<PackageReference>(assignments: [ .derivation("¬a^1.5.0", cause: _cause, decisionLevel: 0), .derivation("a^1.0.0", cause: _cause, decisionLevel: 0) ]) let a2 = s2.positive.first { $0.key.identity == "a" }?.value XCTAssertEqual(a2?.requirement, .versionSet(.range("1.0.0"..<"1.5.0"))) } func testSolutionUndecided() { let solution = PartialSolution<PackageReference>(assignments: [ .derivation("a^1.5.0", cause: rootCause, decisionLevel: 0), .decision("[email protected]", decisionLevel: 0), .derivation("a^1.0.0", cause: rootCause, decisionLevel: 0) ]) XCTAssertEqual(solution.undecided, [term("a^1.5.0")]) } func testSolutionSatisfiesIncompatibility() { let s1 = PartialSolution<PackageReference>(assignments: [ .decision("[email protected]", decisionLevel: 0) ]) XCTAssertEqual(s1.satisfies(Incompatibility("[email protected]")), .satisfied) let s2 = PartialSolution<PackageReference>(assignments: [ .decision("[email protected]", decisionLevel: 0) ]) XCTAssertEqual(s2.satisfies(Incompatibility("¬[email protected]", "[email protected]")), .almostSatisfied(except: "¬[email protected]")) let s3 = PartialSolution<PackageReference>(assignments: [ .decision("[email protected]", decisionLevel: 0) ]) XCTAssertEqual(s3.satisfies(Incompatibility("¬[email protected]", "[email protected]")), .unsatisfied) let s4 = PartialSolution<PackageReference>(assignments: []) XCTAssertEqual(s4.satisfies(Incompatibility("[email protected]")), .unsatisfied) let s5 = PartialSolution<PackageReference>(assignments: [ .decision("[email protected]", decisionLevel: 0), .decision("[email protected]", decisionLevel: 0), .decision("[email protected]", decisionLevel: 0) ]) XCTAssertEqual(s5.satisfies(Incompatibility("[email protected]", "[email protected]")), .satisfied) } func testSolutionAddAssignments() { let a = term("[email protected]") let b = term("[email protected]") let solution = PartialSolution<PackageReference>(assignments: []) solution.decide(aRef, atExactVersion: "1.0.0") solution.derive(b, cause: _cause) XCTAssertEqual(solution.decisionLevel, 1) XCTAssertEqual(solution.assignments, [ .decision(a, decisionLevel: 0), .derivation(b, cause: _cause, decisionLevel: 1) ]) } func testSolutionFindSatisfiers() { let s3 = PartialSolution<PackageReference>(assignments: [ .decision("[email protected]", decisionLevel: 0), .decision("[email protected]", decisionLevel: 0), .decision("[email protected]", decisionLevel: 0) ]) let ac = Incompatibility<PackageReference>("[email protected]", "[email protected]") let (previous1, satisfier1) = s3.earliestSatisfiers(for: ac) XCTAssertEqual(previous1!.term, "[email protected]") XCTAssertEqual(satisfier1!.term, "[email protected]") let s2 = PartialSolution<PackageReference>(assignments: [ .decision("[email protected]", decisionLevel: 0), .decision("[email protected]", decisionLevel: 0) ]) let ab = Incompatibility<PackageReference>("[email protected]", "[email protected]") let (previous2, satisfier2) = s2.earliestSatisfiers(for: ab) XCTAssertEqual(previous2!.term, "[email protected]") XCTAssertEqual(satisfier2!.term, "[email protected]") let s1 = PartialSolution<PackageReference>(assignments: [ .decision("[email protected]", decisionLevel: 0) ]) let a = Incompatibility<PackageReference>("[email protected]") let (previous3, satisfier3) = s1.earliestSatisfiers(for: a) XCTAssertEqual(previous3!.term, "[email protected]") XCTAssertEqual(previous3, satisfier3) } func testSolutionBacktrack() { let solution = PartialSolution<PackageReference>(assignments: [ .decision("[email protected]", decisionLevel: 1), .decision("[email protected]", decisionLevel: 2), .decision("[email protected]", decisionLevel: 3), ]) XCTAssertEqual(solution.decisionLevel, 3) solution.backtrack(toDecisionLevel: 1) XCTAssertEqual(solution.assignments.count, 1) XCTAssertEqual(solution.decisionLevel, 1) } func testSolutionVersionIntersection() { let s1 = PartialSolution(assignments: [ .derivation("a^1.0.0", cause: _cause, decisionLevel: 0), ]) XCTAssertEqual(s1.versionIntersection(for: "a")?.requirement, .versionSet(.range("1.0.0"..<"2.0.0"))) let s2 = PartialSolution(assignments: [ .derivation("a^1.0.0", cause: _cause, decisionLevel: 0), .derivation("a^1.5.0", cause: _cause, decisionLevel: 0) ]) XCTAssertEqual(s2.versionIntersection(for: "a")?.requirement, .versionSet(.range("1.5.0"..<"2.0.0"))) } func testResolverAddIncompatibility() { let solver = PubgrubDependencyResolver(emptyProvider, delegate) let a = Incompatibility(term("[email protected]")) solver.add(a, location: .topLevel) let ab = Incompatibility(term("[email protected]"), term("[email protected]")) solver.add(ab, location: .topLevel) XCTAssertEqual(solver.incompatibilities, [ "a": [a, ab], "b": [ab], ]) } func testResolverUnitPropagation() { let solver1 = PubgrubDependencyResolver(emptyProvider, delegate) // no known incompatibilities should result in no satisfaction checks XCTAssertNil(solver1.propagate("root")) // even if incompatibilities are present solver1.add(Incompatibility(term("[email protected]")), location: .topLevel) XCTAssertNil(solver1.propagate("a")) // adding a satisfying term should result in a conflict solver1.solution.decide(aRef, atExactVersion: "1.0.0") XCTAssertEqual(solver1.propagate(aRef), Incompatibility(term("[email protected]"))) // Unit propagation should derive a new assignment from almost satisfied incompatibilities. let solver2 = PubgrubDependencyResolver(emptyProvider, delegate) solver2.add(Incompatibility(Term("root", .versionSet(.any)), term("¬[email protected]")), location: .topLevel) solver2.solution.decide(rootRef, atExactVersion: "1.0.0") XCTAssertEqual(solver2.solution.assignments.count, 1) XCTAssertNil(solver2.propagate(PackageReference(identity: "root", path: ""))) XCTAssertEqual(solver2.solution.assignments.count, 2) } func testResolverConflictResolution() { let solver1 = PubgrubDependencyResolver(emptyProvider, delegate) solver1.root = rootRef let notRoot = Incompatibility(Term(not: rootRef, .versionSet(.any)), cause: .root) solver1.add(notRoot, location: .topLevel) XCTAssertNil(solver1.resolve(conflict: notRoot)) } func testResolverDecisionMaking() { let solver1 = PubgrubDependencyResolver(emptyProvider, delegate) solver1.root = rootRef // No decision can be made if no unsatisfied terms are available. XCTAssertNil(try solver1.makeDecision()) let a = _MockPackageContainer(name: aRef, dependenciesByVersion: [ v1: [(container: bRef, versionRequirement: v1Range)] ]) let provider = _MockPackageProvider(containers: [a]) let solver2 = PubgrubDependencyResolver(provider, delegate) solver2.root = rootRef let solution = PartialSolution(assignments: [ .derivation("a^1.0.0", cause: rootCause, decisionLevel: 0) ]) solver2.solution = solution XCTAssertEqual(solver2.incompatibilities.count, 0) let decision = try! solver2.makeDecision() XCTAssertEqual(decision, "a") XCTAssertEqual(solver2.incompatibilities.count, 2) XCTAssertEqual(solver2.incompatibilities["a"], [Incompatibility<PackageReference>("a^1.0.0", "¬b^1.0.0", cause: .dependency(package: "a"))]) } func testResolutionNoConflicts() { let root = _MockPackageContainer(name: rootRef) root.unversionedDeps = [_MockPackageConstraint(container: aRef, versionRequirement: v1Range)] let a = _MockPackageContainer(name: aRef, dependenciesByVersion: [ v1: [(container: bRef, versionRequirement: v1Range)] ]) let b = _MockPackageContainer(name: bRef, dependenciesByVersion: [ v1: [], v2: [] ]) let provider = _MockPackageProvider(containers: [root, a, b]) let resolver = PubgrubDependencyResolver(provider, delegate) let result = resolver.solve(root: rootRef, pins: []) switch result { case .success(let bindings): XCTAssertEqual(bindings.count, 2) let a = bindings.first { $0.container.identity == "a" } let b = bindings.first { $0.container.identity == "b" } XCTAssertEqual(a?.binding, .version("1.0.0")) XCTAssertEqual(b?.binding, .version("1.0.0")) case .error(let error): XCTFail("Unexpected error: \(error)") case .unsatisfiable(dependencies: let constraints, pins: let pins): XCTFail("Unexpectedly unsatisfiable with dependencies: \(constraints) and pins: \(pins)") } } func testResolutionAvoidingConflictResolutionDuringDecisionMaking() { let root = _MockPackageContainer(name: rootRef) root.unversionedDeps = [ _MockPackageConstraint(container: aRef, versionRequirement: v1Range), _MockPackageConstraint(container: bRef, versionRequirement: v1Range) ] let a = _MockPackageContainer(name: aRef, dependenciesByVersion: [ v1: [], v1_1: [(container: bRef, versionRequirement: v2Range)] ]) let b = _MockPackageContainer(name: bRef, dependenciesByVersion: [ v1: [], v1_1: [], v2: [] ]) let provider = _MockPackageProvider(containers: [root, a, b]) let resolver = PubgrubDependencyResolver(provider, delegate) let result = resolver.solve(root: rootRef, pins: []) switch result { case .success(let bindings): XCTAssertEqual(bindings.count, 2) let a = bindings.first { $0.container.identity == "a" } let b = bindings.first { $0.container.identity == "b" } XCTAssertEqual(a?.binding, .version("1.0.0")) XCTAssertEqual(b?.binding, .version("1.1.0")) case .error(let error): XCTFail("Unexpected error: \(error)") case .unsatisfiable(dependencies: let constraints, pins: let pins): XCTFail("Unexpectedly unsatisfiable with dependencies: \(constraints) and pins: \(pins)") } } } extension Term: ExpressibleByStringLiteral { public init(stringLiteral value: String) { var value = value var isPositive = true if value.hasPrefix("¬") { value.removeFirst() isPositive = false } var components: [String] = [] var requirement: Requirement if value.contains("@") { components = value.split(separator: "@").map(String.init) requirement = .versionSet(.exact(Version(stringLiteral: components[1]))) } else if value.contains("^") { components = value.split(separator: "^").map(String.init) let upperMajor = Int(String(components[1].split(separator: ".").first!))! + 1 requirement = .versionSet(.range(Version(stringLiteral: components[1])..<Version(stringLiteral: "\(upperMajor).0.0"))) } else if value.contains("-") { components = value.split(separator: "-").map(String.init) assert(components.count == 3, "expected `name-lowerBound-upperBound`") let (lowerBound, upperBound) = (components[1], components[2]) requirement = .versionSet(.range(Version(stringLiteral: lowerBound)..<Version(stringLiteral: upperBound))) } else { fatalError("Unrecognized format") } let packageReference: Identifier = PackageReference(identity: components[0], path: "") as! Identifier self.init(package: packageReference, requirement: requirement, isPositive: isPositive) } } extension PackageReference: ExpressibleByStringLiteral { public init(stringLiteral value: String) { let ref = PackageReference(identity: value.lowercased(), path: "") self = ref } }
38.344316
148
0.610011
201ccf43cb48bc7561379a162070474929e193b0
210
import Foundation import UIKit import PlaygroundSupport public func showWelcomeScreen() { PlaygroundPage.current.liveView = WelcomeViewController() PlaygroundPage.current.needsIndefiniteExecution = true }
23.333333
59
0.838095
d90eb41f78b7175f9e218b0e5b0201dd75372943
4,134
import Foundation import Metrics import BSON import MongoCore import NIO extension MongoConnection { public func executeCodable<E: Encodable>( _ command: E, namespace: MongoNamespace, in transaction: MongoTransaction? = nil, sessionId: SessionIdentifier? ) -> EventLoopFuture<MongoServerReply> { do { let request = try BSONEncoder().encode(command) return execute(request, namespace: namespace) } catch { self.logger.error("Unable to encode MongoDB request") return eventLoop.makeFailedFuture(error) } } public func execute( _ command: Document, namespace: MongoNamespace, in transaction: MongoTransaction? = nil, sessionId: SessionIdentifier? = nil ) -> EventLoopFuture<MongoServerReply> { let result: EventLoopFuture<MongoServerReply> if let serverHandshake = serverHandshake, serverHandshake.maxWireVersion.supportsOpMessage { result = executeOpMessage(command, namespace: namespace) } else { result = executeOpQuery(command, namespace: namespace) } if let queryTimer = queryTimer { let date = Date() result.whenComplete { _ in queryTimer.record(-date.timeIntervalSinceNow) } } return result } public func executeOpQuery( _ query: inout OpQuery, in transaction: MongoTransaction? = nil, sessionId: SessionIdentifier? = nil ) -> EventLoopFuture<OpReply> { query.header.requestId = nextRequestId() return executeMessage(query).flatMapThrowing { reply in guard case .reply(let reply) = reply else { self.logger.error("Unexpected reply type, expected OpReply") throw MongoError(.queryFailure, reason: .invalidReplyType) } return reply } } public func executeOpMessage( _ query: inout OpMessage, in transaction: MongoTransaction? = nil, sessionId: SessionIdentifier? = nil ) -> EventLoopFuture<OpMessage> { query.header.requestId = nextRequestId() return executeMessage(query).flatMapThrowing { reply in guard case .message(let message) = reply else { self.logger.error("Unexpected reply type, expected OpMessage") throw MongoError(.queryFailure, reason: .invalidReplyType) } return message } } internal func executeOpQuery( _ command: Document, namespace: MongoNamespace, sessionId: SessionIdentifier? = nil ) -> EventLoopFuture<MongoServerReply> { var command = command if let id = sessionId?.id { command["lsid"]["id"] = id } return executeMessage( OpQuery( query: command, requestId: nextRequestId(), fullCollectionName: namespace.fullCollectionName ) ) } internal func executeOpMessage( _ command: Document, namespace: MongoNamespace, in transaction: MongoTransaction? = nil, sessionId: SessionIdentifier? = nil ) -> EventLoopFuture<MongoServerReply> { var command = command command["$db"] = namespace.databaseName if let id = sessionId?.id { command["lsid"]["id"] = id } // TODO: When retrying a write, don't resend transaction messages except commit & abort if let transaction = transaction { command["txnNumber"] = transaction.number command["autocommit"] = transaction.autocommit if transaction.startTransaction { command["startTransaction"] = true } } return executeMessage( OpMessage( body: command, requestId: self.nextRequestId() ) ) } }
31.082707
95
0.577891
e2248398b0f53cc0641cea785dfe55e2741537d7
231
// // ExampleProtocol.swift // SwiftExample // // Created by qddios2 on 17/3/21. // Copyright © 2017年 lvguifeng. All rights reserved. // import Foundation @objc protocol XXXXXX { static func URLDefProtocol() -> String }
14.4375
53
0.688312
09c382cea35f3c0d6a6d7def5ded885d4dac0bf7
8,854
// // AlphaBeta.swift // AIToolbox // // Created by Kevin Coble on 2/23/15. // Copyright (c) 2015 Kevin Coble. All rights reserved. // Converted to Swift 4.2 by Maxim Vasin, 01.07.2019 import Foundation /// The AlphaBetaNode protocol is used to provide move generation and static evaluation routines to your node public protocol AlphaBetaNode { func generateMoves(_ forMaximizer: Bool) -> [AlphaBetaNode] // Get the nodes for each move below this node func staticEvaluation() -> Double // Evaluate the worth of this node } open class AlphaBetaGraph { public init() { } open func startAlphaBetaWithNode(_ startNode: AlphaBetaNode, forDepth: Int, startingAsMaximizer : Bool = true) -> AlphaBetaNode? { // Start the recursion let α = -Double.infinity let β = Double.infinity return alphaBeta(startNode, remainingDepth: forDepth, alpha: α, beta : β, maximizer: startingAsMaximizer, topLevel: true).winningNode } func alphaBeta(_ currentNode: AlphaBetaNode, remainingDepth: Int, alpha : Double, beta : Double, maximizer: Bool, topLevel : Bool) -> (value: Double, winningNode: AlphaBetaNode?) { // if this is a leaf node, return the static evaluation if (remainingDepth == 0) { return (value: currentNode.staticEvaluation(), winningNode: currentNode) } let nextDepth = remainingDepth - 1 // Generate the child nodes let children = currentNode.generateMoves(maximizer) // If no children, return the static evaluation for this node if (children.count == 0) { return (value: currentNode.staticEvaluation(), winningNode: currentNode) } if (topLevel && children.count == 1) { // Only one move, so we must take it - no reason to evaluate actual values return (value: 0.0, winningNode: children[0]) } var winningNode : AlphaBetaNode? var α = alpha var β = beta // If the maximizer, maximize the alpha, and prune with the beta if (maximizer) { var value = -Double.infinity // Iterate through the child nodes for child in children { let childValue = alphaBeta(child, remainingDepth: nextDepth, alpha: α, beta: β, maximizer: false, topLevel: false).value if (childValue > value) { value = childValue winningNode = child } value = childValue > value ? childValue : value α = value > α ? value : α if (β <= α) { // β pruning break } } return (value: value, winningNode: winningNode) } // If the minimizer, maximize the beta, and prune with the alpha else { var value = Double.infinity // Iterate through the child nodes for child in children { let childValue = alphaBeta(child, remainingDepth: nextDepth, alpha: α, beta: β, maximizer: true, topLevel: false).value if (childValue < value) { value = childValue winningNode = child } β = value < β ? value : β if (β <= α) { // α pruning break } } return (value: value, winningNode: winningNode) } } open func startAlphaBetaConcurrentWithNode(_ startNode: AlphaBetaNode, forDepth: Int, startingAsMaximizer : Bool = true) -> AlphaBetaNode? { // Start the recursion let α = -Double.infinity let β = Double.infinity return alphaBetaConcurrent(startNode, remainingDepth: forDepth, alpha: α, beta : β, maximizer: startingAsMaximizer, topLevel: true).winningNode } func alphaBetaConcurrent(_ currentNode: AlphaBetaNode, remainingDepth: Int, alpha : Double, beta : Double, maximizer: Bool, topLevel : Bool) -> (value: Double, winningNode: AlphaBetaNode?) { // if this is a leaf node, return the static evaluation if (remainingDepth == 0) { return (value: currentNode.staticEvaluation(), winningNode: currentNode) } let nextDepth = remainingDepth - 1 // Generate the child nodes let children = currentNode.generateMoves(maximizer) // If no children, return the static evaluation for this node if (children.count == 0) { return (value: currentNode.staticEvaluation(), winningNode: currentNode) } if (topLevel && children.count == 1) { // Only one move, so we must take it - no reason to evaluate actual values return (value: 0.0, winningNode: children[0]) } // Create the value array var childValues : [Double] = Array(repeating: 0.0, count: children.count) // Get the concurrent queue and group let tQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default) let tGroup = DispatchGroup() var winningNode : AlphaBetaNode? var α = alpha var β = beta // If the maximizer, maximize the alpha, and prune with the beta if (maximizer) { // Process the first child without concurrency - the alpha-beta range returned allows pruning of the other trees var value = alphaBetaConcurrent(children[0], remainingDepth: nextDepth, alpha: α, beta: β, maximizer: false, topLevel: false).value winningNode = children[0] α = value > α ? value : α if (β <= α) { // β pruning return (value: value, winningNode: winningNode) } // Iterate through the rest of the child nodes if (children.count > 1) { for index in 1..<children.count { tQueue.async(group: tGroup, execute: {() -> Void in childValues[index] = self.alphaBetaConcurrent(children[index], remainingDepth: nextDepth, alpha: α, beta: β, maximizer: false, topLevel: false).value }) } // Wait for the evaluations tGroup.wait() // Prune and find best for index in 1..<children.count { if (childValues[index] > value) { value = childValues[index] winningNode = children[index] } value = childValues[index] > value ? childValues[index] : value α = value > α ? value : α if (β <= α) { // β pruning break } } } return (value: value, winningNode: winningNode) } // If the minimizer, maximize the beta, and prune with the alpha else { // Process the first child without concurrency - the alpha-beta range returned allows pruning of the other trees var value = alphaBetaConcurrent(children[0], remainingDepth: nextDepth, alpha: α, beta: β, maximizer: true, topLevel: false).value winningNode = children[0] β = value < β ? value : β if (β <= α) { // α pruning return (value: value, winningNode: winningNode) } // Iterate through the rest of the child nodes if (children.count > 1) { for index in 1..<children.count { tQueue.async(group: tGroup, execute: {() -> Void in childValues[index] = self.alphaBetaConcurrent(children[index], remainingDepth: nextDepth, alpha: α, beta: β, maximizer: true, topLevel: false).value }) } // Wait for the evaluations tGroup.wait() // Prune and find best for index in 1..<children.count { if (childValues[index] < value) { value = childValues[index] winningNode = children[index] } β = value < β ? value : β if (β <= α) { // α pruning break } } } return (value: value, winningNode: winningNode) } } }
41.764151
195
0.531285
9cd346dd3d518c04886c9548be4016c6dbf42d31
12,305
// // RootTableViewController.swift // Lego_Organizer // // Created by Jason Shultz on 12/6/15. // Copyright © 2015 HashRocket. All rights reserved. // import UIKit import SwiftyJSON import Alamofire import CoreData class RootTableViewController: UITableViewController, NSFetchedResultsControllerDelegate { var apiKey:String = "" var userSets:NSArray = [] var activeSet = -1 var datas: JSON = [] @IBOutlet var legoTable: UITableView! let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { let numberOfSections = fetchedResultController.sections?.count return numberOfSections! } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects return numberOfRowsInSection! } override func viewWillAppear(animated: Bool) { } @IBAction func showSortOptions(sender: AnyObject) { showSorting("Sort Sets", errorMessage: "Sort Sets by either Name or Number.") } // MARK:- Retrieve LegoSets let sortBy = "" func getFetchedResultController(sortBy:String) -> NSFetchedResultsController { fetchedResultController = NSFetchedResultsController(fetchRequest: legoSetFetchRequest(sortBy), managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultController } func legoSetFetchRequest(sortBy:String) -> NSFetchRequest { let fetchRequest = NSFetchRequest(entityName: "LegoSets") var sortDescriptor = NSSortDescriptor() if (sortBy == "description") { sortDescriptor = NSSortDescriptor(key: "descr", ascending: true) } else { sortDescriptor = NSSortDescriptor(key: "set_id", ascending: true) } fetchRequest.sortDescriptors = [sortDescriptor] return fetchRequest } func setupUI() { self.title = "Lego Organizer" self.tableView.backgroundColor = UIColor(red: 0.2706, green: 0.3412, blue: 0.9098, alpha: 1.0) /* #4557e8 */ self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None fetchedResultController = getFetchedResultController("description") fetchedResultController.delegate = self do { try fetchedResultController.performFetch() } catch _ { } } func showAlert(errorTitle:String, errorMessage:String) { let alert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in dispatch_async(dispatch_get_main_queue(), { alert.dismissViewControllerAnimated(true, completion: { print("i'm in the disimissal") self.performSegueWithIdentifier("showProfile", sender: self) }) }) }) alert.addAction(ok) self.presentViewController(alert, animated: true, completion: nil) } func showSorting(errorTitle:String, errorMessage:String) { let alert = UIAlertController(title: "\(errorTitle)", message: "\(errorMessage)", preferredStyle: .Alert) // 1 let firstAction = UIAlertAction(title: "Sort by Set Name", style: .Default) { (alert: UIAlertAction!) -> Void in NSLog("Sorting by Name") self.fetchedResultController = self.getFetchedResultController("description") self.fetchedResultController.delegate = self do { try self.fetchedResultController.performFetch() } catch _ { } self.tableView.reloadData() } // 3 alert.addAction(firstAction) // 5 let secondAction = UIAlertAction(title: "Sort by Set Number", style: .Default) { (alert: UIAlertAction!) -> Void in NSLog("Sorting by Number") self.fetchedResultController = self.getFetchedResultController("set_id") self.fetchedResultController.delegate = self do { try self.fetchedResultController.performFetch() } catch _ { } self.tableView.reloadData() } // 2 alert.addAction(secondAction) // 4 presentViewController(alert, animated: true, completion:nil) // 6 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "LegoSetTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! LegoSetTableViewCell cell.titleLabel.textColor = UIColor.whiteColor() cell.descriptionLabel.textColor = UIColor.whiteColor() cell.backgroundColor = UIColor(red: 0.2941, green: 0.5608, blue: 1, alpha: 1.0) /* #4b8fff */ let legoSet = fetchedResultController.objectAtIndexPath(indexPath) as! LegoSets cell.titleLabel.text = legoSet.valueForKey("set_id") as? String cell.photoImageView.contentMode = .ScaleAspectFit let myImageName = legoSet.valueForKey("img_tn") as? String let imagePath = fileInDocumentsDirectory(myImageName!) let checkImage = NSFileManager.defaultManager() if (checkImage.fileExistsAtPath(imagePath)) { if let _ = loadImageFromPath(imagePath) { if legoSet.valueForKey("img_tn") as? String != "" { cell.photoImageView.image = loadImageFromPath(imagePath) } } else { print("some error message 2") } } else { let checked_url = legoSet.valueForKey("img_tn") as? String if let checkedUrl = NSURL(string: "\(checked_url)") { cell.photoImageView.contentMode = .ScaleAspectFit getDataFromUrl(checkedUrl) { (data, response, error) in dispatch_async(dispatch_get_main_queue()) { () -> Void in guard let data = data where error == nil else { return } cell.photoImageView.image = UIImage(data: data) } } } } cell.descriptionLabel.text = legoSet.valueForKey("descr") as? String return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> 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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let managedObject:NSManagedObject = fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject managedObjectContext.deleteObject(managedObject) do { try managedObjectContext.save() } catch _ { } } 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 } } // MARK: - TableView Refresh func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.reloadData() } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { // print("indexPath: ", indexPath) activeSet = indexPath.row return indexPath } // 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. if segue.identifier == "newPlace" { } else if segue.identifier == "showLegoSet" { let cell = sender as! UITableViewCell let indexPath = legoTable.indexPathForCell(cell) // let cell = sender as! UITableViewCell let legoSetViewController:LegoSetViewController = segue.destinationViewController as! LegoSetViewController let legoSet:LegoSets = fetchedResultController.objectAtIndexPath(indexPath!) as! LegoSets legoSetViewController.legoSet = legoSet } // self.title = "" } func colorForIndex(index: Int) -> UIColor { let itemCount = userSets.count - 1 let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6 return UIColor(red: 1.0, green: color, blue: 0.0, alpha: 1.0) } func getDataFromUrl(url:NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError? ) -> Void)) { NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in completion(data: data, response: response, error: error) }.resume() } func fileInDocumentsDirectory(filename: String) -> String { let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename) return fileURL.path! } func getDocumentsURL() -> NSURL { let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] return documentsURL } func loadImageFromPath(path: String) -> UIImage? { var image = UIImage() let data = NSData(contentsOfFile: path) if (data != nil) { image = UIImage(data: data!)! } else { } return image } func downloadImage(url: NSURL){ print("Download Started") print("lastPathComponent: " + (url.lastPathComponent ?? "")) getDataFromUrl(url) { (data, response, error) in dispatch_async(dispatch_get_main_queue()) { () -> Void in guard let data = data where error == nil else { return } // print(response?.suggestedFilename ?? "") // print("Download Finished") // imageView.image = UIImage(data: data) } } } }
36.405325
188
0.620642
de7d5c2f8956197995e27f914417394362240dc1
501
// // ViewController.swift // Table Views // // Created by Bill W on 10/01/2016. // Copyright © 2016 AppFish. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.269231
80
0.664671
cccdf2816624ff28bb5be2f5574a075c8991958e
1,744
// // MarchSelectorFooter.swift // Open Conquest // // Created by Zach Wild on 1/20/20. // Copyright © 2020 Zach Wild. All rights reserved. // import Foundation import UIKit import PureLayout class MarchSelectorFooter: UIView { var cancelButton: UIButton var attackButton: UIButton override init(frame: CGRect) { cancelButton = UIButton() attackButton = UIButton() super.init(frame: frame) addSubview(cancelButton) cancelButton.backgroundColor = .red addSubview(attackButton) attackButton.backgroundColor = .green backgroundColor = .white } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { let height = self.frame.height let width = self.frame.width let buttonHeight = 2 * height / 3 let buttonWidth = width / 3 let heightOffset = (height - (buttonHeight)) / 2 let widthOffset = (width - (2 * buttonWidth)) / 3 cancelButton.autoSetDimension(.height, toSize: buttonHeight) cancelButton.autoSetDimension(.width, toSize: buttonWidth) cancelButton.autoPinEdge(.top, to: .top, of: self, withOffset: heightOffset) cancelButton.autoPinEdge(.left, to: .left, of: self, withOffset: widthOffset) attackButton.autoSetDimension(.height, toSize: buttonHeight) attackButton.autoSetDimension(.width, toSize: buttonWidth) attackButton.autoPinEdge(.top, to: .top, of: self, withOffset: heightOffset) attackButton.autoPinEdge(.right, to: .right, of: self, withOffset: -widthOffset) } }
30.596491
88
0.638761
e65c2da759f5dfcee3bf3e35c2c56dbb93fc3ba5
10,437
// // AuthViewController.swift // hah-auth-ios-swift // // Created by Anton Antonov on 06.07.17. // Copyright © 2017 KRIT. All rights reserved. // import UIKit import Mixpanel class AuthViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailPlaceholderLabel: UILabel! @IBOutlet weak var passPlaceholderLabel: UILabel! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passTextField: UITextField! @IBOutlet weak var emailBottomLineView: UIView! @IBOutlet weak var passBottomLineView: UIView! @IBOutlet weak var forgotButton: UIButton! @IBOutlet weak var emailPlaceholderTopConstraint: NSLayoutConstraint! @IBOutlet weak var passPlaceholderTopConstraint: NSLayoutConstraint! @IBOutlet weak var baseView: UIView! @IBOutlet weak var baseBottomConstraint: NSLayoutConstraint! @IBOutlet weak var loadingView: UIView! var actualPassword: NSString = "" override func viewDidLoad() { super.viewDidLoad() Mixpanel.mainInstance().track(event: "Auth Screen") configureInterface() registerNotifications() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) UIApplication.shared.isNetworkActivityIndicatorVisible = false } deinit { deregisterNotifications() } //MARK: - Interface func configureInterface() { self.title = NSLocalizedString("Auth.Navigation.Title", comment: "") //Показываем навигационную панель self.navigationController?.setNavigationBarHidden(false, animated: true) //Кнопка "Забыли пароль?" self.forgotButton.layer.cornerRadius = 4.0 self.forgotButton.layer.masksToBounds = true self.forgotButton.layer.borderColor = UIColor.colorFrom(hex: "ebebeb").cgColor self.forgotButton.layer.borderWidth = 0.5 //Скрытие клавиатуры по тапу let tap = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard)) self.view.addGestureRecognizer(tap) } //MARK: - Notifications func registerNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func deregisterNotifications() { NotificationCenter.default.removeObserver(self) } //MARK: - Keyboard func dismissKeyboard() { self.view.endEditing(true) } func keyboardWillShow(notification: NSNotification) { if self.baseBottomConstraint.constant != 0.0 { return } let duration = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double) let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue self.baseBottomConstraint.constant += (keyboardSize?.height)! UIView.animate(withDuration: duration!, animations: { self.view.layoutIfNeeded() }) } func keyboardWillHide(notification: NSNotification) { let duration = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double) self.baseBottomConstraint.constant = 0.0 UIView.animate(withDuration: duration!, animations: { self.view.layoutIfNeeded() }) } //MARK: - Text Field Delegate func textFieldDidBeginEditing(_ textField: UITextField) { if textField == self.emailTextField { if textField.empty() { upEmailPlaceholder() } } else if textField == self.passTextField { if textField.empty() { upPassPlaceholder() } } } func textFieldDidEndEditing(_ textField: UITextField) { if textField == self.emailTextField { if textField.empty() { downEmailPlaceholder() } } else if textField == self.passTextField { if textField.empty() { downPassPlaceholder() } } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { //Для изменения dots в поле пароля if textField == self.passTextField { self.actualPassword = NSString(format: "%@", self.actualPassword.replacingCharacters(in: range, with: "")) self.actualPassword = NSString(format: "%@%@", self.actualPassword, string) var index = 0 var dotsStr = "" while index < self.actualPassword.length { dotsStr += "*" index += 1 } textField.text = dotsStr return false } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == self.emailTextField { self.passTextField.becomeFirstResponder() } else if textField == self.passTextField { dismissKeyboard() doAuth() } return true } //MARK: - Data func doAuth() { if !(self.emailTextField.text?.isEmailValid)! { let title = NSLocalizedString("Auth.Email.Invalid.Title", comment: "") let message = NSLocalizedString("Auth.Email.Invalid.Message", comment: "") self.showNotificationErrorWith(title: title, message: message, duration: 3.0) self.emailTextField.becomeFirstResponder() return } if !(String(self.actualPassword).isPasswordValid) { let title = NSLocalizedString("Auth.Password.Invalid.Title", comment: "") let message = NSLocalizedString("Auth.Password.Invalid.Message", comment: "") self.showNotificationErrorWith(title: title, message: message, duration: 6.0) self.passTextField.becomeFirstResponder() return } dismissKeyboard() if !self.hasConnectivity() { let title = NSLocalizedString("No.Connection.Title", comment: "") let message = NSLocalizedString("No.Connection.Message", comment: "") self.showNotificationErrorWith(title: title, message: message, duration: 5.0) return } showLoader() let request = WeatherRequestModel() request.city = "Moscow" AuthorizationRequestManager.doAuthWith(model: request, success: { (response: WeatherResponseModel) in let title = NSLocalizedString("Auth.Success.Title", comment: "") var message: String! if !response.weather.isEmpty { message = String(format: NSLocalizedString("Auth.Success.Message", comment: ""), response.weather[0].description, String((response.temperature?.temp)!)) } else { message = NSLocalizedString("Auth.Success.Message", comment: "") } self.showAlertWith(title: title, message: message, complition: { self.navigationController?.popViewController(animated: true) }) self.hideLoader() }, failure: { let title = NSLocalizedString("Alert.Bad.Common.Tittle", comment: "") let message = NSLocalizedString("Alert.Bad.Common.Message", comment: "") self.showNotificationErrorWith(title: title, message: message, duration: 5.0) self.hideLoader() }) } //MARK: - Loader func showLoader() { UIApplication.shared.isNetworkActivityIndicatorVisible = true self.loadingView.isHidden = false UIView.animate(withDuration: 0.3, animations: { self.loadingView.alpha = 0.2 }) } func hideLoader() { UIApplication.shared.isNetworkActivityIndicatorVisible = false UIView.animate(withDuration: 0.3, animations: { self.loadingView.alpha = 0.0 }, completion: {(finished: Bool) in self.loadingView.isHidden = true }) } //MARK: - Placeholders func upEmailPlaceholder() { self.emailPlaceholderTopConstraint.constant -= 20.0 UIView.animate(withDuration: 0.2, animations: { self.view.layoutIfNeeded() }) } func downEmailPlaceholder() { self.emailPlaceholderTopConstraint.constant += 20.0 UIView.animate(withDuration: 0.2, animations: { self.view.layoutIfNeeded() }) } func upPassPlaceholder() { self.passPlaceholderTopConstraint.constant -= 20.0 UIView.animate(withDuration: 0.2, animations: { self.view.layoutIfNeeded() }) } func downPassPlaceholder() { self.passPlaceholderTopConstraint.constant += 20.0 UIView.animate(withDuration: 0.2, animations: { self.view.layoutIfNeeded() }) } //MARK: - IB Actions @IBAction func forgotButtonPressed(_ sender: Any) { let title = NSLocalizedString("Auth.Forgot.Title", comment: "") let message = NSLocalizedString("Auth.Forgot.Text", comment: "") self.showErrorWith(title: title, message: message) } @IBAction func authButtonPressed(_ sender: Any) { doAuth() } }
31.155224
168
0.574878
56bb0f33a28d863341dc2e842a5f3fac522690e7
444
// // Set+KK.swift // KakaJSON // // Created by MJ Lee on 2019/8/13. // Copyright © 2019 MJ Lee. All rights reserved. // extension NSSet { func _JSONValue() -> Any? { var arr: [Any] = [] arr.append(contentsOf: self) return arr._JSONValue() } } extension Set { func _JSONValue() -> Any? { var arr: [Any] = [] arr.append(contentsOf: self as NSSet) return arr._JSONValue() } }
18.5
49
0.551802
22745ec58d0d260a0758d7a4880aa355f9483087
892
// // PhotoViewController.swift // CacheDemo // // Created by Raunak Poddar on 14/10/19. // Copyright © 2019 Raunak. All rights reserved. // import UIKit import RPDownloadManager class PhotoViewController: UIViewController { @IBOutlet weak var imageView: RPImageView! var photoURL: URL? override func viewDidLoad() { super.viewDidLoad() if let url = photoURL { self.imageView.rp_setImage(fromURL: url) } // 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. } */ }
24.108108
106
0.656951
5dcefe86937065d31457a83223d0365bd09640e2
1,479
// // Krypton_Animation_TestingUITests.swift // Krypton-Animation-TestingUITests // // Created by Iliya dehsarvi on 8/6/21. // import XCTest class Krypton_Animation_TestingUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
34.395349
182
0.666667
16d31ddeb05bbca889f5d17616022e6fad5e55a0
418
// // WeatherOpen.swift // Nano5 // // Created by Gustavo Rigor on 22/02/21. // import Foundation struct WeatherOpen: Decodable { var coord: Coord? var weather: [Weather?]? var base: String? var main: MainTemp? var visibility: Int? var wind: Wind? var clouds: Clouds? var dt: Int? var sys: Sys? var timezone: Int? var id: Int? var name: String? var cod: Int? }
16.72
41
0.605263
111c5239f215bd918f3fe675339f7887bb87a979
3,880
import WebKit public class SVGView: UIView, WKNavigationDelegate { private lazy var webView: WKWebView = .init(frame: self.bounds) private let loader: SVGLoader private lazy var executor = JavaScriptExecutor(webView: self.webView) public init?(named: String, animationOwner: AnimationOwner, style: SVGLoader.Style? = .default, bundle: Bundle = .main) { let style = style ?? SVGLoader.Style(rawCSS: "") guard let loader = SVGLoader(named: named, animationOwner: animationOwner, style: style, bundle: bundle) else { print("Image not found.") return nil } self.loader = loader super.init(frame: .zero) setup() } public init?(fileURL: URL, animationOwner: AnimationOwner, style: SVGLoader.Style? = .default) { let style = style ?? SVGLoader.Style(rawCSS: "") guard let loader = SVGLoader(fileURL: fileURL, animationOwner: animationOwner, style: style) else { print("Image not found.") return nil } self.loader = loader super.init(frame: .zero) setup() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { webView.navigationDelegate = self webView.translatesAutoresizingMaskIntoConstraints = false addSubview(webView) NSLayoutConstraint.activate([ webView.topAnchor.constraint(equalTo: topAnchor), webView.rightAnchor.constraint(equalTo: rightAnchor), webView.bottomAnchor.constraint(equalTo: bottomAnchor), webView.leftAnchor.constraint(equalTo: leftAnchor), ]) isUserInteractionEnabled = false isOpaque = false backgroundColor = UIColor.clear webView.scrollView.backgroundColor = UIColor.clear webView.scrollView.isScrollEnabled = false webView.loadHTMLString(loader.html, baseURL: nil) } public func isAnimate(result: @escaping (Bool?, Error?) -> Void) { switch loader.animationOwner { case .css: isAnimateCSS(result: result) case .svg: isAnimateSVG(result: result) } } private func isAnimateSVG(result: @escaping (Bool?, Error?) -> Void) { executor.execute(javaScriptCommand: .isAnimateSVG) { (value, error) in guard let value = value as? NSNumber, let bool = Bool(exactly: value) else { result(nil, error); return } result(!bool, error) } } private func isAnimateCSS(result: @escaping (Bool?, Error?) -> Void) { executor.execute(javaScriptCommand: .isAnimateCSS) { (value, error) in guard let value = value as? String else { result(nil, error); return } result(value == "running", error) } } public func startAnimation(result: ((Error?) -> Void)? = nil) { switch loader.animationOwner { case .css: executor.execute(javaScriptCommand: .startCSSAnimation) { (_, e) in result?(e) } case .svg: executor.execute(javaScriptCommand: .startSVGAnimation) { _, e in result?(e) } } } public func stopAnimation(result: ((Error?) -> Void)? = nil) { switch loader.animationOwner { case .css: executor.execute(javaScriptCommand: .stopCSSAnimation) { (_, e) in result?(e) } case .svg: executor.execute(javaScriptCommand: .stopSVGAnimation) { _, e in result?(e) } } } // MARK: - WKNavigationDelegate public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { backgroundColor = .clear isOpaque = false } }
34.954955
125
0.599227
f507f0b6a204099ad3087027d5a97b123173bdea
972
// // Playlist.swift // Apollo // // Created by Khaos Tian on 9/30/18. // Copyright © 2018 Oltica. All rights reserved. // import Foundation public struct Playlist: Codable { public let id: String public let name: String public let owner: PublicUser public let description: String? public let images: [Image] public let followers: Followers public let collaborative: Bool public let tracks: Paginated<PlaylistTrack> public init(id: String, name: String, owner: PublicUser, description: String?, images: [Image], followers: Followers, collaborative: Bool, tracks: Paginated<PlaylistTrack>) { self.id = id self.name = name self.owner = owner self.description = description self.images = images self.followers = followers self.collaborative = collaborative self.tracks = tracks } } extension Playlist: AnyPlaylist {}
24.3
178
0.643004
eb80a240d6c34bfe248e9eac0570c150a90894c3
3,198
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // protocol ReplyCellModuleInput: class { } protocol ReplyCellModuleOutput: class { func showMenu(reply: Reply) func removed(reply: Reply) } class ReplyCellPresenter: ReplyCellModuleInput, ReplyCellViewOutput, ReplyCellInteractorOutput { weak var view: ReplyCellViewInput? var interactor: ReplyCellInteractorInput? var router: ReplyCellRouterInput? var myProfileHolder: UserHolder? weak var moduleOutput: ReplyCellModuleOutput? var reply: Reply! private let actionStrategy: AuthorizedActionStrategy private let userHolder: UserHolder init(actionStrategy: AuthorizedActionStrategy, userHolder: UserHolder = SocialPlus.shared) { self.actionStrategy = actionStrategy self.userHolder = userHolder } func viewIsReady() { } func didPostAction(replyHandle: String, action: RepliesSocialAction, error: Error?) { } func like() { actionStrategy.executeOrPromptLogin { [weak self] in self?._like() } } private func _like() { let status = reply.liked let action: RepliesSocialAction = status ? .unlike : .like reply.liked = !status if action == .like { reply.totalLikes += 1 } else if action == .unlike && reply.totalLikes > 0 { reply.totalLikes -= 1 } view?.configure(reply: reply) interactor?.replyAction(replyHandle: reply.replyHandle, action: action) } func avatarPressed() { guard let handle = reply.user?.uid else { return } if userHolder.me?.uid == handle { router?.openMyProfile() } else { router?.openUser(userHandle: handle) } } func likesPressed() { router?.openLikes(replyHandle: reply.replyHandle) } func optionsPressed() { moduleOutput?.showMenu(reply: reply) } } extension ReplyCellPresenter: PostMenuModuleOutput { func postMenuProcessDidStart() { // view.setRefreshingWithBlocking(state: true) } func postMenuProcessDidFinish() { // view.setRefreshingWithBlocking(state: false) } func didBlock(user: User) { Logger.log("Success") } func didUnblock(user: User) { Logger.log("Success") } func didFollow(user: User) { // comment.userStatus = .accepted // view?.configure(comment: comment) } func didUnfollow(user: User) { // comment.userStatus = .empty // view?.configure(comment: comment) } func didRemove(reply: Reply) { moduleOutput?.removed(reply: reply) } func didReport(post: PostHandle) { Logger.log("Not implemented") } func didRequestFail(error: Error) { Logger.log("Reloading feed", error, event: .error) // view.showError(error: error) // fetchAllItems() } }
25.181102
96
0.607255
09e41b417355d378bc2f5dac292879d13094dcfc
1,792
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // import UIKit class CommentRepliesRouter: CommentRepliesRouterInput { weak var navigationController: UINavigationController? weak var postMenuModuleOutput: PostMenuModuleOutput! weak var moduleInput: CommentRepliesPresenter! // Keeping ref to menu private var postMenuViewController: UIViewController? func backIfNeeded(from view: UIViewController) { if !(view.navigationController?.viewControllers.last is CommentRepliesViewController) { view.navigationController?.popViewController(animated: true) } } func back() { if navigationController?.viewControllers.last is CommentRepliesViewController { navigationController?.popViewController(animated: true) } } func openMyReplyOptions(reply: Reply) { configureOptions(type: .myReply(reply: reply)) } func openOtherReplyOptions(reply: Reply) { configureOptions(type: .otherReply(reply: reply)) } private func configureOptions(type: PostMenuType) { let configurator = PostMenuModuleConfigurator() configurator.configure(menuType: type, moduleOutput: moduleInput, navigationController: navigationController) postMenuViewController = configurator.viewController if let parent = navigationController?.viewControllers.last { postMenuViewController!.modalPresentationStyle = .overCurrentContext parent.present(postMenuViewController!, animated: false, completion: nil) } } }
34.461538
95
0.682478
4840fd5b9e0129bd40bd9d7b2c954241fbdc2105
2,116
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation import PrebidMobile import AppLovinSDK public let MAXCustomParametersKey = "custom_parameters" @objc(PrebidMAXMediationAdapter) public class PrebidMAXMediationAdapter: ALMediationAdapter { // MARK: - Banner public weak var bannerDelegate: MAAdViewAdapterDelegate? public var displayView: PBMDisplayView? // MARK: - Interstitial public weak var interstitialDelegate: MAInterstitialAdapterDelegate? public var interstitialController: InterstitialController? public var interstitialAdAvailable = false // MARK: - Rewarded public weak var rewardedDelegate: MARewardedAdapterDelegate? // MARK: - Native public weak var nativeDelegate: MANativeAdAdapterDelegate? public override func initialize(with parameters: MAAdapterInitializationParameters, completionHandler: @escaping (MAAdapterInitializationStatus, String?) -> Void) { Prebid.initializeSDK() super.initialize(with: parameters, completionHandler: completionHandler) } public override var sdkVersion: String { return Prebid.shared.version } public override var adapterVersion: String { MAXConstants.PrebidMAXAdapterVersion } public override func destroy() { bannerDelegate = nil displayView = nil interstitialDelegate = nil interstitialController = nil rewardedDelegate = nil nativeDelegate = nil super.destroy() } }
30.228571
168
0.718336
fed75351ac5576baa4a3cc28b04cada5d9a6e799
10,914
import Combine import ComposableArchitecture import SwiftUI private let readMe = """ This application demonstrates how to work with a web socket in the Composable Architecture. A lightweight wrapper is made for `URLSession`'s API for web sockets so that we can send, \ receive and ping a socket endpoint. To test, connect to the socket server, and then send a \ message. The socket server should immediately reply with the exact message you send it. """ struct WebSocketState: Equatable { var alert: AlertState<WebSocketAction>? var connectivityState = ConnectivityState.disconnected var messageToSend = "" var receivedMessages: [String] = [] enum ConnectivityState: String { case connected case connecting case disconnected } } enum WebSocketAction: Equatable { case alertDismissed case connectButtonTapped case messageToSendChanged(String) case pingResponse(NSError?) case receivedSocketMessage(Result<WebSocketClient.Message, NSError>) case sendButtonTapped case sendResponse(NSError?) case webSocket(WebSocketClient.Action) } struct WebSocketEnvironment { var mainQueue: AnySchedulerOf<DispatchQueue> var webSocket: WebSocketClient } let webSocketReducer = Reducer<WebSocketState, WebSocketAction, WebSocketEnvironment> { state, action, environment in struct WebSocketId: Hashable {} var receiveSocketMessageEffect: Effect<WebSocketAction, Never> { return environment.webSocket.receive(WebSocketId()) .receive(on: environment.mainQueue) .catchToEffect(WebSocketAction.receivedSocketMessage) .cancellable(id: WebSocketId()) } var sendPingEffect: Effect<WebSocketAction, Never> { return environment.webSocket.sendPing(WebSocketId()) .delay(for: 10, scheduler: environment.mainQueue) .map(WebSocketAction.pingResponse) .eraseToEffect() .cancellable(id: WebSocketId()) } switch action { case .alertDismissed: state.alert = nil return .none case .connectButtonTapped: switch state.connectivityState { case .connected, .connecting: state.connectivityState = .disconnected return .cancel(id: WebSocketId()) case .disconnected: state.connectivityState = .connecting return environment.webSocket.open(WebSocketId(), URL(string: "wss://echo.websocket.org")!, []) .receive(on: environment.mainQueue) .map(WebSocketAction.webSocket) .eraseToEffect() .cancellable(id: WebSocketId()) } case let .messageToSendChanged(message): state.messageToSend = message return .none case .pingResponse: // Ping the socket again in 10 seconds return sendPingEffect case let .receivedSocketMessage(.success(.string(string))): state.receivedMessages.append(string) // Immediately ask for the next socket message return receiveSocketMessageEffect case .receivedSocketMessage(.success): // Immediately ask for the next socket message return receiveSocketMessageEffect case .receivedSocketMessage(.failure): return .none case .sendButtonTapped: let messageToSend = state.messageToSend state.messageToSend = "" return environment.webSocket.send(WebSocketId(), .string(messageToSend)) .receive(on: environment.mainQueue) .eraseToEffect() .map(WebSocketAction.sendResponse) case let .sendResponse(error): if error != nil { state.alert = .init(title: .init("Could not send socket message. Try again.")) } return .none case let .webSocket(.didClose(code, _)): state.connectivityState = .disconnected return .cancel(id: WebSocketId()) case let .webSocket(.didBecomeInvalidWithError(error)), let .webSocket(.didCompleteWithError(error)): state.connectivityState = .disconnected if error != nil { state.alert = .init(title: .init("Disconnected from socket for some reason. Try again.")) } return .cancel(id: WebSocketId()) case .webSocket(.didOpenWithProtocol): state.connectivityState = .connected return .merge( receiveSocketMessageEffect, sendPingEffect ) } } struct WebSocketView: View { let store: Store<WebSocketState, WebSocketAction> var body: some View { WithViewStore(self.store) { viewStore in VStack(alignment: .leading) { Text(template: readMe, .body) .padding(.bottom) HStack { TextField( "Message to send", text: viewStore.binding( get: \.messageToSend, send: WebSocketAction.messageToSendChanged) ) Button( viewStore.connectivityState == .connected ? "Disconnect" : viewStore.connectivityState == .disconnected ? "Connect" : "Connecting..." ) { viewStore.send(.connectButtonTapped) } } Button("Send message") { viewStore.send(.sendButtonTapped) } Spacer() Text("Status: \(viewStore.connectivityState.rawValue)") .foregroundColor(.secondary) Text("Received messages:") .foregroundColor(.secondary) Text(viewStore.receivedMessages.joined(separator: "\n")) } .padding() .alert(self.store.scope(state: \.alert), dismiss: .alertDismissed) .navigationBarTitle("Web Socket") } } } // MARK: - WebSocketClient struct WebSocketClient { enum Action: Equatable { case didBecomeInvalidWithError(NSError?) case didClose(code: URLSessionWebSocketTask.CloseCode, reason: Data?) case didCompleteWithError(NSError?) case didOpenWithProtocol(String?) } enum Message: Equatable { case data(Data) case string(String) init?(_ message: URLSessionWebSocketTask.Message) { switch message { case let .data(data): self = .data(data) case let .string(string): self = .string(string) @unknown default: return nil } } static func == (lhs: Self, rhs: Self) -> Bool { switch (lhs, rhs) { case let (.data(lhs), .data(rhs)): return lhs == rhs case let (.string(lhs), .string(rhs)): return lhs == rhs case (.data, _), (.string, _): return false } } } var cancel: (AnyHashable, URLSessionWebSocketTask.CloseCode, Data?) -> Effect<Never, Never> var open: (AnyHashable, URL, [String]) -> Effect<Action, Never> var receive: (AnyHashable) -> Effect<Message, NSError> var send: (AnyHashable, URLSessionWebSocketTask.Message) -> Effect<NSError?, Never> var sendPing: (AnyHashable) -> Effect<NSError?, Never> } extension WebSocketClient { static let live = WebSocketClient( cancel: { id, closeCode, reason in .fireAndForget { dependencies[id]?.task.cancel(with: closeCode, reason: reason) dependencies[id]?.subscriber.send(completion: .finished) dependencies[id] = nil } }, open: { id, url, protocols in Effect.run { subscriber in let delegate = WebSocketDelegate( didBecomeInvalidWithError: { subscriber.send(.didBecomeInvalidWithError($0 as NSError?)) }, didClose: { subscriber.send(.didClose(code: $0, reason: $1)) }, didCompleteWithError: { subscriber.send(.didCompleteWithError($0 as NSError?)) }, didOpenWithProtocol: { subscriber.send(.didOpenWithProtocol($0)) } ) let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil) let task = session.webSocketTask(with: url, protocols: protocols) task.resume() dependencies[id] = Dependencies(delegate: delegate, subscriber: subscriber, task: task) return AnyCancellable { task.cancel(with: .normalClosure, reason: nil) dependencies[id]?.subscriber.send(completion: .finished) dependencies[id] = nil } } }, receive: { id in .future { callback in dependencies[id]?.task.receive { result in switch result.map(Message.init) { case let .success(.some(message)): callback(.success(message)) case .success(.none): callback(.failure(NSError.init(domain: "co.pointfree", code: 1))) case let .failure(error): callback(.failure(error as NSError)) } } } }, send: { id, message in .future { callback in dependencies[id]?.task.send(message) { error in callback(.success(error as NSError?)) } } }, sendPing: { id in .future { callback in dependencies[id]?.task.sendPing { error in callback(.success(error as NSError?)) } } } ) } private var dependencies: [AnyHashable: Dependencies] = [:] private struct Dependencies { let delegate: URLSessionWebSocketDelegate let subscriber: Effect<WebSocketClient.Action, Never>.Subscriber let task: URLSessionWebSocketTask } private class WebSocketDelegate: NSObject, URLSessionWebSocketDelegate { let didBecomeInvalidWithError: (Error?) -> Void let didClose: (URLSessionWebSocketTask.CloseCode, Data?) -> Void let didCompleteWithError: (Error?) -> Void let didOpenWithProtocol: (String?) -> Void init( didBecomeInvalidWithError: @escaping (Error?) -> Void, didClose: @escaping (URLSessionWebSocketTask.CloseCode, Data?) -> Void, didCompleteWithError: @escaping (Error?) -> Void, didOpenWithProtocol: @escaping (String?) -> Void ) { self.didBecomeInvalidWithError = didBecomeInvalidWithError self.didOpenWithProtocol = didOpenWithProtocol self.didCompleteWithError = didCompleteWithError self.didClose = didClose } func urlSession( _ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String? ) { self.didOpenWithProtocol(`protocol`) } func urlSession( _ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? ) { self.didClose(closeCode, reason) } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { self.didCompleteWithError(error) } func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { self.didBecomeInvalidWithError(error) } } // MARK: - SwiftUI previews struct WebSocketView_Previews: PreviewProvider { static var previews: some View { NavigationView { WebSocketView( store: Store( initialState: .init(receivedMessages: ["Echo"]), reducer: webSocketReducer, environment: WebSocketEnvironment( mainQueue: .main, webSocket: .live ) ) ) } } }
30.066116
100
0.663826
389e2fa59a20ce69b427610c76568c89773c8215
539
import AVFoundation extension VideoIOComponent { func attachScreen(_ screen: AVCaptureScreenInput?) { mixer?.session.beginConfiguration() output = nil guard screen != nil else { input = nil return } input = screen mixer?.session.addOutput(output) output.setSampleBufferDelegate(self, queue: lockQueue) mixer?.session.commitConfiguration() if mixer?.session.isRunning ?? false { mixer?.session.startRunning() } } }
26.95
62
0.602968
1f0012bdefd4ed8182a4c71ac1b8c9a7f29c2cca
1,027
// RUN: %target-swift-frontend -typecheck %s -enable-source-import -I %S/Inputs -sdk "" -verify // RUN: %target-swift-frontend -typecheck %s -enable-source-import -I %S/Inputs -sdk "" -import-module abcde // RUN: not %target-swift-frontend -typecheck %s -enable-source-import -I %S/Inputs -sdk "" -import-module 3333 2>&1 | %FileCheck -check-prefix=NON-IDENT %s // NON-IDENT: error: module name "3333" is not a valid identifier // RUN: not %target-swift-frontend -typecheck %s -enable-source-import -I %S/Inputs -sdk "" -import-module NON_EXISTENT 2>&1 | %FileCheck -check-prefix=NON-EXISTENT %s // NON-EXISTENT: error: no such module 'NON_EXISTENT' // RUN: not %target-swift-frontend -typecheck %s -enable-source-import -I %S/Inputs -sdk "" -testable-import-module abcde 2>&1 | %FileCheck -check-prefix=NON-TESTABLE %s // NON-TESTABLE: error: module 'abcde' was not compiled for testing var a: A? // expected-error {{cannot find type 'A' in scope}} var qA: abcde.A? // expected-error {{cannot find type 'abcde' in scope}}
68.466667
169
0.710808
03d29c21a247d495336f9cb113ad3b06f32eb9be
2,526
// // AppDelegate.swift // UltimateTest // // Created by Paul on 16/09/2015. // Copyright © 2015 ProcessOne. All rights reserved. // import UIKit import xmpp_messenger_ios @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. OneChat.start(true, delegate: nil) { (stream, error) -> Void in if let _ = error { //handle start errors here print("errors from appdelegate") } else { print("Yayyyy") //Activate online UI } } 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. if application.respondsToSelector("setKeepAliveTimeout:handler:") { application.setKeepAliveTimeout(600, handler: { () -> Void in // Do other keep alive stuff here. }) } else { OneChat.stop() } } 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:. OneChat.stop() } }
38.861538
279
0.76247
0e4cf0f13f882d71fc86853ddabd3aa2224594c0
511
// // WeatherConditions.swift // DatWeatherDoe // // Created by Inder Dhir on 1/29/16. // Copyright © 2016 Inder Dhir. All rights reserved. // enum WeatherConditions: String { case sunny = "Sunny" case partlyCloudy = "PartlyCloudy" case cloudy = "Cloudy" case mist = "Mist" case snow = "Snow" case freezingRain = "FreezingRain" case heavyRain = "HeavyRain" case partlyCloudyRain = "PartlyCloudyRain" case lightRain = "LightRain" case thunderstorm = "Thunderstorm" }
24.333333
53
0.67319
38f432c9c1b31ba26ff9d41778c86be9b1f8a67d
1,373
// // ViewController.swift // ImagePickerDemo // // Created by Vibhor Gupta on 8/10/17. // Copyright © 2017 Vibhor Gupta. All rights reserved. // import UIKit class ViewController: UIViewController { //let imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //imagePicker.delegate = self as! UIImagePickerControllerDelegate & UINavigationControllerDelegate } @IBAction func openAlertViewController(_ sender: UIButton) { let controller = UIAlertController() controller.title = "this is a test Alert" controller.message = "this is a test message" let okAction = UIAlertAction(title : "ok", style : UIAlertAction.Style.default){ action in self.dismiss(animated: true, completion: nil) } controller.addAction(okAction) self.present(controller, animated: true, completion: nil) } @IBAction func openImagePicker(_ sender: UIButton) { let image = UIImage() let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil) self.present(controller, animated: true, completion: nil) } }
26.921569
106
0.635106
2665a7ce2a2d1c63acdaf8cd8e8e301a253950dc
910
// // Crypto.swift // WalletKit // // Created by yuzushioh on 2018/02/06. // Copyright © 2018 yuzushioh. All rights reserved. // import Foundation final class HDCrypto { static func HMACSHA512(key: Data, data: Data) -> Data { let output: [UInt8] do { output = try HMAC(key: key.bytes, variant: .sha512).authenticate(data.bytes) } catch let error { fatalError("Error occured. Description: \(error.localizedDescription)") } return Data(output) } static func PBKDF2SHA512(password: [UInt8], salt: [UInt8]) -> Data { let output: [UInt8] do { output = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 2048, variant: .sha512).calculate() } catch let error { fatalError("PKCS5.PBKDF2 faild: \(error.localizedDescription)") } return Data(output) } }
27.575758
117
0.598901
61c4d8c2d0d4e0176feaeea17891beb6e5b509ad
271
// // MoviesCollectionViewCell.swift // AhMovie // // Created by TK Nguyen on 6/20/17. // Copyright © 2017 tknguyen. All rights reserved. // import UIKit class MoviesCollectionViewCell: UICollectionViewCell { @IBOutlet weak var PosterImage: UIImageView! }
18.066667
54
0.719557
9010b1b3eee958346cf2444e4acdbd99f8ae9960
11,600
// // AHAudioPlayerManager.swift // Pods // // Created by Andy Tong on 7/20/17. // // import Foundation import MediaPlayer public let AHAudioPlayerDidStartToPlay = Notification.Name("AHAudioPlayerDidStartToPlay") public let AHAudioPlayerDidChangeState = Notification.Name("AHAudioPlayerDidChangeState") /// Sent every time a track is being played public let AHAudioPlayerDidSwitchPlay = Notification.Name("AHAudioPlayerDidSwitchPlay") public let AHAudioPlayerDidReachEnd = Notification.Name("AHAudioPlayerDidReachEnd") public let AHAudioPlayerFailedToReachEnd = Notification.Name("AHAudioPlayerFailedToReachEnd") public enum AHAudioPlayerState { case none case loading case playing case stopped case paused } public enum AHAudioRateSpeed: Float { case one = 1.0 case one_two_five = 1.25 case one_five = 1.5 case one_seven_five = 1.75 case two = 2.0 } @objc public protocol AHAudioPlayerMangerDelegate: class { /// Update every 10s after the track startd to play. func playerManger(_ manager: AHAudioPlayerManager, updateForTrackId trackId: Int, duration: TimeInterval) /// Update every 10s after the track startd to play, additionally when paused, resume, and right before anything stop. func playerManger(_ manager: AHAudioPlayerManager, updateForTrackId trackId: Int, playedProgress: TimeInterval) ///###### The following five are for audio background mode /// Return a dict should include ['trackId': Int, 'trackURL': URL]. Return [:] if there's none or network is broken. func playerMangerGetPreviousTrackInfo(_ manager: AHAudioPlayerManager, currentTrackId: Int) -> [String: Any] /// Return a dict should include ['trackId': Int, 'trackURL': URL]. Return [:] if there's none or network is broken. func playerMangerGetNextTrackInfo(_ manager: AHAudioPlayerManager, currentTrackId: Int) -> [String: Any] func playerMangerGetTrackTitle(_ player: AHAudioPlayerManager, trackId: Int) -> String? func playerMangerGetAlbumTitle(_ player: AHAudioPlayerManager, trackId: Int) -> String? func playerMangerGetAlbumCover(_ player: AHAudioPlayerManager,trackId: Int, _ callback: @escaping(_ coverImage: UIImage?)->Void) ///###### } struct PlayerItem: Equatable { var id: Int? var url: URL var image: UIImage? public static func ==(lhs: PlayerItem, rhs: PlayerItem) -> Bool { return lhs.url == rhs.url || lhs.id == rhs.id } } public class AHAudioPlayerManager: NSObject { public static let shared = AHAudioPlayerManager() public override init() { super.init() AHAudioPlayer.shared.delegate = self } public weak var delegate: AHAudioPlayerMangerDelegate? public var playingTrackId: Int? { return self.playingItem?.id } public var playingTrackURL: URL? { return self.playingItem?.url } fileprivate(set) var playingItem: PlayerItem? /// Timer used in background mode and save progress periodically fileprivate var timer: Timer? /// For fast backward/forward delta in seconds fileprivate var fastDelta = 10.0 } //MARK:- Player States extension AHAudioPlayerManager { public var state: AHAudioPlayerState { return AHAudioPlayer.shared.state } public var muted: Bool { set { AHAudioPlayer.shared.muted = muted } get { return AHAudioPlayer.shared.muted } } public var rate: AHAudioRateSpeed { set { AHAudioPlayer.shared.rate = newValue.rawValue } get { guard let rate = AHAudioRateSpeed(rawValue: AHAudioPlayer.shared.rate) else { return AHAudioRateSpeed.one } return rate } } /// this value has to be between [0,1] public var volumn: Float { set { AHAudioPlayer.shared.volumn = newValue } get { return AHAudioPlayer.shared.volumn } } public var durationPretty: String { return AHAudioPlayer.shared.durationPretty } public var duration: TimeInterval { return AHAudioPlayer.shared.duration } /// you might need to setup a timer to read this as a progress public var currentTimePretty: String { return AHAudioPlayer.shared.currentTimePretty } public var currentTime: TimeInterval { return AHAudioPlayer.shared.currentTime } /// curreent plackback progress public var progress: Double { return AHAudioPlayer.shared.progress } /// progress downloaded public var loadedProgress: Double { return AHAudioPlayer.shared.loadedProgress } } //MARK:- Play extension AHAudioPlayerManager { /// toProgress should be in seconds, NOT in percentage. public func play(trackId: Int?, trackURL: URL, toTime: TimeInterval? = nil) { self.playingItem = PlayerItem(id: trackId, url: trackURL, image: nil) if timer != nil { timer?.invalidate() timer = nil } //cached progress periodically timer = Timer(timeInterval: 10, target: self, selector: #selector(self.updateInBackground), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: RunLoopMode.commonModes) AHAudioPlayer.shared.play(url: trackURL, toTime: toTime) } } //MARK:- Playback Control extension AHAudioPlayerManager { public func pause() { AHAudioPlayer.shared.pause() if timer != nil { timer?.invalidate() timer = nil } updateTrackPlayedProgress() } public func resume() { AHAudioPlayer.shared.resume() if timer != nil { timer?.invalidate() timer = nil } //cached progress periodically timer = Timer(timeInterval: 10, target: self, selector: #selector(self.updateInBackground), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: RunLoopMode.commonModes) } public func stop() { updateTrackPlayedProgress() AHAudioPlayer.shared.stop() if timer != nil { timer?.invalidate() timer = nil } } public func seekBackward() { AHAudioPlayer.shared.seek(withDelta: -fastDelta) } public func seekForward() { AHAudioPlayer.shared.seek(withDelta: fastDelta) } public func seekToPercent(_ percentage: Double, _ completion: ((Bool)->Void)? = nil) { AHAudioPlayer.shared.seek(toProgress: percentage, completion) } public func changeToNextRate() { AHAudioPlayer.shared.changeToNextRate() } } //MARK:- Helper extension AHAudioPlayerManager { fileprivate func updateTrackDuration() { guard self.duration > 0 else { return } guard let item = self.playingItem else { return } guard let id = item.id else { return } self.delegate?.playerManger(self, updateForTrackId: id, duration: self.duration) } fileprivate func updateTrackPlayedProgress() { guard let item = self.playingItem else { return } guard let id = item.id else { return } self.delegate?.playerManger(self, updateForTrackId: id, playedProgress: self.currentTime) } } extension AHAudioPlayerManager: AHAudioPlayerDelegate { @objc func updateInBackground() { updateTrackPlayedProgress() } func audioPlayerDidStartToPlay(_ player: AHAudioPlayer) { updateTrackPlayedProgress() updateTrackDuration() } func audioPlayerDidReachEnd(_ player: AHAudioPlayer) { stop() guard let nextItem = self.getNextItem() else { return } self.playingItem = nextItem self.play(trackId: nextItem.id, trackURL: nextItem.url) } func audioPlayerShouldPlayNext(_ player: AHAudioPlayer) -> Bool{ guard let nextItem = self.getNextItem() else { return false } stop() self.playingItem = nextItem self.play(trackId: nextItem.id, trackURL: nextItem.url) return true } func audioPlayerShouldPlayPrevious(_ player: AHAudioPlayer) -> Bool{ guard let previousItem = self.getPrevisouItem() else { return false } stop() self.playingItem = previousItem self.play(trackId: previousItem.id, trackURL: previousItem.url) return true } func audioPlayerShouldChangePlaybackRate(_ player: AHAudioPlayer) -> Bool{ self.changeToNextRate() return true } func audioPlayerShouldSeekForward(_ player: AHAudioPlayer) -> Bool{ seekForward() return true } func audioPlayerShouldSeekBackward(_ player: AHAudioPlayer) -> Bool{ seekBackward() return true } func audioPlayerGetTrackTitle(_ player: AHAudioPlayer) -> String?{ guard let item = self.playingItem else { return nil } guard let id = item.id else { return nil } return self.delegate?.playerMangerGetTrackTitle(self, trackId: id) } func audioPlayerGetAlbumTitle(_ player: AHAudioPlayer) -> String?{ guard let item = self.playingItem else { return nil } guard let id = item.id else { return nil } return self.delegate?.playerMangerGetAlbumTitle(self, trackId: id) } func audioPlayerGetAlbumCover(_ player: AHAudioPlayer, _ callback: @escaping (UIImage?) -> Void) { guard let item = self.playingItem else { callback(nil) return } guard let id = item.id else { callback(nil) return } self.delegate?.playerMangerGetAlbumCover(self, trackId: id, { (image) in callback(image) }) } } //MARK:- Helper Methods extension AHAudioPlayerManager { fileprivate func getNextItem() -> PlayerItem? { guard let delegate = self.delegate else { return nil } guard let item = self.playingItem else { return nil } guard let id = item.id else { return nil } let dict = delegate.playerMangerGetNextTrackInfo(self, currentTrackId: id) if let trackId = dict["trackId"] as? Int, let trackURL = dict["trackURL"] as? URL { let item = PlayerItem(id: trackId, url: trackURL, image: nil) return item }else{ return nil } } fileprivate func getPrevisouItem() -> PlayerItem? { guard let delegate = self.delegate else { return nil } guard let item = self.playingItem else { return nil } guard let id = item.id else { return nil } let dict = delegate.playerMangerGetPreviousTrackInfo(self,currentTrackId: id) if let trackId = dict["trackId"] as? Int, let trackURL = dict["trackURL"] as? URL { let item = PlayerItem(id: trackId, url: trackURL, image: nil) return item }else{ return nil } } }
28.712871
132
0.617241
115e5c785b0a867b8846c75ea2be8410f56d11ae
2,173
// // AppDelegate.swift // toy2_view_controller // // Created by imac on 2019/9/24. // Copyright © 2019 Apple. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.234043
285
0.755637
dd3443785fd33ac95bd4af376375e8fe9c76cb4b
546
// // CruOktaUser.swift // OktaAuthentication // // Created by Levi Eggert on 11/24/21. // Copyright © 2021 Cru Global, Inc. All rights reserved. // import Foundation public struct CruOktaUser: Codable { public let email: String public let grMasterPersonId: String public let name: String public let ssoguid: String enum CodingKeys: String, CodingKey { case email = "email" case grMasterPersonId = "grMasterPersonId" case name = "name" case ssoguid = "ssoguid" } }
21
58
0.641026
e077cc1af8c4c4a9414a52394ff563c793261f26
197
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing <T let h{enum B{class case,
24.625
87
0.761421
03f90f9eb2b1718285b09638caebf9100a0c8426
319
// // AddressRepositoryProtocol.swift // WavesWallet-iOS // // Created by Prokofev Ruslan on 20/01/2019. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation import RxSwift public protocol AddressRepositoryProtocol { func isSmartAddress(accountAddress: String) -> Observable<Bool> }
19.9375
67
0.752351
8921f59d9a8bf5000c9efa2e331adc0921e536a3
4,222
// // MainMenu.swift // CaveFlyer // // Created by Henry Oliver on 21/10/19. // Copyright © 2019 Henry Oliver. All rights reserved. // import SpriteKit import GameplayKit class MainMenuScene: SKScene { var titleText: SKLabelNode! var playText: SKLabelNode! var tutText: SKLabelNode! var heli: SKSpriteNode! var longPressed: Bool = false var longPressGestureRecognizer = UILongPressGestureRecognizer() var tapGestureRecognizer = UITapGestureRecognizer() //On start override func didMove(to view: SKView){ //self.backgroundColor = UIColor.gray CreateText() CreateHeli() CreateGestures() } //Gesture Inputs @objc func longPress(sender: UILongPressGestureRecognizer){ if (longPressed == false){ let newScene = HardGameScene(size: (self.view?.bounds.size)!) let transition = SKTransition.reveal(with: .down, duration: 0.2) self.view?.presentScene(newScene, transition: transition) transition.pausesOutgoingScene = true longPressed = true } } @objc func tap(sender: UITapGestureRecognizer){ let newScene = GameScene(size: (self.view?.bounds.size)!) let transition = SKTransition.reveal(with: .up, duration: 0.2) self.view?.presentScene(newScene, transition: transition) transition.pausesOutgoingScene = true } //Create Gestures func CreateGestures(){ //Long press guard let view = view else { return } longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress)) longPressGestureRecognizer.minimumPressDuration = 1 view.addGestureRecognizer(longPressGestureRecognizer) //Tap tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tap)) tapGestureRecognizer.numberOfTapsRequired = 1 view.addGestureRecognizer(tapGestureRecognizer) } //Create text nodes func CreateText(){ titleText = SKLabelNode() titleText.text = "Cave Flyer" titleText.fontSize = 32.0 titleText.fontName = "Copperplate" titleText.position = CGPoint(x: self.frame.midX, y: self.frame.midY+150) titleText.fontColor = UIColor.white self.addChild(titleText) playText = SKLabelNode() playText.text = "Tap To Start" playText.fontSize = 14.0 playText.fontName = "Copperplate" playText.position = CGPoint(x: self.frame.midX, y: self.frame.midY+100) playText.fontColor = UIColor.white self.addChild(playText) tutText = SKLabelNode() tutText.text = "Hold For Impossible Mode" tutText.fontSize = 10.0 tutText.fontName = "Copperplate" tutText.position = CGPoint(x: self.frame.midX, y: self.frame.midY+80) tutText.fontColor = UIColor.white self.addChild(tutText) //Animation let fadeIn = SKAction.fadeAlpha(to: 1, duration: 1.2) let fadeOut = SKAction.fadeAlpha(to: 0, duration: 1.2) let fadeAction = SKAction.sequence([fadeIn, fadeOut]) playText.run(SKAction.repeatForever(fadeAction)) } //create heli node func CreateHeli(){ heli = SKSpriteNode(texture: SKTexture(imageNamed: "f1"), size: CGSize(width: 300, height: 300)) heli.position = CGPoint(x: self.frame.midX, y: self.frame.midY-25)//25 - 100 heli.zRotation = (-25.0 * CGFloat(Double.pi/180.0)) //Animation let heliAtlas = SKTextureAtlas(named: "Helicopter") let flyAction = SKAction.animate(with: [heliAtlas.textureNamed("f1"), heliAtlas.textureNamed("f2")], timePerFrame: 0.1) let hoverDown = SKAction.moveTo(y: self.frame.midY-100, duration: 1.0) let hoverUp = SKAction.moveTo(y: self.frame.midY-25, duration: 1.0) let hoverAction = SKAction.sequence([hoverDown, hoverUp]) heli.run(SKAction.repeatForever(flyAction)) heli.run(SKAction.repeatForever(hoverAction)) self.addChild(heli) } }
35.478992
127
0.639507
0e76541a62e8796b6cafd20bc2b77b8e25cf9218
5,048
// // FinalBugViewController.swift // SoManyBugs // // Created by Jarrod Parkes on 4/16/15. // Copyright (c) 2015 Jarrod Parkes. All rights reserved. // import UIKit // MARK: - FinalBugViewController: UIViewController class FinalBugViewController: UIViewController { // MARK: Properties let bugFactory = BugFactory.sharedInstance() let maxBugs = 100 let moveDuration = 3.0 let disperseDuration = 1.0 var bugs = [UIImageView]() // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() let singleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap)) view.addGestureRecognizer(singleTapRecognizer) } // MARK: Bug Functions func addBugToView() { if bugs.count < maxBugs { let newBug = bugFactory.createBug() bugs.append(newBug) view.addSubview(newBug) moveBugsAnimation() } } func emptyBugsFromView() { for bug in self.bugs { bug.removeFromSuperview() } self.bugs.removeAll(keepingCapacity: true) } // MARK: View Animations func moveBugsAnimation() { UIView.animate(withDuration: moveDuration) { for bug in self.bugs { let randomPosition = CGPoint(x: CGFloat(arc4random_uniform(UInt32(UInt(self.view.bounds.maxX - bug.frame.size.width))) + UInt32(bug.frame.size.width/2)), y: CGFloat(arc4random_uniform(UInt32(UInt(self.view.bounds.maxY - bug.frame.size.height))) + UInt32(bug.frame.size.height/2))) bug.frame = CGRect(x: randomPosition.x - bug.frame.size.width/1.5, y: randomPosition.y - bug.frame.size.height/1.5, width: BugFactory.bugSize.width, height: BugFactory.bugSize.height) } } } func disperseBugsAnimation() { UIView.animate(withDuration: disperseDuration, animations: { () -> Void in for bug in self.bugs { let offScreenPosition = CGPoint(x: (bug.center.x - self.view.center.x) * 20, y: (bug.center.y - self.view.center.y) * 20) bug.frame = CGRect(x: offScreenPosition.x, y: offScreenPosition.y, width: BugFactory.bugSize.width, height: BugFactory.bugSize.height) } }, completion: { (finished) -> Void in if finished { self.emptyBugsFromView() } }) } // MARK: Actions @IBAction func popToMasterView() { self.navigationController!.popToRootViewController(animated: true) } } // MARK: - FinalBugViewController (UIResponder) extension FinalBugViewController { override var canBecomeFirstResponder: Bool { return true } override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { if motion == .motionShake { disperseBugsAnimation() } } @objc func handleSingleTap(_ recognizer: UITapGestureRecognizer) { addBugToView() } } // MARK: - FinalBugViewController (CustomStringConvertible) // NOTE: You don't have to conform to CustomStringConvertible since this is already done by FinalBugViewController's superclasses (via NSObject). extension FinalBugViewController { override var description: String { return "FinalBugViewController contains \(bugs.count) bugs\n" } } // MARK: - FinalBugViewController (CustomDebugStringConvertible) // NOTE: You don't have to conform to CustomDebugStringConvertible since this is already done by FinalBugViewController's superclasses (via NSObject). extension FinalBugViewController { override var debugDescription: String { var index = 0 var debugString = "FinalBugViewController contains \(bugs.count) bugs...\n" for bug in bugs { debugString = debugString + "Bug\(index): \(bug.frame)\n" index += 1 } return debugString } } // MARK: - FinalBugViewController (debugQuickLookObject) extension FinalBugViewController { func debugQuickLookObject() -> AnyObject? { let singleSquareLength: CGFloat = 10.0 let squaresInRow = 10 let imageSize = CGSize(width: singleSquareLength * CGFloat(squaresInRow), height: singleSquareLength * CGFloat(bugs.count / squaresInRow + 1)) UIGraphicsBeginImageContextWithOptions(imageSize, true, 0) var x: CGFloat = 0.0 var y: CGFloat = 0.0 for bug in bugs { bug.tintColor.set() UIRectFill(CGRect(x: x, y: y, width: singleSquareLength, height: singleSquareLength)) x += singleSquareLength if x > CGFloat(squaresInRow) * singleSquareLength { y += singleSquareLength x = 0.0 } } UIColor.yellow.set() UIRectFill(CGRect(x: x, y: y, width: singleSquareLength, height: singleSquareLength)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
34.340136
296
0.645602
4b4f82b720c9167852479e57052077979af9c3f5
3,615
// // Twister.swift // Twister // // Created by Nikhil Sharma on 02/07/18. // Copyright © 2018 Nikhil Sharma. All rights reserved. // ///////////////////////////////////////////////////////////// //URL Parameters (Optional): this is another Dictionary ([String:Any?]) used to compose a dynamic endpoint. If your endpoint require dynamic values (ie. "/articles/{category}/id/{art_id}" ) you can use this dictionary to fill up placeholders (ie. passing ["category":"scifi","art_id":5999] ). //Body (Optional): this the body of the request; its a struct of type RequestBody where you can specify the data to put in body. You can create a JSON Body using let body = RequestBody(json: data) (you can pass any JSON serializable structure); URL Encoded Body is supported (let body = RequestBody(urlEncoded: paramsDict) . Finally you can create a body with raw String or plain Data or provide your own encoding. ///////////////////////////////////////////////////////////// import Foundation import Alamofire import Hydra ///This type encapsulates baseUrl, endpoint, methodType needed by Alamofire request public struct Route{ var r_endpoint:String var r_methodType:HTTPMethod public init(endPoint:String,methodType:HTTPMethod){ self.r_endpoint = endPoint self.r_methodType = methodType } } public enum TwistError:Error{ case configurationError(_ : String) case invalidURL(_: String) case missingEndpoint case noResponse case encodingFailed(_ : Any) case invalidRequestBody(_ : Any?) } public class Twister{ public var configuration:TwistConfig? public init(_ config:TwistConfig? = nil){ if let conf = config{ self.configuration = conf }else{ self.configuration = TwistConfig() } } /// Serial queue for cache network operations let networkQueue = DispatchQueue.init(label: "com.twister.networkQueue") /// This method is used to make an api call using twister /// /// - Parameters: /// - request: TwistRequest object which encapculates request params,headers etc. /// - autoRetryCount: number of times api should retry automatically /// - Returns: promise with reponse data encapsulated in TwistReponse object func apiRequest<Model>(request:TwistRequest<Model>,autoRetryCount:Int? = nil)->Promise<TwistResponse<Model>>{ guard let config = self.configuration else{ fatalError("Twist configuartion not found.") } let operation = Promise<TwistResponse<Model>>(in: request.context ?? .custom(queue: networkQueue), token: request.invalidationToken,{ (fulfill, reject, status) in let rq = try Alamofire.request(request.urlRequest(in: config)) rq.responseData{ (responseData) in let response = TwistResponse<Model>(responseData) switch response.type{ case .success: do{ try response.decodeJSON() fulfill(response) }catch let error{ reject(error) } case .failure(let code): let error = NSError(domain: "", code: code, userInfo: nil) reject(error) case .noResponse: reject(TwistError.noResponse) } } }) guard let retryAttempts = autoRetryCount else { return operation } // single shot return operation.retry(retryAttempts) // retry n times } }
41.551724
418
0.619364
89421aaa1ce7814322e39e2abf2dcb1f411ef978
108
// Copyright © Fleuronic LLC. All rights reserved. public extension JSONBin.V3.API { enum Collection {} }
18
50
0.731481
e01d14ded43c8a1b6b109ed35a985337ffe73ab0
546
// // UIView+Extension.swift // News // // Created by zlf on 2018/5/10. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit protocol RegistterCellOrNib {} extension RegistterCellOrNib{ static var identifier: String { return "\(self)" } static var nib: UINib? { return UINib(nibName: "\(self)", bundle: nil) } } protocol NibLoada {} extension NibLoada { static func loadFromNib() -> Self { return Bundle.main.loadNibNamed("\(self)", owner: nil, options: nil)?.last as! Self } }
19.5
91
0.6337
56208d91806303b544f078c47ea4e8322eeca909
335
@testable import client_ios import Nimble import Quick class ___FILEBASENAMEASIDENTIFIER___: QuickSpec { override func spec() { describe("something") { context("when this") { it("does that") { expect(hello).to(equal(world)) } } } } }
20.9375
50
0.513433
ffe15a77927d0809784cca0b4f4e62451b0035cf
1,064
// // MovieDetailModuleInterfaces.swift // Movie DB Test // // Created by John Edwin Guerrero Ayala on 6/9/19. // Copyright (c) 2019 John Edwin Guerrero Ayala. All rights reserved. // // This file was generated by the 🐍 VIPER generator // import UIKit enum DetailsNavigationOption { case back } typealias MovieServiceResult = (_ apiMovieResponse: Movie?, _ error: Error?) -> Void protocol MovieDetailModuleWireframeInterface: WireframeInterface { func navigate(to option: DetailsNavigationOption) } protocol MovieDetailModuleViewInterface: ViewInterface { func startLoading() func finishLoading() func setMovie(movie: Movie) func showErrorView() func showEmptyView() } protocol MovieDetailModulePresenterInterface: PresenterInterface { func closeMovieDetailView() func getMovieDetails() } protocol MovieDetailModuleFormatterInterface: FormatterInterface { } protocol MovieDetailModuleInteractorInterface: InteractorInterface { func getMovieDetails(for movieId: Int, completion: @escaping MovieServiceResult) }
24.744186
84
0.772556
db2f5a57b9288615c40271d78d584febd7db4f80
497
// // TicTacToeStrategy.swift // TicTacToe // // Copyright © 2017 Pedro Albuquerque. All rights reserved. // import Foundation /** Describes an object capable of deciding where to put the next mark on a GameBoard. */ public protocol TicTacToeStrategy { func choosePositionForMark(mark: Mark, onGameBoard gameBoard: GameBoard, completionHandler: GameBoard.Position -> Void) } public func createArtificialIntelligenceStrategy() -> TicTacToeStrategy { return NewellAndSimonStrategy() }
27.611111
123
0.768612
62f4fc3a553d9c714dc5b4c34c0b39666228c8cc
752
import XCTest import LZSwiftColorKit class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.931034
111
0.603723
1d74dc88c2a98473fbe5df9fddfb1eb4ed67192c
435
// // ErrorHandlingServiceAssembly.swift // Weather // // Created by Sergey on 03/03/2019. // Copyright © 2019 Sergey V. Krupov. All rights reserved. // import Swinject final class ErrorHandlingServiceAssembly: Assembly { func assemble(container: Container) { container.register(ErrorHandlingService.self) { _ in ErrorHandlingComponent() } .implements(ErrorResolvingService.self) } }
21.75
60
0.687356
911b3c883650cf7765d33cc03369e5fd7af08bd5
414
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing n class l<g> { let enum e<q> : r { func k<q>() -> q -> q { return { h o h 1 { } } class k { m func p() -> String { let m: String = { }() struct g<b where f.h == e.h> { } } } protocol h : e { func e
18.818182
87
0.623188
de83396bd8c844669fe7595d40ddd4acc07bf1c5
1,266
// // ResponderTextField.swift // TogglDesktop // // Created by Andrew Nester on 10.08.2020. // Copyright © 2020 Toggl. All rights reserved. // import Foundation class ResponderTextField: NSTextField, ResponderObservable { var observations = ( becomeResponder: [UUID: () -> Void](), resignResponder: [UUID: () -> Void]() ) override func becomeFirstResponder() -> Bool { defer { observations.becomeResponder.values.forEach { $0() } } return super.becomeFirstResponder() } override func resignFirstResponder() -> Bool { defer { observations.resignResponder.values.forEach { $0() } } return super.resignFirstResponder() } override func mouseDown(with event: NSEvent) { super.mouseDown(with: event) observations.becomeResponder.values.forEach { $0() } } override func textDidBeginEditing(_ notification: Notification) { super.textDidBeginEditing(notification) observations.becomeResponder.values.forEach { $0() } } override func textDidEndEditing(_ notification: Notification) { super.textDidEndEditing(notification) observations.resignResponder.values.forEach { $0() } } }
26.93617
69
0.647709
e473ab56a3fdb0bf5948d28ac9533690222d5dc1
5,392
// // WXMiddleButtonTabBar.swift // GitBucket // // Created by sulirong on 2018/1/23. // Copyright © 2018年 CleanAirGames. All rights reserved. // import UIKit protocol WXMiddleButtonTabBarDelegate: class { func tabBarMiddleButtonDidSelected(_ tabBar: WXMiddleButtonTabBar) func tabBarMiddleButtonDidLongPressed(_ tabBar: WXMiddleButtonTabBar) } extension WXMiddleButtonTabBarDelegate { func tabBarMiddleButtonDidLongPressed(_ tabBar: WXMiddleButtonTabBar) {} } class WXMiddleButtonTabBar: UITabBar { //MARK: Properties static var normalTextColor: UIColor? static var selectedTextColor: UIColor? weak var wxDelegate: WXMiddleButtonTabBarDelegate? var imageViewsArray: [UIImageView] { return internalImageViewsArray } var labelsArray: [UILabel] { return internalLabelsArray } //MARK: Public Methods func setMiddleButton(_ button: UIButton, atCenterY centerY: CGFloat) { self.middleButton = button self.middleButtonCenterY = centerY button.sizeToFit() addSubview(button) button.addTarget(self, action: #selector(middleButtonClicked), for: .touchUpInside) let longPress = UILongPressGestureRecognizer(target: self, action: #selector(middleButtonLongPressed(_:))) button.addGestureRecognizer(longPress) } //MARK: Overrides override init(frame: CGRect) { middleButtonCenterY = 0 internalImageViewsArray = [] internalLabelsArray = [] super.init(frame: frame) customizeAppearance() } required init?(coder aDecoder: NSCoder) { middleButtonCenterY = 0 internalImageViewsArray = [] internalLabelsArray = [] super.init(coder: aDecoder) customizeAppearance() } override func didAddSubview(_ subview: UIView) { if let buttonClass = NSClassFromString("UITabBarButton") { if subview.isKind(of: buttonClass) { for view in subview.subviews { if view is UIImageView { self.internalImageViewsArray.append(view as! UIImageView) } else if view is UILabel { self.internalLabelsArray.append(view as! UILabel) } } } } } override func layoutSubviews() { super.layoutSubviews() self.middleButton?.center = CGPoint(x: self.frame.size.width / 2, y: self.middleButtonCenterY) var buttonsArray = [UIView]() if let buttonClass = NSClassFromString("UITabBarButton") { for view in self.subviews { if view.isKind(of: buttonClass) { buttonsArray.append(view) } } } var btnIndex = 0 let buttonWidth: CGFloat = self.frame.size.width / CGFloat(buttonsArray.count + 1) for button in buttonsArray { button.frame = CGRect(x: buttonWidth * CGFloat(btnIndex), y: button.frame.origin.y, width: buttonWidth, height: button.frame.size.height) btnIndex += 1 if btnIndex == buttonsArray.count / 2 { btnIndex += 1 } } if let _ = self.middleButton { bringSubview(toFront: self.middleButton!) } } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { guard let _ = self.middleButton else { return super.hitTest(point, with: event) } if !self.isHidden { let newPoint = self.convert(point, to: self.middleButton) if self.middleButton!.point(inside: newPoint, with: event) { return self.middleButton } else { return super.hitTest(point, with: event) } } else { return super.hitTest(point, with: event) } } //MARK: Private fileprivate var middleButton: UIButton? fileprivate var middleButtonCenterY: CGFloat fileprivate var internalImageViewsArray: [UIImageView] fileprivate var internalLabelsArray: [UILabel] func customizeAppearance() { let tabBarItem = UITabBarItem.appearance(whenContainedInInstancesOf: [type(of: self)]) if let normalColor = WXMiddleButtonTabBar.normalTextColor { let normalAttributes = [NSAttributedStringKey.foregroundColor: normalColor] tabBarItem.setTitleTextAttributes(normalAttributes, for: .normal) } if let selectedColor = WXMiddleButtonTabBar.selectedTextColor { let selectedAttributes = [NSAttributedStringKey.foregroundColor: selectedColor] tabBarItem.setTitleTextAttributes(selectedAttributes, for: .selected) } } @objc func middleButtonClicked() { if let _ = self.wxDelegate { self.wxDelegate?.tabBarMiddleButtonDidSelected(self) } } @objc func middleButtonLongPressed(_ gestureRecognizer: UILongPressGestureRecognizer) { if gestureRecognizer.state == .began { if let _ = self.wxDelegate { self.wxDelegate?.tabBarMiddleButtonDidLongPressed(self) } } } }
32.878049
149
0.611832
f5286312f1e654a4de1042e45565043534f06360
2,001
// // MZCTabBarView.swift // MZCWB // // Created by 马纵驰 on 16/7/20. // Copyright © 2016年 马纵驰. All rights reserved. // import UIKit import QorumLogs protocol MZCTabBarViewDelegate : NSObjectProtocol { func messageDidClick() } class MZCTabBarView: UITabBar { weak var messageDelegate : MZCTabBarViewDelegate? override init(frame: CGRect) { super.init(frame: frame) backgroundImage = UIImage(named: "tabbar_background") } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } lazy var button : UIButton = { let addButton = UIButton(imgName: "tabbar_compose_icon_add", titleString: nil, target: self, action: #selector(MZCTabBarView.messageDidClick)) // 设置背景图片 addButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal) addButton.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted) self.addSubview(addButton) return addButton }() override func layoutSubviews() { let w : CGFloat = self.bounds.size.width / 5 let h : CGFloat = self.bounds.size.height for i in 0..<self.subviews.count { let view = self.subviews[i] var x : CGFloat if i >= 2{ x = w * CGFloat(i + 1) }else{ x = w * CGFloat(i) } view.frame = CGRectMake(x, 0.0, w, h) } let buttonX = self.bounds.size.width / 2 let buttonY = self.bounds.size.height / 2 self.button.bounds = CGRectMake(0, 0, w, h) self.button.center = CGPointMake(buttonX, buttonY) } } extension MZCTabBarView { @objc private func messageDidClick(){ messageDelegate!.messageDidClick() } }
25.329114
150
0.57921
8f09a446db3971c3ed4c9f05b5d3faca763d8b16
14,079
import UIKit public protocol LightboxControllerPageDelegate: class { func lightboxController(_ controller: LightboxController, didMoveToPage page: Int) } public protocol LightboxControllerDismissalDelegate: class { func lightboxControllerWillDismiss(_ controller: LightboxController) } public protocol LightboxControllerTouchDelegate: class { func lightboxController(_ controller: LightboxController, didTouch image: LightboxImage, at index: Int) } public protocol LightboxControllerDeleteDelegate: class { func lightboxController(_ controller: LightboxController, didDeleteImageAt index: Int) } open class LightboxController: UIViewController { // MARK: - Internal views lazy var scrollView: UIScrollView = { [unowned self] in let scrollView = UIScrollView() scrollView.isPagingEnabled = false scrollView.delegate = self scrollView.showsHorizontalScrollIndicator = false scrollView.decelerationRate = UIScrollView.DecelerationRate.fast return scrollView }() lazy var overlayTapGestureRecognizer: UITapGestureRecognizer = { [unowned self] in let gesture = UITapGestureRecognizer() gesture.addTarget(self, action: #selector(overlayViewDidTap(_:))) return gesture }() lazy var effectView: UIVisualEffectView = { let effect = UIBlurEffect(style: .dark) let view = UIVisualEffectView(effect: effect) view.autoresizingMask = [.flexibleWidth, .flexibleHeight] return view }() lazy var backgroundView: UIImageView = { let view = UIImageView() view.autoresizingMask = [.flexibleWidth, .flexibleHeight] return view }() // MARK: - Public views open fileprivate(set) lazy var headerView: HeaderView = { [unowned self] in let view = HeaderView() view.delegate = self return view }() open fileprivate(set) lazy var footerView: FooterView = { [unowned self] in let view = FooterView() view.delegate = self return view }() open fileprivate(set) lazy var overlayView: UIView = { [unowned self] in let view = UIView(frame: CGRect.zero) let gradient = CAGradientLayer() let colors = [UIColor(hex: "090909").withAlphaComponent(0), UIColor(hex: "040404")] view.addGradientLayer(colors) view.alpha = 0 return view }() // MARK: - Properties open fileprivate(set) var currentPage = 0 { didSet { currentPage = min(numberOfPages - 1, max(0, currentPage)) footerView.updatePage(currentPage + 1, numberOfPages) footerView.updateText(pageViews[currentPage].image.text) if currentPage == numberOfPages - 1 { seen = true } reconfigurePagesForPreload() pageDelegate?.lightboxController(self, didMoveToPage: currentPage) if let image = pageViews[currentPage].imageView.image, dynamicBackground { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.125) { self.loadDynamicBackground(image) } } } } open var numberOfPages: Int { return pageViews.count } open var dynamicBackground: Bool = false { didSet { if dynamicBackground == true { effectView.frame = view.frame backgroundView.frame = effectView.frame view.insertSubview(effectView, at: 0) view.insertSubview(backgroundView, at: 0) } else { effectView.removeFromSuperview() backgroundView.removeFromSuperview() } } } open var spacing: CGFloat = 20 { didSet { configureLayout(view.bounds.size) } } open var images: [LightboxImage] { get { return pageViews.map { $0.image } } set(value) { initialImages = value configurePages(value) } } open weak var pageDelegate: LightboxControllerPageDelegate? open weak var dismissalDelegate: LightboxControllerDismissalDelegate? open weak var imageTouchDelegate: LightboxControllerTouchDelegate? open weak var imageDeleteDelegate: LightboxControllerDeleteDelegate? open internal(set) var presented = false open fileprivate(set) var seen = false lazy var transitionManager: LightboxTransition = LightboxTransition() var pageViews = [PageView]() var statusBarHidden = false fileprivate var initialImages: [LightboxImage] fileprivate let initialPage: Int // MARK: - Initializers public init(images: [LightboxImage] = [], startIndex index: Int = 0) { self.initialImages = images self.initialPage = index super.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View lifecycle open override func viewDidLoad() { super.viewDidLoad() statusBarHidden = UIApplication.shared.isStatusBarHidden view.backgroundColor = UIColor.black transitionManager.lightboxController = self transitionManager.scrollView = scrollView transitioningDelegate = transitionManager [scrollView, overlayView, headerView, footerView].forEach { view.addSubview($0) } overlayView.addGestureRecognizer(overlayTapGestureRecognizer) configurePages(initialImages) goTo(initialPage, animated: false) } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !presented { presented = true configureLayout(view.bounds.size) } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.frame = view.bounds footerView.frame.size = CGSize( width: view.bounds.width, height: 100 ) footerView.frame.origin = CGPoint( x: 0, y: view.bounds.height - footerView.frame.height ) headerView.frame = CGRect( x: 0, y: 16, width: view.bounds.width, height: 100 ) } open override var prefersStatusBarHidden: Bool { return LightboxConfig.hideStatusBar } // MARK: - Rotation override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.configureLayout(size) }, completion: nil) } // MARK: - Configuration func configurePages(_ images: [LightboxImage]) { pageViews.forEach { $0.removeFromSuperview() } pageViews = [] let preloadIndicies = calculatePreloadIndicies() for i in 0..<images.count { let pageView = PageView(image: preloadIndicies.contains(i) ? images[i] : LightboxImageStub()) pageView.pageViewDelegate = self scrollView.addSubview(pageView) pageViews.append(pageView) } configureLayout(view.bounds.size) } func reconfigurePagesForPreload() { let preloadIndicies = calculatePreloadIndicies() for i in 0..<initialImages.count { if i <= pageViews.count-1 { let pageView = pageViews[i] if preloadIndicies.contains(i) { if type(of: pageView.image) == LightboxImageStub.self { pageView.update(with: initialImages[i]) } } else { if type(of: pageView.image) != LightboxImageStub.self { pageView.update(with: LightboxImageStub()) } } } } } // MARK: - Pagination open func goTo(_ page: Int, animated: Bool = true) { guard page >= 0 && page < numberOfPages else { return } currentPage = page var offset = scrollView.contentOffset offset.x = CGFloat(page) * (scrollView.frame.width + spacing) let shouldAnimated = view.window != nil ? animated : false scrollView.setContentOffset(offset, animated: shouldAnimated) } open func next(_ animated: Bool = true) { goTo(currentPage + 1, animated: animated) } open func previous(_ animated: Bool = true) { goTo(currentPage - 1, animated: animated) } // MARK: - Actions @objc func overlayViewDidTap(_ tapGestureRecognizer: UITapGestureRecognizer) { footerView.expand(false) } // MARK: - Layout open func configureLayout(_ size: CGSize) { scrollView.frame.size = size scrollView.contentSize = CGSize( width: size.width * CGFloat(numberOfPages) + spacing * CGFloat(numberOfPages - 1), height: size.height) scrollView.contentOffset = CGPoint(x: CGFloat(currentPage) * (size.width + spacing), y: 0) for (index, pageView) in pageViews.enumerated() { var frame = scrollView.bounds frame.origin.x = (frame.width + spacing) * CGFloat(index) pageView.frame = frame pageView.configureLayout() if index != numberOfPages - 1 { pageView.frame.size.width += spacing } } [headerView, footerView].forEach { ($0 as AnyObject).configureLayout() } overlayView.frame = scrollView.frame overlayView.resizeGradientLayer() } fileprivate func loadDynamicBackground(_ image: UIImage) { backgroundView.image = image backgroundView.layer.add(CATransition(), forKey: CATransitionType.fade.rawValue) } func toggleControls(pageView: PageView?, visible: Bool, duration: TimeInterval = 0.1, delay: TimeInterval = 0) { let alpha: CGFloat = visible ? 1.0 : 0.0 pageView?.playButton.isHidden = !visible UIView.animate(withDuration: duration, delay: delay, options: [], animations: { self.headerView.alpha = alpha self.footerView.alpha = alpha pageView?.playButton.alpha = alpha }, completion: nil) } // MARK: - Helper functions func calculatePreloadIndicies () -> [Int] { var preloadIndicies: [Int] = [] let preload = LightboxConfig.preload if preload > 0 { let lb = max(0, currentPage - preload) let rb = min(initialImages.count, currentPage + preload) for i in lb..<rb { preloadIndicies.append(i) } } else { preloadIndicies = [Int](0..<initialImages.count) } return preloadIndicies } } // MARK: - UIScrollViewDelegate extension LightboxController: UIScrollViewDelegate { public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { var speed: CGFloat = velocity.x < 0 ? -2 : 2 if velocity.x == 0 { speed = 0 } let pageWidth = scrollView.bounds.width + spacing var x = scrollView.contentOffset.x + speed * 60.0 if speed > 0 { x = ceil(x / pageWidth) * pageWidth } else if speed < -0 { x = floor(x / pageWidth) * pageWidth } else { x = round(x / pageWidth) * pageWidth } targetContentOffset.pointee.x = x currentPage = Int(x / pageWidth) } } // MARK: - PageViewDelegate extension LightboxController: PageViewDelegate { func remoteImageDidLoad(_ image: UIImage?, imageView: UIImageView) { guard let image = image, dynamicBackground else { return } let imageViewFrame = imageView.convert(imageView.frame, to: view) guard view.frame.intersects(imageViewFrame) else { return } loadDynamicBackground(image) } func pageViewDidZoom(_ pageView: PageView) { let duration = pageView.hasZoomed ? 0.1 : 0.5 toggleControls(pageView: pageView, visible: !pageView.hasZoomed, duration: duration, delay: 0.5) } func pageView(_ pageView: PageView, didTouchPlayButton videoURL: URL) { LightboxConfig.handleVideo(self, videoURL) } func pageViewDidTouch(_ pageView: PageView) { guard !pageView.hasZoomed else { return } imageTouchDelegate?.lightboxController(self, didTouch: images[currentPage], at: currentPage) let visible = (headerView.alpha == 1.0) toggleControls(pageView: pageView, visible: !visible) } } // MARK: - HeaderViewDelegate extension LightboxController: HeaderViewDelegate { func headerView(_ headerView: HeaderView, didPressDeleteButton deleteButton: UIButton) { let alert = UIAlertController(title: NSLocalizedString("Delete image", comment: "Lightbox Alert controller"), message: NSLocalizedString("Would you like to delete the selected image?", comment: "Lightbox Alert controller"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Default action"), style: .`default`, handler: { _ in NSLog("The \"OK\" alert occured.")})) alert.addAction(UIAlertAction(title: NSLocalizedString("Delete", comment: "Confirm delete"), style: .`default`, handler: { _ in deleteButton.isEnabled = false guard self.numberOfPages != 1 else { self.pageViews.removeAll() self.headerView(headerView, didPressCloseButton: headerView.closeButton) self.imageDeleteDelegate?.lightboxController(self, didDeleteImageAt: self.currentPage) return } let prevIndex = self.currentPage if self.currentPage == self.numberOfPages - 1 { self.previous() } else { self.next() self.currentPage -= 1 } self.pageViews.remove(at: prevIndex).removeFromSuperview() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { self.configureLayout(self.view.bounds.size) self.currentPage = Int(self.scrollView.contentOffset.x / self.view.bounds.width) deleteButton.isEnabled = true self.imageDeleteDelegate?.lightboxController(self, didDeleteImageAt: prevIndex) } })) present(alert, animated: true, completion: nil) } func headerView(_ headerView: HeaderView, didPressCloseButton closeButton: UIButton) { closeButton.isEnabled = false presented = false dismissalDelegate?.lightboxControllerWillDismiss(self) dismiss(animated: true, completion: nil) } } // MARK: - FooterViewDelegate extension LightboxController: FooterViewDelegate { public func footerView(_ footerView: FooterView, didExpand expanded: Bool) { UIView.animate(withDuration: 0.25, animations: { self.overlayView.alpha = expanded ? 1.0 : 0.0 self.headerView.deleteButton.alpha = expanded ? 0.0 : 1.0 }) } }
29.149068
251
0.686696
fc03b93d41134b711d461a2cc256ca4f5f52292c
8,578
// 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 Foundation import CoreGraphics.CGBase enum Constants { static let filters = NSLocalizedString("filters", comment: "") static let clearAll = NSLocalizedString("clearAll", comment: "") static let search = NSLocalizedString("search", comment: "") static let loading = NSLocalizedString("loading", comment: "") static let library = NSLocalizedString("library", comment: "") static let myTutorials = NSLocalizedString("myTutorials", comment: "") static let downloads = NSLocalizedString("downloads", comment: "") static let newest = NSLocalizedString("newest", comment: "") static let popularity = NSLocalizedString("popularity", comment: "") static let tutorials = NSLocalizedString("tutorials", comment: "") static let settings = NSLocalizedString("settings", comment: "") // Onboarding static let login = NSLocalizedString("login", comment: "") // Other static let today = NSLocalizedString("today", comment: "") static let by = NSLocalizedString("by", comment: "") static let yes = NSLocalizedString("yes", comment: "") static let no = NSLocalizedString("no", comment: "") // swiftlint:disable:this identifier_name // Video playback static let videoPlaybackProgressTrackingInterval: Int = 5 static let videoPlaybackOfflinePermissionsCheckPeriod: TimeInterval = 7 * 24 * 60 * 60 // Message Banner static let autoDismissTime: TimeInterval = 3 // Appearance static let blurRadius: CGFloat = 5 // Messaging static let bookmarkCreated = NSLocalizedString("bookmarkCreated", comment: "") static let bookmarkDeleted = NSLocalizedString("bookmarkDeleted", comment: "") static let bookmarkCreatedError = NSLocalizedString("bookmarkCreatedError", comment: "") static let bookmarkDeletedError = NSLocalizedString("bookmarkDeletedError", comment: "") static let progressRemoved = NSLocalizedString("progressRemoved", comment: "") static let progressMarkedAsComplete = NSLocalizedString("progressMarkedAsComplete", comment: "") static let progressRemovedError = NSLocalizedString("progressRemovedError", comment: "") static let progressMarkedAsCompleteError = NSLocalizedString("progressMarkedAsCompleteError", comment: "") static let downloadRequestedSuccessfully = NSLocalizedString("downloadRequestedSuccessfully", comment: "") static let downloadRequestedButQueueInactive = NSLocalizedString("downloadRequestedButQueueInactive", comment: "") static let downloadNotPermitted = NSLocalizedString("downloadNotPermitted", comment: "") static let downloadContentNotFound = NSLocalizedString("downloadContentNotFound", comment: "") static let downloadRequestProblem = NSLocalizedString("downloadRequestProblem", comment: "") static let downloadCancelled = NSLocalizedString("downloadCancelled", comment: "") static let downloadDeleted = NSLocalizedString("downloadDeleted", comment: "") static let downloadReset = NSLocalizedString("downloadReset", comment: "") static let downloadUnspecifiedProblem = NSLocalizedString("downloadUnspecifiedProblem", comment: "") static let downloadUnableToCancel = NSLocalizedString("downloadUnableToCancel", comment: "") static let downloadUnableToDelete = NSLocalizedString("downloadUnableToDelete", comment: "") static let simultaneousStreamsError = NSLocalizedString("simultaneousStreamsError", comment: "") static let downloadedContentNotFound = NSLocalizedString("downloadedContentNotFound", comment: "") static let videoPlaybackCannotStreamWhenOffline = NSLocalizedString("videoPlaybackCannotStreamWhenOffline", comment: "") static let videoPlaybackInvalidPermissions = NSLocalizedString("videoPlaybackInvalidPermissions", comment: "") static let videoPlaybackExpiredPermissions = NSLocalizedString("videoPlaybackExpiredPermissions", comment: "") static let appIconUpdatedSuccessfully = NSLocalizedString("appIconUpdatedSuccessfully", comment: "") static let appIconUpdateProblem = NSLocalizedString("appIconUpdateProblem", comment: "") // Settings screens static let settingsPlaybackSpeedLabel = NSLocalizedString("settingsPlaybackSpeedLabel", comment: "") static let settingsWifiOnlyDownloadsLabel = NSLocalizedString("settingsWifiOnlyDownloadsLabel", comment: "") static let settingsDownloadQualityLabel = NSLocalizedString("settingsDownloadQualityLabel", comment: "") static let settingsClosedCaptionOnLabel = NSLocalizedString("settingsClosedCaptionOnLabel", comment: "") // Detail View static let detailContentLockedCosPro = NSLocalizedString("detailContentLockedCosPro", comment: "") // Pull-to-refresh static let pullToRefreshPullMessage = NSLocalizedString("=", comment: "") static let pullToRefreshLoadingMessage = NSLocalizedString("pullToRefreshLoadingMessage", comment: "") // And more static let watchAnytime = NSLocalizedString("watchAnytime", comment: "") static let watchThousands = NSLocalizedString("watchThousands", comment: "") static let onTheGo = NSLocalizedString("onTheGo", comment: "") static let watchOffline = NSLocalizedString("watchOffline", comment: "") static let signIn = NSLocalizedString("signIn", comment: "") static let noAccess = NSLocalizedString("noAccess", comment: "") static let membersOnly = NSLocalizedString("membersOnly", comment: "") static let signOut = NSLocalizedString("signOut", comment: "") static let showHide = NSLocalizedString("showHide", comment: "") static let postNew = NSLocalizedString("postNew", comment: "") static let forceLogout = NSLocalizedString("forceLogout", comment: "") static let logout = NSLocalizedString("logout", comment: "") static let delete = NSLocalizedString("delete", comment: "") static let noConnection = NSLocalizedString("noConnection", comment: "") static let checkConnection = NSLocalizedString("checkConnection", comment: "") static let wentWrong = NSLocalizedString("wentWrong", comment: "") static let tryAgain = NSLocalizedString("tryAgain", comment: "") static let reload = NSLocalizedString("reload", comment: "") static let hide = NSLocalizedString("hide", comment: "") static let show = NSLocalizedString("show", comment: "") static let toggle = NSLocalizedString("toggle", comment: "") static let filterLibrary = NSLocalizedString("filterLibrary", comment: "") static let libraries = NSLocalizedString("libraries", comment: "") static let licenses = NSLocalizedString("licenses", comment: "") static let appIcon = NSLocalizedString("appIcon", comment: "") static let loggedInAs = NSLocalizedString("loggedInAs", comment: "") static let courseEpisodes = NSLocalizedString("courseEpisodes", comment: "") static let proCourse = NSLocalizedString("proCourse", comment: "") static let inProgress = NSLocalizedString("inProgress", comment: "") static let completed = NSLocalizedString("completed", comment: "") static let bookmarked = NSLocalizedString("bookmarked", comment: "") }
59.569444
122
0.767195
ebd03e45c38d73cba239c74ab86d93fcfa929988
8,054
import Foundation internal struct PropertyList: CustomStringConvertible { internal var elements: PropertyList.Element? init() { elements = nil } var description: String { return "" } } extension PropertyList { class Tracker { } } extension PropertyList { internal class Element: CustomStringConvertible { internal var description: String { return "" } } } /*public struct Transaction { var plist: PropertyList public init() { plist = PropertyList() } }*/ @propertyWrapper @dynamicMemberLookup public struct Binding<Value> { //public var transaction: Transaction //internal var location: AnyLocation<Value> //fileprivate var _value: Value let get:() -> Value let set:(Value) -> Void public init(get: @escaping () -> Value, set: @escaping (Value) -> Void) { //self.transaction = Transaction() //self.location = AnyLocation(value: get()) //self._value = get() //set(_value) self.get=get self.set=set } /*public init(get: @escaping () -> Value, set: @escaping (Value, Transaction) -> Void) { self.transaction = Transaction() self.location = AnyLocation(value: get()) self._value = get() //set(_value, self.transaction) }*/ public static func constant(_ value: Value) -> Binding<Value> { fatalError() } public var wrappedValue: Value { get { /*return location._value*/return get() } nonmutating set {/*location._value=newValue*/set(newValue)} } public var projectedValue: Binding<Value> { self } public subscript<Subject>(dynamicMember keyPath: WritableKeyPath<Value, Subject>) -> Binding<Subject> { fatalError() } } class StoredLocation<Value>: AnyLocation<Value> { } /* extension Binding { public func transaction(_ transaction: Transaction) -> Binding<Value> { fatalError() } // public func animation(_ animation: Animation? = .default) -> Binding<Value> { // // } } */ extension Binding: DynamicProperty { public func update() { //DynamicProperty protocol } } extension Binding { public init<V>(_ base: Binding<V>) where Value == V? { fatalError() } public init?(_ base: Binding<Value?>) { fatalError() } public init<V>(_ base: Binding<V>) where Value == AnyHashable, V : Hashable { fatalError() } } extension Binding { @inlinable public func map<T>(_ keyPath: WritableKeyPath<Value, T>) -> Binding<T> { .init( get: { wrappedValue[keyPath: keyPath] }, set: { wrappedValue[keyPath: keyPath] = $0 } ) } } extension Binding { @inlinable public func mirror(to other: Binding) -> Self { .init( get: { wrappedValue }, set: { wrappedValue = $0 other.wrappedValue = $0 } ) } } extension Binding { @inlinable public func onSet(_ body: @escaping (Value) -> ()) -> Self { return .init( get: { self.wrappedValue }, set: { self.wrappedValue = $0; body($0) } ) } public func printOnSet() -> Self { onSet { print("Set value: \($0)") } } } extension Binding { @inlinable public func onChange(perform action: @escaping (Value) -> ()) -> Self where Value: Equatable { return .init( get: { self.wrappedValue }, set: { newValue in let oldValue = self.wrappedValue self.wrappedValue = newValue if newValue != oldValue { action(newValue) } } ) } @inlinable public func onChange(toggle value: Binding<Bool>) -> Self where Value: Equatable { onChange { _ in value.wrappedValue.toggle() } } } extension Binding { public func removeDuplicates() -> Self where Value: Equatable { return .init( get: { self.wrappedValue }, set: { newValue in let oldValue = self.wrappedValue guard newValue != oldValue else { return } self.wrappedValue = newValue } ) } } extension Binding { @inlinable public func withDefaultValue<T>(_ defaultValue: T) -> Binding<T> where Value == Optional<T> { return .init( get: { self.wrappedValue ?? defaultValue }, set: { self.wrappedValue = $0 } ) } @inlinable public func isNil<Wrapped>() -> Binding<Bool> where Optional<Wrapped> == Value { .init( get: { self.wrappedValue == nil }, set: { isNil in self.wrappedValue = isNil ? nil : self.wrappedValue } ) } @inlinable public func isNotNil<Wrapped>() -> Binding<Bool> where Optional<Wrapped> == Value { .init( get: { self.wrappedValue != nil }, set: { isNotNil in self.wrappedValue = isNotNil ? self.wrappedValue : nil } ) } public func nilIfEmpty<T: Collection>() -> Binding where Value == Optional<T> { Binding( get: { guard let wrappedValue = self.wrappedValue, !wrappedValue.isEmpty else { return nil } return wrappedValue }, set: { newValue in if let newValue = newValue { self.wrappedValue = newValue.isEmpty ? nil : newValue } else { self.wrappedValue = nil } } ) } public static func boolean<T: Equatable>(_ value: Binding<T?>, equals some: T) -> Binding<Bool> where Value == Bool { .init( get: { value.wrappedValue == some }, set: { newValue in if newValue { value.wrappedValue = some } else { value.wrappedValue = nil } } ) } } extension Binding { @inlinable public static func && (lhs: Binding, rhs: Bool) -> Binding where Value == Bool { .init( get: { lhs.wrappedValue && rhs }, set: { lhs.wrappedValue = $0 } ) } @inlinable public static func && (lhs: Binding, rhs: Bool) -> Binding where Value == Bool? { .init( get: { lhs.wrappedValue.map({ $0 && rhs }) }, set: { lhs.wrappedValue = $0 } ) } } extension Binding { @inlinable public func takePrefix(_ count: Int) -> Self where Value == String { .init( get: { self.wrappedValue }, set: { self.wrappedValue = $0 self.wrappedValue = .init($0.prefix(count)) } ) } @inlinable public func takeSuffix(_ count: Int) -> Self where Value == String { .init( get: { self.wrappedValue }, set: { self.wrappedValue = $0 self.wrappedValue = .init($0.suffix(count)) } ) } @inlinable public func takePrefix(_ count: Int) -> Self where Value == String? { .init( get: { self.wrappedValue }, set: { self.wrappedValue = $0 self.wrappedValue = $0.map({ .init($0.prefix(count)) }) } ) } @inlinable public func takeSuffix(_ count: Int) -> Self where Value == String? { .init( get: { self.wrappedValue }, set: { self.wrappedValue = $0 self.wrappedValue = $0.map({ .init($0.suffix(count)) }) } ) } }
24.332326
121
0.510678
797704e1d55ded2cb8c873dbd53a964f9cf1b89e
720
import CoreBluetooth extension CBManagerState: CustomStringConvertible { public var description: String { switch self { case .unknown: return "unknown" case .resetting: return "resetting" case .unsupported: return "unsupported" case .unauthorized: return "unauthorized" case .poweredOff: return "poweredOff" case .poweredOn: return "poweredOn" } } } extension Data { func parseBool() -> Bool? { guard count == 1 else { return nil } return self[0] != 0 ? true : false } func parseInt() -> UInt8? { guard count == 1 else { return nil } return self[0] } }
23.225806
53
0.561111
7121f0aa6056580ba3ca43ec981f3872d7a00715
4,119
// // SearchController.swift // TwitterTutorial // // Created by Oscar Rodriguez Garrucho on 10/04/2020. // Copyright © 2020 Oscar Rodriguez Garrucho. All rights reserved. // import UIKit private let reuseIdentifier = "UserCell" enum SearchControllerConfiguration { case messages case userSearch } class SearchController: UITableViewController { // MARK: - Properties private let config: SearchControllerConfiguration private var users = [User]() { didSet { tableView.reloadData() } } private var filteredUsers = [User]() { didSet { tableView.reloadData() } } private var isSearchMode: Bool { return searchController.isActive && !searchController.searchBar.text!.isEmpty } private let searchController = UISearchController(searchResultsController: nil) // MARK: - Lifecycle init(config: SearchControllerConfiguration) { self.config = config super.init(style: .plain) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configureUI() fetchUsers() configureSearchController() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.barStyle = .default navigationController?.navigationBar.isHidden = false } // MARK: - API func fetchUsers() { UserService.shared.fetchUsers { [weak self] users in guard let strongSelf = self else { return } strongSelf.users = users } } // MARK: - Selectors @objc func handleDismissal() { dismiss(animated: true, completion: nil) } // MARK: - Helpers func configureUI() { view.backgroundColor = .white navigationItem.title = config == .messages ? "New Message" : "Explore" tableView.register(UserCell.self, forCellReuseIdentifier: reuseIdentifier) tableView.rowHeight = 60 tableView.separatorStyle = .none if config == .messages { navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(handleDismissal)) } } func configureSearchController() { searchController.searchResultsUpdater = self searchController.obscuresBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false searchController.searchBar.placeholder = "Search for an user" navigationItem.searchController = searchController definesPresentationContext = false } } // MARK: - UITableViewControllerDelegate/DataSoruce extension SearchController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return isSearchMode ? filteredUsers.count : users.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! UserCell let user = isSearchMode ? filteredUsers[indexPath.row] : users[indexPath.row] cell.user = user return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let user = isSearchMode ? filteredUsers[indexPath.row] : users[indexPath.row] let controller = ProfileController(user: user) navigationController?.pushViewController(controller, animated: true) } } // MARK: - UISearchResultsUpdating extension SearchController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { guard let searchText = searchController.searchBar.text?.lowercased() else { return } filteredUsers = users.filter({ $0.username.lowercased().contains(searchText) || $0.fullname.lowercased().contains(searchText) }) } }
30.969925
142
0.679534
bb1597e254fe368a8dbf2401f91302b2efcb9aaf
1,146
// // MainViewModel.swift // SicrediChallenge // // Created by Bruno Dorneles on 05/12/18. // Copyright © 2018 Bruno. All rights reserved. // import UIKit import RxSwift class MainViewModel { internal var events = Variable<[Event]>([]) internal var error = Variable<Error?>(nil) internal var request = Request() //MARK:- PUBLIC OBSERVABLES public var eventObservable: Observable<[Event]>{ return events.asObservable() } public var errorObservable: Observable<Error?> { return error.asObservable() } public func requestEvents() { request.requestEvents(completion: {[weak self](response,error) in guard error == nil else { self?.error.value = RequestError.badRequestError return } self?.events.value = response }) } public func searchEvents(searchText: String) { events.value = events.value.filter {event in return event.title.lowercased().contains(searchText.lowercased()) } } public func eventForRow(row: Int)-> Event { return events.value[row] } }
26.045455
87
0.624782
755217ce8523cfb31ce9df7d5eed6ec9200e351c
2,776
// // StringExample.swift // Debugger // // Created by Claudio Madureira Silva Filho on 4/26/20. // import UIKit enum StringExample: CaseIterable { case date case firstName case lastName case fullName case email case random var examples: [String] { let fullNames: [String] = [ "Claudio Madureira", "John Henry Smith", "Marcus Thibault", "Steve Jobs" ] switch self { case .date: return (0..<4).map({ number in let date = Date().addingTimeInterval(TimeInterval(Int.random(in: 0 ..< 999999999) * (Bool.random() ? 1 : -1))) return "\(date)" }) case .firstName: return fullNames.compactMap({ $0.components(separatedBy: " ").first }) case .lastName: return fullNames.compactMap({ $0.components(separatedBy: " ").last }) case .fullName: return fullNames case .email: let hosts: [String] = ["gmail", "outlook", "yahoo"] let allNames = fullNames + fullNames.compactMap({ $0.components(separatedBy: " ").first }) return allNames.map({ fullName in var email: String = "" let names = fullName.components(separatedBy: " ") for name in names { email.append(name.lowercased()) if names.count > 2, names.last != name, Bool.random() { email.append(Bool.random() ? "." : "_") } } let host = hosts.randomElement() ?? "" email.append("@" + host + ".com") return email }) case .random: return (0..<4).map({ _ in return UUID().uuidString }) } } var keyExamples: [String] { switch self { case .date: return [ "date", "moment", "createdAt", "created_at", "updatedAt", "updated_at", "deletedAt", "deleted_at" ] case .firstName: return ["firstName"] case .lastName: return ["lastName"] case .fullName: return ["fullName", "name"] case .email: return ["email", "mail", "e-mail", "userName", "user_name", "username"] case .random: return [ "_id", "id", "objectId", "object_id", "uid", "identifier", "key", "password", "passkey" ] } } }
29.221053
126
0.444164
c1022153a85c0704938f12ae83270aa33d23ccee
256
// // GlobalProperties.swift // Mongli // // Created by DaEun Kim on 2020/03/25. // Copyright © 2020 DaEun Kim. All rights reserved. // import Foundation let dateFormatter = DateFormatter().then { $0.dateFormat = "yyyy-MM-dd" } let log = Logger()
16
52
0.671875
67136face81fd47f41c20529b3d84143d4f72e7a
2,074
// Copyright 2018, Oath Inc. // Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms. import GLKit extension SphereView { class Camera { private var viewMatrix = GLKMatrix4() let fovRadians: Float = GLKMathDegreesToRadians(60.0) let nearZ: Float = 1 let farZ: Float = 1000 var aspect: Float = (320.0 / 480.0) var yaw: Double = 0.0 { // swiftlint:disable:this variable_name didSet { self.updateViewMatrix() } } var pitch: Double = 0.0 { didSet { self.updateViewMatrix() } } // MARK: - Matrix getters var projection: GLKMatrix4 { let fov = aspect < 1 ? self.fovRadians / aspect : self.fovRadians return GLKMatrix4MakePerspective( fov, self.aspect, self.nearZ, self.farZ ) } var view: GLKMatrix4 { get { return self.viewMatrix } } // MARK: - Init init() { self.updateViewMatrix() } // MARK: - Updaters private func updateViewMatrix() { let cosPitch = cos(pitch) let sinPitch = sin(pitch) let cosYaw = cos(yaw + .pi / 2) let sinYaw = sin(yaw + .pi / 2) let xaxis = GLKVector3( v: (Float(cosYaw), 0, Float(-sinYaw)) ) let yaxis = GLKVector3( v: (Float(sinYaw * sinPitch), Float(cosPitch), Float(cosYaw * sinPitch)) ) let zaxis = GLKVector3( v: (Float(sinYaw * cosPitch), Float(-sinPitch), Float(cosPitch * cosYaw)) ) self.viewMatrix = GLKMatrix4(m: ( xaxis.x, yaxis.x, zaxis.x, 0, xaxis.y, yaxis.y, zaxis.y, 0, xaxis.z, yaxis.z, zaxis.z, 0, 0, 0, 0, 1 )) } } }
29.628571
95
0.470588
223eaaf97891100b6c269eae6622803b14da498e
3,384
// // ResetVC.swift // HCI // // Created by Ankit on 10/10/20. // Give me suggestion on twitter @ankityddv (www.twitter.com/ankityddv) import UIKit import Firebase class ResetVC: UIViewController { @IBOutlet weak var emailField: CustomTextField! @IBAction func resetpasswordBttn(_ sender: Any) { resetUserPassword() } override func viewDidLoad() { super.viewDidLoad() //Hide Keyboard NotificationCenter.default.addObserver(self, selector: #selector(keyboardwilchange(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardwilchange(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardwilchange(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } //MARK:- Function to reset User password. func resetUserPassword(){ if self.emailField.text == "" { let alertController = UIAlertController(title: "Oops!", message: "Please enter an email.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } else { Auth.auth().sendPasswordReset(withEmail: self.emailField.text!, completion: { (error) in var title = "" var message = "" if error != nil { title = "Error!" message = (error?.localizedDescription)! } else { let EmailsentVC = self.storyboard!.instantiateViewController(withIdentifier: "EmailsentVC") as! EmailsentVC self.present(EmailsentVC, animated: true, completion: nil) } let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) }) } } // MARK: - Code below this is for hiding keyboard deinit { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } func hideKeyboard(){ view.resignFirstResponder() } @objc func keyboardwilchange(notification: Notification){ // when textfield pressed } func textFieldShouldReturn(_ textField: UITextField) -> Bool { hideKeyboard() return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) // when textfield rests } }
38.454545
175
0.630319
e0c273b8ae2b8e054ce61129302f12b7f2f89d91
3,879
// // NotificationCategory.swift // HomeAssistant // // Created by Robert Trencheny on 9/28/18. // Copyright © 2018 Robbie Trencheny. All rights reserved. // import Foundation import Shared import RealmSwift import DeviceKit import UserNotifications public class NotificationCategory: Object { static let FallbackActionIdentifier = "_" @objc dynamic var Name: String = "" @objc dynamic var Identifier: String = "" // iOS 11+ only @objc dynamic var HiddenPreviewsBodyPlaceholder: String? // iOS 12+ only @objc dynamic var CategorySummaryFormat: String? // Options @objc dynamic var SendDismissActions: Bool = true // iOS 11+ only @objc dynamic var HiddenPreviewsShowTitle: Bool = false @objc dynamic var HiddenPreviewsShowSubtitle: Bool = false // Maybe someday, HA will be on CarPlay (hey that rhymes!)... // @objc dynamic var AllowInCarPlay: Bool = false var Actions = List<NotificationAction>() override public static func primaryKey() -> String? { return "Identifier" } var options: UNNotificationCategoryOptions { var categoryOptions = UNNotificationCategoryOptions([]) if self.SendDismissActions { categoryOptions.insert(.customDismissAction) } if #available(iOS 11.0, *) { if self.HiddenPreviewsShowTitle { categoryOptions.insert(.hiddenPreviewsShowTitle) } if self.HiddenPreviewsShowSubtitle { categoryOptions.insert(.hiddenPreviewsShowSubtitle) } } return categoryOptions } var categories: [UNNotificationCategory] { let allActions = Array(self.Actions.map({ $0.action })) // both lowercase and uppercase since this is a point of confusion return [ Identifier.uppercased(), Identifier.lowercased() ].map { anIdentifier in if #available(iOS 12.0, *) { return UNNotificationCategory(identifier: anIdentifier, actions: allActions, intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: self.HiddenPreviewsBodyPlaceholder, categorySummaryFormat: self.CategorySummaryFormat, options: self.options) } else if #available(iOS 11.0, *), let placeholder = self.HiddenPreviewsBodyPlaceholder { return UNNotificationCategory(identifier: anIdentifier, actions: allActions, intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: placeholder, options: self.options) } else { return UNNotificationCategory(identifier: anIdentifier, actions: allActions, intentIdentifiers: [], options: self.options) } } } public var exampleServiceCall: String { let urlStrings = Actions.map { "\"\($0.Identifier)\": \"http://example.com/url\"" } let indentation = "\n " return """ service: notify.mobile_app_#name_here data: push: category: \(Identifier.uppercased()) action_data: # see example trigger in action # value will be in fired event # url can be absolute path like: # "http://example.com/url" # or relative like: # "/lovelace/dashboard" # pick one of the following styles: # always open when opening notification url: "/lovelace/dashboard" # open a different url per action # use "\(Self.FallbackActionIdentifier)" as key for no action chosen url: - "\(Self.FallbackActionIdentifier)": "http://example.com/fallback" - \(urlStrings.joined(separator: indentation + "- ")) """ } }
36.59434
115
0.611756
c17611a3267b9c3eb94e486434763dabc0bd6b7a
1,945
// // SnackBar.swift // Surveys // // Created by Le Quoc Anh on 6/20/21. // import Foundation import UIKit import SnapKit class SnackBar: UIView { var title: String? { didSet { titleLabel.text = title } } var detail: String? { didSet { detailLabel.text = detail } } private var iconImageView: UIImageView! private var titleLabel: UILabel! private var detailLabel: UILabel! required init?(coder: NSCoder) { super.init(coder: coder) configureView() } override init(frame: CGRect) { super.init(frame: frame) configureView() } private func configureView() { backgroundColor = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 0.6) iconImageView = UIImageView(image: Images.iconNotification) addSubview(iconImageView) iconImageView.snp.makeConstraints { $0.width.height.equalTo(30) $0.top.equalToSuperview().offset(20) $0.leading.equalToSuperview().offset(16) } titleLabel = UILabel() titleLabel.textColor = .white titleLabel.font = UIFont(name: FontName.neuzeitBookHeavy, size: 15) addSubview(titleLabel) titleLabel.snp.makeConstraints { $0.top.equalTo(iconImageView.snp.top) $0.leading.equalTo(iconImageView.snp.trailing).offset(12) } detailLabel = UILabel() detailLabel.textColor = .white detailLabel.font = UIFont(name: FontName.neuzeitBookStandard, size: 13) addSubview(detailLabel) detailLabel.snp.makeConstraints { $0.top.equalTo(titleLabel.snp.bottom) $0.leading.equalTo(titleLabel.snp.leading) $0.bottom.greaterThanOrEqualToSuperview().offset(8) } invalidateIntrinsicContentSize() } }
26.643836
81
0.593316
7a99fc978c3963d1e2c36108914f92a4035a17be
219
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A class B:A struct d<T where e=p{enum e:T.B
27.375
87
0.757991
5dbcd46f1d5ebb39e01e2a3293f1301bec9f2daf
352
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "CICOAutoCodable", platforms: [.iOS(.v8)], products: [ .library(name: "CICOAutoCodable", targets: ["CICOAutoCodable"]) ], targets: [ .target( name: "CICOAutoCodable", path: "CICOAutoCodable" ) ] )
20.705882
71
0.568182
eb11f5d0d3d2917e3432352717c05d511b74bdd8
320
import Foundation public struct CartItem: Identifiable { public var id: UUID { book.id } var book: Book var count: Int } extension CartItem: Equatable { public static func == (lhs: Self, rhs: Self) -> Bool { lhs.book.id == rhs.book.id && lhs.count == rhs.count } }
17.777778
58
0.578125
725cb1260a9685a05ba804246994fd3d837c429e
418
// // File.swift // // // Created by Everaldlee Johnson on 4/29/21. // import Foundation ///Search response for entity types. public class EntityTypeSearchResponse:Codable{ public var entityTypes:[EntityType]? public var total:Int64? public init(entityTypes: [EntityType]? = nil, total:Int64? = nil) { self.entityTypes = entityTypes self.total = total } }
17.416667
71
0.631579
f783fac7d5cc2599ab5414de3bcb82a62fbb6675
1,534
// // TutorialThemeSettings.swift // TutorialKitDemo // // Created by Lee Cooper on 7/24/16. // Copyright © 2016 Aqueous Software. All rights reserved. // import Foundation class TutorialThemeSettings { var themeForegroundColor = UIColor.yellowColor() var themeBackgroundColor = UIColor.blackColor() init() { let theme = TKBannerTutorialView.defaultTheme() themeForegroundColor = theme.foregroundColor themeBackgroundColor = theme.backgroundColor // check to see if themes have been previously saved; if not, use defaults // let prefs = NSUserDefaults.standardUserDefaults() // // prefs.setValue("Berlin", forKey: "userCity") // //This code saves the value "Berlin" to a key named "userCity". // // reading data // if let city = prefs.stringForKey("userCity"){ // println("The user has a city defined: " + city) // }else{ // //Nothing stored in NSUserDefaults yet. Set a value. // prefs.setValue("Berlin", forKey: "userCity") // } // // let prefs = NSUserDefaults.standardUserDefaults() // if let color = prefs.stringForKey("foreground") { // themeForegroundColor = color // } else { // //Nothing stored in NSUserDefaults yet. Set a value. // themeForegroundColor = theme.foregroundColor // } } }
31.958333
82
0.574316
abb307c5338943210ccc9bb1439481ad51cfc734
4,774
// // CustomSessionDelegate.swift // TPLInsurance // // Created by Tahir Raza on 08/04/2019. // Copyright © 2019 TPLHolding. All rights reserved. // import Foundation import Alamofire import TrustKit class CustomSessionDelegate: SessionDelegate { // Note that this is the almost the same implementation as in the ViewController.swift override init() { super.init() // Alamofire uses a block var here sessionDidReceiveChallengeWithCompletion = { session, challenge, completion in guard let trust = challenge.protectionSpace.serverTrust, SecTrustGetCertificateCount(trust) > 0 else { // This case will probably get handled by ATS, but still... completion(.cancelAuthenticationChallenge, nil) return } if TrustKit.sharedInstance().pinningValidator.handle(challenge, completionHandler: completion) { if let serverCertificate = SecTrustGetCertificateAtIndex(trust, 0), let serverCertificateKey = CustomSessionDelegate.publicKey(for: serverCertificate) { if CustomSessionDelegate.pinnedKeys().contains(serverCertificateKey) { completion(.useCredential, URLCredential(trust: trust)) return } } } // // Call into TrustKit here to do pinning validation // if TrustKit.sharedInstance().pinningValidator.handle(challenge, completionHandler: completionHandler) == false { // // TrustKit did not handle this challenge: perhaps it was not for server trust // // or the domain was not pinned. Fall back to the default behavior // completionHandler(.performDefaultHandling, nil) // } // Compare the server certificate with our own stored // if let serverCertificate = SecTrustGetCertificateAtIndex(trust, 0) { // let serverCertificateData = SecCertificateCopyData(serverCertificate) as Data // // if CustomSessionDelegate.pinnedCertificates().contains(serverCertificateData) { // completion(.useCredential, URLCredential(trust: trust)) // return // } // } // Or, compare the public keys completion(.cancelAuthenticationChallenge, nil) } } private static func pinnedCertificates() -> [Data] { var certificates: [Data] = [] if let pinnedCertificateURL = Bundle.main.url(forResource: "infinumco", withExtension: "crt") { do { let pinnedCertificateData = try Data(contentsOf: pinnedCertificateURL) certificates.append(pinnedCertificateData) } catch (_) { // Handle error } } return certificates } private static func pinnedKeys() -> [SecKey] { var publicKeys: [SecKey] = [] if let pinnedCertificateURL = Bundle.main.url(forResource: "infinumco", withExtension: "crt") { do { let pinnedCertificateData = try Data(contentsOf: pinnedCertificateURL) as CFData if let pinnedCertificate = SecCertificateCreateWithData(nil, pinnedCertificateData), let key = publicKey(for: pinnedCertificate) { publicKeys.append(key) } } catch (_) { // Handle error } } return publicKeys } // Implementation from Alamofire private static func publicKey(for certificate: SecCertificate) -> SecKey? { var publicKey: SecKey? let policy = SecPolicyCreateBasicX509() var trust: SecTrust? let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) if let trust = trust, trustCreationStatus == errSecSuccess { publicKey = SecTrustCopyPublicKey(trust) } return publicKey } override func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { // Call into TrustKit here to do pinning validation if TrustKit.sharedInstance().pinningValidator.handle(challenge, completionHandler: completionHandler) == false { // TrustKit did not handle this challenge: perhaps it was not for server trust // or the domain was not pinned. Fall back to the default behavior completionHandler(.performDefaultHandling, nil) } } }
41.155172
195
0.612903
0172c67ee316336dcb5c3cb733e2a7a52e4b9ab7
1,780
// // EventBenifits.swift // sofastcar // // Created by 김광수 on 2020/09/29. // Copyright © 2020 김광수. All rights reserved. // import Foundation class EventBenifits { var title: String var duration: String var info: String init(title: String, duration: String, info: String) { self.title = title self.duration = duration self.info = info } } extension EventBenifits { static func initialData() -> [EventBenifits] { return [ EventBenifits.init(title: "쏘카마이존 EQC 이벤트", duration: "2020-09-28~2020-10-11", info: "평일엔 벤트 EQC를 내 차처럼"), EventBenifits.init(title: "코로나19 대응 안내", duration: "2020-09-28~2020-10-31", info: "안전한 이동이 필요한 순간"), EventBenifits.init(title: "추석 연휴에도 안심 이동", duration: "2020-08-09~2020-10-10", info: "스카차-브라이트 살균 소독 티슈 배치"), EventBenifits.init(title: "쏘카타고 도미토 픽업", duration: "2020-09-01~2020-09-31", info: "도미도피자 30% 할인!"), EventBenifits.init(title: "네이버페이 결제 이벤트", duration: "2020-08-01~2020-09-28", info: "Npay 최대 9,000원 할인"), EventBenifits.init(title: "티웨이 할인 쿠폰 이벤트", duration: "2020-08-01~2020-09-28", info: "오직 쏘카에서만 티웨이 특가"), EventBenifits.init(title: "초소형 전기차", duration: "2020-08-01~2020-09-28", info: "쏘카에서 만나는 새로운 모빌리티"), EventBenifits.init(title: "쏘카 페어링", duration: "2020-08-01~2020-09-28", info: "미리 준비하는 추석"), EventBenifits.init(title: "쏘카 이용 족집게 가이드", duration: "2020-08-01~2020-09-28", info: "더 똑똑하게 이용하는 방법"), EventBenifits.init(title: "제주에서 만나는 이동의 미래", duration: "쏘카 자율주행 셔틀 운행!", info: "쏘카 스테이션 제주에서 만나보세요"), EventBenifits.init(title: "개인 업무용 예약 이벤트", duration: "2020-08-01~2020-09-28", info: "쏘카패스 무료 체험권 받기"), EventBenifits.init(title: "쏘카 인스타그램 이벤트", duration: "2020-08-01~2020-09-28", info: "팔로우하고 일상을 파랗게 채우세요!") ] } }
41.395349
114
0.651685
33fe9ab3b86c0ef584919d5d7440a50fb6bebd99
1,760
import Foundation import Embassy import EnvoyAmbassador extension MockApiServer { func setChargeRoutes() { let item: [String: Any?] = [ "id": MockIds.chargeId, "platform_id": MockIds.platformId, "store_id": MockIds.storeId, "transaction_token_id": MockIds.transactionTokenId, "transaction_token_type": "recurring", "requested_amount": 1000, "requested_currency": "JPY", "requested_amount_formatted": 1000, "charged_amount": 1000, "charged_currency": "JPY", "charged_amount_formatted": 1000, "status": "successful", "metadata": [:], "mode": "test", "error": nil, "created_on": MockDates.createdOn, "only_direct_currency": false ] self.router["/stores/\(MockIds.storeId)/charges/\(MockIds.chargeId)", "GET"] = JSONResponse(handler: { _ -> Any in return item }) self.router["/stores/\(MockIds.storeId)/charges/\(MockIds.chargeId)", "PATCH"] = JSONResponse(handler: { _ -> Any in return item.copy(newValue: ["id": "testid"], forKey: "metadata") }) self.router["/stores/\(MockIds.storeId)/charges", "GET"] = JSONResponse(handler: { _ -> Any in return [ "items": [item], "has_more": false ] }) self.router["/charges", "GET"] = JSONResponse(handler: { _ -> Any in return [ "items": [item], "has_more": false ] }) self.router["/charges", "POST"] = JSONResponse(handler: { _ -> Any in return item }) } }
30.877193
124
0.521023
c190a86f22e2db9cc156876c8d4ea21565afb381
7,262
// // PopoverUtilities.swift // Popovers // // Created by A. Zheng (github.com/aheze) on 12/23/21. // Copyright © 2022 A. Zheng. All rights reserved. // import SwiftUI public extension UIView { /// Convert a view's frame to global coordinates, which are needed for `sourceFrame` and `excludedFrames.` func windowFrame() -> CGRect { return convert(bounds, to: nil) } } public extension Optional where Wrapped: UIView { /// Convert a view's frame to global coordinates, which are needed for `sourceFrame` and `excludedFrames.` This is a convenience overload for optional `UIView`s. func windowFrame() -> CGRect { if let view = self { return view.windowFrame() } return .zero } } public extension View { /// Read a view's frame. From https://stackoverflow.com/a/66822461/14351818 func frameReader(rect: @escaping (CGRect) -> Void) -> some View { return background( GeometryReader { geometry in Color.clear .preference(key: ContentFrameReaderPreferenceKey.self, value: geometry.frame(in: .global)) .onPreferenceChange(ContentFrameReaderPreferenceKey.self) { newValue in DispatchQueue.main.async { rect(newValue) } } } .hidden() ) } /** Read a view's size. The closure is called whenever the size itself changes, or the transaction changes (in the event of a screen rotation.) From https://stackoverflow.com/a/66822461/14351818 */ func sizeReader(transaction: Transaction?, size: @escaping (CGSize) -> Void) -> some View { return background( GeometryReader { geometry in Color.clear .preference(key: ContentSizeReaderPreferenceKey.self, value: geometry.size) .onPreferenceChange(ContentSizeReaderPreferenceKey.self) { newValue in DispatchQueue.main.async { size(newValue) } } .onValueChange(of: transaction) { _, _ in DispatchQueue.main.async { size(geometry.size) } } } .hidden() ) } } extension Transaction: Equatable { public static func == (lhs: Transaction, rhs: Transaction) -> Bool { lhs.animation == rhs.animation } } struct ContentFrameReaderPreferenceKey: PreferenceKey { static var defaultValue: CGRect { return CGRect() } static func reduce(value: inout CGRect, nextValue: () -> CGRect) { value = nextValue() } } struct ContentSizeReaderPreferenceKey: PreferenceKey { static var defaultValue: CGSize { return CGSize() } static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() } } public extension UIColor { /** Create a UIColor from a hex code. Example: let color = UIColor(hex: 0x00aeef) */ convenience init(hex: UInt, alpha: CGFloat = 1) { self.init( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hex & 0x0000FF) / 255.0, alpha: alpha ) } } /// Position a view using a rectangular frame. Access using `.frame(rect:)`. struct FrameRectModifier: ViewModifier { let rect: CGRect func body(content: Content) -> some View { content .frame(width: rect.width, height: rect.height, alignment: .topLeading) .position(x: rect.origin.x + rect.width / 2, y: rect.origin.y + rect.height / 2) } } public extension View { /// Position a view using a rectangular frame. func frame(rect: CGRect) -> some View { return modifier(FrameRectModifier(rect: rect)) } } /// For easier CGPoint math public extension CGPoint { /// Add 2 CGPoints. static func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } /// Subtract 2 CGPoints. static func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } } /// Get the distance between 2 CGPoints. From https://www.hackingwithswift.com/example-code/core-graphics/how-to-calculate-the-distance-between-two-cgpoints public func CGPointDistanceSquared(from: CGPoint, to: CGPoint) -> CGFloat { return (from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y) } public extension Shape { /// Fill and stroke a shape at the same time. https://www.hackingwithswift.com/quick-start/swiftui/how-to-fill-and-stroke-shapes-at-the-same-time func fill<Fill: ShapeStyle, Stroke: ShapeStyle>(_ fillStyle: Fill, strokeBorder strokeStyle: Stroke, lineWidth: CGFloat = 1) -> some View { stroke(strokeStyle, lineWidth: lineWidth) .background(fill(fillStyle)) } } public extension InsettableShape { /// Fill and stroke a shape at the same time. https://www.hackingwithswift.com/quick-start/swiftui/how-to-fill-and-stroke-shapes-at-the-same-time func fill<Fill: ShapeStyle, Stroke: ShapeStyle>(_ fillStyle: Fill, strokeBorder strokeStyle: Stroke, lineWidth: CGFloat = 1) -> some View { strokeBorder(strokeStyle, lineWidth: lineWidth) .background(fill(fillStyle)) } } public extension UIEdgeInsets { /// The left + right insets. var horizontal: CGFloat { get { left + right } set { left = newValue right = newValue } } /// The top + bottom insets. var vertical: CGFloat { get { top + bottom } set { top = newValue bottom = newValue } } /// Create equal insets on all 4 sides. init(_ inset: CGFloat) { self = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset) } } /// Detect changes in bindings (fallback of `.onChange` for iOS 13+). From https://stackoverflow.com/a/64402663/14351818 struct ChangeObserver<Content: View, Value: Equatable>: View { let content: Content let value: Value let action: (Value, Value) -> Void init(value: Value, action: @escaping (Value, Value) -> Void, content: @escaping () -> Content) { self.value = value self.action = action self.content = content() _oldValue = State(initialValue: value) } @State private var oldValue: Value var body: some View { if oldValue != value { DispatchQueue.main.async { self.action(oldValue, value) oldValue = value } } return content } } public extension View { /// Detect changes in bindings (fallback of `.onChange` for iOS 13+). func onValueChange<Value: Equatable>( of value: Value, perform action: @escaping (_ oldValue: Value, _ newValue: Value) -> Void ) -> some View { ChangeObserver(value: value, action: action) { self } } }
33.009091
165
0.598045
26157570ee9cf0fa43ff5ba0d076964f578b3ba0
16,272
import SourceryRuntime import Foundation // TODO: Split? // swiftlint:disable file_length type_body_length public class ProtocolImplementationFunctionTemplate { private let method: SourceryRuntime.Method public init(method: SourceryRuntime.Method) { self.method = method } public func render() throws -> String { """ \(try functionSignatureWithBrace()) let \(mockManagerVariableName) = getMockManager(MixboxMocksRuntimeVoid.self) let \(defaultImplementationVariableName) = getDefaultImplementation(MixboxMocksRuntimeVoid.self) return \(body.indent()) } """ } private func functionSignatureWithBrace() throws -> String { let prefix = "\(functionAttributes)func \(method.callName)\(try genericParameterClauseString())" return method.parameters.render( separator: ",\n", valueIfEmpty: "\(prefix)() \(functionThrowing ?? "") \(functionResult ?? "") {", surround: { let lines = [ """ \(prefix)( \($0.indent())) """, functionThrowing.map { " \($0)" }, functionResult.map { " \($0)" }, "{" ] return lines .compactMap { $0 } .joined(separator: "\n") }, transform: { index, parameter in let labeledArgument = Snippets.labeledArgumentForFunctionSignature( label: parameter.argumentLabel, name: Snippets.argumentName(index: index) ) let type = parameter.typeName.name return "\(labeledArgument): \(type)" } ) } // To avoid collision with members of protocol // TODO: Pass it via closure, it will resolve collisions without need of UUIDD. private var mockManagerVariableName: String { "mockManager_FE23B3FA8DA04D908BBC814A7E97FF1A" } private var defaultImplementationVariableName: String { "defaultImplementation_FE23B3FA8DA04D908BBC814A7E97FF1A" } private func genericParameterClauseString() throws -> String { let genericNamesWithConstraints = try method.genericParameterClause().map(default: []) { genericParameterClause in genericParameterClause.genericParameters.map { genericParameter in genericParameter.nameWithConstraint } } return genericNamesWithConstraints.render( separator: ", ", valueIfEmpty: "", surround: { "<\($0)>" } ) } private var body: String { Snippets.withoutActuallyEscaping( parameters: method.parameters, argumentName: Snippets.argumentName, isThrowingOrRethrowing: methodThrowsOrRethrows, returnType: returnType, body: bodyWithEscapingClosures ) } // TODO: Sourcery provies also keywords as attributes (`convenience`, `public`, etc). Use them. private var functionAttributes: String { method.attributes.sorted { (lhs, rhs) -> Bool in lhs.key < rhs.key }.render( separator: "\n", valueIfEmpty: "", surround: { "\($0)\n" }, transform: { (_, pair: (key: String, value: Attribute)) in // Example: `@available(swift, introduced: 5.0)` "@\(pair.key)\(attributeArgumentsInParenthesis(attribute: pair.value))" } ) } // Example: `(swift, introduced: 5.0)` private func attributeArgumentsInParenthesis(attribute: Attribute) -> String { attribute.arguments.sorted { (lhs, rhs) -> Bool in lhs.key < rhs.key }.render( separator: ", ", valueIfEmpty: "", surround: { "(\($0))" }, transform: { (_, pair: (key: String, value: NSObject)) -> String in // Examples: // - `iOS 10.0` // - `swift` // - `*` // - `introduced: 5.0` // Note that fixes are more probably will break something. // TODO: Thoroughly test all cases. // ` ` are converted to `_` is `iOS 10.0` for some reason. Converting it back: let fixedKey = pair.key.replacingOccurrences(of: "_", with: " ") let notFixedValue = "\(pair.value)" // Also `*` looks like `1` let fixedValue = notFixedValue == "1" ? "*" : notFixedValue // For some reason key and value are separate by comma for `iOS 10.0, *`: return ["\(fixedKey)", "\(fixedValue)"].joined(separator: ", ") } ) } private var bodyWithEscapingClosures: String { let tryPrefix = methodThrowsOrRethrows ? "try " : "" return """ \(tryPrefix)\(mockManagerVariableName).\(mockManagerCallFunction)( functionIdentifier: \(Snippets.functionIdentifier(method: method).indent()), defaultImplementation: \(defaultImplementationVariableName.indent()), defaultImplementationClosure: { (defaultImplementation, tupledArguments) in \(tryPrefix)defaultImplementation.\(method.callName)\(methodCallArguments.indent(level: 2)) }, tupledArguments: \(tupledArguments.indent()), nonEscapingCallArguments: \(nonEscapingCallArguments.indent()), generatorSpecializations: \(knownTypeGenerationSpecialzations().indent()) ) """ } private func knownTypeGenerationSpecialzations() -> String { allTypeInstanceExpressions().render( separator: "\n", surround: { """ TypeErasedAnyGeneratorSpecializationsBuilder() \($0.indent()) .specializations """ }, transform: { _, expression in ".add(\(expression))" } ) } private func allTypeInstanceExpressions() -> Set<String> { return Set( [method.returnTypeName.typeInstanceExpression] + method.parameters.flatMap { [$0.typeName.typeInstanceExpression] + $0.typeName.validClosureType.map(default: []) { $0.parameters.map { $0.typeName.typeInstanceExpression } } } ) } private var mockManagerCallFunction: String { if method.rethrows { return "callRethrows" } else if method.throws { return "callThrows" } else { return "call" } } private var methodCallArguments: String { method.parameters.render( separator: ",\n", valueIfEmpty: "()", surround: { """ ( \($0.indent()) ) """ }, transform: { index, parameter in let labelPrefix = parameter.argumentLabel.map(default: "", transform: { "\($0): " }) let callParenthesis = parameter.typeName.isAutoclosure ? "()" : "" let tupleMemberSelector = method.parameters.count > 1 ? ".\(index)" // x: (Int, Int) => x.0, x.1 : "" // x: (Int) => x return "\(labelPrefix)tupledArguments\(tupleMemberSelector)\(callParenthesis)" } ) } private var tupledArguments: String { return method.parameters.render( separator: ", ", surround: { "(\($0))" }, transform: { index, _ in Snippets.argumentName(index: index) } ) } private var nonEscapingCallArguments: String { return method.parameters.render( separator: ",\n", surround: { """ MixboxMocksRuntime.NonEscapingCallArguments(arguments: [ \($0.indent()) ]) """ }, transform: { index, parameter in """ MixboxMocksRuntime.NonEscapingCallArgument( name: \(Snippets.stringLiteral(parameter.name.convertEmptyToNil()).indent()), label: \(Snippets.stringLiteral(parameter.argumentLabel.convertEmptyToNil()).indent()), type: \(parameter.typeName.typeInstanceExpression.indent()), value: \(nonEscapingCallArgumentValue(index: index, parameter: parameter).indent()) ) """ } ) } private func nonEscapingCallArgumentValue( index: Int, parameter: MethodParameter) -> String { // There is no way to detect that something is a closure in Swift 5.3 // using a private API. This is a simple way to do it in runtime using private API: // // ``` // @_silgen_name("swift_OpaqueSummary") // internal func _opaqueSummary(_ metadata: Any.Type) -> UnsafePointer<CChar>? // // func isClosure(_ any: Any) -> Bool { // let mirror = Mirror(reflecting: any) // // if let cString = _opaqueSummary(mirror.subjectType), // let opaqueSummary = String(validatingUTF8: cString) // { // // This is guaranteed to be an indicator that object is function and // // that object is not something else, see `swift_OpaqueSummary`: // return opaqueSummary == "(Function)" // } else { // return false // } // } // ``` // // (more complex way is to hack deep into C++ code and call `getKind()` on `Metadata` and // handle `MetadataKind::Function` case, see `ReflectionMirror.mm` in `swift` repo) // // This code relies on private API. The reasons not to use it: // - Private API can change. However it's highly unlikely that it would be impossible // that in future Swift will lack the ablity to determine if object is a function. // - There will be still other challanging things like ability to dynamically call a closure. // // All those things will complicate the code, make it dependent on private API, so // the code generation is used to add ability to inspect values at runtime. Note // that code generation can be much less reliable than doing same thing in runtime, // because code generation is much less supported by Apple, and a lot of things // are done by community and the quality of those things is not good (like using regexps instead of AST). // if let closure = parameter.typeName.validClosureType { if parameter.isNonEscapingClosure { return closureNonEscapingCallArgumentValue( argumenIndex: index, closure: closure, isOptional: false, parameter: parameter, caseName: "nonEscapingClosure", className: "NonEscapingClosureArgumentValue" ) } else if parameter.isEscapingClosure { return closureNonEscapingCallArgumentValue( argumenIndex: index, closure: closure, isOptional: false, parameter: parameter, caseName: "escapingClosure", className: "EscapingClosureArgumentValue" ) } else if parameter.isOptional { return closureNonEscapingCallArgumentValue( argumenIndex: index, closure: closure, isOptional: true, parameter: parameter, caseName: "optionalEscapingClosure", className: "OptionalEscapingClosureArgumentValue" ) } else { return regularNonEscapingCallArgumentValue(argumenIndex: index) } } else { return regularNonEscapingCallArgumentValue(argumenIndex: index) } } private func regularNonEscapingCallArgumentValue(argumenIndex: Int) -> String { """ MixboxMocksRuntime.NonEscapingCallArgumentValue.regular( MixboxMocksRuntime.RegularArgumentValue( value: \(Snippets.argumentName(index: argumenIndex)) as Any ) ) """ } // TODO: Split. // swiftlint:disable:next function_body_length private func closureNonEscapingCallArgumentValue( argumenIndex: Int, closure: ClosureType, isOptional: Bool, parameter: MethodParameter, caseName: String, className: String) -> String { let argumentTypes = closure.parameters.render( separator: ",\n", valueIfEmpty: "[]", surround: { """ [ \($0.indent()) ] """ }, transform: { _, parameter in parameter.typeName.typeInstanceExpression } ) let closureArgumentName = Snippets.argumentName(index: argumenIndex) let unwrapOperatorSuffix = isOptional ? "?" : "" let closureTryPrefix = closure.throws ? "try " : "" let callImplementation = closure.parameters.render( separator: ",\n", valueIfEmpty: """ { _ in \(closureTryPrefix)\(closureArgumentName)\(unwrapOperatorSuffix)() as Any } """, surround: { """ { arguments in \(closureTryPrefix)\(closureArgumentName)\(unwrapOperatorSuffix)( \($0.indent(level: 2)) ) as Any } """ }, transform: { index, parameter in let ampersandPrefix = parameter.inout ? "&" : "" return """ \(ampersandPrefix)arguments[\(index)] """ } ) return """ MixboxMocksRuntime.NonEscapingCallArgumentValue.\(caseName)( MixboxMocksRuntime.\(className.indent(level: 1))( value: \(closureArgumentName.indent(level: 2)), reflection: MixboxMocksRuntime.ClosureArgumentValueReflection( argumentTypes: \(argumentTypes.indent(level: 3)), returnValueType: \(closure.returnTypeName.typeInstanceExpression.indent(level: 3)), callImplementation: \(callImplementation.indent(level: 3)) ) ) ) """ } private var methodThrowsOrRethrows: Bool { return method.throws || method.rethrows } private func closureThrowing(closure: ClosureType) -> String { if closure.throws { return " throws" } else { return "" } } private var functionThrowing: String? { if method.rethrows { return "rethrows" } else if method.throws { return "throws" } else { return nil } } private var functionResult: String? { if method.returnTypeName.isVoid { return nil } return "-> \(returnType)" } private var returnType: String { return method.returnTypeName.validTypeName } }
36.897959
122
0.522185
6170da5494cc214ac29ba51cb5377e1457e113a0
1,288
// // WebViewController.swift // SampleApp // // Created by jin kim on 20/06/2019. // Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit final class WebViewController: UIViewController { var initialURL: URL? // MARK: Properties @IBOutlet private weak var webView: NuguWebView! // MARK: Override override func viewDidLoad() { super.viewDidLoad() guard let initialURL = initialURL else { return } webView.load(URLRequest(url: initialURL)) } } // MARK: - Private (IBAction) private extension WebViewController { @IBAction func closeButtonDidClick(_ button: UIButton) { dismiss(animated: true) } }
27.404255
76
0.684006
e2dd3f89dd0ef3b309d37b745b5f6841bca35745
10,696
// // CaptureTimecodeHelper.swift // DLABCaptureManager // // Created by Takashi Mochizuki on 2017/10/01. // Copyright © 2017-2020年 MyCometG3. All rights reserved. // import Foundation import CoreMedia class CaptureTimecodeHelper: NSObject { /// Special CoreAudio SMPTE Time - embeded as CMSampleBuffer attachment private let smpteTimeKey : String = "com.apple.cmio.buffer_attachment.core_audio_smpte_time" /// Default Timecode format : either TimeCode32 or TimeCode64 public var timeCodeFormatType : CMTimeCodeFormatType = kCMTimeCodeFormatType_TimeCode32 /* ============================================ */ // MARK: - public init/deinit /* ============================================ */ /// Prepare Timecode Helper with specified Timecode FormatType. See TN2310. /// /// - Parameter typeValue: CMTimeCodeFormatType either Timecode32 or TimeCode64. init(formatType typeValue : CMTimeCodeFormatType) { super.init() timeCodeFormatType = typeValue // print("TimecodeHelper.init") } deinit { // print("TimecodeHelper.deinit") } /* ============================================ */ // MARK: - public func /* ============================================ */ /// Extract CoreAudio SMPTETime from CMSampleBuffer Attachment /// /// - Parameter videoSampleBuffer: CMSampleBuffer of VideoSample /// - Returns: CMSampleBuffer of TimecodeSample if available public func createTimeCodeSample(from videoSampleBuffer: CMSampleBuffer) -> CMSampleBuffer? { // Check CMTimeCodeFormatType var sizes: Int = 0 switch timeCodeFormatType { case kCMTimeCodeFormatType_TimeCode32: sizes = MemoryLayout<Int32>.size // tmcd 32bit case kCMTimeCodeFormatType_TimeCode64: sizes = MemoryLayout<Int64>.size // tc64 64bit default: print("ERROR: Unsupported CMTimeCodeFormatType detected.") return nil } // Extract SMPTETime from video sample guard let smpteTime = extractCVSMPTETime(from: videoSampleBuffer) else { return nil } // Evaluate TimeCode Quanta var quanta: UInt32 = 30 switch smpteTime.type { case 0: quanta = 24 case 1: quanta = 25 case 2..<6: quanta = 30 case 6..<10: quanta = 60 case 10: quanta = 50 case 11: quanta = 24 default: break } // Evaluate TimeCode type var tcType: UInt32 = kCMTimeCodeFlag_24HourMax // | kCMTimeCodeFlag_NegTimesOK switch smpteTime.type { case 2,5,8,9: tcType |= kCMTimeCodeFlag_DropFrame default: break } // Prepare Data Buffer for new SampleBuffer guard let dataBuffer = prepareTimeCodeDataBuffer(smpteTime, sizes, quanta, tcType) else { return nil } /* ============================================ */ // Prepare TimeCode SampleBuffer var sampleBuffer: CMSampleBuffer? = nil var status: OSStatus = noErr // Extract duration from video sample let duration = CMSampleBufferGetDuration(videoSampleBuffer) // Extract timingInfo from video sample var timingInfo = CMSampleTimingInfo() CMSampleBufferGetSampleTimingInfo(videoSampleBuffer, at: 0, timingInfoOut: &timingInfo) // Prepare CMTimeCodeFormatDescription var description : CMTimeCodeFormatDescription? = nil status = CMTimeCodeFormatDescriptionCreate(allocator: kCFAllocatorDefault, timeCodeFormatType: timeCodeFormatType, frameDuration: duration, frameQuanta: quanta, flags: tcType, extensions: nil, formatDescriptionOut: &description) if status != noErr || description == nil { print("ERROR: Could not create format description.") return nil } // Create new SampleBuffer var timingInfoTMP = timingInfo status = CMSampleBufferCreate(allocator: kCFAllocatorDefault, dataBuffer: dataBuffer, dataReady: true, makeDataReadyCallback: nil, refcon: nil, formatDescription: description, sampleCount: 1, sampleTimingEntryCount: 1, sampleTimingArray: &timingInfoTMP, sampleSizeEntryCount: 1, sampleSizeArray: &sizes, sampleBufferOut: &sampleBuffer) if status != noErr || sampleBuffer == nil { print("ERROR: Could not create sample buffer.") return nil } return sampleBuffer } /* ============================================ */ // MARK: - private func /* ============================================ */ /// Extract CoreAudio SMPTETime from CMSampleBuffer Attachment /// /// - Parameter sampleBuffer: CMSampleBuffer of source VideoSample /// - Returns: CVSMPTETime struct if available private func extractCVSMPTETime(from sampleBuffer: CMSampleBuffer) -> CVSMPTETime? { // Extract sampleBuffer attachment for SMPTETime let smpteTimeData = CMGetAttachment(sampleBuffer, key: smpteTimeKey as CFString, attachmentModeOut: nil) // Create SMPTETime struct from sampleBuffer attachment var smpteTime: CVSMPTETime? = nil if let smpteTimeData = smpteTimeData as? NSData { smpteTime = smpteTimeData.bytes.load(as: CVSMPTETime.self) } return smpteTime } /// Convert CVSMPTETime struct into CMBlockBuffer of specified type /// /// - Parameters: /// - smpteTime: source CVSMPTETime /// - sizes: size of Timecode Sample /// - quanta: Base Resolution per second in integer value /// - tcType: Timecode Type in kCMTimeCodeFlag_xxx form /// - Returns: CMBlockBuffer of TimecodeSample if available private func prepareTimeCodeDataBuffer(_ smpteTime: CVSMPTETime, _ sizes: Int, _ quanta: UInt32, _ tcType: UInt32) -> CMBlockBuffer? { var dataBuffer: CMBlockBuffer? = nil var status: OSStatus = noErr // Caluculate frameNumber for specific SMPTETime var frameNumber64: Int64 = 0 let tcNegativeFlag = Int16(0x80) frameNumber64 = Int64(smpteTime.frames) frameNumber64 += Int64(smpteTime.seconds) * Int64(quanta) frameNumber64 += Int64(smpteTime.minutes & ~tcNegativeFlag) * Int64(quanta) * 60 frameNumber64 += Int64(smpteTime.hours) * Int64(quanta) * 60 * 60 let fpm: Int64 = Int64(quanta) * 60 if (tcType & kCMTimeCodeFlag_DropFrame) != 0 { let fpm10 = fpm * 10 let num10s = frameNumber64 / fpm10 var frameAdjust = -num10s * (9*2) var numFramesLeft = frameNumber64 % fpm10 if numFramesLeft > 1 { let num1s = numFramesLeft / fpm if num1s > 0 { frameAdjust -= (num1s - 1) * 2 numFramesLeft = numFramesLeft % fpm if numFramesLeft > 1 { frameAdjust -= 2 } else { frameAdjust -= (numFramesLeft + 1) } } } frameNumber64 += frameAdjust } if (smpteTime.minutes & tcNegativeFlag) != 0 { frameNumber64 = -frameNumber64 } // TODO let frameNumber32: Int32 = Int32(frameNumber64) /* ============================================ */ // Allocate BlockBuffer status = CMBlockBufferCreateWithMemoryBlock(allocator: kCFAllocatorDefault, memoryBlock: nil, blockLength: sizes, blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0, dataLength: sizes, flags: kCMBlockBufferAssureMemoryNowFlag, blockBufferOut: &dataBuffer) if status != noErr || dataBuffer == nil { print("ERROR: Could not create block buffer.") return nil } // Write FrameNumfer into BlockBuffer if let dataBuffer = dataBuffer { switch sizes { case MemoryLayout<Int32>.size: var frameNumber32BE = frameNumber32.bigEndian status = CMBlockBufferReplaceDataBytes(with: &frameNumber32BE, blockBuffer: dataBuffer, offsetIntoDestination: 0, dataLength: sizes) case MemoryLayout<Int64>.size: var frameNumber64BE = frameNumber64.bigEndian status = CMBlockBufferReplaceDataBytes(with: &frameNumber64BE, blockBuffer: dataBuffer, offsetIntoDestination: 0, dataLength: sizes) default: status = -1 } if status != kCMBlockBufferNoErr { print("ERROR: Could not write into block buffer.") return nil } } return dataBuffer } }
42.444444
97
0.49972
d5030c1c463d6b0950818d7d19cab1af2cffeab6
10,028
/** * Copyright IBM Corporation 2017, 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import UIKit import CoreML import Vision import ImageIO import UIKit import AVFoundation //import Restkit //import LanguageTranslatorV3 //import TextToSpeechV1 class ImageClassificationViewController: UIViewController { // MARK: - IBOutlets @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var cameraButton: UIBarButtonItem! @IBOutlet weak var classificationLabel: UILabel! // MARK: - Image Classification lazy var classificationRequest: VNCoreMLRequest = { do { // Initialize Vision Core ML model from base Watson Visual Recognition model // Uncomment this line to use the tools model. let model = try VNCoreMLModel(for: watson_tools().model) // Uncomment this line to use the plants model. // let model = try VNCoreMLModel(for: watson_plants().model) // Create visual recognition request using Core ML model let request = VNCoreMLRequest(model: model) { [weak self] request, error in self?.processClassifications(for: request, error: error) } request.imageCropAndScaleOption = .scaleFit return request } catch { fatalError("Failed to load Vision ML model: \(error)") } }() func updateClassifications(for image: UIImage) { classificationLabel.text = "Classifying..." let orientation = CGImagePropertyOrientation(image.imageOrientation) guard let ciImage = CIImage(image: image) else { fatalError("Unable to create \(CIImage.self) from \(image).") } DispatchQueue.global(qos: .userInitiated).async { let handler = VNImageRequestHandler(ciImage: ciImage, orientation: orientation) do { let sema = DispatchSemaphore(value: 0) try handler.perform([self.classificationRequest]) _ = sema.wait(timeout: .distantFuture) } catch { /* This handler catches general image processing errors. The `classificationRequest`'s completion handler `processClassifications(_:error:)` catches errors specific to processing that request. */ print("Failed to perform classification.\n\(error.localizedDescription)") } } } /// Updates the UI with the results of the classification. func processClassifications(for request: VNRequest, error: Error?) { DispatchQueue.main.async { guard let results = request.results else { self.classificationLabel.text = "Unable to classify image.\n\(error!.localizedDescription)" return } // The `results` will always be `VNClassificationObservation`s, as specified by the Core ML model in this project. let classifications = results as! [VNClassificationObservation] if classifications.isEmpty { self.classificationLabel.text = "Nothing recognized." } else { // Display top classification ranked by confidence in the UI. // server endpoint let myGroup = DispatchGroup() myGroup.enter() //// Do your task // LANGAUGE TRANSLATE API REQUEST var v = "" let login = "test" let passwor = "12345" let url = URL(string: "https://gateway.watsonplatform.net/language-translator/api/v3/translate?version=2018-05-01") var request = URLRequest(url: url!) let config = URLSessionConfiguration.default let userPasswordString = "\(login):\(passwor)" let userPasswordData = userPasswordString.data(using: String.Encoding.utf8) let base64EncodedCredential = "YXBpa2V5OkZuLVNsRjdsT1JxdlN5SHBUelNrV0c0bEF6Z3Vrdzg2UFlaMmpXUHVsSldq" let authString = "Basic \(base64EncodedCredential)" config.httpAdditionalHeaders = ["Content-Type":"application/json"] config.httpAdditionalHeaders = ["Authorization" : authString] // API PARAMETERS let json: [String: Any] = ["model_id": "en-es", "text": ["\(classifications[0].identifier)"]] let jsonData = try? JSONSerialization.data(withJSONObject: json) let username = "apikey" let password = "Fn-SlF7lORqvSyHpTzSkWG4lAzgukw86PYZ2jWPulJWj" let loginString = String(format: "%@:%@", username, password) let loginData = loginString.data(using: .utf8)! let base64LoginString = loginData.base64EncodedString() request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization") request.httpBody = jsonData request.httpMethod = "POST" let session = URLSession(configuration: config) print(request) let task = session.dataTask(with: request as URLRequest) { data, response, error in guard let data = data, error == nil else { print(error?.localizedDescription ?? "No data") return } let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) if let responseJSON = responseJSON as? [String: Any] { //print(responseJSON["translations"][0]) var ty = type(of: responseJSON) if var t = responseJSON["translations"] as? [[String:String]] { v = t[0]["translation"]! print(v) self.classificationLabel.text = classifications[0].identifier + " --> " + v myGroup.leave() //// When your task completes } //print(t) } else { print("HAHHAH\nAHHAH\nAHAHHA") } } task.resume() myGroup.wait() print("HIIIII") myGroup.notify(queue: .main) { print(v) self.classificationLabel.text = classifications[0].identifier + " --> " + v } } } } // MARK: - Photo Actions @IBAction func takePicture() { // Show options for the source picker only if the camera is available. guard UIImagePickerController.isSourceTypeAvailable(.camera) else { presentPhotoPicker(sourceType: .photoLibrary) return } let photoSourcePicker = UIAlertController() let takePhoto = UIAlertAction(title: "Take Photo", style: .default) { [unowned self] _ in self.presentPhotoPicker(sourceType: .camera) } let choosePhoto = UIAlertAction(title: "Choose Photo", style: .default) { [unowned self] _ in self.presentPhotoPicker(sourceType: .photoLibrary) } photoSourcePicker.addAction(takePhoto) photoSourcePicker.addAction(choosePhoto) photoSourcePicker.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(photoSourcePicker, animated: true) } func presentPhotoPicker(sourceType: UIImagePickerControllerSourceType) { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = sourceType present(picker, animated: true) } } extension ImageClassificationViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { // MARK: - Handling Image Picker Selection func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) { picker.dismiss(animated: true) // We always expect `imagePickerController(:didFinishPickingMediaWithInfo:)` to supply the original image. let image = info[UIImagePickerControllerOriginalImage] as! UIImage imageView.contentMode = UIViewContentMode.scaleAspectFit imageView.image = image //let apiKey = "iSo1iNVoM4AFyaHPKAkcnSkllyL_6DF1exrGdx2l1tNY" //let version = "2018-11-03" // use today's date for the most recent version //let visualRecognition = VisualRecognition(version: version, apiKey: apiKey) //let url = "https://gateway.watsonplatform.net/visual-recognition/api" //let failure = { (error: Error) in print(error) } //visualRecognition.classify(image: url, failure: failure) { classifiedImages in //classifiedImagesprint(classified) //} updateClassifications(for: image) } }
39.952191
131
0.582569
f81d64f795d78d17e0db25a1639b0c6b3fdff8d6
25,563
// // APNGDecoder.swift // // // Created by Wang Wei on 2021/10/05. // import Foundation import Accelerate import ImageIO import zlib import Delegate // Decodes an APNG to necessary information. class APNGDecoder { struct ResetStatus { let offset: UInt64 let expectedSequenceNumber: Int } // Called when the first pass is done. let onFirstPassDone = Delegate<(), Void>() // Only valid on main thread. Set the `output` to a `.failure` value would result the default image being rendered // for the next frame in APNGImageView. var output: Result<CGImage, APNGKitError>? // Only valid on main thread. var currentIndex: Int = 0 let imageHeader: IHDR let animationControl: acTL private var foundMultipleAnimationControl = false private let renderingQueue = DispatchQueue(label: "com.onevcat.apngkit.renderingQueue", qos: .userInteractive) private(set) var frames: [APNGFrame?] = [] private(set) var defaultImageChunks: [IDAT] = [] private var expectedSequenceNumber = 0 private var currentOutputImage: CGImage? private var previousOutputImage: CGImage? // Used only when `cachePolicy` is `.cache`. private(set) var decodedImageCache: [CGImage?]? private var canvasFullSize: CGSize { .init(width: imageHeader.width, height: imageHeader.height) } private var canvasFullRect: CGRect { .init(origin: .zero, size: canvasFullSize) } // The data chunks shared by all frames: after IHDR and before the actual IDAT or fdAT chunk. // Use this to revert to a valid PNG for creating a CG data provider. private let sharedData: Data private let outputBuffer: CGContext private let reader: Reader private var resetStatus: ResetStatus! private let options: APNGImage.DecodingOptions let cachePolicy: APNGImage.CachePolicy convenience init(data: Data, options: APNGImage.DecodingOptions = []) throws { let reader = DataReader(data: data) try self.init(reader: reader, options: options) } convenience init(fileURL: URL, options: APNGImage.DecodingOptions = []) throws { let reader = try FileReader(url: fileURL) try self.init(reader: reader, options: options) } private init(reader: Reader, options: APNGImage.DecodingOptions) throws { self.reader = reader self.options = options let skipChecksumVerify = options.contains(.skipChecksumVerify) // Decode and load the common part and at least make the first frame prepared. guard let signature = try reader.read(upToCount: 8), signature.bytes == Self.pngSignature else { throw APNGKitError.decoderError(.fileFormatError) } let ihdr = try reader.readChunk(type: IHDR.self, skipChecksumVerify: skipChecksumVerify) imageHeader = ihdr.chunk let acTLResult: UntilChunkResult<acTL> do { acTLResult = try reader.readUntil(type: acTL.self, skipChecksumVerify: skipChecksumVerify) } catch { // Can not read a valid `acTL`. Should be treated as a normal PNG. throw APNGKitError.decoderError(.lackOfChunk(acTL.name)) } let numberOfFrames = acTLResult.chunk.numberOfFrames if numberOfFrames == 0 { // 0 is not a valid value in `acTL` throw APNGKitError.decoderError(.invalidNumberOfFrames(value: 0)) } // Too large `numberOfFrames`. Do not accept it since we are doing a pre-action memory alloc. // Although 1024 frames should be enough for all normal case, there is an improvement plan: // - Add a read option to loose this restriction (at user's risk. A large number would cause OOM.) // - An alloc-with-use memory model. Do not alloc memory by this number (which might be malformed), but do the // alloc JIT. // // For now, just hard code a reasonable upper limitation. if numberOfFrames >= 1024 && !options.contains(.unlimitedFrameCount) { throw APNGKitError.decoderError(.invalidNumberOfFrames(value: numberOfFrames)) } frames = [APNGFrame?](repeating: nil, count: acTLResult.chunk.numberOfFrames) // Determine cache policy. When the policy is explicitly set, use that. Otherwise, choose a cache policy by // image properties. if options.contains(.cacheDecodedImages) { // The optional cachePolicy = .cache } else if options.contains(.notCacheDecodedImages) { cachePolicy = .noCache } else { // Optimization: Auto determine if we want to cache the image based on image information. if acTLResult.chunk.numberOfPlays == 0 { // Although it is not accurate enough, we only use the image header and animation control chunk to estimate. let estimatedTotalBytes = imageHeader.height * imageHeader.bytesPerRow * numberOfFrames // Cache images when it does not take too much memory. cachePolicy = estimatedTotalBytes < APNGImage.maximumCacheSize ? .cache : .noCache } else { // If the animation is not played forever, it does not worth to cache. cachePolicy = .noCache } } if cachePolicy == .cache { decodedImageCache = [CGImage?](repeating: nil, count: acTLResult.chunk.numberOfFrames) } else { decodedImageCache = nil } sharedData = acTLResult.dataBeforeThunk animationControl = acTLResult.chunk guard let outputBuffer = CGContext( data: nil, width: imageHeader.width, height: imageHeader.height, bitsPerComponent: imageHeader.bitDepthPerComponent, bytesPerRow: imageHeader.bytesPerRow, space: imageHeader.colorSpace, bitmapInfo: imageHeader.bitmapInfo.rawValue ) else { throw APNGKitError.decoderError(.canvasCreatingFailed) } self.outputBuffer = outputBuffer // Decode the first frame, so the image view has the initial image to show from the very beginning. var firstFrameData: Data let firstFrame: APNGFrame // fcTL and acTL order can be changed in APNG spec. // Try to check if the first `fcTL` is already existing before `acTL`. If there is already a valid `fcTL`, use // it as the first frame control to extract the default image. let first_fcTLReader = DataReader(data: acTLResult.dataBeforeThunk) let firstFCTL: fcTL? do { let first_fcTLResult = try first_fcTLReader.readUntil(type: fcTL.self) firstFCTL = first_fcTLResult.chunk } catch { firstFCTL = nil } (firstFrame, firstFrameData, defaultImageChunks) = try loadFirstFrameAndDefaultImage(firstFCTL: firstFCTL) self.frames[currentIndex] = firstFrame // Render the first frame. // It is safe to set it here since this `setup()` method will be only called in init, before any chance to // make another call like `renderNext` to modify `output` at the same time. if !foundMultipleAnimationControl { let cgImage = try render(frame: firstFrame, data: firstFrameData, index: currentIndex) output = .success(cgImage) } else { output = .failure(.decoderError(.multipleAnimationControlChunk)) } // Store the current reader offset. If later we need to reset the image loading state, we can start from here // to make the whole image back to the state of just initialized. resetStatus = ResetStatus(offset: try reader.offset(), expectedSequenceNumber: expectedSequenceNumber) if options.contains(.fullFirstPass) { var index = currentIndex while firstPass { index = index + 1 let (frame, data) = try loadFrame() if options.contains(.preRenderAllFrames) { _ = try render(frame: frame, data: data, index: index) } if foundMultipleAnimationControl { throw APNGKitError.decoderError(.multipleAnimationControlChunk) } frames[index] = frame } } if !firstPass { // Animation with only one frame,check IEND. _ = try reader.readChunk(type: IEND.self, skipChecksumVerify: skipChecksumVerify) // Dispatch to give the user a chance to setup delegate after they get the returned APNG image. DispatchQueue.main.async { self.onFirstPassDone() } } } func reset() throws { if currentIndex == 0 { // It is under the initial state. No need to reset. return } var firstFrame: APNGFrame? = nil var firstFrameData: Data? = nil try renderingQueue.sync { firstFrame = frames[0] firstFrameData = try firstFrame?.loadData(with: reader) try reader.seek(toOffset: resetStatus.offset) expectedSequenceNumber = resetStatus.expectedSequenceNumber } if cachePolicy == .cache, let cache = decodedImageCache, cache.contains(nil) { // The cache is only still valid when all frames are in cache. If there is any `nil` in the cache, reset it. // Otherwise, it is not easy to decide the partial drawing context. decodedImageCache = [CGImage?](repeating: nil, count: animationControl.numberOfFrames) } currentIndex = 0 output = .success(try render(frame: firstFrame!, data: firstFrameData!, index: 0)) } private func renderNextImpl() throws -> (CGImage, Int) { let image: CGImage var newIndex = currentIndex + 1 if firstPass { let (frame, data) = try loadFrame() if foundMultipleAnimationControl { throw APNGKitError.decoderError(.multipleAnimationControlChunk) } frames[newIndex] = frame image = try render(frame: frame, data: data, index: newIndex) if !firstPass { _ = try reader.readChunk(type: IEND.self, skipChecksumVerify: options.contains(.skipChecksumVerify)) DispatchQueue.main.asyncOrSyncIfMain { self.onFirstPassDone() } } } else { if newIndex == frames.count { newIndex = 0 } // It is not the first pass. All frames info should be already decoded and stored in `frames`. image = try renderFrame(frame: frames[newIndex]!, index: newIndex) } return (image, newIndex) } func renderNextSync() throws { output = nil do { let (image, index) = try renderNextImpl() self.output = .success(image) self.currentIndex = index } catch { self.output = .failure(error as? APNGKitError ?? .internalError(error)) } } // The result will be rendered to `output`. func renderNext() { output = nil // This method is expected to be called on main thread. renderingQueue.async { do { let (image, index) = try self.renderNextImpl() DispatchQueue.main.async { self.output = .success(image) self.currentIndex = index } } catch { DispatchQueue.main.async { self.output = .failure(error as? APNGKitError ?? .internalError(error)) } } } } private func render(frame: APNGFrame, data: Data, index: Int) throws -> CGImage { // Shortcut for image cache. if let cached = cachedImage(at: index) { return cached } if index == 0 { // Reset for the first frame previousOutputImage = nil currentOutputImage = nil } let pngImageData = try generateImageData(frameControl: frame.frameControl, data: data) guard let source = CGImageSourceCreateWithData( pngImageData as CFData, [kCGImageSourceShouldCache: true] as CFDictionary ) else { throw APNGKitError.decoderError(.invalidFrameImageData(data: pngImageData, frameIndex: index)) } guard let nextFrameImage = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw APNGKitError.decoderError(.frameImageCreatingFailed(source: source, frameIndex: index)) } // Dispose if index == 0 { // Next frame (rendering frame) is the first frame outputBuffer.clear(canvasFullRect) } else { let currentFrame = frames[index - 1]! let currentRegion = currentFrame.normalizedRect(fullHeight: imageHeader.height) switch currentFrame.frameControl.disposeOp { case .none: break case .background: outputBuffer.clear(currentRegion) case .previous: if let previousOutputImage = previousOutputImage { outputBuffer.clear(canvasFullRect) outputBuffer.draw(previousOutputImage, in: canvasFullRect) } else { // Current Frame is the first frame. `.previous` should be treated as `.background` outputBuffer.clear(currentRegion) } } } // Blend & Draw switch frame.frameControl.blendOp { case .source: outputBuffer.clear(frame.normalizedRect(fullHeight: imageHeader.height)) outputBuffer.draw(nextFrameImage, in: frame.normalizedRect(fullHeight: imageHeader.height)) case .over: // Temp outputBuffer.draw(nextFrameImage, in: frame.normalizedRect(fullHeight: imageHeader.height)) } guard let nextOutputImage = outputBuffer.makeImage() else { throw APNGKitError.decoderError(.outputImageCreatingFailed(frameIndex: index)) } previousOutputImage = currentOutputImage currentOutputImage = nextOutputImage if cachePolicy == .cache { decodedImageCache?[index] = nextOutputImage } return nextOutputImage } private func renderFrame(frame: APNGFrame, index: Int) throws -> CGImage { guard !firstPass else { preconditionFailure("renderFrame cannot work until all frames are loaded.") } if let cached = cachedImage(at: index) { return cached } let data = try frame.loadData(with: reader) return try render(frame: frame, data: data, index: index) } private func cachedImage(at index: Int) -> CGImage? { guard cachePolicy == .cache else { return nil } guard let cache = decodedImageCache else { return nil } return cache[index] } private var loadedFrameCount: Int { frames.firstIndex { $0 == nil } ?? frames.count } var firstPass: Bool { loadedFrameCount < frames.count } private func loadFirstFrameAndDefaultImage(firstFCTL: fcTL?) throws -> (APNGFrame, Data, [IDAT]) { var result: (APNGFrame, Data, [IDAT])? while result == nil { try reader.peek { info, action in // Start to load the first frame and default image. There are two possible options. switch info.name.bytes { case fcTL.nameBytes: // Sequence number Chunk // (none) `acTL` // 0 `fcTL` first frame // (none) `IDAT` first frame / default image let frameControl = try action(.read(type: fcTL.self)).fcTL try checkSequenceNumber(frameControl) let (chunks, data) = try loadImageData() result = (APNGFrame(frameControl: frameControl, data: chunks), data, chunks) case IDAT.nameBytes: // Sequence number Chunk // (none) `acTL` // (none) `IDAT` default image // 0 `fcTL` first frame // 1 first `fdAT` for first frame _ = try action(.reset) if let firstFCTL = firstFCTL { try checkSequenceNumber(firstFCTL) let (chunks, data) = try loadImageData() result = (APNGFrame(frameControl: firstFCTL, data: chunks), data, chunks) } else { let (defaultImageChunks, _) = try loadImageData() let (frame, frameData) = try loadFrame() result = (frame, frameData, defaultImageChunks) } case acTL.nameBytes: self.foundMultipleAnimationControl = true _ = try action(.read()) default: _ = try action(.read()) } } } return result! } // Load the next full fcTL controlled and its frame data from current position private func loadFrame() throws -> (APNGFrame, Data) { var result: (APNGFrame, Data)? while result == nil { try reader.peek { info, action in switch info.name.bytes { case fcTL.nameBytes: let frameControl = try action(.read(type: fcTL.self)).fcTL try checkSequenceNumber(frameControl) let (dataChunks, data) = try loadFrameData() result = (APNGFrame(frameControl: frameControl, data: dataChunks), data) case acTL.nameBytes: self.foundMultipleAnimationControl = true _ = try action(.read()) default: _ = try action(.read()) } } } return result! } private func loadFrameData() throws -> ([fdAT], Data) { var result: [fdAT] = [] var allData: Data = .init() let skipChecksumVerify = options.contains(.skipChecksumVerify) var frameDataEnd = false while !frameDataEnd { try reader.peek { info, action in switch info.name.bytes { case fdAT.nameBytes: let peekAction: PeekAction = options.contains(.loadFrameData) ? .read(type: fdAT.self, skipChecksumVerify: skipChecksumVerify) : .readIndexedfdAT(skipChecksumVerify: skipChecksumVerify) let (chunk, data) = try action(peekAction).fdAT try checkSequenceNumber(chunk) result.append(chunk) allData.append(data) case fcTL.nameBytes, IEND.nameBytes: _ = try action(.reset) frameDataEnd = true default: _ = try action(.read()) } } } guard !result.isEmpty else { throw APNGKitError.decoderError(.frameDataNotFound(expectedSequence: expectedSequenceNumber)) } return (result, allData) } private func loadImageData() throws -> ([IDAT], Data) { var chunks: [IDAT] = [] var allData: Data = .init() let skipChecksumVerify = options.contains(.skipChecksumVerify) var imageDataEnd = false while !imageDataEnd { try reader.peek { info, action in switch info.name.bytes { case IDAT.nameBytes: let peekAction: PeekAction = options.contains(.loadFrameData) ? .read(type: IDAT.self, skipChecksumVerify: skipChecksumVerify) : .readIndexedIDAT(skipChecksumVerify: skipChecksumVerify) let (chunk, data) = try action(peekAction).IDAT chunks.append(chunk) allData.append(data) case fcTL.nameBytes, IEND.nameBytes: _ = try action(.reset) imageDataEnd = true default: _ = try action(.read()) } } } guard !chunks.isEmpty else { throw APNGKitError.decoderError(.imageDataNotFound) } return (chunks, allData) } private func checkSequenceNumber(_ frameControl: fcTL) throws { let sequenceNumber = frameControl.sequenceNumber guard sequenceNumber == expectedSequenceNumber else { throw APNGKitError.decoderError(.wrongSequenceNumber(expected: expectedSequenceNumber, got: sequenceNumber)) } expectedSequenceNumber += 1 } private func checkSequenceNumber(_ frameData: fdAT) throws { let sequenceNumber = frameData.sequenceNumber guard sequenceNumber == expectedSequenceNumber else { throw APNGKitError.decoderError(.wrongSequenceNumber(expected: expectedSequenceNumber, got: sequenceNumber!)) } expectedSequenceNumber += 1 } } extension APNGDecoder { static let pngSignature: [Byte] = [ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A ] static let IENDBytes: [Byte] = [ 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 ] private func generateImageData(frameControl: fcTL, data: Data) throws -> Data { try generateImageData(width: frameControl.width, height: frameControl.height, data: data) } private func generateImageData(width: Int, height: Int, data: Data) throws -> Data { let ihdr = try imageHeader.updated( width: width, height: height ).encode() let idat = IDAT.encode(data: data) return Self.pngSignature + ihdr + sharedData + idat + Self.IENDBytes } } extension APNGDecoder { func createDefaultImageData() throws -> Data { let payload = try defaultImageChunks.map { idat in try idat.loadData(with: self.reader) }.joined() let data = try generateImageData( width: imageHeader.width, height: imageHeader.height, data: Data(payload) ) return data } } struct APNGFrame { let frameControl: fcTL let data: [DataChunk] func loadData(with reader: Reader) throws -> Data { Data( try data.map { try $0.loadData(with: reader) } .joined() ) } func normalizedRect(fullHeight: Int) -> CGRect { frameControl.normalizedRect(fullHeight: fullHeight) } } // Drawing properties for IHDR. extension IHDR { var colorSpace: CGColorSpace { switch colorType { case .greyscale, .greyscaleWithAlpha: return .deviceGray case .trueColor, .trueColorWithAlpha: return .deviceRGB case .indexedColor: return .deviceRGB } } var bitmapInfo: CGBitmapInfo { switch colorType { case .greyscale, .trueColor: return CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue) case .greyscaleWithAlpha, .trueColorWithAlpha, .indexedColor: return CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) } } var bitDepthPerComponent: Int { // The sample depth is the same as the bit depth except in the case of // indexed-colour PNG images (colour type 3), in which the sample depth is always 8 bits. Int(colorType == .indexedColor ? 8 : bitDepth) } var bitsPerPixel: UInt32 { let componentsPerPixel = colorType == .indexedColor ? 4 /* Draw indexed color as true color with alpha in CG world. */ : colorType.componentsPerPixel return UInt32(componentsPerPixel * bitDepthPerComponent) } var bytesPerPixel: UInt32 { bitsPerPixel / 8 } var bytesPerRow: Int { width * Int(bytesPerPixel) } } extension fcTL { func normalizedRect(fullHeight: Int) -> CGRect { .init(x: xOffset, y: fullHeight - yOffset - height, width: width, height: height) } } extension CGColorSpace { static let deviceRGB = CGColorSpaceCreateDeviceRGB() static let deviceGray = CGColorSpaceCreateDeviceGray() } extension DispatchQueue { func asyncOrSyncIfMain(execute block: @escaping () -> Void) { if Thread.isMainThread { block() } else { self.async(execute: block) } } }
39.027481
124
0.582013
e076e4eed41d6f744ed1f212b1d613a026456b9c
1,380
// // AppDelegate.swift // Tint Overlay // // Created by Andrew Fletcher on 21/4/20. // Copyright © 2020 Andrew Fletcher. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.315789
177
0.773188
e41f79e8092deeea6358e75ab65e005b0fb2fd1c
410
// // AboutTabState.swift // MobileApp // // Created by Mariusz Sut on 25/12/2020. // Copyright © 2020 MSut. All rights reserved. // import Foundation import Core enum AboutTabLoadable { case ready case loaded(about: About) } extension AboutTabLoadable: Equatable { /*Nop*/ } struct AboutTabState: StateRedux { var status: AboutTabLoadable } extension AboutTabState: Equatable { /*Nop*/ }
17.083333
49
0.707317
79b5dc12b5384ac2a5c58349850cd865cb605297
819
// // Final8ViewController.swift // Final // // Created by 19205313 on 25.05.2021. // import UIKit final class Final8ViewController: UIViewController { var presenter: Final8PresenterProtocol! override func viewDidLoad() { super.viewDidLoad() self.createUI() self.presenter.viewLoaded() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.presenter.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.presenter.viewWillDisappear(animated) } func createUI() { } } // MARK: - Final8ViewProtocol extension Final8ViewController: Final8ViewProtocol { }
19.046512
55
0.628816
918ec082d17831ddc4659040312f994fa5f09309
1,580
// This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors import ArgumentParser import llbuild2 import LLBNinja public struct NinjaBuildTool: ParsableCommand { public static var configuration = CommandConfiguration( commandName: "ninja", abstract: "NinjaBuild tool") @Flag(help: "Print verbose output") var verbose: Bool = false @Option(help: "Path to the Ninja manifest file") var manifest: String @Option(help: "The name of the target to build") var target: String public init() { } public func run() throws { let dryRunDelegate = NinjaDryRunDelegate() let nb = try NinjaBuild(manifest: manifest, delegate: dryRunDelegate) let ctx = Context() _ = try nb.build(target: target, as: Int.self, ctx) } } extension Int: NinjaValue {} private class NinjaDryRunDelegate: NinjaBuildDelegate { func build(group: LLBFuturesDispatchGroup, path: String) -> LLBFuture<NinjaValue> { print("build input: \(path)") return group.next().makeSucceededFuture(0) } func build(group: LLBFuturesDispatchGroup, command: Command, inputs: [NinjaValue]) -> LLBFuture<NinjaValue> { print("build command: \(command.command)") return group.next().makeSucceededFuture(0) } }
30.980392
113
0.693038
d632bb8782a2a75e8b89e179a32739d9ada2e364
1,436
// // AppDelegate.swift // TrueBucha // // Created by Kanstantsin Bucha on 12/7/17. // Copyright © 2018 Truebucha. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillFinishLaunching(_ notification: Notification) { } func applicationDidFinishLaunching(_ aNotification: Notification) { integration.enable() FileManager.default.ensureDirectoryExists(at: Settings.program.backupFolder) interfaceStore.dispatch(InterfaceAction.displaySplashScreen) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Settings.splashScreen.duration) { interfaceStore.dispatch(InterfaceAction.displayMainScreen) } } //MARK - menu actions - @IBAction func openManual(_: AnyObject) { User.did(.openUserManual) } @IBAction func openTutorials(_: AnyObject) { User.did(.openTutorial) } @IBAction func showFeedbackDialog(_: AnyObject?) { User.did(.showFeedbackDialog) } @IBAction func checkForUpdates(_ sender: AnyObject?) { User.did(.checkForUpdates) } @IBAction func displaySplashScreen(_ sender: AnyObject?) { interfaceStore.dispatch(InterfaceAction.displaySplashScreen) } }
23.16129
102
0.637187
69ccce1b7dc8a6ef70f5fd1ea2834f8370e1f7a2
425
// // VisualSearchCTA.swift // Syte // // Created by Artur Tarasenko on 25.08.2021. // import Foundation public class VisualSearchCTA: Codable, ReflectedStringConvertible { public var onFocus: Bool? public var header: Bool? public var noResults: Bool? enum CodingKeys: String, CodingKey { case header case onFocus = "on_focus" case noResults = "no_results" } }
18.478261
67
0.644706
fcc50eb7cea5f0d2a4f5c91ae95da577e2e70f51
978
// // CreateCertificate.swift // AppStoreConnect-Swift-SDK // // Created by Patrick Balestra on 12/15/19. // import Foundation extension APIEndpoint where T == CertificateResponse { /// Create a new certificate using a certificate signing request. /// /// - Parameters: /// - certificateType: (Required) The type of certificate to be created. /// - csrContent: (Required) The certificate signing request to be used to create the certificate. public static func create( certificateWithCertificateType certificateType: CertificateType, csrContent: String) -> APIEndpoint { let request = CertificateCreateRequest(data: .init( attributes: .init( certificateType: certificateType, csrContent: csrContent))) return APIEndpoint( path: "certificates", method: .post, parameters: nil, body: try? JSONEncoder().encode(request)) } }
29.636364
104
0.646217
6119ca405094ff0f2458bea914fcce85e9fd1521
626
// // HeaderFooterView.swift // Example // // Created by Le VanNghia on 3/5/16. // // import UIKit open class HeaderFooterView: UITableViewHeaderFooterView { weak var _viewmodel: HeaderFooterViewModel? open func configureView(_ viewmodel: HeaderFooterViewModel) { _viewmodel = viewmodel configure() } open func configure() { } open func didChangeFloatingState(_ isFloating: Bool, section: Int) { } open func willDisplay(_ tableView: UITableView, section: Int) { } open func didEndDisplaying(_ tableView: UITableView, section: Int) { } }
20.193548
72
0.65655
ddd3567db6211a2b1abbcfc888cf904d7baacf11
1,502
// // Tweet.swift // TweetyTool // // Created by Vaidehi Duraphe on 2/26/17. // Copyright © 2017 Vaidehi Duraphe. All rights reserved. // import UIKit class Tweet: NSObject { var text: String? var timestamp: Date? var retweetCount: Int = 0 var favoritesCount: Int = 0 var retweeted: Bool var favorited: Bool var pers: User var id: Int = 0 init(dictionary: NSDictionary) { text = dictionary["text"] as? String retweetCount = (dictionary["retweet_count"] as? Int) ?? 0 favoritesCount = (dictionary["favorite_count"] as? Int) ?? 0 let timestampString = dictionary["created_at"] as? String if let timestampString = timestampString { let formatter = DateFormatter() formatter.dateFormat = "EEE MMM d HH:mm:ss Z y" timestamp = formatter.date(from: timestampString) as Date? } else { timestamp = Date() as Date? } pers = User(dictionary: dictionary["user"] as! NSDictionary) retweeted = dictionary["retweeted"] as! Bool favorited = dictionary["favorited"] as! Bool id = dictionary["id"] as! Int } class func tweetsWithArray(dictionaries: [NSDictionary]) -> [Tweet] { var tweets = [Tweet]() for dictionary in dictionaries { let tweet = Tweet(dictionary: dictionary) tweets.append(tweet) } return tweets } }
27.814815
73
0.585885
08fe6122584ae6ba5ff3a02dc160a20ea417c40d
2,551
// // SceneDelegate.swift // octopus-reader // // Created by CHAN Hong Wing on 25/9/2019. // Copyright © 2019 CHAN Hong Wing. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
44.754386
147
0.715798
de6af87a449a75f8f6c0d5a9ba8fd1f4f54a1574
4,490
/* * Copyright (c) 2020, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import XCTest @testable import nRF_Blinky @testable import CoreBluetoothMock /// This test simulates a scenario when a device failed to connect for some reason. /// /// It is using the app and testing it by sending notifications that trigger different /// actions. class FailedConnectionTest: XCTestCase { override func setUp() { // This method is called AFTER ScannerTableViewController.viewDidLoad() // where the BlinkyManager is instantiated. A separate mock manager // is not created in this test. // Initially mock Bluetooth adapter is powered Off. CBMCentralManagerMock.simulatePeripherals([blinky, hrm, thingy]) CBMCentralManagerMock.simulateInitialState(.poweredOn) } override func tearDown() { // We can't call CBMCentralManagerMock.tearDownSimulation() here. // That would invalidate the BlinkyManager in ScannerTableViewController. // The central manager must be reused, so let's just power mock off, // which will allow us to set different set of peripherals in another test. CBMCentralManagerMock.simulatePowerOff() } func testScanningBlinky() { // Set up the devices in range. blinky.simulateProximityChange(.immediate) hrm.simulateProximityChange(.near) thingy.simulateProximityChange(.far) // Reset the blinky. blinky.simulateReset() // Wait until the blinky is found. var target: BlinkyPeripheral? let found = XCTestExpectation(description: "Device found") Sim.onBlinkyDiscovery { blinky in XCTAssertEqual(blinky.advertisedName, "nRF Blinky") XCTAssert(blinky.isConnectable == true) XCTAssert(blinky.isConnected == false) XCTAssertGreaterThanOrEqual(blinky.RSSI.intValue, -70 - 15) XCTAssertLessThanOrEqual(blinky.RSSI.intValue, -70 + 15) target = blinky found.fulfill() } wait(for: [found], timeout: 3) XCTAssertNotNil(target, "nRF Blinky not found. Make sure you run the test on a simulator.") if target == nil { // Going further would cause a crash. return } // Let's move Blinky out of range. blinky.simulateProximityChange(.outOfRange) // Select found device. Sim.post(.selectPeripheral(at: 0)) // Wait until blinky is connected and ready. let connected = XCTestExpectation(description: "Connected") connected.isInverted = true target!.onConnected { connected.fulfill() } wait(for: [connected], timeout: 3) let appDelegate = UIApplication.shared.delegate as! AppDelegate let navigationController = appDelegate.window!.rootViewController as! UINavigationController navigationController.popViewController(animated: true) } }
42.358491
100
0.704454
c1cbec8d02edab73f62d95c85b276e17869f5bf4
682
// // FoodSprite.swift // RainCat // // Created by CoderDream on 2019/1/21. // Copyright © 2019 CoderDream. All rights reserved. // import SpriteKit public class FoodSprite : SKSpriteNode { public static func newInstance() -> FoodSprite { let foodDish = FoodSprite(imageNamed: "food_dish") foodDish.physicsBody = SKPhysicsBody(rectangleOf: foodDish.size) foodDish.physicsBody?.categoryBitMask = FoodCategory foodDish.physicsBody?.contactTestBitMask = WorldCategory | RainDropCategory | CatCategory foodDish.zPosition = 5 return foodDish } public func update(deltaTime: TimeInterval) { } }
26.230769
97
0.677419
fb3b53dbee7aa93753a23b1a94a87cfe41c2d4a8
411
// // StringValidateRule.swift // Pods // // Created by Siwasit Anmahapong on 11/14/17. // // import Foundation open class StringRule: Rule { public init() {} open func validate(candidate: Any?) -> Bool { guard let string = candidate as? String else { return false } return validate(string: string) } open func validate(string: String) -> Bool { return true } }
15.222222
50
0.622871
f8a769f2cae6760c0f3f281cbdd2f213cc5113ca
1,869
// // PostsViewController.swift // PetWorld // // Created by Vivian Pham on 5/6/17. // Copyright © 2017 GangsterSwagMuffins. All rights reserved. // import UIKit import AVFoundation import Photos class PostsViewController: UIViewController { var exitedCallback: ((Void) -> Void)? override func viewDidLoad() { super.viewDidLoad() print("POSTVIEWCONTROLLER VIEWDIDLOAD") let storyboard = UIStoryboard(name: "Main", bundle: nil) let tabBarController = storyboard.instantiateViewController(withIdentifier: "PostMediaTabViewController") as! UITabBarController print("viewDidLoad()") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("POSTVIEWCONTROLLER VIEWWILLAPPEAR") performSegue(withIdentifier: "PostMediaSegue", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let tabBarController = segue.destination as! UITabBarController print("POSTVIEWCONTROLLER PREPAREFORSEGUE") if let viewControllers = tabBarController.viewControllers{ let galleryVC = viewControllers[0] as! GalleryViewController galleryVC.finishedCallback = exitedCallback } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
23.074074
136
0.613697
de4c5d4c8487f745aab417931aca4f91bcf4ac1c
3,694
// // Copyright 2021 Adobe // All Rights Reserved. // NOTICE: Adobe permits you to use, modify, and distribute this file in // accordance with the terms of the Adobe license agreement accompanying // it. // // TestData.swift // WKNDAdventures // import Foundation import Apollo // Static test data to power preview struct TestData { static var adventures: [Adventure] = { return [ Adventure(adventureData: AdventureData( _path: "/content/dam/wknd/en/adventures/bali-surf-camp/bali-surf-camp", adventureTitle: "Bali Surf Camping", adventurePrice: "$5000 USD", adventureActivity: "Surfing", adventureDescription: AdventureData.AdventureDescription(plaintext: "Surfing in Bali is on the bucket list of every surfer - whether you're a beginner or someone who's been surfing for decades, there will be a break to cater to your ability. Bali offers warm water, tropical vibes, awesome breaks and low cost expenses."), adventureDifficulty: "Beginner", adventureTripLength: "6 Days", adventurePrimaryImage: AdventureData.AdventurePrimaryImage.makeImageRef(_authorUrl: "http://localhost:4502/content/dam/wknd/en/adventures/bali-surf-camp/AdobeStock_175749320.jpg", _publishUrl: "http://localhost:4503/content/dam/wknd/en/adventures/bali-surf-camp/AdobeStock_175749320.jpg") ) ), Adventure(adventureData: AdventureData( _path: "/content/dam/wknd/en/adventures/climbing-new-zealand/climbing-new-zealand", adventureTitle: "Climbing New Zealand", adventurePrice: "$900 USD", adventureActivity: "Rock Climbing", adventureDescription: AdventureData.AdventureDescription(plaintext: "Let us take you on a spectacular climbing experience unique to New Zealand\n\nFeel the raw adventure and excitement of our guided rock climbing experience. Reach new heights under our professional instruction and feel your body and mind work together in harmony. Come join us for a guided rock climbing adventure in the mountains that trained Sir Edmund Hilary. Whether it is your first time thinking of putting on climbing shoes or you are an old hand looking for some new challenges, our guides can make your climbing adventure a trip you won’t soon forget. New Zealand has countless climbing routes to choose from and is known as one of the premiere climbing destinations in the world. With so many different routes and areas to choose from our guides can tailor each trip to your exact specifications. Let us help you make your New Zealand climbing vacation a memory you will cherish forever!"), adventureDifficulty: "Intermediate", adventureTripLength: "2 Days", adventurePrimaryImage: AdventureData.AdventurePrimaryImage.makeImageRef(_authorUrl: "http://localhost:4502/content/dam/wknd/en/adventures/climbing-new-zealand/AdobeStock_140634652.jpeg", _publishUrl: "http://localhost:4503/content/dam/wknd/en/adventures/climbing-new-zealand/AdobeStock_140634652.jpeg") ) ) ] }() }
76.958333
955
0.621007
4b0cbd307be06f821393d33509d149405c4004f2
8,976
// // Snap.swift // MCM // // Created by Jose Castellanos on 1/7/15. // Copyright (c) 2015 NextGen Apps LLC. All rights reserved. // import Foundation import Photos import NGAEssentials import NGAUI public protocol NGAImageRequestProtocol:class { func imagePicked(img:UIImage?, info: SwiftDictionary?) func imageAssetsPicked(assets:[PHAsset]?) } public protocol BatchPickerDelegate: class{ func batchPicker(picker:BatchImagePickerVC, didFinishPickingWithAssets assets:NSArray) } open class BatchImagePickerVC: NGACollectionViewController { open weak var delegate:AssetsPickerDelegate? open var fetchResult:PHFetchResult<PHAsset>? open let imageManager = PHCachingImageManager() open override var collectionViewCellClass:AnyClass? { get {return NGAPhotoCollectionViewCell.self} } open var assets = NSMutableArray() open var selectedIndexes:NSMutableArray = NSMutableArray() open override func viewDidLoad() { super.viewDidLoad() self.contentView.backgroundColor = UIColor.white self.navigationItem.title = "Photos" collectionView.allowsMultipleSelection = true let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(selectPhotos)) self.navigationItem.rightBarButtonItem = doneButton } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) collectionView.frame = contentView.bounds reloadCollectionViewOnMainThread() } open override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) { self.collectionView.frame = self.contentView.bounds } open override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } open override func setFramesForSubviews() { super.setFramesForSubviews() reloadCollectionViewOnMainThread() } //MARK:override collection view open override func numberOfSections(in: UICollectionView) -> Int { return 1 } open override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return fetchResult?.count ?? 0 } open override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = super.collectionView(collectionView, cellForItemAt: indexPath) if let photoCell = cell as? NGAPhotoCollectionViewCell { photoCell.imageManager = imageManager // if indexPath.row < assets.count {photoCell.asset = assets[indexPath.row] as? ALAsset} if indexPath.row < fetchResult?.count ?? 0 {photoCell.photo = fetchResult?.object(at: indexPath.row)} if selectedIndexes.contains(indexPath.row) { let selectedIndex = self.selectedIndexes.index(of: indexPath.row) photoCell.selectionNumber = selectedIndex + 1 // photoCell.selected = true collectionView.selectItem(at: indexPath, animated: false, scrollPosition: []) photoCell.isSelected = true } else { collectionView.deselectItem(at: indexPath, animated: false) photoCell.isSelected = false } } return cell } open override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var cellSize = CGSize.zero cellSize.width = landscape ? contentView.frameWidth / 6 : contentView.frameWidth / 4 cellSize.height = cellSize.width return cellSize } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(0, 0, 0, 0) } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 0 } open func collectionView(_ collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) { if !selectedIndexes.contains(indexPath.row) {selectedIndexes.add(indexPath.row)} reloadCollectionViewOnMainThread() } open func collectionView(_ collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: IndexPath) { selectedIndexes.remove(indexPath.row) reloadCollectionViewOnMainThread() } //MARK: Actions open func selectPhotos() { var assets:[PHAsset] = [] for object in selectedIndexes { guard let i = object as? Int else {continue} assets.appendIfNotNil(fetchResult?.object(at: i)) } self.navigationController?.dismiss(animated: true, completion: { () -> Void in self.delegate?.assetsPicked(assets: assets) }) } //MARK: Helper methods // func reverseArray(array:NSMutableArray) -> NSMutableArray // { // let reversedArray = NSMutableArray(capacity: array.count) // let enumerator = array.reverseObjectEnumerator() // while let object:AnyObject = enumerator.nextObject() // { // reversedArray.addObject(object) // } // // return reversedArray // // // } } open class NGAPhotoCollectionViewCell: NGACollectionViewCell { open lazy var photoImageView:UIImageView = { let tempImageView = UIImageView() tempImageView.contentMode = UIViewContentMode.scaleAspectFill // tempImageView.frame = self.contentView.frame tempImageView.clipsToBounds = true // self.contentView.addSubview(tempImageView) return tempImageView }() open lazy var selectedView:UIView = { let tempView = UIView() tempView.backgroundColor = UIColor.black.withAlphaComponent(0.5) // tempView.frame = self.contentView.frame return tempView }() open lazy var selectedLabel:UILabel = { let label = UILabel(frame: self.contentView.frame) label.textColor = UIColor.white label.textAlignment = NSTextAlignment.center let fontSize = self.contentView.frame.size.width / 4 label.font = UIFont(name: "Verdana-Bold", size: fontSize) return label; }() open weak var imageManager:PHCachingImageManager? open var requestID:PHImageRequestID? open var photo:PHAsset? { didSet{ if photo != oldValue { let p = photo requestID = imageManager?.requestImage(for: photo!, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFit, options: nil, resultHandler: { (img:UIImage?, dict:SwiftDictionary?) -> Void in if p == self.photo { self.photoImageView.image = img } }) } } } open var selectionNumber:Int? { didSet{ if selectionNumber != nil { selectedLabel.text = "\(selectionNumber!)" } } } open override var isSelected:Bool{ didSet{ if isSelected{ contentView.addSubview(selectedView) // self.contentView.layer.borderWidth = 5 contentView.addSubview(selectedLabel) if selectionNumber != nil { selectedLabel.text = "\(selectionNumber!)" } } else{ selectedView.removeFromSuperview() selectedLabel.removeFromSuperview() // self.contentView.layer.borderWidth = 0 } } } open override func setFramesForSubviews() { super.setFramesForSubviews() photoImageView.frame = contentView.bounds selectedView.frame = contentView.bounds selectedLabel.frame = contentView.bounds selectedLabel.font = UIFont(name: "Verdana-Bold", size: contentView.frame.size.width / 4) contentView.addSubviewIfNeeded(photoImageView) contentView.clipsToBounds = true } }
31.717314
218
0.629679
269d20cda7b529c59ca2d61febe978cc25b309aa
4,429
// // Generated by SwagGen // https://github.com/pace/SwagGen // import Foundation public protocol PayAPIRequestBehaviour { /// runs first and allows the requests to be modified. If modifying asynchronously use validate func modifyRequest(request: AnyPayAPIRequest, urlRequest: URLRequest) -> URLRequest /// validates and modifies the request. complete must be called with either .success or .fail func validate(request: AnyPayAPIRequest, urlRequest: URLRequest, complete: @escaping (RequestValidationResult) -> Void) /// called before request is sent func beforeSend(request: AnyPayAPIRequest) /// called when request successfuly returns a 200 range response func onSuccess(request: AnyPayAPIRequest, result: Any) /// called when request fails with an error. This will not be called if the request returns a known response even if the a status code is out of the 200 range func onFailure(request: AnyPayAPIRequest, error: APIClientError) /// called if the request recieves a network response. This is not called if request fails validation or encoding func onResponse(request: AnyPayAPIRequest, response: AnyPayAPIResponse) } // Provides empty defaults so that each function becomes optional public extension PayAPIRequestBehaviour { func modifyRequest(request: AnyPayAPIRequest, urlRequest: URLRequest) -> URLRequest { return urlRequest } func validate(request: AnyPayAPIRequest, urlRequest: URLRequest, complete: @escaping (RequestValidationResult) -> Void) { complete(.success(urlRequest)) } func beforeSend(request: AnyPayAPIRequest) {} func onSuccess(request: AnyPayAPIRequest, result: Any) {} func onFailure(request: AnyPayAPIRequest, error: APIClientError) {} func onResponse(request: AnyPayAPIRequest, response: AnyPayAPIResponse) {} } // Group different RequestBehaviours together struct PayAPIRequestBehaviourGroup { let request: AnyPayAPIRequest let behaviours: [PayAPIRequestBehaviour] init<T>(request: PayAPIRequest<T>, behaviours: [PayAPIRequestBehaviour]) { self.request = request.asAny() self.behaviours = behaviours } func beforeSend() { behaviours.forEach { $0.beforeSend(request: request) } } func validate(_ urlRequest: URLRequest, complete: @escaping (RequestValidationResult) -> Void) { if behaviours.isEmpty { complete(.success(urlRequest)) return } var count = 0 var modifiedRequest = urlRequest func validateNext() { let behaviour = behaviours[count] behaviour.validate(request: request, urlRequest: modifiedRequest) { result in count += 1 switch result { case .success(let urlRequest): modifiedRequest = urlRequest if count == self.behaviours.count { complete(.success(modifiedRequest)) } else { validateNext() } case .failure(let error): complete(.failure(error)) } } } validateNext() } func onSuccess(result: Any) { behaviours.forEach { $0.onSuccess(request: request, result: result) } } func onFailure(error: APIClientError) { behaviours.forEach { $0.onFailure(request: request, error: error) } } func onResponse(response: AnyPayAPIResponse) { behaviours.forEach { $0.onResponse(request: request, response: response) } } func modifyRequest(_ urlRequest: URLRequest) -> URLRequest { guard let oldUrl = urlRequest.url else { return urlRequest } var newRequest = urlRequest behaviours.forEach { newRequest = $0.modifyRequest(request: request, urlRequest: urlRequest) } newRequest.url = QueryParamHandler.buildUrl(for: oldUrl) newRequest.setValue(Constants.Tracing.identifier, forHTTPHeaderField: Constants.Tracing.key) return newRequest } } extension PayAPIService { public func asAny() -> PayAPIService<AnyResponseValue> { return PayAPIService<AnyResponseValue>(id: id, tag: tag, method: method, path: path, hasBody: hasBody, securityRequirements: securityRequirements) } }
35.717742
162
0.662226
6a22118d50eeddc2ba73e3deb694263931cc5fb6
1,764
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import Freddy /** A wrapper object that contains results from a Speech to Text recognition request. */ internal struct TranscriptionResultWrapper: JSONDecodable { /// Index indicating change point in the results array. /// (See description of `results` array for more information.) internal let resultIndex: Int /// The results array consists of 0 or more final results, followed by 0 or 1 interim /// result. The final results are guaranteed not to change, while the interim result may /// be replaced by 0 or more final results, followed by 0 or 1 interim result. The service /// periodically sends "updates" to the result list, with the `resultIndex` set to the /// lowest index in the array that has changed. `resultIndex` always points to the slot /// just after the most recent final result. internal let results: [TranscriptionResult] /// Used internally to initialize a `TranscriptionResultWrapper` model from JSON. internal init(json: JSON) throws { resultIndex = try json.int("result_index") results = try json.arrayOf("results", type: TranscriptionResult.self) } }
43.02439
94
0.731293
9081a7cac865ec2d72dacd760fcbb311d39cb56e
2,583
// // DefaultVideoRenderView.swift // AmazonChimeSDK // // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // import os import UIKit import VideoToolbox @objcMembers public class DefaultVideoRenderView: UIImageView, VideoRenderView { private let scalingContentModes: [UIView.ContentMode] = [.scaleAspectFill, .scaleToFill, .scaleAspectFit] public var mirror: Bool = false { didSet { transformNeedsUpdate = true } } public override var contentMode: UIView.ContentMode { willSet(newContentMode) { if !scalingContentModes.contains(newContentMode) { os_log(""" Recommend to use a scaling ContentMode on the VideoRenderView, as video resolution may change during the session. """, type: .info) } imageView.contentMode = newContentMode } } // Delay the transform until the next frame private var transformNeedsUpdate: Bool = false // We use an internal UIImageView so we can mirror // it without mirroring the entire view private var imageView: UIImageView public required init?(coder: NSCoder) { imageView = UIImageView() super.init(coder: coder) initImageView() } public override init(frame: CGRect) { imageView = UIImageView() super.init(frame: frame) initImageView() } private func initImageView() { addSubview(imageView) sendSubviewToBack(imageView) imageView.frame = bounds imageView.contentMode = contentMode imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] } // Expects CVPixelBuffer as frame type public func renderFrame(frame: CVPixelBuffer?) { if frame == nil { isHidden = true imageView.image = nil } else if let frame = frame { isHidden = false var cgImage: CGImage? VTCreateCGImageFromCVPixelBuffer(frame, options: nil, imageOut: &cgImage) if cgImage == nil { return } if transformNeedsUpdate { transformNeedsUpdate = false if mirror { imageView.transform = CGAffineTransform(scaleX: -1, y: 1) } else { imageView.transform = CGAffineTransform(scaleX: 1, y: 1) } } imageView.image = UIImage(cgImage: cgImage!) } } }
29.689655
109
0.600077
bf23c3f2fa2cab305401c22b77574a09cbc8b2d2
1,982
// // The MIT License // // Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.com) // // 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. // // // AAAxle.swift // AutoAPI // // Generated by AutoAPIGenerator for Swift. // Copyright © 2021 High-Mobility GmbH. All rights reserved. // import Foundation import HMUtilities /// Axle enum. public enum AAAxle: String, CaseIterable, Codable, HMBytesConvertable { case front case rear public var byteValue: UInt8 { switch self { case .front: return 0x00 case .rear: return 0x01 } } // MARK: HMBytesConvertable public var bytes: [UInt8] { [byteValue] } public init?(bytes: [UInt8]) { guard let uint8 = UInt8(bytes: bytes) else { return nil } switch uint8 { case 0x00: self = .front case 0x01: self = .rear default: return nil } } }
28.314286
81
0.679112
d77bd5d0ea84ef4a137d1bf3ac7994309fec7054
168
// // QuestionBank.swift // Quizzler // // Created by Abhiman Kolte on 12/25/17. // Copyright © 2017 London App Brewery. All rights reserved. // import Foundation
16.8
61
0.690476
8a92ba642ada11e2af9993ae8ad1a951cfd94ee3
2,666
import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate, SPTAppRemoteDelegate { static private let kAccessTokenKey = "access-token-key" private let redirectUri = URL(string:"comspotifytestsdk://")! private let clientIdentifier = "<#ClientID#>" var window: UIWindow? lazy var appRemote: SPTAppRemote = { let configuration = SPTConfiguration(clientID: self.clientIdentifier, redirectURL: self.redirectUri) let appRemote = SPTAppRemote(configuration: configuration, logLevel: .debug) appRemote.connectionParameters.accessToken = self.accessToken appRemote.delegate = self return appRemote }() var accessToken = UserDefaults.standard.string(forKey: kAccessTokenKey) { didSet { let defaults = UserDefaults.standard defaults.set(accessToken, forKey: SceneDelegate.kAccessTokenKey) } } func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { guard let url = URLContexts.first?.url else { return } let parameters = appRemote.authorizationParameters(from: url); if let access_token = parameters?[SPTAppRemoteAccessTokenKey] { appRemote.connectionParameters.accessToken = access_token self.accessToken = access_token } else if let errorDescription = parameters?[SPTAppRemoteErrorDescriptionKey] { playerViewController.showError(errorDescription) } } func sceneDidBecomeActive(_ scene: UIScene) { connect(); } func sceneWillResignActive(_ scene: UIScene) { playerViewController.appRemoteDisconnect() appRemote.disconnect() } func connect() { playerViewController.appRemoteConnecting() appRemote.connect() } // MARK: AppRemoteDelegate func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) { self.appRemote = appRemote playerViewController.appRemoteConnected() } func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) { print("didFailConnectionAttemptWithError") playerViewController.appRemoteDisconnect() } func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) { print("didDisconnectWithError") playerViewController.appRemoteDisconnect() } var playerViewController: ViewController { get { let navController = self.window?.rootViewController?.children[0] as! UINavigationController return navController.topViewController as! ViewController } } }
32.91358
108
0.693548
9be062de614674f8a29dc06c82de67bf1e2e6c83
1,601
import Foundation import Security internal struct UserSession: Codable, Equatable { let clientId: String let userTokens: UserTokens let updatedAt: Date } public struct UserTokens: Codable, Equatable, CustomStringConvertible { let accessToken: String let refreshToken: String? let idToken: String let idTokenClaims: IdTokenClaims public init(accessToken: String, refreshToken: String?, idToken: String, idTokenClaims: IdTokenClaims) { self.accessToken = accessToken self.refreshToken = refreshToken self.idToken = idToken self.idTokenClaims = idTokenClaims } public var description: String { return "UserTokens(" + "accessToken: \(removeSignature(fromToken: accessToken)),\n" + "refreshToken: \(removeSignature(fromToken: refreshToken)),\n" + "idToken: \(removeSignature(fromToken: idToken)),\n" + "idTokenClaims: \(idTokenClaims))" } } internal protocol SessionStorage { var accessGroup: String? { get } func store(_ value: UserSession, accessGroup: String?, completion: @escaping (Result<Void, Error>) -> Void) func get(forClientId: String, completion: @escaping (UserSession?) -> Void) func getAll() -> [UserSession] func remove(forClientId: String) func getLatestSession() -> UserSession? } extension SessionStorage { func getLatestSession() -> UserSession? { let latestUserSession = self.getAll() .sorted { $0.updatedAt > $1.updatedAt } .first return latestUserSession } }
32.673469
111
0.668332
2f07f851d45ab2d4bb3e395438908cf20ef038ba
6,950
// RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck %s protocol P1 { // CHECK: [[@LINE]]:10 | protocol/Swift | P1 | [[P1_USR:.*]] | Def | func foo() // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[P1_foo_USR:.*]] | Def } struct DirectConf: P1 { // CHECK: [[@LINE]]:8 | struct/Swift | DirectConf | [[DirectConf_USR:.*]] | Def func foo() {} // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[DirectConf_foo_USR:.*]] | Def,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[P1_foo_USR]] // CHECK-NEXT: RelChild | struct/Swift | DirectConf | [[DirectConf_USR]] } struct ConfFromExtension {} extension ConfFromExtension: P1 { // CHECK: [[@LINE]]:11 | extension/ext-struct/Swift | ConfFromExtension | [[ConfFromExtension_ext_USR:.*]] | Def func foo() {} // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[ConfFromExtension_ext_foo_USR:.*]] | Def,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[P1_foo_USR]] // CHECK-NEXT: RelChild | extension/ext-struct/Swift | ConfFromExtension | [[ConfFromExtension_ext_USR]] } struct ImplicitConfFromExtension { // CHECK: [[@LINE]]:8 | struct/Swift | ImplicitConfFromExtension | [[ImplicitConfFromExtension_USR:.*]] | Def func foo() {} // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[ImplicitConfFromExtension_foo_USR:.*]] | Def,RelChild | rel: 1 // CHECK-NEXT: RelChild | struct/Swift | ImplicitConfFromExtension | [[ImplicitConfFromExtension_USR]] } extension ImplicitConfFromExtension: P1 { // CHECK: [[@LINE]]:11 | extension/ext-struct/Swift | ImplicitConfFromExtension | [[ImplicitConfFromExtension_USR:.*]] | Def // CHECK: [[@LINE-1]]:11 | instance-method/Swift | foo() | [[ImplicitConfFromExtension_foo_USR]] | Impl,RelOver,RelCont | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[P1_foo_USR]] // CHECK-NEXT: RelCont | extension/ext-struct/Swift | ImplicitConfFromExtension | [[ImplicitConfFromExtension_USR]] } class BaseConfFromBase { // CHECK: [[@LINE]]:7 | class/Swift | BaseConfFromBase | [[BaseConfFromBase_USR:.*]] | Def func foo() {} // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[BaseConfFromBase_foo_USR:.*]] | Def,Dyn,RelChild | rel: 1 // CHECK-NEXT: RelChild | class/Swift | BaseConfFromBase | [[BaseConfFromBase_USR]] } class SubConfFromBase: BaseConfFromBase, P1 { // CHECK: [[@LINE]]:7 | class/Swift | SubConfFromBase | [[SubConfFromBase_USR:.*]] | Def // CHECK: [[@LINE-1]]:7 | instance-method/Swift | foo() | [[BaseConfFromBase_foo_USR]] | Impl,RelOver,RelCont | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[P1_foo_USR]] // CHECK-NEXT: RelCont | class/Swift | SubConfFromBase | [[SubConfFromBase_USR]] } protocol P2 { // CHECK: [[@LINE]]:10 | protocol/Swift | P2 | [[P2_USR:.*]] | Def | func foo() // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[P2_foo_USR:.*]] | Def } extension P2 { // CHECK: [[@LINE]]:11 | extension/ext-protocol/Swift | P2 | [[P2_ext_USR:.*]] | Def func foo() {} // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[P2_ext_foo_USR:.*]] | Def,Dyn,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[P2_foo_USR]] // CHECK-NEXT: RelChild | extension/ext-protocol/Swift | P2 | [[P2_ext_USR]] } struct ConfFromDefaultImpl: P2 { // CHECK: [[@LINE]]:8 | struct/Swift | ConfFromDefaultImpl | [[ConfFromDefaultImpl_USR:.*]] | Def // CHECK: [[@LINE-1]]:8 | instance-method/Swift | foo() | [[P2_ext_foo_USR]] | Impl,RelOver,RelCont | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[P2_foo_USR]] // CHECK-NEXT: RelCont | struct/Swift | ConfFromDefaultImpl | [[ConfFromDefaultImpl_USR]] } protocol P3 { func meth1() // CHECK: [[@LINE]]:8 | instance-method/Swift | meth1() | [[P3_meth1_USR:.*]] | Def func meth2() // CHECK: [[@LINE]]:8 | instance-method/Swift | meth2() | [[P3_meth2_USR:.*]] | Def } class BaseMultiConf { func meth2() {} // CHECK: [[@LINE]]:8 | instance-method/Swift | meth2() | [[BaseMultiConf_meth2_USR:.*]] | Def } extension SubMultiConf { func meth1() {} // CHECK: [[@LINE]]:8 | instance-method/Swift | meth1() | [[SubMultiConf_ext_meth1_USR:.*]] | Def } class SubMultiConf: BaseMultiConf,P2,P1,P3 { // CHECK: [[@LINE]]:7 | class/Swift | SubMultiConf | [[SubMultiConf_USR:.*]] | Def // CHECK: [[@LINE-1]]:7 | instance-method/Swift | foo() | [[P2_ext_foo_USR]] | Impl,RelOver,RelCont | rel: 2 // CHECK-NEXT RelOver | instance-method/Swift | foo() | [[P2_foo_USR]] // CHECK-NEXT RelCont | class/Swift | SubMultiConf | [[SubMultiConf_USR]] // CHECK: [[@LINE-4]]:7 | instance-method/Swift | foo() | [[P2_ext_foo_USR]] | Impl,RelOver,RelCont | rel: 2 // CHECK-NEXT RelOver | instance-method/Swift | foo() | [[P1_foo_USR]] // CHECK-NEXT RelCont | class/Swift | SubMultiConf | [[SubMultiConf_USR]] // CHECK: [[@LINE-7]]:7 | instance-method/Swift | meth1() | [[SubMultiConf_ext_meth1_USR]] | Impl,RelOver,RelCont | rel: 2 // CHECK-NEXT RelOver | instance-method/Swift | meth1() | [[P3_meth1_USR]] // CHECK-NEXT RelCont | class/Swift | SubMultiConf | [[SubMultiConf_USR]] // CHECK: [[@LINE-10]]:7 | instance-method/Swift | meth2() | [[BaseMultiConf_meth2_USR]] | Impl,RelOver,RelCont | rel: 2 // CHECK-NEXT RelOver | instance-method/Swift | meth2() | [[P3_meth2_USR]] // CHECK-NEXT RelCont | class/Swift | SubMultiConf | [[SubMultiConf_USR]] // CHECK-NOT: [[@LINE-13]]:7 | instance-method } protocol InheritingP: P1 { // CHECK: [[@LINE]]:10 | protocol/Swift | InheritingP | [[InheritingP_USR:.*]] | Def func foo() // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[InheritingP_foo_USR:.*]] | Def,Dyn,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | s:14swift_ide_test2P1P3fooyyF // CHECK-NEXT: RelChild | protocol/Swift | InheritingP | [[InheritingP_USR]] } struct DirectConf2: InheritingP { // CHECK: [[@LINE]]:8 | struct/Swift | DirectConf2 | [[DirectConf2_USR:.*]] | Def // FIXME: Should only override InheritingP.foo() func foo() {} // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[DirectConf2_foo_USR:.*]] | Def,RelChild,RelOver | rel: 3 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[InheritingP_foo_USR]] // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[P1_foo_USR]] // CHECK-NEXT: RelChild | struct/Swift | DirectConf2 | [[DirectConf2_USR]] } extension InheritingP { // CHECK: [[@LINE]]:11 | extension/ext-protocol/Swift | InheritingP | [[InheritingP_USR:.*]] | Def func foo() {} // CHECK: [[@LINE]]:8 | instance-method/Swift | foo() | [[InheritingP_ext_foo_USR:.*]] | Def,Dyn,RelChild,RelOver | rel: 2 // CHECK-NEXT: RelOver | instance-method/Swift | foo() | [[InheritingP_foo_USR]] // CHECK-NEXT: RelChild | extension/ext-protocol/Swift | InheritingP | [[InheritingP_USR]] }
68.811881
166
0.659856
feec00a211df33149107db665cca78ca5624e5dc
470
import UIKit extension UISplitViewController { convenience init(masterViewController: UIViewController, detailViewController: UIViewController) { self.init() viewControllers = [masterViewController, detailViewController] } var masterViewController: UIViewController? { return viewControllers.first } var detailViewController: UIViewController? { guard viewControllers.count == 2 else { return nil } return viewControllers.last } }
23.5
99
0.76383