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
1c10885235cfd83b9cecd5ecb128b46d395caa96
3,441
// // QRView.swift // flutter_qr // // Created by Julius Canute on 21/12/18. // import Foundation import MTBBarcodeScanner public class QRView:NSObject,FlutterPlatformView { @IBOutlet var previewView: UIView! var scanner: MTBBarcodeScanner? var registrar: FlutterPluginRegistrar var channel: FlutterMethodChannel public init(withFrame frame: CGRect, withRegistrar registrar: FlutterPluginRegistrar, withId id: Int64){ self.registrar = registrar previewView = UIView(frame: frame) channel = FlutterMethodChannel(name: "net.touchcapture.qr.flutterqr/qrview_\(id)", binaryMessenger: registrar.messenger()) } func isCameraAvailable(success: Bool) -> Void { if success { do { try scanner?.startScanning(resultBlock: { [weak self] codes in if let codes = codes { for code in codes { guard let stringValue = code.stringValue else { continue } self?.channel.invokeMethod("onRecognizeQR", arguments: stringValue) } } }) } catch { NSLog("Unable to start scanning") } } else { UIAlertView(title: "Scanning Unavailable", message: "This app does not have permission to access the camera", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "Ok").show() } } public func view() -> UIView { channel.setMethodCallHandler({ [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in switch(call.method){ case "setDimensions": var arguments = call.arguments as! Dictionary<String, Double> self?.setDimensions(width: arguments["width"] ?? 0,height: arguments["height"] ?? 0) case "flipCamera": self?.flipCamera() case "toggleFlash": self?.toggleFlash() case "pauseCamera": self?.pauseCamera() case "resumeCamera": self?.resumeCamera() default: result(FlutterMethodNotImplemented) return } }) return previewView } func setDimensions(width: Double, height: Double) -> Void { previewView.frame = CGRect(x: 0, y: 0, width: width, height: height) scanner = MTBBarcodeScanner(metadataObjectTypes: [AVMetadataObject.ObjectType.qr.rawValue],previewView: previewView) MTBBarcodeScanner.requestCameraPermission(success: isCameraAvailable) } func flipCamera(){ if let sc: MTBBarcodeScanner = scanner { if sc.hasOppositeCamera() { sc.flipCamera() } } } func toggleFlash(){ if let sc: MTBBarcodeScanner = scanner { if sc.hasTorch() { sc.toggleTorch() } } } func pauseCamera() { if let sc: MTBBarcodeScanner = scanner { if sc.isScanning() { sc.freezeCapture() } } } func resumeCamera() { if let sc: MTBBarcodeScanner = scanner { if !sc.isScanning() { sc.unfreezeCapture() } } } }
33.407767
192
0.544609
f874bc437fe2ddea38cbc18b1eaf33bb680c6523
403
// // PointGeometry.swift // Satin // // Created by Reza Ali on 10/9/19. // import simd open class PointGeometry: Geometry { override public init() { super.init() self.setupData() } func setupData() { primitiveType = .point vertexData.append( Vertex(position: [0.0, 0.0, 0.0, 1.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0]) ) } }
17.521739
91
0.528536
09b4bc3b1df0902adc30408b060a997da7b9a5e9
356
// // InternalMenuItemViewModel.swift // Moment // // Created by Sam Lau on 2021/6/22. // enum InternalMenuItemType: String { case description case featureToggle case actionTrigger } protocol InternalMenuItemViewModel { var type: InternalMenuItemType { get } var title: String { get } var didSelectAction: () -> Void { get } }
18.736842
43
0.685393
878c3e833c25b8bf06e08a6118aca662b2fe08fc
2,530
/* * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /// Calcualtes the stats for a sensor during recording. class StatCalculator { // MARK: - Properties /// The maximum value added. var maximum: Double? /// The minimum value added. var minimum: Double? /// The average (mean) of the values recorded. var average: Double? { guard numberOfValues > 0 else { return nil } return totalValue / Double(numberOfValues) } /// The duration in milliseconds between the first and last timestamps. var duration: Int64? { guard let firstTimestamp = firstTimestamp, let lastTimestamp = lastTimestamp else { return nil } return lastTimestamp - firstTimestamp } /// The first timestamp added, in milliseconds. private var firstTimestamp: Int64? /// The last timestamp added, in milliseconds. private var lastTimestamp: Int64? /// The number of values added. private(set) var numberOfValues = 0 /// The total of all values added. private var totalValue = 0.0 // MARK: - Public /// Adds a data point to the caluclations for each stat. /// /// - Parameter dataPoint: A data point. func addDataPoint(_ dataPoint: DataPoint) { // First timestamp. if firstTimestamp == nil { firstTimestamp = dataPoint.x } // Last timestamp. lastTimestamp = dataPoint.x // Maximum if let maximum = maximum { self.maximum = max(maximum, dataPoint.y) } else { maximum = dataPoint.y } // Minimum if let minimum = minimum { self.minimum = min(minimum, dataPoint.y) } else { minimum = dataPoint.y } // Values for average calculation. numberOfValues += 1 totalValue += dataPoint.y } /// Resets the calculator by removing all stats and values. func reset() { firstTimestamp = nil lastTimestamp = nil maximum = nil minimum = nil numberOfValues = 0 totalValue = 0 } }
25.3
87
0.673913
5b61a6e62715656efa9d0ab2e9ec95585a234ad8
1,983
// // ChordDetectorTests.swift // ChordDetectorTests // // Created by Cem Olcay on 31/03/2017. // Copyright © 2017 cemolcay. All rights reserved. // import XCTest import WebKit @testable import Chord_Detector class ChordDetectorTests: XCTestCase, WKNavigationDelegate { var webView = WKWebView() var wkExpectation = XCTestExpectation(description: "WKNavigationDelegate") let artist = "The Animals" let song = "House Of The Rising Sun" func testUltimateGuitarParse() { var url = "https://www.ultimate-guitar.com/search.php?search_type=title&order=&value=" url += "\(artist.replacingOccurrences(of: " ", with: "+"))+" url += "\(song.replacingOccurrences(of: " ", with: "+"))" guard let chordUrl = URL(string: url) else { return XCTFail("URL not parsed.") } webView.navigationDelegate = self webView.load(URLRequest(url: chordUrl)) wait(for: [wkExpectation], timeout: 10.0) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { let js = """ window.UGAPP.store.page.data.results .filter(function(item){ return (item.type == "Chords") }) .sort(function(a, b){ return b.rating > a.rating })[0] """ webView.evaluateJavaScript(js, completionHandler: { result, error in guard let json = result as? [String: Any], error == nil else { XCTFail("Can not evaluate javascript"); return } guard let url = json["tab_url"] as? String, let artist = json["artist_name"] as? String, let song = json["song_name"] as? String, let item = UGItem(dict: json) else { XCTFail("Can not serialize javascript object"); return } XCTAssertEqual(self.artist, artist) XCTAssertEqual(self.song, song) XCTAssertNotNil(URL(string: url), "Url is nil") XCTAssertEqual(self.artist, item.artist) XCTAssertEqual(self.song, item.song) XCTAssertEqual(url, item.url.absoluteString) self.wkExpectation.fulfill() }) } }
34.789474
90
0.669188
ab56e789d260d6fdc6eaa98957c8b3b27fa01e96
3,525
import ArgumentParser import Scout import Foundation struct SetCommand: ParsableCommand { static let configuration = CommandConfiguration( commandName: "set", abstract: "Change a value at a given path.", discussion: "To find examples and advanced explanations, please type `scout doc set`") @Argument(help: PathAndValue.help) var pathsAndValues = [PathAndValue]() @Option(name: [.short, .customLong("input")], help: "A file path from which to read the data") var inputFilePath: String? @Option(name: [.short, .long], help: "Write the modified data into the file at the given path") var output: String? @Option(name: [.short, .customLong("modify")], help: "Read and write the data into the same file at the given path") var modifyFilePath: String? @Flag(name: [.short, .long], inversion: .prefixedNo, help: "Output the modified data") var verbose = false @Flag(name: [.long], inversion: .prefixedNo, help: "Colorise the ouput") var color = true func run() throws { do { if let filePath = modifyFilePath ?? inputFilePath { let data = try Data(contentsOf: URL(fileURLWithPath: filePath.replacingTilde)) try set(from: data) } else { let streamInput = FileHandle.standardInput.readDataToEndOfFile() try set(from: streamInput) } } catch let error as PathExplorerError { print(error.commandLineErrorDescription) return } } func set(from data: Data) throws { let output = modifyFilePath ?? self.output if var json = try? PathExplorerFactory.make(Json.self, from: data) { try set(pathsAndValues, in: &json) try ScoutCommand.output(output, dataWith: json, verbose: verbose, colorise: color) } else if var plist = try? PathExplorerFactory.make(Plist.self, from: data) { try set(pathsAndValues, in: &plist) try ScoutCommand.output(output, dataWith: plist, verbose: verbose, colorise: color) } else if var xml = try? PathExplorerFactory.make(Xml.self, from: data) { try set(pathsAndValues, in: &xml) try ScoutCommand.output(output, dataWith: xml, verbose: verbose, colorise: color) } else { if let filePath = inputFilePath { throw RuntimeError.unknownFormat("The format of the file at \(filePath) is not recognized") } else { throw RuntimeError.unknownFormat("The format of the input stream is not recognized") } } } func set<Explorer: PathExplorer>(_ pathAndValues: [PathAndValue], in explorer: inout Explorer) throws { for pathAndValue in pathAndValues { let (path, value) = (pathAndValue.readingPath, pathAndValue.value) if pathAndValue.changeKey { try explorer.set(path, keyNameTo: value) continue } if let forceType = pathAndValue.forceType { switch forceType { case .string: try explorer.set(path, to: value, as: .string) case .real: try explorer.set(path, to: value, as: .real) case .int: try explorer.set(path, to: value, as: .int) case .bool: try explorer.set(path, to: value, as: .bool) } } else { try explorer.set(path, to: value) } } } }
37.5
120
0.604539
168a9aabc82e0042347549e1946aa68495dda9ef
248
// // Offence.swift // // Created on 13/03/2020. // Copyright © 2020 WildAid. All rights reserved. // import RealmSwift class Offence: EmbeddedObject, ObservableObject { @objc dynamic var code = "" @objc dynamic var explanation = "" }
17.714286
50
0.673387
140ea34a23317305226ebd995ecd344d372624d0
3,838
// // MyViewController.swift // MinimizePanTest // // Created by hanwe lee on 2020/10/05. // import UIKit protocol MyViewControllerDelegate:class { func currentProgress(persent:CGFloat) } class MyViewController: UIViewController { enum MyState { case max case min } //MAKR: public property public var state:MyState = .max //MARK: private property // var statusbarHeight:CGFloat = 0 private var originBoundsYPosition:CGFloat = 0 private var currentBoundsYPosition:CGFloat = 0 { didSet { // self.currentBoundsYPosition self.currentProgress = 1 + self.currentBoundsYPosition/self.view.bounds.height } } private var centerYPosition:CGFloat = 0 public var currentProgress:CGFloat = 1 { didSet { // print("test:\(self.currentProgress)") // self.view.alpha = self.currentAlpha // self.imgViewCenterXConstraint?.constant // print("test2:\(String(describing: self.imgViewCenterXConstraint?.constant))") } } //MARK: life cycle override func viewDidLoad() { super.viewDidLoad() initSetting() } override func viewWillAppear(_ animated: Bool) { // self.statusbarHeight = UIApplication.shared.statusBarFrame.size.height // print("status:\(self.statusbarHeight)") } override func viewDidAppear(_ animated: Bool) { initSetting() } //MARK: public function func addPhotoViewCenterXConstraint(constraint:NSLayoutConstraint) { } //MARK: private function func initSetting() { self.originBoundsYPosition = self.view.bounds.minY self.centerYPosition = self.view.bounds.height/2 let panGuesture:UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panAction(_:))) self.view.addGestureRecognizer(panGuesture) } func dismissTest() { // self.dismiss(animated: true, completion: { // // }) self.hero.dismissViewController(completion: { }) } func recoveryTest() { UIView.animate(withDuration: 0.3, animations: { self.view.bounds = CGRect(x: 0, y: self.originBoundsYPosition, width: self.view.frame.width, height: self.view.frame.height) }) } @objc func panAction(_ recognizer: UIPanGestureRecognizer) { let transition = recognizer.translation(in: self.view) // var changeY = self.view.frame.minY + transition.y print("changeY :\(transition.y)") // recognizer.state switch recognizer.state { case .began: print("pan start") break case .possible: break case .changed: self.currentBoundsYPosition = -transition.y self.view.bounds = CGRect(x: 0, y: self.currentBoundsYPosition, width: self.view.frame.width, height: self.view.frame.height) break case .ended: print("pan end") print("current:\(-self.currentBoundsYPosition)") print("center:\(self.centerYPosition)") if -self.currentBoundsYPosition > self.centerYPosition { self.state = .min dismissTest() } else { self.state = .max self.recoveryTest() } break case .cancelled: break case .failed: self.view.bounds = CGRect(x: 0, y: self.originBoundsYPosition, width: self.view.frame.width, height: self.view.frame.height) self.currentBoundsYPosition = self.originBoundsYPosition break @unknown default: break } } }
29.523077
137
0.59432
f7224a055d079d5706555ae36f09ee3cbe0a6706
10,193
// // URLImageFileStore.swift // // // Created by Dmytro Anokhin on 08/01/2021. // import Foundation import CoreGraphics import FileIndex import Log import URLImage import ImageDecoder @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) public final class URLImageFileStore { let fileIndex: FileIndex init(fileIndex: FileIndex) { self.fileIndex = fileIndex } public convenience init() { let fileIndexConfiguration = FileIndex.Configuration(name: "URLImage", filesDirectoryName: "images", baseDirectoryName: "URLImage") let fileIndex = FileIndex(configuration: fileIndexConfiguration) self.init(fileIndex: fileIndex) } // MARK: - Access Images public func getImage(_ identifier: String, maxPixelSize: CGSize? = nil, completionQueue: DispatchQueue? = nil, completion: @escaping (_ image: CGImage?) -> Void) { getImage([ .identifier(identifier) ], maxPixelSize: maxPixelSize, completionQueue: completionQueue, completion: completion) } public func getImage(_ url: URL, maxPixelSize: CGSize? = nil, completionQueue: DispatchQueue? = nil, completion: @escaping (_ image: CGImage?) -> Void) { getImage([ .url(url) ], maxPixelSize: maxPixelSize, completionQueue: completionQueue, completion: completion) } public func getImageLocation(_ identifier: String, completionQueue: DispatchQueue? = nil, completion: @escaping (_ location: URL?) -> Void) { getImageLocation([ .identifier(identifier) ], completionQueue: completionQueue, completion: completion) } public func getImageLocation(_ url: URL, completionQueue: DispatchQueue? = nil, completion: @escaping (_ location: URL?) -> Void) { getImageLocation([ .url(url) ], completionQueue: completionQueue, completion: completion) } // MARK: - Cleanup func cleanup() { fileIndexQueue.async(flags: .barrier) { [weak self] in guard let self = self else { return } self.fileIndex.deleteExpired() } } func deleteAll() { fileIndexQueue.async(flags: .barrier) { [weak self] in guard let self = self else { return } self.fileIndex.deleteAll() } } func delete(withIdentifier identifier: String?, orURL url: URL?) { fileIndexQueue.async(flags: .barrier) { [weak self] in log_debug(self, #function, { if let identifier = identifier { return "identifier = " + identifier } if let url = url { return "url = " + url.absoluteString } return "No identifier or url" }(), detail: log_normal) guard let self = self else { return } let file: File? if let identifier = identifier { file = self.fileIndex.get(identifier).first } else if let url = url { file = self.fileIndex.get(url).first } else { file = nil } if let file = file { self.fileIndex.delete(file) } } } // MARK: - Private /// The queue used to access file index private let fileIndexQueue = DispatchQueue(label: "URLImageStore.fileIndexQueue") /// The queue used to decode images private let decodeQueue = DispatchQueue(label: "URLImageStore.decodeQueue") private func getImageLocation(_ keys: [URLImageKey], completionQueue: DispatchQueue? = nil, completion: @escaping (_ location: URL?) -> Void) { fileIndexQueue.async { [weak self] in guard let self = self else { return } var file: File? for key in keys { switch key { case .identifier(let identifier): file = self.fileIndex.get(identifier).first case .url(let url): file = self.fileIndex.get(url).first } if file != nil { break } } if let file = file { let location = self.fileIndex.location(of: file) let queue = completionQueue ?? DispatchQueue.global() queue.async { completion(location) } } else { completion(nil) } } } private func getImage(_ keys: [URLImageKey], maxPixelSize: CGSize? = nil, completionQueue: DispatchQueue? = nil, completion: @escaping (_ image: CGImage?) -> Void) { getImage(keys, open: { location -> CGImage? in guard let decoder = ImageDecoder(url: location) else { return nil } if let sizeForDrawing = maxPixelSize { let decodingOptions = ImageDecoder.DecodingOptions(mode: .asynchronous, sizeForDrawing: sizeForDrawing) return decoder.createFrameImage(at: 0, decodingOptions: decodingOptions)! } else { return decoder.createFrameImage(at: 0)! } }, completion: { result in let queue = completionQueue ?? DispatchQueue.global() switch result { case .success(let image): queue.async { completion(image) } case .failure: queue.async { completion(nil) } } }) } } @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension URLImageFileStore: URLImageFileStoreType { public func removeAllImages() { fileIndexQueue.async(flags: .barrier) { [weak self] in guard let self = self else { return } self.fileIndex.deleteAll() } } public func removeImageWithURL(_ url: URL) { fileIndexQueue.async(flags: .barrier) { [weak self] in guard let self = self else { return } log_debug(self, #function, { "url = " + url.absoluteString }(), detail: log_normal) guard let file = self.fileIndex.get(url).first else { return } self.fileIndex.delete(file) } } public func removeImageWithIdentifier(_ identifier: String) { fileIndexQueue.async(flags: .barrier) { [weak self] in guard let self = self else { return } log_debug(self, #function, { "identifier = " + identifier }(), detail: log_normal) guard let file = self.fileIndex.get(identifier).first else { return } self.fileIndex.delete(file) } } public func getImage<T>(_ keys: [URLImageKey], open: @escaping (_ location: URL) throws -> T?, completion: @escaping (_ result: Result<T?, Swift.Error>) -> Void) { getImageLocation(keys, completionQueue: decodeQueue) { [weak self] location in guard let _ = self else { // Just a sanity check if the cache object is still exists return } guard let location = location else { completion(.success(nil)) return } do { let object = try open(location) completion(.success(object)) } catch { completion(.failure(error)) } } } public func storeImageData(_ data: Data, info: URLImageStoreInfo) { fileIndexQueue.async { [weak self] in guard let self = self else { return } let fileName = UUID().uuidString let fileExtension = ImageDecoder.preferredFileExtension(forTypeIdentifier: info.uti) _ = try? self.fileIndex.write(data, originalURL: info.url, identifier: info.identifier, fileName: fileName, fileExtension: fileExtension, expireAfter: nil) } } public func moveImageFile(from location: URL, info: URLImageStoreInfo) { fileIndexQueue.async { [weak self] in guard let self = self else { return } let fileName = UUID().uuidString let fileExtension: String? if !location.pathExtension.isEmpty { fileExtension = location.pathExtension } else { fileExtension = ImageDecoder.preferredFileExtension(forTypeIdentifier: info.uti) } _ = try? self.fileIndex.move(location, originalURL: info.url, identifier: info.identifier, fileName: fileName, fileExtension: fileExtension, expireAfter: nil) } } }
32.461783
131
0.488276
0100ea1ecf76efec014f3e948ab8eae1d69d0815
5,261
// // TinyLog.swift // TinyLog // // Created by DragonCherry on 1/11/17. // Copyright © 2017 DragonCherry. All rights reserved. // import Foundation public class TinyLog { public static var stripParameters: Bool = true public static var isShowInfoLog = true public static var isShowErrorLog = true public static var filterString: String? static var isTestFlight: Bool { if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, appStoreReceiptURL.lastPathComponent == "sandboxReceipt" { return true } else { return false } } #if DEBUG public static var profilingStartTime: TimeInterval = 0 public static var profilingTagTime: TimeInterval = 0 #endif public static func startProfiling() { #if DEBUG profilingStartTime = Date().timeIntervalSince1970 profilingTagTime = profilingStartTime NSLog("[Profiling] Start") #endif } public static func tagProfiling(_ message: String? = nil) { #if DEBUG guard profilingStartTime > 0 else { return } let now = Date().timeIntervalSince1970 let elapsed = TimeInterval(Int((now - profilingStartTime) * 1000)) / 1000 let elapsedFromLastTag = TimeInterval(Int((now - profilingTagTime) * 1000)) / 1000 profilingTagTime = now NSLog("[Profiling][\(message ?? "")] Total: \(elapsed)s, Elapsed: \(elapsedFromLastTag)s") #endif } public static func stopProfiling() { #if DEBUG profilingStartTime = 0 profilingTagTime = 0 #endif } fileprivate static let queue = DispatchQueue(label: "TinyLog") } fileprivate class TinyLogDateFormatter { // MARK: Singleton fileprivate static let `default`: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" return formatter }() } fileprivate func fileName(_ filePath: String) -> String { let lastPathComponent = NSString(string: filePath).lastPathComponent if let name = lastPathComponent.components(separatedBy: ".").first { return name } else { return lastPathComponent } } fileprivate func functionNameByStrippingParameters(_ function: String) -> String { if let startIndex = function.firstIndex(of: "(") { return String(function[..<startIndex]) } else { return function } } private func log(_ msg: Any? = nil, _ prefix: String = "⚫", _ file: String = #file, _ function: String = #function, _ line: Int = #line) { #if SIMULATOR let isUseConsoleLog: Bool = true #else #if QA let isUseConsoleLog: Bool = true #else let isUseConsoleLog: Bool = false #endif #endif TinyLog.queue.sync(execute: DispatchWorkItem(block: { if let msg = msg { if let filterString = TinyLog.filterString, !filterString.isEmpty { if "\(msg)".contains(filterString) { if isUseConsoleLog { NSLog("\(prefix)\(fileName(file)).\(TinyLog.stripParameters ? functionNameByStrippingParameters(function) : function):\(line) - \(msg)") } } } else { if isUseConsoleLog { NSLog("\(prefix)\(fileName(file)).\(TinyLog.stripParameters ? functionNameByStrippingParameters(function) : function):\(line) - \(msg)") } } } else { if isUseConsoleLog { NSLog("\(prefix)\(fileName(file)).\(TinyLog.stripParameters ? functionNameByStrippingParameters(function) : function):\(line)") } } })) } public func logi(_ msg: Any? = nil, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { if TinyLog.isShowInfoLog { log(msg, "🔵", file, function, line) } } public func logv(_ msg: Any? = nil, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { if TinyLog.isShowInfoLog { log(msg, "⚫", file, function, line) } // I put a black circle instead of black heart since it's available from iOS 10.2. } public func logd(_ msg: Any? = nil, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { if TinyLog.isShowInfoLog { log(msg, "⚪", file, function, line) } } public func logw(_ msg: Any? = nil, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { if TinyLog.isShowErrorLog { log(msg, "🤔", file, function, line) } } public func loge(_ msg: Any? = nil, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { if TinyLog.isShowErrorLog { log(msg, "😡", file, function, line) } } public func logc(_ msg: Any? = nil, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { if TinyLog.isShowErrorLog { log(msg, "💥", file, function, line) } } func logDict(_ dict: Any?, _ file: String = #file, _ function: String = #function, _ line: Int = #line) { if TinyLog.isShowInfoLog { if let dict = dict as? Dictionary<AnyHashable, Any> { log("\(dict as AnyObject)", "⚫", file, function, line) } } }
34.385621
160
0.614522
28133af555c560cadf455e3c1b3dcde88db231c6
3,642
// // FileDestination.swift // JustLog // // Created by Alberto De Bortoli on 20/12/2016. // Copyright © 2017 Just Eat. All rights reserved. // import Foundation import SwiftyBeaver public class FileDestination: BaseDestination { public var logFileURL: URL? public var syncAfterEachWrite: Bool = false override public var defaultHashValue: Int {return 2} let fileManager = FileManager.default var fileHandle: FileHandle? public override init() { super.init() levelColor.verbose = "📣 " levelColor.debug = "📝 " levelColor.info = "ℹ️ " levelColor.warning = "⚠️ " levelColor.error = "☠️ " levelString.verbose = "" levelString.debug = "" levelString.info = "" levelString.warning = "" levelString.error = "" } override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any?) -> String? { let formattedString = super.send(level, msg: msg, thread: thread, file: file, function: function, line: line, context: context) if let str = formattedString { let _ = saveToFile(str: str) } return formattedString } deinit { // close file handle if set if let fileHandle = fileHandle { fileHandle.closeFile() } } /// appends a string as line to a file. /// returns boolean about success func saveToFile(str: String) -> Bool { guard let url = logFileURL else { return false } do { if fileManager.fileExists(atPath: url.path) == false { // create file if not existing let line = str + "\n" try line.write(to: url, atomically: true, encoding: .utf8) #if os(iOS) || os(watchOS) if #available(iOS 10.0, watchOS 3.0, *) { var attributes = try fileManager.attributesOfItem(atPath: url.path) attributes[FileAttributeKey.protectionKey] = FileProtectionType.none try fileManager.setAttributes(attributes, ofItemAtPath: url.path) } #endif } else { // append to end of file if fileHandle == nil { // initial setting of file handle fileHandle = try FileHandle(forWritingTo: url as URL) } if let fileHandle = fileHandle { _ = fileHandle.seekToEndOfFile() let line = str + "\n" if let data = line.data(using: String.Encoding.utf8) { fileHandle.write(data) if syncAfterEachWrite { fileHandle.synchronizeFile() } } } } return true } catch { print("SwiftyBeaver File Destination could not write to file \(url).") return false } } /// deletes log file. /// returns true if file was removed or does not exist, false otherwise public func deleteLogFile() -> Bool { guard let url = logFileURL, fileManager.fileExists(atPath: url.path) == true else { return true } do { try fileManager.removeItem(at: url) fileHandle = nil return true } catch { print("SwiftyBeaver File Destination could not remove file \(url).") return false } } }
33.412844
135
0.53844
012123102bb6ba8ff4fefe2f36e56fb8199dbb1a
1,086
// // DateValueFormatter.swift // Ride // // Created by William Henderson on 3/22/17. // Copyright © 2017 Knock Softwae, Inc. All rights reserved. // import Foundation import Charts class DateValueFormatter: NSObject, IAxisValueFormatter { private var dateFormatter: DateFormatter! private var yearDateFormatter: DateFormatter! private var timeInterval: Double! init(timeInterval: Double, dateFormat: String) { super.init() self.timeInterval = timeInterval self.dateFormatter = DateFormatter() self.dateFormatter.dateFormat = dateFormat self.yearDateFormatter = DateFormatter() self.yearDateFormatter.dateFormat = dateFormat + " ''yy" } func stringForValue(_ value: Double, axis: AxisBase?) -> String { let date = Date(timeIntervalSinceReferenceDate: value*self.timeInterval) if (date.isThisYear()) { return self.dateFormatter.string(from: date) } else { return self.yearDateFormatter.string(from: date) } } }
27.846154
80
0.656538
091fe9d69976214ccffa3664c7593754749d69ae
1,603
// // RxMoyaProviderType+Cache.swift // MoyaMapper // // Created by LinXunFeng on 2018/9/26. // import Moya import RxSwift #if !COCOAPODS import RxMoya import CacheMoyaMapper #endif public extension Reactive where Base: MoyaProviderType { /** 缓存网络请求: - 如果本地无缓存,直接返回网络请求到的数据 - 如果本地有缓存,先返回缓存,再返回网络请求到的数据 - 只会缓存请求成功的数据(缓存的数据 response 的状态码为 MMStatusCode.cache) - 适用于APP首页数据缓存 */ func cacheRequest( _ target: Base.Target, alwaysFetchCache: Bool = false, callbackQueue: DispatchQueue? = nil, cacheType: MMCache.CacheKeyType = .default ) -> Observable<Response> { var originRequest = request(target, callbackQueue: callbackQueue).asObservable() var cacheResponse: Response? = nil if alwaysFetchCache { cacheResponse = MMCache.shared.fetchResponseCache(target: target) } else { if MMCache.shared.isNoRecord(target, cacheType: cacheType) { MMCache.shared.record(target) cacheResponse = MMCache.shared.fetchResponseCache(target: target) } } // 更新缓存 originRequest = originRequest.map { response -> Response in if let resp = try? response.filterSuccessfulStatusCodes() { MMCache.shared.cacheResponse(resp, target: target) } return response } guard let lxf_cacheResponse = cacheResponse else { return originRequest } return Observable.just(lxf_cacheResponse).concat(originRequest) } }
28.625
88
0.626949
33dd49f5f4d7c64e5f7bfe34e62b03e9e7afd236
1,098
/* Mission2 RGB LED Control The Red, Green and Blue LED blink one by one. The delay between each flash is 1s. The circuit: - Connect the anode (long leg) of each LED to digital pins D16, D17 and D18 (via a 1k ohm resistor). - Connect the cathodes (short leg) to the SwiftIO’s ground. created 2019 by Orange J Add more LEDs to your circuit. Don’t forget the current-limiting resistors. You will need to declare the new pins in your code and set them all to OUTPUT. Try to simulate traffic light logic. This example code is in the public domain. Visit madmachine.io for more info. */ import SwiftIO import MadBoard // Initialize three LEDs. let red = DigitalOut(Id.D16) let green = DigitalOut(Id.D17) let blue = DigitalOut(Id.D18) while true { // Turn on red LED for 1 second, then off. red.write(true) sleep(ms: 1000) red.write(false) // Turn on green LED for 1 second, then off. green.write(true) sleep(ms: 1000) green.write(false) // Turn on blue LED for 1 second, then off. blue.high() sleep(ms: 1000) blue.low() }
26.142857
102
0.690346
f4f077f7dbe7eacb198a73276ee522fee5b1dad6
1,719
// // AppDelegate.swift // Example // // Created by Ben on 07/03/2016. // Copyright © 2016 Polydice, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.white window?.rootViewController = UINavigationController(rootViewController: ExampleViewController()) window?.makeKeyAndVisible() return true } }
39.976744
148
0.754508
9c5747bc2ccbbbd5f4e8da1e3d03b5575f3e66c8
6,879
/* * Copyright 2015 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /** Extension for adding Auto-Layout constraints to a UIView. */ extension UIView { /** Adds `views` as subviews to this view. - parameter views: The array of `UIView` objects to add. - parameter translatesAutoresizingMaskIntoConstraints: For every subview that is added, its `translatesAutoresizingMaskIntoConstraints` property is set to this value. Defaults to false. */ internal func bky_addSubviews( _ subviews: [UIView], translatesAutoresizingMaskIntoConstraints: Bool = false) { for subview in subviews { subview.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints addSubview(subview) } } /** Adds all layout constraints inside of `constraints` to the view. - parameter constraints: Array of objects of type `NSLayoutConstraint` or `[NSLayoutConstraint]`. */ internal func bky_addConstraints(_ constraints: [AnyObject]) { for object in constraints { if let layoutConstraint = object as? NSLayoutConstraint { addConstraint(layoutConstraint) } else if let layoutConstraints = object as? [NSLayoutConstraint] { addConstraints(layoutConstraints) } else { bky_assertionFailure("Unsupported object type specified inside the `constraints` array: " + "\(type(of: object)). Values inside this array must be of type `NSLayoutConstraint` " + "or `[NSLayoutConstraint]`") } } } /** For each visual format constraint inside of `visualFormatConstraints`, this method creates and adds a layout constraint to the view via: NSLayoutConstraint.constraintsWithVisualFormat(visualFormat, options: [], metrics: metrics, views: views) - parameter visualFormatConstraints: Array of `String`s that follow Apple's Auto-Layout Visual Format language. - parameter metrics: Value that is passed to the `metrics| parameter of NSLayoutConstraint.constraintsWithVisualFormat(_options:metrics:views:). - parameter views: Value that is passed to the `views` parameter of NSLayoutConstraint.constraintsWithVisualFormat(_options:metrics:views:). */ internal func bky_addVisualFormatConstraints( _ visualFormatConstraints: [String], metrics: [String: Any]?, views: [String: Any]) { for visualFormat in visualFormatConstraints { let constraints = NSLayoutConstraint.constraints(withVisualFormat: visualFormat, options: [], metrics: metrics, views: views) addConstraints(constraints) } } /** Adds a `NSLayoutAttribute.Width` constraint to this view, where this view's width must equal a constant value. - parameter width: The width of the view - parameter priority: The priority to use for the constraint. Defaults to `UILayoutPriorityRequired`. - returns: The constraint that was added. */ @discardableResult internal func bky_addWidthConstraint( _ width: CGFloat, priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width) constraint.priority = priority addConstraint(constraint) return constraint } /** Adds a `NSLayoutAttribute.Height` constraint to this view, where this view's height must equal a constant value. - parameter height: The height of the view - parameter priority: The priority to use for the constraint. Defaults to `UILayoutPriorityRequired`. - returns: The constraint that was added. */ @discardableResult internal func bky_addHeightConstraint( _ height: CGFloat, priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { let constraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height) constraint.priority = priority addConstraint(constraint) return constraint } /** Convenience method for updating constraint values related to this view. - parameter animated: Flag indicating whether the update of constraints should be animated. If set to `true`, this method calls `UIView.animateWithDuration(:delay:options:animations:completion:)`. - parameter duration: [Optional] If `animated` is set to `true`, this is the value that is passed to `UIView.animateWithDuration(...)` for its `duration` value. By default, this value is set to `0.3`. - parameter delay: [Optional] If `animated` is set to `true`, this is the value that is passed to `UIView.animateWithDuration(...)` for its `delay` value. By default, this value is set to `0.0`. - parameter options: [Optional] If `animated` is set to `true`, this is the value that is passed to `UIView.animateWithDuration(...)` for its `options` value. By default, this value is set to `.CurveEaseInOut`. - parameter update: A closure containing the changes to commit to the view (which is where your constraints should be updated). If `animated` is set to `true`, this is the value that is passed to `UIView.animateWithDuration(...)` for its `animations` value. - parameter completion: A closure that is executed when the `updateConstraints` closure ends. If `animated` is set to `true`, this is the value that is passed to `UIView.animateWithDuration(...)` for its `completion` value. By default, this value is set to `nil`. */ internal func bky_updateConstraints( animated: Bool, duration: TimeInterval = 0.3, delay: TimeInterval = 0.0, options: UIViewAnimationOptions = UIViewAnimationOptions(), update: @escaping () -> Void, completion: ((Bool) -> Void)? = nil) { let updateView = { update() self.setNeedsUpdateConstraints() self.superview?.layoutIfNeeded() } if animated { // Force pending layout changes to complete self.superview?.layoutIfNeeded() UIView.animate(withDuration: duration, delay: delay, options: options, animations: { updateView() }, completion: completion) } else { updateView() completion?(true) } } }
39.534483
100
0.715656
50bb980ff868871a20342d4a745408b7d5baa1f4
4,755
// // CreateOrRestoreWallet.IntroPlayerView.swift // p2p_wallet // // Created by Chung Tran on 25/02/2022. // import Foundation import AVFoundation import UIKit extension CreateOrRestoreWallet { final class IntroPlayerView: UIView { // MARK: - Override default layer override class var layerClass: AnyClass { return AVPlayerLayer.self } private var playerLayer: AVPlayerLayer { return layer as! AVPlayerLayer } private var player: AVPlayer! { playerLayer.player } private var currentItem: AVPlayerItem { .init(url: Bundle.main.url(forResource: "onboarding_0\(step)_" + theme, withExtension: "mp4")!) } // MARK: - Properties private lazy var placeholderImageView = UIImageView(image: .onboardingLastFrame) private let theme: String private var step = 1 private var movingToNextStep = false var completion: (() -> Void)? private var isAnimating = false private var isFinished = false private var activeResigned = false init(userInterfaceStyle: UIUserInterfaceStyle) { theme = userInterfaceStyle == .dark ? "b": "w" super.init(frame: .zero) configureForAutoLayout() addSubview(placeholderImageView) placeholderImageView.autoPinEdgesToSuperviewEdges() placeholderImageView.isHidden = true playerLayer.player = AVPlayer(playerItem: currentItem) bind() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Methods private func bind() { NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { [weak self] _ in guard let self = self else {return} switch self.step { case 1: if !self.movingToNextStep { self.player.seek(to: .zero) self.player.play() } else { self.step += 1 // show placeholder to fix slashing problem when changing video file self.placeholderImageView.isHidden = false self.setNeedsDisplay() DispatchQueue.main.async { [weak self] in guard let self = self else {return} // replace video file self.player.replaceCurrentItem(with: self.currentItem) self.player.rate = 1 self.movingToNextStep = false self.player.play() DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) { [weak self] in self?.placeholderImageView.isHidden = true } } } case 2: self.completion?() self.isFinished = true self.isAnimating = false default: return } } NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) } func resume() { if !player.isPlaying && step < 2 { player.seek(to: .zero) player.play() } } func playNext() { guard !isAnimating else {return} guard step < 2 else { completion?() isAnimating = false isFinished = true return } isAnimating = true player.rate = 2 movingToNextStep = true } @objc func appWillResignActive() { activeResigned = true } @objc func appDidBecomeActive() { guard activeResigned, !isFinished else {return} player.play() } } } private extension AVPlayer { var isPlaying: Bool { return rate != 0 && error == nil } }
34.456522
161
0.501367
0816f2e809a1d5c32cac82b327b7a63fc2b9bc53
948
// // Country.swift // MVVM Demo // // Created by Malav Soni on 08/12/19. // Copyright © 2019 Malav Soni. All rights reserved. // import UIKit struct Country:Codable { var name:String var capital:String init(withName name:String,andCapital capital:String) { self.name = name self.capital = capital } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.name, forKey: .name) try container.encode(self.capital, forKey: .capital) } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.name = try container.decode(String.self, forKey: .name) self.capital = try container.decode(String.self, forKey: .capital) } enum CodingKeys:String,CodingKey { case name case capital } }
25.621622
74
0.638186
d6227990473a2d2b1f1670fd620345f19e452fc6
3,228
// // Copied from Saoud M. Rizwan // https://medium.com/@sdrzn/swift-4-codable-lets-make-things-even-easier-c793b6cf29e1 // import Foundation public class CacheStorage { fileprivate init() { } enum Directory { case documents case caches } static fileprivate func getURL(for directory: Directory) -> URL { var searchPathDirectory: FileManager.SearchPathDirectory switch directory { case .documents: searchPathDirectory = .documentDirectory case .caches: searchPathDirectory = .cachesDirectory } if let url = FileManager.default.urls(for: searchPathDirectory, in: .userDomainMask).first { return url } else { fatalError("Could not create URL for specified directory!") } } static func store<T: Encodable>(_ object: T, to directory: Directory, as fileName: String) { let url = getURL(for: directory).appendingPathComponent(fileName, isDirectory: false) let encoder = JSONEncoder() do { let data = try encoder.encode(object) if FileManager.default.fileExists(atPath: url.path) { try FileManager.default.removeItem(at: url) } FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil) print("saved") } catch { fatalError(error.localizedDescription) } } static func retrieve<T: Decodable>(_ fileName: String, from directory: Directory, as type: T.Type) -> T? { let url = getURL(for: directory).appendingPathComponent(fileName, isDirectory: false) if !FileManager.default.fileExists(atPath: url.path) { return nil } if let data = FileManager.default.contents(atPath: url.path) { let decoder = JSONDecoder() do { let model = try decoder.decode(type, from: data) return model } catch { return nil } } else { fatalError("No data at \(url.path)!") } } static func clear(_ directory: Directory) { let url = getURL(for: directory) do { let contents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: []) for fileUrl in contents { try FileManager.default.removeItem(at: fileUrl) } } catch { fatalError(error.localizedDescription) } } static func remove(_ fileName: String, from directory: Directory) { let url = getURL(for: directory).appendingPathComponent(fileName, isDirectory: false) if FileManager.default.fileExists(atPath: url.path) { do { try FileManager.default.removeItem(at: url) } catch { fatalError(error.localizedDescription) } } } static func fileExists(_ fileName: String, in directory: Directory) -> Bool { let url = getURL(for: directory).appendingPathComponent(fileName, isDirectory: false) return FileManager.default.fileExists(atPath: url.path) } }
32.938776
125
0.601921
382d1396bea59e21b4eb5acb246c595dfd1b4cde
2,402
import Foundation import RobinHood protocol ChildSubscriptionFactoryProtocol { func createEventEmittingSubscription( remoteKey: Data, eventFactory: @escaping EventEmittingFactoryClosure ) -> StorageChildSubscribing func createEmptyHandlingSubscription(remoteKey: Data) -> StorageChildSubscribing } final class ChildSubscriptionFactory { let storageFacade: StorageFacadeProtocol let logger: LoggerProtocol let operationManager: OperationManagerProtocol let localKeyFactory: ChainStorageIdFactoryProtocol let eventCenter: EventCenterProtocol private lazy var repository: AnyDataProviderRepository<ChainStorageItem> = { let coreDataRepository: CoreDataRepository<ChainStorageItem, CDChainStorageItem> = storageFacade.createRepository() return AnyDataProviderRepository(coreDataRepository) }() init( storageFacade: StorageFacadeProtocol, operationManager: OperationManagerProtocol, eventCenter: EventCenterProtocol, localKeyFactory: ChainStorageIdFactoryProtocol, logger: LoggerProtocol ) { self.storageFacade = storageFacade self.operationManager = operationManager self.eventCenter = eventCenter self.localKeyFactory = localKeyFactory self.logger = logger } } extension ChildSubscriptionFactory: ChildSubscriptionFactoryProtocol { func createEventEmittingSubscription( remoteKey: Data, eventFactory: @escaping EventEmittingFactoryClosure ) -> StorageChildSubscribing { let localKey = localKeyFactory.createIdentifier(for: remoteKey) return EventEmittingStorageSubscription( remoteStorageKey: remoteKey, localStorageKey: localKey, storage: repository, operationManager: operationManager, logger: logger, eventCenter: eventCenter, eventFactory: eventFactory ) } func createEmptyHandlingSubscription(remoteKey: Data) -> StorageChildSubscribing { let localKey = localKeyFactory.createIdentifier(for: remoteKey) return EmptyHandlingStorageSubscription( remoteStorageKey: remoteKey, localStorageKey: localKey, storage: repository, operationManager: operationManager, logger: logger ) } }
32.90411
90
0.71149
09a838c9c6b7302953dfe2426f0c3b6b12dc8151
2,697
// // This source file is part of Kombucha, an open source project by Wayfair // // Copyright (c) 2019 Wayfair, LLC. // Licensed under the 2-Clause BSD License // // See LICENSE.md for license information // import Basic import JSONCheck import Prelude public extension JSONCheck where A == CheckResult { static let allChecks: [String: JSONCheck] = [ "array-consistency": JSONCheck.arrayConsistency, "empty-arrays": JSONCheck.emptyArrays, "empty-objects": JSONCheck.emptyObjects, "flag-new-keys": JSONCheck.flagNewKeys, "string-bools": JSONCheck.stringBools, "string-numbers": JSONCheck.stringNumbers, "structure": JSONCheck.structure, "strict-equality": JSONCheck.strictEquality ] } public extension JSONCheck where A == CheckResults { static let `default` = defaultErrors <> defaultWarnings <> defaultInfos static let defaultErrors = JSONCheck<CheckResult>.structure.map(mapToErrors) static let defaultInfos = ( JSONCheck<CheckResult>.emptyArrays <> JSONCheck<CheckResult>.emptyObjects <> JSONCheck<CheckResult>.stringBools <> JSONCheck<CheckResult>.flagNewKeys ).map(mapToInfos) static let defaultWarnings = JSONCheck<CheckResult>.arrayConsistency.map(mapToWarnings) } public extension SnapConfiguration { var jsonCheck: JSONCheck<CheckResults> { guard let preferences = preferences else { return .default } return preferences // given the user’s preferences for this test .errors // with all the errors they requested that we run .compactMap { JSONCheck<CheckResult>.allChecks[$0] } // look up the corresponding check function .reduce(.empty, <>) // combine all the checks we found into one big one .map(mapToErrors) // make sure they appear as `ERROR:`s <> preferences .infos .compactMap { JSONCheck<CheckResult>.allChecks[$0] } .reduce(.empty, <>) .map(mapToInfos) <> preferences .warnings .compactMap { JSONCheck<CheckResult>.allChecks[$0] } .reduce(.empty, <>) .map(mapToWarnings) } } func sanitizePathComponent(_ string: String) -> String { return string .replacingOccurrences(of: "\\W+", with: "-", options: .regularExpression) .replacingOccurrences(of: "^-|-$", with: "", options: .regularExpression) } func sha256(string: String) -> String { let sha = SHA256(string) return sha.digestString() }
33.296296
112
0.625881
bbd4392b14b0945ffd86cfc71db3c9d18258c16c
339
// // String+Extensions.swift // DPKit // // Created by Drew Pitchford on 6/27/18. // import Foundation extension String: PopoverDisplayable { public var displayText: String { return self } public func isValid(givenMaxLength max: Int) -> Bool { return self.count <= max } }
15.409091
58
0.587021
0870bca7c40b3200de3bd5b7e48e6a253b06b6c4
2,195
// // AppDelegate.swift // iOS-CoreML-Yolo // // Created by Sri Raghu Malireddi on 16/06/17. // Copyright © 2017 Sri Raghu Malireddi. 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.702128
285
0.755809
bff49d04c50f03470079e5f22bdbad8df892c4fa
653
// // Copyright © 2021 Rosberry. All rights reserved. // import Photos public protocol HasFetchCollectionsService { var fetchCollectionsService: FetchCollectionsService { get } } public protocol FetchCollectionsService { func fetchCollections(with type: PHAssetCollectionType, subtype: PHAssetCollectionSubtype, options: PHFetchOptions?) -> [MediaItemsCollection] func fetchAssetCollections(localIdentifiers: [String], options: PHFetchOptions?) -> PHAssetCollection? func fetchMediaItems(in collection: PHAssetCollection, mediaType: PHAssetMediaType?) -> PHFetchResult<PHAsset>? }
36.277778
115
0.732006
625574e8909003066cad3f82dec4092cb67a8428
2,127
// // InterfaceController.swift // watchOS Extension // // Created by Ignacio Romero on 11/2/16. // Copyright © 2017 DZN. All rights reserved. // import WatchKit import Foundation import Iconic class InterfaceController: WKInterfaceController { @IBOutlet weak var imageView: WKInterfaceImage! @IBOutlet weak var upButtonImageView: WKInterfaceImage! @IBOutlet weak var downButtonImageView: WKInterfaceImage! var scale: UInt = 10 let maxScale: UInt = 30 let imageSize = CGSize(width: 88, height: 88) let buttonSize = CGSize(width: 30, height: 30) let githubIcon = FontAwesomeIcon.githubIcon let upArrowIcon = FontAwesomeIcon.angleUpIcon let downArrowIcon = FontAwesomeIcon.angleDownIcon override class func initialize() { // It is important to register the icon font as soon as possible, // and make the resources available right after launching the app. // // This example uses Awesome Font // http://fontawesome.io/cheatsheet/ FontAwesomeIcon.register() } override func awake(withContext context: Any?) { super.awake(withContext: context) updateImage(scale) let upArrowImage = upArrowIcon.image(ofSize: buttonSize, color: .white) upButtonImageView.setImage(upArrowImage) let downArrowImage = downArrowIcon.image(ofSize: buttonSize, color: .white) downButtonImageView.setImage(downArrowImage) } @IBAction func didPressUp() { if scale > maxScale { return } scale += 1 updateImage(scale) } @IBAction func didPressDown() { if scale <= 2 { return } scale -= 1 updateImage(scale) } func updateImage(_ scale: UInt) { let width = CGFloat(4 * scale) let imgSize = CGSize(width: width, height: width) let image = githubIcon.image(ofSize: imgSize, color: .white) imageView.setImage(image) } }
26.5875
83
0.61448
903b7b08e826633c2e8ed847e43abffd515f39ae
1,598
/* The MIT License (MIT) Copyright (c) 2018 Danil Gontovnik 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 open class ViewController: UIViewController { // MARK: - Vars open var hidesNavigationBarWhenPushed = false var viewWillAppearNavigationBarUpdatesBlock: (() -> Void)? var fakeNavigationBar: NavigationBar? // MARK: - Lifecycle override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewWillAppearNavigationBarUpdatesBlock?() viewWillAppearNavigationBarUpdatesBlock = nil } }
39.95
79
0.757822
08c8f3d0c774e36faf250621bf83aa67fe76e99d
617
// // Product.swift // DemoCheckoutApp // // Created by Olha Prokopiuk on 4/27/18. // Copyright © 2018 Olha Prokopiuk. All rights reserved. // import Foundation struct Category: Codable { let title: String let products: [Product] } struct Product: Codable { let id: String let name: String let details: String let price: Float } extension Product: Hashable { public var hashValue: Int { return id.hashValue } public static func == (lhs: Product, rhs: Product) -> Bool { return lhs.id == rhs.id } }
19.28125
64
0.581848
9183ccf0c376abfb83818c384498a9ce26c218c1
1,467
// // CategoriesCell.swift // Yelp // // Created by hollywoodno on 4/9/17. // Copyright © 2017 Timothy Lee. All rights reserved. // import UIKit // Allows the ability to capture which of the switch cells had their onSwitch toggled @objc protocol CategoriesCellDelegate { @objc optional func CategoriesCell(categoriesCell: CategoriesCell, didChangeValue value: Bool) } class CategoriesCell: UITableViewCell { @IBOutlet weak var switchLabel: UILabel! @IBOutlet weak var onSwitch: UISwitch! // A class that subclasses CategoriesCellDelegate, optionally declare itself as a delegate // and optionally implements it's optional protocol weak var delegate: CategoriesCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code // Wait for user interaction with switch onSwitch.addTarget(self, action: #selector(CategoriesCell.switchValueChanged), for: UIControlEvents.valueChanged) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // User toggled onSwitch func switchValueChanged() { // If I self has a delegate, see if they implemented // the optional categoriesCell function and call it. delegate?.CategoriesCell?(categoriesCell: self, didChangeValue: onSwitch.isOn) } }
31.891304
121
0.706203
39f32fd2949d01b67345e81df69a2a499150e0d5
1,200
// // ResetPassword2Controller.swift // ZuYu2 // // Created by million on 2020/8/3. // Copyright © 2020 million. All rights reserved. // import UIKit class ResetPassword2Controller: UIViewController { @IBOutlet weak var pwdTf: CustomTextField! @IBOutlet weak var confirmPwdTf: CustomTextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func sure(_ sender: Any) { guard let pwd = pwdTf.text, !pwd.isEmpty else { view.makeToast("请输入密码") return } guard let confirmPwd = confirmPwdTf.text, !confirmPwd.isEmpty else { view.makeToast("请再次确认密码") return } navigationController?.popToRootViewController(animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
26.086957
106
0.635833
ebf84277f45a30c26e98fcbe400e428a7fd769f3
3,283
// // ViewController.swift // My Favourite Recipes UIKit // // Created by Chris Barker on 07/02/2020. // Copyright © 2020 Packt. All rights reserved. // import UIKit var mockData = [String]() class DataSourceA: NSObject, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mockData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = mockData[indexPath.row] return cell } } class ViewController: UIViewController, UITableViewDelegate { var tableView: UITableView! var dataSource: UITableViewDataSource! override func viewDidLoad() { // UITableView mockData = ["Recipe 1", "Recipe 2", "Recipe 3", "Recipe 4", "Recipe 5", "Recipe 6"] dataSource = DataSourceA() tableView = UITableView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 400)) tableView.delegate = self tableView.dataSource = dataSource tableView.tableFooterView = UIView() view.addSubview(tableView) // Button with corner radius let button = UIButton(frame: CGRect(x: 0, y: 400, width: view.bounds.width - 60, height: 55)) button.center = CGPoint(x: view.center.x, y: button.center.y) button.setTitle("Border & Radius", for: .normal) button.backgroundColor = .blue button.layer.cornerRadius = 15 button.layer.borderColor = UIColor.black.cgColor button.layer.borderWidth = 8 button.layer.masksToBounds = true view.addSubview(button) // View with a Gradient let gradientView = UIView(frame: CGRect(x: 0, y: 490, width: view.bounds.width - 150, height: 150)) gradientView.center = CGPoint(x: view.center.x, y: gradientView.center.y) let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.frame.size = gradientView.frame.size gradientLayer.colors = [UIColor.white.cgColor, UIColor.blue.cgColor, UIColor.green.cgColor] gradientView.layer.addSublayer(gradientLayer) view.addSubview(gradientView) // UILabel with Strikethough let label = UILabel(frame: CGRect(x: 0, y: 640, width: view.bounds.width - 150, height: 150)) label.textAlignment = .center label.center = CGPoint(x: view.center.x, y: label.center.y) let attributedString = NSMutableAttributedString(string: "Strike through me") attributedString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSRange(location: 7, length: 7)) label.attributedText = attributedString view.addSubview(label) tableView.reloadData() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { present(SecondViewController(), animated: true, completion: nil) } } class SecondViewController: UIViewController { }
32.186275
130
0.625343
561f47c5c2a2d3870436d7971e5db4565c191a66
2,127
// // Country.swift // CountryCode // // Created by Created by WeblineIndia on 01/07/20. // Copyright © 2020 WeblineIndia . All rights reserved. // import Foundation open class Country: NSObject { open var countryCode: String open var phoneExtension: String open var isMain: Bool open var flag : String public static var emptyCountry: Country { return Country(countryCode: "", phoneExtension: "", isMain: true,flag: "") } //init method for country code phone extension and flag public init(countryCode: String, phoneExtension: String, isMain: Bool, flag: String) { self.countryCode = countryCode self.phoneExtension = phoneExtension self.isMain = isMain self.flag = flag } //Method used to find current country of the user public static var currentCountry: Country { let localIdentifier = Locale.current.identifier //returns identifier of your telephones country/region settings let locale = NSLocale(localeIdentifier: localIdentifier) if let countryCode = locale.object(forKey: .countryCode) as? String { return Countries.countryFromCountryCode(countryCode.uppercased()) } return Country.emptyCountry } /// Constructor to initialize a country /// /// - Parameters: /// - countryCode: the country code /// - phoneExtension: phone extension /// - isMain: Bool /// Obatin the country name based on current locale @objc open var name: String { let localIdentifier = Locale.current.identifier //returns identifier of your telephones country/region settings let locale = NSLocale(localeIdentifier: localIdentifier) if let country: String = locale.displayName(forKey: .countryCode, value: countryCode.uppercased()) { return country } else { return "Invalid country code" } } } /// compare to country /// /// - Parameters: /// - lhs: Country /// - rhs: Country /// - Returns: Bool public func ==(lhs: Country, rhs: Country) -> Bool { return lhs.countryCode == rhs.countryCode }
30.826087
122
0.666667
6a0f0a2678fcbc8b37d574e86ad444dc0632cc41
4,457
// // FirstLevel.swift // FirstLevel // // Created by Kim David Hauser on 18.09.21. // import Foundation import SpriteKit class CityNightLevel: BaseLevel { init() { super.init(level: .CityNight, levelName: "City Night", bgImageName: "CityNight") } override func initLevelConfig() { self.levelConfigs[.easy] = LevelConfig( difficulty: .easy, zombieCountAtOnce: 2, syringePickupsAtOnce: 2, certificatePickupsAtOnce: 1, duration: .Minutes1 ) for _ in 0..<4{ let way2Go:CGFloat = CGFloat.random(in: 350 ... 900) let exitWay1:SKAction = SKAction.moveBy(x: 60, y: 10, duration: 0.2) let exitWay2:SKAction = SKAction.moveBy(x: 60, y: -10, duration: 0.2) self.levelConfigs[.easy]?.zombiePaths.append( BasePath( initPos: CGPoint(x: -566.0, y: -174.75), initScale: 1.0, path: SKAction.sequence([ SKAction.moveBy(x: way2Go, y: 0, duration: 6.5), SKAction.group([ SKAction.moveBy(x: -100, y: -210, duration: 1.0), SKAction.scale(to: 3.65, duration: 1.0) ]) ]), exitPath: SKAction.sequence([ exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2 ]) ) ) } for _ in 0..<4{ let way2Go:CGFloat = CGFloat.random(in: 350 ... 900) let exitWay1:SKAction = SKAction.moveBy(x: -60, y: 10, duration: 0.2) let exitWay2:SKAction = SKAction.moveBy(x: -60, y: -10, duration: 0.2) self.levelConfigs[.easy]?.zombiePaths.append( BasePath( initPos: CGPoint(x: 566.0, y: -174.75), initScale: 1.0, path: SKAction.sequence([ SKAction.moveBy(x: -way2Go, y: 0, duration: 6.5), SKAction.group([ SKAction.moveBy(x: 100, y: -210, duration: 1.0), SKAction.scale(to: 3.65, duration: 1.0) ]) ]), exitPath: SKAction.sequence([ exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2, exitWay1, exitWay2 ]) ) ) } // ========= DIFFICULTY: MEDIUM ========= self.levelConfigs[.medium] = LevelConfig( difficulty: .medium, zombieCountAtOnce: 3, syringePickupsAtOnce: 2, certificatePickupsAtOnce: 2, duration: .Minutes2 ) self.levelConfigs[.medium]?.zombiePaths.append(contentsOf: (self.levelConfigs[.easy]!.zombiePaths)) self.levelConfigs[.medium]?.zombiePaths.shuffle() // ========= DIFFICULTY: HARD ========= self.levelConfigs[.hard] = LevelConfig( difficulty: .hard, zombieCountAtOnce: 4, syringePickupsAtOnce: 3, certificatePickupsAtOnce: 3, duration: .Minutes3 ) self.levelConfigs[.hard]?.zombiePaths.append(contentsOf: (self.levelConfigs[.easy]!.zombiePaths)) self.levelConfigs[.hard]?.zombiePaths.shuffle() // ========= DIFFICULTY: NIGHTMARE ========= self.levelConfigs[.nightmare] = LevelConfig( difficulty: .nightmare, zombieCountAtOnce: 5, syringePickupsAtOnce: 4, certificatePickupsAtOnce: 2, duration: .Minutes5 ) self.levelConfigs[.nightmare]?.zombiePaths.append(contentsOf: (self.levelConfigs[.easy]!.zombiePaths)) self.levelConfigs[.nightmare]?.zombiePaths.shuffle() } }
38.094017
110
0.472066
dd9a2b6a58ca4315ed0c81541ffd8990ebf9adf4
100
import Foundation protocol XcodeControlling { func perform(_ action: XcodeAction) async throws }
16.666667
50
0.8
50185c0e412f6e56fa1790fa5e640a7bc9e17c4c
445
// // FirstTVCell.swift // TableViewAdvanceSample // // Created by Lahiru Chathuranga on 11/17/20. // import UIKit class FirstTVCell: UITableViewCell { 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 } }
18.541667
65
0.665169
75ccb860be00e15031e60245c9f7c919efe56dc8
8,138
// // TUSExecutor.swift // TUSKit // // Created by Mark Robert Masterson on 4/16/20. // import Foundation class TUSExecutor: NSObject, URLSessionDelegate { var customHeaders: [String: String] = [:] // MARK: Private Networking / Upload methods private func urlRequest(withFullURL url: URL, andMethod method: String, andContentLength contentLength: String?, andUploadLength uploadLength: String?, andHeaders headers: [String: String]) -> URLRequest { var request: URLRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30) request.httpMethod = method request.addValue(TUSConstants.TUSProtocolVersion, forHTTPHeaderField: "TUS-Resumable") if let contentLength = contentLength { request.addValue(contentLength, forHTTPHeaderField: "Content-Length") } if let uploadLength = uploadLength { request.addValue(uploadLength, forHTTPHeaderField: "Upload-Length") } for header in headers.merging(customHeaders, uniquingKeysWith: { (current, _) in current }) { request.addValue(header.value, forHTTPHeaderField: header.key) } return request } internal func create(forUpload upload: TUSUpload) { let request = urlRequest(withFullURL: TUSClient.shared.uploadURL, andMethod: "POST", andContentLength: upload.contentLength, andUploadLength: upload.uploadLength, andHeaders: ["Upload-Extension": "creation", "Upload-Metadata": upload.encodedMetadata]) let task = TUSClient.shared.tusSession.session.dataTask(with: request) { (data, response, error) in if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 201 { TUSClient.shared.logger.log(forLevel: .Info, withMessage:String(format: "File %@ created", upload.id)) // Set the new status and other props for the upload upload.status = .created // upload.contentLength = httpResponse.allHeaderFields["Content-Length"] as? String upload.uploadLocationURL = URL(string: httpResponse.allHeaderFieldsUpper()["LOCATION"]!, relativeTo: TUSClient.shared.uploadURL) //Begin the upload TUSClient.shared.updateUpload(upload) self.upload(forUpload: upload) } } } task.resume() } internal func upload(forUpload upload: TUSUpload) { /* If the Upload is from a file, turn into data. Loop through until file is fully uploaded and data range has been completed. On each successful chunk, save file to defaults */ //First we create chunks //MARK: FIX THIS TUSClient.shared.logger.log(forLevel: .Info, withMessage: String(format: "Preparing upload data for file %@", upload.id)) let uploadData = try! Data(contentsOf: URL(fileURLWithPath: String(format: "%@%@", TUSClient.shared.fileManager.fileStorePath(), upload.fileName))) // let fileName = String(format: "%@%@", upload.id, upload.fileType!) // let tusName = String(format: "TUS-%@", fileName) //let uploadData = try! UserDefaults.standard.data(forKey: tusName) //upload.data = uploadData // let chunks: [Data] = createChunks(forData: uploadData) // print(chunks.count) let chunks = dataIntoChunks(data: uploadData, chunkSize: TUSClient.shared.chunkSize * 1024 * 1024) //Then we start the upload from the first chunk self.upload(forChunks: chunks, withUpload: upload, atPosition: 0) } private func upload(forChunks chunks: [Data], withUpload upload: TUSUpload, atPosition position: Int) { TUSClient.shared.logger.log(forLevel: .Info, withMessage:String(format: "Upload starting for file %@ - Chunk %u / %u", upload.id, position + 1, chunks.count)) let request: URLRequest = urlRequest(withFullURL: upload.uploadLocationURL!, andMethod: "PATCH", andContentLength: upload.contentLength!, andUploadLength: nil, andHeaders: ["Content-Type":"application/offset+octet-stream", "Upload-Offset": upload.uploadOffset!, "Content-Length": String(chunks[position].count), "Upload-Metadata": upload.encodedMetadata]) let task = TUSClient.shared.tusSession.session.uploadTask(with: request, from: chunks[position], completionHandler: { (data, response, error) in if let httpResponse = response as? HTTPURLResponse { switch httpResponse.statusCode { case 200..<300: //success if (chunks.count > position+1 ){ upload.uploadOffset = httpResponse.allHeaderFieldsUpper()["UPLOAD-OFFSET"] TUSClient.shared.updateUpload(upload) self.upload(forChunks: chunks, withUpload: upload, atPosition: position+1) } else if (httpResponse.statusCode == 204) { TUSClient.shared.logger.log(forLevel: .Info, withMessage:String(format: "Chunk %u / %u complete", position + 1, chunks.count)) if (position + 1 == chunks.count) { TUSClient.shared.logger.log(forLevel: .Info, withMessage:String(format: "File %@ uploaded at %@", upload.id, upload.uploadLocationURL!.absoluteString)) TUSClient.shared.updateUpload(upload) TUSClient.shared.delegate?.TUSSuccess(forUpload: upload) TUSClient.shared.cleanUp(forUpload: upload) TUSClient.shared.status = .ready if (TUSClient.shared.currentUploads!.count > 0) { TUSClient.shared.createOrResume(forUpload: TUSClient.shared.currentUploads![0]) } } } case 400..<500: //reuqest error TUSClient.shared.delegate?.TUSFailure(forUpload: upload, withResponse: nil, andError: error) case 500..<600: //server TUSClient.shared.delegate?.TUSFailure(forUpload: upload, withResponse: nil, andError: error) default: break } } }) task.resume() } internal func cancel(forUpload upload: TUSUpload) { // TODO: Finish implementing this method? } private func dataIntoChunks(data: Data, chunkSize: Int) -> [Data] { var chunks = [Data]() var chunkStart = 0 while(chunkStart < data.count) { let remaining = data.count - chunkStart let nextChunkSize = min(chunkSize, remaining) let chunkEnd = chunkStart + nextChunkSize chunks.append(data.subdata(in: chunkStart..<chunkEnd)) chunkStart = chunkEnd } return chunks } // MARK: Private Networking / Other methods internal func get(forUpload upload: TUSUpload) { var request: URLRequest = URLRequest(url: upload.uploadLocationURL!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 30) request.httpMethod = "GET" // let task = TUSClient.shared.tusSession.session.downloadTask(with: request) { (url, response, error) in // TUSClient.shared.logger.log(forLevel: .Info, withMessage:response!.description) // } // TODO: Finish implementing this method? } }
50.546584
363
0.58405
fb55f6c2eb98db8d0bbf1e1fd76c23046cfe331a
2,618
import XCTest import Vapor import FluentSQLite @testable import Pagination final class PaginationTests: XCTestCase { var app: Application! var sqlConnection: SQLiteConnection! override func setUp() { super.setUp() self.app = try! Application.testable() self.sqlConnection = try! self.app.newConnection(to: .sqlite).wait() } override func tearDown() { self.sqlConnection.close() super.tearDown() } func testLinuxTestSuiteIncludesAllTests() { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) let thisClass = type(of: self) let linuxCount = thisClass.allTests.count let darwinCount = Int(thisClass .defaultTestSuite.testCaseCount) XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests") #endif } func testQuery() throws { let models: [TestModel] = try [ TestModel.create(name: "Test 1", on: self.sqlConnection), TestModel.create(name: "Test 2", on: self.sqlConnection), TestModel.create(name: "Test 3", on: self.sqlConnection), TestModel.create(name: "Test 4", on: self.sqlConnection), TestModel.create(name: "Test 5", on: self.sqlConnection) ] let pageInfo = try TestModel.query(on: self.sqlConnection).sort(\.id).getPage(current: 1).wait() XCTAssertEqual(pageInfo.total, models.count) XCTAssertEqual(pageInfo.data, models) } func testFilterQuery() throws { let model = try TestModel.create(name: "Test Filter", on: self.sqlConnection) let pageInfo = try TestModel.query(on: self.sqlConnection).filter(\TestModel.name == "Test Filter").getPage(current: 1).wait() XCTAssertEqual(pageInfo.total, 1) XCTAssertEqual(pageInfo.data.first?.name, model.name) } func testPaginationResponse() throws { for i in 0..<20 { try TestModel.create(name: "Test \(i)", on: self.sqlConnection) } let pageInfo = try TestModel.query(on: self.sqlConnection).getPage(current: 1).wait() let pageResponse = Paginated(from: pageInfo) XCTAssertEqual(pageInfo.total, 20) XCTAssertEqual(pageResponse.page.position.max, 2) } } // MARK: - All Tests extension PaginationTests { static var allTests = [ ("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests), ("testQuery", testQuery), ("testFilterQuery", testFilterQuery), ("testPaginationResponse", testPaginationResponse) ] }
34
134
0.649351
162d68af49f54d4d98fbabcfadc8a62cace6fade
459
// // SwiftUIView.swift // SwiftStudy // // Created by Zhu ChaoJun on 2020/4/27. // Copyright © 2020 Zhu ChaoJun. All rights reserved. // import SwiftUI @available(iOS 13.0.0, *) struct SwiftUIView: View { var body: some View { Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) } } @available(iOS 13.0.0, *) struct SwiftUIView_Previews: PreviewProvider { static var previews: some View { SwiftUIView() } }
19.125
71
0.64488
e68923ca790321972365493d564a932ff1220bf4
935
// // ReportDetails.swift // // Copyright © 2017 Detroit Block Works. All rights reserved. // import Foundation public struct ReportDetails : JSONContainer { public let organization: String? public let title: String public let questions: [Question] public struct Question : Codable { public let primary_key: String public let question: String public enum QuestionType : String, Codable { case datetime case file case note case select case text case textarea case multivaluelist } public let question_type: QuestionType public let answer_kept_private: Bool public let response_required: Bool public let select_values: [SelectValue]? public struct SelectValue : Codable { public let key: String public let name: String } } }
26.714286
62
0.614973
bf9e1b761c22654f6405cfebe040ac26156a8356
1,594
import Foundation import Substate import SubstateMiddleware struct Tasks: Model, SavedModel { var all: [Task] = [] struct Create: Action, FollowupAction { let body: String let followup: Action = Changed() } struct Update: Action, FollowupAction { let id: UUID let body: String let followup: Action = Changed() } struct Delete: Action, FollowupAction { let id: UUID let followup: Action = Changed() } struct Toggle: Action, FollowupAction { let id: UUID let followup: Action = Changed() } struct Changed: Action {} mutating func update(action: Action) { switch action { case let action as Create: all.append(Task(id: UUID(), date: Date(), body: action.body)) case let action as Update: all.firstIndex(where: { $0.id == action.id }).map { index in all[index].body = action.body } case let action as Delete: all.removeAll { $0.id == action.id } case let action as Toggle: all.firstIndex(where: { $0.id == action.id }).map { index in all[index].completed.toggle() } default: () } } } extension Tasks { static let sample = Tasks(all: [ .init(id: .init(), date: .init(), body: "Lorem ipsum dolor sit amet."), .init(id: .init(), date: .distantFuture, body: "Consectetur adipiscing elit sed."), .init(id: .init(), date: .distantPast, body: "Do eismod tempor elit.") ]) }
23.441176
91
0.560226
eb7cea3e39bef21df135b4d25021dcccd161343b
521
// // FTPopOverMenuModel.swift // FTPopOverMenu_Swift // // Created by liufengting on 2019/12/20. // Copyright © 2019 LiuFengting. All rights reserved. // import UIKit public class FTPopOverMenuModel: NSObject { public var title: String = "" public var image: Imageable? public var selected: Bool = false public convenience init(title: String, image: Imageable?, selected: Bool) { self.init() self.title = title self.image = image self.selected = selected } }
20.84
79
0.660269
1c7046caa1063b6a9d6ae95790a74d4b0c8bc9f9
978
// // Post.swift // Quill // // Created by Yasir Hakami on 24/12/2021. // import Foundation import Firebase struct Post { var id = "" var price = "" var contact = "" var description = "" var signature = "" var imageUrl = "" var user:User var createdAt:Timestamp? init(dict:[String:Any],id:String,user:User) { if let price = dict["price"] as? String, let description = dict["description"] as? String, let contact = dict["contact"] as? String, let signature = dict["signature"] as? String, let imageUrl = dict["imageUrl"] as? String, let createdAt = dict["createdAt"] as? Timestamp{ self.price = price self.signature = signature self.contact = contact self.description = description self.imageUrl = imageUrl self.createdAt = createdAt } self.id = id self.user = user } }
25.736842
60
0.556237
3866b48b0e6bcb1ebd4bf32ef5b5d0b5aae0cfba
2,492
// // RNCFStringTokenizer.swift // RNCFStringTokenizer // // Created by Jamie Birch (shirakaba) on 17/05/2018. // Copyright © 2018 Jamie Birch. All rights reserved. // import Foundation @objc(RNCFStringTokenizer) class RNCFStringTokenizer: NSObject { // Here we don't use the override keyword, because we're inheriting just from NSObject. @objc static func requiresMainQueueSetup() -> Bool { return false } /** API very much still under construction! TODO: should probably handle these as NSString instead */ @objc func copyBestStringLanguage( _ string: String, _ length: NSNumber, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock ) -> Void { let str: String = CFStringTokenizerCopyBestStringLanguage(string as CFString, CFRange(location: 0, length: CFIndex(truncating: length)))! as String NSLog("Best string language determined to be: %@", str) return resolve(str) } /** API very much still under construction! */ @objc func transliterate( _ input: String, _ localeIdentifier: String, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock ) -> Void { let inputText: NSString = input as NSString let range: CFRange = CFRangeMake(0, inputText.length) let targetLocale: NSLocale = NSLocale(localeIdentifier: localeIdentifier) let tokenizer: CFStringTokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, inputText as CFString, range, kCFStringTokenizerUnitWordBoundary, targetLocale) var originals = [String]() var transliterations = [String]() var tokenType: CFStringTokenizerTokenType = CFStringTokenizerGoToTokenAtIndex(tokenizer, 0) while (tokenType != .none) { if let attribute: CFTypeRef = CFStringTokenizerCopyCurrentTokenAttribute(tokenizer, kCFStringTokenizerAttributeLatinTranscription) { let original: String = CFStringCreateWithSubstring(kCFAllocatorDefault, inputText as CFString, CFStringTokenizerGetCurrentTokenRange(tokenizer)) as String originals.append(original) let transliteration: String = attribute as! String transliterations.append(transliteration) tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer) } else { break; } } NSLog("Generated transliterations: %@", transliterations) return resolve(transliterations) } }
39.555556
166
0.727528
eb877bcc8dff8d42ee78db8c520024c48fcef8c3
3,538
import Quick import Nimble @testable import Kiosk import Nimble_Snapshots private let frame = CGRect(x: 0, y: 0, width: 180, height: 320) class RegisterFlowViewConfiguration: QuickConfiguration { override class func configure(configuration: Configuration) { sharedExamples("a register flow view") { (sharedExampleContext: SharedExampleContext) in var subject: RegisterFlowView! beforeEach { subject = sharedExampleContext()["subject"] as! RegisterFlowView } it("looks right by default") { let bidDetails = BidDetails(saleArtwork: nil, paddleNumber: nil, bidderPIN: nil, bidAmountCents: nil) bidDetails.newUser = NewUser() subject.details = bidDetails subject.snapshotViewAfterScreenUpdates(true) expect(subject).to( haveValidSnapshot() ) } it("handles partial data") { let bidDetails = BidDetails(saleArtwork: nil, paddleNumber: nil, bidderPIN: nil, bidAmountCents: nil) bidDetails.newUser = NewUser() bidDetails.newUser.phoneNumber = "132131231" bidDetails.newUser.email = "[email protected]" subject.details = bidDetails subject.snapshotViewAfterScreenUpdates(true) expect(subject).to( haveValidSnapshot() ) } it("handles highlighted index") { let bidDetails = BidDetails(saleArtwork: nil, paddleNumber: nil, bidderPIN: nil, bidAmountCents: nil) bidDetails.newUser = NewUser() bidDetails.newUser.phoneNumber = "132131231" bidDetails.newUser.email = "[email protected]" subject.highlightedIndex = 2 subject.details = bidDetails subject.snapshotViewAfterScreenUpdates(true) expect(subject).to( haveValidSnapshot() ) } it("handles full data") { let bidDetails = BidDetails(saleArtwork: nil, paddleNumber: nil, bidderPIN: nil, bidAmountCents: nil) bidDetails.newUser = NewUser() bidDetails.newUser.phoneNumber = "132131231" bidDetails.newUser.creditCardToken = "...2323" bidDetails.newUser.email = "[email protected]" bidDetails.newUser.zipCode = "90210" subject.details = bidDetails subject.snapshotViewAfterScreenUpdates(true) expect(subject).to( haveValidSnapshot() ) } } } } class RegisterFlowViewTests: QuickSpec { override func spec() { var appSetup: AppSetup! var subject: RegisterFlowView! beforeEach { appSetup = AppSetup() subject = RegisterFlowView(frame: frame) subject.constrainWidth("180") subject.constrainHeight("320") subject.appSetup = appSetup subject.backgroundColor = .whiteColor() } describe("requiring zip code") { itBehavesLike("a register flow view") { () -> (NSDictionary) in appSetup.disableCardReader = true return ["subject": subject] } } describe("not requiring zip code") { itBehavesLike("a register flow view") { () -> (NSDictionary) in appSetup.disableCardReader = false return ["subject": subject] } } } }
34.686275
118
0.579989
269a849c37770a26bcec83e61bd8d1a32c252d34
16,833
// PagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: Protocols public protocol IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo } public protocol PagerTabStripDelegate: class { func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) } public protocol PagerTabStripIsProgressiveDelegate: PagerTabStripDelegate { func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) } public protocol PagerTabStripDataSource: class { func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] } // MARK: PagerTabStripViewController open class PagerTabStripViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak public var containerView: UIScrollView! open weak var delegate: PagerTabStripDelegate? open weak var datasource: PagerTabStripDataSource? open var pagerBehaviour = PagerTabStripBehaviour.progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true) open private(set) var viewControllers = [UIViewController]() open private(set) var currentIndex = 0 open private(set) var preCurrentIndex = 0 // used *only* to store the index to which move when the pager becomes visible open var pageWidth: CGFloat { return containerView.bounds.width } open var scrollPercentage: CGFloat { if swipeDirection != .right { let module = fmod(containerView.contentOffset.x, pageWidth) return module == 0.0 ? 1.0 : module / pageWidth } return 1 - fmod(containerView.contentOffset.x >= 0 ? containerView.contentOffset.x : pageWidth + containerView.contentOffset.x, pageWidth) / pageWidth } open var swipeDirection: SwipeDirection { if containerView.contentOffset.x > lastContentOffset { return .left } else if containerView.contentOffset.x < lastContentOffset { return .right } return .none } override open func viewDidLoad() { super.viewDidLoad() let conteinerViewAux = containerView ?? { let containerView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)) containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] return containerView }() containerView = conteinerViewAux if containerView.superview == nil { view.addSubview(containerView) } containerView.bounces = true containerView.alwaysBounceHorizontal = true containerView.alwaysBounceVertical = false containerView.scrollsToTop = false containerView.delegate = self containerView.showsVerticalScrollIndicator = false containerView.showsHorizontalScrollIndicator = false containerView.isPagingEnabled = true reloadViewControllers() let childController = viewControllers[currentIndex] addChild(childController) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] containerView.addSubview(childController.view) childController.didMove(toParent: self) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isViewAppearing = true children.forEach { $0.beginAppearanceTransition(true, animated: animated) } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) lastSize = containerView.bounds.size updateIfNeeded() let needToUpdateCurrentChild = preCurrentIndex != currentIndex if needToUpdateCurrentChild { moveToViewController(at: preCurrentIndex) } isViewAppearing = false children.forEach { $0.endAppearanceTransition() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) children.forEach { $0.beginAppearanceTransition(false, animated: animated) } } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) children.forEach { $0.endAppearanceTransition() } } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateIfNeeded() } open override var shouldAutomaticallyForwardAppearanceMethods: Bool { return false } open func moveToViewController(at index: Int, animated: Bool = true) { guard isViewLoaded && view.window != nil && currentIndex != index else { preCurrentIndex = index return } let top: CGFloat if #available(iOS 11.0, *) { top = -containerView.adjustedContentInset.top } else { top = -containerView.contentInset.top } if animated && pagerBehaviour.skipIntermediateViewControllers && abs(currentIndex - index) > 1 { var tmpViewControllers = viewControllers let currentChildVC = viewControllers[currentIndex] let fromIndex = currentIndex < index ? index - 1 : index + 1 let fromChildVC = viewControllers[fromIndex] tmpViewControllers[currentIndex] = fromChildVC tmpViewControllers[fromIndex] = currentChildVC pagerTabStripChildViewControllersForScrolling = tmpViewControllers containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: fromIndex), y: top), animated: false) (navigationController?.view ?? view).isUserInteractionEnabled = !animated containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: top), animated: true) } else { (navigationController?.view ?? view).isUserInteractionEnabled = !animated containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: top), animated: animated) } } open func moveTo(viewController: UIViewController, animated: Bool = true) { moveToViewController(at: viewControllers.firstIndex(of: viewController)!, animated: animated) } // MARK: - PagerTabStripDataSource open func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { assertionFailure("Sub-class must implement the PagerTabStripDataSource viewControllers(for:) method") return [] } // MARK: - Helpers open func updateIfNeeded() { if isViewLoaded && !lastSize.equalTo(containerView.bounds.size) { updateContent() } } open func canMoveTo(index: Int) -> Bool { return currentIndex != index && viewControllers.count > index } open func pageOffsetForChild(at index: Int) -> CGFloat { return CGFloat(index) * containerView.bounds.width } open func offsetForChild(at index: Int) -> CGFloat { return (CGFloat(index) * containerView.bounds.width) + ((containerView.bounds.width - view.bounds.width) * 0.5) } open func offsetForChild(viewController: UIViewController) throws -> CGFloat { guard let index = viewControllers.firstIndex(of: viewController) else { throw PagerTabStripError.viewControllerOutOfBounds } return offsetForChild(at: index) } open func pageFor(contentOffset: CGFloat) -> Int { let result = virtualPageFor(contentOffset: contentOffset) return pageFor(virtualPage: result) } open func virtualPageFor(contentOffset: CGFloat) -> Int { return Int((contentOffset + 1.5 * pageWidth) / pageWidth) - 1 } open func pageFor(virtualPage: Int) -> Int { if virtualPage < 0 { return 0 } if virtualPage > viewControllers.count - 1 { return viewControllers.count - 1 } return virtualPage } open func updateContent() { if lastSize.width != containerView.bounds.size.width { lastSize = containerView.bounds.size containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0) } lastSize = containerView.bounds.size let pagerViewControllers = pagerTabStripChildViewControllersForScrolling ?? viewControllers containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(pagerViewControllers.count), height: containerView.contentSize.height) for (index, childController) in pagerViewControllers.enumerated() { let pageOffsetForChild = self.pageOffsetForChild(at: index) if abs(containerView.contentOffset.x - pageOffsetForChild) < containerView.bounds.width { if childController.parent != nil { childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] } else { childController.beginAppearanceTransition(true, animated: false) addChild(childController) childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] containerView.addSubview(childController.view) childController.didMove(toParent: self) childController.endAppearanceTransition() } } else { if childController.parent != nil { childController.beginAppearanceTransition(false, animated: false) childController.willMove(toParent: nil) childController.view.removeFromSuperview() childController.removeFromParent() childController.endAppearanceTransition() } } } let oldCurrentIndex = currentIndex let virtualPage = virtualPageFor(contentOffset: containerView.contentOffset.x) let newCurrentIndex = pageFor(virtualPage: virtualPage) currentIndex = newCurrentIndex preCurrentIndex = currentIndex let changeCurrentIndex = newCurrentIndex != oldCurrentIndex if let progressiveDelegate = self as? PagerTabStripIsProgressiveDelegate, pagerBehaviour.isProgressiveIndicator { let (fromIndex, toIndex, scrollPercentage) = progressiveIndicatorData(virtualPage) progressiveDelegate.updateIndicator(for: self, fromIndex: fromIndex, toIndex: toIndex, withProgressPercentage: scrollPercentage, indexWasChanged: changeCurrentIndex) } else { delegate?.updateIndicator(for: self, fromIndex: min(oldCurrentIndex, pagerViewControllers.count - 1), toIndex: newCurrentIndex) } } open func reloadPagerTabStripView() { guard isViewLoaded else { return } for childController in viewControllers where childController.parent != nil { childController.beginAppearanceTransition(false, animated: false) childController.willMove(toParent: nil) childController.view.removeFromSuperview() childController.removeFromParent() childController.endAppearanceTransition() } reloadViewControllers() containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(viewControllers.count), height: containerView.contentSize.height) if currentIndex >= viewControllers.count { currentIndex = viewControllers.count - 1 } preCurrentIndex = currentIndex containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0) updateContent() } // MARK: - UIScrollViewDelegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { if containerView == scrollView { updateContent() lastContentOffset = scrollView.contentOffset.x } } open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if containerView == scrollView { lastPageNumber = pageFor(contentOffset: scrollView.contentOffset.x) } } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { if containerView == scrollView { pagerTabStripChildViewControllersForScrolling = nil (navigationController?.view ?? view).isUserInteractionEnabled = true updateContent() } } // MARK: - Orientation open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) isViewRotating = true pageBeforeRotate = currentIndex coordinator.animate(alongsideTransition: nil) { [weak self] _ in guard let me = self else { return } me.isViewRotating = false me.currentIndex = me.pageBeforeRotate me.preCurrentIndex = me.currentIndex me.updateIfNeeded() } } // MARK: Private private func progressiveIndicatorData(_ virtualPage: Int) -> (Int, Int, CGFloat) { let count = viewControllers.count var fromIndex = currentIndex var toIndex = currentIndex let direction = swipeDirection if direction == .left { if virtualPage > count - 1 { fromIndex = count - 1 toIndex = count } else { if self.scrollPercentage >= 0.5 { fromIndex = max(toIndex - 1, 0) } else { toIndex = fromIndex + 1 } } } else if direction == .right { if virtualPage < 0 { fromIndex = 0 toIndex = -1 } else { if self.scrollPercentage > 0.5 { fromIndex = min(toIndex + 1, count - 1) } else { toIndex = fromIndex - 1 } } } let scrollPercentage = pagerBehaviour.isElasticIndicatorLimit ? self.scrollPercentage : ((toIndex < 0 || toIndex >= count) ? 0.0 : self.scrollPercentage) return (fromIndex, toIndex, scrollPercentage) } private func reloadViewControllers() { guard let dataSource = datasource else { fatalError("dataSource must not be nil") } viewControllers = dataSource.viewControllers(for: self) // viewControllers guard !viewControllers.isEmpty else { fatalError("viewControllers(for:) should provide at least one child view controller") } viewControllers.forEach { if !($0 is IndicatorInfoProvider) { fatalError("Every view controller provided by PagerTabStripDataSource's viewControllers(for:) method must conform to IndicatorInfoProvider") }} } private var pagerTabStripChildViewControllersForScrolling: [UIViewController]? private var lastPageNumber = 0 private var lastContentOffset: CGFloat = 0.0 private var pageBeforeRotate = 0 private var lastSize = CGSize(width: 0, height: 0) internal var isViewRotating = false internal var isViewAppearing = false }
41.665842
213
0.671657
fe37f8f2a4f9b6df7c68982fddae8d4b7e3f24e7
1,539
// // IngredientsAndMethods.swift // FoodTracker // // Created by Nicole Black on 4/23/18. // Copyright © 2018 Apple Inc. All rights reserved. // import UIKit import os.log class IngredientsMethodsController: UIViewController { @IBOutlet weak var ingredientsTextView: UITextView! @IBOutlet weak var methodsTextView: UITextView! @IBOutlet weak var saveButton: UIBarButtonItem! @IBOutlet weak var cancelButton: UIBarButtonItem! @IBAction func cancel(_ sender: UIBarButtonItem) { let isPresentingInIngredientsMethodsMode = presentingViewController is UINavigationController if isPresentingInIngredientsMethodsMode { dismiss(animated: true, completion: nil) } else if let owningNavigationController = navigationController{ owningNavigationController.popViewController(animated: true) } else { fatalError("The IngredientsMethodsController is not inside a navigation controller.") } } @IBAction func save(_ sender: Any) { } func textFieldDidEndEditing(_ textView: UITextView) { updateSaveButtonState() navigationItem.title = textView.text } private func updateSaveButtonState() { // Disable the Save button if the text field is empty. let ingredients = ingredientsTextView.text ?? "" let methods = methodsTextView.text ?? "" saveButton.isEnabled = !ingredients.isEmpty saveButton.isEnabled = !methods.isEmpty } }
31.408163
101
0.68551
6abff60f13948b7d8421ab041bf42fe710d92bfe
2,229
//Domain B2B/Access/ import SwiftyJSON import Alamofire import ObjectMapper class AccessRemoteManagerImpl:RemoteManagerImpl,CustomStringConvertible{ override init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } override var remoteURLPrefix:String{ //Every manager need to config their own URL return "https://philipgreat.github.io/naf/accessManager/" } func loadAccessDetail(accessId:String, accessSuccessAction: (Access)->String, accessErrorAction: (String)->String){ let methodName = "loadAccessDetail" let parameters = [accessId] let url = compositeCallURL(methodName, parameters: parameters) Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) if let access = self.extractAccessFromJSON(json){ accessSuccessAction(access) } } case .Failure(let error): print(error) accessErrorAction("\(error)") } } } func extractAccessFromJSON(json:JSON) -> Access?{ let jsonTool = SwiftyJSONTool() let access = jsonTool.extractAccess(json) return access } //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). let result = "AccessRemoteManagerImpl, V1" return result } static var CLASS_VERSION = 1 //This value is for serializer like message pack to identify the versions match between //local and remote object. } //Reference http://grokswift.com/simple-rest-with-swift/ //Reference https://github.com/SwiftyJSON/SwiftyJSON //Reference https://github.com/Alamofire/Alamofire //Reference https://github.com/Hearst-DD/ObjectMapper //let remote = RemoteManagerImpl() //let result = remote.compositeCallURL(methodName: "getDetail",parameters:["O0000001"]) //print(result)
26.855422
101
0.686406
260c062a7676334dc0cd345f58db60f103bd9b52
6,337
// // Copyright (c) 2020 Arpit Lokwani // // 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 RealmSwift //------------------------------------------------------------------------------------------------------------------------------------------------- class BlockedView: UIViewController { @IBOutlet var searchBar: UISearchBar! @IBOutlet var tableView: UITableView! private var persons = realm.objects(Person.self).filter(falsepredicate) //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() title = "Blocked Users" navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil) tableView.register(UINib(nibName: "BlockedCell", bundle: nil), forCellReuseIdentifier: "BlockedCell") tableView.tableFooterView = UIView() } //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadPersons() } // MARK: - Realm methods //--------------------------------------------------------------------------------------------------------------------------------------------- func loadPersons(text: String = "") { let predicate1 = NSPredicate(format: "objectId IN %@", Blockeds.blockedIds()) let predicate2 = (text != "") ? NSPredicate(format: "fullname CONTAINS[c] %@", text) : NSPredicate(value: true) persons = realm.objects(Person.self).filter(predicate1).filter(predicate2).sorted(byKeyPath: "fullname") refreshTableView() } // MARK: - Refresh methods //--------------------------------------------------------------------------------------------------------------------------------------------- func refreshTableView() { tableView.reloadData() } } // MARK: - UIScrollViewDelegate //------------------------------------------------------------------------------------------------------------------------------------------------- extension BlockedView: UIScrollViewDelegate { //--------------------------------------------------------------------------------------------------------------------------------------------- func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { view.endEditing(true) } } // MARK: - UITableViewDataSource //------------------------------------------------------------------------------------------------------------------------------------------------- extension BlockedView: UITableViewDataSource { //--------------------------------------------------------------------------------------------------------------------------------------------- func numberOfSections(in tableView: UITableView) -> Int { return 1 } //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return persons.count } //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BlockedCell", for: indexPath) as! BlockedCell let person = persons[indexPath.row] cell.bindData(person: person) cell.loadImage(person: person, tableView: tableView, indexPath: indexPath) return cell } } // MARK: - UITableViewDelegate //------------------------------------------------------------------------------------------------------------------------------------------------- extension BlockedView: UITableViewDelegate { //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let person = persons[indexPath.row] let profileView = ProfileView(userId: person.objectId, chat: true) navigationController?.pushViewController(profileView, animated: true) } } // MARK: - UISearchBarDelegate //------------------------------------------------------------------------------------------------------------------------------------------------- extension BlockedView: UISearchBarDelegate { //--------------------------------------------------------------------------------------------------------------------------------------------- func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { loadPersons(text: searchText) } //--------------------------------------------------------------------------------------------------------------------------------------------- func searchBarTextDidBeginEditing(_ searchBar_: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } //--------------------------------------------------------------------------------------------------------------------------------------------- func searchBarTextDidEndEditing(_ searchBar_: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } //--------------------------------------------------------------------------------------------------------------------------------------------- func searchBarCancelButtonClicked(_ searchBar_: UISearchBar) { searchBar.text = "" searchBar.resignFirstResponder() loadPersons() } //--------------------------------------------------------------------------------------------------------------------------------------------- func searchBarSearchButtonClicked(_ searchBar_: UISearchBar) { searchBar.resignFirstResponder() } }
40.883871
147
0.426543
8a468ea7f664fc7cfb445321850c575242f10329
20,093
// // OAuthSwiftHTTPRequest.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation let kHTTPHeaderContentType = "Content-Type" open class OAuthSwiftHTTPRequest: NSObject, URLSessionDelegate, OAuthSwiftRequestHandle { public typealias SuccessHandler = (_ data: Data, _ response: HTTPURLResponse) -> Void public typealias FailureHandler = (_ error: OAuthSwiftError) -> Void // HTTP request method // https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods public enum Method: String { case GET, POST, PUT, DELETE, PATCH, HEAD //, OPTIONS, TRACE, CONNECT var isBody: Bool { return self == .POST || self == .PUT || self == .PATCH } } // Where the additional parameters will be injected @objc public enum ParamsLocation : Int { case authorizationHeader, /*FormEncodedBody,*/ requestURIQuery } public var config: Config private var request: URLRequest? private var task: URLSessionTask? private var session: URLSession! fileprivate var cancelRequested = false var successHandler: SuccessHandler? var failureHandler: FailureHandler? open static var executionContext: (@escaping () -> Void) -> Void = { block in return DispatchQueue.main.async(execute: block) } // MARK: INIT convenience init(url: URL, method: Method = .GET, parameters: OAuthSwift.Parameters = [:], paramsLocation : ParamsLocation = .authorizationHeader, httpBody: Data? = nil, headers: OAuthSwift.Headers = [:]) { self.init(config: Config(url: url, httpMethod: method, httpBody: httpBody, headers: headers, parameters: parameters, paramsLocation: paramsLocation)) } convenience init(request: URLRequest, paramsLocation : ParamsLocation = .authorizationHeader) { self.init(config: Config(urlRequest: request, paramsLocation: paramsLocation)) } init(config: Config) { self.config = config } func start() { guard request == nil else { return } // Don't start the same request twice! let successHandler = self.successHandler let failureHandler = self.failureHandler do { self.request = try self.makeRequest() } catch let error as NSError { failureHandler?(OAuthSwiftError.requestCreation(message: error.localizedDescription)) self.request = nil return } print("==========================") dump(request) print("==========================") OAuthSwiftHTTPRequest.executionContext { // perform lock here to prevent cancel calls on another thread while creating the request objc_sync_enter(self) defer { objc_sync_exit(self) } if self.cancelRequested { return } self.session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main) self.task = self.session.dataTask(with: self.request!) { (data, response, error) in #if os(iOS) #if !OAUTH_APP_EXTENSIONS UIApplication.shared.isNetworkActivityIndicatorVisible = false #endif #endif if let error = error { var oauthError: OAuthSwiftError = .requestError(error: error) let nsError = error as NSError if nsError.code == NSURLErrorCancelled { oauthError = .cancelled } else if nsError.isExpiredToken { oauthError = .tokenExpired(error: error) } failureHandler?(oauthError) return } guard let response = response as? HTTPURLResponse, let responseData = data else { let badRequestCode = 400 let localizedDescription = OAuthSwiftHTTPRequest.descriptionForHTTPStatus(badRequestCode, responseString: "") let userInfo : [AnyHashable : Any] = [NSLocalizedDescriptionKey: localizedDescription] let error = NSError(domain: OAuthSwiftError.Domain, code: badRequestCode, userInfo: userInfo) failureHandler?(.requestError(error:error)) return } guard response.statusCode < 400 else { var localizedDescription = String() let responseString = String(data: responseData, encoding: OAuthSwiftDataEncoding) let responseJSON = try? JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.mutableContainers) if let responseJSON = responseJSON as? OAuthSwift.Parameters { if let code = responseJSON["error"] as? String, let description = responseJSON["error_description"] as? String { localizedDescription = NSLocalizedString("\(code) \(description)", comment: "") if code == "authorization_pending" { failureHandler?(.authorizationPending) return } } } else { localizedDescription = OAuthSwiftHTTPRequest.descriptionForHTTPStatus(response.statusCode, responseString: String(data: responseData, encoding: OAuthSwiftDataEncoding)!) } let userInfo: OAuthSwift.Parameters = [ NSLocalizedDescriptionKey: localizedDescription, "Response-Headers": response.allHeaderFields, "Response-Body": responseString, NSURLErrorFailingURLErrorKey: response.url?.absoluteString, OAuthSwiftError.ResponseKey: response, OAuthSwiftError.ResponseDataKey: responseData ] let error = NSError(domain: NSURLErrorDomain, code: response.statusCode, userInfo: userInfo) if error.isExpiredToken { failureHandler?(.tokenExpired(error: error)) } else { failureHandler?(.requestError(error: error)) } return } successHandler?(responseData, response) } self.task?.resume() self.session.finishTasksAndInvalidate() #if os(iOS) #if !OAUTH_APP_EXTENSIONS UIApplication.shared.isNetworkActivityIndicatorVisible = true #endif #endif } } open func cancel() { // perform lock here to prevent cancel calls on another thread while creating the request objc_sync_enter(self) defer { objc_sync_exit(self) } // either cancel the request if it's already running or set the flag to prohibit creation of the request if let task = task { task.cancel() } else { cancelRequested = true } } open func makeRequest() throws -> URLRequest { return try OAuthSwiftHTTPRequest.makeRequest(config: self.config) } open class func makeRequest(config: Config) throws -> URLRequest { var request = config.urlRequest return try setupRequestForOAuth(request: &request, parameters: config.parameters, dataEncoding: config.dataEncoding, paramsLocation: config.paramsLocation ) } open class func makeRequest( url: Foundation.URL, method: Method, headers: OAuthSwift.Headers, parameters: OAuthSwift.Parameters, dataEncoding: String.Encoding, body: Data? = nil, paramsLocation: ParamsLocation = .authorizationHeader) throws -> URLRequest { var request = URLRequest(url: url) request.httpMethod = method.rawValue for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } return try setupRequestForOAuth( request: &request, parameters: parameters, dataEncoding: dataEncoding, body: body, paramsLocation: paramsLocation ) } open class func setupRequestForOAuth( request: inout URLRequest, parameters: OAuthSwift.Parameters, dataEncoding: String.Encoding = OAuthSwiftDataEncoding, body: Data? = nil, paramsLocation : ParamsLocation = .authorizationHeader) throws -> URLRequest { let finalParameters : OAuthSwift.Parameters switch (paramsLocation) { case .authorizationHeader: finalParameters = parameters.filter { key, _ in !key.hasPrefix("oauth_") } case .requestURIQuery: finalParameters = parameters } if let b = body { request.httpBody = b } else { if finalParameters.count > 0 { let charset = dataEncoding.charset let headers = request.allHTTPHeaderFields ?? [:] if request.httpMethod == "GET" || request.httpMethod == "HEAD" || request.httpMethod == "DELETE" { let queryString = finalParameters.urlEncodedQuery let url = request.url! request.url = url.urlByAppending(queryString: queryString) if headers[kHTTPHeaderContentType] == nil { request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: kHTTPHeaderContentType) } } else { if let contentType = headers[kHTTPHeaderContentType], contentType.contains("application/json") { let jsonData = try JSONSerialization.data(withJSONObject: finalParameters, options: []) request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: kHTTPHeaderContentType) request.httpBody = jsonData } else { request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: kHTTPHeaderContentType) let queryString = finalParameters.urlEncodedQuery request.httpBody = queryString.data(using: dataEncoding, allowLossyConversion: true) } } } } return request } } extension OAuthSwiftHTTPRequest { // Configuration for request public struct Config { // URLRequest (url, method, ...) public var urlRequest: URLRequest /// These parameters are either added to the query string for GET, HEAD and DELETE requests or /// used as the http body in case of POST, PUT or PATCH requests. /// /// If used in the body they are either encoded as JSON or as encoded plaintext based on the Content-Type header field. public var parameters: OAuthSwift.Parameters public let paramsLocation: ParamsLocation public let dataEncoding: String.Encoding public var httpMethod: Method { if let requestMethod = urlRequest.httpMethod { return Method(rawValue: requestMethod) ?? .GET } return .GET } public var url: Foundation.URL? { return urlRequest.url } public init(url: URL, httpMethod: Method = .GET, httpBody: Data? = nil, headers: OAuthSwift.Headers = [:], timeoutInterval: TimeInterval = 60 , httpShouldHandleCookies: Bool = false, parameters: OAuthSwift.Parameters, paramsLocation: ParamsLocation = .authorizationHeader, dataEncoding: String.Encoding = OAuthSwiftDataEncoding) { var urlRequest = URLRequest(url: url) urlRequest.httpMethod = httpMethod.rawValue urlRequest.httpBody = httpBody urlRequest.allHTTPHeaderFields = headers urlRequest.timeoutInterval = timeoutInterval urlRequest.httpShouldHandleCookies = httpShouldHandleCookies self.init(urlRequest: urlRequest, parameters: parameters, paramsLocation: paramsLocation, dataEncoding: dataEncoding) } public init(urlRequest: URLRequest, parameters: OAuthSwift.Parameters = [:], paramsLocation: ParamsLocation = .authorizationHeader, dataEncoding: String.Encoding = OAuthSwiftDataEncoding) { self.urlRequest = urlRequest self.parameters = parameters self.paramsLocation = paramsLocation self.dataEncoding = dataEncoding } // Modify request with authentification public mutating func updateRequest(credential: OAuthSwiftCredential) { let method = self.httpMethod let url = self.urlRequest.url! let headers: OAuthSwift.Headers = self.urlRequest.allHTTPHeaderFields ?? [:] let paramsLocation = self.paramsLocation let parameters = self.parameters var signatureUrl = url var signatureParameters = parameters // Check if body must be hashed (oauth1) let body: Data? = nil if method.isBody { if let contentType = headers[kHTTPHeaderContentType]?.lowercased() { if contentType.contains("application/json") { // TODO: oauth_body_hash create body before signing if implementing body hashing /*do { let jsonData: Data = try JSONSerialization.jsonObject(parameters, options: []) request.HTTPBody = jsonData requestHeaders["Content-Length"] = "\(jsonData.length)" body = jsonData } catch { }*/ signatureParameters = [:] // parameters are not used for general signature (could only be used for body hashing } // else other type are not supported, see setupRequestForOAuth() } } // Need to account for the fact that some consumers will have additional parameters on the // querystring, including in the case of fetching a request token. Especially in the case of // additional parameters on the request, authorize, or access token exchanges, we need to // normalize the URL and add to the parametes collection. var queryStringParameters = OAuthSwift.Parameters() var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false ) if let queryItems = urlComponents?.queryItems { for queryItem in queryItems { let value = queryItem.value?.safeStringByRemovingPercentEncoding ?? "" queryStringParameters.updateValue(value, forKey: queryItem.name) } } // According to the OAuth1.0a spec, the url used for signing is ONLY scheme, path, and query if queryStringParameters.count>0 { urlComponents?.query = nil // This is safe to unwrap because these just came from an NSURL signatureUrl = urlComponents?.url ?? url } signatureParameters = signatureParameters.join(queryStringParameters) var requestHeaders = OAuthSwift.Headers() switch paramsLocation { case .authorizationHeader: //Add oauth parameters in the Authorization header requestHeaders += credential.makeHeaders(signatureUrl, method: method, parameters: signatureParameters, body: body) case .requestURIQuery: //Add oauth parameters as request parameters self.parameters += credential.authorizationParametersWithSignature(method: method, url: signatureUrl, parameters: signatureParameters, body: body) } self.urlRequest.allHTTPHeaderFields = requestHeaders + headers } } } // MARK: status code mapping extension OAuthSwiftHTTPRequest { class func descriptionForHTTPStatus(_ status: Int, responseString: String) -> String { var s = "HTTP Status \(status)" var description: String? // http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml if status == 400 { description = "Bad Request" } if status == 401 { description = "Unauthorized" } if status == 402 { description = "Payment Required" } if status == 403 { description = "Forbidden" } if status == 404 { description = "Not Found" } if status == 405 { description = "Method Not Allowed" } if status == 406 { description = "Not Acceptable" } if status == 407 { description = "Proxy Authentication Required" } if status == 408 { description = "Request Timeout" } if status == 409 { description = "Conflict" } if status == 410 { description = "Gone" } if status == 411 { description = "Length Required" } if status == 412 { description = "Precondition Failed" } if status == 413 { description = "Payload Too Large" } if status == 414 { description = "URI Too Long" } if status == 415 { description = "Unsupported Media Type" } if status == 416 { description = "Requested Range Not Satisfiable" } if status == 417 { description = "Expectation Failed" } if status == 422 { description = "Unprocessable Entity" } if status == 423 { description = "Locked" } if status == 424 { description = "Failed Dependency" } if status == 425 { description = "Unassigned" } if status == 426 { description = "Upgrade Required" } if status == 427 { description = "Unassigned" } if status == 428 { description = "Precondition Required" } if status == 429 { description = "Too Many Requests" } if status == 430 { description = "Unassigned" } if status == 431 { description = "Request Header Fields Too Large" } if status == 432 { description = "Unassigned" } if status == 500 { description = "Internal Server Error" } if status == 501 { description = "Not Implemented" } if status == 502 { description = "Bad Gateway" } if status == 503 { description = "Service Unavailable" } if status == 504 { description = "Gateway Timeout" } if status == 505 { description = "HTTP Version Not Supported" } if status == 506 { description = "Variant Also Negotiates" } if status == 507 { description = "Insufficient Storage" } if status == 508 { description = "Loop Detected" } if status == 509 { description = "Unassigned" } if status == 510 { description = "Not Extended" } if status == 511 { description = "Network Authentication Required" } if (description != nil) { s = s + ": " + description! + ", Response: " + responseString } return s } }
45.05157
210
0.580451
bf79086bcc8c1835afd33b2742fc065723803493
39,862
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name objc_bridging_any -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import objc_generics protocol P {} protocol CP: class {} struct KnownUnbridged {} // CHECK-LABEL: sil hidden @$S17objc_bridging_any11passingToId{{.*}}F func passingToId<T: CP, U>(receiver: NSIdLover, string: String, nsString: NSString, object: AnyObject, classGeneric: T, classExistential: CP, generic: U, existential: P, error: Error, any: Any, knownUnbridged: KnownUnbridged, optionalA: String?, optionalB: NSString?, optionalC: Any?) { // CHECK: bb0([[SELF:%.*]] : @guaranteed $NSIdLover, // CHECK: debug_value [[STRING:%.*]] : $String // CHECK: debug_value [[NSSTRING:%.*]] : $NSString // CHECK: debug_value [[OBJECT:%.*]] : $AnyObject // CHECK: debug_value [[CLASS_GENERIC:%.*]] : $T // CHECK: debug_value [[CLASS_EXISTENTIAL:%.*]] : $CP // CHECK: debug_value_addr [[GENERIC:%.*]] : $*U // CHECK: debug_value_addr [[EXISTENTIAL:%.*]] : $*P // CHECK: debug_value [[ERROR:%.*]] : $Error // CHECK: debug_value_addr [[ANY:%.*]] : $*Any // CHECK: debug_value [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged // CHECK: debug_value [[OPT_STRING:%.*]] : $Optional<String> // CHECK: debug_value [[OPT_NSSTRING:%.*]] : $Optional<NSString> // CHECK: debug_value_addr [[OPT_ANY:%.*]] : $*Optional<Any> // CHECK: [[STRING_COPY:%.*]] = copy_value [[STRING]] // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK: destroy_value [[ANYOBJECT]] receiver.takesId(string) // CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK: destroy_value [[ANYOBJECT]] receiver.takesId(nsString) // CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[CLASS_GENERIC]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK: destroy_value [[ANYOBJECT]] receiver.takesId(classGeneric) // CHECK: [[OBJECT_COPY:%.*]] = copy_value [[OBJECT]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[OBJECT_COPY]], [[SELF]]) // CHECK: destroy_value [[OBJECT_COPY]] receiver.takesId(object) // CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[CLASS_EXISTENTIAL]] // CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK: destroy_value [[ANYOBJECT]] receiver.takesId(classExistential) // These cases perform a universal bridging conversion. // CHECK: [[COPY:%.*]] = alloc_stack $U // CHECK: copy_addr [[GENERIC]] to [initialization] [[COPY]] // CHECK: // function_ref _bridgeAnythingToObjectiveC // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]]) // CHECK: dealloc_stack [[COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK: destroy_value [[ANYOBJECT]] receiver.takesId(generic) // CHECK: [[COPY:%.*]] = alloc_stack $P // CHECK: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]] // CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]] // CHECK: // function_ref _bridgeAnythingToObjectiveC // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK: dealloc_stack [[TMP]] // CHECK: destroy_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK: destroy_value [[ANYOBJECT]] receiver.takesId(existential) // CHECK: [[ERROR_COPY:%.*]] = copy_value [[ERROR]] : $Error // CHECK: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error // CHECK: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error // CHECK: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @$Ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]]) // CHECK: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: destroy_value [[ERROR_COPY]] : $Error // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[BRIDGED_ERROR]], [[SELF]]) // CHECK: destroy_value [[BRIDGED_ERROR]] : $AnyObject receiver.takesId(error) // CHECK: [[COPY:%.*]] = alloc_stack $Any // CHECK: copy_addr [[ANY]] to [initialization] [[COPY]] // CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]] // CHECK: // function_ref _bridgeAnythingToObjectiveC // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK: destroy_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK: destroy_value [[ANYOBJECT]] receiver.takesId(any) // CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged // CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]]) // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(knownUnbridged) // These cases bridge using Optional's _ObjectiveCBridgeable conformance. // CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @$SSq19_bridgeToObjectiveCyXlyF // CHECK: [[TMP:%.*]] = alloc_stack $Optional<String> // CHECK: [[BORROWED_OPT_STRING_COPY:%.*]] = begin_borrow [[OPT_STRING_COPY]] // CHECK: store_borrow [[BORROWED_OPT_STRING_COPY]] to [[TMP]] // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<String>([[TMP]]) // CHECK: end_borrow [[BORROWED_OPT_STRING_COPY]] from [[OPT_STRING_COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(optionalA) // CHECK: [[OPT_NSSTRING_COPY:%.*]] = copy_value [[OPT_NSSTRING]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @$SSq19_bridgeToObjectiveCyXlyF // CHECK: [[TMP:%.*]] = alloc_stack $Optional<NSString> // CHECK: [[BORROWED_OPT_NSSTRING_COPY:%.*]] = begin_borrow [[OPT_NSSTRING_COPY]] // CHECK: store_borrow [[BORROWED_OPT_NSSTRING_COPY]] to [[TMP]] // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<NSString>([[TMP]]) // CHECK: end_borrow [[BORROWED_OPT_NSSTRING_COPY]] from [[OPT_NSSTRING]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(optionalB) // CHECK: [[TMP:%.*]] = alloc_stack $Optional<Any> // CHECK: copy_addr [[OPT_ANY]] to [initialization] [[TMP]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @$SSq19_bridgeToObjectiveCyXlyF // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<Any>([[TMP]]) // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(optionalC) // TODO: Property and subscript setters } // Once upon a time, as a workaround for rdar://problem/28318984, we had // to skip the peephole for types with nontrivial SIL lowerings because we // didn't correctly form the substitutions for a generic // _bridgeAnythingToObjectiveC call. That's not true anymore. func zim() {} struct Zang {} // CHECK-LABEL: sil hidden @$S17objc_bridging_any27typesWithNontrivialLowering8receiverySo9NSIdLoverC_tF func typesWithNontrivialLowering(receiver: NSIdLover) { // CHECK: apply {{.*}}<() -> ()> receiver.takesId(zim) // CHECK: apply {{.*}}<Zang.Type> receiver.takesId(Zang.self) // CHECK: apply {{.*}}<(() -> (), Zang.Type)> receiver.takesId((zim, Zang.self)) // CHECK: apply {{%.*}}<(Int, String)> receiver.takesId((0, "one")) } // CHECK-LABEL: sil hidden @$S17objc_bridging_any19passingToNullableId{{.*}}F func passingToNullableId<T: CP, U>(receiver: NSIdLover, string: String, nsString: NSString, object: AnyObject, classGeneric: T, classExistential: CP, generic: U, existential: P, error: Error, any: Any, knownUnbridged: KnownUnbridged, optString: String?, optNSString: NSString?, optObject: AnyObject?, optClassGeneric: T?, optClassExistential: CP?, optGeneric: U?, optExistential: P?, optAny: Any?, optKnownUnbridged: KnownUnbridged?, optOptA: String??, optOptB: NSString??, optOptC: Any??) { // CHECK: bb0([[SELF:%.*]] : @guaranteed $NSIdLover, // CHECK: [[STRING:%.*]] : $String, // CHECK: [[NSSTRING:%.*]] : $NSString // CHECK: [[OBJECT:%.*]] : $AnyObject // CHECK: [[CLASS_GENERIC:%.*]] : $T // CHECK: [[CLASS_EXISTENTIAL:%.*]] : $CP // CHECK: [[GENERIC:%.*]] : $*U // CHECK: [[EXISTENTIAL:%.*]] : $*P // CHECK: [[ERROR:%.*]] : $Error // CHECK: [[ANY:%.*]] : $*Any, // CHECK: [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged, // CHECK: [[OPT_STRING:%.*]] : $Optional<String>, // CHECK: [[OPT_NSSTRING:%.*]] : $Optional<NSString> // CHECK: [[OPT_OBJECT:%.*]] : $Optional<AnyObject> // CHECK: [[OPT_CLASS_GENERIC:%.*]] : $Optional<T> // CHECK: [[OPT_CLASS_EXISTENTIAL:%.*]] : $Optional<CP> // CHECK: [[OPT_GENERIC:%.*]] : $*Optional<U> // CHECK: [[OPT_EXISTENTIAL:%.*]] : $*Optional<P> // CHECK: [[OPT_ANY:%.*]] : $*Optional<Any> // CHECK: [[OPT_KNOWN_UNBRIDGED:%.*]] : $Optional<KnownUnbridged> // CHECK: [[OPT_OPT_A:%.*]] : $Optional<Optional<String>> // CHECK: [[OPT_OPT_B:%.*]] : $Optional<Optional<NSString>> // CHECK: [[OPT_OPT_C:%.*]] : $*Optional<Optional<Any>> // CHECK: [[STRING_COPY:%.*]] = copy_value [[STRING]] // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) // CHECK: destroy_value [[OPT_ANYOBJECT]] receiver.takesNullableId(string) // CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(nsString) // CHECK: [[OBJECT_COPY:%.*]] = copy_value [[OBJECT]] // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[OBJECT_COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(object) // CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[CLASS_GENERIC]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(classGeneric) // CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[CLASS_EXISTENTIAL]] // CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]] // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) // CHECK: destroy_value [[OPT_ANYOBJECT]] receiver.takesNullableId(classExistential) // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $U // CHECK-NEXT: copy_addr [[GENERIC]] to [initialization] [[COPY]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: destroy_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]] receiver.takesNullableId(generic) // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $P // CHECK-NEXT: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: destroy_addr [[TMP]] // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: destroy_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]] receiver.takesNullableId(existential) // CHECK-NEXT: [[ERROR_COPY:%.*]] = copy_value [[ERROR]] : $Error // CHECK-NEXT: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error // CHECK-NEXT: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @$Ss27_bridgeAnythingToObjectiveCyyXlxlF // CHECK-NEXT: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]]) // CHECK-NEXT: [[BRIDGED_ERROR_OPT:%[0-9]+]] = enum $Optional<AnyObject>, #Optional.some!enumelt.1, [[BRIDGED_ERROR]] : $AnyObject // CHECK-NEXT: destroy_addr [[ERROR_STACK]] // CHECK-NEXT: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: destroy_value [[ERROR_COPY]] : $Error // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK-NEXT: apply [[METHOD]]([[BRIDGED_ERROR_OPT]], [[SELF]]) // CHECK-NEXT: destroy_value [[BRIDGED_ERROR_OPT]] receiver.takesNullableId(error) // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [[ANY]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED_COPY]] to [initialization] [[TMP]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: destroy_addr [[TMP]] // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: destroy_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) // CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]] receiver.takesNullableId(any) // CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged // CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]]) // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(knownUnbridged) // CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]] // CHECK: switch_enum [[OPT_STRING_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[STRING_DATA:%.*]] : @owned $String): // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_DATA:%.*]] = begin_borrow [[STRING_DATA]] // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_DATA]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_STRING_DATA]] from [[STRING_DATA]] // CHECK: destroy_value [[STRING_DATA]] // CHECK: br [[JOIN:bb.*]]([[OPT_ANYOBJECT]] // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_NONE:%.*]] = enum $Optional<AnyObject>, #Optional.none!enumelt // CHECK: br [[JOIN]]([[OPT_NONE]] // // CHECK: [[JOIN]]([[PHI:%.*]] : @owned $Optional<AnyObject>): // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] // CHECK: apply [[METHOD]]([[PHI]], [[SELF]]) // CHECK: destroy_value [[PHI]] receiver.takesNullableId(optString) // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] receiver.takesNullableId(optNSString) // CHECK: [[OPT_OBJECT_COPY:%.*]] = copy_value [[OPT_OBJECT]] // CHECK: [[METHOD:%.*]] = objc_method [[SELF]] // CHECK: apply [[METHOD]]([[OPT_OBJECT_COPY]], [[SELF]]) receiver.takesNullableId(optObject) receiver.takesNullableId(optClassGeneric) receiver.takesNullableId(optClassExistential) receiver.takesNullableId(optGeneric) receiver.takesNullableId(optExistential) receiver.takesNullableId(optAny) receiver.takesNullableId(optKnownUnbridged) receiver.takesNullableId(optOptA) receiver.takesNullableId(optOptB) receiver.takesNullableId(optOptC) } protocol Anyable { init(any: Any) init(anyMaybe: Any?) var anyProperty: Any { get } var maybeAnyProperty: Any? { get } } // Make sure we generate correct bridging thunks class SwiftIdLover : NSObject, Anyable { func methodReturningAny() -> Any { fatalError() } // SEMANTIC ARC TODO: This is another case of pattern matching the body of one // function in a different function... Just pattern match the unreachable case // to preserve behavior. We should check if it is correct. // CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF : $@convention(method) (@guaranteed SwiftIdLover) -> @out Any // CHECK: unreachable // CHECK: } // end sil function '$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF' // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased AnyObject { // CHECK: bb0([[SELF:%[0-9]+]] : @unowned $SwiftIdLover): // CHECK: [[NATIVE_RESULT:%.*]] = alloc_stack $Any // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $SwiftIdLover // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE_IMP:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF // CHECK: apply [[NATIVE_IMP]]([[NATIVE_RESULT]], [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[OPEN_RESULT:%.*]] = open_existential_addr immutable_access [[NATIVE_RESULT]] // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[OPEN_RESULT]] to [initialization] [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F // CHECK: [[OBJC_RESULT:%.*]] = apply [[BRIDGE_ANYTHING]]<{{.*}}>([[TMP]]) // CHECK: return [[OBJC_RESULT]] // CHECK: } // end sil function '$S17objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo' func methodReturningOptionalAny() -> Any? { fatalError() } // CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyF // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyFTo // CHECK: function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F @objc func methodTakingAny(a: Any) { fatalError() } // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC15methodTakingAny1ayyp_tFTo : $@convention(objc_method) (AnyObject, SwiftIdLover) -> () // CHECK: bb0([[ARG:%.*]] : @unowned $AnyObject, [[SELF:%.*]] : @unowned $SwiftIdLover): // CHECK: function_ref [[BRIDGE_ANYOBJECT_TO_ANY:@\$Ss018_bridgeAnyObjectToB0yypyXlSgF]] : $@convention(thin) (@guaranteed Optional<AnyObject>) -> @out Any // CHECK: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC15methodTakingAny1ayyp_tF // CHECK-NEXT: apply [[METHOD]]([[RESULT:%.*]], [[BORROWED_SELF_COPY:%.*]]) : func methodTakingOptionalAny(a: Any?) { fatalError() } // CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAny1ayypSg_tF // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAny1ayypSg_tFTo // CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyyypXEF : $@convention(method) (@noescape @callee_guaranteed (@in_guaranteed Any) -> (), @guaranteed SwiftIdLover) -> () // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyyypXEFTo : $@convention(objc_method) (@convention(block) @noescape (AnyObject) -> (), SwiftIdLover) -> () // CHECK: bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape (AnyObject) -> (), [[SELF:%.*]] : @unowned $SwiftIdLover): // CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK_FN:%.*]] = function_ref @$SyXlIyBy_ypIegn_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[BLOCK_COPY]]) // CHECK-NEXT: [[THUNK_CVT:%.*]] = convert_escape_to_noescape [[THUNK]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyyypXEF // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK_CVT]], [[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[THUNK]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SyXlIyBy_ypIegn_TR // CHECK: bb0([[ANY:%.*]] : @trivial $*Any, [[BLOCK:%.*]] : @guaranteed $@convention(block) @noescape (AnyObject) -> ()): // CHECK-NEXT: [[OPENED_ANY:%.*]] = open_existential_addr immutable_access [[ANY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK: [[TMP:%.*]] = alloc_stack // CHECK: copy_addr [[OPENED_ANY]] to [initialization] [[TMP]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK-NEXT: apply [[BLOCK]]([[BRIDGED]]) // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK-NEXT: destroy_value [[BRIDGED]] // CHECK-NEXT: destroy_addr [[TMP]] // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: return [[VOID]] @objc func methodTakingBlockTakingAny(_: (Any) -> ()) { fatalError() } // CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_guaranteed (@in_guaranteed Any) -> () // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) (AnyObject) -> () // CHECK: bb0([[SELF:%.*]] : @unowned $SwiftIdLover): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD:%.*]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_guaranteed (@in_guaranteed Any) -> () // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: store [[RESULT:%.*]] to [init] [[BLOCK_STORAGE_ADDR]] // CHECK: [[THUNK_FN:%.*]] = function_ref @$SypIegn_yXlIeyBy_TR // CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed (@in_guaranteed Any) -> (), invoke [[THUNK_FN]] // CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]] // CHECK-NEXT: destroy_addr [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]] // CHECK-NEXT: return [[BLOCK]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SypIegn_yXlIeyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed (@in_guaranteed Any) -> (), AnyObject) -> () // CHECK: bb0([[BLOCK_STORAGE:%.*]] : @trivial $*@block_storage @callee_guaranteed (@in_guaranteed Any) -> (), [[ANY:%.*]] : @unowned $AnyObject): // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]] // CHECK-NEXT: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY_COPY]] // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[INIT:%.*]] = init_existential_addr [[RESULT]] : $*Any // CHECK-NEXT: store [[OPENED_ANY]] to [init] [[INIT]] // CHECK-NEXT: [[BORROW_FUN:%.*]] = begin_borrow [[FUNCTION]] // CHECK-NEXT: apply [[BORROW_FUN]]([[RESULT]]) // CHECK-NEXT: end_borrow [[BORROW_FUN]] from [[FUNCTION]] // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK-NEXT: destroy_addr [[RESULT]] // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: destroy_value [[FUNCTION]] // CHECK-NEXT: return [[VOID]] : $() @objc func methodTakingBlockTakingOptionalAny(_: (Any?) -> ()) { fatalError() } @objc func methodReturningBlockTakingAny() -> ((Any) -> ()) { fatalError() } // CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyyypyXEF : $@convention(method) (@noescape @callee_guaranteed () -> @out Any, @guaranteed SwiftIdLover) -> () { // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyyypyXEFTo : $@convention(objc_method) (@convention(block) @noescape () -> @autoreleased AnyObject, SwiftIdLover) -> () // CHECK: bb0([[BLOCK:%.*]] : @unowned $@convention(block) @noescape () -> @autoreleased AnyObject, [[ANY:%.*]] : @unowned $SwiftIdLover): // CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @$SyXlIyBa_ypIegr_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[BLOCK_COPY]]) // CHECK-NEXT: [[THUNK_CVT:%.*]] = convert_escape_to_noescape [[THUNK]] // CHECK-NEXT: [[BORROWED_ANY_COPY:%.*]] = begin_borrow [[ANY_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyyypyXEF // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK_CVT]], [[BORROWED_ANY_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_ANY_COPY]] from [[ANY_COPY]] // CHECK-NEXT: destroy_value [[THUNK]] // CHECK-NEXT: destroy_value [[ANY_COPY]] // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SyXlIyBa_ypIegr_TR : $@convention(thin) (@guaranteed @convention(block) @noescape () -> @autoreleased AnyObject) -> @out Any // CHECK: bb0([[ANY_ADDR:%.*]] : @trivial $*Any, [[BLOCK:%.*]] : @guaranteed $@convention(block) @noescape () -> @autoreleased AnyObject): // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BLOCK]]() // CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[BRIDGED]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[BORROWED_OPTIONAL:%.*]] = begin_borrow [[OPTIONAL]] // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[ANY_ADDR]], [[BORROWED_OPTIONAL]]) // CHECK-NEXT: [[EMPTY:%.*]] = tuple () // CHECK-NEXT: end_borrow [[BORROWED_OPTIONAL]] // CHECK-NEXT: destroy_value [[OPTIONAL]] // CHECK-NEXT: return [[EMPTY]] @objc func methodReturningBlockTakingOptionalAny() -> ((Any?) -> ()) { fatalError() } @objc func methodTakingBlockReturningAny(_: () -> Any) { fatalError() } // CHECK-LABEL: sil hidden @$S17objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_guaranteed () -> @out Any // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) () -> @autoreleased AnyObject // CHECK: bb0([[SELF:%.*]] : @unowned $SwiftIdLover): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @$S17objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF // CHECK-NEXT: [[FUNCTION:%.*]] = apply [[METHOD]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_guaranteed () -> @out Any // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: store [[FUNCTION]] to [init] [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @$SypIegr_yXlIeyBa_TR // CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_guaranteed () -> @out Any, invoke [[THUNK_FN]] // CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]] // CHECK-NEXT: destroy_addr [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]] // CHECK-NEXT: return [[BLOCK]] // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SypIegr_yXlIeyBa_TR : $@convention(c) (@inout_aliasable @block_storage @callee_guaranteed () -> @out Any) -> @autoreleased AnyObject // CHECK: bb0(%0 : @trivial $*@block_storage @callee_guaranteed () -> @out Any): // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0 // CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[BORROW_FUN:%.*]] = begin_borrow [[FUNCTION]] // CHECK-NEXT: apply [[BORROW_FUN]]([[RESULT]]) // CHECK-NEXT: end_borrow [[BORROW_FUN]] from [[FUNCTION]] // CHECK-NEXT: [[OPENED:%.*]] = open_existential_addr immutable_access [[RESULT]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK: [[TMP:%.*]] = alloc_stack $[[OPENED_TYPE]] // CHECK: copy_addr [[OPENED]] to [initialization] [[TMP]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[TMP]]) // CHECK-NEXT: destroy_addr [[TMP]] // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: destroy_addr [[RESULT]] // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: destroy_value [[FUNCTION]] // CHECK-NEXT: return [[BRIDGED]] @objc func methodTakingBlockReturningOptionalAny(_: () -> Any?) { fatalError() } @objc func methodReturningBlockReturningAny() -> (() -> Any) { fatalError() } @objc func methodReturningBlockReturningOptionalAny() -> (() -> Any?) { fatalError() } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SypSgIegr_yXlSgIeyBa_TR // CHECK: function_ref @$Ss27_bridgeAnythingToObjectiveC{{.*}}F override init() { fatalError() } @objc dynamic required convenience init(any: Any) { fatalError() } @objc dynamic required convenience init(anyMaybe: Any?) { fatalError() } @objc dynamic var anyProperty: Any @objc dynamic var maybeAnyProperty: Any? subscript(_: IndexForAnySubscript) -> Any { get { fatalError() } set { fatalError() } } @objc func methodReturningAnyOrError() throws -> Any { fatalError() } } class IndexForAnySubscript { } func dynamicLookup(x: AnyObject) { _ = x.anyProperty _ = x[IndexForAnySubscript()] } extension GenericClass { // CHECK-LABEL: sil hidden @$SSo12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasure1xypx_tF : func pseudogenericAnyErasure(x: T) -> Any { // CHECK: bb0([[ANY_OUT:%.*]] : @trivial $*Any, [[ARG:%.*]] : @guaranteed $T, [[SELF:%.*]] : @guaranteed $GenericClass<T> // CHECK: [[ANY_BUF:%.*]] = init_existential_addr [[ANY_OUT]] : $*Any, $AnyObject // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[ARG_COPY]] : $T : $T, $AnyObject // CHECK: store [[ANYOBJECT]] to [init] [[ANY_BUF]] return x } // CHECK: } // end sil function '$SSo12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasure1xypx_tF' } // Make sure AnyHashable erasure marks Hashable conformance as used class AnyHashableClass : NSObject { // CHECK-LABEL: sil hidden @$S17objc_bridging_any16AnyHashableClassC07returnsdE0s0dE0VyF // CHECK: [[FN:%.*]] = function_ref @$Ss21_convertToAnyHashableys0cD0Vxs0D0RzlF // CHECK: apply [[FN]]<GenericOption>({{.*}}) func returnsAnyHashable() -> AnyHashable { return GenericOption.multithreaded } } // CHECK-LABEL: sil hidden @$S17objc_bridging_any33bridgeOptionalFunctionToAnyObject2fnyXlyycSg_tF : $@convention(thin) (@guaranteed Optional<@callee_guaranteed () -> ()>) -> @owned AnyObject // CHECK: [[BRIDGE:%.*]] = function_ref @$SSq19_bridgeToObjectiveCyXlyF // CHECK: [[FN:%.*]] = function_ref @$SIeg_ytytIegnr_TR // CHECK: partial_apply [callee_guaranteed] [[FN]] // CHECK: [[SELF:%.*]] = alloc_stack $Optional<@callee_guaranteed (@in_guaranteed ()) -> @out ()> // CHECK: apply [[BRIDGE]]<() -> ()>([[SELF]]) func bridgeOptionalFunctionToAnyObject(fn: (() -> ())?) -> AnyObject { return fn as AnyObject } // When bridging `id _Nonnull` values incoming from unknown ObjC code, // turn them into `Any` using a runtime call that defends against the // possibility they still may be nil. // CHECK-LABEL: sil hidden @$S17objc_bridging_any22bridgeIncomingAnyValueyypSo9NSIdLoverCF func bridgeIncomingAnyValue(_ receiver: NSIdLover) -> Any { // CHECK: function_ref [[BRIDGE_ANYOBJECT_TO_ANY]] return receiver.makesId() } class SwiftAnyEnjoyer: NSIdLover, NSIdLoving { // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any15SwiftAnyEnjoyerC7takesIdyyypFTo // CHECK: function_ref [[BRIDGE_ANYOBJECT_TO_ANY]] override func takesId(_ x: Any) { } // CHECK-LABEL: sil hidden [thunk] @$S17objc_bridging_any15SwiftAnyEnjoyerC7takesId11viaProtocolyyp_tFTo // CHECK: function_ref [[BRIDGE_ANYOBJECT_TO_ANY]] func takesId(viaProtocol x: Any) { } } // CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics { // CHECK-NEXT: base_protocol Equatable: GenericOption: Equatable module objc_generics // CHECK-NEXT: method #Hashable.hashValue!getter.1: {{.*}} : @$SSo13GenericOptionas8HashableSCsACP9hashValueSivgTW // CHECK-NEXT: method #Hashable._hash!1: {{.*}} : @$SSo13GenericOptionas8HashableSCsACP5_hash4intoys7_HasherVz_tFTW // CHECK-NEXT: }
56.783476
224
0.641262
18e20fd8d7a5ae4532253b8d33efe0384ce052cb
9,464
import Foundation extension String: Decodable { /** Decode `JSON` into `Decoded<String>`. Succeeds if the value is a string, otherwise it returns a type mismatch. - parameter j: The `JSON` value to decode - returns: A decoded `String` value */ public static func decode(j: JSON) -> Decoded<String> { switch j { case let .String(s): return pure(s) default: return .typeMismatch("String", actual: j) } } } extension Int: Decodable { /** Decode `JSON` into `Decoded<Int>`. Succeeds if the value is a number that can be converted to an `Int`, otherwise it returns a type mismatch. - parameter j: The `JSON` value to decode - returns: A decoded `Int` value */ public static func decode(j: JSON) -> Decoded<Int> { switch j { case let .Number(n): return pure(n as Int) default: return .typeMismatch("Int", actual: j) } } } extension UInt: Decodable { /** Decode `JSON` into `Decoded<UInt>`. Succeeds if the value is a number that can be converted to a `UInt`, otherwise it returns a type mismatch. - parameter json: The `JSON` value to decode - returns: A decoded `UInt` value */ public static func decode(j: JSON) -> Decoded<UInt> { switch j { case let .Number(n): return pure(n as UInt) default: return .typeMismatch("UInt", actual: j) } } } extension Int64: Decodable { /** Decode `JSON` into `Decoded<Int64>`. Succeeds if the value is a number that can be converted to an `Int64` or a string that represents a large number, otherwise it returns a type mismatch. - parameter j: The `JSON` value to decode - returns: A decoded `Int64` value */ public static func decode(j: JSON) -> Decoded<Int64> { switch j { case let .Number(n): return pure(n.longLongValue) case let .String(s): guard let i = Int64(s) else { fallthrough } return pure(i) default: return .typeMismatch("Int64", actual: j) } } } extension UInt64: Decodable { /** Decode `JSON` into `Decoded<UInt64>`. Succeeds if the value is a number that can be converted to an `UInt64` or a string that represents a large number, otherwise it returns a type mismatch. - parameter json: The `JSON` value to decode - returns: A decoded `UInt` value */ public static func decode(j: JSON) -> Decoded<UInt64> { switch j { case let .Number(n): return pure(n.unsignedLongLongValue) case let .String(s): guard let i = UInt64(s) else { fallthrough } return pure(i) default: return .typeMismatch("UInt64", actual: j) } } } extension Double: Decodable { /** Decode `JSON` into `Decoded<Double>`. Succeeds if the value is a number that can be converted to a `Double`, otherwise it returns a type mismatch. - parameter j: The `JSON` value to decode - returns: A decoded `Double` value */ public static func decode(j: JSON) -> Decoded<Double> { switch j { case let .Number(n): return pure(n as Double) default: return .typeMismatch("Double", actual: j) } } } extension Float: Decodable { /** Decode `JSON` into `Decoded<Float>`. Succeeds if the value is a number that can be converted to a `Float`, otherwise it returns a type mismatch. - parameter j: The `JSON` value to decode - returns: A decoded `Float` value */ public static func decode(j: JSON) -> Decoded<Float> { switch j { case let .Number(n): return pure(n as Float) default: return .typeMismatch("Float", actual: j) } } } extension Bool: Decodable { /** Decode `JSON` into `Decoded<Bool>`. Succeeds if the value is a boolean or if the value is a number that is able to be converted to a boolean, otherwise it returns a type mismatch. - parameter j: The `JSON` value to decode - returns: A decoded `Bool` value */ public static func decode(j: JSON) -> Decoded<Bool> { switch j { case let .Bool(n): return pure(n) case let .Number(n): return pure(n as Bool) default: return .typeMismatch("Bool", actual: j) } } } public extension Optional where Wrapped: Decodable, Wrapped == Wrapped.DecodedType { /** Decode `JSON` into an `Optional<Wrapped>` value where `Wrapped` is `Decodable`. Returns a decoded optional value from the result of performing `decode` on the internal wrapped type. - parameter j: The `JSON` value to decode - returns: A decoded optional `Wrapped` value */ static func decode(j: JSON) -> Decoded<Wrapped?> { return .optional(Wrapped.decode(j)) } } public extension CollectionType where Generator.Element: Decodable, Generator.Element == Generator.Element.DecodedType { /** Decode `JSON` into an array of values where the elements of the array are `Decodable`. If the `JSON` is an array of `JSON` objects, this returns a decoded array of values by mapping the element's `decode` function over the `JSON` and then applying `sequence` to the result. This makes this `decode` function an all-or-nothing operation (See the documentation for `sequence` for more info). If the `JSON` is not an array, this returns a type mismatch. - parameter j: The `JSON` value to decode - returns: A decoded array of values */ static func decode(j: JSON) -> Decoded<[Generator.Element]> { switch j { case let .Array(a): return sequence(a.map(Generator.Element.decode)) default: return .typeMismatch("Array", actual: j) } } } /** Decode `JSON` into an array of values where the elements of the array are `Decodable`. If the `JSON` is an array of `JSON` objects, this returns a decoded array of values by mapping the element's `decode` function over the `JSON` and then applying `sequence` to the result. This makes `decodeArray` an all-or-nothing operation (See the documentation for `sequence` for more info). If the `JSON` is not an array, this returns a type mismatch. This is a convenience function that is the same as `[T].decode(j)` (where `T` is `Decodable`) and only exists to ease some pain around needing to use the full type of the array when calling `decode`. We expect this function to be removed in a future version. - parameter j: The `JSON` value to decode - returns: A decoded array of values */ public func decodeArray<T: Decodable where T.DecodedType == T>(j: JSON) -> Decoded<[T]> { return [T].decode(j) } public extension DictionaryLiteralConvertible where Value: Decodable, Value == Value.DecodedType { /** Decode `JSON` into a dictionary of keys and values where the keys are `String`s and the values are `Decodable`. If the `JSON` is a dictionary of `String`/`JSON` pairs, this returns a decoded dictionary of key/value pairs by mapping the value's `decode` function over the `JSON` and then applying `sequence` to the result. This makes this `decode` function an all-or-nothing operation (See the documentation for `sequence` for more info). If the `JSON` is not a dictionary, this returns a type mismatch. - parameter j: The `JSON` value to decode - returns: A decoded dictionary of key/value pairs */ static func decode(j: JSON) -> Decoded<[String: Value]> { switch j { case let .Object(o): return sequence(Value.decode <^> o) default: return .typeMismatch("Object", actual: j) } } } /** Decode `JSON` into a dictionary of keys and values where the keys are `String`s and the values are `Decodable`. If the `JSON` is a dictionary of `String`/`JSON` pairs, this returns a decoded dictionary of key/value pairs by mapping the value's `decode` function over the `JSON` and then applying `sequence` to the result. This makes `decodeObject` an all-or-nothing operation (See the documentation for `sequence` for more info). If the `JSON` is not a dictionary, this returns a type mismatch. This is a convenience function that is the same as `[String: T].decode(j)` (where `T` is `Decodable`) and only exists to ease some pain around needing to use the full type of the dictionary when calling `decode`. We expect this function to be removed in a future version. - parameter j: The `JSON` value to decode - returns: A decoded dictionary of key/value pairs */ public func decodeObject<T: Decodable where T.DecodedType == T>(j: JSON) -> Decoded<[String: T]> { return [String: T].decode(j) } /** Pull an embedded `JSON` value from a specified key. If the `JSON` value is an object, it will attempt to return the embedded `JSON` value at the specified key, failing if the key doesn't exist. If the `JSON` value is not an object, this will return a type mismatch. This is similar to adding a subscript to `JSON`, except that it returns a `Decoded` type. - parameter json: The `JSON` value that contains the key - parameter key: The key containing the embedded `JSON` object - returns: A decoded `JSON` value representing the success or failure of extracting the value from the object */ public func decodedJSON(json: JSON, forKey key: String) -> Decoded<JSON> { switch json { case let .Object(o): return guardNull(key, j: o[key] ?? .Null) default: return .typeMismatch("Object", actual: json) } } private func guardNull(key: String, j: JSON) -> Decoded<JSON> { switch j { case .Null: return .missingKey(key) default: return pure(j) } }
30.627832
120
0.677726
d77348c8819959994b98144a4ee45f77f44816cf
709
import Foundation import Firebase final class AnalyticsProviderFirebase:AnalyticsProviderProtocol { func startFirebase() { guard FirebaseApp.app() == nil else { return } FirebaseConfiguration.shared.setLoggerLevel(FirebaseLoggerLevel.min) FirebaseApp.configure() } func setScreen(screenName:String) { Firebase.Analytics.setScreenName(screenName, screenClass:screenName) } func logEvent( eventName:String, parameters:[String:Any]) { Firebase.Analytics.logEvent( eventName, parameters:parameters) } }
20.257143
76
0.5811
acf16e0fb5a7a4a8dadbc8ad8bdeaf2bbec84d00
3,470
// // TestMiscObjTypes.swift // RubyGatewayTests // // Distributed under the MIT license, see LICENSE // import CRuby @testable /* various macros */ import RubyGateway import XCTest /// Misc data type tests class TestMiscObjTypes: XCTestCase { func testNilConstants() { let nilVal = Qnil let falseVal = Qfalse let trueVal = Qtrue XCTAssertTrue(RB_NIL_P(nilVal)) XCTAssertFalse(RB_NIL_P(falseVal)) XCTAssertFalse(RB_NIL_P(trueVal)) XCTAssertFalse(RB_TEST(nilVal)) XCTAssertFalse(RB_TEST(falseVal)) XCTAssertTrue(RB_TEST(trueVal)) XCTAssertEqual(.T_NIL, TYPE(nilVal)) XCTAssertEqual(.T_FALSE, TYPE(falseVal)) XCTAssertEqual(.T_TRUE, TYPE(trueVal)) } // Used to support ExpressibleAsNilLiteral but turns out is not so useful // and docs say not to do so... func testNilLiteralPromotion() { let obj: RbObject = RbObject.nilObject XCTAssertFalse(obj.isTruthy) XCTAssertTrue(obj.isNil) obj.withRubyValue { rubyVal in XCTAssertEqual(Qnil, rubyVal) } } private func doTestBoolRoundTrip(_ val: Bool) { let obj = RbObject(val) XCTAssertTrue(obj.rubyType == .T_FALSE || obj.rubyType == .T_TRUE) guard let bool = Bool(obj) else { XCTFail("Couldn't convert boolean value") return } XCTAssertEqual(val, bool) } func testBoolRoundTrip() { doTestBoolRoundTrip(true) doTestBoolRoundTrip(false) } func testFailedBoolConversion() { let obj = RbObject(rubyValue: Qundef) if let bool = Bool(obj) { XCTFail("Converted undef to bool - \(bool)") } } func testBoolLiteralPromotion() { let trueObj: RbObject = true let falseObj: RbObject = false XCTAssertEqual(.T_TRUE, trueObj.rubyType) XCTAssertEqual(.T_FALSE, falseObj.rubyType) } func testSymbols() { let sym = RbSymbol("name") XCTAssertEqual("RbSymbol(name)", sym.description) let obj = sym.rubyObject XCTAssertEqual(.T_SYMBOL, obj.rubyType) if let backSym = RbSymbol(obj) { XCTFail("Managed to create symbol from object: \(backSym)") } } func testHashableSymbols() { let h1 = [RbSymbol("one"): "One", RbSymbol("two"): "Two"] let h2 = [RbSymbol("one").rubyObject: "One", RbSymbol("two").rubyObject: "Two"] let rh1 = h1.rubyObject let rh2 = h2.rubyObject XCTAssertEqual(rh1, rh2) } func testBadCoerce() { doErrorFree { let obj = RbObject("string") doError { let a: Int = try obj.convert() XCTFail("Managed to convert string to int: \(a)") } doError { let a = try obj.convert(to: Int.self) XCTFail("Managed to convert string to int: \(a)") } } } static var allTests = [ ("testNilConstants", testNilConstants), ("testNilLiteralPromotion", testNilLiteralPromotion), ("testBoolRoundTrip", testBoolRoundTrip), ("testFailedBoolConversion", testFailedBoolConversion), ("testBoolLiteralPromotion", testBoolLiteralPromotion), ("testSymbols", testSymbols), ("testHashableSymbols", testHashableSymbols), ("testBadCoerce", testBadCoerce) ] }
28.677686
87
0.604035
efa324e75400a8dbbe792881e6376eef7afdf6f7
2,792
import Foundation public struct Time: Comparable, CustomStringConvertible, Strideable { public let hours: Int public let minutes: Int public let seconds: Int public init(hours: Int, minutes: Int, seconds: Int) { self.hours = hours self.minutes = minutes self.seconds = seconds } public init?(timeString: String) { let parts = timeString.components(separatedBy: ":") guard parts.count == 2 || parts.count == 3 else { return nil } guard let hour = Int(parts[0]), let minute = Int(parts[1]) else { return nil } self.hours = hour self.minutes = minute if parts.count == 3 { guard let second = Int(parts[2]) else { return nil } self.seconds = second } else { self.seconds = 0 } } func timeByAdding(seconds: Int) -> Time { var newSeconds = self.seconds + seconds var newMinutes = self.minutes var newHours = self.hours if newSeconds > 59 { newMinutes += (newSeconds / 60) newSeconds -= (newSeconds / 60) * 60 } if newMinutes > 59 { newHours += (newMinutes / 60) newMinutes -= (newMinutes / 60) * 60 } return Time(hours: newHours, minutes: newMinutes, seconds: newSeconds) } var totalSeconds: Int { return hours * 60 * 60 + minutes * 60 + seconds } func toFormattedTimeString(showSeconds: Bool = false) -> String { if showSeconds { return "\(String(format: "%02d", hours)):\(String(format: "%02d", minutes)):\(String(format: "%02d", seconds))" } return "\(String(format: "%02d", hours)):\(String(format: "%02d", minutes))h." } // MARK: - CustomStringConvertible public var description: String { return "\(String(format: "%02d", hours)):\(String(format: "%02d", minutes)):\(String(format: "%02d", seconds))" } // MARK: - Strideable public func distance(to other: Time) -> Time.Stride { return totalSeconds + other.totalSeconds } public func advanced(by nSec: Time.Stride) -> Time { return timeByAdding(seconds: nSec) } public typealias Stride = Int } public func == (lhs: Time, rhs: Time) -> Bool { return lhs.hours == rhs.hours && lhs.minutes == rhs.minutes && lhs.seconds == rhs.seconds } public func < (lhs: Time, rhs: Time) -> Bool { if lhs.hours == rhs.hours && lhs.minutes == rhs.minutes { return lhs.seconds < rhs.seconds } if lhs.hours == rhs.hours { return lhs.minutes < rhs.minutes } return lhs.hours < rhs.hours }
30.021505
123
0.554799
2f12931864eab34e3d0e7f7b67e6dcaf6646925a
1,179
// // AppDelegatePlug.swift // AppDelegatePlug // // Created by Md. Kamrul Hasan on 27/5/20. // Copyright © 2020 MKHG Lab. All rights reserved. // import UIKit open class AppDelegatePlug: UIResponder, UIApplicationDelegate { open var services: [AppPlugService] { return [] } lazy var _services: [AppPlugService] = { return self.services }() @discardableResult internal func apply<T, S>(_ work: (AppPlugService, @escaping (T) -> Void) -> S?, completionHandler: @escaping ([T]) -> Void) -> [S] { let dispatchGroup = DispatchGroup() var results: [T] = [] var returns: [S] = [] for service in _services { dispatchGroup.enter() let returned = work(service, { result in results.append(result) dispatchGroup.leave() }) if let returned = returned { returns.append(returned) } else { // delegate doesn't impliment method dispatchGroup.leave() } } dispatchGroup.notify(queue: .main) { completionHandler(results) } return returns } }
26.2
137
0.564885
89d7372940c99b58db3e7a85ab71b27b76e0761e
1,172
// // GiphyViewerUITests.swift // GiphyViewerUITests // // Created by Thierry on 9/20/19. // Copyright © 2019 Thierry Sansaricq. All rights reserved. // import XCTest class GiphyViewerUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.485714
182
0.693686
8929ad51e352ffdbc4ad27e909d95cc7da6fa97d
762
// // ProfileViewController.swift // tinderapp // // Created by Mely Bohlman on 10/29/18. // Copyright © 2018 Chris Bohlman. All rights reserved. // import UIKit class ProfileViewController: UIViewController { @IBOutlet weak var cardImage: UIImageView! var newImage: UIImage! override func viewDidLoad() { super.viewDidLoad() cardImage.image = newImage } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
23.090909
106
0.667979
d9c569c251776a946571cf546ea4e9d8456cccb8
4,890
// // GridView.swift // Forms // // Created by Konrad on 8/23/20. // Copyright © 2020 Limbo. All rights reserved. // import FormsAnchor import FormsUtilsUI import UIKit // MARK: GridView open class GridView: FormsComponent, FormsComponentWithMarginEdgeInset, FormsComponentWithPaddingEdgeInset { public let backgroundView = UIView() public let stackView = UIStackView() open var axis: NSLayoutConstraint.Axis { get { return self.stackView.axis } set { self.stackView.axis = newValue self.remakeView() } } override open var backgroundColor: UIColor? { get { return self.backgroundView.backgroundColor } set { self.backgroundView.backgroundColor = newValue } } open var height: CGFloat = UITableView.automaticDimension open var items: [UIView] = [] { didSet { self.remakeView() } } open var itemsPerSection: Int = 0 { didSet { self.remakeView() } } open var marginEdgeInset: UIEdgeInsets = UIEdgeInsets(0) { didSet { self.updateMarginEdgeInset() } } open var paddingEdgeInset: UIEdgeInsets = UIEdgeInsets(0) { didSet { self.updatePaddingEdgeInset() } } open var spacing: CGFloat { get { return self.stackView.spacing } set { self.stackView.spacing = newValue } } public var sectionsCount: Int { return self.stackView.arrangedSubviews.count } override open func setupView() { self.setupBackgroundView() self.setupStackView() super.setupView() } override open func componentHeight() -> CGFloat { return self.height } open func setupBackgroundView() { self.backgroundView.frame = self.bounds self.addSubview(self.backgroundView, with: [ Anchor.to(self).fill ]) } open func setupStackView() { self.stackView.alignment = UIStackView.Alignment.fill self.stackView.axis = NSLayoutConstraint.Axis.vertical self.stackView.distribution = UIStackView.Distribution.fillEqually self.stackView.spacing = 0 self.backgroundView.addSubview(self.stackView, with: [ Anchor.to(self.backgroundView).fill ]) } open func updateMarginEdgeInset() { let edgeInset: UIEdgeInsets = self.marginEdgeInset self.backgroundView.frame = self.bounds.with(inset: edgeInset) self.backgroundView.constraint(to: self, position: .top)?.constant = edgeInset.top self.backgroundView.constraint(to: self, position: .bottom)?.constant = -edgeInset.bottom self.backgroundView.constraint(to: self, position: .leading)?.constant = edgeInset.leading self.backgroundView.constraint(to: self, position: .trailing)?.constant = -edgeInset.trailing } open func updatePaddingEdgeInset() { let edgeInset: UIEdgeInsets = self.paddingEdgeInset self.stackView.frame = self.bounds.with(inset: edgeInset) self.stackView.constraint(to: self.backgroundView, position: .top)?.constant = edgeInset.top self.stackView.constraint(to: self.backgroundView, position: .bottom)?.constant = -edgeInset.bottom self.stackView.constraint(to: self.backgroundView, position: .leading)?.constant = edgeInset.leading self.stackView.constraint(to: self.backgroundView, position: .trailing)?.constant = -edgeInset.trailing } } // MARK: View public extension GridView { func remakeView() { self.stackView.removeArrangedSubviews() guard 0 < self.itemsPerSection else { return } let sections: Int = (self.items.count.asCGFloat / self.itemsPerSection.asCGFloat).ceiled.asInt for section in 0..<sections { let view: UIStackView = UIStackView() view.alignment = UIStackView.Alignment.fill view.axis = self.axis.reversed view.distribution = UIStackView.Distribution.fillEqually for j in 0..<self.itemsPerSection { let i: Int = (section * self.itemsPerSection) + j guard let item: UIView = self.items[safe: i] else { break } view.addArrangedSubview(item) } self.stackView.addArrangedSubview(view) } } } // MARK: Builder public extension GridView { func with(axis: NSLayoutConstraint.Axis) -> Self { self.axis = axis return self } @objc override func with(height: CGFloat) -> Self { self.height = height return self } func with(items: [UIView]) -> Self { self.items = items return self } func with(itemsPerSection: Int) -> Self { self.itemsPerSection = itemsPerSection return self } func with(spacing: CGFloat) -> Self { self.spacing = spacing return self } }
34.43662
111
0.646012
286a2e8b49bcbc81e5e8c6ac919c34baf73cfea6
505
// // Copyright (c) 2019 Adyen B.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import Foundation struct OpenInvoicePersonalDetails { var firstName: String? var lastName: String? var dateOfBirth: String? var gender: String? var telephoneNumber: String? var socialSecurityNumber: String? var shopperEmail: String? func fullName() -> String { return "\(firstName ?? "") \(lastName ?? "")" } }
22.954545
100
0.657426
69f50034daa698baf51af3e58b987dd2514618ba
5,117
import WebKit /// Handles interaction with the Page Content Service JavaScript interface /// Passes setup parameters to the webpage (theme, margins, etc) and sets up a listener to recieve events (link tapped, image tapped, etc) through the messaging bridge /// https://www.mediawiki.org/wiki/Page_Content_Service final class PageContentService { struct Setup { struct Parameters: Codable { let platform = "ios" let version = 1 var theme: String var dimImages: Bool struct Margins: Codable { // these values are strings to allow for units to be included let top: String let right: String let bottom: String let left: String } var margins: Margins var leadImageHeight: String // units are included var areTablesInitiallyExpanded: Bool var textSizeAdjustmentPercentage: String // string like '125%' var userGroups: [String] } } struct Footer { struct Menu: Codable { static let fragment = "pcs-footer-container-menu" enum Item: String, Codable { case lastEdited case pageIssues case disambiguation case coordinate case talkPage } let items: [Item] let editedDaysAgo: Int? } struct ReadMore: Codable { static let fragment = "pcs-footer-container-readmore" let itemCount: Int let baseURL: String } struct Parameters: Codable { let title: String let menu: Menu let readMore: ReadMore } } static let paramsEncoder = JSONEncoder() static let messageHandlerName = "pcs" /// - Parameter encodable: the object to encode /// - Returns: a JavaScript string that will call JSON.parse on the JSON representation of the encodable class func getJavascriptFor<T>(_ encodable: T) throws -> String where T: Encodable { let data = try PageContentService.paramsEncoder.encode(encodable) guard let string = String(data: data, encoding: .utf8) else { throw RequestError.invalidParameters } return "JSON.parse(`\(string.sanitizedForJavaScriptTemplateLiterals)`)" } final class SetupScript: WKUserScript { required init(_ parameters: Setup.Parameters) throws { let source = """ document.pcsActionHandler = (action) => { window.webkit.messageHandlers.\(PageContentService.messageHandlerName).postMessage(action) }; document.pcsSetupSettings = \(try PageContentService.getJavascriptFor(parameters)); """ super.init(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: true) } } final class PropertiesScript: WKUserScript { static let source: String = { guard let fileURL = Bundle.main.url(forResource: "Properties", withExtension: "js"), let data = try? Data(contentsOf: fileURL), let jsString = String(data: data, encoding: .utf8)?.replacingOccurrences(of: "{{messageHandlerName}}", with: PageContentService.messageHandlerName) else { return "" } return jsString }() required override init() { super.init(source: PropertiesScript.source, injectionTime: .atDocumentEnd, forMainFrameOnly: true) } } final class UtilitiesScript: WKUserScript { static let source: String = { guard let fileURL = Bundle.wmf.url(forResource: "index", withExtension: "js", subdirectory: "assets"), let data = try? Data(contentsOf: fileURL), let jsString = String(data: data, encoding: .utf8) else { return "" } return jsString }() required override init() { super.init(source: UtilitiesScript.source, injectionTime: .atDocumentEnd, forMainFrameOnly: true) } } final class StyleScript: WKUserScript { static let source: String = { guard let fileURL = Bundle.wmf.url(forResource: "styleoverrides", withExtension: "css", subdirectory: "assets"), let data = try? Data(contentsOf: fileURL), let cssString = String(data: data, encoding: .utf8)?.sanitizedForJavaScriptTemplateLiterals else { return "" } return "const style = document.createElement('style'); style.innerHTML = `\(cssString)`; document.head.appendChild(style);" }() required override init() { super.init(source: StyleScript.source, injectionTime: .atDocumentEnd, forMainFrameOnly: true) } } }
37.625
167
0.575923
017472ab24e8cd2698ea48b8dabbcfddcea093c9
20,171
// // AVOption.swift // SwiftFFmpeg // // Created by sunlubo on 2018/7/10. // import CFFmpeg // MARK: - AVOption typealias CAVOption = CFFmpeg.AVOption public struct AVOption { public var name: String /// The short English help text about the option. public var help: String? /// The offset relative to the context structure where the option value is stored. /// It should be 0 for named constants. public var offset: Int public var type: Kind /// The default value for scalar options. public var defaultValue: Any /// The minimum valid value for the option. public var min: Double /// The maximum valid value for the option. public var max: Double public var flags: Flag /// The logical unit to which the option belongs. /// Non-constant options and corresponding named constants share the same unit. public var unit: String? init(cOption: CAVOption) { self.name = String(cString: cOption.name) self.help = String(cString: cOption.help) self.offset = Int(cOption.offset) self.type = Kind(rawValue: cOption.type.rawValue)! self.min = cOption.min self.max = cOption.max self.flags = Flag(rawValue: cOption.flags) self.unit = String(cString: cOption.unit) switch type { case .flags, .int, .int64, .uint64, .const, .pixelFormat, .sampleFormat, .duration, .channelLayout: self.defaultValue = cOption.default_val.i64 case .double, .float, .rational: self.defaultValue = cOption.default_val.dbl case .bool: self.defaultValue = cOption.default_val.i64 != 0 ? "true" : "false" case .string, .imageSize, .videoRate, .color: self.defaultValue = String(cString: cOption.default_val.str) ?? "nil" case .binary: self.defaultValue = 0 case .dict: // Cannot set defaults for these types self.defaultValue = "" } } } extension AVOption: CustomStringConvertible { public var description: String { var str = "{name: \"\(name)\", " if let help = help { str += "help: \"\(help)\", " } str += "offset: \(offset), type: \(type), " if defaultValue is String { str += "default: \"\(defaultValue)\", " } else { str += "default: \(defaultValue), " } str += "min: \(min), max: \(max), flags: \(flags), " if let unit = unit { str += "unit: \"\(unit)\"" } else { str.removeLast(2) } str += "}" return str } } // MARK: - AVOption.Kind extension AVOption { // https://github.com/FFmpeg/FFmpeg/blob/master/libavutil/opt.h#L221 public enum Kind: UInt32 { case flags case int case int64 case double case float case string case rational /// offset must point to a pointer immediately followed by an int for the length case binary case dict case uint64 case const /// offset must point to two consecutive integers case imageSize case pixelFormat case sampleFormat /// offset must point to `AVRational` case videoRate case duration case color case channelLayout case bool } } extension AVOption.Kind: CustomStringConvertible { public var description: String { switch self { case .flags: return "flags" case .int, .int64, .uint64: return "integer" case .double, .float: return "float" case .string: return "string" case .rational: return "rational number" case .binary: return "hexadecimal string" case .dict: return "dictionary" case .const: return "const" case .imageSize: return "image size" case .pixelFormat: return "pixel format" case .sampleFormat: return "sample format" case .videoRate: return "video rate" case .duration: return "duration" case .color: return "color" case .channelLayout: return "channel layout" case .bool: return "bool" } } } // MARK: - AVOption.Flag extension AVOption { // https://github.com/FFmpeg/FFmpeg/blob/master/libavutil/opt.h#L221 public struct Flag: OptionSet { /// A generic parameter which can be set by the user for muxing or encoding. public static let encoding = Flag(rawValue: AV_OPT_FLAG_ENCODING_PARAM) /// A generic parameter which can be set by the user for demuxing or decoding. public static let decoding = Flag(rawValue: AV_OPT_FLAG_DECODING_PARAM) public static let audio = Flag(rawValue: AV_OPT_FLAG_AUDIO_PARAM) public static let video = Flag(rawValue: AV_OPT_FLAG_VIDEO_PARAM) public static let subtitle = Flag(rawValue: AV_OPT_FLAG_SUBTITLE_PARAM) /// The option is intended for exporting values to the caller. public static let export = Flag(rawValue: AV_OPT_FLAG_EXPORT) /// The option may not be set through the `AVOption` API, only read. /// This flag only makes sense when `export` is also set. public static let readonly = Flag(rawValue: AV_OPT_FLAG_READONLY) /// A generic parameter which can be set by the user for bit stream filtering. public static let bsf = Flag(rawValue: AV_OPT_FLAG_BSF_PARAM) /// A generic parameter which can be set by the user for filtering. public static let filtering = Flag(rawValue: AV_OPT_FLAG_FILTERING_PARAM) /// Set if option is deprecated, users should refer to `AVOption.help` text for more information. public static let deprecated = Flag(rawValue: AV_OPT_FLAG_DEPRECATED) public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } } } extension AVOption.Flag: CustomStringConvertible { public var description: String { var str = "[" if contains(.encoding) { str += "encoding, " } if contains(.decoding) { str += "decoding, " } if contains(.audio) { str += "audio, " } if contains(.video) { str += "video, " } if contains(.subtitle) { str += "subtitle, " } if contains(.export) { str += "export, " } if contains(.bsf) { str += "bsf, " } if contains(.filtering) { str += "filtering, " } if contains(.deprecated) { str += "deprecated, " } if str.suffix(2) == ", " { str.removeLast(2) } str += "]" return str } } // MARK: - AVOptionSearchFlag extension AVOption { // https://github.com/FFmpeg/FFmpeg/blob/master/libavutil/opt.h#L556 public struct SearchFlag: OptionSet { /// Search in possible children of the given object first. public static let children = SearchFlag(rawValue: 1 << 0) /// The obj passed to `av_opt_find()` is fake – only a double pointer to `AVClass` /// instead of a required pointer to a struct containing `AVClass`. /// This is useful for searching for options without needing to allocate the corresponding object. public static let fakeObject = SearchFlag(rawValue: 1 << 1) /// In av_opt_get, return NULL if the option has a pointer type and is set to NULL, /// rather than returning an empty string. public static let nullable = SearchFlag(rawValue: 1 << 2) public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } } } @available(*, deprecated, renamed: "AVOption.SearchFlag") public typealias AVOptionSearchFlag = AVOption.SearchFlag // MARK: - AVOptionSupport public protocol AVOptionSupport { func withUnsafeObjectPointer<T>(_ body: (UnsafeMutableRawPointer) throws -> T) rethrows -> T } extension AVOptionSupport { /// Returns an array of the options supported by the type. public var supportedOptions: [AVOption] { withUnsafeObjectPointer { ptr in var list = [AVOption]() var prev: UnsafePointer<CAVOption>? while let option = av_opt_next(ptr, prev) { list.append(AVOption(cOption: option.pointee)) prev = option } return list } } } // MARK: - Option Getter extension AVOptionSupport { /// Returns the string value associated with the specified key. /// /// - Parameters: /// - key: The name of the option to get. /// - searchFlags: The flags passed to av_opt_find2. /// - Returns: The string value associated with the specified key. /// - Throws: AVError public func string( forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws -> String { try withUnsafeObjectPointer { ptr in var value: UnsafeMutablePointer<UInt8>! defer { av_free(value) } try throwIfFail(av_opt_get(ptr, key, searchFlags.rawValue, &value)) return String(cString: value) } } /// Returns the integer value associated with the specified key. /// /// - Parameters: /// - key: The name of the option to get. /// - searchFlags: The flags passed to av_opt_find2. /// - Returns: The integer value associated with the specified key. /// - Throws: AVError public func integer<T: FixedWidthInteger>( forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws -> T { try withUnsafeObjectPointer { ptr in var value: Int64 = 0 try throwIfFail(av_opt_get_int(ptr, key, searchFlags.rawValue, &value)) return T(value) } } /// Returns the double value associated with the specified key. /// /// - Parameters: /// - key: The name of the option to get. /// - searchFlags: The flags passed to av_opt_find2. /// - Returns: The double value associated with the specified key. /// - Throws: AVError public func double( forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws -> Double { try withUnsafeObjectPointer { ptr in var value: Double = 0 try throwIfFail(av_opt_get_double(ptr, key, searchFlags.rawValue, &value)) return value } } /// Returns the rational value associated with the specified key. /// /// - Parameters: /// - key: The name of the option to get. /// - searchFlags: The flags passed to av_opt_find2. /// - Returns: The rational value associated with the specified key. /// - Throws: AVError public func rational( forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws -> AVRational { try withUnsafeObjectPointer { ptr in var value = AVRational(num: 0, den: 0) try throwIfFail(av_opt_get_q(ptr, key, searchFlags.rawValue, &value)) return value } } /// Returns the image size associated with the specified key. /// /// - Parameters: /// - key: The name of the option to get. /// - searchFlags: The flags passed to av_opt_find2. /// - Returns: The image size associated with the specified key. /// - Throws: AVError public func size( forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws -> (width: Int, height: Int) { try withUnsafeObjectPointer { ptr in var width: Int32 = 0 var height: Int32 = 0 try throwIfFail(av_opt_get_image_size(ptr, key, searchFlags.rawValue, &width, &height)) return (Int(width), Int(height)) } } /// Returns the pixel format associated with the specified key. /// /// - Parameters: /// - key: The name of the option to get. /// - searchFlags: The flags passed to av_opt_find2. /// - Returns: The pixel format associated with the specified key. /// - Throws: AVError public func pixelFormat( forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws -> AVPixelFormat { try withUnsafeObjectPointer { ptr in var value = AVPixelFormat.none try throwIfFail(av_opt_get_pixel_fmt(ptr, key, searchFlags.rawValue, &value)) return value } } /// Returns the sample format associated with the specified key. /// /// - Parameters: /// - key: The name of the option to get. /// - searchFlags: The flags passed to av_opt_find2. /// - Returns: The sample format associated with the specified key. /// - Throws: AVError public func sampleFormat( forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws -> AVSampleFormat { try withUnsafeObjectPointer { ptr in var value = AV_SAMPLE_FMT_NONE try throwIfFail(av_opt_get_sample_fmt(ptr, key, searchFlags.rawValue, &value)) return AVSampleFormat(native: value) } } /// Returns the video rate associated with the specified key. /// /// - Parameters: /// - key: The name of the option to get. /// - searchFlags: The flags passed to av_opt_find2. /// - Returns: The video rate associated with the specified key. /// - Throws: AVError public func videoRate( forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws -> AVRational { try withUnsafeObjectPointer { ptr in var value = AVRational(num: 0, den: 0) try throwIfFail(av_opt_get_video_rate(ptr, key, searchFlags.rawValue, &value)) return value } } /// Returns the channel layout associated with the specified key. /// /// - Parameters: /// - key: The name of the option to get. /// - searchFlags: The flags passed to av_opt_find2. /// - Returns: The channel layout associated with the specified key. /// - Throws: AVError public func channelLayout( forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws -> Int64 { try withUnsafeObjectPointer { ptr in var value: Int64 = 0 try throwIfFail(av_opt_get_channel_layout(ptr, key, searchFlags.rawValue, &value)) return value } } } // MARK: - Option Setter extension AVOptionSupport { /// Sets the value of the specified key. /// /// If the field is not of a string type, then the given string is parsed. /// SI postfixes and some named scalars are supported. /// If the field is of a numeric type, it has to be a numeric or named /// scalar. Behavior with more than one scalar and +- infix operators /// is undefined. /// If the field is of a flags type, it has to be a sequence of numeric /// scalars or named flags separated by '+' or '-'. Prefixing a flag /// with '+' causes it to be set without affecting the other flags; /// similarly, '-' unsets a flag. /// If the field is of a dictionary type, it has to be a ':' separated list of /// key=value parameters. Values containing ':' special characters must be /// escaped. /// /// - Parameters: /// - value: The value to set. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set( _ value: String, forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail(av_opt_set(ptr, key, value, searchFlags.rawValue)) } } /// Sets the value of the specified key to the integer value. /// /// - Parameters: /// - value: The integer value. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set<T: FixedWidthInteger>( _ value: T, forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail(av_opt_set_int(ptr, key, Int64(value), searchFlags.rawValue)) } } /// Sets the value of the specified key to the double value. /// /// - Parameters: /// - value: The double value. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set( _ value: Double, forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail(av_opt_set_double(ptr, key, value, searchFlags.rawValue)) } } /// Sets the value of the specified key to the rational value. /// /// - Parameters: /// - value: The rational value. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set( _ value: AVRational, forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail(av_opt_set_q(ptr, key, value, searchFlags.rawValue)) } } /// Sets the value of the specified key to the binary value. /// /// - Parameters: /// - value: The binary value. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set( _ value: UnsafeBufferPointer<UInt8>, forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail( av_opt_set_bin(ptr, key, value.baseAddress, Int32(value.count), searchFlags.rawValue)) } } /// Sets the value of the specified key to the image size. /// /// - Parameters: /// - value: The image size. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set( _ size: (width: Int, height: Int), forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail( av_opt_set_image_size( ptr, key, Int32(size.width), Int32(size.height), searchFlags.rawValue ) ) } } /// Sets the value of the specified key to the pixel format. /// /// - Parameters: /// - value: The pixel format. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set( _ value: AVPixelFormat, forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail(av_opt_set_pixel_fmt(ptr, key, value, searchFlags.rawValue)) } } /// Sets the value of the specified key to the sample format. /// /// - Parameters: /// - value: The sample format. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set( _ value: AVSampleFormat, forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail(av_opt_set_sample_fmt(ptr, key, value.native, searchFlags.rawValue)) } } /// Sets the value of the specified key to the video rate. /// /// - Parameters: /// - value: The video rate. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func setVideoRate( _ value: AVRational, forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail(av_opt_set_video_rate(ptr, key, value, searchFlags.rawValue)) } } /// Sets the value of the specified key to the channel layout. /// /// - Parameters: /// - value: The channel layout. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set( _ value: AVChannelLayout, forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try withUnsafeObjectPointer { ptr in try throwIfFail( av_opt_set_channel_layout(ptr, key, Int64(value.rawValue), searchFlags.rawValue)) } } /// Sets the value of the specified key to the integer array. /// /// - Parameters: /// - value: The integer array. /// - key: The key with which to associate the value. /// - searchFlags: The flags passed to `av_opt_find2`. /// - Throws: AVError public func set<T: FixedWidthInteger>( _ value: [T], forKey key: String, searchFlags: AVOption.SearchFlag = .children ) throws { try value.withUnsafeBytes { ptr in let ptr = ptr.bindMemory(to: UInt8.self).baseAddress let count = MemoryLayout<T>.size * value.count try set(UnsafeBufferPointer(start: ptr, count: count), forKey: key) } } }
33.674457
102
0.663428
23d7b478a62a782c36f3ac85da8401bf7d65f885
4,766
// // BaseKitTableViewModel.swift // SwiftMKitDemo // // Created by Mao on 5/13/16. // Copyright © 2016 cdts. All rights reserved. // import UIKit import CocoaLumberjack import Alamofire import MJRefresh open class BaseKitTableViewModel: NSObject { open weak var viewController: BaseKitTableViewController! open var hud: HudProtocol { get { return self.viewController.hud } } open var taskIndicator: Indicator { get { return self.viewController.taskIndicator } } open var view: UIView { get { return self.viewController.view } } open func fetchData() { } deinit { DDLogError("Deinit: \(NSStringFromClass(type(of: self)))") } fileprivate struct InnerConstant { static let StringNoMoreDataTip = "数据已全部加载完毕" } open var listViewController: BaseKitTableViewController! { get { return viewController as BaseKitTableViewController } } var dataArray:[AnyObject] { get { if dataSource.first == nil { dataSource.append([AnyObject]()) } return dataSource.first! } set { dataSource = [newValue] } } var dataSource:[[AnyObject]] = [[AnyObject]]() { didSet { if self.viewController == nil { return } if self.listViewController.listViewType == .refreshOnly || self.listViewController.listViewType == .none { return } var noMoreDataTip = InnerConstant.StringNoMoreDataTip let count: UInt = UInt(dataSource.count) if count == 0 { self.viewController.showEmptyView() self.listViewController.listView.mj_footer.endRefreshingWithNoMoreData() noMoreDataTip = "" return } if oldValue.count == 0 { self.viewController.hideEmptyView() self.listViewController.listView.mj_footer.resetNoMoreData() } if count < listLoadNumber { self.listViewController.listView.mj_footer.endRefreshingWithNoMoreData() noMoreDataTip = "" }else if count % listLoadNumber > 0 || count >= listMaxNumber { self.listViewController.listView.mj_footer.endRefreshingWithNoMoreData() } if let footer = self.listViewController.listView.mj_footer as? MJRefreshAutoStateFooter { footer.setTitle(noMoreDataTip, for: .noMoreData) } } } var dataIndex: UInt = 0 let listLoadNumber: UInt = 20 let listMaxNumber: UInt = UInt.max open func updateDataArray(_ newData: [AnyObject]?) { if let data = newData { if dataIndex == 0 { dataArray = data } else { dataArray += data } } else { if dataIndex == 0 { dataArray = [] } } if let table = self.listViewController.listView as? UITableView { table.reloadData() } else if let collect = self.listViewController.listView as? UICollectionView { collect.reloadData() } } open func updateDataSource(_ newData: [[AnyObject]]?) { dataSource = newData ?? [[AnyObject]]() if let table = self.listViewController.listView as? UITableView { table.reloadData() } else if let collect = self.listViewController.listView as? UICollectionView { collect.reloadData() } } } //HUD extension BaseKitTableViewModel { public func showTip(_ tip: String, completion : @escaping () -> Void = {}) { showTip(tip, view: self.view, completion: completion) } public func showTip(_ tip: String, image: UIImage?, completion : @escaping () -> Void = {}) { MBHud.shared.showTip(inView: view, text: tip, image: image, animated: true, completion: completion) } public func showTip(_ tip: String, view: UIView, offset: CGPoint = CGPoint.zero, completion : @escaping () -> Void = {}) { MBHud.shared.showTip(inView: view, text: tip, offset: offset, animated: true, completion: completion) } public func showLoading(_ text: String = "") { viewController.showIndicator(inView: viewController.view, text: text) } public func showLoading(_ text: String, view: UIView) { viewController.showIndicator(inView: view, text: text) } public func hideLoading() { viewController.hideLoading() } public func hideLoading(_ view: UIView) { viewController.hideLoading(view) } }
32.868966
126
0.589173
e2df59b9e7cab7f4730d0788903085c2d01d0a67
3,794
// // ViewController.swift // TableEx // // Created by 동균 on 04/12/2018. // Copyright © 2018 동균. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{ //섹션별 셀 수 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: //섹션은 0부터 시작 가장 첫 섹션 return 1 case 1: return 2 default: return 0 } } //셀별 세부사항 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell! cell.textLabel?.text = "title" cell.detailTextLabel?.text = "1" return cell } //섹션의 개수 func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "앞부분" } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return "뒷부분" } // 기존에 존재하던 스와이프함수 // func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { // let delete = UITableViewRowAction(style: .default, title: "삭제") { (UITableViewRowAction, IndexPath) in // print("1") // } // let edit = UITableViewRowAction(style: .destructive, title: "수정") { (UITableViewRowAction, IndexPath) in // print("1") // } // // return [delete, edit] // // } // 왼 -> 오 스와이프 iOS11 이 나오고 새로 생김 func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let deleteAction = UIContextualAction(style: .destructive, title: "삭제", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in // Call edit action // Reset state success(true) }) let shareAction = UIContextualAction(style: .normal, title: "공유", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in // Call edit action // Reset state success(true) }) return UISwipeActionsConfiguration(actions:[deleteAction,shareAction]) } // 오->왼 스와이프 iOS11 이 나오고 새로 생김 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let deleteAction = UIContextualAction(style: .destructive, title: "삭제", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in // Call edit action // Reset state success(true) }) let shareAction = UIContextualAction(style: .normal, title: "공유", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in // Call edit action // Reset state success(true) }) return UISwipeActionsConfiguration(actions:[deleteAction,shareAction]) } @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self // Do any additional setup after loading the view, typically from a nib. } }
29.874016
155
0.576173
dd86669ef04a38ed9b733a76d837fba4c56be0e7
630
// // ConversationListTableVCMock.swift // ApplozicSwiftDemoTests // // Created by Shivam Pokhriyal on 19/12/18. // Copyright © 2018 Applozic. All rights reserved. // import Foundation import Applozic @testable import ApplozicSwift class ConversationListTableVCMock: ALKConversationListTableViewController { var isMuteCalled: Bool = false override func mute(conversation: ALMessage, forTime: Int64, atIndexPath: IndexPath) { isMuteCalled = true } func tapped(_ chat: ALKChatViewModelProtocol, at index: Int) { } func emptyChatCellTapped() { } }
21
89
0.685714
56b521a3b79fbf5c7520e0c898655cdd06d36dcd
1,762
// // Aletheia // // Created by Stephen Chen on 27/1/2017. // Copyright © 2018 stephenchen. All rights reserved. // #if os(iOS) import UIKit public extension UIColor { /// SwifterSwift: Create UIColor from hexadecimal value with optional transparency. /// /// - Parameters: /// - hex: hex Int (example: 0xDECEB5). /// - transparency: optional transparency value (default is 1). convenience init(hex: Int, transparency: CGFloat = 1) { var trans: CGFloat { if transparency > 1 { return 1 } else if transparency < 0 { return 0 } else { return transparency } } self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff, transparency: trans) } /// SwifterSwift: Create UIColor from RGB values with optional transparency. /// /// - Parameters: /// - red: red component. /// - green: green component. /// - blue: blue component. /// - transparency: optional transparency value (default is 1). convenience init(red: Int, green: Int, blue: Int, transparency: CGFloat = 1) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") var trans: CGFloat { if transparency > 1 { return 1 } else if transparency < 0 { return 0 } else { return transparency } } self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: trans) } } #endif
30.37931
118
0.544835
fcdeeb60e9a3fd979042bc3fe19f5da98af14b90
112
import XCTest import XOpenTests var tests = [XCTestCaseEntry]() tests += XOpenTests.allTests() XCTMain(tests)
14
31
0.767857
0393f31876a33eececd9083a54f5026b4b7027f1
986
// // TriangleView.swift // PokeMaster // // Created by kingcos on 2020/4/26. // Copyright © 2020 OneV's Den. All rights reserved. // import SwiftUI struct TriangleView: Shape { func path(in rect: CGRect) -> Path { Path { path in // 起点为左上角 path.move(to: .zero) // 添加圆弧 path.addArc(center: CGPoint(x: -rect.width / 5, y: rect.height / 2), radius: rect.width / 2, startAngle: .degrees(-45), endAngle: .degrees(45), clockwise: false) path.addLine(to: CGPoint(x: 0, y: rect.height)) path.addLine(to: CGPoint(x: rect.width, y: rect.height / 2)) // 闭合线段 path.closeSubpath() } } } struct TriangleView_Previews: PreviewProvider { static var previews: some View { TriangleView() .fill(Color.green) .frame(width: 80, height: 80) } }
26.648649
80
0.511156
623733a4f2f0725d792ec9948fead7547b004d4f
1,136
// // AddressView.swift // CupcakeCorner // // Created by Richard-Bollans, Jack on 28.9.2021. // import SwiftUI struct AddressView: View { @ObservedObject var model: OrderModel var body: some View { Form { Section { TextField("Name", text: $model.order.name) TextField("Street Address", text: $model.order.streetAddress) TextField("City", text: $model.order.city) TextField("Zip", text: $model.order.zip) } Section { NavigationLink( destination: CheckoutView(model: model), label: { Text("Checkout") }) } .disabled(model.order.hasValidAddress == false) } .navigationBarTitle("Delivery details", displayMode: .inline) } } struct AddressView_Previews: PreviewProvider { static var previews: some View { NavigationView{ AddressView(model: OrderModel()) } } }
24.695652
77
0.494718
ffe4fd04f89a249ef07c0a69fe99ff8fcc09642a
586
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "XLPagerTabStrip", platforms: [.iOS(.v9)], products: [ .library(name: "XLPagerTabStrip", targets: ["XLPagerTabStrip"]) ], dependencies: [], targets: [ .target( name: "XLPagerTabStrip", dependencies: [], path: "Sources", resources: [.process("ButtonCell.xib")], publicHeadersPath: "XLPagerTabStrip"), .testTarget( name: "XLPagerTabStripTests", dependencies: ["XLPagerTabStrip"], path: "Tests", exclude: ["Info.plist"]) ] )
22.538462
67
0.619454
223ca7feedab8d167899588b342405124be03936
323
// // Comic.swift // App Marvel // // Created by Thiago Vaz on 09/12/21. // import Foundation public struct Comic: Decodable { public let id: Int public let title: String? public let issueNumber: Double? public let description: String? public let pageCount: Int? public let thumbnail: Image? }
17.944444
38
0.671827
d6137b32e5a25749bc3d3dff723c311c494d677d
1,092
// // Keychain+Keys.swift // Tradelytics // // Created by Prince Ugwuh on 2/14/19. // Copyright © 2019 Alerting Options. All rights reserved. // import Foundation import SwiftAdditions extension Keychain { public struct Key: RawRepresentable, Hashable { public let rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } } } extension Keychain { public static func value<T: Codable>(forKey key: Key) -> T? { return value(forKey: key.rawValue) } public static func remove(key: Key, accessibility: Keychain.Accessibility = .whenUnlockedThisDeviceOnly) -> Bool { return remove(key: key.rawValue, accessibility: accessibility) } @discardableResult public static func set<T: Codable>(_ value: T?, key: Key, accessibility: Keychain.Accessibility = .whenUnlockedThisDeviceOnly) -> Bool { return set(value, key: key.rawValue, accessibility: accessibility) } }
27.3
140
0.650183
2355854e1cfa359231fc568d70677dcbb645eedb
869
// // SortingTest.swift // SwiftAlgorithms // // Created by Kartupelis, John on 25/03/2018. // Copyright © 2018 Kartupelis, John. All rights reserved. // import Foundation class SortingTest { let unsortedArray: [Int] init() { var unsortedArray = [Int]() for _ in 1..<arc4random_uniform(10000) { unsortedArray.append(Int(arc4random())) } self.unsortedArray = unsortedArray } func run(sortingAlgorithmType: BaseSorting<Int>.Type) { let algorithm = sortingAlgorithmType.init(unsortedArray) let sortedArray = unsortedArray.sorted() let ourSortedArray = algorithm.sort() assert(sortedArray == ourSortedArray, String(format:"Our %@ array should be the same as the system sorted array", algorithm.name())) NSLog("Successfully performed %@", algorithm.name()) } }
28.032258
140
0.657077
dd035de996de9d4bc55225cd5ca02bb881415f65
641
// // ViewController.swift // ModalViewSample // // Created by 关东升 on 16/2/6. // 本书网站:http://www.51work6.com // 智捷课堂在线课堂:http://www.zhijieketang.com/ // 智捷课堂微信公共号:zhijieketang // 作者微博:@tony_关东升 // 作者微信:tony关东升 // QQ:569418560 邮箱:[email protected] // QQ交流群:162030268 // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.03125
80
0.672387
5bc57a816f718eb600e9409732d718cc6559f0a7
7,372
// // Publishers.First.swift // // // Created by Joseph Spadafora on 7/8/19. // extension Publisher { /// Publishes the first element of a stream, then finishes. /// /// If this publisher doesn’t receive any elements, it finishes without publishing. /// - Returns: A publisher that only publishes the first element of a stream. public func first() -> Publishers.First<Self> { return .init(upstream: self) } /// Publishes the first element of a stream to /// satisfy a predicate closure, then finishes. /// /// The publisher ignores all elements after the first. /// If this publisher doesn’t receive any elements, /// it finishes without publishing. /// - Parameter predicate: A closure that takes an element as a parameter and /// returns a Boolean value that indicates whether to publish the element. /// - Returns: A publisher that only publishes the first element of a stream /// that satisfies the predicate. public func first( where predicate: @escaping (Output) -> Bool ) -> Publishers.FirstWhere<Self> { return .init(upstream: self, predicate: predicate) } /// Publishes the first element of a stream to satisfy a /// throwing predicate closure, then finishes. /// /// The publisher ignores all elements after the first. If this publisher /// doesn’t receive any elements, it finishes without publishing. If the /// predicate closure throws, the publisher fails with an error. /// - Parameter predicate: A closure that takes an element as a parameter and /// returns a Boolean value that indicates whether to publish the element. /// - Returns: A publisher that only publishes the first element of a stream /// that satisfies the predicate. public func tryFirst( where predicate: @escaping (Output) throws -> Bool ) -> Publishers.TryFirstWhere<Self> { return .init(upstream: self, predicate: predicate) } } extension Publishers { /// A publisher that publishes the first element of a stream, then finishes. public struct First<Upstream: Publisher>: Publisher { public typealias Output = Upstream.Output public typealias Failure = Upstream.Failure /// The publisher from which this publisher receives elements. public let upstream: Upstream public init(upstream: Upstream) { self.upstream = upstream } public func receive<Downstream: Subscriber>(subscriber: Downstream) where Failure == Downstream.Failure, Output == Downstream.Input { upstream.subscribe(Inner(downstream: subscriber)) } } /// A publisher that only publishes the first element of a /// stream to satisfy a predicate closure. public struct FirstWhere<Upstream: Publisher>: Publisher { public typealias Output = Upstream.Output public typealias Failure = Upstream.Failure /// The publisher from which this publisher receives elements. public let upstream: Upstream /// The closure that determines whether to publish an element. public let predicate: (Output) -> Bool public init(upstream: Upstream, predicate: @escaping (Output) -> Bool) { self.upstream = upstream self.predicate = predicate } public func receive<Downstream: Subscriber>(subscriber: Downstream) where Failure == Downstream.Failure, Output == Downstream.Input { upstream.subscribe(Inner(downstream: subscriber, predicate: predicate)) } } /// A publisher that only publishes the first element of a stream /// to satisfy a throwing predicate closure. public struct TryFirstWhere<Upstream: Publisher>: Publisher { public typealias Output = Upstream.Output public typealias Failure = Error /// The publisher from which this publisher receives elements. public let upstream: Upstream /// The error-throwing closure that determines whether to publish an element. public let predicate: (Output) throws -> Bool public init(upstream: Upstream, predicate: @escaping (Output) throws -> Bool) { self.upstream = upstream self.predicate = predicate } public func receive<Downstream: Subscriber>(subscriber: Downstream) where Failure == Downstream.Failure, Output == Downstream.Input { upstream.subscribe(Inner(downstream: subscriber, predicate: predicate)) } } } extension Publishers.First: Equatable where Upstream: Equatable {} extension Publishers.First { private final class Inner<Downstream: Subscriber> : ReduceProducer<Downstream, Upstream.Output, Upstream.Output, Upstream.Failure, Void> where Upstream.Output == Downstream.Input, Upstream.Failure == Downstream.Failure { fileprivate init(downstream: Downstream) { super.init(downstream: downstream, initial: nil, reduce: ()) } override func receive( newValue: Upstream.Output ) -> PartialCompletion<Void, Downstream.Failure> { result = newValue return .finished } override var description: String { return "First" } } } extension Publishers.FirstWhere { private final class Inner<Downstream: Subscriber> : ReduceProducer<Downstream, Output, Output, Failure, (Output) -> Bool> where Upstream.Output == Downstream.Input, Upstream.Failure == Downstream.Failure { fileprivate init(downstream: Downstream, predicate: @escaping (Output) -> Bool) { super.init(downstream: downstream, initial: nil, reduce: predicate) } override func receive( newValue: Output ) -> PartialCompletion<Void, Downstream.Failure> { if reduce(newValue) { result = newValue return .finished } else { return .continue } } override var description: String { return "TryFirst" } } } extension Publishers.TryFirstWhere { private final class Inner<Downstream: Subscriber> : ReduceProducer<Downstream, Output, Output, Upstream.Failure, (Output) throws -> Bool> where Upstream.Output == Downstream.Input, Downstream.Failure == Error { fileprivate init(downstream: Downstream, predicate: @escaping (Output) throws -> Bool) { super.init(downstream: downstream, initial: nil, reduce: predicate) } override func receive( newValue: Output ) -> PartialCompletion<Void, Error> { do { if try reduce(newValue) { result = newValue return .finished } else { return .continue } } catch { return .failure(error) } } override var description: String { return "TryFirstWhere" } } }
34.938389
89
0.616251
cc787aa8dc3a29b35d9db509b7b65f24e054c9b7
4,033
import RxSwift import BigInt class TransactionSyncManager { private let disposeBag = DisposeBag() private let scheduler = ConcurrentDispatchQueueScheduler(qos: .background) private let stateSubject = PublishSubject<SyncState>() private let transactionsSubject = PublishSubject<[FullTransaction]>() private let notSyncedTransactionManager: NotSyncedTransactionManager private let syncStateQueue = DispatchQueue(label: "transaction_sync_manager_state_queue", qos: .background) private var syncers = [ITransactionSyncer]() private var syncerDisposables = [String: Disposable]() private var accountState: AccountState? = nil var state: SyncState = .notSynced(error: Kit.SyncError.notStarted) { didSet { if state != oldValue { stateSubject.onNext(state) } } } var stateObservable: Observable<SyncState> { stateSubject.asObservable() } var transactionsObservable: Observable<[FullTransaction]> { transactionsSubject.asObservable() } init(notSyncedTransactionManager: NotSyncedTransactionManager) { self.notSyncedTransactionManager = notSyncedTransactionManager } func set(ethereumKit: EthereumKit.Kit) { accountState = ethereumKit.accountState ethereumKit.accountStateObservable .observeOn(scheduler) .subscribe(onNext: { [weak self] in self?.onUpdateAccountState(accountState: $0) }) .disposed(by: disposeBag) ethereumKit.lastBlockHeightObservable .observeOn(scheduler) .subscribe(onNext: { [weak self] in self?.onLastBlockNumber(blockNumber: $0) }) .disposed(by: disposeBag) ethereumKit.syncStateObservable .observeOn(scheduler) .subscribe(onNext: { [weak self] in self?.onEthereumKitSyncState(state: $0) }) .disposed(by: disposeBag) } private func onEthereumKitSyncState(state: SyncState) { if .synced == state { syncers.forEach { $0.onEthereumSynced() } } } private func onLastBlockNumber(blockNumber: Int) { syncers.forEach { $0.onLastBlockNumber(blockNumber: blockNumber) } } private func onUpdateAccountState(accountState: AccountState) { if self.accountState != nil { syncers.forEach { $0.onUpdateAccountState(accountState: accountState) } } self.accountState = accountState } private func syncState() { switch state { case .synced: if let notSyncedState = syncers.first(where: { $0.state.notSynced })?.state { state = notSyncedState } case .syncing, .notSynced: state = syncers.first { $0.state.notSynced }?.state ?? syncers.first { $0.state.syncing }?.state ?? .synced } } func add(syncer: ITransactionSyncer) { guard !syncers.contains(where: { $0.id == syncer.id }) else { return } syncer.set(delegate: notSyncedTransactionManager) syncers.append(syncer) syncerDisposables[syncer.id] = syncer.stateObservable .observeOn(scheduler) .subscribe(onNext: { [weak self] _ in self?.syncStateQueue.async { [weak self] in self?.syncState() } }) syncer.start() } func removeSyncer(byId id: String) { syncers.removeAll { $0.id == id } syncerDisposables[id]?.dispose() syncerDisposables.removeValue(forKey: id) } } extension TransactionSyncManager: ITransactionSyncerListener { func onTransactionsSynced(fullTransactions: [FullTransaction]) { transactionsSubject.onNext(fullTransactions) } }
31.507813
111
0.605257
eb54265bee4666e56d3ff7e2b22a2769afb15aff
4,556
// // HomeScreenEnvironment.swift // Overseas // // Created by Elaine Cruz on 09/07/21. // import Foundation import CoreData import SwiftUI class HomeScreenEnvironment: ObservableObject, LearningDelegate{ @Published var categories: [Category] = [] let context = AppDelegate.viewContext @Published var fixedLearnings: [Learning] = [] @Published var allLearnings: [Learning] = [] @Published var didSelectNewCategory = false @Published var didSelectNewLearning = false @Published var categorySelected: Category? @Published var categoriesIsOpen: Bool = true @Published var lastCategory: Int = 0 init(){ NotificationCenter.default.addObserver(self, selector: #selector(self.addNewLearningByCategoryView(_:)), name: .addNewLearningByCategoryView, object: nil) reset() } init(_ any: Any?){ } func resetFixedLearnings() { fixedLearnings = [] let fixedsRequest: NSFetchRequest<Learning> = Learning.fetchRequest() fixedsRequest.predicate = NSPredicate(format: "isFixed == true") fixedsRequest.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] do { try fixedLearnings = context.fetch(fixedsRequest) } catch { print(error) } } func reset(){ print("resetted") categories = [] allLearnings = [] fixedLearnings = [] let categoriesRequest: NSFetchRequest<Category> = Category.fetchRequest() categoriesRequest.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] do { try categories = context.fetch(categoriesRequest) }catch{ print(error) } let fixedsRequest: NSFetchRequest<Learning> = Learning.fetchRequest() fixedsRequest.predicate = NSPredicate(format: "isFixed == true") fixedsRequest.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let learningsRequest: NSFetchRequest<Learning> = Learning.fetchRequest() learningsRequest.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] do { try fixedLearnings = context.fetch(fixedsRequest) try allLearnings = context.fetch(learningsRequest) }catch{ print(error) } self.objectWillChange.send() } func createNewCategory(name: String, colorIndex: Int){ if name == ""{ print("Please insert a name") return } let context = AppDelegate.viewContext let category = Category(name: name, color: colorIndex, context: context) categories.append(category) do{ try context.save() }catch{ print(error) } } func updateCategory(categoryIndex: Int, name: String, index: Int){ categories[categoryIndex].name = name categories[categoryIndex].color = String(index) do{ try context.save() }catch{ print(error) } } func getLearningsFromCategory(_ index: Int)->[Learning]{ let category = self.categories[index] var learnings = (category.learnings?.allObjects as! [Learning]) learnings.sort(by: {(learning1, learning2) in learning1.creationDate! > learning2.creationDate! }) learnings.sort(by: {(learning1, learning2) in learning1.isFixed && !learning2.isFixed }) return learnings } func saveNewLearning(categoryIndex: Int, title: String, description: String, emoji: String) { if title.isEmpty || description.isEmpty { return } let context = AppDelegate.viewContext let learning = Learning(name: title, descriptionText: description, emoji: emoji, estimatedTime: 0, text: "", context: context) categories[categoryIndex].addToLearnings(learning) learning.category = categories[categoryIndex] allLearnings.insert(learning, at: 0) do { try context.save() } catch { print(error) } } @objc func addNewLearningByCategoryView(_ note: NSNotification) { } }
28.654088
162
0.589552
038edf6bf607ce268d74f6f9aa6c93b58f144253
2,384
// // TestData.swift // PayTheory_Tests // // Created by Austin Zani on 5/18/21. // Copyright © 2021 CocoaPods. All rights reserved. // import Foundation import PayTheory let lastFour = "4242" let receiptNumber = "Test Receipt" let createdAt = "Now" let amount = 100 let serviceFee = 20 let state = "OH" let tags = ["Test": "Tags"] let brand = "Visa" let firstSix = "424242" let type = "fail" let transferToken = [ "last_four": lastFour, "created_at": createdAt, "amount": amount, "service_fee": serviceFee, "state": state, "tags": tags, "type": type, "receipt_number": receiptNumber ] as [String: AnyObject] let transferTokenWithBrand = [ "last_four": lastFour, "created_at": createdAt, "amount": amount, "service_fee": serviceFee, "state": state, "tags": tags, "card_brand": brand, "type": type, "receipt_number": receiptNumber ] as [String : AnyObject] let cardPaymentToken = [ "idempotency": receiptNumber, "payment": [ "amount": amount, "service_fee": serviceFee, ], "bin": [ "card_brand": brand, "first_six": firstSix ] ] as [String: AnyObject] let achPaymentToken = [ "idempotency": receiptNumber, "payment": [ "amount": amount, "service_fee": serviceFee, ], "bin": [ "last_four": lastFour ] ] as [String: AnyObject] let achCompletionResponse = [ "receipt_number": receiptNumber, "last_four": lastFour, "created_at": createdAt, "amount": amount, "service_fee": serviceFee, "state": state, "tags": tags ] as [String: Any] let cardCompletionResponse = [ "receipt_number": receiptNumber, "last_four": lastFour, "created_at": createdAt, "amount": amount, "service_fee": serviceFee, "state": state, "tags": tags, "brand": brand ] as [String: AnyObject] let failureResponse = FailureResponse(type: type, receiptNumber: receiptNumber, lastFour: lastFour, brand: brand) let cardTokenizationResponse = [ "receipt_number": receiptNumber, "amount": amount, "convenience_fee": serviceFee, "brand": brand, "first_six": firstSix ] as [String: AnyObject] let achTokenizationResponse = [ "receipt_number": receiptNumber, "amount": amount, "convenience_fee": serviceFee, "last_four": lastFour ] as [String: AnyObject]
22.280374
113
0.64094
7a4c74a2085a91ecda655142ae9c677c250b92a7
2,712
// Copyright © 2014 C4 // // 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 public extension View { /// Creates a flattened image of the receiver and its subviews / layers. /// - returns: A new Image public func render() -> Image? { guard let l = layer else { print("Could not retrieve layer for current object: \(self)") return nil } UIGraphicsBeginImageContextWithOptions(CGSize(size), false, UIScreen.main.scale) let context = UIGraphicsGetCurrentContext()! l.render(in: context) let uiimage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Image(uiimage: uiimage!) } } public extension Shape { /// Creates a flattened image of the receiver and its subviews / layers. /// This override takes into consideration the lineWidth of the receiver. /// - returns: A new Image public override func render() -> Image? { var s = CGSize(size) var inset: CGFloat = 0 if let alpha = strokeColor?.alpha, alpha > 0.0 && lineWidth > 0 { inset = CGFloat(lineWidth/2.0) s = CGRect(frame).insetBy(dx: -inset, dy: -inset).size } let scale = CGFloat(UIScreen.main.scale) UIGraphicsBeginImageContextWithOptions(s, false, scale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: CGFloat(-bounds.origin.x)+inset, y: CGFloat(-bounds.origin.y)+inset) shapeLayer.render(in: context) let uiimage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return Image(uiimage: uiimage!) } }
43.741935
99
0.695428
7a735f38daf3881e9a54d84e3b46290952b60061
1,791
// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Lima class BaselineAlignmentViewController: UIViewController { override func loadView() { let cellStyle = { (cell: UIView) in cell.layer.borderWidth = 0.5 cell.layer.borderColor = UIColor.lightGray.cgColor } view = LMScrollView(isFitToWidth: true, backgroundColor: UIColor.white, LMColumnView(margin: 8, LMRowView(margin: 4, isAlignToBaseline: true, LMSpacer(), UILabel(text: "abcd", font: UIFont.systemFont(ofSize: 16)), UILabel(text: "efg", font: UIFont.systemFont(ofSize: 32)), UILabel(text: "hijk", font: UIFont.systemFont(ofSize: 24)), LMSpacer(), with: cellStyle ), LMColumnView(margin: 4, horizontalAlignment: .center, isAlignToBaseline: true, UILabel(text: "abcd", font: UIFont.systemFont(ofSize: 16)), UILabel(text: "efg", font: UIFont.systemFont(ofSize: 32)), UILabel(text: "hijk", font: UIFont.systemFont(ofSize: 24)), with: cellStyle ) ) ) } }
39.8
94
0.600782
03f4c9ba67ba7a25fd70542b11daaa86863728e9
2,343
// CSQueqe.swift // CloudService /* ****************************************************************** * COPYRIGHT (c) <<2020>> <<tanu inc >> * * * All rights reserved * * * This software embodies materials and concepts which are * * confidential to <<Customer Name>> and is made available solely * * pursuant to the terms of a written license agreement with * * <<tanu Product>>. * * * Designed and Developed by tanu inc Industries, Inc. . * *----------------------------------------------------------------* * MODULE OR UNIT: CloudService * * * PROGRAMMER : Tanuja Awasthi * * DATE : 06/10/20 * * VERSION : 1.0 * * *----------------------------------------------------------------* * * MODULE SUMMARY : This is custom generic queue class which * will serve. FIFO operations * * * * * *----------------------------------------------------------------* * * TRACEABILITY RECORDS to SW requirements and detailed design : * * iOS 12 and onward * * *----------------------------------------------------------------* * * MODIFICATION RECORDS * * ****************************************************************** */ import Foundation struct CSQueue<T> { /// Contain list of items var list: [T] = [] /// Appending item in list /// - Parameter element: Generic elements mutating func enQueue(_ element: T) { list.append(element) } /// deleted item from the list at first place /// - Returns: return deleted item mutating func deQueue() ->T? { if list.isEmpty { return nil }else { return list.removeFirst() } } /// Picking first item /// - Returns: retrurn picked item mutating func peek() ->T? { if list.isEmpty { return nil }else { return list.first } } /// Checking list whether its empty or not /// - Returns: return the status func isEmptyList() -> Bool { return self.list.isEmpty } }
28.925926
66
0.405463
56e67d8d5a07cf4facea2e6aa16714f44542e7dd
396
// 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 class func compose<T : end: A> { enum S<T>) -> { } extension NSSet { extension String { } } self.A, T : a { } enum b { func a<T where T -> d>) { return ") private class func a: T.B
19.8
87
0.676768
89993fcd830e248ce139958edbba3f2ee01ca187
6,545
// Copyright (c) 2019 Spotify AB. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 /// Parses Swift Function times generated by the SwiftCompiler /// if you pass the flags `-Xfrontend -debug-time-function-bodies` public class SwiftFunctionTimesParser { typealias FilePath = String private static let compilerFlag = "-debug-time-function-bodies" private static let invalidLoc = "<invalid loc>" lazy var functionRegexp: NSRegularExpression? = { let pattern = "\\t*([0-9]+\\.[0-9]+)ms\\t+(<invalid\\tloc>|[^\\t]+)\\t+(.+)\\r" return NSRegularExpression.fromPattern(pattern) }() /// Array to store the text of the log sections and their commandDetailDesc var commands = [(String, String)]() /// Dictionary to store the function times found per filepath var functionsPerFile: [FilePath: [FunctionTime]]? public func addLogSection(_ logSection: IDEActivityLogSection) { commands.append((logSection.text, logSection.commandDetailDesc)) } /// Checks the `commandDetailDesc` stored by the function `addLogSection` /// to know if the command `text` contains data about the swift function times. /// If there is data, the `text` wit that raw data is returned as part of a Set. /// /// - Returns: a Set of Strings with the raw Swift function times data public func findRawSwiftFunctionTimes() -> Set<String> { let insertQueue = DispatchQueue(label: "swift_function_times_queue") var rawTexts = Set<String>() DispatchQueue.concurrentPerform(iterations: commands.count) { index in let (rawFunctionTimes, commandDesc) = commands[index] guard hasCompilerFlag(commandDesc) && rawFunctionTimes.isEmpty == false else { return } insertQueue.sync { _ = rawTexts.insert(rawFunctionTimes) } } return rawTexts } /// Parses the swift function times and store them internally public func parse() { let rawTexts = findRawSwiftFunctionTimes() functionsPerFile = rawTexts.compactMap { rawTime -> [FunctionTime]? in parseFunctionTimes(from: rawTime) }.joined().reduce([FilePath: [FunctionTime]]()) { (functionsPerFile, functionTime) -> [FilePath: [FunctionTime]] in var functionsPerFile = functionsPerFile if var functions = functionsPerFile[functionTime.file] { functions.append(functionTime) functionsPerFile[functionTime.file] = functions } else { functionsPerFile[functionTime.file] = [functionTime] } return functionsPerFile } } public func findFunctionTimesForFilePath(_ filePath: String) -> [FunctionTime]? { return functionsPerFile?[filePath] } public func hasFunctionTimes() -> Bool { guard let functionsPerFile = functionsPerFile else { return false } return functionsPerFile.isEmpty == false } public func parseFunctionTimes(from string: String) -> [FunctionTime]? { guard let regexp = functionRegexp else { return nil } let range = NSRange(location: 0, length: string.count) let matches = regexp.matches(in: string, options: .reportProgress, range: range) let functionTimes = matches.compactMap { result -> FunctionTime? in let durationString = string.substring(result.range(at: 1)) let file = string.substring(result.range(at: 2)) // some entries are invalid, we discarded them if file == SwiftFunctionTimesParser.invalidLoc { return nil } let name = string.substring(result.range(at: 3)) guard let (fileName, location) = parseFunctionLocation(file) else { return nil } // transform it to a file URL to match the one in IDELogSection.documentURL let fileURL = "file://\(fileName)" guard let (line, column) = parseLocation(location) else { return nil } let duration = parseFunctionCompileDuration(durationString) return FunctionTime(file: fileURL, durationMS: duration, startingLine: line, startingColumn: column, signature: name) } return functionTimes } private func hasCompilerFlag(_ text: String) -> Bool { text.range(of: Self.compilerFlag) != nil } private func parseFunctionLocation(_ function: String) -> (String, String)? { guard let colonIndex = function.firstIndex(of: ":") else { return nil } let functionName = function[..<colonIndex] let locationIndex = function.index(after: colonIndex) let location = function[locationIndex...] return (String(functionName), String(location)) } private func parseLocation(_ location: String) -> (Int, Int)? { guard let colonIndex = location.firstIndex(of: ":") else { return nil } let line = location[..<colonIndex] let columnIndex = location.index(after: colonIndex) let column = location[columnIndex...] guard let lineNumber = Int(String(line)), let columnNumber = Int(String(column)) else { return nil } return (lineNumber, columnNumber) } private func parseFunctionCompileDuration(_ durationString: String) -> Double { if let duration = Double(durationString) { return duration } return 0.0 } }
38.727811
90
0.63071
1e07447d1b0b1600a017400b28d75a23961c1474
2,244
// -------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // -------------------------------------------------------------------------- import AzureCore import Foundation // swiftlint:disable superfluous_disable_command // swiftlint:disable identifier_name // swiftlint:disable line_length /// User-configurable options for the `GetUnixTime` operation. public struct GetUnixTimeOptions: RequestOptions { /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs. /// Highly recommended for correlating client-side activites with requests received by the server. public let clientRequestId: String? /// A token used to make a best-effort attempt at canceling a request. public let cancellationToken: CancellationToken? /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`. public var dispatchQueue: DispatchQueue? /// A `PipelineContext` object to associate with the request. public var context: PipelineContext? /// Initialize a `GetUnixTimeOptions` structure. /// - Parameters: /// - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs. /// - cancellationToken: A token used to make a best-effort attempt at canceling a request. /// - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`. /// - context: A `PipelineContext` object to associate with the request. public init( clientRequestId: String? = nil, cancellationToken: CancellationToken? = nil, dispatchQueue: DispatchQueue? = nil, context: PipelineContext? = nil ) { self.clientRequestId = clientRequestId self.cancellationToken = cancellationToken self.dispatchQueue = dispatchQueue self.context = context } }
44
122
0.680927
014218b03d55edf7119e1d125c7e451fe0ed6d2a
1,244
import Foundation // References // https://github.com/R-a-dio/site/blob/develop/app/start/global.php#L125 // https://github.com/yattoz/Radio2/blob/master/app/src/main/java/io/r_a_d/radio2/ui/songs/request/CooldownCalculator.kt#L50 public struct SongDelayLogic { public init() {} public func isSongUnderCooldown(track: FavoriteTrack) -> Bool { if let requestCount = track.requestCount, let lastRequested = track.lastRequested?.timeIntervalSince1970, let lastPlayed = track.lastPlayed?.timeIntervalSince1970 { let now = Date().timeIntervalSince1970 let delay = self.delay(requestCount) let remainingCooldown = max(lastPlayed, lastRequested) + delay - now return remainingCooldown > 0.0 } return true } func delay(_ requestCount: Int) -> Double { let priority = min(requestCount, 30) var duration: Double = 0.0 if 0...7 ~= priority { duration = -11057 * Double(priority*priority) + 172954 * Double(priority) + 81720 } else { duration = 599955 * exp(0.0372 * Double(priority)) + 0.5 } return duration / 2 } }
32.736842
124
0.61254
7235b866d9b12609a2c480f9c275b89051780921
900
// // ActionFactory.swift // PlantsLife // // Created by Sonam Dhingra on 5/20/18. // Copyright © 2018 Sonam Dhingra. All rights reserved. // import Foundation import SceneKit struct ActionFactory { func moveAction(to newPos: SCNVector3, with duration: TimeInterval) -> SCNAction { return SCNAction.move(to: newPos, duration: duration) } func scaleOutAndIn(_ scaleByFactor: CGFloat, with duration: TimeInterval) -> SCNAction { let scaleLarger = SCNAction.scale(by: scaleByFactor, duration: duration) scaleLarger.timingMode = .easeOut let scaleSmaller = SCNAction.scale(by: -scaleByFactor, duration: duration) scaleSmaller.timingMode = .easeInEaseOut; let scaleSequence = SCNAction.sequence([scaleLarger, scaleSmaller]) let scaleLoop = SCNAction.repeatForever(scaleSequence) return scaleLoop } }
31.034483
92
0.695556
29eea0d64eaf2affc63282a5e4ba1165efafad53
422
// // SimpleCommandBus.swift // Application // // Created by Fiser on 7/5/18. // public class SimpleCommandBus : CommandBus { public private(set) var messageBus:MessageBus init(messageBus:MessageBus) { self.messageBus = messageBus } public func handle(command:Command) throws { do{ try self.messageBus.handle(message: command) } catch { } } }
17.583333
56
0.606635
692bc9fd46ae6e293ea2899e8bb6d26ac2f713b9
420
// // UIColorExtension.swift // Solo Space War // // Created by Tuncay Cansız on 13.12.2018. // Copyright © 2018 Tuncay Cansız. All rights reserved. // import SpriteKit extension UIColor { static func color(redValue: CGFloat, greenValue: CGFloat, blueValue: CGFloat, alpha: CGFloat) -> UIColor { return UIColor(red: redValue/255.0, green: greenValue/255.0, blue: blueValue/255.0, alpha: alpha) } }
26.25
110
0.697619
3ab02d4ba6cd5076905798e54a415c4b91b9a399
1,432
// // Quick_TipUITests.swift // Quick TipUITests // // Created by John Cheshire on 11/20/21. // import XCTest class Quick_TipUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.302326
182
0.656425
bf6dcdcbf89584b1bf5d4f3c9196e9901707bbe4
951
// // UserProfileServiceDao.swift // MVP // // Created by Ashish Awasthi on 26/12/19. // Copyright © 2019 Tanuja Awasthi. All rights reserved. // import Foundation import iOSCoreDataConnect import CoreData struct MyAccountServiceDao { static func listOfUsers() ->UserProfileList? { let arrayList = DataManager.convertToJSONArray(moArray: self.managedObjectList( )) let dict = ["data" : arrayList] guard let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) else{ return nil} guard let list = try? JSONDecoder().decode(UserProfileList.self, from: data) else{ return nil} return list } static func managedObjectList()->[NSManagedObject] { let issuesList = DataManager.fetchObjects(entity: UserProfileTable.self, predicate:nil, context: DataManager.mainContext) return issuesList } }
31.7
131
0.66877
14f4b31b57bfc2ac8275fd26cef7cf69868016a4
1,262
// // LSUserAccountModel.swift // LSVbo_Swift // // Created by WangBiao on 2016/12/4. // Copyright © 2016年 lsrain. All rights reserved. // import UIKit class LSUserAccountModel: NSObject, NSCoding { /// 用户授权的唯一票据 var access_token: String? /// 生命周期 单位是s var expires_in: TimeInterval = 0{ didSet{ /// 当前日期s + 过期秒数 = 将要过期的日期 expires_Date = Date().addingTimeInterval(expires_in) } } /// 授权用户的UID var uid: String? /// UserInfo /// 用户昵称 var screen_name: String? /// 用户头像地址(中图)50×50像素 var profile_image_url: String? /// 将授权有效日期转换等Date类型 var expires_Date: Date? override init() { super.init() } override var description: String{ let keys = [ "access_token", "expires_Date", "uid", "screen_name", "profile_image_url" ] return dictionaryWithValues(forKeys: keys).description } /// 使用`YYModel`实现归档/解档 /// 归档 func encode(with aCoder: NSCoder) { self.yy_modelEncode(with: aCoder) } /// 解档 required init?(coder aDecoder: NSCoder) { super.init() self.yy_modelInit(with: aDecoder) } }
20.688525
64
0.559429
9cf2f7d1ddc543b2489c279114253f6199f99e4e
2,418
// // VADay.swift // VACalendar // // Created by Anton Vodolazkyi on 20.02.18. // Copyright © 2018 Vodolazkyi. All rights reserved. // import UIKit @objc public enum VADayState: Int { case out, selected, available, unavailable, today, past } @objc public enum VADayShape: Int { case square, circle } public enum VADaySupplementary: Hashable { // 3 dot max case bottomDots([UIColor]) public var hashValue: Int { switch self { case .bottomDots: return 1 } } public func hash(into hasher: inout Hasher) { hasher.combine(1) } public static func ==(lhs: VADaySupplementary, rhs: VADaySupplementary) -> Bool { return lhs.hashValue == rhs.hashValue } } class VADay { let date: Date var stateChanged: ((VADayState) -> Void)? var supplementariesDidUpdate: (() -> Void)? let calendar: Calendar var reverseSelectionState: VADayState { return state == .available ? .selected : .available } var isSelected: Bool { return state == .selected } var isSelectable: Bool { return state == .selected || state == .available } var dayInMonth: Bool { return state != .out } var state: VADayState { didSet { stateChanged?(state) } } var supplementaries = Set<VADaySupplementary>() { didSet { supplementariesDidUpdate?() } } init(date: Date, state: VADayState, calendar: Calendar) { self.date = date self.state = state self.calendar = calendar } func dateInDay(_ date: Date) -> Bool { return calendar.isDate(date, equalTo: self.date, toGranularity: .day) } func setSelectionState(_ state: VADayState) { guard state == reverseSelectionState && isSelectable else { return } self.state = state } func setState(_ state: VADayState) { self.state = state } func set(_ supplementaries: [VADaySupplementary]) { self.supplementaries = Set(supplementaries) } } extension VADay: Comparable { static func <(lhs: VADay, rhs: VADay) -> Bool { return !lhs.dateInDay(rhs.date) } static func ==(lhs: VADay, rhs: VADay) -> Bool { return lhs.dateInDay(rhs.date) } }
21.026087
85
0.579818
7aa09ca89c1c324c136ef85d3e10759af1a242ca
2,254
// // SoundTableViewCell.swift // ChelseabandSDK_Example // // Created by Vladyslav Shepitko on 03.12.2020. // Copyright © 2020 Sonerim. All rights reserved. // import UIKit import SnapKit import RxSwift import ChelseabandSDK class SoundTableViewCell: UITableViewCell { private lazy var title: UILabel = { let view = UILabel() view.textColor = .black return view }() private lazy var dropdownPicker: DropdownPicker<Sound> = { let view = DropdownPicker<Sound>(values: Sound.allCases) return view }() private lazy var iconImageView: UIImageView = { let view = UIImageView() view.backgroundColor = .white return view }() var disposeBag = DisposeBag() var selectionObservable: Observable<Sound> { return dropdownPicker.selectedObservable } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none contentView.backgroundColor = .white setupLayout() } private func setupLayout() { contentView.addSubview(iconImageView) contentView.addSubview(dropdownPicker) contentView.addSubview(title) iconImageView.snp.makeConstraints { $0.height.width.equalTo(30) $0.top.equalTo(contentView.snp.top).inset(10) $0.bottom.equalTo(contentView.snp.bottom).inset(10) $0.leading.equalTo(contentView.snp.leading).offset(10) } title.snp.makeConstraints { $0.leading.equalTo(iconImageView.snp.trailing).offset(10) $0.centerY.equalTo(iconImageView.snp.centerY) } dropdownPicker.snp.makeConstraints { $0.trailing.equalTo(contentView.snp.trailing).inset(10) $0.centerY.equalTo(iconImageView .snp.centerY) } } required init?(coder: NSCoder) { return nil } override func prepareForReuse() { disposeBag = DisposeBag() } func bind(viewModel: SoundRowViewModel) { title.text = viewModel.title iconImageView.image = viewModel.image dropdownPicker.set(value: viewModel.sound) } }
26.209302
79
0.647294
dd9ce769dbf7415d714371862e27b087aaf6ae1b
1,462
// MIT license. Copyright (c) 2019 SwiftyFORM. All rights reserved. import UIKit import SwiftyFORM class StaticTextAndAttributedTextViewController: FormViewController { override func populate(_ builder: FormBuilder) { builder.navigationTitle = "Text" builder.toolbarMode = .none builder += SectionHeaderTitleFormItem(title: "Static Text") builder += StaticTextFormItem().title("Title 0").value("Value 0") builder += StaticTextFormItem().title("Title 1").value("Value 1") builder += StaticTextFormItem().title("Title 2").value("Value 2") builder += SectionHeaderTitleFormItem(title: "Attributed Text") builder += AttributedTextFormItem().title("Title 0").value("Value 0") builder += AttributedTextFormItem() .title("Title 1", [NSAttributedString.Key.foregroundColor.rawValue: UIColor.gray as AnyObject]) .value("Value 1", [ NSAttributedString.Key.backgroundColor.rawValue: UIColor.black as AnyObject, NSAttributedString.Key.foregroundColor.rawValue: UIColor.white as AnyObject ]) builder += AttributedTextFormItem() .title("Orange 🍊", [ NSAttributedString.Key.foregroundColor.rawValue: UIColor.orange as AnyObject, NSAttributedString.Key.font.rawValue: UIFont.boldSystemFont(ofSize: 24) as AnyObject, NSAttributedString.Key.underlineStyle.rawValue: NSUnderlineStyle.single.rawValue as AnyObject ]) .value("Heart ❤️", [NSAttributedString.Key.foregroundColor.rawValue: UIColor.red as AnyObject]) } }
45.6875
98
0.759918
fbf13e22329e4a2f5c7a77021bd29340c1c564fe
1,033
//Created on 2019/6/24 by LCD:https://github.com/liucaide . /***** 模块文档 ***** * */ import Foundation import CaamDau public protocol PGPayProtocol { associatedtype DataSource static var scheme:String {get set} static func handleOpen(_ url:URL) static func pay(_ order: DataSource, completion:((PGPay.Status)->Void)?) } public class PGPay { private init(){} public static let shared = PGPay() open var schemes:[String:String] = [:] open var completion:((PGPay.Status)->Void)? } public extension PGPay { enum Style { case ali case wx case union } enum Status { case succeed case dealing case cancel case error(_ code:Int, _ msg:String) case signerError case none } enum Notic:String { case callBack = "callBack" } } extension PGPay.Notic: CaamDauNotificationProtocol { public var name: Notification.Name { return Notification.Name("PGPay." + self.rawValue) } }
19.490566
76
0.617619
67f84117d465297d4df5d1e9db24c888b5215b08
2,026
// // File.swift // // // Created by Andreas Bauer on 30.05.21. // import Apodini private struct TestStruct: Handler { func handle() -> String { "Hello World!" } var metadata: Metadata { TestVoidHandlerMetadata() // error: Argument type 'AnyWebServiceMetadata' does not conform to expected type 'AnyHandlerMetadata' TestVoidWebServiceMetadata() // error: Argument type 'AnyComponentOnlyMetadata' does not conform to expected type 'AnyHandlerMetadata' TestVoidComponentOnlyMetadata() TestVoidComponentMetadata() // error: No exact matches in call to static method 'buildExpression' TestVoidContentMetadata() Block { TestVoidHandlerMetadata() } StandardHandlerMetadataBlock { TestVoidHandlerMetadata() // error: Argument type 'AnyWebServiceMetadata' does not conform to expected type 'AnyHandlerMetadata' TestVoidWebServiceMetadata() // error: Argument type 'AnyComponentOnlyMetadata' does not conform to expected type 'AnyHandlerMetadata' TestVoidComponentOnlyMetadata() TestVoidComponentMetadata() // error: No exact matches in call to static method 'buildExpression' TestVoidContentMetadata() } // error: Argument type 'AnyWebServiceMetadata' does not conform to expected type 'AnyHandlerMetadata' StandardWebServiceMetadataBlock { TestVoidWebServiceMetadata() } // error: Argument type 'AnyComponentOnlyMetadata' does not conform to expected type 'AnyHandlerMetadata' StandardComponentOnlyMetadataBlock { TestVoidComponentOnlyMetadata() } StandardComponentMetadataBlock { TestVoidComponentMetadata() } // error: No exact matches in call to static method 'buildExpression' StandardContentMetadataBlock { TestVoidContentMetadata() } } }
29.794118
117
0.658934
5d51b4c9cbbc8676bd95f1df5374727bc206b287
3,471
import Foundation import DLJSONAPI /// Controller to load all available resources. public class LoadAllResourcesController <ResourceType: Resource> { public typealias LoadPageCompletionBlock = (_ result: PageResult) -> Void public typealias LoadPageBlock = ( _ pagination: RequestPagination, _ completion: @escaping LoadPageCompletionBlock ) -> Void public typealias LoadCompletionBlock = ( _ result: Result, _ data: [ResourceType] ) -> Void // MARK: - Public properties public private(set) var data: [ResourceType] = [] public private(set) var error: Error? // MARK: - Private properties private let requestPagination: RequestPagination // MARK: - public init( requestPagination: RequestPagination ) { self.requestPagination = requestPagination } // MARK: - Public public func loadResources( loadPage: @escaping LoadPageBlock, completion: @escaping LoadCompletionBlock ) { self.error = nil self.data = [] self.requestPagination.resetToFirstPage() loadPage(self.requestPagination, { [weak self] (result) in guard let sSelf = self else { return } switch result { case .failed(let error): sSelf.error = error sSelf.completed(completion: completion) case .succeeded(let data): sSelf.data = data if sSelf.requestPagination.hasNextPage(resultsCount: data.count) { sSelf.loadResourcesPage( loadPage: loadPage, completion: completion ) } else { sSelf.completed(completion: completion) } } }) } // MARK: - Private private func loadResourcesPage( loadPage: @escaping LoadPageBlock, completion: @escaping LoadCompletionBlock ) { loadPage(self.requestPagination, { [weak self] (result) in guard let sSelf = self else { return } switch result { case .failed(let error): sSelf.error = error sSelf.completed(completion: completion) case .succeeded(let data): sSelf.data.appendUniques(contentsOf: data) if sSelf.requestPagination.hasNextPage(resultsCount: data.count) { sSelf.loadResourcesPage( loadPage: loadPage, completion: completion ) } else { sSelf.completed(completion: completion) } } }) } private func completed(completion: LoadCompletionBlock) { if let error = self.error { completion(.failed(error), self.data) } else { completion(.succeded, self.data) } } } extension LoadAllResourcesController { public enum Result { case failed(Error) case succeded } public enum PageResult { case failed(Error) case succeeded([ResourceType]) } }
27.547619
82
0.521464
381ecdc7941e05d64a0d77ed173eb98f0743ff0a
630
// // EditToDoPresenter.swift // ToDo // // Created by Kemal Sanlı on 25.11.2021. // import Foundation class EditToDoPresenter{ var editToDoInteractor: PresenterToInteractorEditToDoProtocol? var editToDoView: PresenterToViewEditToDoProtocol? } //MARK: View To Presenter Protocol Stubs extension EditToDoPresenter:ViewToPresenterEditToDoProtocol{ func editToDo(_ todo: ToDo) { editToDoInteractor?.editToDo(todo) } } //MARK: Interactor To Presenter Protocol Stubs extension EditToDoPresenter:InteractorToPresenterEditToDoProtocol{ func navigate() { editToDoView?.navigate() } }
20.322581
66
0.746032
46c83bbb2b331a622ea8f7721a1a81e95f9734a6
897
// // DOUYUTests.swift // DOUYUTests // // Created by Michael Wang on 2020/2/27. // Copyright © 2020 Michael Wang. All rights reserved. // import XCTest @testable import DOUYU class DOUYUTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.628571
111
0.651059
eb423e90093fb57af683792252a9a219ea291580
1,617
// // ProductTableViewCell.swift // MilkshakrKit // // Created by Guilherme Rambo on 10/06/18. // Copyright © 2018 Guilherme Rambo. All rights reserved. // import UIKit public final class ProductTableViewCell: UITableViewCell { private lazy var productView = ProductView(frame: .zero) public var viewModel: ProductViewModel? { get { return productView.viewModel } set { productView.viewModel = newValue } } public var didReceiveTap: (() -> Void)? { get { return productView.didReceiveTap } set { productView.didReceiveTap = newValue } } public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) buildUI() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) buildUI() } private func buildUI() { productView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(productView) productView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Metrics.padding).isActive = true productView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -Metrics.padding).isActive = true productView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: Metrics.padding).isActive = true productView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -Metrics.padding).isActive = true } }
28.875
126
0.675943
e44a74c62f2c4fb09b40935e94d750cc0bd6f456
5,646
import UIKit import Photos protocol ImageStackViewDelegate: class { func imageStackViewDidPress() } class ImageStackView: UIView { struct Dimensions { static let imageSize: CGFloat = 58 } weak var delegate: ImageStackViewDelegate? lazy var activityView: UIActivityIndicatorView = { let view = UIActivityIndicatorView() view.alpha = 0.0 return view }() var views: [UIImageView] = { var array = [UIImageView]() for _ in 0...3 { let view = UIImageView() view.layer.cornerRadius = 3 view.layer.borderColor = UIColor.white.cgColor view.layer.borderWidth = 1 view.contentMode = .scaleAspectFill view.clipsToBounds = true view.alpha = 0 array.append(view) } return array }() // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) subscribe() views.forEach { addSubview($0) } addSubview(activityView) views.first?.alpha = 1 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Helpers func subscribe() { NotificationCenter.default.addObserver(self, selector: #selector(imageDidPush(_:)), name: NSNotification.Name(rawValue: ImageStack.Notifications.imageDidPush), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(imageStackDidChangeContent(_:)), name: NSNotification.Name(rawValue: ImageStack.Notifications.imageDidDrop), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(imageStackDidChangeContent(_:)), name: NSNotification.Name(rawValue: ImageStack.Notifications.stackDidReload), object: nil) } override func layoutSubviews() { let step: CGFloat = -3.0 let scale: CGFloat = 0.8 let viewSize = CGSize(width: frame.width * scale, height: frame.height * scale) let offset = -step * CGFloat(views.count) var origin = CGPoint(x: offset, y: offset) for view in views { origin.x += step origin.y += step view.frame = CGRect(origin: origin, size: viewSize) } } func startLoader() { if let firstVisibleView = views.filter({ $0.alpha == 1.0 }).last { activityView.frame.origin.x = firstVisibleView.center.x activityView.frame.origin.y = firstVisibleView.center.y } activityView.startAnimating() UIView.animate(withDuration: 0.3, animations: { self.activityView.alpha = 1.0 }) } } extension ImageStackView { @objc func imageDidPush(_ notification: Notification) { let emptyView = views.filter { $0.image == nil }.first if let emptyView = emptyView { animateImageView(emptyView) } if let sender = notification.object as? ImageStack { renderViews(sender.assets) activityView.stopAnimating() } } @objc func imageStackDidChangeContent(_ notification: Notification) { if let sender = notification.object as? ImageStack { renderViews(sender.assets) activityView.stopAnimating() } } func renderViews(_ assets: [PHAsset]) { if let firstView = views.first, assets.isEmpty { views.forEach { $0.image = nil $0.alpha = 0 } firstView.alpha = 1 return } let photos = Array(assets.suffix(4)) for (index, view) in views.enumerated() { if index <= photos.count - 1 { AssetManager.resolveAsset(photos[index], size: CGSize(width: Dimensions.imageSize, height: Dimensions.imageSize)) { image in view.image = image } view.alpha = 1 } else { view.image = nil view.alpha = 0 } if index == photos.count { UIView.animate(withDuration: 0.3, animations: { self.activityView.frame.origin = CGPoint(x: view.center.x + 3, y: view.center.x + 3) }) } } } fileprivate func animateImageView(_ imageView: UIImageView) { imageView.transform = CGAffineTransform(scaleX: 0, y: 0) UIView.animate(withDuration: 0.3, animations: { imageView.transform = CGAffineTransform(scaleX: 1.05, y: 1.05) }, completion: { _ in UIView.animate(withDuration: 0.2, animations: { () -> Void in self.activityView.alpha = 0.0 imageView.transform = CGAffineTransform.identity }, completion: { _ in self.activityView.stopAnimating() }) }) } }
32.262857
140
0.518951
16aefdb259ae99ab762e1acdb8dc2a53d8ad9f67
760
import UIKit import XCTest import FerrisMenu class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.333333
111
0.605263