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
2822e733e310503ec5e37f89d5ff26efc7714db8
1,002
// // DeviceFingerprintDeleteUseCaseCoordinator.swift // Domain // // Created by Li Hao Lai on 28/9/17. // Copyright © 2017 Pointwelve. All rights reserved. // import Foundation import RxSwift public struct DeviceFingerprintDeleteUseCaseCoordinator: UseCaseCoordinatorType { public typealias DeleteAction = () -> Observable<String> let deleteAction: DeleteAction public init(deleteAction: @escaping DeleteAction) { self.deleteAction = deleteAction } func deleteRequest() -> Observable<String> { return deleteAction() } func delete() -> Observable<DeviceFingerprintDeleteUseCaseCoordinator> { return deleteRequest().map(replacing) } public func deleteResult() -> Observable<Result<DeviceFingerprintDeleteUseCaseCoordinator>> { return result(from: delete()).startWith(.content(.with(self, .loading))) } func replacing(string: String) -> DeviceFingerprintDeleteUseCaseCoordinator { return .init(deleteAction: deleteAction) } }
27.081081
96
0.733533
23e9b52b97da094107ecc5cc2736b49f12f17123
10,421
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2021 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 Dispatch import TSCBasic import TSCUtility import SPMBuildCore import Basics import Build import PackageGraph import PackageModel import SourceControl import Workspace /// Helper for emitting a JSON API baseline for a module. struct APIDigesterBaselineDumper { /// The revision to emit a baseline for. let baselineRevision: Revision /// The root package path. let packageRoot: AbsolutePath /// The input build parameters. let inputBuildParameters: BuildParameters /// The manifest loader. let manifestLoader: ManifestLoaderProtocol /// The repository manager. let repositoryManager: RepositoryManager /// The API digester tool. let apiDigesterTool: SwiftAPIDigester /// The diagnostics engine for emitting errors/warnings. let diags: DiagnosticsEngine init( baselineRevision: Revision, packageRoot: AbsolutePath, buildParameters: BuildParameters, manifestLoader: ManifestLoaderProtocol, repositoryManager: RepositoryManager, apiDigesterTool: SwiftAPIDigester, diags: DiagnosticsEngine ) { self.baselineRevision = baselineRevision self.packageRoot = packageRoot self.inputBuildParameters = buildParameters self.manifestLoader = manifestLoader self.repositoryManager = repositoryManager self.apiDigesterTool = apiDigesterTool self.diags = diags } /// Emit the API baseline files and return the path to their directory. func emitAPIBaseline(for modulesToDiff: Set<String>, at baselineDir: AbsolutePath?, force: Bool) throws -> AbsolutePath { var modulesToDiff = modulesToDiff let apiDiffDir = inputBuildParameters.apiDiff let baselineDir = (baselineDir ?? apiDiffDir).appending(component: baselineRevision.identifier) let baselinePath: (String)->AbsolutePath = { module in baselineDir.appending(component: module + ".json") } if !force { // Baselines which already exist don't need to be regenerated. modulesToDiff = modulesToDiff.filter { !localFileSystem.exists(baselinePath($0)) } } guard !modulesToDiff.isEmpty else { // If none of the baselines need to be regenerated, return. return baselineDir } // Setup a temporary directory where we can checkout and build the baseline treeish. let baselinePackageRoot = apiDiffDir.appending(component: "\(baselineRevision.identifier)-checkout") if localFileSystem.exists(baselinePackageRoot) { try localFileSystem.removeFileTree(baselinePackageRoot) } // Clone the current package in a sandbox and checkout the baseline revision. let specifier = RepositorySpecifier(url: baselinePackageRoot.pathString) let workingCopy = try repositoryManager.provider.createWorkingCopy( repository: specifier, sourcePath: packageRoot, at: baselinePackageRoot, editable: false ) try workingCopy.checkout(revision: baselineRevision) // Create the workspace for this package. let workspace = Workspace.create( forRootPackage: baselinePackageRoot, manifestLoader: manifestLoader, repositoryManager: repositoryManager ) let graph = try workspace.loadPackageGraph( rootPath: baselinePackageRoot, diagnostics: diags) // Don't emit a baseline for a module that didn't exist yet in this revision. modulesToDiff.formIntersection(graph.apiDigesterModules) // Abort if we weren't able to load the package graph. if diags.hasErrors { throw Diagnostics.fatalError } // Update the data path input build parameters so it's built in the sandbox. var buildParameters = inputBuildParameters buildParameters.dataPath = workspace.dataPath // Build the baseline module. let buildOp = BuildOperation( buildParameters: buildParameters, cacheBuildManifest: false, packageGraphLoader: { graph }, pluginInvoker: { _ in [:] }, diagnostics: diags, stdoutStream: stdoutStream ) try buildOp.build() // Dump the SDK JSON. try localFileSystem.createDirectory(baselineDir, recursive: true) let group = DispatchGroup() let semaphore = DispatchSemaphore(value: Int(buildParameters.jobs)) let errors = ThreadSafeArrayStore<Swift.Error>() for module in modulesToDiff { semaphore.wait() DispatchQueue.sharedConcurrent.async(group: group) { do { try apiDigesterTool.emitAPIBaseline( to: baselinePath(module), for: module, buildPlan: buildOp.buildPlan! ) } catch { errors.append(error) } semaphore.signal() } } group.wait() for error in errors.get() { diags.emit(error) } if diags.hasErrors { throw Diagnostics.fatalError } return baselineDir } } /// A wrapper for the swift-api-digester tool. public struct SwiftAPIDigester { /// The absolute path to `swift-api-digester` in the toolchain. let tool: AbsolutePath init(tool: AbsolutePath) { self.tool = tool } /// Emit an API baseline file for the specified module at the specified location. public func emitAPIBaseline( to outputPath: AbsolutePath, for module: String, buildPlan: BuildPlan ) throws { var args = ["-dump-sdk"] args += buildPlan.createAPIToolCommonArgs(includeLibrarySearchPaths: false) args += ["-module", module, "-o", outputPath.pathString] try runTool(args) if !localFileSystem.exists(outputPath) { throw Error.failedToGenerateBaseline(module) } } /// Compare the current package API to a provided baseline file. public func compareAPIToBaseline( at baselinePath: AbsolutePath, for module: String, buildPlan: BuildPlan, except breakageAllowlistPath: AbsolutePath? ) -> ComparisonResult? { var args = [ "-diagnose-sdk", "-baseline-path", baselinePath.pathString, "-module", module ] args.append(contentsOf: buildPlan.createAPIToolCommonArgs(includeLibrarySearchPaths: false)) if let breakageAllowlistPath = breakageAllowlistPath { args.append(contentsOf: ["-breakage-allowlist-path", breakageAllowlistPath.pathString]) } return try? withTemporaryFile(deleteOnClose: false) { file in args.append(contentsOf: ["-serialize-diagnostics-path", file.path.pathString]) try runTool(args) let contents = try localFileSystem.readFileContents(file.path) guard contents.count > 0 else { return nil } let serializedDiagnostics = try SerializedDiagnostics(bytes: contents) let apiDigesterCategory = "api-digester-breaking-change" let apiBreakingChanges = serializedDiagnostics.diagnostics.filter { $0.category == apiDigesterCategory } let otherDiagnostics = serializedDiagnostics.diagnostics.filter { $0.category != apiDigesterCategory } return ComparisonResult(moduleName: module, apiBreakingChanges: apiBreakingChanges, otherDiagnostics: otherDiagnostics) } } private func runTool(_ args: [String]) throws { let arguments = [tool.pathString] + args let process = Process( arguments: arguments, outputRedirection: .collect, verbose: verbosity != .concise ) try process.launch() try process.waitUntilExit() } } extension SwiftAPIDigester { public enum Error: Swift.Error, DiagnosticData { case failedToGenerateBaseline(String) public var description: String { switch self { case .failedToGenerateBaseline(let module): return "failed to generate baseline for \(module)" } } } } extension SwiftAPIDigester { /// The result of comparing a module's API to a provided baseline. public struct ComparisonResult { /// The name of the module being diffed. var moduleName: String /// Breaking changes made to the API since the baseline was generated. var apiBreakingChanges: [SerializedDiagnostics.Diagnostic] /// Other diagnostics emitted while comparing the current API to the baseline. var otherDiagnostics: [SerializedDiagnostics.Diagnostic] /// `true` if the comparison succeeded and no breaking changes were found, otherwise `false`. var hasNoAPIBreakingChanges: Bool { apiBreakingChanges.isEmpty && otherDiagnostics.filter { [.fatal, .error].contains($0.level) }.isEmpty } } } extension BuildParameters { /// The directory containing artifacts for API diffing operations. var apiDiff: AbsolutePath { dataPath.appending(component: "apidiff") } } extension PackageGraph { /// The list of modules that should be used as an input to the API digester. var apiDigesterModules: [String] { self.rootPackages .flatMap(\.products) .filter { $0.type.isLibrary } .flatMap(\.targets) .filter { $0.underlyingTarget is SwiftTarget } .map { $0.c99name } } } extension SerializedDiagnostics.SourceLocation: DiagnosticLocation { public var description: String { return "\(filename):\(line):\(column)" } }
34.736667
116
0.640438
21db2ceacc91e25ca4467ed64641ada6117db793
1,016
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "JsonStore", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "JsonStore", targets: ["JsonStore"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "JsonStore", dependencies: []), .testTarget( name: "JsonStoreTests", dependencies: ["JsonStore"]), ] )
35.034483
117
0.619094
bbc5ea575cfda2360c4f2b8b90758968bec5fa21
3,286
// // ArchivedChatsTableViewController.swift // Tinodios // // Copyright © 2019 Tinode. All rights reserved. // import UIKit import TinodeSDK class ArchivedChatsTableViewController: UITableViewController { @IBOutlet var chatListTableView: UITableView! private var topics: [DefaultComTopic] = [] override func viewDidLoad() { super.viewDidLoad() self.chatListTableView.register(UINib(nibName: "ChatListViewCell", bundle: nil), forCellReuseIdentifier: "ChatListViewCell") self.reloadData() } private func reloadData() { self.topics = Cache.tinode.getFilteredTopics(filter: {(topic: TopicProto) in return topic.topicType.matches(TopicType.user) && topic.isArchived && topic.isJoiner })?.map { // Must succeed. $0 as! DefaultComTopic } ?? [] } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.topics.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ChatListViewCell") as! ChatListViewCell let topic = self.topics[indexPath.row] cell.fillFromTopic(topic: topic) return cell } private func unarchiveTopic(topic: DefaultComTopic) { topic.updateArchived(archived: false)?.then( onSuccess: { [weak self] _ in DispatchQueue.main.async { if let vc = self { vc.reloadData() vc.tableView.reloadData() // If there are no more archived topics, close the view. if vc.topics.isEmpty { vc.navigationController?.popViewController(animated: true) vc.dismiss(animated: true, completion: nil) } } } return nil }, onFailure: UiUtils.ToastFailureHandler) } override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let unarchive = UITableViewRowAction(style: .normal, title: NSLocalizedString("Unarchive", comment: "Swipe action")) { (_, indexPath) in let topic = self.topics[indexPath.row] self.unarchiveTopic(topic: topic) } return [unarchive] } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.performSegue(withIdentifier: "ArchivedChats2Messages", sender: self.topics[indexPath.row].name) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ArchivedChats2Messages", let topicName = sender as? String { let messageController = segue.destination as! MessageViewController messageController.topicName = topicName } } }
37.770115
144
0.623554
9160e5e634d563cce567c1b2fc85e5cdb9958090
18,707
// // Airspace.swift // Iguazu // // Created by Engin Kurutepe on 10/12/2016. // Copyright © 2016 Fifteen Jugglers Software. All rights reserved. // import Foundation import CoreLocation public enum AirspaceClass: String { case Alpha = "A" case Bravo = "B" case Charlie = "C" case Delta = "D" case Restricted = "R" case Danger = "Q" case Prohibited = "P" case GliderProhibited = "GP" case CTR = "CTR" case WaveWindow = "W" case TransponderMandatoryZone = "TMZ" case RadioMandatoryZone = "RMZ" case thermalHotspot case thermalBadspot } public typealias AirspacesByClassDictionary = [AirspaceClass: [Airspace]] public typealias Altitude = Measurement<UnitLength> public typealias DegreeComponents = Array<String> public extension Collection where Iterator.Element == String { var degree: CLLocationDegrees? { guard allSatisfy({ Double($0) != nil }) else { return nil } return self.enumerated().map { (n,c) in let idx = Double(n) let value = Double(c)! return value * pow(60.0, -idx) } .reduce(0.0, +) } } public enum AirspaceAltitude: Equatable { case surface case agl(Altitude) case msl(Altitude) case fl(Int) init?(_ string: String) { let lowercase = string.lowercased() if lowercase == "gnd" || lowercase == "sfc" { self = .surface return } let impliedMSLString: String if let mslRange = lowercase.range(of: "msl") { impliedMSLString = lowercase.replacingCharacters(in: mslRange, with: "") } else { impliedMSLString = lowercase } guard let value = Int(impliedMSLString.trimmingCharacters(in: CharacterSet.decimalDigits.inverted).trimmingCharacters(in: .whitespaces)) else { return nil } if impliedMSLString.hasPrefix("fl") { self = .fl(value) return } let unit: UnitLength if impliedMSLString.contains("m") { unit = .meters } else { unit = .feet } if impliedMSLString.hasSuffix("agl") { self = .agl(Altitude(value: Double(value), unit: unit)) return } self = .msl(Altitude(value: Double(value), unit: unit)) return } } extension AirspaceAltitude: Comparable { /// Compare only makes sense for comparing FL and MSL. /// Even then the current implementation is inaccurate and equates msl == 100 * fl /// Comparisons with surface and especailly AGL are programmer error!!! public static func < (lhs: AirspaceAltitude, rhs: AirspaceAltitude) -> Bool { switch (lhs, rhs) { case (.surface, _): return true case (_, .surface): return false case (.fl(let a1), .fl(let a2)): return a1 < a2 case (.msl(let a1), .msl(let a2)): return a1 < a2 case (.msl(let msl), .fl(let fl)): return msl.converted(to: .feet).value < Double(fl * 100) case (.fl(let fl), .msl(let msl)): return Double(fl*100) < msl.converted(to: .feet).value case (.agl(_), .fl(_)): return true case (.fl(_), .agl(_)): return false default: assertionFailure("Compare only makes sense for comparing FL and MSL. Comparisons with surface and AGL are programmer error!!!") return false } } } public struct Airspace: Equatable { public let airspaceClass: AirspaceClass public let ceiling: AirspaceAltitude public let floor: AirspaceAltitude public let name: String public let labelCoordinates: [CLLocationCoordinate2D]? public let polygonCoordinates: [CLLocationCoordinate2D] public var sourceIdentifier: String? public init(name: String, class c: AirspaceClass, floor: AirspaceAltitude, ceiling: AirspaceAltitude, polygon: [CLLocationCoordinate2D], labelCoordinates: [CLLocationCoordinate2D]? = nil) { self.airspaceClass = c self.ceiling = ceiling self.floor = floor self.name = name self.polygonCoordinates = polygon self.labelCoordinates = labelCoordinates } } public final class OpenAirParser { enum OpenAirParserError: Error, Equatable { } public init() {} public func airSpacesByClass(from openAirString: String, sourceIdentifier: String?) -> AirspacesByClassDictionary? { let lines = openAirString.components(separatedBy: .newlines) var airSpaces = AirspacesByClassDictionary() var currentAirspace: AirspaceInProgress? = nil var state = ParserState() for line in lines { guard line.utf8.count > 1 else { continue } guard let firstWhiteSpace = line.rangeOfCharacter(from: .whitespaces) else { continue } let prefix = line[line.startIndex ..< firstWhiteSpace.lowerBound] let value = line[firstWhiteSpace.upperBound ..< line.endIndex] .trimmingCharacters(in: .whitespacesAndNewlines) switch prefix { case "AC": currentAirspace.flatMap { $0.validAirspace.flatMap { asp in guard asp.floor < .fl(100) else { return } var list = airSpaces[asp.airspaceClass] ?? [Airspace]() list.append(asp) airSpaces[asp.airspaceClass] = list } } state = ParserState() currentAirspace = AirspaceInProgress() currentAirspace?.sourceIdentifier = sourceIdentifier currentAirspace?.class = AirspaceClass(rawValue: value) case "AN": currentAirspace?.name = value case "AL": currentAirspace?.floor = AirspaceAltitude(value) case "AH": currentAirspace?.ceiling = AirspaceAltitude(value) case "AT": guard let coord = coordinate(from: value) else { assertionFailure("got unparseable label coordinate: \(line)") currentAirspace = nil continue } if currentAirspace?.labelCoordinates == nil { currentAirspace?.labelCoordinates = [CLLocationCoordinate2D]() } currentAirspace?.labelCoordinates?.append(coord) case "V": if value.hasPrefix("X") { guard let eqRange = value.range(of: "=") else { assertionFailure("malformed X"); return nil } state.x = coordinate(from: value.suffix(from: eqRange.upperBound)) } else if value.hasPrefix("D") { guard let signRange = value.rangeOfCharacter(from: .plusMinus) else { assertionFailure("malformed direction line: \(line)") currentAirspace = nil continue } let sign = value[signRange.lowerBound ..< signRange.upperBound] state.clockwise = (sign == "+") } else { continue } case "DC": //* DC radius; draw a circle (center taken from the previous V X=... record, radius in nm guard let center = state.x else { assertionFailure("got circle but got no center: \(line)") currentAirspace = nil continue } guard let radiusInNM = Double(value) else { assertionFailure("got circle but got no radius: \(line)") currentAirspace = nil continue } let radius = Measurement(value: radiusInNM, unit: UnitLength.nauticalMiles).converted(to: .meters) currentAirspace?.polygonCoordinates.append(contentsOf: polygonArc(around: center, radius: radius.value, from: 0.0, to: 0.0, clockwise: true)) case "DP": //* DP coordinate; add polygon pointC guard let coord = coordinate(from: value) else { print("got unparseable polygon point: \(line)") continue } currentAirspace?.polygonCoordinates.append(coord) case "DA": //* DA radius, angleStart, angleEnd; add an arc, angles in degrees, radius in nm (set center using V X=...) guard let center = state.x else { assertionFailure("got an arc but got no center: \(line)") currentAirspace = nil continue } let numbers = value.components(separatedBy: ",").map { $0.trimmingCharacters(in: .whitespaces) }.compactMap(Double.init) var start = 0.0 var end = 0.0 guard numbers.count > 0 else { assertionFailure("Need 3 parameters for DA arc but got \(numbers.count): \(line)") currentAirspace = nil continue } if numbers.count > 1 { start = numbers[1] } if numbers.count > 2 { end = numbers[2] } let radius = Measurement(value: numbers[0], unit: UnitLength.nauticalMiles).converted(to: .meters) let coords = polygonArc(around: center, radius: radius.value, from: start, to: end, clockwise: state.clockwise) currentAirspace?.polygonCoordinates.append(contentsOf: coords) case "DB": //* DB coordinate1, coordinate2; add an arc, from coordinate1 to coordinate2 (set center using V X=...) guard let center = state.x else { assertionFailure("got an arc but got no center: \(line)") currentAirspace = nil continue } let fromToCoords = value.components(separatedBy: ",").compactMap(coordinate) guard fromToCoords.count == 2 else { assertionFailure("Need 2 points for DB arc but got \(fromToCoords.count): \(line)") currentAirspace = nil continue } let from = fromToCoords.first! let to = fromToCoords.last! let dist1 = center.distance(from: from) let dist2 = center.distance(from: to) let radius = 0.5 * (dist1 + dist2) let fromDeg = center.bearing(to: from) let toDeg = center.bearing(to: to) let coords = polygonArc(around: center, radius: radius, from: fromDeg, to: toDeg, clockwise: state.clockwise) currentAirspace?.polygonCoordinates.append(contentsOf: coords) default: continue } } currentAirspace.flatMap { $0.validAirspace.flatMap { asp in guard asp.floor < .fl(100) else { return } var list = airSpaces[asp.airspaceClass] ?? [Airspace]() list.append(asp) airSpaces[asp.airspaceClass] = list } } return airSpaces } public func airSpaces(from openAirString: String, sourceIdentifier: String?) -> [Airspace]? { guard let airspaces = self.airSpacesByClass(from: openAirString, sourceIdentifier: sourceIdentifier) else { return nil } let flatAirspaces = airspaces.reduce([Airspace]()) { (res, tuple) -> [Airspace] in return res + tuple.value } return flatAirspaces.isEmpty ? nil : flatAirspaces } public func airSpacesByClass(withContentsOf url: URL) -> AirspacesByClassDictionary? { var openAirString = "" var encoding: String.Encoding = .init(rawValue: 0) do { openAirString = try String(contentsOf: url, usedEncoding: &encoding) } catch { do { openAirString = try String(contentsOf: url, encoding: .ascii) } catch { assertionFailure("failed opening \(url): \(error.localizedDescription)") return nil } } return self.airSpacesByClass(from: openAirString, sourceIdentifier: url.lastPathComponent) } public func airSpaces(withContentsOf url: URL) -> [Airspace]? { var openAirString = "" var encoding: String.Encoding = .init(rawValue: 0) do { openAirString = try String(contentsOf: url, usedEncoding: &encoding) } catch { do { openAirString = try String(contentsOf: url, encoding: .ascii) } catch { assertionFailure("failed opening \(url): \(error.localizedDescription)") return nil } } return self.airSpaces(from: openAirString, sourceIdentifier: url.lastPathComponent) } private func coordinate<S: StringProtocol>(from string: S) -> CLLocationCoordinate2D? { let upperCased = string.uppercased() let scanner = Scanner(string: upperCased) guard let latString = scanner.scanUpToCharacters(from: .northSouth), latString != upperCased else { print("could not find N/S in coordinate string") return nil } let latComponents = latString.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: ":") guard var latitude = latComponents.degree, latitude <= 90.0 else { assertionFailure("invalid latitude for \"\(string)\"; \(dump(latComponents))") return nil } guard let latHemisphere = scanner.scanCharacters(from: .northSouth) else { assertionFailure("could not find N/S hemisphere") return nil } if latHemisphere == "S" { latitude = -1.0 * latitude } guard let lngString = scanner.scanUpToCharacters(from: .eastWest) else { assertionFailure("could not find EW in coordinate string") return nil } guard let lngHemisphere = scanner.scanCharacters(from: .eastWest) else { assertionFailure("could not find E/W hemisphere") return nil } let lngComponents = lngString.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: ":") guard var longitude = lngComponents.degree, longitude <= 180.0 else { assertionFailure("invalid longitude for \"\(string)\"; \(dump(lngComponents))") return nil } if lngHemisphere == "W" { longitude = -1.0 * longitude } return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } private func polygonArc(around center: CLLocationCoordinate2D, radius: CLLocationDistance, from: CLLocationDegrees, to: CLLocationDegrees, clockwise: Bool) -> [CLLocationCoordinate2D] { let resolution = 5.0 let sign = clockwise ? 1.0 : -1.0 let start = from var end = (to == from) ? from+360.0 : to if (clockwise && to < from ) { end += 360.0 } if (!clockwise && to > from) { end -= 360.0 } let range = fabs(end - start) let count = ceil(range/resolution) let step = sign*range/count let coordinates = stride(from: start, through: end, by: step) .map { degree in center.coordinate(at: radius, direction: degree) } return coordinates } private struct ParserState { var x: CLLocationCoordinate2D? var clockwise = true } private struct AirspaceInProgress { var `class`: AirspaceClass? = nil var ceiling: AirspaceAltitude? = nil var floor: AirspaceAltitude? = nil var name: String? = nil var labelCoordinates: [CLLocationCoordinate2D]? = nil var polygonCoordinates = [CLLocationCoordinate2D]() var sourceIdentifier: String? = nil var validAirspace: Airspace? { guard let klass = self.class, let ceiling = self.ceiling, let floor = self.floor, let name = self.name, polygonCoordinates.count > 2, let first = polygonCoordinates.first, let last = polygonCoordinates.last else { return nil } var coords = polygonCoordinates if first != last { coords.append(first) } var a = Airspace(name: name, class: klass, floor: floor, ceiling: ceiling, polygon: coords, labelCoordinates: self.labelCoordinates) a.sourceIdentifier = sourceIdentifier return a } } } extension AirspaceAltitude { var geoJsonAltitude: Int { switch self { case .surface: return 0 case .fl(let level): let flMeasure = Measurement(value: 100.0*Double(level), unit: UnitLength.feet).converted(to: .meters) let intMeters = Int(flMeasure.value.rounded()) return intMeters case .agl(let alt): let intAGL = Int(alt.converted(to: .meters).value) return intAGL case .msl(let alt): let intMSL = Int(alt.converted(to: .meters).value) return intMSL } } } extension Airspace: GeoJsonEncodable { public var geoJsonString: String? { let coordinatesArray: [[Double]] = (self.polygonCoordinates+[self.polygonCoordinates[0]]).reversed().map { [$0.longitude, $0.latitude] } let dict: NSDictionary = [ "type": "Feature", "properties": [ "name": self.name as NSString, "type": self.airspaceClass.rawValue as NSString, "floor": self.floor.geoJsonAltitude, "ceiling": self.ceiling.geoJsonAltitude, ] as NSDictionary, "geometry": [ "type": "Polygon" as NSString, "coordinates": [ coordinatesArray as NSArray ] as NSArray, ] as NSDictionary ] guard JSONSerialization.isValidJSONObject(dict) else { return nil } guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else { return nil } return String(data: data, encoding: .utf8) } }
37.639839
193
0.567809
1c129652e82255f230a078ccd3700921151aae91
13,658
// // PreviewViewController.swift // HttpCapture // // Created by liuyihao1216 on 16/8/24. // Copyright © 2016年 liuyihao1216. All rights reserved. // import Foundation import UIKit class PreviewCell: UITableViewCell { var nameLabel = UILabel() var dateLabel = UILabel() var mimeLabel = UILabel() var statusLabel = UILabel() override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.backgroundColor = UIColor.whiteColor() nameLabel.frame = CGRectMake(10, 5, self.width - 10 - 75 - 44 , 65) nameLabel.backgroundColor = UIColor.fromRGBA(0xffffffff) nameLabel.textAlignment = NSTextAlignment.Left nameLabel.numberOfLines = 3 nameLabel.font = UIFont.systemFontOfSize(15) nameLabel.textColor = UIColor.fromRGBA(0x222222ff) self.contentView.addSubview(nameLabel) mimeLabel.frame = CGRectMake(10, nameLabel.top + nameLabel.height + 2, 180 , 13) mimeLabel.backgroundColor = UIColor.fromRGBA(0xffffffff) mimeLabel.textAlignment = NSTextAlignment.Left mimeLabel.font = UIFont.systemFontOfSize(13) mimeLabel.textColor = UIColor.fromRGBA(0xe11644ff) self.contentView.addSubview(mimeLabel) statusLabel.frame = CGRectMake(mimeLabel.left + mimeLabel.width + 10, nameLabel.top + nameLabel.height + 2, 120 , 13) statusLabel.backgroundColor = UIColor.fromRGBA(0xffffffff) statusLabel.textAlignment = NSTextAlignment.Left statusLabel.font = UIFont.systemFontOfSize(13) statusLabel.textColor = UIColor.fromRGBA(0x22ee77ff) self.contentView.addSubview(statusLabel) dateLabel.frame = CGRectMake(self.width - 10 - nameLabel.width , 5 , 75 , 65) dateLabel.backgroundColor = UIColor.fromRGBA(0xffffffff) dateLabel.numberOfLines = 3 dateLabel.textAlignment = NSTextAlignment.Right dateLabel.font = UIFont.systemFontOfSize(13) dateLabel.textColor = UIColor.fromRGBA(0x333333ff) self.contentView.addSubview(dateLabel) } override func layoutSubviews() { super.layoutSubviews() nameLabel.frame = CGRectMake(10, 5, self.width - 10 - 75 - 44 , 65) dateLabel.frame = CGRectMake(10 + nameLabel.width + 10 , 5 , 75 , 65) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } @objc class PreviewViewController: CaptureBaseViewController,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate { var tableView = UITableView() var searchBar = UISearchBar() var tempEntries:NSMutableArray? var beginFilter = false; @objc var entries = NSMutableArray() { didSet{ self.searchBar.hidden = false; self.reload() } } func configTempEntries() { tempEntries = NSMutableArray(array: entries) } override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false tableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Grouped) tableView.delegate = self; tableView.dataSource = self; tableView.tableFooterView = UIView(frame:CGRectZero) tableView.registerClass(PreviewCell.self, forCellReuseIdentifier: "CellID") self.view.addSubview(tableView) rightBtn.frame = CGRectMake(0, 0, 44, 44) rightBtn.contentHorizontalAlignment = .Right rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 15) rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 15) rightBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0) rightBtn.setTitleColor(UIColor.fromRGBA(0x666666ff), forState: UIControlState.Normal) rightBtn.contentMode = UIViewContentMode.ScaleAspectFit; rightBtn.setTitle("清除", forState: UIControlState.Normal) rightBtn.addTarget(self, action: "rightButtonClick:", forControlEvents: UIControlEvents.TouchUpInside) let rightItem = UIBarButtonItem(customView: rightBtn) self.navigationItem.rightBarButtonItem = rightItem searchBar = UISearchBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 44)) let img:UIImage = UIImage.imageWithColor(UIColor.fromRGBA(0xf2f2f2ff), size: CGSizeMake(WXDevice.width, 64)) searchBar.setBackgroundImage(img, forBarPosition: .Any, barMetrics: UIBarMetrics.Default) searchBar.barTintColor = UIColor.fromRGBA(0xf2f2f2ff) searchBar.delegate = self searchBar.placeholder = "过滤" self.tableView.tableHeaderView = searchBar self.navigationItem.title = "预览" } func scrollToTop(){ self.tableView.scrollRectToVisible(CGRectMake(0, 0, self.view.width, 10), animated: true) } func scrollViewDidScroll(scrollView: UIScrollView) { self.searchBar.resignFirstResponder() if scrollView.contentOffset.y > 150 { if let btn = self.view.scrollToTopButton where btn.alpha == 0 { self.view.bringSubviewToFront(btn) UIView.animateWithDuration(0.2, animations: { () -> Void in self.view.scrollToTopButton?.alpha = 1 }) } } else{ if self.view.scrollToTopButton?.alpha == 1 { UIView.animateWithDuration(0.2, animations: { () -> Void in self.view.scrollToTopButton?.alpha = 0 }, completion: { (finished) -> Void in }) } } } func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool { let button = searchBar.cancelButton let attri = NSAttributedString(string: "取消", attributes: [NSFontAttributeName:UIFont.systemFontOfSize(16.0),NSForegroundColorAttributeName:UIColor.customTextColor()]) button?.setAttributedTitle(attri, forState: UIControlState.Normal) return true } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if let temp = tempEntries { if searchText.length == 0 { self.entries = NSMutableArray(array:temp) } else{ let newar = temp.filter({ (entry) -> Bool in if let _entry = entry as? Entry { if (_entry.request.url.lowercaseString as NSString).rangeOfString(searchText.lowercaseString).length > 0 || (_entry.response.content.mimeType.lowercaseString as NSString).rangeOfString(searchText.lowercaseString).length > 0 || ("\(_entry.response.status)".lowercaseString as NSString).rangeOfString(searchText.lowercaseString).length > 0 { return true; } } return false }) self.entries = NSMutableArray(array: newar) } } } func searchBarCancelButtonClicked(searchBar: UISearchBar) { if let temp = tempEntries { self.entries = NSMutableArray(array: temp) } self.searchBar.resignFirstResponder() self.searchBar.text = "" self.searchBar.setShowsCancelButton(false, animated: false) } func searchBarSearchButtonClicked(searchBar: UISearchBar) { self.searchBar.setShowsCancelButton(false, animated: false) self.searchBar.resignFirstResponder() } override func useDefaultBackButton() -> Bool{ return true; } override func rightButtonClick(item: UIButton) { HttpCaptureManager.shareInstance().removeEntries(self.entries) { (rs) in self.entries.removeAllObjects() self.tempEntries?.removeAllObjects() self.tempEntries = nil self.tableView.reloadData() self.searchBar.text = "" self.searchBar.hidden = true; } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() tableView.frame = CGRectMake(0, 64, self.view.width, self.view.height - 64) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("CellID") as? PreviewCell if cell == nil { cell = PreviewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CellID") } if self.entries.count > indexPath.row { if let entry = self.entries[indexPath.row] as? Entry { cell?.nameLabel.text = entry.request.url cell?.dateLabel.text = entry.getStartTime() cell?.mimeLabel.text = "类型:" + entry.response.content.mimeType cell?.statusLabel.text = "状态码:\(entry.response.status)" } } cell?.nameLabel.lineBreakMode = NSLineBreakMode.ByTruncatingTail; cell?.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell! } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 93; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return self.entries.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if let entry = self.entries.objectAtIndex(indexPath.row) as? Entry { let captureVC = CaptureDetailViewController() captureVC.entry = entry self.navigationController?.pushViewController(captureVC, animated: true) } } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.1 } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // if let key = entries.allKeys[section] as? String // { // let header = UIButton(frame:CGRectMake(0,0,self.view.width,30)) // header.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left // header.setTitle(" \(key)", forState: UIControlState.Normal) // header.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) // header.titleLabel?.font = UIFont.boldSystemFontOfSize(14) // header.titleLabel?.numberOfLines = 1 // header.tag = 1000 + section // header.addTarget(self, action: "exposure:", forControlEvents: UIControlEvents.TouchUpInside) // return header // } return nil; } func exposure(btn:UIButton){ // if searchBar.isFirstResponder() // { // return; // } // let tag = btn.tag - 1000 // if tag >= 0 && self.entries.allKeys.count > tag // { // if let key = self.entries.allKeys[tag] as? String,let ar = self.entries.objectForKey(key) as? Array<Entry> // { // if ar.count > 0 // { // self.entries.setObject(Array<Entry>(), forKey: key) // } // else{ // if let temp = self.tempEntries,let values = temp.objectForKey(key) as? Array<Entry> // { // var arr = Array<Entry>() // arr.appendContentsOf(values) // self.entries.setObject(arr, forKey: key) // } // } // DPrintln("btn = \(tag);\(ar.count);") // for (key,value) in entries { // DPrintln("key value =\(key as! String);\((value as! Array<Entry>).count)") // } // self.tableView.reloadSections(NSIndexSet(index: tag), withRowAnimation: UITableViewRowAnimation.Automatic) // DPrintln("btn2 = \(tag);\(ar.count)") // } // } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.1; } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { self.onSetMarginOrInset(true, fSetOffset: 10, cell: cell) } func onSetMarginOrInset(bSetTable:Bool,fSetOffset:CGFloat,cell:UITableViewCell){ if #available(iOS 8.0, *) { tableView.layoutMargins = UIEdgeInsetsZero cell.preservesSuperviewLayoutMargins = false cell.layoutMargins = UIEdgeInsetsMake(0, fSetOffset, 0, 0) } tableView.separatorInset = UIEdgeInsetsZero cell.separatorInset = UIEdgeInsetsMake(0, fSetOffset, 0, 0) } func reload() { self.tableView.reloadData() } deinit { self.searchBar.resignFirstResponder() } }
35.201031
250
0.612169
1d234760324f0f8b0e486a1d9a48980fdfc020a7
8,071
// // CookBook.swift // Intelligent refrigerator // // Created by cjj on 2021/3/2. // 详情跳转有bug import SwiftUI import SwiftUIX struct CookBook: View { @Environment(\.presentationMode) var presentationMode @State var isshowvideo=false @State var isshowvideo1=false @State var isshowvideo2=false @State var isshowvideo3=false @State var navtoCookBook=false var body: some View { VStack { // 头部菜单 ZStack { HStack { Button(action: { presentationMode.wrappedValue.dismiss() }, label: { Image(systemName: "house") .imageScale(.large) }) Spacer() } Text("菜谱") .font(.title2) }.foregroundColor(.gray) .padding(.horizontal) ScrollView(.vertical, showsIndicators: false) { VStack(spacing: 30.0) { ZStack { // 搜素 RoundedRectangle(cornerRadius: 25.0) .fill(Color.Neumorphic.main) .softOuterShadow() .frame(width: UIScreen.main.bounds.width - 40, height: 40, alignment: .center) HStack { Image(systemName: "magnifyingglass").foregroundColor(.white) Text("请输入食材").foregroundColor(.gray) Spacer() } .padding(.all, 30) } // 菜谱 Recommend(isshow1: $isshowvideo1, isshow2: $isshowvideo2, isshow3: $isshowvideo3) BanderCook(isshowVideo: $isshowvideo, title: "收藏菜谱", sizebig: 150, sizesmall: 60) BanderCook(isshowVideo: $isshowvideo, title: "热门菜谱", sizebig: 150, sizesmall: 60) } } .navigationBarTitle(Text("菜谱"), displayMode: .inline) .navigationBarItems(trailing: Button(action: {}, label: { Image(systemName: "") .imageScale(.large) })) } .background(Color.Neumorphic.main.ignoresSafeArea()) .navigationBarHidden(true) .navigationBarBackButtonHidden(true) } } struct CookCircleButton: View { @Binding var isshow: Bool var image="cc" var title="接听" var size: CGFloat=100 var body: some View { VStack(alignment: .center) { Button(action: { self.isshow.toggle() }, label: { VStack { Image(image) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 150, height: 150, alignment: .center) .clipShape(Circle()) }.frame(width: size, height: size, alignment: .center) }).softButtonStyle(Circle()) Text(title).foregroundColor(.gray) } } } //普通菜谱卡片 struct BanderCook: View { @Binding var isshowVideo: Bool var image="perch" var icon="" var title="今日菜谱" var sizebig: CGFloat=250 var sizesmall: CGFloat=250 var body: some View { VStack { HStack { Text("\(title)") .font(.title) Spacer() Image(systemName: "\(icon)") } .padding(.horizontal, 25) ScrollView(.horizontal, showsIndicators: false) { HStack { ForEach(0..<5, id: \.self) { _ in NavigationLink( destination: CoolVideo(), isActive: $isshowVideo, label: { Button(action: { self.isshowVideo.toggle() }, label: { ZStack { Rectangle() .fill(Color.Neumorphic.main) .frame(width: sizebig, height: sizebig, alignment: .center) .softOuterShadow() Image("\(image)") .resizable() .frame(width: sizesmall, height: sizesmall, alignment: .center) .aspectRatio(contentMode: .fill) } }) }) } .padding() } }.padding() } } } //分栏菜谱 struct Recommend: View { @Binding var isshow1: Bool @Binding var isshow2: Bool @Binding var isshow3: Bool @State var index=0 // 位移的下标 var body: some View { VStack { HStack(spacing: 20.0) { Text("今日菜谱") .font(.title) .padding(.trailing, 30.0) ZStack { Capsule().fill(Color.gray).frame(width: 80, height: 40, alignment: .center).offset(x: CGFloat(100 * index), y: 0) Button(action: { self.index=0 }, label: { Text("早餐") }).frame(width: 80, height: 40, alignment: .center) } Button(action: { self.index=1 }, label: { Text("午餐") }).frame(width: 80, height: 40, alignment: .center) Button(action: { self.index=2 }, label: { Text("晚餐") }).frame(width: 80, height: 40, alignment: .center) Spacer() } .padding(.horizontal, 20.0) .foregroundColor(.white) TabView(selection: $index) { RecommendBander(isshowVideo: $isshow1).tag(0) RecommendBander(isshowVideo: $isshow2,image:"").tag(1) RecommendBander(isshowVideo: $isshow3,image:"").tag(2) }.tabViewStyle(PageTabViewStyle(indexDisplayMode: PageTabViewStyle.IndexDisplayMode.never)).frame(width: UIScreen.main.bounds.width, height: 250, alignment: .center) } .frame(width: UIScreen.main.bounds.width, height: 300, alignment: .center) } } //分栏菜谱卡片 struct RecommendBander: View { @Binding var isshowVideo: Bool var image="perch" var sizebig: CGFloat=230 var sizesmall: CGFloat=230 var body: some View { HStack { ForEach(0..<3, id: \.self) { _ in NavigationLink( destination: CoolVideo(), isActive: $isshowVideo, label: { Button(action: { self.isshowVideo=true }, label: { ZStack { Rectangle() .fill(Color.Neumorphic.main) .frame(width: sizebig, height: sizebig, alignment: .center) .softOuterShadow() Image("\(image)") .resizable() .frame(width: sizesmall, height: sizesmall, alignment: .center) .aspectRatio(contentMode: .fill) } }) }) } .padding(.horizontal) } } } struct CookBook_Previews: PreviewProvider { static var previews: some View { CookBook().preferredColorScheme(.dark) } }
36.355856
177
0.430926
182c70a91b72835ab488f30b2755f512be5847b4
249
// // AlertModuleConfig.swift // Demo // // Created by Cheslau Bachko. // Copyright © 2020-present demo. All rights reserved. // struct AlertModuleInputConfig { let title: String? let message: String? // TODO: Place your code here }
19.153846
55
0.674699
cc9b59374d076f412270412d44a0c09c4e7c4eb1
1,644
/** * 项目销售信息-销售明细-sectionHeader */ import UIKit //点击事件回调 typealias SellInfoDetialClickBlock = () -> Void class THJGProjectSellInfoDetailSectionHeaderView: UITableViewHeaderFooterView { @IBOutlet weak var blockNameLabel: UILabel! @IBOutlet weak var allLabel: UILabel! @IBOutlet weak var soldLabel: UILabel! @IBOutlet weak var rateLabel: UILabel! @IBOutlet weak var arrowBtn: UIButton! var clickBlock: SellInfoDetialClickBlock! func reloadData(_ bean: ProjectSellDetailHandledBean, clickBlock: @escaping SellInfoDetialClickBlock) { //赋值内容 blockNameLabel.text = bean.headerBean.proBlock allLabel.text = bean.headerBean.proSellable != 0 ? "\(bean.headerBean.proSellable)" : "-" soldLabel.text = bean.headerBean.proSold != 0 ? "\(bean.headerBean.proSold)" : "-" if bean.headerBean.proRecBack == 0, bean.headerBean.proDealTotal == 0 { rateLabel.text = "-" } else { rateLabel.text = "\(DQSUtils.showNumWithComma(num: DQSUtils.showDoubleNum(sourceDouble: bean.headerBean.proRecBack/10000, floatNum: 2, showStyle: .showStyleNoZero)))/\(DQSUtils.showNumWithComma(num: DQSUtils.showDoubleNum(sourceDouble: bean.headerBean.proDealTotal/10000, floatNum: 2, showStyle: .showStyleNoZero)))" } //调整箭头 arrowBtn.isSelected = bean.isSelected.0 //赋值点击事件 self.clickBlock = clickBlock } } //MARK: - METHODS extension THJGProjectSellInfoDetailSectionHeaderView { @IBAction func headerDidClicked(_ sender: UIButton) { clickBlock() } }
33.55102
328
0.675791
d9e60fa0b9470e4651fe9ed73433fd4b52ef7b58
11,132
// // GeneratorTests.swift // OneTimePassword // // Copyright (c) 2014-2017 Matt Rubin and the OneTimePassword authors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import XCTest import OneTimePassword class GeneratorTests: XCTestCase { func testInit() { // Create a generator let factor = OneTimePassword.Generator.Factor.counter(111) let secret = "12345678901234567890".data(using: String.Encoding.ascii)! let algorithm = Generator.Algorithm.sha256 let digits = 8 let generator = Generator( factor: factor, secret: secret, algorithm: algorithm, digits: digits ) XCTAssertEqual(generator?.factor, factor) XCTAssertEqual(generator?.secret, secret) XCTAssertEqual(generator?.algorithm, algorithm) XCTAssertEqual(generator?.digits, digits) // Create another generator let other_factor = OneTimePassword.Generator.Factor.timer(period: 123) let other_secret = "09876543210987654321".data(using: String.Encoding.ascii)! let other_algorithm = Generator.Algorithm.sha512 let other_digits = 7 let other_generator = Generator( factor: other_factor, secret: other_secret, algorithm: other_algorithm, digits: other_digits ) XCTAssertEqual(other_generator?.factor, other_factor) XCTAssertEqual(other_generator?.secret, other_secret) XCTAssertEqual(other_generator?.algorithm, other_algorithm) XCTAssertEqual(other_generator?.digits, other_digits) // Ensure the generators are different XCTAssertNotEqual(generator?.factor, other_generator?.factor) XCTAssertNotEqual(generator?.secret, other_generator?.secret) XCTAssertNotEqual(generator?.algorithm, other_generator?.algorithm) XCTAssertNotEqual(generator?.digits, other_generator?.digits) } func testCounter() { let factors: [(TimeInterval, TimeInterval, UInt64)] = [ // swiftlint:disable comma (100, 30, 3), (10000, 30, 333), (1000000, 30, 33333), (100000000, 60, 1666666), (10000000000, 90, 111111111), // swiftlint:enable comma ] for (timeSinceEpoch, period, count) in factors { let time = Date(timeIntervalSince1970: timeSinceEpoch) let timer = Generator.Factor.timer(period: period) let counter = Generator.Factor.counter(count) let secret = "12345678901234567890".data(using: String.Encoding.ascii)! let hotp = Generator(factor: counter, secret: secret, algorithm: .sha1, digits: 6) .flatMap { try? $0.password(at: time) } let totp = Generator(factor: timer, secret: secret, algorithm: .sha1, digits: 6) .flatMap { try? $0.password(at: time) } XCTAssertEqual(hotp, totp, "TOTP with \(timer) should match HOTP with counter \(counter) at time \(time).") } } func testValidation() { let digitTests: [(Int, Bool)] = [ (-6, false), (0, false), (1, false), (5, false), (6, true), (7, true), (8, true), (9, false), (10, false), ] let periodTests: [(TimeInterval, Bool)] = [ (-30, false), (0, false), (1, true), (30, true), (300, true), (301, true), ] for (digits, digitsAreValid) in digitTests { let generator = Generator( factor: .counter(0), secret: Data(), algorithm: .sha1, digits: digits ) // If the digits are invalid, password generation should throw an error let generatorIsValid = digitsAreValid if generatorIsValid { XCTAssertNotNil(generator) } else { XCTAssertNil(generator) } for (period, periodIsValid) in periodTests { let generator = Generator( factor: .timer(period: period), secret: Data(), algorithm: .sha1, digits: digits ) // If the digits or period are invalid, password generation should throw an error let generatorIsValid = digitsAreValid && periodIsValid if generatorIsValid { XCTAssertNotNil(generator) } else { XCTAssertNil(generator) } } } } func testPasswordAtInvalidTime() { guard let generator = Generator( factor: .timer(period: 30), secret: Data(), algorithm: .sha1, digits: 6 ) else { XCTFail("Failed to initialize a Generator.") return } let badTime = Date(timeIntervalSince1970: -100) do { _ = try generator.password(at: badTime) } catch Generator.Error.invalidTime { // This is the expected type of error return } catch { XCTFail("passwordAtTime(\(badTime)) threw an unexpected type of error: \(error))") return } XCTFail("passwordAtTime(\(badTime)) should throw an error)") } func testPasswordWithInvalidPeriod() { // It should not be possible to try to get a password from a generator with an invalid period, because the // generator initializer should fail when given an invalid period. let generator = Generator(factor: .timer(period: 0), secret: Data(), algorithm: .sha1, digits: 8) XCTAssertNil(generator) } func testPasswordWithInvalidDigits() { // It should not be possible to try to get a password from a generator with an invalid digit count, because the // generator initializer should fail when given an invalid digit count. let generator = Generator(factor: .timer(period: 30), secret: Data(), algorithm: .sha1, digits: 3) XCTAssertNil(generator) } // The values in this test are found in Appendix D of the HOTP RFC // https://tools.ietf.org/html/rfc4226#appendix-D func testHOTPRFCValues() { let secret = "12345678901234567890".data(using: String.Encoding.ascii)! let expectedValues: [UInt64: String] = [ 0: "755224", 1: "287082", 2: "359152", 3: "969429", 4: "338314", 5: "254676", 6: "287922", 7: "162583", 8: "399871", 9: "520489", ] for (counter, expectedPassword) in expectedValues { let generator = Generator(factor: .counter(counter), secret: secret, algorithm: .sha1, digits: 6) let time = Date(timeIntervalSince1970: 0) let password = generator.flatMap { try? $0.password(at: time) } XCTAssertEqual(password, expectedPassword, "The generator did not produce the expected OTP.") } } // The values in this test are found in Appendix B of the TOTP RFC // https://tools.ietf.org/html/rfc6238#appendix-B func testTOTPRFCValues() { let secretKeys: [Generator.Algorithm: String] = [ .sha1: "12345678901234567890", .sha256: "12345678901234567890123456789012", .sha512: "1234567890123456789012345678901234567890123456789012345678901234", ] let timesSinceEpoch: [TimeInterval] = [59, 1111111109, 1111111111, 1234567890, 2000000000, 20000000000] let expectedValues: [Generator.Algorithm: [String]] = [ .sha1: ["94287082", "07081804", "14050471", "89005924", "69279037", "65353130"], .sha256: ["46119246", "68084774", "67062674", "91819424", "90698825", "77737706"], .sha512: ["90693936", "25091201", "99943326", "93441116", "38618901", "47863826"], ] for (algorithm, secretKey) in secretKeys { let secret = secretKey.data(using: String.Encoding.ascii)! let generator = Generator(factor: .timer(period: 30), secret: secret, algorithm: algorithm, digits: 8) for (timeSinceEpoch, expectedPassword) in zip(timesSinceEpoch, expectedValues[algorithm]!) { let time = Date(timeIntervalSince1970: timeSinceEpoch) let password = generator.flatMap { try? $0.password(at: time) } XCTAssertEqual(password, expectedPassword, "Incorrect result for \(algorithm) at \(timeSinceEpoch)") } } } // From Google Authenticator for iOS // https://code.google.com/p/google-authenticator/source/browse/mobile/ios/Classes/TOTPGeneratorTest.m func testTOTPGoogleValues() { let secret = "12345678901234567890".data(using: String.Encoding.ascii)! let timesSinceEpoch: [TimeInterval] = [1111111111, 1234567890, 2000000000] let expectedValues: [Generator.Algorithm: [String]] = [ .sha1: ["050471", "005924", "279037"], .sha256: ["584430", "829826", "428693"], .sha512: ["380122", "671578", "464532"], ] for (algorithm, expectedPasswords) in expectedValues { let generator = Generator(factor: .timer(period: 30), secret: secret, algorithm: algorithm, digits: 6) for (timeSinceEpoch, expectedPassword) in zip(timesSinceEpoch, expectedPasswords) { let time = Date(timeIntervalSince1970: timeSinceEpoch) let password = generator.flatMap { try? $0.password(at: time) } XCTAssertEqual(password, expectedPassword, "Incorrect result for \(algorithm) at \(timeSinceEpoch)") } } } }
41.22963
119
0.59549
de5c4382364c5c3ba585604e0a470a9cd90967de
1,202
// RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | FileCheck %s // CHECK-LABEL: @_specialize(Int, Float) // CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U) @_specialize(Int, Float) func specializeThis<T, U>(_ t: T, u: U) {} public protocol PP { associatedtype PElt } public protocol QQ { associatedtype QElt } public struct RR : PP { public typealias PElt = Float } public struct SS : QQ { public typealias QElt = Int } public struct GG<T : PP> {} // CHECK-LABEL: public class CC<T : PP> { // CHECK-NEXT: @_specialize(RR, SS) // CHECK-NEXT: @inline(never) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) public class CC<T : PP> { @inline(never) @_specialize(RR, SS) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) { return (u, g) } } // CHECK-LABEL: sil hidden [_specialize <Int, Float>] @_TF15specialize_attr14specializeThisu0_rFTx1uq__T_ : $@convention(thin) <T, U> (@in T, @in U) -> () { // CHECK-LABEL: sil [noinline] [_specialize <RR, Float, SS, Int>] @_TFC15specialize_attr2CC3foouRd__S_2QQrfTqd__1gGVS_2GGx__Tqd__GS2_x__ : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
31.631579
247
0.652246
2f7f2dfe4f79219b5f1669c0ba3abaa2e3db6cb5
1,256
// // Copyright (c) 2019-Present Umobi - https://github.com/umobi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit public protocol UIViewCreator: ViewCreator { associatedtype View: UIView }
43.310345
80
0.764331
f9c6fda3a716299b9a577423dcca32c036cabffc
1,165
// // Copyright (c) Vatsal Manot // import Swift import SwiftUI #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) public struct CocoaHostingControllerContent<Content: View>: View { weak var parent: CocoaController? var content: Content var presentationCoordinator: CocoaPresentationCoordinator? init( parent: CocoaController?, content: Content, presentationCoordinator: CocoaPresentationCoordinator? ) { self.content = content self.presentationCoordinator = presentationCoordinator } public var body: some View { content .environment(\.cocoaPresentationCoordinator, presentationCoordinator) .environment(\.dynamicViewPresenter, presentationCoordinator) .environment(\.presentationManager, CocoaPresentationMode(coordinator: presentationCoordinator)) .onPreferenceChange(ViewDescription.PreferenceKey.self, perform: { if let parent = self.parent as? CocoaHostingController<EnvironmentalAnyView> { parent.subviewDescriptions = $0 } }) } } #endif
29.125
108
0.670386
769646b6678669875de618ae87a580ab1d6360bf
3,597
// // OffscreenRemovalComponent.swift // OctopusKit // // Created by [email protected] on 2017/10/16. // Copyright © 2020 Invading Octopus. Licensed under Apache License v2.0 (see LICENSE.txt) // import GameplayKit /// Removes the entity's `NodeComponent` node, and optionally the entity as well, from its parent after it has been outside the viewable area of its scene for the specified duration. /// /// **Dependencies:** `NodeComponent` public final class OffscreenRemovalComponent: OKComponent, RequiresUpdatesPerFrame { public override var requiredComponents: [GKComponent.Type]? { [NodeComponent.self] } public fileprivate(set) var secondsElapsedSinceOffscreen: TimeInterval = 0 /// The duration in seconds to wait after the node has moved off screen, before removing it. @GKInspectable public var removalDelay: TimeInterval = 0 @GKInspectable public var shouldRemoveEntityOnNodeRemoval: Bool = true public override init() { super.init() } public init(removalDelay: TimeInterval = 0, shouldRemoveEntityOnNodeRemoval: Bool = true) { self.removalDelay = removalDelay self.shouldRemoveEntityOnNodeRemoval = shouldRemoveEntityOnNodeRemoval super.init() } public required init?(coder aDecoder: NSCoder) { guard let unarchiver = aDecoder as? NSKeyedUnarchiver else { fatalError("init(coder:) has not been implemented for \(aDecoder)") } super.init(coder: aDecoder) if let removalDelay = unarchiver.decodeObject(forKey: "removalDelay") as? Double { self.removalDelay = removalDelay } if let shouldRemoveEntityOnNodeRemoval = unarchiver.decodeObject(forKey: "shouldRemoveEntityOnNodeRemoval") as? Bool { self.shouldRemoveEntityOnNodeRemoval = shouldRemoveEntityOnNodeRemoval } } public override func update(deltaTime seconds: TimeInterval) { // TODO: Confirm that the scene intersection check works without a camera and with arbitrary scene/screen sizes. super.update(deltaTime: seconds) guard let node = super.entityNode, // We want either NodeComponent or GKSKNodeComponent (in case the Scene Editor was used)) let scene = node.scene else { return } // If the node is within the scene or its camera, if (scene.camera != nil && scene.camera!.contains(node)) || (scene.camera == nil && scene.intersects(node)) { secondsElapsedSinceOffscreen = 0 // Reset the timer. } else { // But if the node is "offscreen" (not in its scene's area), // for a duration longer than the specified delay, // remove it. secondsElapsedSinceOffscreen += seconds if secondsElapsedSinceOffscreen >= removalDelay { node.removeFromParent() if shouldRemoveEntityOnNodeRemoval, let entity = self.entity, let entityDelegate = (self.entity as? OKEntity)?.delegate { entityDelegate.entityDidRequestRemoval(entity) } } } } /// Resets the removal countdown to `0` even if the node is offscren. public func resetTimer() { secondsElapsedSinceOffscreen = 0 } }
36.333333
182
0.619405
fe674c534b3b2b04fbc3c2d265b60c99cbea540d
5,730
// // MetalChartView.swift // ScheduleChart // // Created by Alexander Graschenkov on 06/04/2019. // Copyright © 2019 Alex the Best. All rights reserved. // import UIKit import MetalKit struct PointIn { var point: vector_float2 } struct GlobalParameters { var lineWidth: Float var halfViewport: (Float, Float) var transform: matrix_float3x3 var linePointsCount: UInt32 var chartCount: UInt32 } extension matrix_float3x3 { static let identity = matrix_from_rows(float3(1, 0, 0), float3(0, 1, 0), float3(0, 0, 1)) } //private extension MTLDevice { // func makeBuffer<T>(arr: inout [T], options: MTLResourceOptions = []) -> MTLBuffer? { // return makeBuffer(bytes: arr, length: MemoryLayout<T>.stride * arr.count, options: options) // } //} class MetalChartView: MTKView { private(set) var maxChartDataCount: Int = 0 private(set) var maxChartItemsCount: Int = 0 var isSelectionChart: Bool = false private var commandQueue: MTLCommandQueue! = nil private var library: MTLLibrary! = nil private var pipelineDescriptor = MTLRenderPipelineDescriptor() private var pipelineState : MTLRenderPipelineState! = nil private var levelDisplay: LineLevelDisplay? var display: BaseDisplay! var globalParams: GlobalParameters! var customScale: [Float] = [] let mutex = Mutex() override init(frame frameRect: CGRect, device: MTLDevice?) { let d = device ?? MTLCreateSystemDefaultDevice()! super.init(frame: frameRect, device: d) configureWithDevice(d) } required init(coder: NSCoder) { super.init(coder: coder) configureWithDevice(MTLCreateSystemDefaultDevice()!) } func updateChartType(chartType: ChartType) { switch chartType { case .line: if !(display is LineDisplay) { display = LineDisplay(view: self, device: device!, reuseBuffers: display?.buffers) } case .stacked: if !(display is StackFillDisplay) { display = StackFillDisplay(view: self, device: device!, reuseBuffers: display?.buffers) } case .percentage: if !(display is PercentFillDisplay) { display = PercentFillDisplay(view: self, device: device!, reuseBuffers: display?.buffers) } } display?.setupBuffers(maxChartDataCount: maxChartDataCount, maxChartItemsCount: maxChartItemsCount) } private func configureWithDevice(_ device : MTLDevice) { // display = LineDisplay(view: self, device: device) // display = StackFillDisplay(view: self, device: device) // display = PercentFillDisplay(view: self, device: device) let viewport = (Float(drawableSize.width) / 2.0, Float(drawableSize.height) / 2.0) globalParams = GlobalParameters(lineWidth: 4, halfViewport: viewport, transform: .identity, linePointsCount: 0, chartCount: 0) clearColor = MTLClearColor.init(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) autoresizingMask = [.flexibleWidth, .flexibleHeight] framebufferOnly = true colorPixelFormat = .bgra8Unorm // Run with 4rx MSAA: sampleCount = 4 preferredFramesPerSecond = 60 isPaused = true enableSetNeedsDisplay = true self.device = device } override var device: MTLDevice! { didSet { super.device = device commandQueue = (self.device?.makeCommandQueue())! } } func setupBuffers(maxChartDataCount: Int, maxChartItemsCount: Int) { self.maxChartDataCount = maxChartDataCount self.maxChartItemsCount = maxChartItemsCount globalParams.linePointsCount = UInt32(maxChartItemsCount) display?.setupBuffers(maxChartDataCount: maxChartDataCount, maxChartItemsCount: maxChartItemsCount) } func setupWithData(data: ChartGroupData) { mutex.lock() defer { mutex.unlock() } updateChartType(chartType: data.type) display.data = data } func updateLevels(levels: [LineAlpha]) { if levelDisplay == nil { levelDisplay = LineLevelDisplay(view: self, device: device, reuseBuffers: nil) } levelDisplay?.update(lines: levels) } override func draw(_ rect: CGRect) { // if chartDataCount == 0 { return } globalParams.halfViewport = (Float(drawableSize.width) / 2.0, Float(drawableSize.height) / 2.0) display.prepareDisplay() mutex.lock() guard let commandBuffer = commandQueue!.makeCommandBuffer(), let renderPassDescriptor = self.currentRenderPassDescriptor, let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { mutex.unlock() return } commandBuffer.addCompletedHandler { (_) in self.mutex.unlock() } let drawLineFirst = display.groupMode == .none if drawLineFirst { levelDisplay?.display(renderEncoder: renderEncoder) } display.display(renderEncoder: renderEncoder) if !drawLineFirst { levelDisplay?.display(renderEncoder: renderEncoder) } renderEncoder.endEncoding() commandBuffer.present(self.currentDrawable!) commandBuffer.commit() } }
32.556818
134
0.614136
72adc36919738fc727f9c454b2647a389dbb46c6
952
// // NetworkObserver.swift // RAD // // Copyright 2018 NPR // // 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 /// A protocol which may be implemented to observe the network requests /// executed by framework. public protocol NetworkObserver: AnyObject { /// Callback for each performed network request. /// /// - Parameter request: The request. func didBeginExecutionOfUrlRequest(_ request: URLRequest) }
34
94
0.735294
765fb103dbf52b64477390997d72d86036381a2b
175
// // PromiseFailure.swift // ShallowPromises // // Created by JuanJo on 19/04/20. // import Foundation public enum PromiseFailure: Error { case cancelled, timeout }
13.461538
35
0.697143
e007c07c212ee40d93b7deb4a974b41744ab9892
508
// // Animator.swift // DDMvvm // // Created by Dao Duy Duong on 9/26/18. // import UIKit open class Animator: NSObject, UIViewControllerAnimatedTransitioning { public var isPresenting = false open func transitionDuration( using transitionContext: UIViewControllerContextTransitioning? ) -> TimeInterval { return 1 } open func animateTransition( using transitionContext: UIViewControllerContextTransitioning ) { fatalError("Subclassess have to impleted this method") } }
20.32
70
0.740157
f5d1c1326acf21650c6af1a9a1ff8b674f64ddb4
439
// // ModalViewController.swift // Example // // Created by DianQK on 16/3/24. // Copyright © 2016年 com.transitiontreasury. All rights reserved. // import UIKit import TransitionTreasury class ModalViewController: UIViewController { weak var modalDelegate: ModalViewControllerDelegate? @IBAction func dissmissClick(_ sender: UIButton) { modalDelegate?.modalViewControllerDismiss(callbackData: nil) } }
20.904762
68
0.731207
0ab0db7594bd06f05217d0309f4563bfc313b4b9
2,622
import Foundation import DivvunSpell protocol BannerManagerDelegate: class { var hasFullAccess: Bool { get } func bannerDidProvideInput(banner: Banner, inputText: String) } final class BannerManager { weak var delegate: BannerManagerDelegate? private let view: UIView private let spellBanner: SpellBanner private let updateInProgressBanner: UpdateBanner private let spellerAvailableBanner: SpellerAvailableBanner private var currentBanner: Banner? private let ipc = IPC() init(view: UIView, theme: ThemeType, delegate: BannerManagerDelegate?) { self.view = view self.delegate = delegate spellBanner = SpellBanner(theme: theme) updateInProgressBanner = UpdateBanner(theme: theme) spellerAvailableBanner = SpellerAvailableBanner(theme: theme) ipc.delegate = self spellBanner.delegate = self print(KeyboardSettings.groupContainerURL) updateBanner() } private func updateBanner() { guard let currentSpellerId = Bundle.main.spellerPackageKey else { print("BannerMananger: Couldn't get current speller id") // There is no speller for this keyboard. Show empty spell banner. presentBanner(spellBanner) return } if ipc.isDownloading(id: currentSpellerId.absoluteString) { presentBanner(updateInProgressBanner) } else if spellBanner.spellerNeedsInstall { presentBanner(spellerAvailableBanner) } else { presentBanner(spellBanner) } } private func presentBanner(_ banner: Banner) { if type(of: banner) == type(of: currentBanner) { return } currentBanner?.view.removeFromSuperview() view.addSubview(banner.view) banner.view.fill(superview: self.view) currentBanner = banner } public func propagateTextInputUpdateToBanners(newContext: CursorContext) { spellBanner.updateSuggestions(newContext) } public func updateTheme(_ theme: ThemeType) { spellBanner.updateTheme(theme) } } extension BannerManager: IPCDelegate { func didBeginDownloading(id: String) { } func didFinishInstalling(id: String) { spellBanner.loadSpeller() updateBanner() } } extension BannerManager: SpellBannerDelegate { var hasFullAccess: Bool { return delegate?.hasFullAccess ?? false } func didSelectSuggestion(banner: SpellBanner, suggestion: String) { delegate?.bannerDidProvideInput(banner: banner, inputText: suggestion) } }
29.460674
78
0.679634
e5727a7b0992ae8bb5ed0da8d70eb52505f43eba
2,642
import Foundation import Vapor import JSON import HTTP import VaporMySQL import TfbCommon let drop = Droplet() try drop.addProvider(VaporMySQL.Provider.self) // All test types require `Server` and `Date` HTTP response headers. // Vapor has standard middleware that adds `Date` header. // We use custom middleware that adds `Server` header. drop.middleware.append(ServerMiddleware()) // Normally we would add preparation for Fluent Models. // `drop.preparations.append(World.self)` etc. // During preparation Fluent creates `fluent` table to track migrations. // But TFB environment does not grant user rights to create tables. // So we just configure our Models with correct database. World.database = drop.database Fortune.database = drop.database // Test type 1: JSON serialization drop.get("json") { req in return try JSON(node: Message("Hello, World!")) } // Test type 2: Single database query drop.get("db") { _ in let worldId = WorldMeta.randomId() return try World.find(worldId)?.makeJSON() ?? JSON(node: .null) } // Test type 3: Multiple database queries drop.get("queries") { req in let queries = queriesParam(for: req) let ids = (1...queries).map({ _ in WorldMeta.randomId() }) let worlds = try ids.flatMap { try World.find($0)?.makeJSON() } return JSON(worlds) } // Test type 4: Fortunes /// Locale for string comparison to workaround https://bugs.swift.org/browse/SR-530 private let posixLocale = Locale(identifier: "en_US_POSIX") drop.get("fortunes") { _ in var fortunes = try Fortune.all() let additional = Fortune(id: 0, message: "Additional fortune added at request time.") fortunes.insert(additional, at: 0) fortunes.sort(by: { lhs, rhs -> Bool in return lhs.message.compare(rhs.message, locale: posixLocale) == .orderedAscending }) let nodes = try fortunes.map { try $0.makeNode() } return try drop.view.make("fortune", ["fortunes": Node(nodes)]) } // Test type 5: Database updates drop.get("updates") { req in let queries = queriesParam(for: req) let ids = (1...queries).map({ _ in WorldMeta.randomId() }) var worlds = try ids.flatMap { try World.find($0) } worlds.forEach { $0.randomNumber = WorldMeta.randomRandomNumber() } worlds = try worlds.flatMap { world in var modifiedWorld = world try modifiedWorld.save() return modifiedWorld } let updatedWorlds = try worlds.flatMap { try $0.makeJSON() } return JSON(updatedWorlds) } // Test type 6: Plaintext let helloWorldBuffer = "Hello, World!".utf8.array drop.get("plaintext") { req in return Response(headers: ["Content-Type": "text/plain; charset=utf-8"], body: helloWorldBuffer) } drop.run()
32.617284
97
0.717638
6af900d3afd1e2e0bf412fd4642c5625b0d69a3a
1,903
// // SocialMediasAlert.swift // ManGO // // Created by Priba on 7/1/19. // Copyright © 2019 Priba. All rights reserved. // import UIKit protocol SocialMediaAlertDelegate: class { func facebookAction() func instagramAction() func snapchatAction() } class SocialMediasAlert: UIViewController { var delegate: SocialMediaAlertDelegate? @IBOutlet weak var titleLbl: UILabel! @IBOutlet weak var messageLbl: UILabel! @IBOutlet weak var contactUs: UIButton! @IBOutlet weak var facebookBtn: UIButton! @IBOutlet weak var instagramBtn: UIButton! @IBOutlet weak var snapchatBtn: UIButton! @IBOutlet weak var backView: UIView! override func viewDidLoad() { backView.layer.cornerRadius = 10 facebookBtn.setHalfCornerRadius() instagramBtn.setHalfCornerRadius() snapchatBtn.setHalfCornerRadius() let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark)) visualEffectView.alpha = 0.6 visualEffectView.frame = self.view.bounds visualEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] visualEffectView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backgroundViewTapped))) self.view.insertSubview(visualEffectView, at: 0) titleLbl.setupTitleForKey(key: "contact_us") messageLbl.setupTitleForKey(key: "contact_us_description") contactUs.setupTitleForKey(key: "send_us_message") } @objc func backgroundViewTapped(sender:AnyObject) { dismiss(animated: true, completion: nil) } @IBAction func fbAction(_ sender: Any) { delegate?.facebookAction() } @IBAction func igAction(_ sender: Any) { delegate?.instagramAction() } @IBAction func snapAction(_ sender: Any) { delegate?.snapchatAction() } }
29.734375
124
0.689963
e6f12b3f75eea8c3343b888cc9d482fed2db6b3d
6,603
import XCTest @testable import DarkSky class DarkSkyTests: XCTestCase { static let secretKey = "" override func setUp() { super.setUp() 🌩.secretKey = DarkSkyTests.secretKey } func testFetchingWeather() { var fetchResult: 🌩.Result? let e = expectation(description: "testFetchingWeather") 🌩.weather(latitude: 28.608276, longitude: -80.604097) { result in fetchResult = result e.fulfill() } waitForExpectations(timeout: 60) switch fetchResult! { case .failure(let error): XCTFail("Request failed with error: \(error)") case .success(_): break } } func testExcludableCurrently() { do { let weather = try performWeatherRequest(exclude: [.currently]) XCTAssertNil(weather.currently) XCTAssertNotNil(weather.minutely) XCTAssertNotNil(weather.hourly) XCTAssertNotNil(weather.daily) XCTAssertNotNil(weather.flags) } catch { XCTFail("Failed with error: \(error)") } } func testExcludableMinutely() { do { let weather = try performWeatherRequest(exclude: [.minutely]) XCTAssertNotNil(weather.currently) XCTAssertNil(weather.minutely) XCTAssertNotNil(weather.hourly) XCTAssertNotNil(weather.daily) XCTAssertNotNil(weather.flags) } catch { XCTFail("Failed with error: \(error)") } } func testExcludableHourly() { do { let weather = try performWeatherRequest(exclude: [.hourly]) XCTAssertNotNil(weather.currently) XCTAssertNotNil(weather.minutely) XCTAssertNil(weather.hourly) XCTAssertNotNil(weather.daily) XCTAssertNotNil(weather.flags) } catch { XCTFail("Failed with error: \(error)") } } func testExcludableDaily() { do { let weather = try performWeatherRequest(exclude: [.daily]) XCTAssertNotNil(weather.currently) XCTAssertNotNil(weather.minutely) XCTAssertNotNil(weather.hourly) XCTAssertNil(weather.daily) XCTAssertNotNil(weather.flags) } catch { XCTFail("Failed with error: \(error)") } } func testExcludableAlerts() { do { let weather = try performWeatherRequest(exclude: [.alerts]) XCTAssertNotNil(weather.currently) XCTAssertNotNil(weather.minutely) XCTAssertNotNil(weather.hourly) XCTAssertNotNil(weather.daily) XCTAssertNil(weather.alerts) XCTAssertNotNil(weather.flags) } catch { XCTFail("Failed with error: \(error)") } } func testExcludableFlags() { do { let weather = try performWeatherRequest(exclude: [.flags]) XCTAssertNotNil(weather.currently) XCTAssertNotNil(weather.minutely) XCTAssertNotNil(weather.hourly) XCTAssertNotNil(weather.daily) XCTAssertNil(weather.flags) } catch { XCTFail("Failed with error: \(error)") } } func testExcludableEverything() { do { let weather = try performWeatherRequest(exclude: [.currently, .minutely, .hourly, .daily, .alerts, .flags]) XCTAssertNil(weather.currently) XCTAssertNil(weather.minutely) XCTAssertNil(weather.hourly) XCTAssertNil(weather.daily) XCTAssertNil(weather.alerts) XCTAssertNil(weather.flags) } catch { XCTFail("Failed with error: \(error)") } } func testExcludableNothing() { do { let weather = try performWeatherRequest(exclude: []) XCTAssertNotNil(weather.currently) XCTAssertNotNil(weather.minutely) XCTAssertNotNil(weather.hourly) XCTAssertNotNil(weather.daily) XCTAssertNotNil(weather.flags) } catch { XCTFail("Failed with error: \(error)") } } enum FetchError: Error { case timeout case requestFailed(Error) } func performWeatherRequest(latitude: Double = 28.608276, longitude: Double = -80.604097, exclude: Set<WeatherRequest.ExcludableResponseData>? = nil) throws -> Weather { var fetchResult: 🌩.Result? let e = expectation(description: "Weather Request") 🌩.weather(latitude: latitude, longitude: longitude, exclude: exclude) { result in fetchResult = result e.fulfill() } waitForExpectations(timeout: 60.0) guard let result = fetchResult else { throw FetchError.timeout } switch result { case .failure(let error): throw FetchError.requestFailed(error) case .success(let weather): return weather } } func testAllCities() { City.allCases.forEach { do { let weather = try performWeatherRequest(latitude: $0.coordinates.latitude, longitude: $0.coordinates.longitude) XCTAssertNotNil(weather.currently, "\($0): currently is nil") XCTAssertNotNil(weather.minutely, "\($0): minutely is nil") XCTAssertNotNil(weather.hourly, "\($0): hourly is nil") XCTAssertNotNil(weather.daily, "\($0): daily is nil") XCTAssertNotNil(weather.flags, "\($0): flags is nil") } catch { XCTFail("City: \($0) failed with error: \(error)") } } } func testRandomly() { for _ in 1...50 { let latitude = Double.random(in: -90...90) let longitude = Double.random(in: -180...180) do { print("Fetching weather at random latitude: \(latitude) longitude: \(longitude)") let weather = try performWeatherRequest(latitude: latitude, longitude: longitude) XCTAssertNotNil(weather.currently) XCTAssertNotNil(weather.hourly) XCTAssertNotNil(weather.daily) XCTAssertNotNil(weather.flags) } catch { XCTFail("Failed with error: \(error)") } } } }
32.527094
172
0.5602
29170e55df4f5654d9c79e814e691fd91dd220cf
430
// // Fish+CoreDataProperties.swift // Splash // // Created by Ben Lapidus on 12/1/19. // Copyright © 2019 Ben Lapidus. All rights reserved. // // import Foundation import CoreData extension Fish { @nonobjc public class func fetchRequest() -> NSFetchRequest<Fish> { return NSFetchRequest<Fish>(entityName: "Fish") } @NSManaged public var dateCaught: NSDate? @NSManaged public var name: String? }
17.916667
71
0.683721
f7e115984ec0e40b827ee21a6fb99aa9a7a35bf7
1,139
// // Gallery+Convenience.swift // Gallery // // Created by Isaac Lyons on 1/12/21. // import CoreData import WebDAV //MARK: Account extension Account { convenience init(username: String?, baseURL: String?, context moc: NSManagedObjectContext) { self.init(context: moc) self.id = UUID() self.username = username self.baseURL = baseURL } } //MARK: Album extension Album { func imagesFetchRequest() -> NSFetchRequest<ImageItem> { let fetchRequest: NSFetchRequest<ImageItem> = ImageItem.fetchRequest() fetchRequest.predicate = NSPredicate(format: "album == %@", self) fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \ImageItem.index, ascending: true)] return fetchRequest } } //MARK: ImageItem extension ImageItem { convenience init(file: WebDAVFile, index: Int16, account: Account, album: Album, context moc: NSManagedObjectContext) { self.init(context: moc) self.imagePath = file.path self.imageSize = Int64(file.size) self.index = index self.account = account self.album = album } }
25.311111
123
0.662862
ef1f3dd1f97d4aea5c1e33d7348b3a7ef3bbf79e
9,354
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/noppoMan/aws-sdk-swift/blob/master/Sources/CodeGenerator/main.swift. DO NOT EDIT. import Foundation import AWSSDKSwiftCore import NIO /** */ public struct Transfer { let client: AWSClient public init(accessKeyId: String? = nil, secretAccessKey: String? = nil, region: AWSSDKSwiftCore.Region? = nil, endpoint: String? = nil) { self.client = AWSClient( accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, region: region, amzTarget: "TransferService", service: "transfer", serviceProtocol: ServiceProtocol(type: .json, version: ServiceProtocol.Version(major: 1, minor: 1)), apiVersion: "2018-11-05", endpoint: endpoint, middlewares: [], possibleErrorTypes: [TransferErrorType.self] ) } /// Instantiates an autoscaling virtual server based on Secure File Transfer Protocol (SFTP) in AWS. The call returns the ServerId property assigned by the service to the newly created server. Reference this ServerId property when you make updates to your server, or work with users. The response returns the ServerId value for the newly created server. public func createServer(_ input: CreateServerRequest) throws -> Future<CreateServerResponse> { return try client.send(operation: "CreateServer", path: "/", httpMethod: "POST", input: input) } /// Adds a user and associate them with an existing Secure File Transfer Protocol (SFTP) server. Using parameters for CreateUser, you can specify the user name, set the home directory, store the user's public key, and assign the user's AWS Identity and Access Management (IAM) role. You can also optionally add a scope-down policy, and assign metadata with tags that can be used to group and search for users. The response returns the UserName and ServerId values of the new user for that server. public func createUser(_ input: CreateUserRequest) throws -> Future<CreateUserResponse> { return try client.send(operation: "CreateUser", path: "/", httpMethod: "POST", input: input) } /// Deletes the Secure File Transfer Protocol (SFTP) server that you specify. If you used SERVICE_MANAGED as your IdentityProviderType, you need to delete all users associated with this server before deleting the server itself No response returns from this call. @discardableResult public func deleteServer(_ input: DeleteServerRequest) throws -> Future<Void> { return try client.send(operation: "DeleteServer", path: "/", httpMethod: "POST", input: input) } /// Deletes a user's Secure Shell (SSH) public key. No response is returned from this call. @discardableResult public func deleteSshPublicKey(_ input: DeleteSshPublicKeyRequest) throws -> Future<Void> { return try client.send(operation: "DeleteSshPublicKey", path: "/", httpMethod: "POST", input: input) } /// Deletes the user belonging to the server you specify. No response returns from this call. When you delete a user from a server, the user's information is lost. @discardableResult public func deleteUser(_ input: DeleteUserRequest) throws -> Future<Void> { return try client.send(operation: "DeleteUser", path: "/", httpMethod: "POST", input: input) } /// Describes the server that you specify by passing the ServerId parameter. The response contains a description of the server's properties. public func describeServer(_ input: DescribeServerRequest) throws -> Future<DescribeServerResponse> { return try client.send(operation: "DescribeServer", path: "/", httpMethod: "POST", input: input) } /// Describes the user assigned to a specific server, as identified by its ServerId property. The response from this call returns the properties of the user associated with the ServerId value that was specified. public func describeUser(_ input: DescribeUserRequest) throws -> Future<DescribeUserResponse> { return try client.send(operation: "DescribeUser", path: "/", httpMethod: "POST", input: input) } /// Adds a Secure Shell (SSH) public key to a user account identified by a UserName value assigned to a specific server, identified by ServerId. The response returns the UserName value, the ServerId value, and the name of the SshPublicKeyId. public func importSshPublicKey(_ input: ImportSshPublicKeyRequest) throws -> Future<ImportSshPublicKeyResponse> { return try client.send(operation: "ImportSshPublicKey", path: "/", httpMethod: "POST", input: input) } /// Lists the Secure File Transfer Protocol (SFTP) servers that are associated with your AWS account. public func listServers(_ input: ListServersRequest) throws -> Future<ListServersResponse> { return try client.send(operation: "ListServers", path: "/", httpMethod: "POST", input: input) } /// Lists all of the tags associated with the Amazon Resource Number (ARN) you specify. The resource can be a user, server, or role. public func listTagsForResource(_ input: ListTagsForResourceRequest) throws -> Future<ListTagsForResourceResponse> { return try client.send(operation: "ListTagsForResource", path: "/", httpMethod: "POST", input: input) } /// Lists the users for the server that you specify by passing the ServerId parameter. public func listUsers(_ input: ListUsersRequest) throws -> Future<ListUsersResponse> { return try client.send(operation: "ListUsers", path: "/", httpMethod: "POST", input: input) } /// Changes the state of a Secure File Transfer Protocol (SFTP) server from OFFLINE to ONLINE. It has no impact on an SFTP server that is already ONLINE. An ONLINE server can accept and process file transfer jobs. The state of STARTING indicates that the server is in an intermediate state, either not fully able to respond, or not fully online. The values of START_FAILED can indicate an error condition. No response is returned from this call. @discardableResult public func startServer(_ input: StartServerRequest) throws -> Future<Void> { return try client.send(operation: "StartServer", path: "/", httpMethod: "POST", input: input) } /// Changes the state of an SFTP server from ONLINE to OFFLINE. An OFFLINE server cannot accept and process file transfer jobs. Information tied to your server such as server and user properties are not affected by stopping your server. Stopping a server will not reduce or impact your Secure File Transfer Protocol (SFTP) endpoint billing. The states of STOPPING indicates that the server is in an intermediate state, either not fully able to respond, or not fully offline. The values of STOP_FAILED can indicate an error condition. No response is returned from this call. @discardableResult public func stopServer(_ input: StopServerRequest) throws -> Future<Void> { return try client.send(operation: "StopServer", path: "/", httpMethod: "POST", input: input) } /// Attaches a key-value pair to a resource, as identified by its Amazon Resource Name (ARN). Resources are users, servers, roles, and other entities. There is no response returned from this call. @discardableResult public func tagResource(_ input: TagResourceRequest) throws -> Future<Void> { return try client.send(operation: "TagResource", path: "/", httpMethod: "POST", input: input) } /// If the IdentityProviderType of the server is API_Gateway, tests whether your API Gateway is set up successfully. We highly recommend that you call this method to test your authentication method as soon as you create your server. By doing so, you can troubleshoot issues with the API Gateway integration to ensure that your users can successfully use the service. public func testIdentityProvider(_ input: TestIdentityProviderRequest) throws -> Future<TestIdentityProviderResponse> { return try client.send(operation: "TestIdentityProvider", path: "/", httpMethod: "POST", input: input) } /// Detaches a key-value pair from a resource, as identified by its Amazon Resource Name (ARN). Resources are users, servers, roles, and other entities. No response is returned from this call. @discardableResult public func untagResource(_ input: UntagResourceRequest) throws -> Future<Void> { return try client.send(operation: "UntagResource", path: "/", httpMethod: "POST", input: input) } /// Updates the server properties after that server has been created. The UpdateServer call returns the ServerId of the Secure File Transfer Protocol (SFTP) server you updated. public func updateServer(_ input: UpdateServerRequest) throws -> Future<UpdateServerResponse> { return try client.send(operation: "UpdateServer", path: "/", httpMethod: "POST", input: input) } /// Assigns new properties to a user. Parameters you pass modify any or all of the following: the home directory, role, and policy for the UserName and ServerId you specify. The response returns the ServerId and the UserName for the updated user. public func updateUser(_ input: UpdateUserRequest) throws -> Future<UpdateUserResponse> { return try client.send(operation: "UpdateUser", path: "/", httpMethod: "POST", input: input) } }
77.95
578
0.735407
39852684f80aae05356da56ab95a2823e571ba27
14,490
// // HTTPClientSpec.swift // TalkyTests // // Created by Martin Klöpfel on 01.08.18. // Copyright © 2018 Martin Klöpfel. All rights reserved. // import Quick import Nimble @testable import Talky fileprivate struct Test: Codable, Equatable { let testString: String } fileprivate let testApiBaseURL = URL(string: "https://api.test.com")! fileprivate let testURL = URL(string: "Test", relativeTo: testApiBaseURL)! fileprivate let errorURL = URL(string: "Error", relativeTo: testApiBaseURL)! fileprivate let testParameter = Test(testString: "TestParameter") fileprivate let testBody = Test(testString: "TestBody") fileprivate let testError = Test(testString: "Error") class HTTPClientSpec: QuickSpec { private let sessionMock: URLSessionMock = { let mock = URLSessionMock() let requestBuilder = RequestBuilder() // setup success results for test url // GET mock.setResult(result: ((try! JSONEncoder().encode(testBody), HTTPURLResponse(url: testURL, statusCode: 200, httpVersion: nil, headerFields: nil), nil)), for: try! requestBuilder.buildURLRequest(url: testURL, headerFields: [.accept: "application/json;charset=UTF-8"])) // POST mock.setResult(result: ((try! JSONEncoder().encode(testBody), HTTPURLResponse(url: testURL, statusCode: 200, httpVersion: nil, headerFields: nil), nil)), for: try! requestBuilder.buildURLRequest(url: testURL, method: .post, body: testParameter, headerFields: [.accept: "application/json;charset=UTF-8"])) // PUT mock.setResult(result: ((try! JSONEncoder().encode(testBody), HTTPURLResponse(url: testURL, statusCode: 200, httpVersion: nil, headerFields: nil), nil)), for: try! requestBuilder.buildURLRequest(url: testURL, method: .put, body: testParameter, headerFields: [.accept: "application/json;charset=UTF-8"])) // DELETE mock.setResult(result: ((try! JSONEncoder().encode(testBody), HTTPURLResponse(url: testURL, statusCode: 200, httpVersion: nil, headerFields: nil), nil)), for: try! requestBuilder.buildURLRequest(url: testURL, method: .delete, headerFields: [.accept: "application/json;charset=UTF-8"])) // setup error results for test url // GET mock.setResult(result: ((try! JSONEncoder().encode(testError), HTTPURLResponse(url: errorURL, statusCode: 404, httpVersion: nil, headerFields: nil), nil)), for: try! requestBuilder.buildURLRequest(url: errorURL, headerFields: [.accept: "application/json;charset=UTF-8"])) // POST mock.setResult(result: ((try! JSONEncoder().encode(testError), HTTPURLResponse(url: errorURL, statusCode: 400, httpVersion: nil, headerFields: nil), nil)), for: try! requestBuilder.buildURLRequest(url: errorURL, method: .post, body: testParameter, headerFields: [.accept: "application/json;charset=UTF-8"])) // PUT mock.setResult(result: ((try! JSONEncoder().encode(testError), HTTPURLResponse(url: errorURL, statusCode: 400, httpVersion: nil, headerFields: nil), nil)), for: try! requestBuilder.buildURLRequest(url: errorURL, method: .put, body: testParameter, headerFields: [.accept: "application/json;charset=UTF-8"])) // DELETE mock.setResult(result: ((try! JSONEncoder().encode(testError), HTTPURLResponse(url: errorURL, statusCode: 404, httpVersion: nil, headerFields: nil), nil)), for: try! requestBuilder.buildURLRequest(url: errorURL, method: .delete, headerFields: [.accept: "application/json;charset=UTF-8"])) return mock }() private lazy var httpClient: HTTPClient = { let httpClient = HTTPClient(session: sessionMock) return httpClient }() override func spec() { describe("HTTPClient") { /////////////////////////////////////////////////////////////// //MARK: - success cases /////////////////////////////////////////////////////////////// context("When I run a GET request on \"\(testURL.absoluteString)\".") { it("should succeed and respond with \(testBody).") { waitUntil(timeout: 10) { done in self.httpClient.GET(url: testURL, completionWithOptinalResults: { (_, body: Test?, _: RequestError<AnyDecodable>?) in expect(body) == testBody done() }) } } } context("When I run a POST request on \"\(testURL.absoluteString)\" with \"\(testParameter)\" as body.") { it("should succeed and respond with \(testBody).") { waitUntil(timeout: 10) { done in self.httpClient.POST(url: testURL, parameters: testParameter, completionWithOptinalResults: { (_, body: Test?, _: RequestError<AnyDecodable>?) in expect(body) == testBody done() }) } } } context("When I run a PUT request on \"\(testURL.absoluteString)\" with \"\(testParameter)\" as body.") { it("should succeed and respond with \(testBody).") { waitUntil(timeout: 10) { done in self.httpClient.PUT(url: testURL, parameters: testParameter, completionWithOptinalResults: { (_, body: Test?, _: RequestError<AnyDecodable>?) in expect(body) == testBody done() }) } } } context("When I run a DELETE request on \"\(testURL.absoluteString)\".") { it("should succeed and respond with \(testBody).") { waitUntil(timeout: 10) { done in self.httpClient.DELETE(url: testURL, completionWithOptinalResults: { (_, body: Test?, _: RequestError<AnyDecodable>?) in expect(body) == testBody done() }) } } } /////////////////////////////////////////////////////////////// //MARK: - error cases /////////////////////////////////////////////////////////////// context("When I run a GET request on \"\(errorURL.absoluteString)\".") { it("should fail with status code '404' and \(testError) response.") { waitUntil(timeout: 10) { done in self.httpClient.GET(url: errorURL, completionWithOptinalResults: { (_, _: AnyDecodable?, error: RequestError<Test>?) in switch error { case .some(.apiError(let urlResponse, let errorBody)): expect(urlResponse.statusCode) == 404 expect(errorBody) == testError default: fail("") // TODO: nice error message } done() }) } } } context("When I run a POST request on \"\(errorURL.absoluteString)\" with \"\(testParameter)\" as body.") { it("should fail with status code '400' and \(testError) response.") { waitUntil(timeout: 10) { done in self.httpClient.POST(url: errorURL, parameters: testParameter, completionWithOptinalResults: { (_, _: AnyDecodable?, error: RequestError<Test>?) in switch error { case .some(.apiError(let urlResponse, let errorBody)): expect(urlResponse.statusCode) == 400 expect(errorBody) == testError default: fail("") // TODO: nice error message } done() }) } } } context("When I run a PUT request on \"\(errorURL.absoluteString)\" with \"\(testParameter)\" as body.") { it("should fail with status code '400' and \(testError) response.") { waitUntil(timeout: 10) { done in self.httpClient.PUT(url: errorURL, parameters: testParameter, completionWithOptinalResults: { (_, _: AnyDecodable?, error: RequestError<Test>?) in switch error { case .some(.apiError(let urlResponse, let errorBody)): expect(urlResponse.statusCode) == 400 expect(errorBody) == testError default: fail("") // TODO: nice error message } done() }) } } } context("When I run a DELETE request on \"\(errorURL.absoluteString)\".") { it("should fail with status code '404' and \(testError) response.") { waitUntil(timeout: 10) { done in self.httpClient.DELETE(url: errorURL, completionWithOptinalResults: { (_, _: AnyDecodable?, error: RequestError<Test>?) in switch error { case .some(.apiError(let urlResponse, let errorBody)): expect(urlResponse.statusCode) == 404 expect(errorBody) == testError default: fail("") // TODO: nice error message } done() }) } } } /////////////////////////////////////////////////////////////// //MARK: - /////////////////////////////////////////////////////////////// } } } extension HTTPClient { //TODO: move it, move it ... public func GET<ResponseBody: Decodable, ErrorResponse: Decodable>(url: URL, headerFields: [HTTPHeaderField : String]? = nil, completionWithOptinalResults: @escaping ((HTTPURLResponse?, ResponseBody?, RequestError<ErrorResponse>?) -> Void)) { self.GET(url: url, headerFields: headerFields) { (result: RequestResult<ResponseBody, ErrorResponse>) in switch result { case let .success(response, body): completionWithOptinalResults(response, body, nil) case .failure(let error): completionWithOptinalResults(nil, nil, error) } } } public func POST<Parameters: Encodable, ResponseBody: Decodable, ErrorResponse: Decodable>(url: URL, parameters: Parameters? = nil, headerFields: [HTTPHeaderField : String]? = nil, completionWithOptinalResults: @escaping ((HTTPURLResponse?, ResponseBody?, RequestError<ErrorResponse>?) -> Void)) { self.POST(url: url, parameters: parameters, headerFields: headerFields) { (result: RequestResult<ResponseBody, ErrorResponse>) in switch result { case let .success(response, body): completionWithOptinalResults(response, body, nil) case .failure(let error): completionWithOptinalResults(nil, nil, error) } } } public func PUT<Parameters: Encodable, ResponseBody: Decodable, ErrorResponse: Decodable>(url: URL, parameters: Parameters? = nil, headerFields: [HTTPHeaderField : String]? = nil, completionWithOptinalResults: @escaping ((HTTPURLResponse?, ResponseBody?, RequestError<ErrorResponse>?) -> Void)) { self.PUT(url: url, parameters: parameters, headerFields: headerFields) { (result: RequestResult<ResponseBody, ErrorResponse>) in switch result { case let .success(response, body): completionWithOptinalResults(response, body, nil) case .failure(let error): completionWithOptinalResults(nil, nil, error) } } } public func DELETE<ResponseBody: Decodable, ErrorResponse: Decodable>(url: URL, headerFields: [HTTPHeaderField : String]? = nil, completionWithOptinalResults: @escaping ((HTTPURLResponse?, ResponseBody?, RequestError<ErrorResponse>?) -> Void)) { self.DELETE(url: url, headerFields: headerFields) { (result: RequestResult<ResponseBody, ErrorResponse>) in switch result { case let .success(response, body): completionWithOptinalResults(response, body, nil) case .failure(let error): completionWithOptinalResults(nil, nil, error) } } } }
53.076923
187
0.483851
e55027c55bbf20e057ca0db75d9abac1cb1e5084
1,004
// // TableViewController+NavigationBar.swift // iOS_WB // // Created by Alpha on 2017/7/28. // Copyright © 2017年 STT. All rights reserved. // import UIKit extension UIViewController{ // 分类 func setNavigationControllerBarLeftItemAndRightItem(leftImageName:String?,rightImageName:String?) { guard leftImageName != nil else { return } navigationItem.leftBarButtonItem = UIBarButtonItem.init(imageName: leftImageName!, target: self, action: #selector(navigationLeftButtonAction(leftItem:))) guard rightImageName != nil else { return } navigationItem.rightBarButtonItem = UIBarButtonItem.init(imageName: rightImageName!, target: self, action: #selector(navigationRightButtonAction(rightItem:))) } @objc func navigationLeftButtonAction(leftItem:UIButton){ } @objc func navigationRightButtonAction(rightItem:UIButton){ } }
25.1
166
0.653386
9cd151116af9b2a5156e9b65f9a2ea9f0f43ac89
5,153
// // DownloadPhotos.swift // Virtual Tourist // // Created by Christopher Weaver on 8/18/16. // Copyright © 2016 Christopher Weaver. All rights reserved. // import Foundation import CoreData import UIKit class DownloadPhotos { let delegate = UIApplication.shared.delegate as! AppDelegate func flickrURLFromParameters(_ parameters: [String:AnyObject]) -> URL { var components = URLComponents() components.scheme = Constants.Flickr.APIScheme components.host = Constants.Flickr.APIHost components.path = Constants.Flickr.APIPath components.queryItems = [URLQueryItem]() for (key, value) in parameters { let queryItem = URLQueryItem(name: key, value: "\(value)") components.queryItems!.append(queryItem) } return components.url! } func displayImageFromFlickr(_ pin: Pin, completionHandlerForPhotos: @escaping (_ results: [[String:AnyObject]]?, _ pagesNumber: Int, _ error: String?) -> Void) { let pageChoosen = randomPage((pin.pages as? Int)!) let methodParameters: [String: String?] = [Constants.FlickrParameterKeys.Method:Constants.FlickrParameterValues.SearchMethod, Constants.FlickrParameterKeys.APIKey: Constants.FlickrParameterValues.APIKey, Constants.FlickrParameterKeys.BoundingBox: bBoxString((pin.latitude as? Double)!, Long: (pin.longitude as? Double)!), Constants.FlickrParameterKeys.Extras: Constants.FlickrParameterValues.MediumURL, Constants.FlickrParameterKeys.Page: String(pageChoosen), Constants.FlickrParameterKeys.Format: Constants.FlickrParameterValues.ResponseFormat, Constants.FlickrParameterKeys.NoJSONCallback: Constants.FlickrParameterValues.DisableJSONCallback] let request = URLRequest(url: flickrURLFromParameters(methodParameters as [String : AnyObject])) let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in func errorFound(_ error: String) { print(error) completionHandlerForPhotos(nil, 0, error) } guard (error == nil) else { errorFound((error?.localizedDescription)!) return } guard let statusCode = (response as? HTTPURLResponse)?.statusCode , statusCode >= 200 && statusCode <= 299 else { errorFound("Status Code was \(response as? HTTPURLResponse)?.statusCode), which in not within the 200 to 299 range") return } guard let data = data else { errorFound("no data returned") return } var parsedData: AnyObject! do { parsedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject! } catch { errorFound("Unable to successfully parse data") } guard let photosDictionary = parsedData["photos"] as? [String:AnyObject] else { return } guard let pagesNumber = photosDictionary["pages"] as? Int else { return } guard let photoArray = photosDictionary["photo"] as? [[String:AnyObject]] else { return } let finalPhotoArray = self.randomPhotos(photoArray) completionHandlerForPhotos(finalPhotoArray, pagesNumber, nil) }) task.resume() } func randomPage(_ pages: Int) -> Int { var pageChoosen = Int() if pages == 0 { pageChoosen = 1 } else { pageChoosen = Int(arc4random_uniform(UInt32((pages)))) } return pageChoosen } func randomPhotos(_ photoArray: [[String:AnyObject]]) -> [[String:AnyObject]] { let number = Int(arc4random_uniform(UInt32(photoArray.count - 21))) var photoNum = 0 var photoLimit = 0 var finalPhotoArray = [[String:AnyObject]]() for i in photoArray { if photoNum >= number { if photoLimit < 21 { finalPhotoArray.append(i) photoLimit += 1 } } photoNum += 1 } return finalPhotoArray } func bBoxString(_ Lat: Double, Long: Double) -> String { let minimumLong = min(Long + Constants.Flickr.SearchBBoxHalfWidth, Constants.Flickr.SearchLonRange.1) let maximumLong = max(Long - Constants.Flickr.SearchBBoxHalfWidth, Constants.Flickr.SearchLonRange.0) let minimumLat = min(Lat + Constants.Flickr.SearchBBoxHalfHeight, Constants.Flickr.SearchLatRange.1) let maximumLat = max(Lat - Constants.Flickr.SearchBBoxHalfHeight, Constants.Flickr.SearchLatRange.0) return "\(maximumLong),\(maximumLat),\(minimumLong),\(minimumLat)" } }
37.889706
652
0.597128
f8c3145641f1adfbf950f401254a82c4fd8a8cf0
210
enum Token: String { case carriageReturn = "\r" case comment = "#" case equal = "=" case eof = "\0" case newline = "\n" case quote = "\"" case tab = "\t" case whitespace = " " }
19.090909
30
0.5
bbf7dfc4875add400cb0494134a595c65f56c18b
985
// // UIColorExtensions.swift // FlickrImageViewer // // Created by Alexey Danilov on 19/09/2017. // Copyright © 2017 DanilovDev. All rights reserved. // import Foundation import UIKit extension UIColor { convenience init(hexString: String) { let scanner = Scanner(string: hexString) scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#") var hexInt: UInt64 = 0 /* What does an ampersand (&) mean in the Swift language? It works as an inout to make the variable an in-out parameter. In-out means in fact passing value by reference, not by value. */ scanner.scanHexInt64(&hexInt) print(hexInt) let red = CGFloat((hexInt & 0xff0000) >> 16) / 255.0 let green = CGFloat((hexInt & 0xff00) >> 8) / 255.0 let blue = CGFloat((hexInt & 0xff) >> 0) / 255.0 self.init(red: red, green: green, blue: blue, alpha: 1.0) } }
28.142857
71
0.601015
79b6ee0acbb5e9c4a00664bb8cbbb3b9efc02585
180
import Foundation import QueueModels public final class JobStateRequest: Codable { public let jobId: JobId public init(jobId: JobId) { self.jobId = jobId } }
16.363636
45
0.688889
f4724eeefbe92c33a9129e5715d40cf76d34a7a0
2,221
// // FormRowRadioView.swift // AptoSDK // // Created by Ivan Oliver Martínez on 27/02/16. // // import UIKit import Bond class FormRowCheckView: FormRowView { let label: UILabel let checkIcon: UIImageView var checked: Bool = false { didSet { self.checked ? self.showCheckedState() : self.showUncheckedState() } } init(label: UILabel, showSplitter: Bool = false, height: CGFloat = 44) { self.label = label self.checkIcon = UIImageView(image: UIImage.imageFromPodBundle("empty_tick_circled.png")) super.init(showSplitter: showSplitter, height: height) contentView.addSubview(label) contentView.addSubview(checkIcon) checkIcon.snp.makeConstraints { make in make.left.equalTo(contentView) make.top.equalTo(label) make.width.height.equalTo(20) } checkIcon.isUserInteractionEnabled = true checkIcon.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(FormRowCheckView.switchValue))) label.snp.makeConstraints { make in make.left.equalTo(checkIcon.snp.right).offset(15) make.top.equalTo(contentView).offset(7) make.right.equalTo(contentView) make.bottom.equalTo(contentView).offset(-7) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var _bndValue: Observable<Bool>? var bndValue: Observable<Bool> { if let bndValue = _bndValue { return bndValue } else { let bndValue = Observable<Bool>(self.checked) _ = bndValue.observeNext { [weak self] (value: Bool) in self?.checked = value } _bndValue = bndValue return bndValue } } // MARK: - Private methods and attributes fileprivate func showCheckedState() { DispatchQueue.main.async { self.checkIcon.image = UIImage.imageFromPodBundle("blue_tick_circled.png")?.asTemplate() } } fileprivate func showUncheckedState() { DispatchQueue.main.async { self.checkIcon.image = UIImage.imageFromPodBundle("empty_tick_circled.png") } } @objc func switchValue() { self.bndValue.send(!self.bndValue.value) } }
27.7625
107
0.674471
50e0bf32b64c453e6e1632c9461c77589b634944
2,265
// Copyright © 2018-2020 App Dev Guy. All rights reserved. // // This code is distributed under the terms and conditions of the MIT license. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // import UIKit import OSSSpeechKit class CountryLanguageTableViewCell: UITableViewCell { // MARK: - Variables public var language: OSSVoiceEnum? { didSet { imageView?.image = language?.flag textLabel?.text = language?.title detailTextLabel?.text = language?.rawValue } } // MARK: - Lifecycle override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) imageView?.contentMode = .scaleAspectFit imageView?.layer.masksToBounds = true imageView?.clipsToBounds = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() textLabel?.text = "" detailTextLabel?.text = "" imageView?.image = nil } }
35.952381
80
0.689625
61b14be252c3568ea901254cb3d37091de69b0a2
546
// // Post.swift // Debiru // // Created by Mike Polan on 3/23/21. // import Foundation struct Post: Identifiable, Hashable { let id: Int let boardId: String let threadId: Int let isRoot: Bool let author: User let date: Date let replyToId: Int? let subject: String? let content: String? let sticky: Bool let closed: Bool let spoileredImage: Bool let attachment: Asset? let threadStatistics: ThreadStatistics? let archived: Bool let archivedDate: Date? let replies: [Int] }
18.827586
43
0.650183
f4b8a10d560aa2f4b22a3ef0c3297bf2a2b1feb4
280
// RUN: not --crash %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 if true{struct Q<d where H:P{struct c{}struct c{var _=c{
35
87
0.739286
28c211d13ac751b89434c019baa1b74735556811
729
// // GetEncryptionKeyUseCase.swift // DirectCheckout // // Created by Diego Trevisan Lara on 21/07/19. // Copyright © 2019 Juno Pagamentos. All rights reserved. // protocol IGetEncryptionKeyUseCase { func get(publicToken: String, version: String, completion: @escaping (_ result: Result<String, DirectCheckoutError>) -> Void) } struct GetEncryptionKeyUseCase: IGetEncryptionKeyUseCase { let gateway: DirectCheckoutGateway func get(publicToken: String, version: String, completion: @escaping (Result<String, DirectCheckoutError>) -> Void) { let payload = GetKeyPayload(publicToken: publicToken, version: version) gateway.getEncryptionKey(payload: payload, completion: completion) } }
31.695652
129
0.739369
dbf0eec6fd67a9d40f0205caed9a17d41cdfa8a0
2,173
// // AppDelegate.swift // iOS12 // // Created by hzyuxiaohua on 2018/6/18. // Copyright © 2018 XOYO Co., Ltd. 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.753797
bfa07847ce8acd13af742395914bc0d63d29f02b
547
// swift-tools-version:5.5 import PackageDescription let package = Package( name: "PhotoBrowser", platforms: [ .iOS(.v13) ], products: [ .library( name: "PhotoBrowser", targets: ["PhotoBrowser"]), ], dependencies: [ ], targets: [ .target( name: "PhotoBrowser", dependencies: [], resources: [.process("Resources")]), .testTarget( name: "PhotoBrowserTests", dependencies: ["PhotoBrowser"]), ] )
20.259259
48
0.500914
bf93ec3de43694543435610b27d90fc08991c8ca
16,598
// // ResourceObjectDecodingErrorTests.swift // // // Created by Mathew Polzin on 11/8/19. // import XCTest @testable import JSONAPI // MARK: - Relationships final class ResourceObjectDecodingErrorTests: XCTestCase { func test_missingRelationshipsObject() { XCTAssertThrowsError(try testDecoder.decode( TestEntity.self, from: entity_relationships_entirely_missing )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: ResourceObjectDecodingError.entireObject, cause: .keyNotFound, location: .relationships ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "relationships object is required and missing." ) } } func test_required_relationship() { XCTAssertThrowsError(try testDecoder.decode( TestEntity.self, from: entity_required_relationship_is_omitted )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .keyNotFound, location: .relationships ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'required' relationship is required and missing." ) } } func test_relationshipWithNoId() { XCTAssertThrowsError(try testDecoder.decode( TestEntity.self, from: entity_required_relationship_no_id )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .keyNotFound, location: .relationshipId ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'required' relationship does not have an 'id'." ) } } func test_relationshipWithNoType() { XCTAssertThrowsError(try testDecoder.decode( TestEntity.self, from: entity_required_relationship_no_type )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .keyNotFound, location: .relationshipType ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'required' relationship does not have a 'type'." ) } } func test_NonNullable_relationship() { XCTAssertThrowsError(try testDecoder.decode( TestEntity.self, from: entity_nonNullable_relationship_is_null )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .valueNotFound, location: .relationships ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'required' relationship is not nullable but null was found." ) } } func test_NonNullable_relationship2() { XCTAssertThrowsError(try testDecoder.decode( TestEntity.self, from: entity_nonNullable_relationship_is_null2 )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .valueNotFound, location: .relationships ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'required' relationship is not nullable but null was found." ) } } func test_oneTypeVsAnother_relationship() { XCTAssertThrowsError(try testDecoder.decode( TestEntity.self, from: entity_relationship_is_wrong_type )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .jsonTypeMismatch(expectedType: "thirteenth_test_entities", foundType: "not_the_same"), location: .relationships ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, #"'required' relationship is of JSON:API type "not_the_same" but it was expected to be "thirteenth_test_entities""# ) } } func test_twoOneVsToMany_relationship() { XCTAssertThrowsError(try testDecoder.decode( TestEntity.self, from: entity_single_relationship_is_many )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .quantityMismatch(expected: .one), location: .relationships ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'required' relationship should contain one value but found many" ) } XCTAssertThrowsError(try testDecoder.decode( TestEntity.self, from: entity_many_relationship_is_single )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "omittable", cause: .quantityMismatch(expected: .many), location: .relationships ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'omittable' relationship should contain many values but found one" ) } } } // MARK: - Attributes extension ResourceObjectDecodingErrorTests { func test_missingAttributesObject() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_attributes_entirely_missing )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: ResourceObjectDecodingError.entireObject, cause: .keyNotFound, location: .attributes ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "attributes object is required and missing." ) } } func test_required_attribute() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_required_attribute_is_omitted )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .keyNotFound, location: .attributes ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'required' attribute is required and missing." ) } } func test_NonNullable_attribute() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_nonNullable_attribute_is_null )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .valueNotFound, location: .attributes ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'required' attribute is not nullable but null was found." ) } } func test_oneTypeVsAnother_attribute() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_attribute_is_wrong_type )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "required", cause: .typeMismatch(expectedTypeName: String(describing: String.self)), location: .attributes ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'required' attribute is not a String as expected." ) } } func test_oneTypeVsAnother_attribute2() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_attribute_is_wrong_type2 )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "other", cause: .typeMismatch(expectedTypeName: String(describing: Int.self)), location: .attributes ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'other' attribute is not a Int as expected." ) } } func test_oneTypeVsAnother_attribute3() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_attribute_is_wrong_type3 )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "yetAnother", cause: .typeMismatch(expectedTypeName: String(describing: Bool.self)), location: .attributes ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'yetAnother' attribute is not a Bool as expected." ) } } func test_transformed_attribute() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_attribute_is_wrong_type4 )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "transformed", cause: .typeMismatch(expectedTypeName: String(describing: Int.self)), location: .attributes ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, "'transformed' attribute is not a Int as expected." ) } } func test_transformed_attribute2() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_attribute_always_fails )) { error in XCTAssertEqual( String(describing: error), "Error: Always Fails" ) } } } // MARK: - JSON:API Type extension ResourceObjectDecodingErrorTests { func test_wrongJSONAPIType() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_is_wrong_type )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "self", cause: .jsonTypeMismatch(expectedType: "fourteenth_test_entities", foundType: "not_correct_type"), location: .type ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, #"found JSON:API type "not_correct_type" but expected "fourteenth_test_entities""# ) } } func test_wrongDecodedType() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_type_is_wrong_type )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "type", cause: .typeMismatch(expectedTypeName: String(describing: String.self)), location: .type ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, #"'type' (a.k.a. the JSON:API type name) is not a String as expected."# ) } } func test_type_missing() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_type_is_missing )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "type", cause: .keyNotFound, location: .type ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, #"'type' (a.k.a. JSON:API type name) is required and missing."# ) } } func test_type_null() { XCTAssertThrowsError(try testDecoder.decode( TestEntity2.self, from: entity_type_is_null )) { error in XCTAssertEqual( error as? ResourceObjectDecodingError, ResourceObjectDecodingError( subjectName: "type", cause: .valueNotFound, location: .type ) ) XCTAssertEqual( (error as? ResourceObjectDecodingError)?.description, #"'type' (a.k.a. JSON:API type name) is not nullable but null was found."# ) } } } // MARK: - Test Types extension ResourceObjectDecodingErrorTests { enum TestEntityType: ResourceObjectDescription { public static var jsonType: String { return "thirteenth_test_entities" } typealias Attributes = NoAttributes public struct Relationships: JSONAPI.Relationships { let required: ToOneRelationship<TestEntity, NoMetadata, NoLinks> let omittable: ToManyRelationship<TestEntity, NoMetadata, NoLinks>? } } typealias TestEntity = BasicEntity<TestEntityType> enum TestEntityType2: ResourceObjectDescription { public static var jsonType: String { return "fourteenth_test_entities" } public struct Attributes: JSONAPI.Attributes { let required: Attribute<String> let other: Attribute<Int>? let yetAnother: Attribute<Bool?>? let transformed: TransformedAttribute<Int, IntToString>? let transformed2: TransformedAttribute<String, AlwaysFails>? } typealias Relationships = NoRelationships } typealias TestEntity2 = BasicEntity<TestEntityType2> enum IntToString: Transformer { static func transform(_ value: Int) throws -> String { return "\(value)" } typealias From = Int typealias To = String } enum AlwaysFails: Transformer { static func transform(_ value: String) throws -> String { throw Error() } struct Error: Swift.Error, CustomStringConvertible { let description: String = "Error: Always Fails" } } }
33.063745
131
0.550247
e8bc95031763983019a1b31fdcc2c7e5dfd2e9c7
355
// // OutputFrameBuffer.swift // Framenderer // // Created by tqtifnypmb on 04/01/2017. // Copyright © 2017 tqitfnypmb. All rights reserved. // import CoreGraphics protocol OutputFrameBuffer { func useAsOutput() throws func convertToImage() -> CGImage? func convertToInput() -> InputFrameBuffer func retrieveRawData() -> [GLubyte] }
20.882353
53
0.707042
bbdbe7181adde75a549a4b01f75d74c766793c66
6,638
// // DropDownList.swift // iOSPond // // Created by iOSPond on 11/07/16. // Copyright © 2016 iOSPond. All rights reserved. // import UIKit /*! - author: iOSPond I defined enum so that I can group my constants here. - cellIdentifier: This is identity of the cell for dropdown list tableview */ enum constant:String { case cellIdentifier="CellIdentity" } public class SwiftDropDownList: UITextField, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate { //MARK: - Global Vars private var tblView:UITableView! var arrayList:NSArray=NSArray() static var arrList:NSArray! var isArrayWithObject:Bool = false var isDismissWhenSelected = true public var isKeyboardHidden=false public var keyPath:String! public var textField:UITextField! private var arrFiltered:NSArray! var superViews:UIView! //MARK:- Delegate object public weak var delegates:DropDownListDelegate! //MARK:- Class constructor required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.delegate=self self.tblView=UITableView() self.tblView.delegate=self self.tblView.dataSource=self self.tblView.registerClass(UITableViewCell.self, forCellReuseIdentifier: constant.cellIdentifier.rawValue) } convenience init(){ self.init() } //MARK:- TextField delegate methods public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let myStr = textField.text! as NSString let finalString = myStr.stringByReplacingCharactersInRange(range, withString: string) if isArrayWithObject{ if finalString.isEmpty{ arrFiltered = arrayList }else{ let pred=NSPredicate(format: "\(keyPath) beginswith[c] '\(finalString)'") self.arrFiltered = arrayList.filteredArrayUsingPredicate(pred) } }else{ let array:[AnyObject]=arrayList as [AnyObject] if finalString.isEmpty{ arrFiltered = arrayList }else{ arrFiltered = array.filter{($0 as! String) .localizedCaseInsensitiveContainsString(finalString)} } } print(self.arrFiltered) self.tblView.reloadData() return true } public func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if self.tblView.frame.size.height > 0{ UIView.animateWithDuration(0.5, animations: { self.tblView.frame.size.height=0 }) }else{ textField.resignFirstResponder() self.tblView.frame.size.width=textField.frame.size.width self.tblView.frame.origin.x=textField.frame.origin.x self.tblView.frame.size.height=0 self.tblView.layer.borderWidth = 1 self.tblView.layer.borderColor = textField.layer.borderColor self.textField=textField self.arrFiltered = self.arrayList self.getSuperView(self.superview!) let rect = superViews.convertRect(textField.frame, fromView: textField.superview) self.tblView.frame.origin.y = rect.origin.y + rect.size.height-2 self.tblView.frame.origin.x = rect.origin.x UIView.animateWithDuration(0.5, animations: { self.tblView.frame.size.height=200 self.superViews.addSubview(self.tblView) self.tblView.reloadData() }) } return !isKeyboardHidden } public func textFieldShouldEndEditing(textField: UITextField) -> Bool { UIView.animateWithDuration(0.5, animations: { self.tblView.frame.size.height=0 }) textField.resignFirstResponder() return true } public func textFieldDidEndEditing(textField: UITextField) { UIView.animateWithDuration(0.5, animations: { self.tblView.frame.size.height=0 }) } public func textFieldShouldReturn(textField: UITextField) -> Bool { UIView.animateWithDuration(0.5, animations: { self.tblView.frame.size.height=0 }) textField.resignFirstResponder() return true } //MARK: - Custome Methods func getSuperView(views:UIView){ superViews = views.superview if superViews.frame.size.height < 200{ getSuperView(superViews!) } } //MARK- TableView Delegate public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.arrFiltered.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(constant.cellIdentifier.rawValue) if isArrayWithObject { cell?.textLabel?.text = self.arrFiltered.objectAtIndex(indexPath.row).valueForKey(keyPath) as? String }else{ cell?.textLabel?.text=self.arrFiltered.objectAtIndex(indexPath.row) as? String } return cell! } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let object = self.arrFiltered.objectAtIndex(indexPath.row) if delegates != nil{ self.delegates.dropDownSelectedIndex(indexPath.row, textField: self.textField, object: object) } if !isArrayWithObject { textField.text = object as? String }else{ textField.text = object.valueForKeyPath(keyPath) as? String } if isDismissWhenSelected { UIView.animateWithDuration(0.5, animations: { self.tblView.frame.size.height=0 }, completion: { (value: Bool) in self.tblView.removeFromSuperview() self.resignFirstResponder() }) } } } //MARK:- Protocol public protocol DropDownListDelegate:class { /*! - author: iOSPond This delegate method will call when user will select any option from dropdown list - parameter index: index which user select - parameter textField: textField from which drop down is apeared - parameter object: object that which is currently selected */ func dropDownSelectedIndex(index:Int, textField:UITextField, object:AnyObject) }
36.273224
139
0.636638
64a5a16dc9bdfce49bc50a76c001923b6df9d96c
3,127
// // CCBufferedImageView.swift // Concorde // // Created by Boris Bügling on 11/03/15. // Copyright (c) 2015 Contentful GmbH. All rights reserved. // import UIKit /// A subclass of UIImageView which displays a JPEG progressively while it is downloaded public class CCBufferedImageView : UIImageView, NSURLConnectionDataDelegate { private weak var connection: NSURLConnection? private let defaultContentLength = 5 * 1024 * 1024 private var data: NSMutableData? private let queue = DispatchQueue(label: "com.contentful.Concorde") /// Optional handler which is called after an image has been successfully downloaded public var loadedHandler: (() -> ())? deinit { connection?.cancel() } /// Initialize a new image view with the given frame public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.gray } /// Initialize a new image view and start loading a JPEG from the given URL public init(URL: URL) { super.init(image: nil) backgroundColor = .gray load(URL: URL) } /// Required initializer, not implemented required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = .gray } /// Load a JPEG from the given URL public func load(URL: URL) { connection?.cancel() connection = NSURLConnection(request: NSURLRequest(url: URL as URL) as URLRequest, delegate: self) } // MARK: NSURLConnectionDataDelegate /// see NSURLConnectionDataDelegate public func connection(connection: NSURLConnection, didFailWithError error: NSError) { NSLog("Error: %@", error) } /// see NSURLConnectionDataDelegate public func connection(connection: NSURLConnection, didReceiveData data: NSData) { self.data?.append(data as Data) queue.sync() { let decoder = CCBufferedImageDecoder(data: self.data as Data?) decoder?.decompress() guard let decodedImage = decoder?.toImage() else { return } UIGraphicsBeginImageContext(CGSize(width: 1, height: 1)) let context = UIGraphicsGetCurrentContext() context?.draw(decodedImage.cgImage!, in: CGRect(x: 0, y: 0, width: 1, height: 1)) UIGraphicsEndImageContext() DispatchQueue.main.async { self.image = decodedImage } } } /// see NSURLConnectionDataDelegate public func connection(connection: NSURLConnection, didReceiveResponse response: URLResponse) { var contentLength = Int(response.expectedContentLength) if contentLength < 0 { contentLength = defaultContentLength } data = NSMutableData(capacity: contentLength) } /// see NSURLConnectionDataDelegate public func connectionDidFinishLoading(connection: NSURLConnection) { data = nil if let loadedHandler = loadedHandler { loadedHandler() } } }
29.780952
106
0.63991
67a2695fd694929173fd2d887ca8adbfa99265f6
701
// // ArrayExtension.swift // kraken // // Created by 晨风 on 2017/7/14. // Copyright © 2017年 晨风. All rights reserved. // import Foundation extension Array { func subarray(range: NSRange) -> [Element] { let array = NSArray(array: self) return array.subarray(with: range) as! [Element] } var deleteFirst: [Element] { return subarray(range: NSMakeRange(1, count - 1)) } } extension Array where Element: Equatable { func has(any: Element) -> Index { for value in self.enumerated() { if value.element == any { return value.offset } } return -1 } }
16.302326
57
0.542083
465fb32a05d7898f666e0391aa4bbadb87b825ec
1,010
// // Falcon.swift // Test // // Created by Francesco Chiusolo on 23/03/2018. // Copyright © 2018 Francesco Chiusolo. All rights reserved. // import SpriteKit public class Falcon: SKSpriteNode { public init() { let texture = Textures.falcon let textureSize = texture.size() super.init(texture: texture, color: UIColor.clear, size: textureSize) zPosition = ZPosition.mainActor.rawValue physicsBody = SKPhysicsBody(rectangleOf: size) physicsBody?.affectedByGravity = false physicsBody?.mass = 20.0 physicsBody?.restitution = 0.0 physicsBody?.categoryBitMask = BitmaskCategories.falcon.rawValue physicsBody?.contactTestBitMask = BitmaskCategories.earth.rawValue physicsBody?.collisionBitMask = BitmaskCategories.earth.rawValue addSpark() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
28.055556
77
0.657426
e8430d46ceb25d406defc093962701e0b759fd3c
780
// // MockMigrationPolicy.swift // Tests // // Created by Ben Kreeger on 12/14/18. // Copyright © 2018 O'Reilly Media, Inc. All rights reserved. // import Foundation import CoreData @testable import Flapjack @testable import FlapjackCoreData @objc(MockMigrationPolicy) class MockMigrationPolicy: MigrationPolicy { override var migrations: [String: MigrationOperation] { return [ "EntityToMigrateToMigratedEntity": entityMigration ] } private var entityMigration: MigrationOperation { return { _, source, destination in if let sourceValue = source.value(forKey: "renamedProperty") as? Int32 { destination?.setValue(String(sourceValue), forKey: "convertedProperty") } } } }
25.16129
87
0.673077
38a61e8c27c9f212839dd414bdb5af6458a40165
326
// 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 lass func e: Int { } struct c : a { protocol a { typealias d(() return ")).<e(A<T>(v: l.<T typealias e : d : (
23.285714
87
0.687117
79cdffe491ca2bfbb8daebc9dd9ceec2cea8a007
3,012
import UIKit /*: ## Exercise - Guard Statements Imagine you want to write a function to calculate the area of a rectangle. However, if you pass a negative number into the function, you don't want it to calculate a negative area. Create a function called `calculateArea` that takes two `Double` parameters, `x` and `y`, and returns an optional `Double`. Write a guard statement at the beginning of the function that verifies each of the parameters is greater than zero and returns `nil` if not. When the guard has succeeded, calculate the area by multiplying `x` and `y` together, then return the area. Call the function once with positive numbers and once with at least one negative number. */ func calculateArea(x: Double, y: Double) -> Double? { guard x > 0 && y > 0 else { return nil } return x * y } calculateArea(x: 4, y: 5) calculateArea(x: 4, y: -5) /*: Create a function called `add` that takes two optional integers as parameters and returns an optional integer. You should use one `guard` statement to unwrap both optional parameters, returning `nil` in the `guard` body if one or both of the parameters doesn't have a value. If both parameters can successfully be unwrapped, return their sum. Call the function once with non-`nil` numbers and once with at least one parameter being `nil`. */ func add(x: Int?, y: Int?) -> Int? { guard let first = x, let second = y else { return nil } return first + second } add(x: 6, y: 4) add(x: 6, y: nil) /*: When working with UIKit objects, you will occasionally need to unwrap optionals to handle user input. For example, the text fields initialized below have `text` properties that are of type `String?`. Write a function below the given code called `createUser` that takes no parameters and returns an optional `User` object. Write a guard statement at the beginning of the function that unwraps the values of each text field's `text` property, and returns `nil` if not all values are successfully unwrapped. After the guard statement, use the unwrapped values to create and return and instance of `User`. */ struct User { var firstName: String var lastName: String var age: String } let firstNameTextField = UITextField() let lastNameTextField = UITextField() let ageTextField = UITextField() firstNameTextField.text = "Jonathan" lastNameTextField.text = "Sanders" ageTextField.text = "28" func createUser() -> User? { guard let firstName = firstNameTextField.text, let lastName = lastNameTextField.text, let age = ageTextField.text else { return nil } return User.init(firstName: firstName, lastName: lastName, age: age) } /*: Call the function you made above and capture the return value. Unwrap the `User` with standard optional binding and print a statement using each of its properties. */ var newUser: User? = createUser() if let user = newUser { print("First name: \(user.firstName), last name: \(user.lastName), age: \(user.age)") } //: page 1 of 2 | [Next: App Exercise - Guard](@next)
53.785714
643
0.73672
46d2a9c6814ab7229375788fabf1fc27834e2cb4
743
// // ActivityOperation.swift // Radio // // Created by Damien Glancy on 17/03/2019. // Copyright © 2019 Het is Simple BV. All rights reserved. // import Foundation import os.log final class ActivityOperation: BlockOperation { // MARK: - Properties let activity: NSObjectProtocol let activityUUID: UUID // MARK: - Lifecycle init(activity: NSObjectProtocol) { self.activity = activity self.activityUUID = UUID() os_log("ActivityOperation started (UUID: %@).", log: CloudKitLog, activityUUID.uuidString) } override func main() { super.main() ProcessInfo.processInfo.endActivity(activity) os_log("ActivityOperation finished (UUID: %@).", log: CloudKitLog, activityUUID.uuidString) } }
22.515152
95
0.695828
e9374cb371356924995c86d538d2041b4d994f1b
8,983
// // Log.swift // iOSSdk // // Created by Elisha Sterngold on 25/10/2017. // Copyright © 2018 ShipBook Ltd. All rights reserved. // #if canImport(UIKit) import Foundation fileprivate let appName = Bundle.main.infoDictionary?[kCFBundleExecutableKey as String] as? String ?? "" /** The class that create the logs. There are two ways that you can call this class: 1. Getting this class from `ShipBook.getLogger` 2. Calling static functions. This is not recommended and the caveats are listed below. When a static function activates the logger, the tag will become the filename. As mentioned, working with this static logger isn’t ideal: * Performance is slower, especially in cases where the log is closed * The log’s information is less detailed. Ideally, you should create a logger for each class. * The Log name can have a name collision with a local Log class. */ @objcMembers public class Log: NSObject { // static part of the class /** Error message - Parameters: - msg: The message. - tag: The tag. If no tag is given then it will be the file name. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public static func e(_ msg:String,tag:String? = nil,function: String = #function, file: String = #file, line: Int = #line){ Log.message(msg: msg, severity: .Error, tag: tag, function: function,file: file,line: line) } /** Warning message - Parameters: - msg: The message. - tag: The tag. If no tag is given then it will be the file name. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public static func w(_ msg:String,tag:String? = nil,function: String = #function, file: String = #file, line: Int = #line){ Log.message(msg: msg, severity: .Warning, tag: tag, function: function,file: file,line: line) } /** Information message - Parameters: - msg: The message. - tag: The tag. If no tag is given then it will be the file name. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public static func i(_ msg:String,tag:String? = nil,function: String = #function, file: String = #file, line: Int = #line){ Log.message(msg: msg, severity: .Info, tag: tag, function: function,file: file,line: line) } /** Debug message - Parameters: - msg: The message. - tag: The tag. If no tag is given then it will be the file name. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public static func d(_ msg:String,tag:String? = nil,function: String = #function, file: String = #file, line: Int = #line){ Log.message(msg: msg, severity: .Debug, tag: tag, function: function,file: file,line: line) } /** Verbose message - Parameters: - msg: The message. - tag: The tag. If no tag is given then it will be the file name. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public static func v(_ msg:String,tag:String? = nil,function: String = #function, file: String = #file, line: Int = #line){ Log.message(msg: msg, severity: .Verbose, tag: tag, function: function,file: file,line: line) } /** General message - Parameters: - msg: The message. - severity: The log severity of the message. - tag: The tag. If no tag is given then it will be the file name. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public static func message(msg:String,severity:Severity,tag:String? = nil,function: String = #function, file: String = #file, line: Int = #line){ let logClass = Log(tag, file: file) logClass.message(msg: msg, severity:severity, function: function, file: file, line: line) } // None static part of class var tag: String var severity: Severity var callStackSeverity: Severity init(_ tag: String?, file: String = #file) { var tempTag = tag if tempTag == nil { // for the case that there is no tag let lastPath = (file as NSString).lastPathComponent tempTag = lastPath.components(separatedBy: ".swift")[0] } self.tag = "\(appName).\(tempTag!)" severity = LogManager.shared.getSeverity(self.tag) callStackSeverity = LogManager.shared.getCallStackSeverity(self.tag) super.init() addNotification() } init(_ klass: AnyClass) { self.tag = String(reflecting: klass) self.severity = LogManager.shared.getSeverity(tag) self.callStackSeverity = LogManager.shared.getCallStackSeverity(tag) super.init() addNotification() } private func addNotification () { weak var _self = self NotificationCenter.default.addObserver( forName: NotificationName.ConfigChange, object: nil, queue: nil) { (notification) in if let _self = _self { _self.severity = LogManager.shared.getSeverity(self.tag) _self.callStackSeverity = LogManager.shared.getCallStackSeverity(self.tag) } } } /** Error message - Parameters: - msg: The message. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public func e(_ msg:String, function: String = #function, file: String = #file, line: Int = #line){ message(msg: msg, severity: .Error, function: function,file: file,line: line) } /** Warning message - Parameters: - msg: The message. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public func w(_ msg:String, function: String = #function, file: String = #file, line: Int = #line){ message(msg: msg, severity: .Warning, function: function,file: file,line: line) } /** Information message - Parameters: - msg: The message. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public func i(_ msg:String, function: String = #function, file: String = #file, line: Int = #line){ message(msg: msg, severity: .Info, function: function,file: file,line: line) } /** Debug message - Parameters: - msg: The message. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public func d(_ msg:String, function: String = #function, file: String = #file, line: Int = #line){ message(msg: msg, severity: .Debug, function: function,file: file,line: line) } /** Verbose message - Parameters: - msg: The message. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public func v(_ msg:String, function: String = #function, file: String = #file, line: Int = #line){ message(msg: msg, severity: .Verbose, function: function,file: file,line: line) } /** Checking if the severity is enabled. Is needed in the case that the user wants to do calculations just for the log. In this case when the log is closed the it shouldn't do the calculation. - Parameters: - severety: The severity to check. */ public func isEnabled(_ severity: Severity) -> Bool { return severity.rawValue <= self.severity.rawValue } /** General message - Parameters: - msg: The message. - severity: The log severity of the message. - function: The function that the log is written in. - file: The file that the log is written in. - line: The line number that the log is written in. */ public func message(msg:String, severity:Severity, function: String = #function, file: String = #file, line: Int = #line) { if (severity.rawValue > self.severity.rawValue) { return } var callStackSymbols: [String]? = nil if (severity.rawValue <= callStackSeverity.rawValue) { callStackSymbols = Thread.callStackSymbols } let messageObj = Message(message: msg, severity:severity, tag: self.tag, function: function, file: file, line: line, callStackSymbols: callStackSymbols) LogManager.shared.push(log: messageObj) } } #endif
37.902954
167
0.659691
222a1bb0df9994be07f1f22e32d4e14b3eb169d8
3,410
// // General+Extensions.swift // MediaListing // // Created by Rahul Mayani on 25/03/21. // import Foundation import UIKit import MobileCoreServices extension UIStoryboard{ func loadViewController<T>() -> T{ return self.instantiateViewController(withIdentifier: "\(T.self)") as! T } } extension String { func isValidURL() -> Bool { /*guard let urlString = self else {return false} guard let url = NSURL(string: urlString) else {return false} if !UIApplication.sharedApplication().canOpenURL(url) {return false}*/ let regEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+" let predicate = NSPredicate(format:"SELF MATCHES %@", regEx) return predicate.evaluate(with: self) } func mimeTypeForPathExtension() -> String { if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, self as NSString, nil)?.takeRetainedValue() { if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { return mimetype as String } } return "application/octet-stream" } func date(_ dateFormate: String? = nil) -> Date? { if let timeStamp = TimeInterval(self) { return timeStamp.date() } else { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormate dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone.current return dateFormatter.date(from: self) } } func timeStamp() -> Date { var orderDate = TimeInterval(self) ?? 0 if self.count > 10 { orderDate = orderDate / 1000 } return orderDate.date() } } public extension TimeInterval { func date() -> Date { return Date(timeIntervalSince1970: self) } func string(dateFormate: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormate return dateFormatter.string(from: date()) } func hoursMinutes () -> (Int, Int) { return ((Int(self) / 3600), ((Int(self) % 3600) / 60)) } } extension Date { public func string(dateFormate: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormate dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.timeZone = TimeZone.current return dateFormatter.string(from: self) } } extension CGRect { init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) { self.init(x:x, y:y, width:w, height:h) } } extension UIApplication { class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(base: nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(base: selected) } } if let presented = base?.presentedViewController { return topViewController(base: presented) } return base } }
30.176991
134
0.613196
ddd965acdac7960ff2f28ccf8fcf4b9fe1b333fa
2,028
// // BottomPopP_proxy.swift // petit // // Created by Jz D on 2020/10/28. // Copyright © 2020 swift. All rights reserved. // import Foundation import UIKit extension BottomPopP: UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 37 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 5 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let v = UIView() v.backgroundColor = UIColor(rgb: 0x575A61) return v } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 5 } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let v = UIView() v.backgroundColor = UIColor(rgb: 0x575A61) return v } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.selectYeB(idx: indexPath.row, src: kind) } } extension BottomPopP: UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch kind { case .interval: return secondsSpan.count case .times: return sourceTime.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = tableView.dequeue(for: PopChooseCel.self, ip: indexPath) switch kind { case .interval: let span = secondsSpan[indexPath.row].format(f: ".0") + " 秒" item.config(title: span) case .times: item.config(title: "\(sourceTime[indexPath.row]) 遍") } return item } }
20.079208
100
0.58925
d623e3ae5788882538485ba91b857798c6f572ae
2,045
#if canImport(UIKit) && (os(iOS) || os(tvOS)) import UIKit public extension UICollectionView { func isValidIndexPath(_ indexPath: IndexPath) -> Bool { return indexPath.section >= 0 && indexPath.item >= 0 && indexPath.section < numberOfSections && indexPath.item < numberOfItems(inSection: indexPath.section) } func safeScrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionView.ScrollPosition, animated: Bool) { guard isValidIndexPath(indexPath) else { return } scrollToItem(at: indexPath, at: scrollPosition, animated: animated) } // MARK: - Cell Registration func register<T: UICollectionViewCell>(_ class: T.Type) { register(T.self, forCellWithReuseIdentifier: String(describing: `class`)) } func dequeueReusableCell<T: UICollectionViewCell>(withClass class: T.Type, for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withReuseIdentifier: String(describing: `class`), for: indexPath) as? T else { fatalError() } return cell } // MARK: - Header & Footer Registration func register<T: UICollectionReusableView>(_ class: T.Type, kind: String) { register(T.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: String(describing: `class`)) } func dequeueReusableSupplementaryView<T: UICollectionReusableView>(withCalss class: T.Type, kind: String, for indexPath: IndexPath) -> T { guard let view = dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: String(describing: `class`), for: indexPath) as? T else { fatalError() } return view } // MARK: - Layout func invalidateLayout(animated: Bool) { if animated { performBatchUpdates({ self.collectionViewLayout.invalidateLayout() }, completion: nil) } else { collectionViewLayout.invalidateLayout() } } } #endif
35.877193
150
0.6489
7235fca3d6327f3677d1ed343140e67b9b3f73de
769
// Copyright © 2021 Flinesoft. All rights reserved. #if canImport(CryptoKit) import CryptoKit import Foundation extension Data { /// Encrypts this plain `Data` with the given key using AES.GCM and returns the encrypted data. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public func encrypted(key: SymmetricKey) throws -> Data { try AES.GCM.seal(self, using: key).combined! } /// Decrypts this encrypted data with the given key using AES.GCM and returns the decrypted `Data`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public func decrypted(key: SymmetricKey) throws -> Data { let sealedBox = try AES.GCM.SealedBox(combined: self) return try AES.GCM.open(sealedBox, using: key) } } #endif
34.954545
103
0.690507
d6de034a914a63fd71fe4dc7f667819e2d0474a3
1,162
// // ImageHelper.swift // 9squareApp // // Created by Jane Zhu on 2/14/19. // Copyright © 2019 EnProTech Group. All rights reserved. // import UIKit final class ImageHelper { private init() {} private static var cache = NSCache<NSString, UIImage>() static func fetchImageFromNetwork(urlString: String, completion: @escaping (AppError?, UIImage?) -> Void) { NetworkHelper.shared.performDataTask(endpointURLString: urlString, httpMethod: "GET", httpBody: nil) { (appError, data ) in if let appError = appError { completion(appError, nil) } else if let data = data { DispatchQueue.global().async { if let image = UIImage(data: data) { cache.setObject(image, forKey: urlString as NSString) DispatchQueue.main.async { completion(nil, image) } } } } } } static func fetchImageFromCache(urlString: String) -> UIImage? { return cache.object(forKey: urlString as NSString) } }
31.405405
131
0.555077
71b6b631710cdf205d5fdd115df759316dc1c704
2,251
// // SceneDelegate.swift // ShoppingList // // Created by Alex Paul on 7/15/20. // Copyright © 2020 Alex Paul. 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. } }
41.685185
143
0.742781
48f79b8b6a81ec0ff40e8bad885f4398fae11193
823
// // Tip_CalculatorUITestsLaunchTests.swift // Tip CalculatorUITests // // Created by Katherine Sullivan on 8/12/21. // import XCTest class Tip_CalculatorUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
24.939394
88
0.681652
4638e3be4c90934cef24e33e15a8d8c104c0f7d8
537
// // TextDisplaySmall.swift // GitHubViewer // // Created by Виталий Зарубин on 16.01.2022. // import SwiftUI struct TextDisplaySmall: View { var text: String var maxLines = Int.max var color = Color.onBackground var alignment: TextAlignment = .leading var body: some View { Text(text) .font(Font.custom(PoppinsName(.Regular), size: 36)) .foregroundColor(color) .lineSpacing(0) .lineLimit(maxLines) .multilineTextAlignment(alignment) } }
21.48
63
0.620112
790d1055a15a79bd9b3bd339f82051aa0561870b
775
// // File.swift // // // Created by Morten Bertz on 2020/07/03. // import Foundation import SwiftUI #if canImport(UIKit) import PencilKit internal extension Color{ static let quaternaryLabel = Color(UIColor.quaternaryLabel) } public class CanvasConfiguration:ObservableObject{ @Published public var backgroundColor = Color.quaternaryLabel @Published public var foregroundColor = Color.red @Published public var strokeColor = UIColor.label @Published public var strokeWidth : CGFloat = 5 @Published public var toolType:PKInkingTool.InkType = .pen @Published public var showStandardButtons = true public init(){} } #else internal extension Color{ static let quaternaryLabel = Color(NSColor.quaternaryLabelColor) } #endif
19.871795
68
0.743226
9baa74c2083174de19f1286906aff225f52e17ec
6,452
// // BrowserAlbumHeader.swift // Ubiquity // // Created by SAGESSE on 8/1/17. // Copyright © 2017 SAGESSE. All rights reserved. // import UIKit internal class BrowserAlbumHeader: UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) _setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _setup() } weak var parent: BrowserAlbumHeader? var effect: UIVisualEffect? { willSet { // has any effect? guard let newValue = newValue else { // remove effect view _visualEffectView?.removeFromSuperview() _visualEffectView = nil // move content view to self addSubview(_contentView) return } // create view guard _visualEffectView == nil else { _visualEffectView?.effect = newValue return } let visualEffectView = UIVisualEffectView(frame: bounds) // config effect view visualEffectView.effect = newValue visualEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] visualEffectView.contentView.addSubview(_contentView) // move to effect view addSubview(visualEffectView) _visualEffectView = visualEffectView } } var source: Source? { willSet { // The source is change? guard source !== newValue else { return } // update content section.map { _updateCollection(newValue?.collection(at: $0)) } // update subheader _headers.forEach { key, value in value._updateCollection(newValue?.collection(at: key)) } } } var section: Int? { didSet { // section has any change? guard oldValue != section else { return } // self is subheader? if let parent = parent { // remove link from parent if let oldValue = oldValue { parent._headers.removeValue(forKey: oldValue) } // add link to parent if let newValue = section { parent._headers[newValue] = self } } // update self status _updateStatus(section) // update self contents if let section = section { _updateCollection((source ?? parent?.source)?.collection(at: section)) } // self is parent? _headers.forEach { $1._updateStatus($1.section) } } } override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize { // don't call super, size is fixed return frame.size } override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { super.apply(layoutAttributes) // update section if section != layoutAttributes.indexPath.section, parent != nil { section = layoutAttributes.indexPath.section } } // update display status private func _updateStatus(_ section: Int?) { // if parent is nil, can't hide guard let parent = parent else { _contentView.isHidden = false return } let isHidden = parent.section == section guard isHidden != _contentView.isHidden else { return } // if section is equal, hide _contentView.isHidden = isHidden } // update display contents private func _updateCollection(_ collection: Collection?) { // has any change? guard _collection !== collection else { return } _collection = collection // update text _titleLabel.text = collection?.title _subtitleLabel.text = collection?.subtitle } private func _setup() { // setup title _titleLabel.font = .systemFont(ofSize: 15) _titleLabel.translatesAutoresizingMaskIntoConstraints = false _subtitleLabel.font = .systemFont(ofSize: 11) _subtitleLabel.translatesAutoresizingMaskIntoConstraints = false // center view let tmp = UIView(frame: bounds) tmp.translatesAutoresizingMaskIntoConstraints = false tmp.addSubview(_titleLabel) tmp.addSubview(_subtitleLabel) tmp.addConstraints([ .ub_make(tmp, .top, .equal, _titleLabel, .top, -1), .ub_make(tmp, .left, .equal, _titleLabel, .left), .ub_make(tmp, .right, .equal, _titleLabel, .right), .ub_make(_titleLabel, .bottom, .equal, _subtitleLabel, .top, -1), .ub_make(tmp, .left, .equal, _subtitleLabel, .left), .ub_make(tmp, .right, .equal, _subtitleLabel, .right), .ub_make(tmp, .bottom, .equal, _subtitleLabel, .bottom), ]) // setup content view _contentView.frame = bounds _contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] _contentView.addSubview(tmp) _contentView.addConstraints([ .ub_make(_contentView, .centerY, .equal, tmp, .centerY), .ub_make(_contentView, .leftMargin, .equal, tmp, .left), .ub_make(_contentView, .rightMargin, .equal, tmp, .right), ]) // setup subviews addSubview(_contentView) } private var _collection: Collection? private var _headers: [Int: BrowserAlbumHeader] = [:] private var _contentView: UIView = .init() private var _visualEffectView: UIVisualEffectView? private lazy var _titleLabel: UILabel = .init() private lazy var _subtitleLabel: UILabel = .init() }
31.019231
193
0.541538
f8b8e5ccc8cd8b054a0af5178a04532bba0e5c99
5,409
// // Copyright (c) 2021 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // @testable import Adyen @testable import AdyenCard @testable import AdyenDropIn import XCTest class StoredPaymentMethodComponentTests: XCTestCase { func testLocalizationWithCustomTableName() { let method = StoredPaymentMethodMock(identifier: "id", supportedShopperInteractions: [.shopperNotPresent], type: "test_type", name: "test_name") let sut = StoredPaymentMethodComponent(paymentMethod: method, apiContext: Dummy.context) let payment = Payment(amount: Amount(value: 34, currencyCode: "EUR"), countryCode: "DE") sut.payment = payment sut.localizationParameters = LocalizationParameters(tableName: "AdyenUIHost", keySeparator: nil) let viewController = sut.viewController as? UIAlertController XCTAssertNotNil(viewController) XCTAssertEqual(viewController?.actions.count, 2) XCTAssertEqual(viewController?.actions.first?.title, localizedString(.cancelButton, sut.localizationParameters)) XCTAssertEqual(viewController?.actions.last?.title, localizedSubmitButtonTitle(with: payment.amount, style: .immediate, sut.localizationParameters)) } func testLocalizationWithZeroPayment() { let method = StoredPaymentMethodMock(identifier: "id", supportedShopperInteractions: [.shopperNotPresent], type: "test_type", name: "test_name") let sut = StoredPaymentMethodComponent(paymentMethod: method, apiContext: Dummy.context) let payment = Payment(amount: Amount(value: 0, currencyCode: "EUR"), countryCode: "DE") sut.payment = payment let viewController = sut.viewController as? UIAlertController XCTAssertNotNil(viewController) XCTAssertEqual(viewController?.actions.count, 2) XCTAssertEqual(viewController?.actions.first?.title, localizedString(.cancelButton, sut.localizationParameters)) XCTAssertEqual(viewController?.actions.last?.title, localizedSubmitButtonTitle(with: payment.amount, style: .immediate, sut.localizationParameters)) XCTAssertEqual(viewController?.actions.last?.title, "Confirm preauthorization") } func testLocalizationWithCustomKeySeparator() { let method = StoredPaymentMethodMock(identifier: "id", supportedShopperInteractions: [.shopperNotPresent], type: "test_type", name: "test_name") let sut = StoredPaymentMethodComponent(paymentMethod: method, apiContext: Dummy.context) let payment = Payment(amount: Amount(value: 34, currencyCode: "EUR"), countryCode: "DE") sut.payment = payment sut.localizationParameters = LocalizationParameters(tableName: "AdyenUIHostCustomSeparator", keySeparator: "_") let viewController = sut.viewController as? UIAlertController XCTAssertNotNil(viewController) XCTAssertEqual(viewController?.actions.count, 2) XCTAssertEqual(viewController?.actions.first?.title, localizedString(.cancelButton, sut.localizationParameters)) XCTAssertEqual(viewController?.actions.last?.title, localizedSubmitButtonTitle(with: payment.amount, style: .immediate, sut.localizationParameters)) } func testUI() { let method = StoredPaymentMethodMock(identifier: "id", supportedShopperInteractions: [.shopperPresent], type: "type", name: "name") let sut = StoredPaymentMethodComponent(paymentMethod: method, apiContext: Dummy.context) let delegate = PaymentComponentDelegateMock() let delegateExpectation = expectation(description: "expect delegate to be called.") delegate.onDidSubmit = { data, component in XCTAssertTrue(component === sut) XCTAssertNotNil(data.paymentMethod as? StoredPaymentDetails) let details = data.paymentMethod as! StoredPaymentDetails XCTAssertEqual(details.type, "type") XCTAssertEqual(details.storedPaymentMethodIdentifier, "id") delegateExpectation.fulfill() } delegate.onDidFail = { _, _ in XCTFail("delegate.didFail() should never be called.") } sut.delegate = delegate let payment = Payment(amount: Amount(value: 174, currencyCode: "EUR"), countryCode: "NL") sut.payment = payment UIApplication.shared.keyWindow?.rootViewController?.present(sut.viewController, animated: false, completion: nil) let uiExpectation = expectation(description: "Dummy Expectation") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) { let alertController = sut.viewController as! UIAlertController XCTAssertTrue(alertController.actions.contains { $0.title == localizedString(.cancelButton, nil) }) XCTAssertTrue(alertController.actions.contains { $0.title == localizedSubmitButtonTitle(with: payment.amount, style: .immediate, nil) }) let payAction = alertController.actions.first { $0.title == localizedSubmitButtonTitle(with: payment.amount, style: .immediate, nil) }! payAction.tap() uiExpectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } }
52.009615
156
0.700129
cc8fc2ae38e0cfdc8785752a82a5136cebf4ed04
1,271
// // OverlapRemovalRefiner.swift // SwiftyChrono // // Created by Jerry Chen on 1/24/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation class OverlapRemovalRefiner: Refiner { override public func refine(text: String, results: [ParsedResult], opt: [OptionType: Int]) -> [ParsedResult] { let resultsLength = results.count if resultsLength < 2 { return results } var filteredResults = [ParsedResult]() var previousResult: ParsedResult = results[0] var i = 1 while i < resultsLength { var result = results[i] // If overlap, compare the length and discard the shorter one let previousTextLength = previousResult.text.characters.count if result.index < previousResult.index + previousTextLength { if result.text.characters.count > previousTextLength { previousResult = result } } else { filteredResults.append(previousResult) previousResult = result } i += 1 } // The last one filteredResults.append(previousResult) return filteredResults } }
30.261905
114
0.579858
507297c0f78873a93ab76a7ea81bc487b035090b
4,013
// // LocationSearchController.swift // MapsDirectionsGooglePlaces // // Created by Gin Imor on 5/7/21. // // import SwiftUI import UIKit import MapKit import Combine class LocationSearchCell: GIListCell<MKMapItem> { let nameLabel = UILabel.new("Name", .headline) let addressLabel = UILabel.new("Address", .footnote) override func setup() { super.setup() GIVStack(nameLabel, addressLabel).spacing() .add(to: self).filling(self, edgeInsets: .init(0, 16, 8)) addBottomBorder(leftPad: 16) } override func didSetItem() { nameLabel.text = item.name addressLabel.text = item.address } } class LocationSearchController: GIListController<MKMapItem>, UICollectionViewDelegateFlowLayout { override var ItemCellClass: GIListCell<MKMapItem>.Type? { LocationSearchCell.self } var didSelectMapItem: ((MKMapItem) -> Void)? let backButton = UIButton.system(imageName: "arrow.left", size: 18, tintColor: .black) let searchTextField = IndentedTextField(8, "Enter search term", .body) override func viewDidLoad() { super.viewDidLoad() setupListeners() } // no need to cancel the listener manually, cause when the controller // deinit, the listener will cancel iteself before it deinit private var textFiledListener: AnyCancellable? private func setupListeners() { backButton.addTarget(self, action: #selector(handleBack)) textFiledListener = NotificationCenter.default .publisher(for: UITextField.textDidChangeNotification, object: searchTextField) .debounce(for: .milliseconds(500), scheduler: RunLoop.main) .sink(receiveValue: { [weak self] (_) in self?.performLocalSearch() }) } @objc func handleBack() { navigationController?.popViewController(animated: true) } override func setupViews() { super.setupViews() searchTextField.backgroundColor = UIColor(white: 1.0, alpha: 0.3) searchTextField.layer.borderWidth = 2 searchTextField.layer.borderColor = UIColor.red.cgColor searchTextField.layer.cornerRadius = 8 let navBar = UIView(backgroundColor: .white) navBar.add(to: view).hLining(.horizontal, to: view) .vLining(.top, to: view).vLining(.bottom, .top, value: navBarHeight) GIHStack(backButton, searchTextField.withCH(249, axis: .horizontal)).spacing() .add(to: navBar).filling(edgeInsets: .init(0, 16, 8)) collectionView.verticalScrollIndicatorInsets.top += navBarHeight } private let navBarHeight: CGFloat = 55 override func setupFlowLayout(_ flowLayout: UICollectionViewFlowLayout) { flowLayout.sectionInset.top = navBarHeight } private func performLocalSearch() { let request = MKLocalSearch.Request() request.naturalLanguageQuery = searchTextField.text let localSearch = MKLocalSearch(request: request) localSearch.start { [weak self] (response, error) in if let error = error { print("local search error in direction controller", error) return } guard let response = response else { return } self?.setItems(response.mapItems) } } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { navigationController?.popViewController(animated: true) didSelectMapItem?(items[indexPath.item]) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.bounds.width, height: 70) } } struct LocationSearchView: UIViewControllerRepresentable { func makeUIViewController(context: Context) -> some UIViewController { return LocationSearchController() } func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { } } struct LocationSearchView_Previews: PreviewProvider { static var previews: some View { LocationSearchView().edgesIgnoringSafeArea(.all) } }
31.108527
158
0.721405
d6d3c1b0dd9017d27a511ea318498d4ca80b6026
3,075
// // UIView+Maple.swift // Maple // // Created by cy on 2020/4/5. // Copyright © 2020 cy. All rights reserved. // #if canImport(UIKit) && !os(watchOS) import UIKit extension UIView: MabpleCompatible { } // MARK: - Properties public extension MabpleWrapper where Base: UIView { /// Corner radius of view; var cornerRadius: CGFloat { get { return base.layer.cornerRadius } set { base.layer.masksToBounds = true base.layer.cornerRadius = abs(CGFloat(Int(newValue * 100)) / 100) } } /// Get view's parent view controller var parentViewController: UIViewController? { weak var parentResponder: UIResponder? = base while parentResponder != nil { parentResponder = parentResponder!.next if let viewController = parentResponder as? UIViewController { return viewController } } return nil } /// Take screenshot of view (if applicable). var screenshot: UIImage? { UIGraphicsBeginImageContextWithOptions(base.layer.frame.size, false, 0) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { return nil } base.layer.render(in: context) return UIGraphicsGetImageFromCurrentImageContext() } } // MARK: - Methods public extension MabpleWrapper where Base: UIView { /// Recursively find the first responder. func firstResponder() -> UIView? { var views = [UIView](arrayLiteral: base) var i = 0 repeat { let view = views[i] if view.isFirstResponder { return view } views.append(contentsOf: view.subviews) i += 1 } while i < views.count return nil } /// Add shadow to view. /// - Parameters: /// - color: shadow color (default is #fffff). /// - radius: shadow radius (default is 3). /// - offset: shadow offset (default is .zero). /// - opacity: shadow opacity (default is 0.5). func addShadow(ofColor color: UIColor = .black, radius: CGFloat = 3, offset: CGSize = .zero, opacity: Float = 0.5) { base.layer.shadowColor = color.cgColor base.layer.shadowOffset = offset base.layer.shadowRadius = radius base.layer.shadowOpacity = opacity base.layer.masksToBounds = false } /// Set some or all corners radiuses of view. /// /// - Parameters: /// - corners: array of corners to change (example: [.bottomLeft, .topRight]). /// - radius: radius for selected corners. func roundCorners(_ corners: UIRectCorner, radius: CGFloat) { let maskPath = UIBezierPath( roundedRect: base.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let shape = CAShapeLayer() shape.path = maskPath.cgPath base.layer.mask = shape } } #endif
30.75
120
0.594797
cccfe76193b527a04d1f95c151faae1435d52717
2,346
import XCTest @testable import Combinatorics final class PermutationsTests: XCTestCase { func test_empty() { let a: [Int] = [] let res = Combinatorics.permutations(of: a) XCTAssertTrue(res == []) } func test_single() { let res = Combinatorics.permutations(of: [1]) XCTAssertTrue(res == [[1]]) } func test_pair() { let exp = [ [1,2], [2,1] ] let res = Combinatorics.permutations(of: [1,2]) XCTAssertTrue(res == exp) } func test_triple() { let exp = [ [1,2,3], [2,1,3], [3,1,2], [1,3,2], [2,3,1], [3,2,1] ] let res = Combinatorics.permutations(of: [1,2,3]) XCTAssertTrue(res == exp) } func test_quadra() { let exp = [ [1,2,3,4], [2,1,3,4], [3,1,2,4], [1,3,2,4], [2,3,1,4], [3,2,1,4], [4,2,1,3], [2,4,1,3], [1,4,2,3], [4,1,2,3], [2,1,4,3], [1,2,4,3], [1,3,4,2], [3,1,4,2], [4,1,3,2], [1,4,3,2], [3,4,1,2], [4,3,1,2], [4,3,2,1], [3,4,2,1], [2,4,3,1], [4,2,3,1], [3,2,4,1], [2,3,4,1] ] let res = Combinatorics.permutations(of: [1,2,3,4]) XCTAssertTrue(res == exp) } func test_empty_async() { let a: [Int] = [] Combinatorics.permutations( of: a, executionQueue: DispatchQueue.global(qos: .background), receiverQueue: DispatchQueue.main ) { res in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(res == []) } } func test_single_async() { let a = [1] let exp = [ [1] ] Combinatorics.permutations( of: a, executionQueue: DispatchQueue.global(qos: .background), receiverQueue: DispatchQueue.main ) { res in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(res == exp) } } func test_pair_async() { let a = [1,2] let exp = [ [1,2], [2,1] ] Combinatorics.permutations( of: a, executionQueue: DispatchQueue.global(qos: .background), receiverQueue: DispatchQueue.main ) { res in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(res == exp) } } }
26.965517
77
0.479966
487f12736c09e36f03dc4f21cd59d70cbb0fe1f4
1,600
/* ObjectPool.swift Copyright © 2021 BB9z. https://github.com/BB9z/iOS-Project-Template The MIT License https://opensource.org/licenses/MIT */ /** 弱引用存储 model 实例,用于保证相同 id 的对象有唯一实例,线程安全 项目模版的 model 更新后刷新机制依赖 model 实例的唯一性 */ final class ObjectPool<Key: Hashable, Value: AnyObject> { private var store = [Key: Weak]() private let lock = NSLock() init() { } /** 只读或写线程安全 但如果类似下列代码,不存在则创建保存这种,请用 `object(key: Key, creator: @autoclosure () -> Value)` 方法 ``` // 反例,下述方法不是线程安全的,相同 id 的 Obj 可以创建多个并返回 fun someFunc(id: Key) -> Obj { if let old = pool[id] { return old } else { let new = Obj(id) pool[id] = new return new } } ``` */ subscript(index: Key) -> Value? { get { lock.lock() let value = store[index] lock.unlock() return value?.object } set { lock.lock() store[index] = Weak(object: newValue) lock.unlock() } } /** 返回 key 对应的对象,如果未在对象池中不存在,则用 creator 创建,存储后返回 */ func object(key: Key, creator: @autoclosure () -> Value) -> Value { lock.lock() defer { lock.unlock() } if let obj = store[key]?.object { return obj } let obj = creator() store[key] = Weak(object: obj) return obj } func removeAll() { lock.lock() store = [:] lock.unlock() } private struct Weak { weak var object: Value? } }
20.253165
85
0.50625
5645144277b3a03c7804c23a255d9cc5e289eb61
5,798
// // SignUpOrIn.swift // BookShare // // Created by 藤澤洋佑 on 2019/02/06. // Copyright © 2019年 NEKOKICHI. All rights reserved. // import UIKit import Firebase class SignUp: UIViewController,UITextFieldDelegate { @IBOutlet weak var userNameForm: UITextField! @IBOutlet weak var userIDForm: UITextField! @IBOutlet weak var mailForm: UITextField! @IBOutlet weak var passForm: UITextField! //UserDataClass var userDataClass = UserData.userClass //UserDefault let userDataID = UserDefaults.standard.string(forKey: "userDataID") //FireStore let db = Firestore.firestore() override func viewDidLoad() { super.viewDidLoad() userNameForm.delegate = self userIDForm.delegate = self mailForm.delegate = self passForm.delegate = self userNameForm.layer.borderWidth = 1 userNameForm.layer.cornerRadius = 10 userIDForm.layer.borderWidth = 1 userIDForm.layer.cornerRadius = 10 mailForm.layer.borderWidth = 1 mailForm.layer.cornerRadius = 10 passForm.layer.borderWidth = 1 passForm.layer.cornerRadius = 10 } //サインアップ @IBAction func signup(_ sender: Any) { //2つのフォームが入力されてる場合 if mailForm.text != "" && passForm.text != "" { //入力したパスワードが7文字以上の場合 if (passForm.text?.count)! > 6 { Auth.auth().createUser(withEmail: mailForm.text!, password: passForm.text!) { (user, error) in if error == nil { Auth.auth().currentUser?.sendEmailVerification(completion: { (error) in if error == nil { //ログイン状態をtrueに let ud = UserDefaults.standard ud.set(true, forKey: "loginStatus") ud.synchronize() //ユーザー名をセット if let user = Auth.auth().currentUser { let changeRequest = user.createProfileChangeRequest() changeRequest.displayName = self.userNameForm.text! } //UserDefaultsとUserDataクラスにuserDataIDを保存 ud.set((Auth.auth().currentUser?.uid)!, forKey: "userDataID") ud.synchronize() self.userDataClass.userDataID = ud.string(forKey: "userDataID")! //ユーザーデータを作成 self.createUserData() //ユーザーデータを取得 let readD = readData() readD.readMyData() //ホーム画面に遷移 let storyboard = UIStoryboard(name: "Main", bundle:Bundle.main) let rootViewController = storyboard.instantiateViewController(withIdentifier: "Main") UIApplication.shared.keyWindow?.rootViewController = rootViewController } }) } else { print(error) } } //入力したパスワードが6文字以下の場合 } else { self.alert(title: "エラー", message: "7文字以上のパスワードを入力してください。", actiontitle: "OK") } //いずれかのフォームが未入力の場合 } else { self.alert(title: "エラー", message: "入力されてない箇所があります。", actiontitle: "OK") } } //ログイン画面に移行 @IBAction func changeToLogin(_ sender: Any) { performSegue(withIdentifier: "gosignin", sender: nil) } //アラート func alert(title:String,message:String,actiontitle:String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: actiontitle, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } //ユーザーデータを新規作成 func createUserData() { //保存するデータを宣言 let userData : [String:Any] = [ "UserName":userNameForm.text!, "UserID":userIDForm.text!, "UserDataID":self.userDataClass.userDataID, "Grade":"0", "Follow":"0", "Follower":"0", "Good":"0", "Share":"0", "Get":"0", "Profile":""] //ユーザーデータを保存 db.collection("User").document(userDataID!).setData(userData, completion: { (err) in if err != nil { print("success") } else { print("fail") } }) //Storageにプレースホルダー用の画像を保存 //画像を保存 let storageref = Storage.storage().reference(forURL: "gs://bookshare-b78b4.appspot.com").child("User").child(userDataClass.userDataID) var data = NSData() let meta = StorageMetadata() meta.contentType = "image/jpeg" data = UIImage(named: "Icon")!.jpegData(compressionQuality: 1.0)! as NSData storageref.putData(data as Data, metadata: meta) { (metadata, error) in if error != nil { return } } self.dismiss(animated: true, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { userNameForm.resignFirstResponder() userIDForm.resignFirstResponder() mailForm.resignFirstResponder() passForm.resignFirstResponder() } }
37.166667
142
0.526388
0ee4a2f5004764f12d5d780aa2febb1caf4c2dfd
914
import Foundation extension Requests { public static func media( filename: String, contentType: String, fileData: Data ) -> POSTRequest<Responses.Attachment> { let boundary = "MastodonAPIBoundary" var body = Data() body.append("--\(boundary)\r\n") body.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n") body.append("Content-Type: \(contentType)\r\n\r\n") body.append(fileData) body.append("\r\n") body.append("--\(boundary)--\r\n") return POSTRequest( endpoint: "/api/v2/media", body: body, contentType: "multipart/form-data; boundary=\(boundary)" ) } } // MARK: - extension Data { mutating func append(_ string: String) { guard let data = string.data(using: .utf8) else { return } append(data) } }
27.69697
98
0.571116
c121f5b6151a6bac9c3e29be3317b8260e91c446
239
// // ImageHostingServiceProtocol.swift // Travelly // // Created by Георгий Куликов on 14.04.2021. // import UIKit protocol ImageHostingServiceProtocol { func getUrl(for image: UIImage, complition: @escaping (String?) -> Void) }
18.384615
76
0.719665
e655fcededa456a9b5236d339294f3a181c91ab5
681
// // AuthSession.swift // EasyLogin // // Created by Vinh on 3/2/19. // Copyright © 2019 Vinh. All rights reserved. // import Foundation class AuthSession { init(provider: String, appId: String) { self.provider = provider self.authStatus = AuthStatus.unknown.rawValue self.appId = appId } var appId: String var provider: String var channel: Channel? var state: String? var authStatus: String? var authToken: EasyAuthToken? } enum AuthStatus: String { case unknown = "unknown" case authorized = "authorized" case waitReg = "wait_reg" case failed = "failed" case succeeded = "succeeded" }
20.029412
53
0.641703
714f9808d574813780b88bfd868cfda077f767ba
3,087
#if !os(macOS) import UIKit @available(*, deprecated, renamed: "UBarButtonItem") public typealias BarButtonItem = UBarButtonItem open class UBarButtonItem: UIBarButtonItem { public init(_ title: String?) { super.init() self.title = title setup() } public init(_ localized: LocalizedString...) { super.init() self.title = String(localized) setup() } public init(_ localized: [LocalizedString]) { super.init() self.title = String(localized) setup() } // TODO: figure out how to implement `barButtonSystemItem` // public init(_ barButtonSystemItem: UIBarButtonItem.SystemItem) { // super.init() // self.image // setup() // } public init(image: UIImage?) { super.init() self.image = image setup() } public init(_ image: State<UIImage>) { super.init() self.image = image.wrappedValue setup() image.listen { [weak self] in self?.image = $0 } } public init(image imageName: String) { super.init() self.image = UIImage(named: imageName) setup() } public init(_ customView: UIView) { super.init() self.customView = customView setup() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { target = self action = #selector(tapEvenWithbuttont(_:)) } // MARK: TouchUpInside public typealias TapAction = ()->Void public typealias TapActionWithButton = (UBarButtonItem)->Void private var tapCallback: TapAction? private var tapWithButtonCallback: TapActionWithButton? @discardableResult public func tapAction(_ callback: @escaping TapAction) -> Self { tapCallback = callback return self } @discardableResult public func tapAction(_ callback: @escaping TapActionWithButton) -> Self { tapWithButtonCallback = callback return self } @objc private func tapEvenWithbuttont(_ button: UBarButtonItem) { tapCallback?() tapWithButtonCallback?(button) } @discardableResult public func style(_ style: UIBarButtonItem.Style) -> Self { self.style = style return self } // MARK: tint @discardableResult public func tint(_ color: UIColor) -> Self { self.tintColor = color return self } @discardableResult public func tint(_ color: Int) -> Self { tint(color.color) } @discardableResult public func tint(_ binding: State<UIColor>) -> Self { binding.listen { [weak self] in self?.tint($0) } return tint(binding.wrappedValue) } @discardableResult public func tint(_ binding: State<Int>) -> Self { binding.listen { [weak self] in self?.tint($0) } return tint(binding.wrappedValue) } } #endif
24.5
78
0.591189
1ad6ff88e20d3ff2c2270100d7ac46311d3a5e1d
6,137
// // CesiumKitController.swift // CesiumKit // // Created by Ryan Walklin on 6/01/2016. // Copyright © 2016 Test Toast. All rights reserved. // import Foundation import MetalKit import CesiumKit class CesiumKitController: NSObject, MTKViewDelegate { fileprivate let _globe: CesiumGlobe! fileprivate let _view: MTKView //private let _viewportOverlay: ViewportQuad fileprivate let _fontName = "HelveticaNeue" fileprivate let _fontSize: Float = 36 init (view: MTKView) { _view = view _view.device = MTLCreateSystemDefaultDevice() _view.colorPixelFormat = PixelFormat.bgra8Unorm.toMetal() _view.depthStencilPixelFormat = PixelFormat.depth32FloatStencil8.toMetal() _view.framebufferOnly = false _view.preferredFramesPerSecond = 60 _view.autoResizeDrawable = true let options = CesiumOptions( //clock: Clock(multiplier: 600), clock: Clock(clockStep: .systemClock, isUTC: false), imageryProvider: nil, terrain: false, lighting: true, skyBox: true, fog: true, scene3DOnly: true ) _globe = CesiumGlobe(view: _view, options: options) _globe.scene.imageryLayers.addImageryProvider(BingMapsImageryProvider(key: Constants.BING_MAPS_KEY)) //_globe.scene.imageryLayers.addImageryProvider(TileCoordinateImageryProvider()) _globe.scene.camera.constrainedAxis = Cartesian3.unitZ //Flat ocean view /*_globe.scene.camera.setView( orientation: .headingPitchRoll(heading: 0.0, pitch: 0.0, roll: 0.0), destination: .cartesian(Cartesian3.fromDegrees(longitude: 0.0, latitude: 0.0, height: 100)) )*/ // Everest _globe.scene.camera.lookAt(Cartesian3.fromDegrees(longitude: 86.95278, latitude: 28.288056, height: 10000), offset: HeadingPitchRange(heading: 180.0, pitch: 0, range: 5000)) // Murrumbeena //_globe.scene.camera.setView(position: Cartesian3.fromDegrees(longitude: 145.075, latitude: -37.892, height: 1000), heading: 0, pitch: 0, roll: 0) //Wellington, /*_globe.scene.camera.setView( orientation: .headingPitchRoll(heading: 0.0, pitch: 0.0, roll: 0.0), destination: .cartesian(Cartesian3.fromDegrees(longitude: 174.784356, latitude: -41.438928, height: 1000)) )*/ //_globe.scene.camera.viewRectangle(Rectangle(fromDegreesWest: 150, south: -90, east: 110, north: 20)) /*let viewportFabric = ColorFabricDescription(color: Color(fromRed: 1.0, green: 1.0, blue: 1.0, alpha: 0.8)) _viewportOverlay = ViewportQuad( rectangle: BoundingRectangle(x: 20, y: 20, width: 400, height: 400), material: Material(fromType: ColorMaterialType(fabric: viewportFabric)) ) _globe.scene.primitives.add(_viewportOverlay)*/ /*let labels = LabelCollection(scene: _globe.scene) labels.add( position: Cartesian3(x: 4.0, y: 5.0, z: 6.0), text: "A label" ) _globe.scene.primitives.add(labels)*/ /* let window = _globe.scene.addOffscreenQuad(width: 400, height: 400) let blue = Color(fromRed: 40/255, green: 144/255, blue: 252/255, alpha: 1.0) let viewportFabric = ColorFabricDescription(color: Color(fromRed: 40/255, green: 144/255, blue: 252/255, alpha: 1.0)) let material = Material(fromType: ColorMaterialType(fabric: viewportFabric)) window.addRectangle(Cartesian4(x: 50, y: 50, width: 50, height: 50), material: material) window.addString("Test", fontName: "HelveticaNeue", color: blue, pointSize: 20, rectangle: Cartesian4(x: 110, y: 50, width: 600, height: 50))*/ super.init() } func startRendering () { _view.isPaused = false } func stopRendering () { _view.isPaused = true } func draw(in view: MTKView) { _globe.scene.camera.moveForward(5.0) #if os(iOS) view.contentScaleFactor = 2.0 let scaleFactor = view.contentScaleFactor #elseif os(OSX) view.layer!.contentsScale = 2.0 let scaleFactor = view.layer!.contentsScale #endif let viewBoundsSize = view.bounds.size let renderWidth = viewBoundsSize.width * scaleFactor let renderHeight = viewBoundsSize.height * scaleFactor let renderSize = CGSize(width: renderWidth, height: renderHeight) #if os(OSX) //view.autoResizeDrawable = false //view.drawableSize = renderSize #endif _globe.render(renderSize) } func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { //_viewportOverlay.rectangle = BoundingRectangle(x: 20, y: 20, width: 200, height: 200) /*let scale = self.v!.backingScaleFactor let layerSize = view.bounds.size _metalView.metalLayer.contentsScale = scale _metalView.metalLayer.frame = CGRectMake(0, 0, layerSize.width, layerSize.height) _metalView.metalLayer.drawableSize = CGSizeMake(layerSize.width * scale, layerSize.height * scale)*/ } func handleMouseDown (_ button: MouseButton, position: Cartesian2, modifier: KeyboardEventModifier?) { _globe.eventHandler.handleMouseDown(button, position: position, modifier: modifier) } func handleMouseMove (_ button: MouseButton, position: Cartesian2, modifier: KeyboardEventModifier?) { _globe.eventHandler.handleMouseMove(button, position: position, modifier: modifier) } func handleMouseUp (_ button: MouseButton, position: Cartesian2, modifier: KeyboardEventModifier?) { _globe.eventHandler.handleMouseMove(button, position: position, modifier: modifier) } func handleWheel (_ deltaX: Double, deltaY: Double) { _globe.eventHandler.handleWheel(deltaX, deltaY: deltaY) } }
39.850649
181
0.640867
0852d474ff3a514716b588b39899beaf34f08f6d
3,180
// // LoadingVIew.swift // Hex // // Created by Giang Nguyenn on 3/18/21. // import SwiftUI struct LoadingView: View { @EnvironmentObject var viewRouter: ViewRouter @EnvironmentObject var audioManager: AudioManager @State var game: OnlineGame private let backgroundColor = Color(red: 0.83984, green: 0.90625, blue: 0.7265625, opacity: 1) private let buttonFontSize: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 60 : 30 private let gameTitle: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 20 : 10 private let playerTurnFontSize: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 50 : 25 private let hunterGreen = Color(red: 0.15625, green: 0.3125, blue: 0.1796875, opacity: 0.5) @AppStorage("musicOn") var musicOn = false @AppStorage("soundOn") var soundOn = false var body: some View { GeometryReader { geometry in Rectangle().foregroundColor(backgroundColor).ignoresSafeArea().zIndex(-1) Text("Back").font(Font.custom("PressStart2P-Regular", size: geometry.size.width / buttonFontSize)) .foregroundColor(.black) .frame(maxWidth: .infinity, alignment: .leading) .padding() .onTapGesture { audioManager.playSound("MouseClick", type: "mp3") } if game.ready { VStack { Text("Found you a worthy contender") .font(Font.custom("PressStart2P-Regular", size: geometry.size.width / buttonFontSize)) .position(x: geometry.size.width / 2, y: geometry.size.height / 4) .foregroundColor(.black) Image("notalkweangy") .scaleEffect( geometry.size.width / 2048) .position(x: geometry.size.width / 2, y: geometry.size.height / 2) Image(uiImage: UIImage(fromDiskWithFileName: "avatar")!) } } else { let random = Bool.random() Text("Back").font(Font.custom("PressStart2P-Regular", size: geometry.size.width / buttonFontSize)) .padding() .foregroundColor(.black) .frame(maxWidth: .infinity, alignment: .topLeading) .onTapGesture { audioManager.playSound("MouseClick", type: "mp3") game.exitMatch() viewRouter.currentScreen = .welcome } VStack { Image(random ? "redwiz" : "bluewiz").spinning().scaleEffect(geometry.size.width / 1350) Text("Looking for a worthy contender...") .font(Font.custom("PressStart2P-Regular", size: geometry.size.width / 40)) .foregroundColor(.black) } .position(x: geometry.size.width / 2, y: geometry.size.height / 2) } } } } struct LoadingView_Previews: PreviewProvider { static var previews: some View { LoadingView(game: OnlineGame()) } }
43.561644
114
0.560692
1433ebd8172b8430718d5b0e0ec7608d52253fa0
497
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class a<T where g:A{class A{let b={let a{let g=e<f{let c{class A{class d{class a{class n{func p(){{}for{
49.7
104
0.734406
e2e2bfb97dd36b3e7d9c05782209b13a5dc6dbcb
452
import Vaux extension HTML { func inlineBlock() -> HTML { return style([StyleAttribute(key: "display", value: "inline-block")]) } func floatRight() -> HTML { style([StyleAttribute(key: "float", value: "right")]) } func iconStyleAttributes(width: Int) -> HTML { return style([StyleAttribute(key: "width", value: "\(width)px"), StyleAttribute(key: "height", value: "auto")]) } }
26.588235
77
0.575221
1e770e58dd90fa0c8cdeac85e704fe3af0e6be8c
3,629
import UIKit import QuartzCore class ViewController: UIViewController { @IBOutlet var bgImageView: UIImageView! @IBOutlet var summaryIcon: UIImageView! @IBOutlet var summary: UILabel! @IBOutlet var flightNr: UILabel! @IBOutlet var gateNr: UILabel! @IBOutlet var departingFrom: UILabel! @IBOutlet var arrivingTo: UILabel! @IBOutlet var planeImage: UIImageView! @IBOutlet var flightStatus: UILabel! @IBOutlet var statusBanner: UIImageView! //MARK: view controller methods override func viewDidLoad() { super.viewDidLoad() //adjust ui summary.addSubview(summaryIcon) summaryIcon.center.y = summary.frame.size.height/2 //start rotating the flights changeFlightDataTo(londonToParis) let rect = CGRect(x: 0.0, y: -70.0, width: view.bounds.width, height: 50.0) let emitter = CAEmitterLayer() emitter.frame = rect view.layer.addSublayer(emitter) emitter.emitterShape = kCAEmitterLayerRectangle emitter.emitterPosition = CGPoint(x: rect.width/2, y: rect.height/2) emitter.emitterSize = rect.size let emitterCell = CAEmitterCell() emitterCell.contents = UIImage(named: "flake.png")?.cgImage emitterCell.birthRate = 150 emitterCell.lifetime = 3.5 emitterCell.yAcceleration = 70.0 emitterCell.xAcceleration = 10.0 emitterCell.velocity = 20.0 emitterCell.emissionLongitude = .pi * -0.5 emitterCell.velocityRange = 200.0 emitterCell.emissionRange = .pi * 0.5 emitterCell.color = UIColor(red: 0.9, green: 1.0, blue: 1.0, alpha: 1.0).cgColor emitterCell.redRange = 0.1 emitterCell.greenRange = 0.1 emitterCell.blueRange = 0.1 emitterCell.scale = 0.8 emitterCell.scaleRange = 0.8 emitterCell.scaleSpeed = -0.15// The scaleSpeed property above instructs your particles to scale down by 15% of their original size per second emitterCell.alphaRange = 0.75 emitterCell.alphaSpeed = -0.15 emitterCell.emissionLongitude = -.pi emitterCell.lifetimeRange = 1.0 //cell #2 let cell2 = CAEmitterCell() cell2.contents = UIImage(named: "flake2.png")?.cgImage cell2.birthRate = 50 cell2.lifetime = 2.5 cell2.lifetimeRange = 1.0 cell2.yAcceleration = 50 cell2.xAcceleration = 50 cell2.velocity = 80 cell2.emissionLongitude = .pi cell2.velocityRange = 20 cell2.emissionRange = .pi * 0.25 cell2.scale = 0.8 cell2.scaleRange = 0.2 cell2.scaleSpeed = -0.1 cell2.alphaRange = 0.35 cell2.alphaSpeed = -0.15 cell2.spin = .pi cell2.spinRange = .pi //cell #3 let cell3 = CAEmitterCell() cell3.contents = UIImage(named: "flake3.png")?.cgImage cell3.birthRate = 20 cell3.lifetime = 7.5 cell3.lifetimeRange = 1.0 cell3.yAcceleration = 20 cell3.xAcceleration = 10 cell3.velocity = 40 cell3.emissionLongitude = .pi cell3.velocityRange = 50 cell3.emissionRange = .pi * 0.25 cell3.scale = 0.8 cell3.scaleRange = 0.2 cell3.scaleSpeed = -0.05 cell3.alphaRange = 0.5 cell3.alphaSpeed = -0.05 emitter.emitterCells = [emitterCell, cell2, cell3] } //MARK: custom methods func changeFlightDataTo(_ data: FlightData) { // populate the UI with the next flight's data summary.text = data.summary flightNr.text = data.flightNr gateNr.text = data.gateNr departingFrom.text = data.departingFrom arrivingTo.text = data.arrivingTo flightStatus.text = data.flightStatus bgImageView.image = UIImage(named: data.weatherImageName) } }
28.131783
146
0.677873
9c568cc0c2dfdfef4020a8504c0ca6c3b67e0a87
11,004
// // Created by Manuel Vrhovac on 13/01/2019. // Copyright © 2018 Manuel Vrhovac. All rights reserved. // import Foundation import UIKit import AVFoundation import AVKit import RxSwift import RxCocoa class ReviewViewController: UIViewController { // MARK: IBOutlets @IBOutlet private(set) weak var countLabel: UILabel! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var imageView: UIImageView! @IBOutlet private weak var slider: UISlider! @IBOutlet private weak var confirmButton: UIButton! @IBOutlet private weak var cancelButton: UIButton! @IBOutlet private weak var mainStack: UIStackView! @IBOutlet private(set) weak var cvStack: UIStackView! @IBOutlet private(set) weak var addMoreButton: UIButton! @IBOutlet private(set) weak var buttonStack: UIStackView! // MARK: Properties var viewModel: ReviewViewModel! var swipeGestureRecognizer: UISwipeGestureRecognizer! var leftSwipe: UISwipeGestureRecognizer! var collectionView: SmartLayoutCollectionView! var playerView: AVPlayerViewController! var bag = DisposeBag() // MARK: Calculated var removeButton: UIButton { return view.all(UIButton.self).last! } var mediaStack: UIStackView { return imageView.superview as! UIStackView } var currentIndex: Int { return viewModel.currentIndex.value } var player: AVPlayer! { get { return playerView.player } set { playerView?.player = newValue } } // MARK: - Init override func viewDidLoad() { super.viewDidLoad() confirmButton.layer.cornerRadius = 10.0 confirmButton.backgroundColor = view.tintColor cancelButton.layer.cornerRadius = 10.0 cancelButton.layer.addShadow(.black, o: 0.18, r: 14.0, d: 8.0) addMoreButton.layer.cornerRadius = 10.0 imageView.contentMode = .scaleAspectFit addMoreButton.isHidden = !viewModel.canAddMore leftSwipe = .init(target: self, action: #selector(swipe)) leftSwipe.direction = .right imageView.addGestureRecognizer(leftSwipe) swipeGestureRecognizer = .init(target: self, action: #selector(swipe)) swipeGestureRecognizer.direction = .left imageView.addGestureRecognizer(swipeGestureRecognizer) imageView.isUserInteractionEnabled = true collectionView = .init(spacing: 3.0, maximumItemWidth: 56) collectionView.flowLayout.scrollDirection = .horizontal cvStack.addArrangedSubview(collectionView) collectionView.registerNibForCellWith(reuseIdentifier: ItemCellView.selfID, bundle: bundle) collectionView.dataSource = self collectionView.contentInset = .zero collectionView.layoutMargins = .zero collectionView.backgroundColor = UIColor.black.withAlphaComponent(0.1) collectionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(cvTapped))) collectionView.layer.cornerRadius = 6.0 collectionView.alwaysBounceHorizontal = true collectionView.heightAnchor.constraint(equalToConstant: 60.0).isActive = true reload() playerView = .init() playerView.player = .init() playerView.view.backgroundColor = .clear mediaStack.addArrangedSubview(playerView.view) setupBindings() viewModel.assets.accept(viewModel.assets.value) } static func initi(viewModel: ReviewViewModel) -> ReviewViewController { let rvc = UIStoryboard.instantiateVC(ReviewViewController.self) rvc.viewModel = viewModel return rvc } func setupBindings() { let assetsChanged = viewModel .assets .share() let assetsCount = assetsChanged .map { $0.count } .share() let sliderValue = slider.rx.value .map { return Int($0 * Float(self.viewModel.numberOfItems - 1)) } .distinctUntilChanged() .share() bag.insert( viewModel.currentIndex .bind(onNext: indexChanged), viewModel.onFinish .bind(onNext: clearAndDismiss(result:)), assetsChanged .map { _ in } .bind(onNext: reload), assetsCount .map { $0 < 2 } .bind(to: removeButton.rx.isHidden), assetsCount .map { $0 < 2 } .bind(to: cvStack.rx.isHidden), assetsCount .map { $0 < 30 } .bind(to: slider.superview!.rx.isHidden), sliderValue .throttleMain(0.1) .bind(to: viewModel.currentIndex), sliderValue .debounceMain(0.1) .bind(onNext: indexChangedScroll), removeButton.rx.tap .delayMain(0.1) .bind(onNext: viewModel.removeCurrentAsset), cancelButton.rx.tap .delayMain(0.1) .bind(onNext: { self.viewModel.finish(.canceled) }), confirmButton.rx.tap .delayMain(0.1) .bind(onNext: { self.viewModel.finish(.confirmed) }), addMoreButton.rx.tap .delayMain(0.1) .bind(onNext: { self.viewModel.finish(.wantsMore) }) ) for button in [removeButton, cancelButton, confirmButton, addMoreButton] { button?.rx.tap.bind(onNext: { button?.animateShrinkGrow(duration: 0.2) }).disposed(by: bag) } } func preview(result: ReviewViewModel.PreviewResult) { var isImage = true switch result { case .image(let image): imageView.image = image playerView?.player?.pause() playerView?.player = .init() case .video(let url): isImage = false player = .init(url: url) } imageView.isHidden = !isImage playerView.view.isHidden = isImage } func clearAndDismiss(result: ReviewViewModel.Result) { if result != .confirmed { self.dismiss(animated: true, completion: nil) } } override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { super.dismiss(animated: flag, completion: completion) } func indexChanged(index: Int) { guard countLabel != nil else { return } countLabel.text = viewModel.countText if !slider.isTracking { slider.value = Float(index) / Float(viewModel.numberOfItems - 1) } viewModel.getPreview(atIndex: index) { result in guard index == self.viewModel.currentIndex.value else { return } self.preview(result: result) } } func reload() { self.collectionView?.reloadData() } func setViews(hidden: Bool) { [view, cancelButton, confirmButton].compactMapAs(UIView.self).forEach { $0.transform = .init(scaleX: hidden ? 0.7 : 1.0, y: hidden ? 0.7 : 1.0) $0.alpha = hidden ? 0.0 : 1.0 } } override func viewWillAppear(_ animated: Bool) { if viewModel.numberOfItems == 0 { dismiss(animated: false, completion: nil) return } setViews(hidden: true) UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseInOut, animations: { self.setViews(hidden: false) }, completion: nil) titleLabel.text = viewModel.title(forLanguage: "en") } // MARK: Interaction @objc func swipe(_ swipe: UISwipeGestureRecognizer) { let index = currentIndex + (swipe.direction == .left ? 1 : -1) viewModel.currentIndex.v = index.fixOverflow(count: viewModel.numberOfItems) } func indexChangedScroll(newIndex: Int) { UIView.animate(withDuration: 0.1) { self.collectionView.scrollToItem(at: .init(row: newIndex, section: 0), at: .centeredHorizontally, animated: false) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() delay(0.01) { self.moveSliderIfNeeded() } } @objc func cvTapped(tap: UITapGestureRecognizer) { let location = tap.location(in: collectionView) if let i = collectionView.indexPathForItem(at: location) { viewModel.currentIndex.accept(i.row) } } // MARK: Layout /// Rearanges the slider according to screen width. func moveSliderIfNeeded() { let cvContainer = collectionView.superview! // the container to be moved let landscape = mainStack.frame.width > 400 let isSeparate = mainStack.arrangedSubviews.contains(cvContainer) if landscape && isSeparate { cvContainer.removeFromSuperview() buttonStack.insertArrangedSubview(cvContainer, at: 1) } if !landscape && !isSeparate { cvContainer.removeFromSuperview() let sliderI = mainStack.arrangedSubviews .enumerated() .first(where: { $0.element === slider })? .offset mainStack.insertArrangedSubview(cvContainer, at: (sliderI ?? 2) + 1) } collectionView.heightAnchor.constraint(equalToConstant: 60.0).isActive = true self.view.layoutIfNeeded() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - extension ReviewViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.numberOfItems } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let ivm = viewModel.itemCellViewModel(atIndex: indexPath.row) ivm.fetchImage() let cell = collectionView.dequeue(ItemCellView.self, for: indexPath)! cell.configure(viewModel: ivm) cell.imageView.layer.cornerRadius = 4.0 cell.shadow.layer.cornerRadius = 4.0 return cell } }
32.556213
105
0.58815
33f5eef4816dc5f5421210542be672b3f45e3cd0
1,857
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** The feedback to be added to an element in the document. */ internal struct FeedbackInput: Codable, Equatable { /** An optional string identifying the user. */ public var userID: String? /** An optional comment on or description of the feedback. */ public var comment: String? /** Feedback data for submission. */ public var feedbackData: FeedbackDataInput // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case userID = "user_id" case comment = "comment" case feedbackData = "feedback_data" } /** Initialize a `FeedbackInput` with member variables. - parameter feedbackData: Feedback data for submission. - parameter userID: An optional string identifying the user. - parameter comment: An optional comment on or description of the feedback. - returns: An initialized `FeedbackInput`. */ public init( feedbackData: FeedbackDataInput, userID: String? = nil, comment: String? = nil ) { self.feedbackData = feedbackData self.userID = userID self.comment = comment } }
27.716418
82
0.67636
61363ee6c9e889d61f9ece69910cb6c4a44f613e
1,315
// // SwiftyPopover // // Created by Lukas Hakulin. // Copyright © 2020 Lukas Hakulin. All rights reserved. // import UIKit final class Example5ViewLayout: UIView { private let margin: CGFloat = 20.0 private let label = UILabel() init() { super.init(frame: .zero) addViews() setupViews() setupConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addViews() { addSubview(label) } private func setupViews() { backgroundColor = .white clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false label.textColor = .blue } private func setupConstraints() { label.translatesAutoresizingMaskIntoConstraints = false label.topAnchor.constraint(equalTo: topAnchor, constant: margin).isActive = true label.rightAnchor.constraint(equalTo: rightAnchor, constant: -margin).isActive = true label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -margin).isActive = true label.leftAnchor.constraint(equalTo: leftAnchor, constant: margin).isActive = true } } extension Example5ViewLayout { func setTitle(text: String) { label.text = text } }
24.351852
95
0.660837
16418c8afa819d8418ffe31450eef796e4d3f4e6
3,018
// // Entity+Album.swift // MusicshotCore // // Created by 林達也 on 2018/03/04. // Copyright © 2018年 林達也. All rights reserved. // import Foundation import RealmSwift import AppleMusicKit import MusicshotUtility extension Entity { @objc(EntityAlbum) public final class Album: Object, AppleMusicKit.Album { public typealias Artwork = Entity.Artwork public typealias EditorialNotes = Entity.EditorialNotes public typealias PlayParameters = Entity.PlayParameters public typealias Identifier = Tagged<Album, String> public var id: Identifier { return Identifier(rawValue: _id) } @objc private dynamic var _id: String = "" @objc public private(set) dynamic var artistName: String = "" @objc public private(set) dynamic var contentRating: String? @objc public private(set) dynamic var copyright: String = "" @objc public private(set) dynamic var editorialNotes: Entity.EditorialNotes? @objc public private(set) dynamic var isComplete: Bool = false @objc public private(set) dynamic var isSingle: Bool = false @objc public private(set) dynamic var name: String = "" @objc public private(set) dynamic var playParams: Entity.PlayParameters? @objc public private(set) dynamic var trackCount: Int = -1 public var artwork: Entity.Artwork { return _artwork } @objc private dynamic var _artwork: Entity.Artwork! public var genreNames: [String] { return Array(_genreNames) } private let _genreNames = List<String>() public var trackNumber: Int? { return _trackNumber.value } private let _trackNumber = RealmOptional<Int>() @objc private dynamic var _releaseDate: String = "" @objc private dynamic var _url: String = "" @objc override public class func primaryKey() -> String? { return "_id" } public convenience init( id: Identifier, artistName: String, artwork: Entity.Artwork, contentRating: String?, copyright: String, editorialNotes: Entity.EditorialNotes?, genreNames: [String], isComplete: Bool, isSingle: Bool, name: String, releaseDate: String, playParams: Entity.PlayParameters?, trackCount: Int, url: String ) throws { self.init() self._id = id.rawValue self.artistName = artistName self._artwork = artwork self.contentRating = contentRating self.copyright = copyright self.editorialNotes = editorialNotes self._genreNames.append(objectsIn: genreNames) self.isComplete = isComplete self.isSingle = isSingle self.name = name self.playParams = playParams self._releaseDate = releaseDate self.trackCount = trackCount self._url = url } } }
36.361446
84
0.628562
e0ba4990ed80d0c6a1b6cefe7beb6716357104fc
26,687
// // String+Extension.swift // JQTools // // Created by 杨锴 on 2020/3/15. // import Foundation import CommonCrypto public extension String{ private static let random_str_characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" enum JQSafeBase64Type { ///加密 case encode ///解密 case decode } enum HMACAlgorithm { case MD5, SHA1, SHA224, SHA256, SHA384, SHA512 func toCCHmacAlgorithm() -> CCHmacAlgorithm { var result: Int = 0 switch self { case .MD5: result = kCCHmacAlgMD5 case .SHA1: result = kCCHmacAlgSHA1 case .SHA224: result = kCCHmacAlgSHA224 case .SHA256: result = kCCHmacAlgSHA256 case .SHA384: result = kCCHmacAlgSHA384 case .SHA512: result = kCCHmacAlgSHA512 } return CCHmacAlgorithm(result) } func digestLength() -> Int { var result: CInt = 0 switch self { case .MD5: result = CC_MD5_DIGEST_LENGTH case .SHA1: result = CC_SHA1_DIGEST_LENGTH case .SHA224: result = CC_SHA224_DIGEST_LENGTH case .SHA256: result = CC_SHA256_DIGEST_LENGTH case .SHA384: result = CC_SHA384_DIGEST_LENGTH case .SHA512: result = CC_SHA512_DIGEST_LENGTH } return Int(result) } } // MARK: -- Static /// 获取字符串宽度 static func jq_getWidth(text: String, height: CGFloat, font: CGFloat) -> CGFloat { let text = text as NSString let rect = text.boundingRect(with: CGSize(width: CGFloat(Int.max), height: height), options: .usesLineFragmentOrigin, attributes: [.font : UIFont.systemFont(ofSize: font)], context: nil) return rect.size.width } /// 从文本中提取所有链接 /// - Returns: 提取的url func jq_pickUpUrls() -> [String] { var urls = [String]() // 创建一个正则表达式对象 do { let dataDetector = try NSDataDetector(types:NSTextCheckingTypes(NSTextCheckingResult.CheckingType.link.rawValue)) // 匹配字符串,返回结果集 let res = dataDetector.matches(in: self,options: NSRegularExpression.MatchingOptions(rawValue: 0),range: NSMakeRange(0, self.count)) // 取出结果 for checkingRes in res { urls.append((self as NSString).substring(with: checkingRes.range)) } } catch { print(error) } return urls } /// 从文本中提取所有时间 /// - Returns: 提取的时间 func jq_pickUpDate() -> [String] { var urls = [String]() // 创建一个正则表达式对象 do { let dataDetector = try NSDataDetector(types:NSTextCheckingTypes(NSTextCheckingResult.CheckingType.date.rawValue)) // 匹配字符串,返回结果集 let res = dataDetector.matches(in: self,options: NSRegularExpression.MatchingOptions(rawValue: 0),range: NSMakeRange(0, self.count)) // 取出结果 for checkingRes in res { urls.append((self as NSString).substring(with: checkingRes.range)) } } catch { print(error) } return urls } /// 从文本中提取所有电话号码 /// - Returns: 提取的电话号码 func jq_pickUpPhone() -> [String] { var urls = [String]() // 创建一个正则表达式对象 do { let dataDetector = try NSDataDetector(types:NSTextCheckingTypes(NSTextCheckingResult.CheckingType.phoneNumber.rawValue)) // 匹配字符串,返回结果集 let res = dataDetector.matches(in: self,options: NSRegularExpression.MatchingOptions(rawValue: 0),range: NSMakeRange(0, self.count)) // 取出结果 for checkingRes in res { urls.append((self as NSString).substring(with: checkingRes.range)) } } catch { print(error) } return urls } ///获取字符串高度 static func jq_getHeight(text: String, width: CGFloat, font: CGFloat) -> CGFloat { let text = text as NSString let rect = text.boundingRect(with: CGSize(width: width, height: CGFloat(Int.max)), options: .usesLineFragmentOrigin, attributes: [.font : UIFont.systemFont(ofSize: font)], context: nil) return rect.size.height } ///获取字符串高度(带font) static func jq_getHeightwithFont(text: String, width: CGFloat, font: UIFont) -> CGFloat { let text = text as NSString let rect = text.boundingRect(with: CGSize(width: width, height: CGFloat(Int.max)), options: .usesLineFragmentOrigin, attributes: [.font : font], context: nil) return rect.size.height } ///获取指定长度的随机字符串 static func jq_randomStr(len : Int) -> String{ var ranStr = "" for _ in 0..<len { let index = Int(arc4random_uniform(UInt32(random_str_characters.count))) ranStr.append(random_str_characters[random_str_characters.index(random_str_characters.startIndex, offsetBy: index)]) } return ranStr } /// 指定范围随机数值 func jq_randomNumber(start: Int, end: Int) ->() ->Int? { //根据参数初始化可选值数组 var nums = [Int](); for i in start...end{ nums.append(i) } func randomMan() -> Int! { if !nums.isEmpty { //随机返回一个数,同时从数组里删除 let index = Int(arc4random_uniform(UInt32(nums.count))) return nums.remove(at: index) }else { //所有值都随机完则返回nil return nil } } return randomMan } // MARK: -- Instance Method ///将 String/Data 类型转换成UnsafeMutablePointer<UInt8>类型 func jq_mutableBytes(_ clouse:((UnsafeMutablePointer<UInt8>)->Void)?){ var data = self.data(using: .utf8)! data.withUnsafeMutableBytes({ (bytes: UnsafeMutablePointer<UInt8>) -> Void in //bytes即为指针地址 print("指针地址:\(bytes)") //通过指针移动来取值(赋值也是可以的) var bytesStart = bytes for _ in 0..<6 { print(bytesStart.pointee) bytesStart += 1 } clouse?(bytes) }) } ///16进制字符串转Data func jq_hexData() -> Data? { var data = Data(capacity: count / 2) let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive) regex.enumerateMatches(in: self, range: NSMakeRange(0, utf16.count)) { match, flags, stop in let byteString = (self as NSString).substring(with: match!.range) var num = UInt8(byteString, radix: 16)! data.append(&num, count: 1) } guard data.count > 0 else { return nil } return data } func jq_utf8Data()-> Data? { return self.data(using: .utf8) } func jq_subString(sub:String)->(index:NSInteger,length:NSInteger){ if let range = self.range(of:sub) { let startPos = self.distance(from: self.startIndex, to: range.lowerBound) let endPos = self.distance(from: self.startIndex, to: range.upperBound) return(startPos,endPos) } return (0,0) } subscript(start:Int, length:Int) -> String{ get{ let index1 = self.index(self.startIndex, offsetBy: start) let index2 = self.index(index1, offsetBy: length) let range = Range(uncheckedBounds: (lower: index1, upper: index2)) return self.substring(with: range) } set{ let tmp = self var s = "" var e = "" for (idx, item) in tmp.enumerated() { if(idx < start) { s += "\(item)" } if(idx >= start + length) { e += "\(item)" } } self = s + newValue + e } } subscript(index:Int) -> String { get{ return String(self[self.index(self.startIndex, offsetBy: index)]) } set{ let tmp = self self = "" for (idx, item) in tmp.enumerated() { if idx == index { self += "\(newValue)" }else{ self += "\(item)" } } } } @available(*,deprecated,message: "废弃:建议使用jq_subRange") func jq_nsRange(from range: Range<String.Index>) -> NSRange { let from = range.lowerBound.samePosition(in: utf16) let to = range.upperBound.samePosition(in: utf16) return NSRange(location: utf16.distance(from: utf16.startIndex, to: from!), length: utf16.distance(from: from!, to: to!)) } /// 获取子字符串的NSRange func jq_subRange(_ subText:String)->NSRange{ let range = self.range(of: subText) let from = range?.lowerBound.samePosition(in: utf16) let to = range?.upperBound.samePosition(in: utf16) return NSRange(location: utf16.distance(from: utf16.startIndex, to: from!), length: utf16.distance(from: from!, to: to!)) } /// 将字符串转换为字典类型 @available(*,deprecated,message: "废弃") func toDict() -> [String : Any]?{ let data = self.data(using: String.Encoding.utf8) if let dict = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : Any] { return dict } return nil } /// 将字符串转换为字典类型 func jq_toDict() -> [String : Any]?{ let data = self.data(using: String.Encoding.utf8) if let dict = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : Any] { return dict } return nil } ///JSONString转换为数组 static func jq_toArray(jsonString:String) ->NSArray{ let jsonData:Data = jsonString.data(using: .utf8)! let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) if array != nil { return array as! NSArray } return array as! NSArray } ///字符串分割成数组 func jq_toArray(character:String) -> Array<String>{ let array : Array = components(separatedBy: character) return array } /// NSRange 转 Range @available(*,deprecated,message: "废弃") func jq_range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } ///去掉首尾空格 后 指定开头空格数 func jq_beginSpaceNum(num: Int) -> String { var beginSpace = "" for _ in 0..<num { beginSpace += " " } return beginSpace + self.jq_removeHeadAndTailSpacePro } ///配合 TextDelegate -> shouldChangeCharactersIn @available(*,deprecated,message: "废弃:使用Textfield 扩展") func jq_filterDecimals(replacementString:String,range:NSRange,limit:NSInteger = 2)->Bool{ let futureString: NSMutableString = NSMutableString(string: self) futureString.insert(replacementString, at: range.location) var flag = 0 let limited = limit//小数点后需要限制的个数 if !futureString.isEqual(to: "") { for i in stride(from: (futureString.length - 1), through: 0, by: -1) { let char = Character(UnicodeScalar(futureString.character(at: i))!) if char == "." { if flag > limited {return false} break } flag += 1 } } return true } ///适配Web,填充HTML的完整 func jq_wrapHtml()-> String{ return "<html><head><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><style>*{ width: 100%; margin: 0; padding: 0 3; box-sizing: border-box;} img{ width: 100%;}</style></head><body>\(self)</body></html>" } /// 适配Web,JS代码,WKWebView代理didFinish执行 /// /* /// webView.evaluateJavaScript('') /// */ func jq_adaptJS()->String{ return """ document.createElement('meta');script.name = 'viewport';script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";document.getElementsByTagName('head')[0].appendChild(script);var style = document.createElement('style');style.type='text/css';style.innerHTML='body{width:100%;height:auto;margin:auto;background-color:#ffffff}img{max-width:100%}p{word-wrap: break-word;color: #222;list-style-position: inside;list-style-type: square;margin-top: 17px;font-size: 18px;line-height: 1.76;border: none;outline: none;display: block;margin-block-start: 1em;margin-block-end: 1em;margin-inline-start: 0px;margin-inline-end: 0px;} p img {margin-bottom: -9px}';document.body.appendChild(style); """ } /// 将HTML 转化为富文本格式 /// - Parameter lossy: 是否损耗转化 /// - Returns: 返回富文本 func jq_htmlToAttibute(lossy:Bool = false)->NSMutableAttributedString?{ if let data = self.data(using: .unicode, allowLossyConversion: lossy){ do { let attribute = try NSMutableAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil) return attribute } catch { return nil } }else{ return nil } } ///JsonString->字典 func jq_dictionaryFromJsonString() -> Any? { let jsonData = self.data(using: String.Encoding.utf8) if jsonData != nil { let dic = try? JSONSerialization.jsonObject(with: jsonData!, options: []) if dic != nil { return dic }else { return nil } }else { return nil } } /// 手机号转138****6372 func jq_blotOutPhone() -> String{ if self.count != 11{ print("传入手机号格式错误") return "" }else{ let befor = prefix(3) let last = suffix(4) return befor + "****" + last } } ///将原始的url编码为合法的url func jq_urlEncoded() -> String { let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) return encodeUrlString ?? "" } ///将编码后的url转换回原始的url func jq_urlDecoded() -> String { return self.removingPercentEncoding ?? "" } ///获取子字符串 func jq_substingInRange(_ r: Range<Int>) -> String? { if r.lowerBound < 0 || r.upperBound > self.count { return nil } let startIndex = self.index(self.startIndex, offsetBy:r.lowerBound) let endIndex = self.index(self.startIndex, offsetBy:r.upperBound) return String(self[startIndex..<endIndex]) } ///时间转换为Date func jq_toDate(format:String = "YYYY-MM-dd") ->Date?{ let dateformatter = DateFormatter() dateformatter.dateFormat = format dateformatter.timeZone = TimeZone.current return dateformatter.date(from: self) } /// 将HTML标签中<>去除 func jq_filterFromHTML(_ htmlString:String)->String{ var html = htmlString let scanner = Scanner(string: htmlString) let text:String = "" while scanner.isAtEnd == false { scanner.scanUpTo("<", into: nil) scanner.scanUpTo(">", into: nil) html = htmlString.replacingOccurrences(of:"\(text)>", with: "") } return html } /// 将HTML标签中<>去除 func jq_filterFromHTML_1()->String{ do { let regularExpretion = try NSRegularExpression(pattern: "<[^>]*>|\n", options: .caseInsensitive) let html = regularExpretion.stringByReplacingMatches(in: self, options: .reportProgress, range: NSRange(location: 0, length: self.count), withTemplate: "") return html } catch { return "" } } ///减少内存(截取) func jq_substring(from index: Int) -> String { if self.count > index { let startIndex = self.index(self.startIndex, offsetBy: index) let subString = self[startIndex..<self.endIndex] return String(subString) } else { return self } } ///减少内存(截取) func jq_substring(to index: Int) -> String { if self.count > index { let endIndex = self.index(self.startIndex, offsetBy: index) let subString = self[self.startIndex..<endIndex] return String(subString) } else { return self } } ///转化为Base64 func jq_safeBase64(type: JQSafeBase64Type) -> String { var base64Str: String! if type == .encode { base64Str = self.replacingOccurrences(of: "+", with: "-") base64Str = base64Str.replacingOccurrences(of: "/", with: "_") base64Str = base64Str.replacingOccurrences(of: "=", with: "") }else { base64Str = self.replacingOccurrences(of: "-", with: "+") base64Str = base64Str.replacingOccurrences(of: "_", with: "/") let mod = base64Str.count % 4 if mod > 0 { base64Str += "====".jq_substring(to: mod) } } return base64Str } ///base64 转Data func jq_base64ToData()->Data?{ if self.contains("%") { return Data(base64Encoded: self.removingPercentEncoding!) } return Data(base64Encoded: self) } ///MD5 func jq_md5String() -> String { let str = self.cString(using: String.Encoding.utf8) let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0 ..< digestLen { hash.appendFormat("%02x", result[i]) } result.deinitialize(count: digestLen) return String(format: hash as String) } ///获取字符串拼音 func jq_getPinyin() -> String { let str = NSMutableString(string: self) CFStringTransform(str as CFMutableString, nil, kCFStringTransformMandarinLatin, false) CFStringTransform(str as CFMutableString, nil, kCFStringTransformStripDiacritics, false) return str.capitalized } ///获取字符串首字母大写 func jq_FirstLetter() -> String { let str = NSMutableString(string: self) CFStringTransform(str as CFMutableString, nil, kCFStringTransformMandarinLatin, false) CFStringTransform(str as CFMutableString, nil, kCFStringTransformStripDiacritics, false) let strPinYin = str.capitalized return strPinYin.jq_substring(to: 1) } /// 去除emoji表情 func jq_fliterEmoji()->String{ let a = try! JQ_RegexTool(.emoji) return a.replacingMatches(in: self, with: "") } //转译成字符值引用(NCR) func jq_toEncoded() -> String { var result:String = ""; for scalar in self.utf16 { //将十进制转成十六进制,不足4位前面补0 let tem = String().appendingFormat("%04x",scalar) result += "&#x\(tem);"; } return result } /// 精准身份证号码判断 func jq_idCard()->Bool{ let idArray = NSMutableArray() for i in 0..<18 { let range = NSMakeRange(i, 1); let subString = NSString(string: self).substring(with: range) idArray.add(subString) } let coefficientArray = NSArray(arrayLiteral:"7","9","10","5","8","4","2","1","6","3","7","9","10","5","8","4","2") let remainderArray = NSArray(arrayLiteral:"1","0","X","9","8","7","6","5","4","3","2") var sum = 0 for i in 0..<17 { let coefficient = NSInteger((coefficientArray[i] as! String))! let id = NSInteger((idArray[i] as! String))! sum += coefficient * id } let str = remainderArray[(sum % 11)] as! String let string = NSString(string: self).substring(from: 17) return str == string } ///判断是否为汉字 func jq_isValidateChinese() -> Bool { let match: String = "[\\u4e00-\\u9fa5]+$" return NSPredicate(format: "SELF MATCHES %@", match).evaluate(with:self) } ///获取文件/文件夹大小 func jq_getFileSize() -> UInt64 { var size: UInt64 = 0 let fileManager = FileManager.default var isDir: ObjCBool = false let isExists = fileManager.fileExists(atPath: self, isDirectory: &isDir) if isExists { if isDir.boolValue { let enumerator = fileManager.enumerator(atPath: self) for subPath in enumerator! { let fullPath = self.appending("/\(subPath)") do { let attr = try fileManager.attributesOfItem(atPath: fullPath) size += attr[FileAttributeKey.size] as! UInt64 } catch { print("error :\(error)") } } } else { do { let attr = try fileManager.attributesOfItem(atPath: self) size += attr[FileAttributeKey.size] as! UInt64 } catch { print("error :\(error)") } } } return size } func jq_hmac(algorithm: HMACAlgorithm, key: String) -> String { let cKey = key.cString(using: String.Encoding.utf8) let cData = self.cString(using: String.Encoding.utf8) // var result = [CUnsignedChar](count: Int(algorithm.digestLength()), repeatedValue: 0) // var hmacData:NSData = NSData(bytes: result, length: (Int(algorithm.digestLength()))) // var hmacBase64 = hmacData.base64EncodedStringWithOptions(NSData.Base64EncodingOptions.Encoding76CharacterLineLength) var result = [CUnsignedChar](repeating: 0, count: Int(algorithm.digestLength())) CCHmac(algorithm.toCCHmacAlgorithm(), cKey!, strlen(cKey!), cData!, strlen(cData!), &result) var hmacData: Data = Data(bytes: result, count: (Int(algorithm.digestLength()))) // var str = String(data: hmacData, encoding: String.Encoding.utf8)! // str += "\(self)" // let data = str.data(using: String.Encoding.utf8)! let data = self.data(using: String.Encoding.utf8)! hmacData.append(data) let hmacBase64 = hmacData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength76Characters) return String(hmacBase64) } // MARK: -- property ///去掉首尾空格 var jq_removeHeadAndTailSpace:String { let whitespace = NSCharacterSet.whitespaces return self.trimmingCharacters(in: whitespace) } ///去掉首尾空格 包括后面的换行 \n var jq_removeHeadAndTailSpacePro:String { let whitespace = NSCharacterSet.whitespacesAndNewlines return self.trimmingCharacters(in: whitespace) } ///去掉所有空格 var jq_removeAllSapce: String { return self.replacingOccurrences(of: " ", with: "", options: .literal, range: nil) } /// 判断是否为手机号 var jq_isPhone:Bool{ let pattern2 = "^1[0-9]{10}$" if NSPredicate(format: "SELF MATCHES %@", pattern2).evaluate(with: self) { return true } return false } /// 判断是否是身份证 var jq_isIdCard:Bool{ let pattern = "(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)"; let pred = NSPredicate(format: "SELF MATCHES %@", pattern) let isMatch:Bool = pred.evaluate(with: self) return isMatch } ///正则匹配用户密码6-18位数字和字母组合 var jq_isComplexPassword:Bool{ let pattern = "^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}" let pred = NSPredicate(format: "SELF MATCHES %@", pattern) let isMatch:Bool = pred.evaluate(with: self) return isMatch } /// 判断是否是邮箱 var jq_isEmail:Bool { let pattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" let pred = NSPredicate(format: "SELF MATCHES %@", pattern) let isMatch:Bool = pred.evaluate(with: self) return isMatch; } /// 判断是否是中文 var jq_isChinese:Bool { let pattern = "^[a-zA-Z\\u4E00-\\u9FA5]{1,20}" let pred = NSPredicate(format: "SELF MATCHES %@", pattern) let isMatch:Bool = pred.evaluate(with: self) return isMatch; } /// 判断是否是链接 var jq_isURL:Bool { let url = URL(string: self) return url != nil } /// 返回字数 var jq_count: Int { let string_NS = self as NSString return string_NS.length } var jq_isIP:Bool{ let pattern = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" let pred = NSPredicate(format: "SELF MATCHES %@", pattern) let isMatch:Bool = pred.evaluate(with: self) return isMatch; } /// 对Unicode编码进行转换 var jq_unicodeDescription : String{ return self.jq_stringByReplaceUnicode } var jq_stringByReplaceUnicode : String{ let tempStr1 = self.replacingOccurrences(of: "\\u", with: "\\U") let tempStr2 = tempStr1.replacingOccurrences(of: "\"", with: "\\\"") let tempStr3 = "\"".appending(tempStr2).appending("\"") let tempData = tempStr3.data(using: String.Encoding.utf8) var returnStr:String = "" do { returnStr = try PropertyListSerialization.propertyList(from: tempData!, options: [.mutableContainers], format: nil) as! String } catch { print(error) } return returnStr.replacingOccurrences(of: "\\n", with: "\n") } }
35.300265
735
0.564694
5d970c35e44a52d66e2ebe275c2371f91c147ebc
25,638
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest #if DEBUG @testable import RealmSwift #else import RealmSwift #endif import Foundation class RealmTests: TestCase { func testPath() { XCTAssertEqual(try! Realm(path: testRealmPath()).path, testRealmPath()) } func testReadOnly() { autoreleasepool { XCTAssertEqual(try! Realm().readOnly, false) try! Realm().write { try! Realm().create(SwiftIntObject.self, value: [100]) } } let readOnlyRealm = try! Realm(configuration: Realm.Configuration(path: defaultRealmPath(), readOnly: true)) XCTAssertEqual(true, readOnlyRealm.readOnly) XCTAssertEqual(1, readOnlyRealm.objects(SwiftIntObject).count) assertThrows(try! Realm(), "Realm has different readOnly settings") } func testOpeningInvalidPathThrows() { assertFails(Error.FileAccess) { try Realm(configuration: Realm.Configuration(path: "/dev/null/foo")) } } func testReadOnlyFile() { autoreleasepool { let realm = try! Realm(path: testRealmPath()) try! realm.write { realm.create(SwiftStringObject.self, value: ["a"]) } } let fileManager = NSFileManager.defaultManager() try! fileManager.setAttributes([ NSFileImmutable: NSNumber(bool: true) ], ofItemAtPath: testRealmPath()) // Should not be able to open read-write assertFails(Error.Fail) { try Realm(path: testRealmPath()) } assertSucceeds { let realm = try Realm(configuration: Realm.Configuration(path: self.testRealmPath(), readOnly: true)) XCTAssertEqual(1, realm.objects(SwiftStringObject).count) } try! fileManager.setAttributes([ NSFileImmutable: NSNumber(bool: false) ], ofItemAtPath: testRealmPath()) } func testReadOnlyRealmMustExist() { assertFails(Error.FileNotFound) { try Realm(configuration: Realm.Configuration(path: defaultRealmPath(), readOnly: true)) } } func testFilePermissionDenied() { autoreleasepool { let _ = try! Realm(path: testRealmPath()) } // Make Realm at test path temporarily unreadable let fileManager = NSFileManager.defaultManager() let permissions = try! fileManager.attributesOfItemAtPath(testRealmPath())[NSFilePosixPermissions] as! NSNumber try! fileManager.setAttributes([ NSFilePosixPermissions: NSNumber(int: 0000) ], ofItemAtPath: testRealmPath()) assertFails(Error.FilePermissionDenied) { try Realm(path: testRealmPath()) } try! fileManager.setAttributes([ NSFilePosixPermissions: permissions ], ofItemAtPath: testRealmPath()) } #if DEBUG func testFileFormatUpgradeRequiredButDisabled() { var config = Realm.Configuration() config.path = NSBundle(forClass: RealmTests.self).pathForResource("fileformat-pre-null.realm", ofType: nil)! config.disableFormatUpgrade = true assertFails(Error.FileFormatUpgradeRequired) { try Realm(configuration: config) } } #endif func testSchema() { let schema = try! Realm().schema XCTAssert(schema as AnyObject is Schema) XCTAssertEqual(1, schema.objectSchema.filter({ $0.className == "SwiftStringObject" }).count) } func testIsEmpty() { let realm = try! Realm() XCTAssert(realm.isEmpty, "Realm should be empty on creation.") realm.beginWrite() realm.create(SwiftStringObject.self, value: ["a"]) XCTAssertFalse(realm.isEmpty, "Realm should not be empty within a write transaction after adding an object.") realm.cancelWrite() XCTAssertTrue(realm.isEmpty, "Realm should be empty after canceling a write transaction that added an object.") realm.beginWrite() realm.create(SwiftStringObject.self, value: ["a"]) try! realm.commitWrite() XCTAssertFalse(realm.isEmpty, "Realm should not be empty after committing a write transaction that added an object.") } func testInit() { XCTAssertEqual(try! Realm(path: testRealmPath()).path, testRealmPath()) assertThrows(try! Realm(path: "")) } func testInitFailable() { autoreleasepool { _ = try! Realm() } NSFileManager.defaultManager().createFileAtPath(defaultRealmPath(), contents:"a".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false), attributes: nil) assertFails(Error.FileAccess) { _ = try Realm() XCTFail("Realm creation should have failed") } } func testInitInMemory() { autoreleasepool { let realm = inMemoryRealm("identifier") try! realm.write { realm.create(SwiftIntObject.self, value: [1]) return } } let realm = inMemoryRealm("identifier") XCTAssertEqual(realm.objects(SwiftIntObject).count, 0) try! realm.write { realm.create(SwiftIntObject.self, value: [1]) XCTAssertEqual(realm.objects(SwiftIntObject).count, 1) inMemoryRealm("identifier").create(SwiftIntObject.self, value: [1]) XCTAssertEqual(realm.objects(SwiftIntObject).count, 2) } let realm2 = inMemoryRealm("identifier2") XCTAssertEqual(realm2.objects(SwiftIntObject).count, 0) } func testInitCustomClassList() { let configuration = Realm.Configuration(path: Realm.Configuration.defaultConfiguration.path, objectTypes: [SwiftStringObject.self]) XCTAssert(configuration.objectTypes! is [SwiftStringObject.Type]) let realm = try! Realm(configuration: configuration) XCTAssertEqual(["SwiftStringObject"], realm.schema.objectSchema.map { $0.className }) } func testWrite() { try! Realm().write { self.assertThrows(try! Realm().beginWrite()) self.assertThrows(try! Realm().write { }) try! Realm().create(SwiftStringObject.self, value: ["1"]) XCTAssertEqual(try! Realm().objects(SwiftStringObject).count, 1) } XCTAssertEqual(try! Realm().objects(SwiftStringObject).count, 1) } func testDynamicWrite() { try! Realm().write { self.assertThrows(try! Realm().beginWrite()) self.assertThrows(try! Realm().write { }) try! Realm().dynamicCreate("SwiftStringObject", value: ["1"]) XCTAssertEqual(try! Realm().objects(SwiftStringObject).count, 1) } XCTAssertEqual(try! Realm().objects(SwiftStringObject).count, 1) } func testDynamicWriteSubscripting() { try! Realm().beginWrite() let object = try! Realm().dynamicCreate("SwiftStringObject", value: ["1"]) try! Realm().commitWrite() XCTAssertNotNil(object, "Dynamic Object Creation Failed") let stringVal = object["stringCol"] as! String XCTAssertEqual(stringVal, "1", "Object Subscripting Failed") } func testBeginWrite() { try! Realm().beginWrite() assertThrows(try! Realm().beginWrite()) try! Realm().cancelWrite() try! Realm().beginWrite() try! Realm().create(SwiftStringObject.self, value: ["1"]) XCTAssertEqual(try! Realm().objects(SwiftStringObject).count, 1) } func testCommitWrite() { try! Realm().beginWrite() try! Realm().create(SwiftStringObject.self, value: ["1"]) try! Realm().commitWrite() XCTAssertEqual(try! Realm().objects(SwiftStringObject).count, 1) try! Realm().beginWrite() } func testCancelWrite() { assertThrows(try! Realm().cancelWrite()) try! Realm().beginWrite() try! Realm().create(SwiftStringObject.self, value: ["1"]) try! Realm().cancelWrite() XCTAssertEqual(try! Realm().objects(SwiftStringObject).count, 0) try! Realm().write { self.assertThrows(self.realmWithTestPath().cancelWrite()) let object = try! Realm().create(SwiftStringObject) try! Realm().cancelWrite() XCTAssertTrue(object.invalidated) XCTAssertEqual(try! Realm().objects(SwiftStringObject).count, 0) } XCTAssertEqual(try! Realm().objects(SwiftStringObject).count, 0) } func testInWriteTransaction() { let realm = try! Realm() XCTAssertFalse(realm.inWriteTransaction) realm.beginWrite() XCTAssertTrue(realm.inWriteTransaction) realm.cancelWrite() try! realm.write { XCTAssertTrue(realm.inWriteTransaction) realm.cancelWrite() XCTAssertFalse(realm.inWriteTransaction) } realm.beginWrite() realm.invalidate() XCTAssertFalse(realm.inWriteTransaction) } func testAddSingleObject() { let realm = try! Realm() assertThrows(_ = realm.add(SwiftObject())) XCTAssertEqual(0, realm.objects(SwiftObject).count) var defaultRealmObject: SwiftObject! try! realm.write { defaultRealmObject = SwiftObject() realm.add(defaultRealmObject) XCTAssertEqual(1, realm.objects(SwiftObject).count) realm.add(defaultRealmObject) XCTAssertEqual(1, realm.objects(SwiftObject).count) } XCTAssertEqual(1, realm.objects(SwiftObject).count) let testRealm = realmWithTestPath() try! testRealm.write { self.assertThrows(_ = testRealm.add(defaultRealmObject)) } } func testAddWithUpdateSingleObject() { let realm = try! Realm() XCTAssertEqual(0, realm.objects(SwiftPrimaryStringObject).count) var defaultRealmObject: SwiftPrimaryStringObject! try! realm.write { defaultRealmObject = SwiftPrimaryStringObject() realm.add(defaultRealmObject, update: true) XCTAssertEqual(1, realm.objects(SwiftPrimaryStringObject).count) realm.add(SwiftPrimaryStringObject(), update: true) XCTAssertEqual(1, realm.objects(SwiftPrimaryStringObject).count) } XCTAssertEqual(1, realm.objects(SwiftPrimaryStringObject).count) let testRealm = realmWithTestPath() try! testRealm.write { self.assertThrows(_ = testRealm.add(defaultRealmObject, update: true)) } } func testAddMultipleObjects() { let realm = try! Realm() assertThrows(_ = realm.add([SwiftObject(), SwiftObject()])) XCTAssertEqual(0, realm.objects(SwiftObject).count) try! realm.write { let objs = [SwiftObject(), SwiftObject()] realm.add(objs) XCTAssertEqual(2, realm.objects(SwiftObject).count) } XCTAssertEqual(2, realm.objects(SwiftObject).count) let testRealm = realmWithTestPath() try! testRealm.write { self.assertThrows(_ = testRealm.add(realm.objects(SwiftObject))) } } func testAddWithUpdateMultipleObjects() { let realm = try! Realm() XCTAssertEqual(0, realm.objects(SwiftPrimaryStringObject).count) try! realm.write { let objs = [SwiftPrimaryStringObject(), SwiftPrimaryStringObject()] realm.add(objs, update: true) XCTAssertEqual(1, realm.objects(SwiftPrimaryStringObject).count) } XCTAssertEqual(1, realm.objects(SwiftPrimaryStringObject).count) let testRealm = realmWithTestPath() try! testRealm.write { self.assertThrows(_ = testRealm.add(realm.objects(SwiftPrimaryStringObject), update: true)) } } // create() tests are in ObjectCreationTests.swift func testDeleteSingleObject() { let realm = try! Realm() XCTAssertEqual(0, realm.objects(SwiftObject).count) assertThrows(_ = realm.delete(SwiftObject())) var defaultRealmObject: SwiftObject! try! realm.write { defaultRealmObject = SwiftObject() self.assertThrows(_ = realm.delete(defaultRealmObject)) XCTAssertEqual(0, realm.objects(SwiftObject).count) realm.add(defaultRealmObject) XCTAssertEqual(1, realm.objects(SwiftObject).count) realm.delete(defaultRealmObject) XCTAssertEqual(0, realm.objects(SwiftObject).count) } assertThrows(_ = realm.delete(defaultRealmObject)) XCTAssertEqual(0, realm.objects(SwiftObject).count) let testRealm = realmWithTestPath() assertThrows(_ = testRealm.delete(defaultRealmObject)) try! testRealm.write { self.assertThrows(_ = testRealm.delete(defaultRealmObject)) } } func testDeleteSequenceOfObjects() { let realm = try! Realm() XCTAssertEqual(0, realm.objects(SwiftObject).count) var objs: [SwiftObject]! try! realm.write { objs = [SwiftObject(), SwiftObject()] realm.add(objs) XCTAssertEqual(2, realm.objects(SwiftObject).count) realm.delete(objs) XCTAssertEqual(0, realm.objects(SwiftObject).count) } XCTAssertEqual(0, realm.objects(SwiftObject).count) let testRealm = realmWithTestPath() assertThrows(_ = testRealm.delete(objs)) try! testRealm.write { self.assertThrows(_ = testRealm.delete(objs)) } } func testDeleteListOfObjects() { let realm = try! Realm() XCTAssertEqual(0, realm.objects(SwiftCompanyObject).count) try! realm.write { let obj = SwiftCompanyObject() obj.employees.append(SwiftEmployeeObject()) realm.add(obj) XCTAssertEqual(1, realm.objects(SwiftEmployeeObject).count) realm.delete(obj.employees) XCTAssertEqual(0, obj.employees.count) XCTAssertEqual(0, realm.objects(SwiftEmployeeObject).count) } XCTAssertEqual(0, realm.objects(SwiftEmployeeObject).count) } func testDeleteResults() { let realm = try! Realm(path: testRealmPath()) XCTAssertEqual(0, realm.objects(SwiftCompanyObject).count) try! realm.write { realm.add(SwiftIntObject(value: [1])) realm.add(SwiftIntObject(value: [1])) realm.add(SwiftIntObject(value: [2])) XCTAssertEqual(3, realm.objects(SwiftIntObject).count) realm.delete(realm.objects(SwiftIntObject).filter("intCol = 1")) XCTAssertEqual(1, realm.objects(SwiftIntObject).count) } XCTAssertEqual(1, realm.objects(SwiftIntObject).count) } func testDeleteAll() { let realm = try! Realm() try! realm.write { realm.add(SwiftObject()) XCTAssertEqual(1, realm.objects(SwiftObject).count) realm.deleteAll() XCTAssertEqual(0, realm.objects(SwiftObject).count) } XCTAssertEqual(0, realm.objects(SwiftObject).count) } func testObjects() { try! Realm().write { try! Realm().create(SwiftIntObject.self, value: [100]) try! Realm().create(SwiftIntObject.self, value: [200]) try! Realm().create(SwiftIntObject.self, value: [300]) } XCTAssertEqual(0, try! Realm().objects(SwiftStringObject).count) XCTAssertEqual(3, try! Realm().objects(SwiftIntObject).count) assertThrows(try! Realm().objects(Object)) } func testDynamicObjects() { try! Realm().write { try! Realm().create(SwiftIntObject.self, value: [100]) try! Realm().create(SwiftIntObject.self, value: [200]) try! Realm().create(SwiftIntObject.self, value: [300]) } XCTAssertEqual(0, try! Realm().dynamicObjects("SwiftStringObject").count) XCTAssertEqual(3, try! Realm().dynamicObjects("SwiftIntObject").count) assertThrows(try! Realm().dynamicObjects("Object")) } func testDynamicObjectProperties() { try! Realm().write { try! Realm().create(SwiftObject) } let object = try! Realm().dynamicObjects("SwiftObject")[0] let dictionary = SwiftObject.defaultValues() XCTAssertEqual(object["boolCol"] as? NSNumber, dictionary["boolCol"] as! NSNumber?) XCTAssertEqual(object["intCol"] as? NSNumber, dictionary["intCol"] as! NSNumber?) XCTAssertEqual(object["floatCol"] as? NSNumber, dictionary["floatCol"] as! Float?) XCTAssertEqual(object["doubleCol"] as? NSNumber, dictionary["doubleCol"] as! Double?) XCTAssertEqual(object["stringCol"] as! String?, dictionary["stringCol"] as! String?) XCTAssertEqual(object["binaryCol"] as! NSData?, dictionary["binaryCol"] as! NSData?) XCTAssertEqual(object["dateCol"] as! NSDate?, dictionary["dateCol"] as! NSDate?) XCTAssertEqual(object["objectCol"]?.boolCol, false) } func testDynamicObjectOptionalProperties() { try! Realm().write { try! Realm().create(SwiftOptionalDefaultValuesObject) } let object = try! Realm().dynamicObjects("SwiftOptionalDefaultValuesObject")[0] let dictionary = SwiftOptionalDefaultValuesObject.defaultValues() XCTAssertEqual(object["optIntCol"] as? NSNumber, dictionary["optIntCol"] as! NSNumber?) XCTAssertEqual(object["optInt8Col"] as? NSNumber, dictionary["optInt8Col"] as! NSNumber?) XCTAssertEqual(object["optInt16Col"] as? NSNumber, dictionary["optInt16Col"] as! NSNumber?) XCTAssertEqual(object["optInt32Col"] as? NSNumber, dictionary["optInt32Col"] as! NSNumber?) XCTAssertEqual(object["optInt64Col"] as? NSNumber, dictionary["optInt64Col"] as! NSNumber?) XCTAssertEqual(object["optFloatCol"] as? NSNumber, dictionary["optFloatCol"] as! Float?) XCTAssertEqual(object["optDoubleCol"] as? NSNumber, dictionary["optDoubleCol"] as! Double?) XCTAssertEqual(object["optStringCol"] as! String?, dictionary["optStringCol"] as! String?) XCTAssertEqual(object["optNSStringCol"] as! String?, dictionary["optNSStringCol"] as! String?) XCTAssertEqual(object["optBinaryCol"] as! NSData?, dictionary["optBinaryCol"] as! NSData?) XCTAssertEqual(object["optDateCol"] as! NSDate?, dictionary["optDateCol"] as! NSDate?) XCTAssertEqual(object["optObjectCol"]?.boolCol, true) } func testObjectForPrimaryKey() { let realm = try! Realm() try! realm.write { realm.create(SwiftPrimaryStringObject.self, value: ["a", 1]) realm.create(SwiftPrimaryStringObject.self, value: ["b", 2]) } XCTAssertNotNil(realm.objectForPrimaryKey(SwiftPrimaryStringObject.self, key: "a")) // When this is directly inside the XCTAssertNil, it fails for some reason let missingObject = realm.objectForPrimaryKey(SwiftPrimaryStringObject.self, key: "z") XCTAssertNil(missingObject) } func testDynamicObjectForPrimaryKey() { let realm = try! Realm() try! realm.write { realm.create(SwiftPrimaryStringObject.self, value: ["a", 1]) realm.create(SwiftPrimaryStringObject.self, value: ["b", 2]) } XCTAssertNotNil(realm.dynamicObjectForPrimaryKey("SwiftPrimaryStringObject", key: "a")) XCTAssertNil(realm.dynamicObjectForPrimaryKey("SwiftPrimaryStringObject", key: "z")) } func testDynamicObjectForPrimaryKeySubscripting() { let realm = try! Realm() try! realm.write { realm.create(SwiftPrimaryStringObject.self, value: ["a", 1]) } let object = realm.dynamicObjectForPrimaryKey("SwiftPrimaryStringObject", key: "a") let stringVal = object!["stringCol"] as! String XCTAssertEqual(stringVal, "a", "Object Subscripting Failed!") } func testAddNotificationBlock() { let realm = try! Realm() var notificationCalled = false let token = realm.addNotificationBlock { _, realm in XCTAssertEqual(realm.path, self.defaultRealmPath()) notificationCalled = true } XCTAssertFalse(notificationCalled) try! realm.write {} XCTAssertTrue(notificationCalled) realm.removeNotification(token) } func testRemoveNotification() { let realm = try! Realm() var notificationCalled = false let token = realm.addNotificationBlock { (notification, realm) -> Void in XCTAssertEqual(realm.path, self.defaultRealmPath()) notificationCalled = true } realm.removeNotification(token) try! realm.write {} XCTAssertFalse(notificationCalled) } func testAutorefresh() { let realm = try! Realm() XCTAssertTrue(realm.autorefresh, "Autorefresh should default to true") realm.autorefresh = false XCTAssertFalse(realm.autorefresh) realm.autorefresh = true XCTAssertTrue(realm.autorefresh) // test that autoreresh is applied // we have two notifications, one for opening the realm, and a second when performing our transaction let notificationFired = expectationWithDescription("notification fired") let token = realm.addNotificationBlock { _, realm in XCTAssertNotNil(realm, "Realm should not be nil") notificationFired.fulfill() } dispatchSyncNewThread { let realm = try! Realm() try! realm.write { realm.create(SwiftStringObject.self, value: ["string"]) } } waitForExpectationsWithTimeout(1, handler: nil) realm.removeNotification(token) // get object let results = realm.objects(SwiftStringObject) XCTAssertEqual(results.count, Int(1), "There should be 1 object of type StringObject") XCTAssertEqual(results[0].stringCol, "string", "Value of first column should be 'string'") } func testRefresh() { let realm = try! Realm() realm.autorefresh = false // test that autoreresh is not applied // we have two notifications, one for opening the realm, and a second when performing our transaction let notificationFired = expectationWithDescription("notification fired") let token = realm.addNotificationBlock { _, realm in XCTAssertNotNil(realm, "Realm should not be nil") notificationFired.fulfill() } let results = realm.objects(SwiftStringObject) XCTAssertEqual(results.count, Int(0), "There should be 1 object of type StringObject") dispatchSyncNewThread { try! Realm().write { try! Realm().create(SwiftStringObject.self, value: ["string"]) return } } waitForExpectationsWithTimeout(1, handler: nil) realm.removeNotification(token) XCTAssertEqual(results.count, Int(0), "There should be 1 object of type StringObject") // refresh realm.refresh() XCTAssertEqual(results.count, Int(1), "There should be 1 object of type StringObject") XCTAssertEqual(results[0].stringCol, "string", "Value of first column should be 'string'") } func testInvalidate() { let realm = try! Realm() let object = SwiftObject() try! realm.write { realm.add(object) return } realm.invalidate() XCTAssertEqual(object.invalidated, true) try! realm.write { realm.add(SwiftObject()) return } XCTAssertEqual(realm.objects(SwiftObject).count, 2) XCTAssertEqual(object.invalidated, true) } func testWriteCopyToPath() { let realm = try! Realm() try! realm.write { realm.add(SwiftObject()) } let path = ((defaultRealmPath() as NSString).stringByDeletingLastPathComponent as NSString ) .stringByAppendingPathComponent("copy.realm") do { try realm.writeCopyToPath(path) } catch { XCTFail("writeCopyToPath failed") } autoreleasepool { let copy = try! Realm(path: path) XCTAssertEqual(1, copy.objects(SwiftObject).count) } try! NSFileManager.defaultManager().removeItemAtPath(path) } func testEquals() { let realm = try! Realm() XCTAssertTrue(try! realm == Realm()) let testRealm = realmWithTestPath() XCTAssertFalse(realm == testRealm) dispatchSyncNewThread { let otherThreadRealm = try! Realm() XCTAssertFalse(realm == otherThreadRealm) } } }
38.437781
119
0.632655
f9d214f34d2ef3d891fccf2a0bff87d46937b69c
666
// // VirtualContent.swift // EyeTrackingTest // // Created by Jason Shang on 10/29/21. // import ARKit import SceneKit /// For forwarding `ARSCNViewDelegate` messages to the object controlling the currently visible virtual content. protocol VirtualContentController: ARSCNViewDelegate { /// The root node for the virtual content. var contentNode: SCNNode? { get set } func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) } func makeController() -> VirtualContentController { return TransformVisualization() }
27.75
112
0.743243
1c425a3f031a337435cec4262006573598bd323e
2,189
// // AppDelegate.swift // TipCalculator // // Created by Nishant Mendiratta on 3/1/17. // Copyright © 2017 Nishant Mendiratta. 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.574468
285
0.756967
e65206a44a66546ca5bed5cbcf2e0129cd991ed6
7,658
// // HomeTableViewController.swift // ZhiHuSwift // // Created by YangJingping on 16/8/24. // Copyright © 2016年 YJP. All rights reserved. // import UIKit import SDWebImage import MJRefresh class HomeTableViewController: UIViewController,UITableViewDelegate,NavViewDelegate,UITableViewDataSource { let SectionViewIdentifier = "sectionviewidentifier" var headView:TopView! var tableView:UITableView! var navView:NavView! var isloading:Bool = false var homeModel:HomeModel = HomeModel() var dataArray:[HomeModel]?{ didSet{ tableView.reloadData() } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBarHidden = true } override func viewDidAppear(animated: Bool) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } //MARK: - viewdidload override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().statusBarHidden = false navigationController?.navigationBarHidden = true automaticallyAdjustsScrollViewInsets = false configTableView() fetchHomeData() } //MARK: - 配置tableView private func configTableView(){ tableView = UITableView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHieght), style:.Plain) tableView.registerNib(UINib(nibName: String(HomeCell), bundle: nil), forCellReuseIdentifier: "cell_id") tableView.registerClass(SectionView.classForCoder(), forHeaderFooterViewReuseIdentifier: SectionViewIdentifier) tableView.delegate = self tableView.dataSource = self tableView.rowHeight = 80 tableView.showsVerticalScrollIndicator = false view.addSubview(tableView) tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "footerRefresh") headView = TopView(frame: CGRect(x: 0, y: 0, width:ScreenWidth, height: 200)) tableView.tableHeaderView = headView navView = NavView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 64)) navView.delegate = self view.addSubview(navView) } //MARK: - 获取数据 func fetchHomeData(){ weak var weakSelf = self homeModel.loadLastedHomeData { () -> Void in weakSelf?.headView.imageTitle = weakSelf?.homeModel.loopImageTitles() weakSelf?.headView?.imagesUrl = weakSelf?.homeModel.loopImagesUrls() weakSelf?.headView?.imageNum = (weakSelf?.homeModel.numberOfLoopImages())! weakSelf?.tableView.reloadData() } } //MARK: - 左侧菜单 func leftMenu() { let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController as! BaseViewController rootVC.toggleDrawerSide(.Left, animated: true, completion: nil) } //MARK: - 刷新 func headerRefresh(){ isloading = true weak var weakSelf = self homeModel.loadLastedHomeData { () -> Void in weakSelf?.navView.indicator?.stopAnimating() weakSelf?.navView.indicator?.hidesWhenStopped = true weakSelf?.tableView.reloadData() weakSelf?.isloading = false } } func footerRefresh(){ weak var weakSelf = self homeModel.loadPreviousHomeData { () -> Void in weakSelf?.tableView.reloadData() weakSelf?.tableView.mj_footer.endRefreshing() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - Table view data source extension HomeTableViewController{ func numberOfSectionsInTableView(tableView: UITableView) -> Int { return homeModel.numberOfSections() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return homeModel.numberOfRowInSection(section) ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell_id", forIndexPath: indexPath) as! HomeCell let story = homeModel.storyAtIndexPath(indexPath) cell.titleContent.text = story.title cell.imgView.sd_setImageWithURL(NSURL(string: (story.images?.first)!), placeholderImage: UIImage(named: "placeholder.png")) return cell } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0{ return 0 } else{ return 40 } } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let secView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionViewIdentifier) as! SectionView secView.titleLabel?.text = homeModel.dateStringOfSection(section) return secView } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let story = homeModel.storyAtIndexPath(indexPath) let homeDetailVC = HomeDetailViewController() homeDetailVC.detailId = story.id homeDetailVC.homeModel = self.homeModel navigationController?.pushViewController(homeDetailVC, animated: true) tableView.deselectRowAtIndexPath(indexPath, animated: true) } //MARK: - ScrollView func scrollViewDidScroll(scrollView: UIScrollView) { let offY = scrollView.contentOffset.y if offY <= 0{ var rect = headView?.frame rect?.size.height = 200 - offY rect?.origin.y = offY headView?.topScrollView!.frame = rect! } if offY >= -90.0{ //circle的进度 let loadPercent = offY/(-50.0) if !isloading { navView.loadProgress = (loadPercent > 1.0 ? 1.0:loadPercent) } else{ navView.loadProgress = 0.0 } if offY < -50.0 && offY >= -90.0 && !scrollView.dragging && !isloading{ navView.loadProgress = 0.0 navView.indicator?.hidden = false navView.indicator?.startAnimating() headerRefresh() } } if offY <= -90{ tableView.contentOffset = CGPointMake(0, -90) } //透明度 let percent = offY/200.0 navView.statusView.backgroundColor = UIColor.colorWithAlpha(percent) navView.navigationView.backgroundColor = UIColor.colorWithAlpha(percent) //便宜设置 if offY > 200.0{ scrollView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0); } else{ scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0); } //标题 if offY >= (80.0 * CGFloat(homeModel.numberOfRowInSection(0))+180.0){ navView.navigationView.backgroundColor = UIColor.colorWithAlpha(0) navView.navTitle.text = "" } else{ navView.navTitle.text = "今日热闻" } } }
30.75502
131
0.607208
b9c7ec48f4f073a3270097a1e98d20564573358c
1,139
// // custom_resource_bundle_accessor.swift // LispMac // // Created by Roman Podymov on 10/21/20. // Copyright © 2020 Roman Podymov. All rights reserved. // import Foundation #if SWIFT_PACKAGE #else private class BundleFinder {} extension Foundation.Bundle { /// Returns the resource bundle associated with the current Swift module. static var module: Bundle = { let bundleName = "LispCore_LispCore" let candidates = [ // Bundle should be present here when the package is linked into an App. Bundle.main.resourceURL, // Bundle should be present here when the package is linked into a framework. Bundle(for: BundleFinder.self).resourceURL, // For command-line tools. Bundle.main.bundleURL, ] for candidate in candidates { let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle") if let bundle = bundlePath.flatMap(Bundle.init(url:)) { return bundle } } fatalError("unable to find bundle named LispCore_LispCore") }() } #endif
27.780488
89
0.636523
90fdfa7a83a143c427c692fa7e93ec6c50bb2fcc
856
// // GameViewController.swift // MiaoShow // // Created by Mazy on 2017/4/7. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class GameViewController: XMBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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.777778
106
0.668224
088c9892a4426eedf77cb6e79526db68a92c72bc
6,160
import Foundation import RxSwift import EthereumKit import FeeRateKit import Erc20Kit class SendEthereumHandler { private var gasDisposeBag = DisposeBag() weak var delegate: ISendHandlerDelegate? private let interactor: ISendEthereumInteractor private let amountModule: ISendAmountModule private let addressModule: ISendAddressModule private let feePriorityModule: ISendFeePriorityModule private let feeModule: ISendFeeModule private var estimateGasLimitState: FeeState = .zero init(interactor: ISendEthereumInteractor, amountModule: ISendAmountModule, addressModule: ISendAddressModule, feeModule: ISendFeeModule, feePriorityModule: ISendFeePriorityModule) { self.interactor = interactor self.amountModule = amountModule self.addressModule = addressModule self.feeModule = feeModule self.feePriorityModule = feePriorityModule } private func syncValidation() { do { _ = try amountModule.validAmount() try addressModule.validateAddress() delegate?.onChange(isValid: feeModule.isValid && feePriorityModule.feeRateState.isValid && estimateGasLimitState.isValid) } catch { delegate?.onChange(isValid: false) } } private func processFee(error: Error) { feeModule.set(externalError: error is EthereumKit.ValidationError ? nil : error) } private func syncState() { let loading = feePriorityModule.feeRateState.isLoading || estimateGasLimitState.isLoading amountModule.set(loading: loading) feeModule.set(loading: loading) guard !loading else { return } if case let .error(error) = feePriorityModule.feeRateState { feeModule.set(fee: 0) processFee(error: error) } else if case let .error(error) = estimateGasLimitState { feeModule.set(fee: 0) processFee(error: error) } else if case let .value(feeRateValue) = feePriorityModule.feeRateState, case let .value(estimateGasLimitValue) = estimateGasLimitState { amountModule.set(availableBalance: interactor.availableBalance(gasPrice: feeRateValue, gasLimit: estimateGasLimitValue)) feeModule.set(externalError: nil) feeModule.set(fee: interactor.fee(gasPrice: feeRateValue, gasLimit: estimateGasLimitValue)) } } private func syncEstimateGasLimit() { guard let address = try? addressModule.validAddress(), !amountModule.currentAmount.isZero else { onReceive(gasLimit: 0) return } gasDisposeBag = DisposeBag() estimateGasLimitState = .loading syncState() syncValidation() interactor.estimateGasLimit(to: address, value: amountModule.currentAmount, gasPrice: feePriorityModule.feeRate) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated)) .observeOn(MainScheduler.instance) .subscribe(onSuccess: onReceive, onError: onGasLimitError) .disposed(by: gasDisposeBag) } } extension SendEthereumHandler: ISendHandler { func onViewDidLoad() { feePriorityModule.fetchFeeRate() amountModule.set(minimumRequiredBalance: interactor.minimumRequiredBalance) if let minimumSpendableAmount = interactor.minimumSpendableAmount { amountModule.set(minimumAmount: minimumSpendableAmount) } feeModule.set(availableFeeBalance: interactor.ethereumBalance) syncState() syncEstimateGasLimit() } func showKeyboard() { amountModule.showKeyboard() } func confirmationViewItems() throws -> [ISendConfirmationViewItemNew] { [ SendConfirmationAmountViewItem(primaryInfo: try amountModule.primaryAmountInfo(), secondaryInfo: try amountModule.secondaryAmountInfo(), receiver: try addressModule.validAddress()), SendConfirmationFeeViewItem(primaryInfo: feeModule.primaryAmountInfo, secondaryInfo: feeModule.secondaryAmountInfo), SendConfirmationDurationViewItem(timeInterval: feePriorityModule.duration) ] } func sync() { if feePriorityModule.feeRateState.isError || estimateGasLimitState.isError { feePriorityModule.fetchFeeRate() syncEstimateGasLimit() } } func sync(rateValue: Decimal?) { amountModule.set(rateValue: rateValue) feeModule.set(rateValue: rateValue) } func sync(inputType: SendInputType) { amountModule.set(inputType: inputType) feeModule.update(inputType: inputType) } func sendSingle() throws -> Single<Void> { guard let feeRate = feePriorityModule.feeRate, case let .value(gasLimit) = estimateGasLimitState else { throw SendTransactionError.noFee } return interactor.sendSingle(amount: try amountModule.validAmount(), address: try addressModule.validAddress(), gasPrice: feeRate, gasLimit: gasLimit) } } extension SendEthereumHandler: ISendAmountDelegate { func onChangeAmount() { syncValidation() syncEstimateGasLimit() } func onChange(inputType: SendInputType) { feeModule.update(inputType: inputType) } } extension SendEthereumHandler: ISendAddressDelegate { func validate(address: String) throws { try interactor.validate(address: address) } func onUpdateAddress() { syncValidation() syncEstimateGasLimit() } func onUpdate(amount: Decimal) { amountModule.set(amount: amount) } } extension SendEthereumHandler: ISendFeePriorityDelegate { func onUpdateFeePriority() { syncState() syncValidation() syncEstimateGasLimit() } } extension SendEthereumHandler { func onReceive(gasLimit: Int) { estimateGasLimitState = .value(gasLimit) syncState() syncValidation() } func onGasLimitError(_ error: Error) { estimateGasLimitState = .error(error.convertedError) syncState() syncValidation() } }
30.8
193
0.685877
ccf34b9491e21ffd9c15bc3e51aca08687012f16
290
// // ContentView.swift // ShoeUI // // Created by Jovins on 2021/8/31. // import SwiftUI struct ContentView: View { var body: some View { BaseView() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
13.809524
46
0.62069
ebe806f4b6f0cff031f09b4400921adf9f5ff764
657
public protocol Arithmetic { static func + (lhs: Self, rhs: Self) -> Self static func - (lhs: Self, rhs: Self) -> Self static func * (lhs: Self, rhs: Self) -> Self static func / (lhs: Self, rhs: Self) -> Self static func += (lhs: inout Self, rhs: Self) static func -= (lhs: inout Self, rhs: Self) static func *= (lhs: inout Self, rhs: Self) static func /= (lhs: inout Self, rhs: Self) } public protocol Moduloable { static func % (lhs: Self, rhs: Self) -> Self } extension Int: Arithmetic, Moduloable {} extension UInt: Arithmetic, Moduloable {} extension Float: Arithmetic {} extension Double: Arithmetic {}
29.863636
48
0.636225
ace7243dfe1f81e42f3f0ed8fd77bc5d4b7918c4
809
// // crashNSExceptionManager.swift // XYGenericFramework // // Created by xiaoyi on 2017/8/15. // Copyright © 2017年 xiaoyi. All rights reserved. // 用于捕获OC的NSException导致的异常崩溃 import UIKit func registerUncaughtExceptionHandler() { NSSetUncaughtExceptionHandler(UncaughtExceptionHandler) } func UncaughtExceptionHandler(exception: NSException) { let arr = exception.callStackSymbols let reason = exception.reason let name = exception.name.rawValue var crash = String() crash += "Stack:\n" crash = crash.appendingFormat("slideAdress:0x%0x\r\n", calculate()) crash += "\r\n\r\n name:\(name) \r\n reason:\(String(describing: reason)) \r\n \(arr.joined(separator: "\r\n")) \r\n\r\n" CrashManager.saveCrash(appendPathStr: .nsExceptionCrashPath, exceptionInfo: crash) }
28.892857
125
0.721879
e623d0d0a5828b3b6c361368de8c33d238c56f01
5,989
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension Rocket.Support { /** When a user requests to reset their password via the /request-password-reset endpoint, an email is sent to the email address of the primary profile of the account. This email contains a link with a token as query parameter. The link should takes the user to the "reset-password" page of the website. From the reset-password page a user should enter their primary account email address and the new password they wish to use. These should then be submitted to this endpoint, along with the token from the email link. The token should be provided in the authorization header as a bearer token. */ public enum ResetPassword { public static let service = APIService<Response>(id: "resetPassword", tag: "support", method: "POST", path: "/reset-password", hasBody: true, securityRequirement: SecurityRequirement(type: "resetPasswordAuth", scope: "")) public final class Request: APIRequest<Response> { public var body: PasswordResetRequest public init(body: PasswordResetRequest) { self.body = body super.init(service: ResetPassword.service) { let jsonEncoder = JSONEncoder() return try jsonEncoder.encode(body) } } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = Void /** OK */ case status204 /** Bad request. */ case status400(ServiceError) /** Invalid access token. */ case status401(ServiceError) /** Forbidden. */ case status403(ServiceError) /** Not found. */ case status404(ServiceError) /** Internal server error. */ case status500(ServiceError) /** Service error. */ case defaultResponse(statusCode: Int, ServiceError) public var success: Void? { switch self { case .status204: return () default: return nil } } public var failure: ServiceError? { switch self { case .status400(let response): return response case .status401(let response): return response case .status403(let response): return response case .status404(let response): return response case .status500(let response): return response case .defaultResponse(_, let response): return response default: return nil } } /// either success or failure value. Success is anything in the 200..<300 status code range public var responseResult: APIResponseResult<Void, ServiceError> { if let successValue = success { return .success(successValue) } else if let failureValue = failure { return .failure(failureValue) } else { fatalError("Response does not have success or failure response") } } public var response: Any { switch self { case .status400(let response): return response case .status401(let response): return response case .status403(let response): return response case .status404(let response): return response case .status500(let response): return response case .defaultResponse(_, let response): return response default: return () } } public var statusCode: Int { switch self { case .status204: return 204 case .status400: return 400 case .status401: return 401 case .status403: return 403 case .status404: return 404 case .status500: return 500 case .defaultResponse(let statusCode, _): return statusCode } } public var successful: Bool { switch self { case .status204: return true case .status400: return false case .status401: return false case .status403: return false case .status404: return false case .status500: return false case .defaultResponse: return false } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 204: self = .status204 case 400: self = try .status400(decoder.decode(ServiceError.self, from: data)) case 401: self = try .status401(decoder.decode(ServiceError.self, from: data)) case 403: self = try .status403(decoder.decode(ServiceError.self, from: data)) case 404: self = try .status404(decoder.decode(ServiceError.self, from: data)) case 500: self = try .status500(decoder.decode(ServiceError.self, from: data)) default: self = try .defaultResponse(statusCode: statusCode, decoder.decode(ServiceError.self, from: data)) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
38.88961
229
0.558524
bfb9a791c81bba44b0a30f89357255521fee01ff
519
// // PhotoCell.swift // tumblr_clone // // Created by Nabil on 10/1/18. // Copyright © 2018 Nabil. All rights reserved. // import UIKit class PhotoCell: UITableViewCell { @IBOutlet weak var photosView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
19.222222
65
0.655106
87c9436eda530b739933356aed2a3c64398707a8
2,185
// // AppDelegate.swift // MyUnitConverter // // Created by Malvern Madondo on 9/5/17. // Copyright © 2017 Malvern Madondo. 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.489362
285
0.756522
de3537e1602c9f60f32fcbccf813175dcecc3915
5,566
/* This source file is part of the Swift.org open source project Copyright (c) 2021 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information See https://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Foundation @testable import SwiftDocC class PresentationURLGeneratorTests: XCTestCase { func testInternalURLs() throws { let (bundle, context) = try testBundleAndContext(named: "TestBundle") let generator = PresentationURLGenerator(context: context, baseURL: URL(string: "https://host:1024/webPrefix")!) // Test resolved tutorial reference let reference = ResolvedTopicReference(bundleIdentifier: bundle.identifier, path: "/tutorials/Test-Bundle/TestTutorial", sourceLanguage: .swift) XCTAssertEqual(generator.presentationURLForReference(reference).absoluteString, "https://host:1024/webPrefix/tutorials/test-bundle/testtutorial") // Test resolved symbol reference let symbol = ResolvedTopicReference(bundleIdentifier: bundle.identifier, path: "/documentation/MyKit/MyClass", sourceLanguage: .swift) XCTAssertEqual(generator.presentationURLForReference(symbol).absoluteString, "https://host:1024/webPrefix/documentation/mykit/myclass") // Test root let root = ResolvedTopicReference(bundleIdentifier: bundle.identifier, path: "/", sourceLanguage: .swift) XCTAssertEqual(generator.presentationURLForReference(root).absoluteString, "https://host:1024/webPrefix/documentation") // Fragment let fragment = ResolvedTopicReference(bundleIdentifier: bundle.identifier, path: "/path", fragment: "test URL! FRAGMENT", sourceLanguage: .swift) XCTAssertEqual(generator.presentationURLForReference(fragment).absoluteString, "https://host:1024/webPrefix/path#test-URL!-FRAGMENT") } func testExternalURLs() throws { let bundle = DocumentationBundle( info: DocumentationBundle.Info( displayName: "Test", identifier: "com.example.test", version: "1.0" ), baseURL: URL(string: "https://example.com/example")!, symbolGraphURLs: [], markupURLs: [], miscResourceURLs: [] ) let provider = PrebuiltLocalFileSystemDataProvider(bundles: [bundle]) let workspace = DocumentationWorkspace() try workspace.registerProvider(provider) let context = try DocumentationContext(dataProvider: workspace) context.externalReferenceResolvers = [ bundle.identifier: ExternalReferenceResolverTests.TestExternalReferenceResolver(), ] let reference = ResolvedTopicReference(bundleIdentifier: "com.example.test", path: "/Test/Path", sourceLanguage: .swift) let generator = PresentationURLGenerator(context: context, baseURL: bundle.baseURL) XCTAssertEqual(generator.presentationURLForReference(reference), URL(string: "https://example.com/example/Test/Path")) } func testCustomExternalURLs() throws { /// Resolver for this test, returns fixed custom URL. struct TestLinkResolver: ExternalReferenceResolver { let customResolvedURL = URL(string: "https://resolved.com/resolved/path?query=item")! func resolve(_ reference: TopicReference, sourceLanguage: SourceLanguage) -> TopicReferenceResolutionResult { return .success(ResolvedTopicReference(bundleIdentifier: "com.example.test", path: "/path", sourceLanguage: .swift)) } func entity(with reference: ResolvedTopicReference) throws -> DocumentationNode { enum Error: DescribedError { case empty var errorDescription: String { return "empty" } } throw Error.empty } func urlForResolvedReference(_ reference: ResolvedTopicReference) -> URL { return customResolvedURL } } let bundle = DocumentationBundle( info: DocumentationBundle.Info( displayName: "Test", identifier: "com.example.test", version: "1.0" ), baseURL: URL(string: "https://example.com/example")!, symbolGraphURLs: [], markupURLs: [], miscResourceURLs: [] ) let provider = PrebuiltLocalFileSystemDataProvider(bundles: [bundle]) let workspace = DocumentationWorkspace() try workspace.registerProvider(provider) let testResolver = TestLinkResolver() let context = try DocumentationContext(dataProvider: workspace) context.externalReferenceResolvers = [ bundle.identifier: testResolver, ] let reference = ResolvedTopicReference(bundleIdentifier: "com.example.test", path: "/Test/Path", sourceLanguage: .swift) let generator = PresentationURLGenerator(context: context, baseURL: bundle.baseURL) /// Check that the presentation generator got a custom final URL from the resolver. XCTAssertEqual( generator.presentationURLForReference(reference), testResolver.customResolvedURL ) } }
45.622951
153
0.650557
c18f23a01225a6fff505a59321548177ace14772
465
// // OutputFromMultipleTasks.swift // RsyncSwiftUI // // Created by Thomas Evensen on 03/02/2021. // import Foundation final class OutputFromMultipleTasks: ObservableObject { private var output: [RemoteinfonumbersOnetask]? func setoutput(output: [RemoteinfonumbersOnetask]?) { self.output = output } func getoutput() -> [RemoteinfonumbersOnetask]? { return output } func resetoutput() { output = nil } }
18.6
57
0.664516
8f67c7243811c1369256d95eb7a3e4977912cc5e
2,219
//// SYWaypointExtension.swift // // Copyright (c) 2019 - Sygic a.s. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the &quot;Software&quot;), 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 &quot;AS IS&quot;, 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 SygicMaps import SygicUIKit public extension SYWaypoint { static var currentLocationIdentifier: String { LS("Current location") } static func currentLocationWaypoint() -> SYWaypoint? { guard let location = SYPosition.lastKnownLocation()?.coordinate else { return nil } return SYWaypoint(position: location, type: .start, name: SYWaypoint.currentLocationIdentifier) } var isCurrentLocationWaypoint: Bool { return name == SYWaypoint.currentLocationIdentifier } } extension Array where Element == SYWaypoint { func waypointsWithTypeCorrection() -> [SYWaypoint] { var fixed = [SYWaypoint]() for (index, wp) in enumerated() { var type: SYWaypointType = .via if index == 0 { type = .start } else if index == count-1 { type = .end } fixed.append(SYWaypoint(position: wp.originalPosition, type: type, name: wp.name)) } return fixed } }
38.258621
103
0.694006
167c7d91da5ad0e445ed0f6d94ea80d21d4eb192
3,102
// // AppDelegate.swift // FileExplorerExampleApp // // Created by Rafal Augustyniak on 27/11/2016. // Copyright (c) 2016 Rafal Augustyniak // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import FileExplorer @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let directoryURL = URL.documentDirectory let audioURL = Bundle.main.url(forResource: "audio", withExtension: "mp3")! let videoURL = Bundle.main.url(forResource: "video", withExtension: "mp4")! let pdfURL = Bundle.main.url(forResource: "pdf", withExtension: "pdf")! let image = UIImage(named: "image.jpg")! let imageData = image.pngData()! let firstDirectoryURL = directoryURL.appendingPathComponent("Directory") try? FileManager.default.createDirectory(at: firstDirectoryURL, withIntermediateDirectories: true, attributes: [FileAttributeKey: Any]()) let items = [ (audioURL, "audio.mp3"), (videoURL, "video.mp4"), (pdfURL, "pdf.pdf") ] for (url, filename) in items { let destinationURL = firstDirectoryURL.appendingPathComponent(filename) try? FileManager.default.copyItem(at: url, to: destinationURL) } let imageURL = firstDirectoryURL.appendingPathComponent("image.png") try? imageData.write(to: imageURL) let subdirectoryURL = firstDirectoryURL.appendingPathComponent("Empty Directory") try? FileManager.default.createDirectory(at: subdirectoryURL, withIntermediateDirectories: true, attributes: [FileAttributeKey: Any]()) let secondDirectoryURL = directoryURL.appendingPathComponent("Empty Directory") try? FileManager.default.createDirectory(at: secondDirectoryURL, withIntermediateDirectories: true, attributes: [FileAttributeKey: Any]()) return true } }
45.617647
146
0.72147
9cc7ad7a899ea559e9f8dc07e1eb9858788af9bf
3,314
// The MIT License (MIT) // // Copyright (c) 2020 Ruslan Shevtsov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit final class NotificationsPermission: PermissionProtocol { var name: String { "Push Notifications" } var key: String { "" } func isKeyExist() -> Bool { guard let modes = Bundle.main.object(forInfoDictionaryKey: "UIBackgroundModes") as? [String] else { print("Warning!!! - UIBackgroundModes for remote-notification is missing in Info.plist. Please, add key remote-notification to info.plist with description which explains why a user should allow \(name) permission") return false } for mode in modes { if mode == "remote-notification" { return true } } print("Warning!!! - UIBackgroundModes for remote-notification is missing in Info.plist. Please, add key remote-notification to info.plist with description which explains why a user should allow \(name) permission") return false } var status: Permissions.Status { var notificationSettings: UNNotificationSettings? let semaphore = DispatchSemaphore(value: 0) DispatchQueue.global().async { UNUserNotificationCenter.current().getNotificationSettings { setttings in notificationSettings = setttings semaphore.signal() } } semaphore.wait() switch notificationSettings?.authorizationStatus { case .notDetermined, .none: return .notDetermined case .denied: return .denied case .authorized, .provisional: return .granted @unknown default: return .notDetermined } } func request(completion: @escaping PermissionRequestCompletion) { let center = UNUserNotificationCenter.current() center.requestAuthorization(options:[.badge, .alert, .sound]) { granted, _ in if granted { completion(.granted) } else { completion(.denied) } } } }
38.091954
226
0.642728
e40a1e46f6cc5117693d52c774bff004c0dadbd6
6,531
// // PBXBuildRule.swift // PBXProj // // Created by Tyler Anger on 2018-12-02. // import Foundation /// A class storing the building rules public final class PBXBuildRule: PBXUnknownObject { /// Build Rules coding keys internal enum BuildRuleCodingKeys: String, CodingKey { public typealias parent = PBXObject.ObjectCodingKeys case compilerSpec case filePatterns case fileType case editable = "isEditable" case name case inputFiles case outputFiles case outputFilesCompilerFlags case script } private typealias CodingKeys = BuildRuleCodingKeys internal override class var CODING_KEY_ORDER: [String] { var rtn = super.CODING_KEY_ORDER rtn.append(CodingKeys.compilerSpec) rtn.append(CodingKeys.filePatterns) rtn.append(CodingKeys.fileType) rtn.append(CodingKeys.name) rtn.append(CodingKeys.inputFiles) rtn.append(CodingKeys.outputFiles) rtn.append(CodingKeys.outputFilesCompilerFlags) rtn.append(CodingKeys.script) return rtn } internal override class var knownProperties: [String] { var rtn: [String] = super.knownProperties rtn.append(CodingKeys.compilerSpec) rtn.append(CodingKeys.filePatterns) rtn.append(CodingKeys.fileType) rtn.append(CodingKeys.editable) rtn.append(CodingKeys.name) rtn.append(CodingKeys.inputFiles) rtn.append(CodingKeys.outputFiles) rtn.append(CodingKeys.outputFilesCompilerFlags) rtn.append(CodingKeys.script) return rtn } /// Element compiler spec. public var compilerSpec: String { didSet { self.proj?.sendChangedNotification() } } /// Element file patterns. public var filePatterns: String? { didSet { self.proj?.sendChangedNotification() } } /// Element file type. public var fileType: PBXFileType { didSet { self.proj?.sendChangedNotification() } } /// Element is editable. public var editable: Bool { didSet { self.proj?.sendChangedNotification() } } /// Element name. public var name: String? { didSet { self.proj?.sendChangedNotification() } } /// Element input files. public var inputFiles: [String] { didSet { self.proj?.sendChangedNotification() } } /// Element output files. public var outputFiles: [String] { didSet { self.proj?.sendChangedNotification() } } /// Element output files compiler flags. public var outputFilesCompilerFlags: [String]? { didSet { self.proj?.sendChangedNotification() } } /// Element script. public var script: String? { didSet { self.proj?.sendChangedNotification() } } /// Create a new instance of PBXBuildRule /// /// - Parameters: /// - id: The unique reference of this object /// - name: The name of the build rule (Optional) /// - compilerSpec: The compiler specs /// - fileType: The file type /// - editable: If its editable or not (Default: true) /// - filePatterns: The file patterns (Optional) /// - inputFiles: The input files (Default: Empty Array) /// - outputFiles: The output files (Default: Empty Array) /// - outputFilesCompilerFlags: Output compiler flags (Optional) /// - script: Script string (Optional) internal init(id: PBXReference, name: String? = nil, compilerSpec: String, fileType: PBXFileType, editable: Bool = true, filePatterns: String? = nil, inputFiles: [String] = [], outputFiles: [String] = [], outputFilesCompilerFlags: [String]? = nil, script: String? = nil) { self.name = name self.compilerSpec = compilerSpec self.filePatterns = filePatterns self.fileType = fileType self.editable = editable self.inputFiles = inputFiles self.outputFiles = outputFiles self.outputFilesCompilerFlags = outputFilesCompilerFlags self.script = script super.init(id: id, type: .buildRule) } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.name = try container.decodeIfPresent(String.self, forKey: .name) self.compilerSpec = try container.decodeIfPresent(String.self, forKey: .compilerSpec) ?? "" self.filePatterns = try container.decodeIfPresent(String.self, forKey: .filePatterns) self.fileType = try container.decodeIfPresent(PBXFileType.self, forKey: .fileType) ?? PBXFileType() self.editable = ((try container.decode(Int.self, forKey: .editable)) == 1) self.inputFiles = try container.decodeIfPresent([String].self, forKey: .inputFiles) ?? [] self.outputFiles = try container.decodeIfPresent([String].self, forKey: .outputFiles) ?? [] self.outputFilesCompilerFlags = try container.decodeIfPresent([String].self, forKey: .outputFilesCompilerFlags) self.script = try container.decodeIfPresent(String.self, forKey: .script) try super.init(from: decoder) } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(self.name, forKey: .name) if !self.compilerSpec.isEmpty { try container.encode(self.compilerSpec, forKey: .compilerSpec) } try container.encodeIfPresent(filePatterns, forKey: .filePatterns) if !self.fileType.isEmpty { try container.encode(self.fileType, forKey: .fileType) } try container.encode(self.editable ? 1 : 0, forKey: .editable) if !self.inputFiles.isEmpty { try container.encode(self.inputFiles, forKey: .inputFiles) } if !self.outputFiles.isEmpty { try container.encode(self.outputFiles, forKey: .outputFiles) } try container.encodeIfPresent(self.outputFilesCompilerFlags, forKey: .outputFilesCompilerFlags) try container.encodeIfPresent(self.script, forKey: .script) try super.encode(to: encoder) } }
35.112903
119
0.62655