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
09640572afbd48dcbd9487dbba78d508795cd6de
592
// // CopyDefines.swift // Saturdays // // Created by Said Ozcan on 25/06/2017. // Copyright © 2017 Said Ozcan. All rights reserved. // import Foundation struct CopyDefines { let saturdaysTitle = NSLocalizedString("SATURDAYS", comment: "") let tracksTitle = NSLocalizedString("Tracks", comment: "") let venuesTitle = NSLocalizedString("Venues", comment: "") let postsTitle = NSLocalizedString("Posts", comment: "") let openIssue = NSLocalizedString("Open Issue", comment: "") let dismiss = NSLocalizedString("Dismiss", comment: "") }
31.157895
70
0.660473
acc998cc6ae5d258f93719ce82710370e2dce5c3
912
// // DesignPatternTests.swift // DesignPatternTests // // Created by vchan on 2021/2/20. // import XCTest @testable import DesignPattern class DesignPatternTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.823529
111
0.669956
46db0c577035373edb8480c7813b22675a6123ef
2,513
// // GenerateThumbnailFileMessageUseCase.swift // GenerateThumbnailForFileOpenChannel // // Created by Yogesh Veeraraj on 03.05.22. // Copyright © 2022 Sendbird. All rights reserved. // import Foundation import SendbirdChatSDK class GenerateThumbnailFileMessageUseCase { public struct MediaFile { let data: Data let name: String let mimeType: String public init(data: Data, name: String, mimeType: String) { self.data = data self.name = name self.mimeType = mimeType } } private let channel: OpenChannel private var cachedDatasForResending: [String: Data] = [:] public init(channel: OpenChannel) { self.channel = channel } open func sendFile(_ mediaFile: MediaFile, completion: @escaping (Result<BaseMessage, SBError>) -> Void) -> FileMessage? { let fileMessageParams = FileMessageCreateParams(file: mediaFile.data) fileMessageParams.fileName = mediaFile.name fileMessageParams.fileSize = UInt(mediaFile.data.count) fileMessageParams.mimeType = mediaFile.mimeType fileMessageParams.thumbnailSizes = [ .make(maxWidth: 100, maxHeight: 100), .make(maxWidth: 320.0, maxHeight: 320.0) ] let fileMessage = channel.sendFileMessage(params: fileMessageParams) { [weak self] message, error in if let error = error { completion(.failure(error)) return } guard let message = message else { return } self?.cachedDatasForResending.removeValue(forKey: message.requestID) completion(.success(message)) } if let requestID = fileMessage?.requestID { cachedDatasForResending[requestID] = mediaFile.data } return fileMessage } open func resendMessage(_ message: FileMessage, completion: @escaping (Result<BaseMessage, SBError>) -> Void) { guard let binaryData = cachedDatasForResending[message.requestID] else { return } channel.resendFileMessage(message, binaryData: binaryData) { message, error in if let error = error { completion(.failure(error)) return } guard let message = message else { return } completion(.success(message)) } } }
31.024691
126
0.598886
fb40aba5b41a6a62edc82afdcdc13548313173e6
4,318
// // TOTP.swift // OTPKit // // Created by Tim Gymnich on 7/17/19. // import Foundation public final class TOTP: OTP { public static let typeString = "totp" public let secret: Data /// The period defines a period that a TOTP code will be valid for, in seconds. public let period: UInt64 public let algorithm: Algorithm public let digits: Int public var counter : UInt64 { return UInt64(Date().timeIntervalSince1970) / period } public var urlQueryItems: [URLQueryItem] { let items: [URLQueryItem] = [ URLQueryItem(name: "secret", value: secret.base32EncodedString.lowercased()), URLQueryItem(name: "algorithm", value: algorithm.string), URLQueryItem(name: "period", value: String(period)), URLQueryItem(name: "digits", value: String(digits)), ] return items } @available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) private lazy var timer: Timer = { let timeForNextPeriod = Date(timeIntervalSince1970: TimeInterval((counter + 1) * period)) let timer = Timer(fire: timeForNextPeriod, interval: TimeInterval(period), repeats: true) { [weak self] _ in guard let self = self else { return } let timeForNextPeriod = Date(timeIntervalSince1970: TimeInterval((self.counter + 1) * self.period)) let timeRemaining = timeForNextPeriod.timeIntervalSince(Date()) NotificationCenter.default.post(name: .didGenerateNewOTPCode, object: self, userInfo: [UserInfoKeys.code : self.code(), UserInfoKeys.timeRemaining: timeRemaining]) } timer.tolerance = 1 return timer }() public init(algorithm: Algorithm? = nil, secret: Data, digits: Int? = nil, period: UInt64? = nil) { self.secret = secret self.period = period ?? 30 self.digits = digits ?? 6 self.algorithm = algorithm ?? .sha1 if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { RunLoop.main.add(timer, forMode: .default) timer.fire() } } public required convenience init(from url: URL) throws { print(url) guard url.scheme == "otpauth" else { throw URLDecodingError.invalidURLScheme(url.scheme) } guard url.host == "totp" else { throw URLDecodingError.invalidOTPType(url.host) } guard let query = url.queryParameters else { throw URLDecodingError.invalidURLQueryParamters } var algorithm: Algorithm? if let algorithmString = query["algorithm"] { guard let algo = Algorithm(from: algorithmString) else { throw URLDecodingError.invalidAlgorithm(algorithmString) } algorithm = algo } guard let secret = query["secret"]?.base32DecodedData, secret.count != 0 else { throw URLDecodingError.invalidSecret } var digits: Int? if let digitsString = query["digits"], let value = Int(digitsString), value >= 6 { digits = value } var period: UInt64? if let periodString = query["period"] { period = UInt64(periodString) } self.init(algorithm: algorithm, secret: secret, digits: digits, period: period) } public func code() -> String { return code(for: Date()) } public func code(for date: Date) -> String { let count = UInt64(date.timeIntervalSince1970) / period return code(for: count) } deinit { if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) { timer.invalidate() } } // MARK: Equatable public static func ==(lhs: TOTP, rhs: TOTP) -> Bool { return lhs.secret == rhs.secret && lhs.algorithm == rhs.algorithm && lhs.digits == rhs.digits && lhs.period == rhs.period } // MARK: Hashable public func hash(into hasher: inout Hasher) { hasher.combine(secret) hasher.combine(algorithm) hasher.combine(digits) hasher.combine(period) } } public extension TOTP { enum UserInfoKeys: Hashable { case code case timeRemaining } } public extension Notification.Name { static let didGenerateNewOTPCode = Notification.Name("didGenerateNewOTPCode") }
34.269841
179
0.6195
61752d1765bdd527b7a34abf3bc5d2b2816c8b24
1,104
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation final class ThreadLocalStorage<T: AnyObject> { private let key: NSString init (key: String) { self.key = NSString(string: key) } var Data: T? { get { let dict = Thread.current.threadDictionary #if APPLE_FRAMEWORKS_AVAILABLE return dict.object(forKey: key) as? T #else if let index = dict.indexForKey(key) { return dict[index].1 as? T } return nil #endif } set (value) { Thread.current.threadDictionary[key] = value } } }
28.307692
80
0.533514
762165db5d9c0b93db2951b3d3a2dced6ff5624b
3,233
// // main.swift // AdventOfCodeDay5 // // Created by Jeff Kelley on 12/5/16. // Copyright © 2016 Jeff Kelley. All rights reserved. // import Foundation extension String { var md5: String { let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1) var digest = Array<UInt8>(repeating:0, count:Int(CC_MD5_DIGEST_LENGTH)) CC_MD5_Init(context) CC_MD5_Update(context, self, CC_LONG(utf8.count)) CC_MD5_Final(&digest, context) context.deallocate(capacity: 1) return digest .map { String(format:"%02x", $0) } .joined() } var startsWithFiveZeroes: Bool { return hasPrefix("00000") } var part1Password: String { var index = 0 var password = String() while password.characters.count < 8 { index += 1 let md5 = (self + String(index)).md5 if md5.startsWithFiveZeroes { let sixthIndex = md5.characters.index(md5.characters.startIndex, offsetBy: 5) let sixthCharacter = md5.characters[sixthIndex] password.append(sixthCharacter) } } return password } var part2Password: String { var index = 0 var password = "________" while password.contains("_") { index += 1 let md5 = (self + String(index)).md5 if md5.startsWithFiveZeroes { let sixthIndex = md5.characters.index(md5.characters.startIndex, offsetBy: 5) let sixthCharacter = md5.characters[sixthIndex] if let digit = Int(String(sixthCharacter)) { guard digit < 8 else { continue } let seventh = md5.characters.index(md5.characters.startIndex, offsetBy: 6) let seventhCharacter = md5.characters[seventh] let index = password.characters.index(password.characters.startIndex, offsetBy: digit) if password.characters[index] == "_" { password.remove(at: index) password.insert(seventhCharacter, at: index) print(password) } } } } return password } } // Part 1 print("Starting at \(Date())") print("abc") print("Password of abc: \("abc".part1Password)") print("cxdnnyjw") print("Password of cxdnnyjw: \("cxdnnyjw".part1Password)") // Part 2 print("abc") print("Password of abc: \("abc".part2Password)") print("cxdnnyjw") print("Password of cxdnnyjw: \("cxdnnyjw".part2Password)") print("Finishing at \(Date())")
28.359649
89
0.474173
d717327cd15f73fdaa5d9316c3674d1e6a3ef43a
868
// // ViewController.swift // ScrollingNavbarDemo // // Created by Andrea Mazzini on 24/07/15. // Copyright (c) 2015 Fancy Pixel. All rights reserved. // import UIKit import AMScrollingNavbar class ViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() title = "Sampler" tableView.tableFooterView = UIView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if #available(iOS 13.0, *) { navigationController?.navigationBar.standardAppearance.backgroundColor = UIColor(red:0.1, green:0.1, blue:0.1, alpha:1) navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance } else { navigationController?.navigationBar.barTintColor = UIColor(red:0.1, green:0.1, blue:0.1, alpha:1) } } }
24.8
125
0.723502
79e5e0128cb920d8355e493eca36f38d981b6958
2,063
// // KMNetwork.swift // KMTIMSDK_Example // // Created by Ed on 2020/3/2. // Copyright © 2020 zhenlove. All rights reserved. // import Foundation import Alamofire @objc(KMNetwork) open class KMNetwork: NSObject { public static var sessionManager: SessionManager = { let tSessionManager = SessionManager.default tSessionManager.adapter = KMAdapter() tSessionManager.retrier = KMRetrier() return tSessionManager }() } extension KMNetwork { @objc public static func request(url:String, method:String, parameters:[String: Any]?, isHttpBody:Bool, callBack:@escaping (Any?,Error?)-> Void) -> Void { KMNetwork .sessionManager .request(url, method: HTTPMethod(rawValue: method) ?? .get, parameters: parameters, encoding: isHttpBody ? JSONEncoding.default : URLEncoding.default) .validateDataStatus(statusCode: [5,-5]) .responseJSON { (dataResponse) in callBack(dataResponse.result.value,dataResponse.result.error) } } @objc public static func upload(url:String, imageData: Data, callBack:@escaping (Any?,Error?)-> Void) -> Void { KMNetwork .sessionManager .upload(multipartFormData: { (data) in data.append(imageData, withName: String.generateRandomString(5) + Date.timeIntervalBetween1970AndReferenceDate.description, mimeType: "image/jpeg") }, to: url) { (result) in switch result { case .success(let upload,_,_): upload.responseJSON { (dataResponse) in callBack(dataResponse.result.value,nil) } case .failure(let encodingError): callBack(nil,encodingError) } } } }
36.192982
163
0.545322
6253652cfb3d4a0c2abd32d3fb159a31e649839b
166
// // enums.swift // FileManager-Swift // // Created by Algorithm on 7/16/18. // import Foundation public enum CellType { case title case titleAndSize }
11.857143
36
0.662651
ac72dada1d71343387bfbaea52234cfc238dc4b4
5,801
// // UComicHead.swift // F-U17 // // Created by ZhouRui on 2022/2/15. // import UIKit class UComicHeadCCell: UBaseCollectionViewCell { lazy var titleLabel: UILabel = { let tl = UILabel() tl.textColor = .white tl.textAlignment = .center tl.font = .systemFont(ofSize: 14) return tl }() override func configUI() { layer.cornerRadius = 3 layer.borderColor = UIColor.white.cgColor layer.borderWidth = 1 contentView.addSubview(titleLabel) titleLabel.snp.makeConstraints { $0.edges.equalToSuperview() } } } class UComicHead: UIView { private lazy var bgView: UIImageView = { let bv = UIImageView() bv.isUserInteractionEnabled = true bv.contentMode = .scaleAspectFill #warning ("TODO:") return bv }() private lazy var coverView: UIImageView = { let cv = UIImageView() cv.contentMode = .scaleAspectFill cv.layer.cornerRadius = 3 cv.layer.borderWidth = 1 cv.layer.borderColor = UIColor.white.cgColor return cv }() private lazy var nameLabel: UILabel = { let nl = UILabel() nl.textColor = .white nl.font = .systemFont(ofSize: 16) return nl }() private lazy var authorLabel: UILabel = { let al = UILabel() al.textColor = .white al.font = .systemFont(ofSize: 13) return al }() private lazy var totalLabel: UILabel = { let tl = UILabel() tl.textColor = UIColor.white tl.font = UIFont.systemFont(ofSize: 13) return tl }() private lazy var themeView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 5 layout.itemSize = CGSize(width: 40, height: 20) layout.scrollDirection = .horizontal let tv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) tv.backgroundColor = UIColor.clear tv.dataSource = self tv.showsHorizontalScrollIndicator = false tv.register(cellType: UComicHeadCCell.self) return tv }() private var themes: [String]? override init(frame: CGRect) { super.init(frame: frame) configUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configUI() { addSubview(bgView) bgView.snp.makeConstraints { $0.edges.equalToSuperview() } bgView.addSubview(coverView) coverView.snp.makeConstraints { $0.left.bottom.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 20, bottom: 20, right: 0)) $0.width.equalTo(90) $0.height.equalTo(120) } bgView.addSubview(nameLabel) nameLabel.snp.makeConstraints { $0.left.equalTo(coverView.snp.right).offset(20) $0.right.greaterThanOrEqualToSuperview().offset(-20) $0.top.equalTo(coverView) $0.height.equalTo(20) } bgView.addSubview(authorLabel) authorLabel.snp.makeConstraints { $0.left.height.equalTo(nameLabel) $0.right.greaterThanOrEqualToSuperview().offset(-20) $0.top.equalTo(nameLabel.snp.bottom).offset(5) } bgView.addSubview(totalLabel) totalLabel.snp.makeConstraints { $0.left.height.equalTo(authorLabel) $0.right.greaterThanOrEqualToSuperview().offset(-20) $0.top.equalTo(authorLabel.snp.bottom).offset(10) } bgView.addSubview(themeView) themeView.snp.makeConstraints { $0.left.equalTo(totalLabel) $0.height.equalTo(30) $0.right.greaterThanOrEqualToSuperview().offset(-20) $0.bottom.equalTo(coverView) } } var detailStatic: ComicStaticModel? { didSet { guard let detailStatic = detailStatic else { return } bgView.kf.setImage(urlString: detailStatic.cover, placeholder: UIImage(named: "normal_placeholder_v")) coverView.kf.setImage(urlString: detailStatic.cover, placeholder: UIImage(named: "normal_placeholder_v")) nameLabel.text = detailStatic.name authorLabel.text = detailStatic.author?.name themes = detailStatic.theme_ids themeView.reloadData() } } var detailRealtime: ComicRealtimeModel? { didSet { guard let detailRealtime = detailRealtime else { return } let text = NSMutableAttributedString(string: "点击 收藏") text.insert(NSAttributedString(string: "\(detailRealtime.click_total)", attributes: [NSAttributedString.Key.foregroundColor: UIColor.orange, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)]), at: 2) text.append(NSAttributedString(string: "\(detailRealtime.favorite_total ?? "0")", attributes: [NSAttributedString.Key.foregroundColor: UIColor.orange, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)])) totalLabel.attributedText = text } } } extension UComicHead: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return themes?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: UComicHeadCCell.self) cell.titleLabel.text = themes?[indexPath.row] return cell } }
32.960227
224
0.615928
0e4e7bee692a6412b4215ab99bc79a32a917d756
1,362
// // WCTimeZone.swift // WorldClock // // Created by Kartik Venugopal on 16/03/22. // import Foundation struct WCTimeZone: Codable, CustomStringConvertible { internal init(index: Int, location: String, offsetHours: Int, offsetMins: Int, isDST: Bool) { self.index = index self.location = location self.offsetHours = offsetHours self.offsetMins = offsetMins self.isDST = isDST } var index: Int let location: String var humanReadableLocation: String { let split = location.split(separator: "/") return (split.count >= 2 ? String(split.last!) : location).replacingOccurrences(of: "_", with: " ") } let offsetHours: Int let offsetMins: Int let isDST: Bool lazy var offsetAsSeconds: Int = { let isNegative = offsetHours < 0 let offset = abs(offsetHours) * 3600 + offsetMins * 60 return offset * (isNegative ? -1 : 1) }() lazy var timeZone: TimeZone = TimeZone.init(secondsFromGMT: offsetAsSeconds)! var description: String { "\(location) - \(humanReadableOffset)\(isDST ? " (DST)" : "")" } var humanReadableOffset: String { "GMT\(offsetHours >= 0 ? "+" : "")\(offsetHours):\(String(format: "%02d", offsetMins))" } }
25.222222
107
0.585903
89cc1ba9d9f993ffed37528971d5f01eb4d14b85
956
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package(name: "ASCollectionView", platforms: [.iOS(.v11)], products: [// Products define the executables and libraries produced by a package, and make them visible to other packages. .library(name: "ASCollectionView", targets: ["ASCollectionView"]), .library(name: "ASCollectionViewDynamic", type: .dynamic, targets: ["ASCollectionView"]), ], dependencies: [ .package(url: "https://github.com/ZevEisenberg/DifferenceKit", .branch("master")) ], targets: [ .target(name: "ASCollectionView", dependencies: ["DifferenceKit"]), ] )
45.52381
145
0.544979
5033eccb341d98267602a68e7d8593aceea3f9d7
743
// // String+Format.swift // Grapqhl Codegen // // Created by Romy Cheah on 9/9/21. // import Foundation import SwiftFormat public extension String { /// Formats the given Swift source code. func format() throws -> String { let trimmed = trimmingCharacters( in: CharacterSet.newlines.union(.whitespaces) ) // TODO: Read configurtion from .swiftformat var formatOptions = FormatOptions.default formatOptions.indent = " " formatOptions.trailingCommas = false formatOptions.shortOptionals = .exceptProperties do { let formatted = try SwiftFormat.format(trimmed, options: formatOptions) return formatted } catch { print("\(error)\n\(trimmed)") throw error } } }
21.852941
77
0.674293
d7a0254b53ca8051a669c1708dfb845f7587d337
1,968
// // CMImageElement.swift // ChattingManage // // Created by sunshine.lee on 2019/5/15. // Copyright © 2019 YCM. All rights reserved. // 纯图片布局 import UIKit import Kingfisher class CMImageElement: CMBaseElement { var imageUrl:String? { didSet { setupImageViewImage(imageUrl: imageUrl) } } private lazy var imageView:UIImageView = { let view = UIImageView() view.contentMode = .scaleToFill return view }() //MARK : 构造方法 override init(frame: CGRect) { super.init(frame: frame) setupBannerCell() layoutConstraint() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// MARK: 私有方法 private func setupBannerCell() { addSubview(imageView) } private func layoutConstraint() { imageView.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets.zero) } } private func setupImageViewImage(imageUrl:String?) { imageView.kf.setImage(with: URL(string: imageUrl ?? ""), placeholder: UIImage.imageWithColor(color: spaceColor), options: [.fromMemoryCacheOrRefresh,.transition(.fade(1))], progressBlock: nil, completionHandler: nil) } override class func cell(collectView:UICollectionView,indexPath:IndexPath) -> CMImageElement? { return collectView.dequeueReusableCell(withReuseIdentifier: identifier(), for: indexPath) as? CMImageElement } class func element(collectView:UICollectionView,indexPath:IndexPath,model:CMElementModel) -> CMImageElement { let element = cell(collectView: collectView, indexPath: indexPath) element?.setupImageViewImage(imageUrl: model.imageUrl) return element ?? CMImageElement() } override class func identifier() -> String{ return "CMImageElement.cell" } }
29.373134
224
0.651423
09b0fa096f069a2f07e3fbcb0a70aaf2ba67bd09
1,454
// // FinanceKit // Copyright © 2021 Christian Mitteldorf. All rights reserved. // MIT license, see LICENSE file for details. // import Foundation /// A Change keeps track of the numerical and percent changes between the cost and current price. public struct Change: Codable, Equatable, Hashable { public static let zero = Change(cost: 0, currentValue: 0) public let amount: Amount public let percentage: Percentage public var percentageText: String? { percentage.formattedString } public init(percentageValue: Percentage) { self.amount = percentageValue.decimal.isPositive ? 1.0 : -1.0 self.percentage = percentageValue } public init(cost: Amount, currentValue: Amount) { guard !cost.isZero else { self.amount = 0 self.percentage = .zero return } self.amount = (currentValue - cost) if amount.isPositive { self.percentage = Percentage((amount / cost).doubleValue) } else { self.percentage = Percentage((((cost - currentValue) / cost) * -1).doubleValue) } } } extension Change: ComparableToZero { public var isZero: Bool { amount.isZero } public var isPositive: Bool { amount.isPositive } public var isNegative: Bool { amount.isNegative } public var isGreaterThanZero: Bool { amount.isGreaterThanZero } }
23.836066
97
0.63205
e4f6ded6cf0a5cad6bbf70223dbc33a7aa409125
6,271
// Advent of Code 2017 - Day 5: A Maze of Twisty Trampolines, All Alike // Swift 4 // ------------------------------------------------------------------ // let puzzleInput = """ 0 2 0 0 -2 -2 -1 -4 -5 -6 0 1 -5 -3 -10 -8 -2 -13 -14 -15 -8 -5 -13 -16 -21 -3 -14 -23 -9 -11 -19 -29 -2 -20 -28 1 -3 -35 1 -20 -4 -37 -11 -27 -33 -43 -20 -5 -9 -22 -47 -5 -49 -13 -22 -2 -2 -51 -53 -22 -38 -16 -37 -30 -49 -48 -35 -5 -42 -21 -31 -61 -43 -31 -72 -35 -3 -31 -65 -78 2 -17 -80 -10 -6 -68 -69 -44 -71 -78 -89 -19 -22 -28 -21 -7 -54 -63 -48 -70 -73 -52 -47 -49 -2 -91 -65 -76 -58 -47 -45 -21 -11 -112 -80 -93 -98 -41 -54 -105 -36 -102 -75 -102 -67 -100 -41 -56 -19 -90 -5 -66 -41 -3 -32 -95 -65 -44 -1 1 -62 -7 -29 -61 -7 1 -63 0 -20 -58 -58 -7 -54 -80 -48 -51 -151 -141 -37 -122 -130 -132 -158 -117 -63 -103 -130 -116 -130 -63 -134 -131 -59 -30 -33 -38 -127 -31 -76 -35 -162 -132 -121 -31 -28 -2 -29 -148 -156 -168 2 -33 -85 -25 -18 -167 -152 -22 -38 -136 -83 -46 -73 -139 -15 -185 -197 -125 -159 -80 -161 -158 -82 -36 -52 -210 -200 -90 -199 -70 -135 -195 -54 -156 -46 -74 -73 -221 -96 -37 -189 -27 -209 -30 -50 -4 -74 -15 -184 2 -78 -33 -37 -99 -65 -196 -32 -36 -188 -62 -5 -244 -116 -150 -118 -124 -54 -28 -43 -208 -205 -95 -90 -129 -242 -70 -144 -64 -247 -170 -213 -40 -173 -90 -77 -139 -56 -70 -120 -9 -68 -78 -7 -123 -103 -173 -254 -249 -246 -139 -192 -92 -204 -71 -199 -56 -63 -231 -23 -115 -240 -51 -200 -184 -287 -98 -7 -81 -275 -262 -260 -32 -99 -28 -199 -160 -176 -210 -244 -162 -82 -35 -276 -71 -114 -222 -294 -28 -122 -110 -178 -264 -239 -104 -85 -11 -117 -15 -69 -275 -289 -212 1 -296 -285 -9 -95 -149 -197 -152 -141 -148 -138 -173 -224 -297 -299 -53 -335 -36 -17 -291 -25 -211 -175 -104 -328 -58 -15 -198 -102 -122 -211 -74 -117 -205 -143 -353 -187 -323 -172 -133 -170 -41 -92 -84 -72 -352 -278 -164 -124 -175 -113 -175 -152 -160 -33 -126 -226 -237 -135 -156 -190 -378 -168 -271 -240 -111 -398 -91 -243 -336 -311 -368 -396 -202 -262 -18 -303 -363 -67 -36 -284 -404 -120 -97 -387 -26 -135 -112 -325 -82 -53 -307 -410 -276 -384 -64 -60 -412 -335 -356 -82 -134 -251 -408 -342 -9 -73 -27 -388 -434 -80 -231 -114 0 -64 -325 -251 -153 -109 1 -92 -167 -89 -454 -154 -13 -283 -231 -357 -244 -324 -134 -41 -380 -169 -247 -301 -297 -388 -304 -135 -403 -168 -314 -117 -281 -76 -473 -281 -322 -79 -39 -129 -432 -452 -183 -164 -76 -382 -306 -58 -126 -141 -4 -3 -201 -480 -443 -313 -361 -279 -250 -38 -1 -340 -138 -69 -462 -32 -68 -19 -31 -271 -86 -141 -331 -412 -29 -369 -518 -103 -502 -24 -67 -130 -247 -331 -535 -77 -305 -153 -44 -382 -309 -162 -430 -480 -25 -431 -78 -442 -549 -184 -523 -94 -380 -227 -526 -209 -508 -129 -36 -510 -310 -133 -145 -146 -244 -245 -541 -362 -7 -103 -565 -209 2 -140 -51 -572 -28 -354 -525 -148 -79 -176 -34 -396 -162 -374 -448 -76 -87 -136 -584 -179 -230 -490 -361 -333 -328 -34 -524 -273 -195 -32 -520 -260 -506 -576 -422 -115 -65 -285 -314 -322 -146 -287 -251 -585 -326 -77 -250 -321 -334 -560 -455 -523 -90 -234 -343 -457 -395 -173 -560 -474 -118 -244 -263 -493 -597 -232 -237 -619 -372 -416 -142 -93 -546 -538 -198 -574 -250 -491 -168 -47 -247 -127 -641 -228 -192 -545 -543 -172 -220 -277 -647 -87 -198 -450 -247 -15 -406 -562 -335 -436 -665 -362 -211 -582 -178 -523 -232 -287 -635 -33 -666 -577 -54 -509 -271 -561 -491 -512 -212 -269 -473 -460 -587 -209 -538 -14 -303 -360 -275 -125 -373 -108 -31 -314 -639 -220 -52 -378 -398 -369 -594 -204 -423 -441 -447 -27 -495 -595 -352 -388 -127 -424 -609 -435 -626 -191 -46 -363 -15 -557 -433 -53 -680 -129 -462 -40 -598 -246 -468 -600 -351 -409 -89 -732 -178 -472 -335 -622 -563 -322 -261 -63 -671 -291 -591 -518 -373 -615 -727 -553 -166 -108 -723 -77 -736 -364 -765 -49 -41 -99 -134 -684 -281 -530 -545 -372 -570 -48 -288 -583 -421 -601 -162 -176 -414 -735 -195 -786 -656 -488 -744 -256 -345 -152 -44 -29 1 -582 -30 -351 -379 -23 -48 -737 -293 -525 -73 -79 -531 -775 -706 -59 -74 -805 -311 -544 -33 -603 -454 -700 -506 -489 -617 -485 -267 -794 -13 -707 -557 -368 -730 -696 -728 -167 -413 -639 -705 -391 -11 -195 -416 -788 -295 -768 -192 -2 -771 -675 -687 -198 -568 -663 -302 -732 -265 -796 -370 -18 -579 -771 -349 -365 -214 -598 -314 -752 -315 -815 -487 -511 -126 -6 -146 -353 -787 -204 -330 -517 -456 -805 -4 -500 -150 -242 -833 -804 -663 -554 -41 -607 -121 -762 -892 -249 -405 -403 -255 -457 -613 -91 -157 -890 -631 -908 -544 -487 -813 -541 -108 -147 -702 -301 -430 -66 -492 -902 -284 -464 -784 -312 -762 -588 -17 -809 -436 -483 -16 -410 -180 -568 -37 -687 -444 -619 -211 -386 -673 -600 -155 -558 -849 -37 -717 -867 -236 -98 -165 -579 -677 -691 -602 -878 -555 -893 -773 -395 -942 -661 -850 -881 -485 -312 -689 -258 -899 -120 -227 -349 -467 -404 -45 -919 -329 -365 -22 -462 -632 -498 -873 -288 -901 -655 -321 -922 -882 -416 -946 -320 -5 -57 -352 -711 -197 -705 -737 -439 -39 -252 -1002 -617 -373 -605 -887 -451 -824 -455 -66 -619 -18 -404 -64 -736 -44 -381 -447 -567 -877 -411 -216 -635 -598 -419 -577 -142 -189 -917 -692 -153 -2 -116 -172 -423 -886 -454 -492 -491 -656 -832 -1036 -468 -23 -709 -292 -668 -454 -478 -302 -182 -677 -904 -648 -513 -901 -331 -750 -445 -758 -842 -372 -471 -109 -239 -704 -817 -340 -591 -40 """ // ------------------------------------------------------------------ // extension String { var puzzleNumbers: [Int] { return split(separator: "\n") .flatMap({ Int($0) }) } } struct Instructions: Sequence, IteratorProtocol { var currentPosition = 0 var instructions: [Int] var mutatePosition: (inout Int) -> () init(_ instructions: [Int], _ mutatePosition: @escaping (inout Int) -> ()) { self.instructions = instructions self.mutatePosition = mutatePosition } mutating func next() -> Int? { if 0..<instructions.count ~= currentPosition { let offset = instructions[currentPosition] mutatePosition(&instructions[currentPosition]) currentPosition += offset return 1 // 1 jump } return nil } } var instructions1 = Instructions(puzzleInput .puzzleNumbers) { $0 += 1 } var instructions2 = Instructions(puzzleInput .puzzleNumbers) { $0 += ($0 < 3 ? 1 : -1) } let numSteps1 = instructions1.reduce(0, +) let numSteps2 = instructions2.reduce(0, +) print("Part 1 =", numSteps1) // 364539 print("Part 2 =", numSteps2) // 27477714
5.599107
80
0.563865
f56501e2953100e9c62ae2af8ae2e1118fd3d69c
1,326
// // ConstantDeclaration.swift // TurtleAssemblerCore // // Created by Andrew Fox on 5/16/20. // Copyright © 2020 Andrew Fox. All rights reserved. // import TurtleCompilerToolbox import TurtleCore public class ConstantDeclaration: AbstractSyntaxTreeNode { public let identifier: String public let value: Int public convenience init(identifier: String, value: Int) { self.init(sourceAnchor: nil, identifier: identifier, value: value) } public required init(sourceAnchor: SourceAnchor?, identifier: String, value: Int) { self.identifier = identifier self.value = value super.init(sourceAnchor: sourceAnchor) } public override func isEqual(_ rhs: Any?) -> Bool { guard rhs != nil else { return false } guard type(of: rhs!) == type(of: self) else { return false } guard let rhs = rhs as? ConstantDeclaration else { return false } guard identifier == rhs.identifier else { return false } guard value == rhs.value else { return false } return true } public override var hash: Int { var hasher = Hasher() hasher.combine(identifier) hasher.combine(value) hasher.combine(super.hash) return hasher.finalize() } }
29.466667
87
0.631976
9b1f7e448e80e27092659ebded1d0cede3335907
8,257
import Quick import Nimble @testable import NatDS final class NatShortSpec: QuickSpec { override func spec() { var systemUnderTest: NatShortcut! var applyStyleInvocations: Int! var styleSpy: NatShortcut.Style! var notificationCenterSpy: NotificationCenterSpy! beforeEach { ConfigurationStorage.shared.currentTheme = StubTheme() applyStyleInvocations = 0 styleSpy = .init( applyStyle: { _ in applyStyleInvocations += 1 } ) notificationCenterSpy = .init() systemUnderTest = .init(style: styleSpy, notificationCenter: notificationCenterSpy) } describe("#init") { it("applies style only once") { expect(applyStyleInvocations).to(equal(1)) } it("sets a default icon") { let shortcutView = systemUnderTest.subviews.first let circleView = shortcutView?.subviews.first let iconView = circleView?.subviews.first as? IconView expect(iconView?.defaultImageView.isHidden).to(beFalse()) } it("calls notificationCenter.addObserver only once") { expect(notificationCenterSpy.addObserverInvocations).to(equal(1)) } it("registers to expected notification event without passing objects") { expect(notificationCenterSpy.invokedAddObserver?.name).to(equal(.themeHasChanged)) expect(notificationCenterSpy.invokedAddObserver?.object).to(beNil()) } it("assures that the gestureRecognizer is UITapGestureRecognizer") { let tapped = systemUnderTest.gestureRecognizers?.first { $0 is UITapGestureRecognizer } expect(tapped).toNot(beNil()) } it("assures that the gestureRecognizer is UILongPressGestureRecognizer") { let longPressed = systemUnderTest.gestureRecognizers?.first { $0 is UILongPressGestureRecognizer } expect(longPressed).toNot(beNil()) } } describe("#configure(text:)") { beforeEach { systemUnderTest.configure(text: "stub text") } it("sets text to label") { let label = systemUnderTest.subviews.last as? UILabel expect(label?.text).to(equal("stub text")) } } describe("#configure(icon:)") { beforeEach { systemUnderTest.configure(icon: nil) } it("sets icon to iconView") { let shortcutView = systemUnderTest.subviews.first let circleView = shortcutView?.subviews.first let iconView = circleView?.subviews.first as? IconView expect(iconView?.defaultImageView.isHidden).to(beFalse()) } } describe("#configure(circleColor:)") { beforeEach { systemUnderTest.configure(circleColor: .red) } it("sets background color to circleView") { let circleView = systemUnderTest.subviews.first expect(circleView?.backgroundColor).to(equal(.red)) } } describe("#configure(circleBorderWidth:)") { beforeEach { systemUnderTest.configure(circleBorderWidth: 2.5) } it("sets border width to circleView") { let circleView = systemUnderTest.subviews.first expect(circleView?.layer.borderWidth).to(equal(2.5)) } } describe("#configure(circleBorderColor:)") { beforeEach { systemUnderTest.configure(circleBorderColor: UIColor.red.cgColor) } it("sets border color to circleView") { let circleView = systemUnderTest.subviews.first expect(circleView?.layer.borderColor).to(equal(UIColor.red.cgColor)) } } describe("#configure(iconColor:)") { beforeEach { systemUnderTest.configure(iconColor: UIColor.red) } it("sets tintColor to iconView") { let shortcutView = systemUnderTest.subviews.first let circleView = shortcutView?.subviews.first let iconView = circleView?.subviews.first as? IconView expect(iconView?.tintColor).to(equal(.red)) } } describe("#configure(action:)") { var actionInvocations = 0 beforeEach { systemUnderTest.configure(action: { actionInvocations += 1 }) systemUnderTest.gestureRecognizers?.forEach { $0.sendGesturesEvents() } } it("stores action and uses it in tap events") { expect(actionInvocations).toEventually(equal(1)) } } describe("#configure(badgeValue:)") { context("when value is bigger than 0") { beforeEach { systemUnderTest.configure(badgeValue: 10) } it("adds sublayer for badge") { expect(systemUnderTest.subviews.first?.layer.sublayers?.count).to(equal(2)) } } context("when value is 0") { beforeEach { systemUnderTest.configure(badgeValue: 0) } it("removes sublayer for badge if exists") { expect(systemUnderTest.subviews.first?.layer.sublayers?.count).to(equal(1)) } } context("when value is bigger than 0 then a 0 value") { beforeEach { systemUnderTest.configure(badgeValue: 10) systemUnderTest.configure(badgeValue: 0) } it("removes sublayer for badge") { expect(systemUnderTest.subviews.first?.layer.sublayers?.count).to(equal(1)) } } } describe("#tapHandler") { beforeEach { systemUnderTest.tapHandler(.init()) } it("calls addPulseLayerAnimated and sublayer for animation is add") { let circleView = systemUnderTest.subviews.first expect(circleView?.layer.sublayers?.count).to(equal(2)) } it("calls removePulseLayer and sublayer is removed after animation ends") { let circleView = systemUnderTest.subviews.first expect(circleView?.layer.sublayers?.count).toEventually(equal(1)) } } describe("#LongPressHandler") { beforeEach { let gestureBegan = UILongPressGestureRecognizer() gestureBegan.state = .began systemUnderTest.longPressHandler(gestureBegan) let gestureEnded = UILongPressGestureRecognizer() gestureEnded.state = .ended systemUnderTest.longPressHandler(gestureEnded) } it("calls addPulseLayerAnimated and sublayer for animation is add") { let circleView = systemUnderTest.subviews.first expect(circleView?.layer.sublayers?.count).to(equal(2)) } it("calls removePulseLayer and sublayer is removed after animation ends") { let circleView = systemUnderTest.subviews.first expect(circleView?.layer.sublayers?.count).toEventually(equal(1)) } } context("When a notification of .themeHasChange is received") { beforeEach { applyStyleInvocations = 0 styleSpy = .init( applyStyle: { _ in applyStyleInvocations += 1 } ) systemUnderTest = .init(style: styleSpy) NotificationCenter.default.post(name: .themeHasChanged, object: nil) } it("applies style again besides init") { expect(applyStyleInvocations).to(equal(2)) } } } }
33.979424
114
0.553228
fb4f8ad31a256af507b5410ff7c71f44777085b9
2,401
import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? var appCoordinator: AppCoordinator? func scene( _ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let scene = (scene as? UIWindowScene) else { return } let window = UIWindow(windowScene: scene) let appCoordinator = AppCoordinator() window.rootViewController = appCoordinator.root window.makeKeyAndVisible() self.window = window self.appCoordinator = appCoordinator appCoordinator.trigger(route: .home) } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. // (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
41.396552
140
0.69596
2fde11dc826fe86729745a2071dee08815e0f9cf
3,492
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation import ProcedureKit public class QueueTestDelegate: ProcedureQueueDelegate, OperationQueueDelegate { public typealias OperationQueueCheckType = (OperationQueue, Operation) public typealias ProcedureQueueCheckType = (ProcedureQueue, Operation) public typealias ProcedureQueueCheckTypeWithErrors = (ProcedureQueue, Operation, [Error]) public var operationQueueWillAddOperation: [OperationQueueCheckType] { get { return _operationQueueWillAddOperation.read { $0 } } } public var operationQueueWillFinishOperation: [OperationQueueCheckType] { get { return _operationQueueWillFinishOperation.read { $0 } } } public var operationQueueDidFinishOperation: [OperationQueueCheckType] { get { return _operationQueueDidFinishOperation.read { $0 } } } public var procedureQueueWillAddOperation: [ProcedureQueueCheckType] { get { return _procedureQueueWillAddOperation.read { $0 } } } public var procedureQueueWillProduceOperation: [ProcedureQueueCheckType] { get { return _procedureQueueWillProduceOperation.read { $0 } } } public var procedureQueueWillFinishOperation: [ProcedureQueueCheckTypeWithErrors] { get { return _procedureQueueWillFinishOperation.read { $0 } } } public var procedureQueueDidFinishOperation: [ProcedureQueueCheckTypeWithErrors] { get { return _procedureQueueDidFinishOperation.read { $0 } } } private var _operationQueueWillAddOperation = Protector([OperationQueueCheckType]()) private var _operationQueueWillFinishOperation = Protector([OperationQueueCheckType]()) private var _operationQueueDidFinishOperation = Protector([OperationQueueCheckType]()) private var _procedureQueueWillAddOperation = Protector([ProcedureQueueCheckType]()) private var _procedureQueueWillProduceOperation = Protector([ProcedureQueueCheckType]()) private var _procedureQueueWillFinishOperation = Protector([ProcedureQueueCheckTypeWithErrors]()) private var _procedureQueueDidFinishOperation = Protector([ProcedureQueueCheckTypeWithErrors]()) public func operationQueue(_ queue: OperationQueue, willAddOperation operation: Operation) { _operationQueueWillAddOperation.append((queue, operation)) } public func operationQueue(_ queue: OperationQueue, willFinishOperation operation: Operation) { _operationQueueWillFinishOperation.append((queue, operation)) } public func operationQueue(_ queue: OperationQueue, didFinishOperation operation: Operation) { _operationQueueDidFinishOperation.append((queue, operation)) } public func procedureQueue(_ queue: ProcedureQueue, willAddOperation operation: Operation) { _procedureQueueWillAddOperation.append((queue, operation)) } public func procedureQueue(_ queue: ProcedureQueue, willProduceOperation operation: Operation) { _procedureQueueWillProduceOperation.append((queue, operation)) } public func procedureQueue(_ queue: ProcedureQueue, willFinishOperation operation: Operation, withErrors errors: [Error]) { _procedureQueueWillFinishOperation.append((queue, operation, errors)) } public func procedureQueue(_ queue: ProcedureQueue, didFinishOperation operation: Operation, withErrors errors: [Error]) { _procedureQueueDidFinishOperation.append((queue, operation, errors)) } }
45.947368
127
0.7689
c142397a1f64b99547a396d466e89d81c0efc227
1,545
import Foundation /// Model for Cartfile.resolved struct Lockfile { struct Item { let type: String let source: String let version: String var name: String { guard let lastComponent = source.components(separatedBy: "/").last else { return "" } if lastComponent.hasSuffix(".git") { return String(lastComponent[lastComponent.startIndex..<lastComponent.index(lastComponent.endIndex, offsetBy: -4)]) } if lastComponent.hasSuffix(".json") { return String(lastComponent[lastComponent.startIndex..<lastComponent.index(lastComponent.endIndex, offsetBy: -5)]) } return lastComponent } } let dependencies: [Item] } extension Lockfile { static func from(string: String) -> Lockfile { let rows = string.components(separatedBy: "\n") .filter { $0.count > 0 } return .init(dependencies: rows.compactMap(Item.from)) } } extension Lockfile.Item { static func from(row: String) -> Lockfile.Item? { let components = row.components(separatedBy: " ") guard components.count == 3 else { return nil } let type = components[0] let source = components[1].replacingOccurrences(of: #"""#, with: "") let version = components[2].replacingOccurrences(of: #"""#, with: "") return .init(type: type, source: source, version: version) } }
30.9
130
0.577994
9c533130a7d0edc04bf12981b95c8f26518653db
1,395
// // PrismDeviceType.swift // PrismUI // // Created by Erik Bautista on 7/21/20. // Copyright © 2020 ErrorErrorError. All rights reserved. // import Cocoa public enum PrismDeviceModel: CaseIterable { case perKey case perKeyGS65 case threeRegion case unknown public func productInformation() -> IOHIDManager.ProductInformation { return .init(vendorId: vendorId, productId: productId, versionNumber: versionNumber, primaryUsagePage: primaryUsagePage) } internal var vendorId: Int { switch self { case .perKey, .perKeyGS65: return 0x1038 case .threeRegion: return 0x1770 default: return 0 } } internal var productId: Int { switch self { case .perKey, .perKeyGS65: return 0x1122 case .threeRegion: return 0xff00 default: return 0 } } internal var versionNumber: Int { switch self { case .perKey: return 0x230 case .perKeyGS65: return 0x229 case .threeRegion: return 0x110 default: return 0 } } internal var primaryUsagePage: Int { switch self { case .perKey, .perKeyGS65: return 0xffc0 case .threeRegion: return 0xffa0 default: return 0 } } }
22.5
73
0.577778
2f729ca32e3b2b4891a7ea68c5289254d9c96e54
749
// // ViewController.swift // shopping-tracker // // Created by Cristian Ames on 2/13/17. // Copyright © 2017 Cristian Ames. All rights reserved. // import UIKit open class ViewController: UIViewController { open let viewModel: ViewModel public init(viewModel: ViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() bindViewModel() } open func bindViewModel() { } open func unbindViewModel() { } deinit { unbindViewModel() } }
19.205128
59
0.608812
1acc7aadad97321f1f6f61831a79f2de3b1e6e0e
2,915
// // YPLibraryViewCell.swift // YPImgePicker // // Created by Sacha Durand Saint Omer on 2015/11/14. // Copyright © 2015 Yummypets. All rights reserved. // import UIKit import Stevia class YPMultipleSelectionIndicator: UIView { let circle = UIView() let label = UILabel() var selectionColor = UIColor.ypSystemBlue convenience init() { self.init(frame: .zero) let size: CGFloat = 20 sv( circle, label ) circle.fillContainer() circle.size(size) label.fillContainer() circle.layer.cornerRadius = size / 2.0 label.textAlignment = .center label.textColor = .white label.font = YPConfig.fonts.multipleSelectionIndicatorFont set(number: nil) } func set(number: Int?) { label.isHidden = (number == nil) if let number = number { circle.backgroundColor = selectionColor circle.layer.borderColor = UIColor.clear.cgColor circle.layer.borderWidth = 0 label.text = "\(number)" } else { circle.backgroundColor = UIColor.white.withAlphaComponent(0.3) circle.layer.borderColor = UIColor.white.cgColor circle.layer.borderWidth = 1 label.text = "" } } } class YPLibraryViewCell: UICollectionViewCell { var representedAssetIdentifier: String! let imageView = UIImageView() let durationLabel = UILabel() let selectionOverlay = UIView() let multipleSelectionIndicator = YPMultipleSelectionIndicator() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) sv( imageView, durationLabel, selectionOverlay, multipleSelectionIndicator ) imageView.fillContainer() selectionOverlay.fillContainer() layout( durationLabel-5-|, 5 ) layout( 3, multipleSelectionIndicator-3-| ) imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true durationLabel.textColor = .white durationLabel.font = YPConfig.fonts.durationFont durationLabel.isHidden = true selectionOverlay.backgroundColor = .white selectionOverlay.alpha = 0 backgroundColor = .ypSecondarySystemBackground } override var isSelected: Bool { didSet { refreshSelection() } } override var isHighlighted: Bool { didSet { refreshSelection() } } private func refreshSelection() { let showOverlay = isSelected || isHighlighted selectionOverlay.alpha = showOverlay ? 0.6 : 0 } }
26.5
99
0.593139
22e4adca171f0bd126a634918df93ed3b0cdf420
790
// // Router.swift // RootViewController // // Created by satoutakeshi on 2018/04/01. // Copyright © 2018年 Personal Factory. All rights reserved. // import UIKit final class Router { enum Locate { case login case main case camera case setting } let rootViewController = RootViewController() func route(to locate: Locate, from viewController: UIViewController) { switch locate { case .login: rootViewController.showLoginScreen() break case .main: rootViewController.showMain() case .camera: rootViewController.showCameraScreen() break case .setting: rootViewController.showSettingScreen() break } } }
23.235294
74
0.594937
fbab40fa4e0d326910589550c18fec876c34f4d6
5,777
// // ImagePresenterTests.swift // Reddit-ShowcaseTests // // Created by Gustavo on 10/06/21. // import XCTest import Reddit_Showcase class ImagePresenterTests: XCTestCase { func test_init_doesNotMessageView() { let (_, view) = makeSUT() XCTAssertEqual(view.messages.count, 0) } func test_didStartLoadingImageData_displaysLoadingImage() { let (sut, view) = makeSUT() let model = feedModel sut.didStartLoadingImageData(for: model) let message = view.messages.first XCTAssertEqual(view.messages.count, 1) XCTAssertEqual(message?.title, model.title) XCTAssertEqual(message?.author, model.author) XCTAssertNotNil(message?.elapsedInterval) XCTAssertEqual(message?.numberOfComments, model.numberOfComments) XCTAssertEqual(message?.imageURL, model.imageURL) XCTAssertEqual(message?.isLoading, true) } func test_didFinishLoadingImageData_Ok_displayViewModelWithImage() { let transformedData = AnyImage() let (sut, view) = makeSUT(imageTransformer: { _ in transformedData }) let model = feedModel sut.didFinishLoadingImageData(with: Data(), for: model) let message = view.messages.first XCTAssertEqual(view.messages.count, 1) XCTAssertEqual(message?.title, model.title) XCTAssertEqual(message?.author, model.author) XCTAssertNotNil(message?.elapsedInterval) XCTAssertEqual(message?.numberOfComments, model.numberOfComments) XCTAssertEqual(message?.imageURL, model.imageURL) XCTAssertEqual(message?.isLoading, false) XCTAssertEqual(message?.thumbnail, transformedData) } func test_didFinishLoadingmageData_Error_displayViewModelWithoutImage() { let transformedData = AnyImage() let (sut, view) = makeSUT(imageTransformer: { _ in transformedData }) let model = feedModel sut.didFinishLoadingImageData(with: anyNSError, for: model) let message = view.messages.first XCTAssertEqual(view.messages.count, 1) XCTAssertEqual(message?.title, model.title) XCTAssertEqual(message?.author, model.author) XCTAssertNotNil(message?.elapsedInterval) XCTAssertEqual(message?.numberOfComments, model.numberOfComments) XCTAssertEqual(message?.imageURL, model.imageURL) XCTAssertEqual(message?.isLoading, false) XCTAssertEqual(message?.thumbnail, nil) } func test_didStartSavingData_messageViewToStartLoading() { let (sut, view) = makeSUT() sut.didStartSavingData() XCTAssertEqual(view.saveMessages, [.isSavingData(true)]) } func test_didFinishSavingDataWithError_messageViewToStopLoadingAndDisplayError() { let (sut, view) = makeSUT() sut.didFinishSavingData(with: anyNSError) XCTAssertEqual(view.saveMessages, [.isSavingData(false), .displayError(true)]) } func test_didFinishSavingDataSuccessfully_messageViewToStopLoadingAndDisplaySuccess() { let (sut, view) = makeSUT() sut.didFinishSavingData() XCTAssertEqual(view.saveMessages, [.isSavingData(false), .displayError(false)]) } func test_deleteRowAtIndex_messageViewToDeleteRow() { let (sut, view) = makeSUT() let expetedIndex = IndexPath() sut.deleteRow(at: expetedIndex) XCTAssertEqual(view.saveMessages, [.delete(expetedIndex)]) } func test_displayExpandedImage_messageViewToExpandImageWithURL() { let (sut, view) = makeSUT() let expectedUrl = anyURL sut.displayExpandedImage(with: expectedUrl) XCTAssertEqual(view.saveMessages, [.presentImage(expectedUrl)]) } // MARK: Helpers private var feedModel = FeedViewModel(item: sampleFeed) private struct AnyImage: Equatable {} private func makeSUT(imageTransformer: @escaping (Data) -> AnyImage? = { _ in nil }, file: StaticString = #file, line: UInt = #line) -> (sut: ImagePresenter<ViewSpy, AnyImage>, view: ViewSpy) { let view = ViewSpy() let sut = ImagePresenter(view: view, cellDestructionView: view, expandedImagePresenterView: view, imageTransformer: imageTransformer) trackForMemoryLeaks(view, file: file, line: line) trackForMemoryLeaks(sut, file: file, line: line) return (sut, view) } private class ViewSpy: ImagePresenterView, CellDestructionView, ExpandedImagePresenterView { private(set) var messages = [FeedImageViewModel<AnyImage>]() private(set) var saveMessages = [SaveMessage]() enum SaveMessage: Equatable { case isSavingData(Bool) case displayError(Bool) case delete(IndexPath) case presentImage(URL) } func display(_ model: FeedImageViewModel<AnyImage>) { messages.append(model) } func diplay(isSavingData: Bool) { saveMessages.append(.isSavingData(isSavingData)) } func diplay(didFinishSavingDataSuccessfully: Bool) { saveMessages.append(.displayError(!didFinishSavingDataSuccessfully)) } func removeCell(at index: IndexPath) { saveMessages.append(.delete(index)) } func presentExpanedImage(at url: URL) { saveMessages.append(.presentImage(url)) } } }
35.660494
96
0.635797
891d5c20babe6f4e4798c00a043840a64bab8b6c
2,945
// // GameController.swift // douyu // // Created by qianjn on 2017/1/1. // Copyright © 2017年 SF. All rights reserved. // import UIKit private let kEdgeMargin: CGFloat = 10 private let k_Item_Width: CGFloat = (kScreenWidth - 2 * kEdgeMargin) / 3 private let k_Item_Height: CGFloat = k_Item_Width * 6 / 5 private let kGameViewH : CGFloat = 90 private let kGameCellID = "kGameCellID" class GameController: UIViewController { fileprivate lazy var gameModel:GameViewModel = GameViewModel() fileprivate lazy var collectionView: UICollectionView = { [weak self] in let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: k_Item_Width, height: k_Item_Height) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin) let collView = UICollectionView(frame: (self?.view.bounds)!, collectionViewLayout: layout) collView.dataSource = self collView.backgroundColor = UIColor.white collView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collView.register(UINib(nibName: "GameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) return collView }() fileprivate lazy var collectionHeadTopView: CollectionHeader = { let headView = CollectionHeader.createHeadView() headView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenWidth, height: kGameViewH) headView.iconImage.image = UIImage(named: "Img_orange") headView.titlelabel.text = "常见" headView.moreBtn.isHidden = true return headView }() override func viewDidLoad() { super.viewDidLoad() buildUI() loadData() } } // MARK: - UI extension GameController { fileprivate func buildUI() { view.addSubview(collectionView) collectionView.addSubview(collectionHeadTopView) collectionView.contentInset = UIEdgeInsets(top: collectionHeadTopView.frame.height, left: 0, bottom: 0, right: 0) } } // MARK: - load data extension GameController { fileprivate func loadData() { gameModel.loadGamesData { self.collectionView.reloadData() } } } // MARK: - UICollectionView extension GameController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameModel.games.count; } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let game = gameModel.games[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as? GameCell cell?.game = game return cell! } }
31
121
0.67674
91d7b7d4dbfdd04229afc9d0e5bbf7f4bc6c5ed5
272
// // ViewController.swift // App // // Created by Inpyo Hong on 2021/07/23. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
13.6
58
0.639706
79dc2fe2fc24a220d03b1ed440794a2b08bbc6d5
633
import Foundation import ArgumentParser struct PrettyPrintRegexLiteral: ParsableCommand { static let configuration = CommandConfiguration( commandName: "PrettyPrintRegexLiteral", abstract: "A command-line tool to pretty print regex literals.", subcommands: []) @Argument(help: "literal") private var literal: String @Flag(name: [.short, .long], help: "Colorcode matching parenthesis") var colored = false func run() throws { let prettyPrinter = PrettyPrinter(input: literal, colored: colored) prettyPrinter.printOut() } } PrettyPrintRegexLiteral.main()
26.375
75
0.693523
67e3694925eddfcf3312d460e6dafc284b994afe
2,315
// // KingfisherSource.swift // ImageSlideshow // // Created by feiin // // import Kingfisher import UIKit /// Input Source to image using Kingfisher public class KingfisherSource: NSObject, InputSource { /// url to load public var url: URL /// placeholder used before image is loaded public var placeholder: UIImage? /// options for displaying, ie. [.transition(.fade(0.2))] public var options: KingfisherOptionsInfo? /// Initializes a new source with a URL /// - parameter url: a url to be loaded /// - parameter placeholder: a placeholder used before image is loaded /// - parameter options: options for displaying public init(url: URL, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil) { self.url = url self.placeholder = placeholder self.options = options super.init() } /// Initializes a new source with a URL string /// - parameter urlString: a string url to load /// - parameter placeholder: a placeholder used before image is loaded /// - parameter options: options for displaying public init?(urlString: String, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil) { if let validUrl = URL(string: urlString) { url = validUrl self.placeholder = placeholder self.options = options super.init() } else { return nil } } /// Load an image to an UIImageView /// /// - Parameters: /// - imageView: UIImageView that receives the loaded image /// - callback: Completion callback with an optional image @objc public func load(to imageView: UIImageView, with callback: @escaping (UIImage?) -> Void) { imageView.kf.setImage(with: url, placeholder: placeholder, options: options, progressBlock: nil) { result in switch result { case let .success(image): callback(image.image) case .failure: callback(nil) } } } /// Cancel an image download task /// /// - Parameter imageView: UIImage view with the download task that should be canceled public func cancelLoad(on imageView: UIImageView) { imageView.kf.cancelDownloadTask() } }
31.712329
116
0.628942
1a7f50097587331ceb45b5a9fc42a65b828ac327
1,082
// Copyright 2022 Pera Wallet, LDA // 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. // // WCSessionDisconnectedEvent.swift import Foundation struct WCSessionDisconnectedEvent: AnalyticsEvent { let dappName: String let dappURL: String let address: String? let key: AnalyticsEventKey = .wcSessionDisconnected var params: AnalyticsParameters? { var params: AnalyticsParameters = [.dappName: dappName, .dappURL: dappURL] if let address = address { params[.address] = address } return params } }
29.243243
82
0.707024
f821b6a3c443e9010bab5ed96bd0843ad7c65980
973
import XCTest import RxTest import RxBlocking import RxSwift @testable import RxParseCallback class CallbackBasedAPI { static func giveMeTheThing<T>(thing: T, callback: @escaping (T, Swift.Error?) -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) { callback(thing, .none) } } } class Rxifyed { static func giveMeTheThing<T>(thing: T) -> Observable<T> { return RxParseCallback.createWithCallback { observer in CallbackBasedAPI.giveMeTheThing(thing: thing, callback: RxParseCallback.parseCallback(observer)) } } } class RxParseCallbackTests: XCTestCase { func testBasics() { let object = try? Rxifyed.giveMeTheThing(thing: "hi").toBlocking(timeout: 0.1).first() guard let maybeObject = object, let definitelyObject = maybeObject else { return XCTFail("got back nothing") } XCTAssertEqual(definitelyObject, "hi") } }
27.8
108
0.670092
e0a35d2d8ce2da5129fc52ec8cf0b37abcdab5f1
1,787
// // Nib+NSView.swift // Instantiate // // Created by tarunon on 2017/06/11. // #if os(macOS) import AppKit public extension NibInstantiatable where Self: NSView { init(with dependency: Dependency) { var objects: NSArray? = NSArray() Self.nib.instantiate(withOwner: nil, topLevelObjects: &objects) self = objects!.filter { !($0 is NSApplication) }[Self.instantiateIndex] as! Self self.inject(dependency) } } public extension NibInstantiatableWrapper where Self: NSView, Wrapped: NSView { var view: Wrapped { return self.subviews.first as! Wrapped } var viewIfLoaded: Wrapped? { return self.subviews.first as? Wrapped } func loadView(with dependency: Wrapped.Dependency) { let view = Wrapped(with: dependency) if translatesAutoresizingMaskIntoConstraints { view.translatesAutoresizingMaskIntoConstraints = true view.autoresizingMask = [.width, .height] view.frame = self.bounds self.addSubview(view, positioned: .above, relativeTo: self.subviews.first) } else { view.translatesAutoresizingMaskIntoConstraints = false self.addSubview(view, positioned: .above, relativeTo: self.subviews.first) view.topAnchor.constraint(equalTo: self.topAnchor).isActive = true view.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true view.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true view.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true } } } #endif
36.469388
93
0.61164
50d4f4438a18a244d3d50e8af3f07ba01afd3aa6
7,278
// // PagerControlView.swift // Spartak Moscow FC // // Created by Smirnov Maxim on 16/10/2017. // Copyright © 2017 Smirnov Maxim. All rights reserved. // import UIKit open class PagerControlView: UIView { // MARK: - Properties private var collectionView: UICollectionView! private(set) public var selectedItem: Int = 0 open weak var delegate: PagerControlViewDelegate? private lazy var cellDealer: PagerControlCellDealer = { return PagerControllCellDealerImplementation() }() private var _lineDealer: PagerControlLineDealer? private var lineDealer: PagerControlLineDealer? { guard let dealer = _lineDealer else { guard viewModel?.lineModel != nil else { return nil } _lineDealer = PagerControlLineDealerImplementation(superview: collectionView) return _lineDealer } return dealer } // MARK: - Model Properties private var viewModel: PagerControlViewModel? // MARK: - LifeCircle override open func layoutSubviews() { super.layoutSubviews() let cellFrame = collectionView?.cellForItem(at: IndexPath(row: selectedItem, section: 0))?.frame guard frame.width != 0.0, cellFrame == nil else { return } setupLine() } // MARK: - init override init(frame: CGRect) { super.init(frame: frame) setupCollectionView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupCollectionView() } private func setupCollectionView() { self.collectionView?.removeFromSuperview() let flow = UICollectionViewFlowLayout() flow.scrollDirection = .horizontal let collectionView = UICollectionView(frame: frame, collectionViewLayout: flow) addSubview(collectionView) collectionView.autoPinEdgesToSuperviewEdges() collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = .clear self.collectionView = collectionView } //MARK: - Public open func setup(withModel viewModel: PagerControlViewModel) { self.viewModel = viewModel setupLine() cellDealer.registerCell(withEntity: viewModel.cellEntity, forCollectionView: collectionView) collectionView?.reloadData() scroll(toIndex: 0, isForce: true) } open func selectItem(_ index: Int) { scroll(toIndex: index) } //MARK: - Private private func scroll(toIndex index: Int, isForce: Bool = false) { let previousIndexPath = IndexPath(item: selectedItem, section: 0) let previousIndex = selectedItem guard (previousIndex != index) || isForce else { return } selectedItem = index let scrollPosition: UICollectionView.ScrollPosition switch index { case collectionView.numberOfItems(inSection: 0) - 1: scrollPosition = .left case 0: scrollPosition = .right default: scrollPosition = .centeredHorizontally } let indexPath = IndexPath(item: index, section: 0) collectionView.scrollToItem(at: indexPath, at: scrollPosition, animated: true) //TODO: - maybe batch update? setupCells(forCollectionView: collectionView, withIndexPaxes: [indexPath, previousIndexPath], animate: true) guard let frame = collectionView.cellForItem(at: indexPath)?.frame else { return } updateLine(forFrame: frame) } //MARK: - Line private func setupLine() { guard let model = viewModel?.lineModel, let width = viewModel?.cellModel.selectedWidth(forIndex: 0) else { return } lineDealer?.setupLine(withModel: model, andInitialWidth: width) } private func updateLine(forFrame frame: CGRect) { lineDealer?.updateLine(forFrame: frame) } } //MARK: - UICollectionViewDelegateFlowLayout extension PagerControlView: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { scroll(toIndex: indexPath.item) delegate?.didSwitchToItem(withIndex: selectedItem) //call delegate after animation DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { self.delegate?.didSwitchToItemAfterAnimation(withIndex: self.selectedItem) } } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard let viewModel = viewModel else { return .zero } let item = indexPath.item let isSelected = (item == selectedItem) let setupWidth = isSelected ? viewModel.cellModel.selectedWidth(forIndex: item) : viewModel.cellModel.width(forIndex: item) return CGSize(width: setupWidth, height: collectionView.frame.height) } } //MARK: - UICollectionViewDataSource extension PagerControlView: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel?.cellModel.count ?? 0 } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = cellDealer.collectionView(collectionView, cellForItemAt: indexPath) if let cell = cell as? Setupable { setup(cell: cell, forIndexPath: indexPath) } return cell } private func setupCells(forCollectionView collectionView: UICollectionView, withIndexPaxes indexPaxes: [IndexPath], animate: Bool = false) { for indexPath in indexPaxes { guard let cell = collectionView.cellForItem(at: indexPath) as? Setupable else { continue } setup(cell: cell, forIndexPath: indexPath) } } private func setup(cell: Setupable, forIndexPath indexPath: IndexPath) { guard let cellModel = viewModel?.cellModel else { return } let item = indexPath.item let isSelected = (item == selectedItem) guard let setupModel = isSelected ? cellModel.selectedCellModels[safe: item] : cellModel.cellModels[safe: item] else { return } cell.setup(setupModel) } }
28.880952
167
0.607997
4aef0d33b3cdb3ca1285122f205903f1d0aeb18c
5,077
// // Mapper.swift // Pods // // Created by Arnaud Dorgans on 04/09/2017. // // import UIKit import ObjectMapper import Realm import RealmSwift internal class RealmMapper<T: MappableObject> { var context: RealmMapContext? var realm: (()->Realm)? var shouldIncludeNilValues: Bool init(context: RealmMapContext? = nil, realm: (()->Realm)? = nil, shouldIncludeNilValues: Bool = false) { self.context = context self.realm = realm self.shouldIncludeNilValues = shouldIncludeNilValues } convenience init(map: Map) { self.init(context: map.context as? RealmMapContext, realm: nil, shouldIncludeNilValues: map.shouldIncludeNilValues) } func map(JSONObject: Any?, options: RealmMapOptions? = nil) throws -> T? { let context = RealmMapContext.from(context: self.context, realm: self.realm, options: options) self.context = context let JSONObject = self.jsonObject(fromJSONObject: JSONObject, context: context) let preferredPrimaryKey = T.preferredPrimaryKey let sync = context.options.contains(.sync) let copy = context.options.contains(.copy) let isRealmNeeded = sync let realm = isRealmNeeded ? (try context.realm?() ?? Realm()) : nil var object: T? let update = { if T.hasPrimaryKey, sync, let realm = realm, let preferredPrimaryKey = preferredPrimaryKey, let primaryValue = (JSONObject as? [String:Any])?.nestedValue(at: preferredPrimaryKey, nested: T.jsonPrimaryKeyOptions().nested, nestedKeyDelimiter: T.jsonPrimaryKeyOptions().delimiter), let savedObject = realm.object(ofType: T.self, forPrimaryKey: primaryValue) { if !copy { object = savedObject } else { object = T(value: savedObject, schema: RLMSchema.partialShared()) } } if var _object = object ?? T(map: self.map(fromJSONObject: JSONObject, context: context)) { _object = Mapper<T>(context: self.context, shouldIncludeNilValues: self.shouldIncludeNilValues).map(JSONObject: JSONObject, toObject: _object) if let realm = realm, sync && !copy { realm.add(_object, update: T.hasPrimaryKey) } object = _object } } if let realm = realm { try realm.safeWrite(update) } else { update() } return object } private func map(fromJSONObject JSONObject: Any?, context: RealmMapContext) -> Map { return Map(mappingType: .fromJSON, JSON: (JSONObject as? [String:Any]) ?? [:], context: context, shouldIncludeNilValues: self.shouldIncludeNilValues) } private func jsonObject(fromJSONObject JSONObject: Any?, context: RealmMapContext) -> Any? { if context.options.contains(.override) { var JSON = T().toJSON(shouldIncludeNilValues: true) if var _JSON = JSONObject as? [String:Any] { JSON.map{ $0.key } .filter{_JSON[$0] != nil} .forEach{ key in JSON[key] = _JSON[key] } } return JSON } return JSONObject } } extension Mapper where N: MappableObject { public var realm: (()->Realm)? { get { return (self.context as? RealmMapContext)?.realm } set { if let context = self.context as? RealmMapContext { context.realm = newValue } else { self.context = RealmMapContext(realm: newValue) } } } public var options: RealmMapOptions? { get { return (self.context as? RealmMapContext)?.options } set { let options = newValue ?? [] if let context = self.context as? RealmMapContext { context.options = options } else { self.context = RealmMapContext(options: options) } } } public convenience init(context: RealmMapContext? = nil, realm: (()->Realm)?, shouldIncludeNilValues: Bool = false) { self.init(context: context, realm: realm, options: nil, shouldIncludeNilValues: shouldIncludeNilValues) } public convenience init(context: RealmMapContext? = nil, realm: (()->Realm)? = nil, options: RealmMapOptions, shouldIncludeNilValues: Bool = false) { self.init(context: context, realm: realm, options: options as RealmMapOptions?, shouldIncludeNilValues: shouldIncludeNilValues) } private convenience init(context: RealmMapContext?, realm: (()->Realm)?, options: RealmMapOptions?, shouldIncludeNilValues: Bool = false) { self.init(context: RealmMapContext.from(context: context, realm: realm, options: options) as MapContext, shouldIncludeNilValues: shouldIncludeNilValues) } }
38.462121
202
0.596218
bbc05b361a9e00270b7bd325235da2c8022d29e5
1,006
import Foundation // Going to the cinema (Swift) // https://www.codewars.com/kata/562f91ff6a8b77dfe900006e/train/swift func movie(card: Double, ticket: Double, perc: Double) -> Int { var res = 0, a = 0.0, c = card, t = ticket while ceil(a) <= ceil(c) { a = a + ticket t = t * perc c += t res += 1 } return res } // MARK: - Solution 2 - /* func movie(card: Double, ticket: Double, perc: Double) -> Int { var a = 0.0, b = card, i = 0 while a <= ceil(b) { i += 1 a = ticket * Double(i) b += ticket * pow(perc , Double(i)) } return i } */ // MARK: - Tests import XCTest // Executed 2 tests, with 0 failures (0 unexpected) in 0.105 (0.107) seconds class SolutionTest: XCTestCase { func test0() { XCTAssertEqual(movie(card: 500.0, ticket: 15.0, perc: 0.9), 43) } func test1() { XCTAssertEqual(movie(card: 100.0, ticket: 10.0, perc: 0.95), 24) } } SolutionTest.defaultTestSuite.run()
21.404255
76
0.5666
d7658e5061aca14422481055057d662acfb67a54
12,538
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Combine import XCTest import Amplify @testable import AmplifyTestCommon @testable import AWSAPICategoryPlugin import AppSyncRealTimeClient @available(iOS 13.0, *) class GraphQLSubscribeCombineTests: OperationTestBase { // Setup expectations var onSubscribeInvoked: XCTestExpectation! // Subscription state expectations var receivedStateCompletionSuccess: XCTestExpectation! var receivedStateCompletionFailure: XCTestExpectation! var receivedStateValueConnecting: XCTestExpectation! var receivedStateValueConnected: XCTestExpectation! var receivedStateValueDisconnected: XCTestExpectation! // Subscription item expectations var receivedDataCompletionSuccess: XCTestExpectation! var receivedDataCompletionFailure: XCTestExpectation! var receivedDataValueSuccess: XCTestExpectation! var receivedDataValueError: XCTestExpectation! // Handles to the subscription item and event handler used to make mock calls into the // subscription system var subscriptionItem: SubscriptionItem! var subscriptionEventHandler: SubscriptionEventHandler! var connectionStateSink: AnyCancellable? var subscriptionDataSink: AnyCancellable? override func setUpWithError() throws { try super.setUpWithError() onSubscribeInvoked = expectation(description: "onSubscribeInvoked") receivedStateCompletionSuccess = expectation(description: "receivedStateCompletionSuccess") receivedStateCompletionFailure = expectation(description: "receivedStateCompletionFailure") receivedStateValueConnecting = expectation(description: "receivedStateValueConnecting") receivedStateValueConnected = expectation(description: "receivedStateValueConnected") receivedStateValueDisconnected = expectation(description: "receivedStateValueDisconnected") receivedDataCompletionSuccess = expectation(description: "receivedDataCompletionSuccess") receivedDataCompletionFailure = expectation(description: "receivedDataCompletionFailure") receivedDataValueSuccess = expectation(description: "receivedDataValueSuccess") receivedDataValueError = expectation(description: "receivedDataValueError") try setUpMocksAndSubscriptionItems() } func testHappyPath() throws { receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = true receivedDataValueError.shouldTrigger = false let testJSON: JSONValue = ["foo": true] let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! subscribe(expecting: testJSON) wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.data(testData), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } func testConnectionWithNoData() throws { receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = false receivedDataValueError.shouldTrigger = false subscribe() wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } func testConnectionError() throws { receivedStateCompletionSuccess.shouldTrigger = false receivedStateCompletionFailure.shouldTrigger = true receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = false receivedStateValueDisconnected.shouldTrigger = false receivedDataCompletionSuccess.shouldTrigger = false receivedDataCompletionFailure.shouldTrigger = true receivedDataValueSuccess.shouldTrigger = false receivedDataValueError.shouldTrigger = false subscribe() wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.failed("Error"), subscriptionItem) waitForExpectations(timeout: 0.05) } func testDecodingError() throws { let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = false receivedDataValueError.shouldTrigger = true subscribe() wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.data(testData), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } func testMultipleSuccessValues() throws { let testJSON: JSONValue = ["foo": true] let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = true receivedDataValueSuccess.expectedFulfillmentCount = 2 receivedDataValueError.shouldTrigger = false subscribe(expecting: testJSON) wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.data(testData), subscriptionItem) subscriptionEventHandler(.data(testData), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } func testMixedSuccessAndErrorValues() throws { let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)! let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! receivedStateCompletionSuccess.shouldTrigger = true receivedStateCompletionFailure.shouldTrigger = false receivedStateValueConnecting.shouldTrigger = true receivedStateValueConnected.shouldTrigger = true receivedStateValueDisconnected.shouldTrigger = true receivedDataCompletionSuccess.shouldTrigger = true receivedDataCompletionFailure.shouldTrigger = false receivedDataValueSuccess.shouldTrigger = true receivedDataValueSuccess.expectedFulfillmentCount = 2 receivedDataValueError.shouldTrigger = true subscribe() wait(for: [onSubscribeInvoked], timeout: 0.05) subscriptionEventHandler(.connection(.connecting), subscriptionItem) subscriptionEventHandler(.connection(.connected), subscriptionItem) subscriptionEventHandler(.data(successfulTestData), subscriptionItem) subscriptionEventHandler(.data(invalidTestData), subscriptionItem) subscriptionEventHandler(.data(successfulTestData), subscriptionItem) subscriptionEventHandler(.connection(.disconnected), subscriptionItem) waitForExpectations(timeout: 0.05) } // MARK: - Utilities /// Sets up test with a mock subscription connection handler that populates /// self.subscriptionItem and self.subscriptionEventHandler, then fulfills /// self.onSubscribeInvoked func setUpMocksAndSubscriptionItems() throws { let onSubscribe: MockSubscriptionConnection.OnSubscribe = { requestString, variables, eventHandler in let item = SubscriptionItem( requestString: requestString, variables: variables, eventHandler: eventHandler ) self.subscriptionItem = item self.subscriptionEventHandler = eventHandler self.onSubscribeInvoked.fulfill() return item } let onGetOrCreateConnection: MockSubscriptionConnectionFactory.OnGetOrCreateConnection = { _, _, _ in MockSubscriptionConnection(onSubscribe: onSubscribe, onUnsubscribe: { _ in }) } try setUpPluginForSubscriptionResponse(onGetOrCreateConnection: onGetOrCreateConnection) } /// Calls `Amplify.API.subscribe` with a request made from a generic document, and returns /// the operation created from that subscription. If `expectedValue` is not nil, also asserts /// that the received value is equal to the expected value @discardableResult func subscribe( expecting expectedValue: JSONValue? = nil ) -> GraphQLSubscriptionOperation<JSONValue> { let testDocument = "subscribe { subscribeTodos { id name description }}" let request = GraphQLRequest( document: testDocument, variables: nil, responseType: JSONValue.self ) let operation = Amplify.API.subscribe(request: request) connectionStateSink = operation .connectionStatePublisher .sink( receiveCompletion: { completion in switch completion { case .failure: self.receivedStateCompletionFailure.fulfill() case .finished: self.receivedStateCompletionSuccess.fulfill() } }, receiveValue: { connectionState in switch connectionState { case .connecting: self.receivedStateValueConnecting.fulfill() case .connected: self.receivedStateValueConnected.fulfill() case .disconnected: self.receivedStateValueDisconnected.fulfill() } } ) subscriptionDataSink = operation .subscriptionDataPublisher .sink(receiveCompletion: { completion in switch completion { case .failure: self.receivedDataCompletionFailure.fulfill() case .finished: self.receivedDataCompletionSuccess.fulfill() } }, receiveValue: { result in switch result { case .success(let actualValue): if let expectedValue = expectedValue { XCTAssertEqual(actualValue, expectedValue) } self.receivedDataValueSuccess.fulfill() case .failure: self.receivedDataValueError.fulfill() } } ) return operation } }
41.516556
109
0.701547
564efe0f706d2909af8d0209642a35e57df8c912
227
// // Card.swift // Raise // // Created by Stephen Hayes on 3/13/18. // Copyright © 2018 Raise Software. All rights reserved. // import Foundation struct Card: Codable { let type: DeckType let value: CardValue }
14.1875
57
0.660793
1eebf25b2626f70822f53309c8d7624ed819d4ab
1,208
import Foundation internal enum URLPathToken { case slash case dot case literal(String) var routeEdge: RouteEdge { switch self { case .slash: return .slash case .dot: return .dot case let .literal(value): return .literal(value) } } } extension URLPathToken: CustomStringConvertible, CustomDebugStringConvertible { var description: String { switch self { case .slash: return "/" case .dot: return "." case .literal(let value): return value } } var debugDescription: String { switch self { case .slash: return "[Slash]" case .dot: return "[Dot]" case .literal(let value): return "[Literal \"\(value)\"]" } } } extension URLPathToken: Equatable { } func == (lhs: URLPathToken, rhs: URLPathToken) -> Bool { switch (lhs, rhs) { case (.slash, .slash): return true case (.dot, .dot): return true case (let .literal(lval), let .literal(rval)): return lval == rval default: return false } }
20.827586
79
0.524007
db8c8abd06236660efedd5b70dba1f6ae8f2bb3b
419
// // PhotoCellView.swift // ProBill // // Created by Ysée Monnier on 06/05/16. // Copyright © 2016 MONNIER Ysee. All rights reserved. // import Foundation import UIKit class PhotoCellView: UICollectionViewCell { @IBOutlet weak var picture: UIImageView! @IBOutlet weak var image: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
19.952381
55
0.673031
d70c51b3c98a73282f9cf15ee75849f874e27cde
1,189
// // JXDBListCell.swift // ShoppingGo // // Created by 杜进新 on 2017/8/16. // Copyright © 2017年 杜进新. All rights reserved. // import UIKit class JXDBListCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var ageLabel: UILabel! @IBOutlet weak var genderLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! var model: DBUserModel! { didSet{ nameLabel.text = model.name ageLabel.text = "\(model.age)" genderLabel.text = model.gender == 0 ? "男":"女" scoreLabel.text = "\(model.score)" } } 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 } } class DBUserModel: NSObject { var id : Int = 0 var name : String? var age : Int = 18 var gender : Int = 0 //0为男,1位女 var score : Int = 0 override func setValue(_ value: Any?, forUndefinedKey key: String) { print("UndefinedKey = ",key) } }
23.313725
72
0.600505
d562c3c6b164d37de58e154cee5241511668ca68
1,609
// import SwiftUI struct SymbolView: View { static let symbolColor = Color(red: 79.0 / 255, green: 79.0 / 255, blue: 191.0 / 255) var body: some View { GeometryReader { geometry in Path { path in let width = min(geometry.size.width, geometry.size.height) let height = width * 0.75 let spacing = width * 0.030 let middle = width / 2 let topWidth = 0.226 * width let topHeight = 0.488 * height path.addLines([ CGPoint(x: middle, y: spacing), CGPoint(x: middle - topWidth, y: topHeight - spacing), CGPoint(x: middle, y: topHeight / 2 + spacing), CGPoint(x: middle + topWidth, y: topHeight - spacing), CGPoint(x: middle, y: spacing) ]) path.move(to: CGPoint(x: middle, y: topHeight / 2 + spacing * 3)) path.addLines([ CGPoint(x: middle - topWidth, y: topHeight + spacing), CGPoint(x: spacing, y: height - spacing), CGPoint(x: width - spacing, y: height - spacing), CGPoint(x: middle + topWidth, y: topHeight + spacing), CGPoint(x: middle, y: topHeight / 2 + spacing * 3) ]) } .fill(Self.symbolColor) } } } #if DEBUG struct SymbolView_Previews: PreviewProvider { static var previews: some View { SymbolView() } } #endif
34.234043
89
0.48353
d98a17eb266c662937d6fc76dc2bb3a279ad2360
491
// // ConnectivityPercentage.swift // Connectivity // // Created by Ross Butler on 12/9/18. // import Foundation public struct ConnectivityPercentage: Comparable { let value: Double init(_ value: Double) { var result = value < 0.0 ? 0.0 : value result = value > 100.0 ? 100.0 : value self.value = result } public static func < (lhs: ConnectivityPercentage, rhs: ConnectivityPercentage) -> Bool { return lhs.value < rhs.value } }
22.318182
93
0.629328
b958f4337d8afefa8dd6c1776c9462a006792662
1,169
// // StripeError.swift // Stripe // // Created by Anthony Castelli on 4/13/17. // // import Node public enum StripeError: Error { // Provider Errors case missingConfig case missingAPIKey // Serialization case serializationError // API Error's case apiConnectionError(String) case apiError(String) case authenticationError(String) case cardError(String) case invalidRequestError(String) case rateLimitError(String) case validationError(String) // Other case invalidSourceType case missingParamater(String) public var localizedDescription: String { switch self { case .apiConnectionError(let err): return err case .apiError(let err): return err case .authenticationError(let err): return err case .cardError(let err): return err case .invalidRequestError(let err): return err case .rateLimitError(let err): return err case .validationError(let err): return err default: return "unknown error" } } }
21.254545
45
0.607357
8929828ed66b6628fefe68541125085b6200520e
5,609
import Foundation public protocol Tester: Sendable { associatedtype Metrics: MetricSet func runSingleTest(seed: Int?) async throws -> Metrics func runSingleTest(seeds: [Int]?, delay: Double?) async throws -> [Metrics] func run(seeds: [Int]?, delay: Double?, hparams: HyperParamSet?) async throws -> [[Metrics]] } public enum OpenKeModel: String, Sendable { case transe case complex } public let DEFAULT_CV_SPLIT_INDEX: Int = 0 public let USER = ProcessInfo.processInfo.environment["USER"]! public struct OpenKeTester: Tester { public typealias Metrics = MeagerMetricSet public let model: OpenKeModel public let env: String public let corpus: String public let nWorkers: Int? public let remove: Bool public let gpu: Bool public let differentGpus: Bool public let terminationDelay: Double? public init(model: OpenKeModel, env: String, corpus: String, nWorkers: Int? = nil, remove: Bool = false, gpu: Bool = true, differentGpus: Bool = true, terminationDelay: Double? = nil) { self.model = model self.env = env self.corpus = corpus self.nWorkers = nWorkers self.remove = remove self.gpu = gpu self.differentGpus = differentGpus self.terminationDelay = terminationDelay } public func runSingleTest(seed: Int? = nil) async throws -> Metrics { try await runSingleTest(seed: seed, cvSplitIndex: DEFAULT_CV_SPLIT_INDEX) } public func runSingleTest(seed: Int? = nil, cvSplitIndex: Int, workerIndex: Int? = nil, hparams: HyperParamSet? = nil, usingValidationSubset: Bool = false) async throws -> Metrics { // Configure args var args = ["-m", "relentness", "test", "\(corpusPath)/\(String(format: "%04i", cvSplitIndex))/", "-m", model.rawValue, "-t"] if let unwrappedHparams = hparams { args.append(contentsOf: unwrappedHparams.openKeArgs) } if let unwrappedSeed = seed { args.append( contentsOf: ["-s", String(describing: unwrappedSeed)] ) } else { args.append("-r") } if (remove && !args.contains("-r")) { args.append("-r") } if usingValidationSubset { args.append("-val") } // Configure env var envVars = ["TF_CPP_MIN_LOG_LEVEL": "3"] if !gpu { envVars["CUDA_VISIBLE_DEVICES"] = "-1" } else if let unwrappedWorkerIndex = workerIndex, differentGpus { envVars["CUDA_VISIBLE_DEVICES"] = String(describing: unwrappedWorkerIndex) } // print("Running command '\(args.joined(separator: " "))'") return try await measureExecutionTime { try await runSubprocessAndGetOutput( path: "/home/\(USER)/anaconda3/envs/\(env)/bin/python", args: args, env: envVars, terminationDelay: terminationDelay ) } handleExecutionTimeMeasurement: { output, nSeconds in return MeagerMetricSet( output, time: nSeconds ) } } public func runSingleTest(seeds: [Int]? = nil, delay: Double?) async throws -> [Metrics] { try await runSingleTest(seeds: seeds, delay: delay, cvSplitIndex: DEFAULT_CV_SPLIT_INDEX) } public func runSingleTest(seeds: [Int]? = nil, delay: Double? = nil, cvSplitIndex: Int, hparams: HyperParamSet? = nil, usingValidationSubset: Bool = false) async throws -> [Metrics] { if let unwrappedSeeds = seeds { if nWorkers == nil || nWorkers! > 1 { return try await unwrappedSeeds.asyncMap(nWorkers: nWorkers, delay: delay) { seed, workerIndex in // TODO: Add support for total time (instead of computing sum, here max must me chosen) try await runSingleTest( seed: seed, cvSplitIndex: cvSplitIndex, workerIndex: workerIndex, hparams: hparams, usingValidationSubset: usingValidationSubset ) } } else { return try await unwrappedSeeds.map { seed in try await runSingleTest( seed: seed, cvSplitIndex: cvSplitIndex, workerIndex: 0, hparams: hparams, usingValidationSubset: usingValidationSubset ) } } } let result: Metrics = try await runSingleTest(cvSplitIndex: cvSplitIndex) return [result] } public func run(seeds: [Int]? = nil, delay: Double? = nil, hparams: HyperParamSet? = nil) async throws -> [[Metrics]] { return try await getNestedFolderNames(corpusPath).map { cvSplitStringifiedIndex in // No parallelism on this level let result = try await runSingleTest( seeds: seeds, delay: delay, cvSplitIndex: cvSplitStringifiedIndex.asInt, hparams: hparams ) return result } } public var corpusPath: String { "./Assets/Corpora/\(corpus)" } } public extension Array { func map<Type>(closure: (Element) async throws -> Type) async throws -> [Type] { var result = [Type]() for item in self { result.append( try await closure(item) ) } return result } }
33.993939
201
0.578713
1ec5657b916c2d5eba0bb810ce37d8ad3e203cba
43,618
// // PodCommsSession.swift // OmniKit // // Created by Pete Schwamb on 10/13/17. // Copyright © 2017 Pete Schwamb. All rights reserved. // import Foundation import RileyLinkBLEKit import LoopKit import os.log public enum PodCommsError: Error { case noPodPaired case invalidData case noResponse case emptyResponse case podAckedInsteadOfReturningResponse case unexpectedPacketType(packetType: PacketType) case unexpectedResponse(response: MessageBlockType) case unknownResponseType(rawType: UInt8) case invalidAddress(address: UInt32, expectedAddress: UInt32) case noRileyLinkAvailable case unfinalizedBolus case unfinalizedTempBasal case nonceResyncFailed case podSuspended case podFault(fault: DetailedStatus) case commsError(error: Error) case rejectedMessage(errorCode: UInt8) case podChange case activationTimeExceeded case rssiTooLow case rssiTooHigh case diagnosticMessage(str: String) case podIncompatible(str: String) } extension PodCommsError: LocalizedError { public var errorDescription: String? { switch self { case .noPodPaired: return LocalizedString("No pod paired", comment: "Error message shown when no pod is paired") case .invalidData: return nil case .noResponse: return LocalizedString("No response from pod", comment: "Error message shown when no response from pod was received") case .emptyResponse: return LocalizedString("Empty response from pod", comment: "Error message shown when empty response from pod was received") case .podAckedInsteadOfReturningResponse: return LocalizedString("Pod sent ack instead of response", comment: "Error message shown when pod sends ack instead of response") case .unexpectedPacketType: return nil case .unexpectedResponse: return LocalizedString("Unexpected response from pod", comment: "Error message shown when empty response from pod was received") case .unknownResponseType: return nil case .invalidAddress(address: let address, expectedAddress: let expectedAddress): return String(format: LocalizedString("Invalid address 0x%x. Expected 0x%x", comment: "Error message for when unexpected address is received (1: received address) (2: expected address)"), address, expectedAddress) case .noRileyLinkAvailable: return LocalizedString("No RileyLink available", comment: "Error message shown when no response from pod was received") case .unfinalizedBolus: return LocalizedString("Bolus in progress", comment: "Error message shown when operation could not be completed due to existing bolus in progress") case .unfinalizedTempBasal: return LocalizedString("Temp basal in progress", comment: "Error message shown when temp basal could not be set due to existing temp basal in progress") case .nonceResyncFailed: return nil case .podSuspended: return LocalizedString("Pod is suspended", comment: "Error message action could not be performed because pod is suspended") case .podFault(let fault): let faultDescription = String(describing: fault.faultEventCode) return String(format: LocalizedString("Pod Fault: %1$@", comment: "Format string for pod fault code"), faultDescription) case .commsError(let error): return error.localizedDescription case .rejectedMessage(let errorCode): return String(format: LocalizedString("Command error %1$u", comment: "Format string for invalid message error code (1: error code number)"), errorCode) case .podChange: return LocalizedString("Unexpected pod change", comment: "Format string for unexpected pod change") case .activationTimeExceeded: return LocalizedString("Activation time exceeded", comment: "Format string for activation time exceeded") case .rssiTooLow: // occurs when RileyLink is too far from pod for reliable pairing, but can sometimes occur at other distances & positions return LocalizedString("Poor signal strength", comment: "Format string for poor pod signal strength") case .rssiTooHigh: // only occurs when RileyLink is too close to the pod for reliable pairing return LocalizedString("Signal strength too high", comment: "Format string for pod signal strength too high") case .diagnosticMessage(let str): return str case .podIncompatible(let str): return str } } // public var failureReason: String? { // return nil // } public var recoverySuggestion: String? { switch self { case .noPodPaired: return nil case .invalidData: return nil case .noResponse: return LocalizedString("Please try repositioning the pod or the RileyLink and try again", comment: "Recovery suggestion when no response is received from pod") case .emptyResponse: return nil case .podAckedInsteadOfReturningResponse: return LocalizedString("Try again", comment: "Recovery suggestion when ack received instead of response") case .unexpectedPacketType: return nil case .unexpectedResponse: return nil case .unknownResponseType: return nil case .invalidAddress: return LocalizedString("Crosstalk possible. Please move to a new location and try again", comment: "Recovery suggestion when unexpected address received") case .noRileyLinkAvailable: return LocalizedString("Make sure your RileyLink is nearby and powered on", comment: "Recovery suggestion when no RileyLink is available") case .unfinalizedBolus: return LocalizedString("Wait for existing bolus to finish, or cancel bolus", comment: "Recovery suggestion when operation could not be completed due to existing bolus in progress") case .unfinalizedTempBasal: return LocalizedString("Wait for existing temp basal to finish, or suspend to cancel", comment: "Recovery suggestion when operation could not be completed due to existing temp basal in progress") case .nonceResyncFailed: return nil case .podSuspended: return nil case .podFault: return nil case .commsError: return nil case .rejectedMessage: return nil case .podChange: return LocalizedString("Please bring only original pod in range or deactivate original pod", comment: "Recovery suggestion on unexpected pod change") case .activationTimeExceeded: return nil case .rssiTooLow: return LocalizedString("Please reposition the RileyLink relative to the pod", comment: "Recovery suggestion when pairing signal strength is too low") case .rssiTooHigh: return LocalizedString("Please reposition the RileyLink further from the pod", comment: "Recovery suggestion when pairing signal strength is too high") case .diagnosticMessage: return nil case .podIncompatible: return nil } } public var isFaulted: Bool { switch self { case .podFault, .activationTimeExceeded, .podIncompatible: return true default: return false } } } public protocol PodCommsSessionDelegate: AnyObject { func podCommsSession(_ podCommsSession: PodCommsSession, didChange state: PodState) } public class PodCommsSession { private let useCancelNoneForStatus: Bool = false // whether to always use a cancel none to get status public let log = OSLog(category: "PodCommsSession") private var podState: PodState { didSet { assertOnSessionQueue() delegate.podCommsSession(self, didChange: podState) } } private unowned let delegate: PodCommsSessionDelegate private var transport: MessageTransport init(podState: PodState, transport: MessageTransport, delegate: PodCommsSessionDelegate) { self.podState = podState self.transport = transport self.delegate = delegate self.transport.delegate = self } // Handles updating PodState on first pod fault seen private func handlePodFault(fault: DetailedStatus) { if self.podState.fault == nil { self.podState.fault = fault // save the first fault returned handleCancelDosing(deliveryType: .all, bolusNotDelivered: fault.bolusNotDelivered) podState.updateFromDetailedStatusResponse(fault) } log.error("Pod Fault: %@", String(describing: fault)) } // Will throw either PodCommsError.podFault or PodCommsError.activationTimeExceeded private func throwPodFault(fault: DetailedStatus) throws { handlePodFault(fault: fault) if fault.podProgressStatus == .activationTimeExceeded { // avoids a confusing "No fault" error when activation time is exceeded throw PodCommsError.activationTimeExceeded } throw PodCommsError.podFault(fault: fault) } /// Performs a message exchange, handling nonce resync, pod faults /// /// - Parameters: /// - messageBlocks: The message blocks to send /// - confirmationBeepType: If specified, type of confirmation beep to append as a separate beep message block /// - expectFollowOnMessage: If true, the pod will expect another message within 4 minutes, or will alarm with an 0x33 (51) fault. /// - Returns: The received message response /// - Throws: /// - PodCommsError.noResponse /// - PodCommsError.podFault /// - PodCommsError.unexpectedResponse /// - PodCommsError.rejectedMessage /// - PodCommsError.nonceResyncFailed /// - MessageError /// - RileyLinkDeviceError func send<T: MessageBlock>(_ messageBlocks: [MessageBlock], confirmationBeepType: BeepConfigType? = nil, expectFollowOnMessage: Bool = false) throws -> T { var triesRemaining = 2 // Retries only happen for nonce resync var blocksToSend = messageBlocks // If a confirmation beep type was specified & pod isn't faulted, append a beep config message block to emit the requested beep type if let confirmationBeepType = confirmationBeepType, podState.isFaulted == false { let confirmationBeepBlock = BeepConfigCommand(beepConfigType: confirmationBeepType, basalCompletionBeep: true, tempBasalCompletionBeep: false, bolusCompletionBeep: true) blocksToSend += [confirmationBeepBlock] } if blocksToSend.contains(where: { $0 as? NonceResyncableMessageBlock != nil }) { podState.advanceToNextNonce() } let messageNumber = transport.messageNumber var sentNonce: UInt32? while (triesRemaining > 0) { triesRemaining -= 1 for command in blocksToSend { if let nonceBlock = command as? NonceResyncableMessageBlock { sentNonce = nonceBlock.nonce break // N.B. all nonce commands in single message should have the same value } } let message = Message(address: podState.address, messageBlocks: blocksToSend, sequenceNum: messageNumber, expectFollowOnMessage: expectFollowOnMessage) let response = try transport.sendMessage(message) // Simulate fault //let podInfoResponse = try PodInfoResponse(encodedData: Data(hexadecimalString: "0216020d0000000000ab6a038403ff03860000285708030d0000")!) //let response = Message(address: podState.address, messageBlocks: [podInfoResponse], sequenceNum: message.sequenceNum) if let responseMessageBlock = response.messageBlocks[0] as? T { log.info("POD Response: %@", String(describing: responseMessageBlock)) return responseMessageBlock } if let fault = response.fault { try throwPodFault(fault: fault) // always throws } let responseType = response.messageBlocks[0].blockType guard let errorResponse = response.messageBlocks[0] as? ErrorResponse else { log.error("Unexpected response: %{public}@", String(describing: response.messageBlocks[0])) throw PodCommsError.unexpectedResponse(response: responseType) } switch errorResponse.errorResponseType { case .badNonce(let nonceResyncKey): guard let sentNonce = sentNonce else { log.error("Unexpected bad nonce response: %{public}@", String(describing: response.messageBlocks[0])) throw PodCommsError.unexpectedResponse(response: responseType) } podState.resyncNonce(syncWord: nonceResyncKey, sentNonce: sentNonce, messageSequenceNum: message.sequenceNum) log.info("resyncNonce(syncWord: 0x%02x, sentNonce: 0x%04x, messageSequenceNum: %d) -> 0x%04x", nonceResyncKey, sentNonce, message.sequenceNum, podState.currentNonce) blocksToSend = blocksToSend.map({ (block) -> MessageBlock in if var resyncableBlock = block as? NonceResyncableMessageBlock { log.info("Replaced old nonce 0x%04x with resync nonce 0x%04x", resyncableBlock.nonce, podState.currentNonce) resyncableBlock.nonce = podState.currentNonce return resyncableBlock } return block }) podState.advanceToNextNonce() break case .nonretryableError(let errorCode, let faultEventCode, let podProgress): log.error("Command error: code %u, %{public}@, pod progress %{public}@", errorCode, String(describing: faultEventCode), String(describing: podProgress)) throw PodCommsError.rejectedMessage(errorCode: errorCode) } } throw PodCommsError.nonceResyncFailed } // Returns time at which prime is expected to finish. public func prime() throws -> TimeInterval { let primeDuration: TimeInterval = .seconds(Pod.primeUnits / Pod.primeDeliveryRate) + 3 // as per PDM // If priming has never been attempted on this pod, handle the pre-prime setup tasks. // A FaultConfig can only be done before the prime bolus or the pod will generate an 049 fault. if podState.setupProgress.primingNeverAttempted { // This FaultConfig command will set Tab5[$16] to 0 during pairing, which disables $6x faults let _: StatusResponse = try send([FaultConfigCommand(nonce: podState.currentNonce, tab5Sub16: 0, tab5Sub17: 0)]) // Set up the finish pod setup reminder alert which beeps every 5 minutes for 1 hour let finishSetupReminder = PodAlert.finishSetupReminder try configureAlerts([finishSetupReminder]) } else { // Not the first time through, check to see if prime bolus was successfully started let status: StatusResponse = try send([GetStatusCommand()]) podState.updateFromStatusResponse(status) if status.podProgressStatus == .priming || status.podProgressStatus == .primingCompleted { podState.setupProgress = .priming return podState.primeFinishTime?.timeIntervalSinceNow ?? primeDuration } } // Mark Pod.primeUnits (2.6U) bolus delivery with Pod.primeDeliveryRate (1) between pulses for prime let primeFinishTime = Date() + primeDuration podState.primeFinishTime = primeFinishTime podState.setupProgress = .startingPrime let timeBetweenPulses = TimeInterval(seconds: Pod.secondsPerPrimePulse) let bolusSchedule = SetInsulinScheduleCommand.DeliverySchedule.bolus(units: Pod.primeUnits, timeBetweenPulses: timeBetweenPulses) let scheduleCommand = SetInsulinScheduleCommand(nonce: podState.currentNonce, deliverySchedule: bolusSchedule) let bolusExtraCommand = BolusExtraCommand(units: Pod.primeUnits, timeBetweenPulses: timeBetweenPulses) let status: StatusResponse = try send([scheduleCommand, bolusExtraCommand]) podState.updateFromStatusResponse(status) podState.setupProgress = .priming return primeFinishTime.timeIntervalSinceNow } public func programInitialBasalSchedule(_ basalSchedule: BasalSchedule, scheduleOffset: TimeInterval) throws { if podState.setupProgress == .settingInitialBasalSchedule { // We started basal schedule programming, but didn't get confirmation somehow, so check status let status: StatusResponse = try send([GetStatusCommand()]) podState.updateFromStatusResponse(status) if status.podProgressStatus == .basalInitialized { podState.setupProgress = .initialBasalScheduleSet podState.finalizedDoses.append(UnfinalizedDose(resumeStartTime: Date(), scheduledCertainty: .certain, insulinType: podState.insulinType)) return } } podState.setupProgress = .settingInitialBasalSchedule // Set basal schedule let _ = try setBasalSchedule(schedule: basalSchedule, scheduleOffset: scheduleOffset) podState.setupProgress = .initialBasalScheduleSet podState.finalizedDoses.append(UnfinalizedDose(resumeStartTime: Date(), scheduledCertainty: .certain, insulinType: podState.insulinType)) } @discardableResult private func configureAlerts(_ alerts: [PodAlert]) throws -> StatusResponse { let configurations = alerts.map { $0.configuration } let configureAlerts = ConfigureAlertsCommand(nonce: podState.currentNonce, configurations: configurations) let status: StatusResponse = try send([configureAlerts]) for alert in alerts { podState.registerConfiguredAlert(slot: alert.configuration.slot, alert: alert) } podState.updateFromStatusResponse(status) return status } // emits the specified beep type and sets the completion beep flags, doesn't throw public func beepConfig(beepConfigType: BeepConfigType, basalCompletionBeep: Bool, tempBasalCompletionBeep: Bool, bolusCompletionBeep: Bool) -> Result<StatusResponse, Error> { if let fault = self.podState.fault { log.info("Skip beep config with faulted pod") return .failure(PodCommsError.podFault(fault: fault)) } let beepConfigCommand = BeepConfigCommand(beepConfigType: beepConfigType, basalCompletionBeep: basalCompletionBeep, tempBasalCompletionBeep: tempBasalCompletionBeep, bolusCompletionBeep: bolusCompletionBeep) do { let statusResponse: StatusResponse = try send([beepConfigCommand]) podState.updateFromStatusResponse(statusResponse) return .success(statusResponse) } catch let error { return .failure(error) } } private func markSetupProgressCompleted(statusResponse: StatusResponse) { if (podState.setupProgress != .completed) { podState.setupProgress = .completed podState.setupUnitsDelivered = statusResponse.insulin // stash the current insulin delivered value as the baseline log.info("Total setup units delivered: %@", String(describing: statusResponse.insulin)) } } public func insertCannula() throws -> TimeInterval { let cannulaInsertionUnits = Pod.cannulaInsertionUnits + Pod.cannulaInsertionUnitsExtra let insertionWait: TimeInterval = .seconds(cannulaInsertionUnits / Pod.primeDeliveryRate) guard let activatedAt = podState.activatedAt else { throw PodCommsError.noPodPaired } if podState.setupProgress == .startingInsertCannula || podState.setupProgress == .cannulaInserting { // We started cannula insertion, but didn't get confirmation somehow, so check status let status: StatusResponse = try send([GetStatusCommand()]) if status.podProgressStatus == .insertingCannula { podState.setupProgress = .cannulaInserting podState.updateFromStatusResponse(status) return insertionWait // Not sure when it started, wait full time to be sure } if status.podProgressStatus.readyForDelivery { markSetupProgressCompleted(statusResponse: status) podState.updateFromStatusResponse(status) return TimeInterval(0) // Already done; no need to wait } podState.updateFromStatusResponse(status) } else { // Configure all the non-optional Pod Alarms let expirationTime = activatedAt + Pod.nominalPodLife let timeUntilExpirationAdvisory = expirationTime.timeIntervalSinceNow let expirationAdvisoryAlarm = PodAlert.expirationAdvisoryAlarm(alarmTime: timeUntilExpirationAdvisory, duration: Pod.expirationAdvisoryWindow) let endOfServiceTime = activatedAt + Pod.serviceDuration let shutdownImminentAlarm = PodAlert.shutdownImminentAlarm((endOfServiceTime - Pod.endOfServiceImminentWindow).timeIntervalSinceNow) try configureAlerts([expirationAdvisoryAlarm, shutdownImminentAlarm]) } // Mark cannulaInsertionUnits (0.5U) bolus delivery with Pod.secondsPerPrimePulse (1) between pulses for cannula insertion let timeBetweenPulses = TimeInterval(seconds: Pod.secondsPerPrimePulse) let bolusSchedule = SetInsulinScheduleCommand.DeliverySchedule.bolus(units: cannulaInsertionUnits, timeBetweenPulses: timeBetweenPulses) let bolusScheduleCommand = SetInsulinScheduleCommand(nonce: podState.currentNonce, deliverySchedule: bolusSchedule) podState.setupProgress = .startingInsertCannula let bolusExtraCommand = BolusExtraCommand(units: cannulaInsertionUnits, timeBetweenPulses: timeBetweenPulses) let status2: StatusResponse = try send([bolusScheduleCommand, bolusExtraCommand]) podState.updateFromStatusResponse(status2) podState.setupProgress = .cannulaInserting return insertionWait } public func checkInsertionCompleted() throws { if podState.setupProgress == .cannulaInserting { let response: StatusResponse = try send([GetStatusCommand()]) if response.podProgressStatus.readyForDelivery { markSetupProgressCompleted(statusResponse: response) } podState.updateFromStatusResponse(response) } } // Throws SetBolusError public enum DeliveryCommandResult { case success(statusResponse: StatusResponse) case certainFailure(error: PodCommsError) case uncertainFailure(error: PodCommsError) } public enum CancelDeliveryResult { case success(statusResponse: StatusResponse, canceledDose: UnfinalizedDose?) case certainFailure(error: PodCommsError) case uncertainFailure(error: PodCommsError) } public func bolus(units: Double, automatic: Bool, acknowledgementBeep: Bool = false, completionBeep: Bool = false, programReminderInterval: TimeInterval = 0) -> DeliveryCommandResult { let timeBetweenPulses = TimeInterval(seconds: Pod.secondsPerBolusPulse) let bolusSchedule = SetInsulinScheduleCommand.DeliverySchedule.bolus(units: units, timeBetweenPulses: timeBetweenPulses) let bolusScheduleCommand = SetInsulinScheduleCommand(nonce: podState.currentNonce, deliverySchedule: bolusSchedule) guard podState.unfinalizedBolus == nil else { return DeliveryCommandResult.certainFailure(error: .unfinalizedBolus) } // Between bluetooth and the radio and firmware, about 1.2s on average passes before we start tracking let commsOffset = TimeInterval(seconds: -1.5) let bolusExtraCommand = BolusExtraCommand(units: units, timeBetweenPulses: timeBetweenPulses, acknowledgementBeep: acknowledgementBeep, completionBeep: completionBeep, programReminderInterval: programReminderInterval) do { let statusResponse: StatusResponse = try send([bolusScheduleCommand, bolusExtraCommand]) podState.unfinalizedBolus = UnfinalizedDose(bolusAmount: units, startTime: Date().addingTimeInterval(commsOffset), scheduledCertainty: .certain, insulinType: podState.insulinType, automatic: automatic) podState.updateFromStatusResponse(statusResponse) return DeliveryCommandResult.success(statusResponse: statusResponse) } catch PodCommsError.nonceResyncFailed { return DeliveryCommandResult.certainFailure(error: PodCommsError.nonceResyncFailed) } catch PodCommsError.rejectedMessage(let errorCode) { return DeliveryCommandResult.certainFailure(error: PodCommsError.rejectedMessage(errorCode: errorCode)) } catch let error { self.log.debug("Uncertain result bolusing") // Attempt to verify bolus let podCommsError = error as? PodCommsError ?? PodCommsError.commsError(error: error) guard let status = try? getStatus() else { self.log.debug("Status check failed; could not resolve bolus uncertainty") podState.unfinalizedBolus = UnfinalizedDose(bolusAmount: units, startTime: Date(), scheduledCertainty: .uncertain, insulinType: podState.insulinType, automatic: automatic) return DeliveryCommandResult.uncertainFailure(error: podCommsError) } if status.deliveryStatus.bolusing { self.log.debug("getStatus resolved bolus uncertainty (succeeded)") podState.unfinalizedBolus = UnfinalizedDose(bolusAmount: units, startTime: Date().addingTimeInterval(commsOffset), scheduledCertainty: .certain, insulinType: podState.insulinType, automatic: automatic) return DeliveryCommandResult.success(statusResponse: status) } else { self.log.debug("getStatus resolved bolus uncertainty (failed)") return DeliveryCommandResult.certainFailure(error: podCommsError) } } } public func setTempBasal(rate: Double, duration: TimeInterval, acknowledgementBeep: Bool = false, completionBeep: Bool = false, programReminderInterval: TimeInterval = 0) -> DeliveryCommandResult { let tempBasalCommand = SetInsulinScheduleCommand(nonce: podState.currentNonce, tempBasalRate: rate, duration: duration) let tempBasalExtraCommand = TempBasalExtraCommand(rate: rate, duration: duration, acknowledgementBeep: acknowledgementBeep, completionBeep: completionBeep, programReminderInterval: programReminderInterval) guard podState.unfinalizedBolus?.isFinished != false else { return DeliveryCommandResult.certainFailure(error: .unfinalizedBolus) } do { let status: StatusResponse = try send([tempBasalCommand, tempBasalExtraCommand]) podState.unfinalizedTempBasal = UnfinalizedDose(tempBasalRate: rate, startTime: Date(), duration: duration, scheduledCertainty: .certain, insulinType: podState.insulinType) podState.updateFromStatusResponse(status) return DeliveryCommandResult.success(statusResponse: status) } catch PodCommsError.nonceResyncFailed { return DeliveryCommandResult.certainFailure(error: PodCommsError.nonceResyncFailed) } catch PodCommsError.rejectedMessage(let errorCode) { return DeliveryCommandResult.certainFailure(error: PodCommsError.rejectedMessage(errorCode: errorCode)) } catch let error { podState.unfinalizedTempBasal = UnfinalizedDose(tempBasalRate: rate, startTime: Date(), duration: duration, scheduledCertainty: .uncertain, insulinType: podState.insulinType) return DeliveryCommandResult.uncertainFailure(error: error as? PodCommsError ?? PodCommsError.commsError(error: error)) } } @discardableResult private func handleCancelDosing(deliveryType: CancelDeliveryCommand.DeliveryType, bolusNotDelivered: Double) -> UnfinalizedDose? { var canceledDose: UnfinalizedDose? = nil let now = Date() if deliveryType.contains(.basal) { podState.unfinalizedSuspend = UnfinalizedDose(suspendStartTime: now, scheduledCertainty: .certain) podState.suspendState = .suspended(now) } if let unfinalizedTempBasal = podState.unfinalizedTempBasal, let finishTime = unfinalizedTempBasal.finishTime, deliveryType.contains(.tempBasal), finishTime > now { podState.unfinalizedTempBasal?.cancel(at: now) if !deliveryType.contains(.basal) { podState.suspendState = .resumed(now) } canceledDose = podState.unfinalizedTempBasal log.info("Interrupted temp basal: %@", String(describing: canceledDose)) } if let unfinalizedBolus = podState.unfinalizedBolus, let finishTime = unfinalizedBolus.finishTime, deliveryType.contains(.bolus), finishTime > now { podState.unfinalizedBolus?.cancel(at: now, withRemaining: bolusNotDelivered) canceledDose = podState.unfinalizedBolus log.info("Interrupted bolus: %@", String(describing: canceledDose)) } return canceledDose } // Suspends insulin delivery and sets appropriate podSuspendedReminder & suspendTimeExpired alerts. // An expected suspend time of 0 is an untimed suspend which only uses podSuspendedReminder alert beeps. // An expected suspend time of > 0 and <= 5 minutes will only use suspendTimeExpired alert beeps. public func suspendDelivery(suspendTime: TimeInterval = 0, confirmationBeepType: BeepConfigType? = nil) -> CancelDeliveryResult { do { var alertConfigurations: [AlertConfiguration] = [] // podSuspendedReminder provides a periodic pod suspended reminder beep until the specified suspend time. let podSuspendedReminder = PodAlert.podSuspendedReminder(active: true, suspendTime: suspendTime) let usePodSuspendedReminder = suspendTime == 0 || suspendTime > .minutes(5) // untimed or long enough suspend if usePodSuspendedReminder { alertConfigurations += [podSuspendedReminder.configuration] } // suspendTimeExpired provides suspend time expired alert beeping after the expected suspend time has passed. let suspendTimeExpired = PodAlert.suspendTimeExpired(suspendTime: suspendTime) let useSuspendTimeExpired = suspendTime > 0 // timed suspend if useSuspendTimeExpired { alertConfigurations += [suspendTimeExpired.configuration] } let configureAlerts = ConfigureAlertsCommand(nonce: podState.currentNonce, configurations: alertConfigurations) let cancelDeliveryCommand = CancelDeliveryCommand(nonce: podState.currentNonce, deliveryType: .all, beepType: .noBeep) let status: StatusResponse = try send([cancelDeliveryCommand, configureAlerts], confirmationBeepType: confirmationBeepType) let canceledDose = handleCancelDosing(deliveryType: .all, bolusNotDelivered: status.bolusNotDelivered) podState.updateFromStatusResponse(status) if usePodSuspendedReminder { podState.registerConfiguredAlert(slot: podSuspendedReminder.configuration.slot, alert: podSuspendedReminder) } if useSuspendTimeExpired { podState.registerConfiguredAlert(slot: suspendTimeExpired.configuration.slot, alert: suspendTimeExpired) } return CancelDeliveryResult.success(statusResponse: status, canceledDose: canceledDose) } catch PodCommsError.nonceResyncFailed { return CancelDeliveryResult.certainFailure(error: PodCommsError.nonceResyncFailed) } catch PodCommsError.rejectedMessage(let errorCode) { return CancelDeliveryResult.certainFailure(error: PodCommsError.rejectedMessage(errorCode: errorCode)) } catch let error { podState.unfinalizedSuspend = UnfinalizedDose(suspendStartTime: Date(), scheduledCertainty: .uncertain) return CancelDeliveryResult.uncertainFailure(error: error as? PodCommsError ?? PodCommsError.commsError(error: error)) } } // Cancels any suspend related alerts, should be called when resuming after using suspendDelivery() @discardableResult public func cancelSuspendAlerts() throws -> StatusResponse { do { let podSuspendedReminder = PodAlert.podSuspendedReminder(active: false, suspendTime: 0) let suspendTimeExpired = PodAlert.suspendTimeExpired(suspendTime: 0) // A suspendTime of 0 deactivates this alert let status = try configureAlerts([podSuspendedReminder, suspendTimeExpired]) return status } catch let error { throw error } } // Cancel beeping can be done implemented using beepType (for a single delivery type) or a separate confirmation beep message block (for cancel all). // N.B., Using the built-in cancel delivery command beepType method when cancelling all insulin delivery will emit 3 different sets of cancel beeps!!! public func cancelDelivery(deliveryType: CancelDeliveryCommand.DeliveryType, beepType: BeepType = .noBeep, confirmationBeepType: BeepConfigType? = nil) -> CancelDeliveryResult { do { let cancelDeliveryCommand = CancelDeliveryCommand(nonce: podState.currentNonce, deliveryType: deliveryType, beepType: beepType) let status: StatusResponse = try send([cancelDeliveryCommand], confirmationBeepType: confirmationBeepType) let canceledDose = handleCancelDosing(deliveryType: deliveryType, bolusNotDelivered: status.bolusNotDelivered) podState.updateFromStatusResponse(status) return CancelDeliveryResult.success(statusResponse: status, canceledDose: canceledDose) } catch PodCommsError.nonceResyncFailed { return CancelDeliveryResult.certainFailure(error: PodCommsError.nonceResyncFailed) } catch PodCommsError.rejectedMessage(let errorCode) { return CancelDeliveryResult.certainFailure(error: PodCommsError.rejectedMessage(errorCode: errorCode)) } catch let error { podState.unfinalizedSuspend = UnfinalizedDose(suspendStartTime: Date(), scheduledCertainty: .uncertain) return CancelDeliveryResult.uncertainFailure(error: error as? PodCommsError ?? PodCommsError.commsError(error: error)) } } public func testingCommands(confirmationBeepType: BeepConfigType? = nil) throws { try cancelNone(confirmationBeepType: confirmationBeepType) // reads status & verifies nonce by doing a cancel none } public func setTime(timeZone: TimeZone, basalSchedule: BasalSchedule, date: Date, acknowledgementBeep: Bool = false, completionBeep: Bool = false) throws -> StatusResponse { let result = cancelDelivery(deliveryType: .all) switch result { case .certainFailure(let error): throw error case .uncertainFailure(let error): throw error case .success: let scheduleOffset = timeZone.scheduleOffset(forDate: date) let status = try setBasalSchedule(schedule: basalSchedule, scheduleOffset: scheduleOffset, acknowledgementBeep: acknowledgementBeep, completionBeep: completionBeep) return status } } public func setBasalSchedule(schedule: BasalSchedule, scheduleOffset: TimeInterval, acknowledgementBeep: Bool = false, completionBeep: Bool = false, programReminderInterval: TimeInterval = 0) throws -> StatusResponse { let basalScheduleCommand = SetInsulinScheduleCommand(nonce: podState.currentNonce, basalSchedule: schedule, scheduleOffset: scheduleOffset) let basalExtraCommand = BasalScheduleExtraCommand.init(schedule: schedule, scheduleOffset: scheduleOffset, acknowledgementBeep: acknowledgementBeep, completionBeep: completionBeep, programReminderInterval: programReminderInterval) do { let status: StatusResponse = try send([basalScheduleCommand, basalExtraCommand]) let now = Date() podState.suspendState = .resumed(now) podState.unfinalizedResume = UnfinalizedDose(resumeStartTime: now, scheduledCertainty: .certain, insulinType: podState.insulinType) podState.updateFromStatusResponse(status) return status } catch PodCommsError.nonceResyncFailed { throw PodCommsError.nonceResyncFailed } catch PodCommsError.rejectedMessage(let errorCode) { throw PodCommsError.rejectedMessage(errorCode: errorCode) } catch let error { podState.unfinalizedResume = UnfinalizedDose(resumeStartTime: Date(), scheduledCertainty: .uncertain, insulinType: podState.insulinType) throw error } } public func resumeBasal(schedule: BasalSchedule, scheduleOffset: TimeInterval, acknowledgementBeep: Bool = false, completionBeep: Bool = false, programReminderInterval: TimeInterval = 0) throws -> StatusResponse { let status = try setBasalSchedule(schedule: schedule, scheduleOffset: scheduleOffset, acknowledgementBeep: acknowledgementBeep, completionBeep: completionBeep, programReminderInterval: programReminderInterval) podState.suspendState = .resumed(Date()) return status } // use cancelDelivery with .none to get status as well as to validate & advance the nonce // Throws PodCommsError @discardableResult public func cancelNone(confirmationBeepType: BeepConfigType? = nil) throws -> StatusResponse { var statusResponse: StatusResponse let cancelResult: CancelDeliveryResult = cancelDelivery(deliveryType: .none, confirmationBeepType: confirmationBeepType) switch cancelResult { case .certainFailure(let error): throw error case .uncertainFailure(let error): throw error case .success(let response, _): statusResponse = response } podState.updateFromStatusResponse(statusResponse) return statusResponse } // Throws PodCommsError @discardableResult public func getStatus(confirmationBeepType: BeepConfigType? = nil) throws -> StatusResponse { if useCancelNoneForStatus { return try cancelNone(confirmationBeepType: confirmationBeepType) // functional replacement for getStatus() } let statusResponse: StatusResponse = try send([GetStatusCommand()], confirmationBeepType: confirmationBeepType) podState.updateFromStatusResponse(statusResponse) return statusResponse } @discardableResult public func getDetailedStatus(confirmationBeepType: BeepConfigType? = nil) throws -> DetailedStatus { let infoResponse: PodInfoResponse = try send([GetStatusCommand(podInfoType: .detailedStatus)], confirmationBeepType: confirmationBeepType) guard let detailedStatus = infoResponse.podInfo as? DetailedStatus else { throw PodCommsError.unexpectedResponse(response: .podInfoResponse) } if detailedStatus.isFaulted && self.podState.fault == nil { // just detected that the pod has faulted, handle setting the fault state but don't throw handlePodFault(fault: detailedStatus) } else { podState.updateFromDetailedStatusResponse(detailedStatus) } return detailedStatus } public func finalizeFinishedDoses() { podState.finalizeFinishedDoses() } @discardableResult public func readPodInfo(podInfoResponseSubType: PodInfoResponseSubType, confirmationBeepType: BeepConfigType? = nil) throws -> PodInfoResponse { let podInfoCommand = GetStatusCommand(podInfoType: podInfoResponseSubType) let podInfoResponse: PodInfoResponse = try send([podInfoCommand], confirmationBeepType: confirmationBeepType) return podInfoResponse } public func deactivatePod() throws { // Don't try to cancel if the pod hasn't completed its setup as it will either receive no response // (pod progress state <= 2) or creates a $31 pod fault (pod progress states 3 through 7). if podState.setupProgress == .completed && podState.fault == nil && !podState.isSuspended { let result = cancelDelivery(deliveryType: .all) switch result { case .certainFailure(let error): throw error case .uncertainFailure(let error): throw error default: break } } if podState.fault != nil { // All the dosing cleanup from the fault should have already been // handled in handlePodFault() when podState.fault was initialized. do { // read the most recent pulse log entries for later analysis, but don't throw on error try readPodInfo(podInfoResponseSubType: .pulseLogRecent) } catch let error { log.error("Read pulse log failed: %@", String(describing: error)) } } let deactivatePod = DeactivatePodCommand(nonce: podState.currentNonce) do { let _: StatusResponse = try send([deactivatePod]) } catch let error as PodCommsError { switch error { case .podFault, .unexpectedResponse: break default: throw error } } } public func acknowledgeAlerts(alerts: AlertSet, confirmationBeepType: BeepConfigType? = nil) throws -> [AlertSlot: PodAlert] { let cmd = AcknowledgeAlertCommand(nonce: podState.currentNonce, alerts: alerts) let status: StatusResponse = try send([cmd], confirmationBeepType: confirmationBeepType) podState.updateFromStatusResponse(status) return podState.activeAlerts } func dosesForStorage(_ storageHandler: ([UnfinalizedDose]) -> Bool) { assertOnSessionQueue() let dosesToStore = podState.dosesToStore if storageHandler(dosesToStore) { log.info("Stored doses: %@", String(describing: dosesToStore)) self.podState.finalizedDoses.removeAll() } } public func assertOnSessionQueue() { transport.assertOnSessionQueue() } } extension PodCommsSession: MessageTransportDelegate { func messageTransport(_ messageTransport: MessageTransport, didUpdate state: MessageTransportState) { messageTransport.assertOnSessionQueue() podState.messageTransportState = state } }
52.934466
238
0.692306
e2e839e2da7cdc5af09f00db2b3e3c929acbe71a
1,604
extension Application { /// Controls application's configured caches. /// /// app.caches.use(.memory) /// public var caches: Caches { .init(application: self) } /// Current application cache. See `Request.cache` for caching in request handlers. public var cache: Cache { guard let makeCache = self.caches.storage.makeCache else { fatalError("No cache configured. Configure with app.caches.use(...)") } return makeCache(self) } public struct Caches { public struct Provider { let run: (Application) -> () public init(_ run: @escaping (Application) -> ()) { self.run = run } } final class Storage { var makeCache: ((Application) -> Cache)? init() { } } struct Key: StorageKey { typealias Value = Storage } public let application: Application public func use(_ provider: Provider) { provider.run(self.application) } public func use(_ makeCache: @escaping (Application) -> (Cache)) { self.storage.makeCache = makeCache } func initialize() { self.application.storage[Key.self] = .init() self.use(.memory) } var storage: Storage { guard let storage = self.application.storage[Key.self] else { fatalError("Caches not configured. Configure with app.caches.initialize()") } return storage } } }
27.186441
91
0.539277
cc098f59a1f78be03ef6758616276b95a49180bc
489
// // MenuAbout.swift // LanguBrain // // Created by Anessa Petteruti on 7/7/19. // Copyright © 2019 Sahand Edrisian. All rights reserved. // import UIKit class MenuAbout: UITableViewController { @IBAction func goShop(_ sender: Any) { guard let url = URL(string: "https://apps.apple.com/tt/developer/anessa-petteruti/id1464196411") else { return } UIApplication.shared.open(url) } override func viewDidLoad() { super.viewDidLoad() } }
19.56
120
0.658487
e82fac7e72f59932b8abd426c81f87163d422bae
399
// // Utils.swift // SwiftBilibili // // Created by luowen on 2020/9/29. // Copyright © 2020 luowen. All rights reserved. // import UIKit import SwiftDate struct Utils { /// 当前app时间 static func currentAppTime() -> TimeInterval { return Date().timeIntervalSince1970 } /// 是否登录 static var isLogin: Bool { return !UserDefaultsManager.user.token.isEmpty } }
19
54
0.649123
f9c10e47e0a459b5bb792954fd3410976e38286d
560
// // ServerDetails.swift // AWPresentation // // Copyright © 2016 VMware, Inc. All rights reserved. This product is protected // by copyright and intellectual property laws in the United States and other // countries as well as by international treaties. VMware products are covered // by one or more patents listed at http://www.vmware.com/go/patents. // struct ServerDetails { var serverURL : String var groupID : String init(serverURL: String, groupID: String) { self.serverURL = serverURL self.groupID = groupID } }
29.473684
80
0.707143
2f9ec0e1c34e419c07405878255a6f50068d3b85
430
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class B<T where A: T } protocol A : B
35.833333
78
0.74186
ccf26914b889963cfbf9efcbcf0b0e6c9095050c
7,579
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import gizmo // Test mangling of Unicode identifiers. // These examples are from RFC 3492, which defines the Punycode encoding used // by name mangling. // CHECK-LABEL: sil hidden @_T08mangling0022egbpdajGbuEbxfgehfvwxnyyF func ليهمابتكلموشعربي؟() { } // CHECK-LABEL: sil hidden @_T08mangling0024ihqwcrbEcvIaIdqgAFGpqjyeyyF func 他们为什么不说中文() { } // CHECK-LABEL: sil hidden @_T08mangling0027ihqwctvzcJBfGFJdrssDxIboAybyyF func 他們爲什麽不說中文() { } // CHECK-LABEL: sil hidden @_T08mangling0030Proprostnemluvesky_uybCEdmaEBayyF func Pročprostěnemluvíčesky() { } // <rdar://problem/13757744> Variadic tuples need a different mangling from // non-variadic tuples. // CHECK-LABEL: sil hidden @_T08mangling9r13757744ySaySiG1x_tF func r13757744(x: [Int]) {} // CHECK-LABEL: sil hidden @_T08mangling9r13757744ySi1xd_tF func r13757744(x: Int...) {} // <rdar://problem/13757750> Prefix, postfix, and infix operators need // distinct manglings. prefix operator +- postfix operator +- infix operator +- // CHECK-LABEL: sil hidden @_T08mangling2psopyxlF prefix func +- <T>(a: T) {} // CHECK-LABEL: sil hidden @_T08mangling2psoPyxlF postfix func +- <T>(a: T) {} // CHECK-LABEL: sil hidden @_T08mangling2psoiyx_xtlF func +- <T>(a: T, b: T) {} // CHECK-LABEL: sil hidden @_T08mangling2psopyx1a_x1bt_tlF prefix func +- <T>(_: (a: T, b: T)) {} // CHECK-LABEL: sil hidden @_T08mangling2psoPyx1a_x1bt_tlF postfix func +- <T>(_: (a: T, b: T)) {} infix operator «+» {} // CHECK-LABEL: sil hidden @_T08mangling007p_qcaDcoiS2i_SitF func «+»(a: Int, b: Int) -> Int { return a + b } protocol Foo {} protocol Bar {} // Ensure protocol list manglings are '_' terminated regardless of length // CHECK-LABEL: sil hidden @_T08mangling12any_protocolyypF func any_protocol(_: Any) {} // CHECK-LABEL: sil hidden @_T08mangling12one_protocolyAA3Foo_pF func one_protocol(_: Foo) {} // CHECK-LABEL: sil hidden @_T08mangling18one_protocol_twiceyAA3Foo_p_AaC_ptF func one_protocol_twice(_: Foo, _: Foo) {} // CHECK-LABEL: sil hidden @_T08mangling12two_protocolyAA3Bar_AA3FoopF func two_protocol(_: Foo & Bar) {} // Ensure archetype depths are mangled correctly. class Zim<T> { // CHECK-LABEL: sil hidden @_T08mangling3ZimC4zangyx_qd__tlF func zang<U>(_: T, _: U) {} // CHECK-LABEL: sil hidden @_T08mangling3ZimC4zungyqd___xtlF func zung<U>(_: U, _: T) {} } // Don't crash mangling single-protocol "composition" types. // CHECK-LABEL: sil hidden @_T08mangling27single_protocol_compositionyAA3Foo_p1x_tF func single_protocol_composition(x: protocol<Foo>) {} // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} // Clang-imported classes and protocols get mangled into a magic 'So' context // to make collisions into link errors. <rdar://problem/14221244> // CHECK-LABEL: sil hidden @_T08mangling28uses_objc_class_and_protocolySo8NSObjectC1o_So8NSAnsing_p1ptF func uses_objc_class_and_protocol(o: NSObject, p: NSAnsing) {} // Clang-imported structs get mangled using their Clang module name. // FIXME: Temporarily mangles everything into the virtual module __C__ // <rdar://problem/14221244> // CHECK-LABEL: sil hidden @_T08mangling17uses_clang_structySC6NSRectV1r_tF func uses_clang_struct(r: NSRect) {} // CHECK-LABEL: sil hidden @_T08mangling14uses_optionalss7UnicodeO6ScalarVSgSiSg1x_tF func uses_optionals(x: Int?) -> UnicodeScalar? { return nil } enum GenericUnion<T> { // CHECK-LABEL: sil shared [transparent] @_T08mangling12GenericUnionO3FooACyxGSicAEmlF case Foo(Int) } func instantiateGenericUnionConstructor<T>(_ t: T) { _ = GenericUnion<T>.Foo } struct HasVarInit { static var state = true && false } // CHECK-LABEL: // function_ref implicit closure #1 : @autoclosure () throws -> Swift.Bool in variable initialization expression of static mangling.HasVarInit.state : Swift.Bool // CHECK-NEXT: function_ref @_T08mangling10HasVarInitV5stateSbvpZfiSbyKXKfu_ // auto_closures should not collide with the equivalent non-auto_closure // function type. // CHECK-LABEL: sil hidden @_T08mangling19autoClosureOverloadySiyXK1f_tF : $@convention(thin) (@owned @noescape @callee_owned () -> Int) -> () { func autoClosureOverload(f: @autoclosure () -> Int) {} // CHECK-LABEL: sil hidden @_T08mangling19autoClosureOverloadySiyc1f_tF : $@convention(thin) (@owned @noescape @callee_owned () -> Int) -> () { func autoClosureOverload(f: () -> Int) {} // CHECK-LABEL: sil hidden @_T08mangling24autoClosureOverloadCallsyyF : $@convention(thin) () -> () { func autoClosureOverloadCalls() { // CHECK: function_ref @_T08mangling19autoClosureOverloadySiyXK1f_tF autoClosureOverload(f: 1) // CHECK: function_ref @_T08mangling19autoClosureOverloadySiyc1f_tF autoClosureOverload {1} } // <rdar://problem/16079822> Associated type requirements need to appear in the // mangling. protocol AssocReqt {} protocol HasAssocType { associatedtype Assoc } // CHECK-LABEL: sil hidden @_T08mangling4fooAyxAA12HasAssocTypeRzlF : $@convention(thin) <T where T : HasAssocType> (@in T) -> () func fooA<T: HasAssocType>(_: T) {} // CHECK-LABEL: sil hidden @_T08mangling4fooByxAA12HasAssocTypeRzAA0D4Reqt0D0RpzlF : $@convention(thin) <T where T : HasAssocType, T.Assoc : AssocReqt> (@in T) -> () func fooB<T: HasAssocType>(_: T) where T.Assoc: AssocReqt {} // CHECK-LABEL: sil hidden @_T08mangling2qqoiySi_SitF func ??(x: Int, y: Int) {} struct InstanceAndClassProperty { var property: Int { // CHECK-LABEL: sil hidden @_T08mangling24InstanceAndClassPropertyV8propertySivg get { return 0 } // CHECK-LABEL: sil hidden @_T08mangling24InstanceAndClassPropertyV8propertySivs set {} } static var property: Int { // CHECK-LABEL: sil hidden @_T08mangling24InstanceAndClassPropertyV8propertySivgZ get { return 0 } // CHECK-LABEL: sil hidden @_T08mangling24InstanceAndClassPropertyV8propertySivsZ set {} } } // CHECK-LABEL: sil hidden @_T08mangling6curry1yyF : $@convention(thin) () -> () func curry1() { } // CHECK-LABEL: sil hidden @_T08mangling3barSiyKF : $@convention(thin) () -> (Int, @error Error) func bar() throws -> Int { return 0 } // CHECK-LABEL: sil hidden @_T08mangling12curry1ThrowsyyKF : $@convention(thin) () -> @error Error func curry1Throws() throws { } // CHECK-LABEL: sil hidden @_T08mangling12curry2ThrowsyycyKF : $@convention(thin) () -> (@owned @callee_owned () -> (), @error Error) func curry2Throws() throws -> () -> () { return curry1 } // CHECK-LABEL: sil hidden @_T08mangling6curry3yyKcyF : $@convention(thin) () -> @owned @callee_owned () -> @error Error func curry3() -> () throws -> () { return curry1Throws } // CHECK-LABEL: sil hidden @_T08mangling12curry3ThrowsyyKcyKF : $@convention(thin) () -> (@owned @callee_owned () -> @error Error, @error Error) func curry3Throws() throws -> () throws -> () { return curry1Throws } // CHECK-LABEL: sil hidden @_T08mangling14varargsVsArrayySi3arrd_SS1ntF : $@convention(thin) (@owned Array<Int>, @owned String) -> () func varargsVsArray(arr: Int..., n: String) { } // CHECK-LABEL: sil hidden @_T08mangling14varargsVsArrayySaySiG3arr_SS1ntF : $@convention(thin) (@owned Array<Int>, @owned String) -> () func varargsVsArray(arr: [Int], n: String) { } // CHECK-LABEL: sil hidden @_T08mangling14varargsVsArrayySaySiG3arrd_SS1ntF : $@convention(thin) (@owned Array<Array<Int>>, @owned String) -> () func varargsVsArray(arr: [Int]..., n: String) { }
39.680628
177
0.740599
8f8830d99bd6656d26fd852aecd4dd196bed2d59
723
// // File.swift // Bicisendas // // Created by Pablo Bendersky on 21/08/2018. // Copyright © 2018 Pablo Bendersky. All rights reserved. // import MapKit import GeoJSON class BikeStation: NSObject, MKAnnotation { private var feature: Feature public var coordinate: CLLocationCoordinate2D public var title: String? { guard let stationName = feature.properties["Nombre"] as? String else { return nil } return stationName } init(feature: Feature) { self.feature = feature switch feature.geometry { case .point(let latitude, let longitude): self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } } }
21.264706
94
0.665284
181027bf10342a84e22f8424c32ae9e567f0c818
1,013
// // ComposeViewController.swift // Twitter // // Created by Nuraini Aguse on 2/27/16. // Copyright © 2016 Nuraini Aguse. All rights reserved. // import UIKit class ComposeViewController: UIViewController { @IBOutlet weak var tweetField: UITextField! @IBAction func isTyping(sender: AnyObject) { } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
23.55814
106
0.660415
26139d40c2619369bd45162a86749fa1abf8783a
1,341
// // TabBar.swift // TABTestKit // // Created by Kane Cheshire on 09/09/2019. // import XCTest /// Represents the UITabBar of the app. /// Since most apps generally just have one tab bar, /// you don't need to provide an ID, but you can do so /// if you need to. public struct TabBar: Element { public let id: String? public let parent: Element public let type: XCUIElement.ElementType = .tabBar /// Creates a new TabBar. /// Since most apps generally have just one tab bar, /// you don't need to provide an ID, but you can do so /// if you need to. /// /// - Parameter id: The ID of the tab bar. Defaults to nil. public init(id: String? = nil, parent: Element = App.shared) { self.id = id self.parent = parent } /// "Vends" a button representing a tab. /// Typically the ID is just the title of the button, /// but if you've set a custom identifier or label on the buttons /// you can use that as the ID instead. /// /// /// - Parameter buttonID: The ID of the button. Typically the title of the button. /// - Returns: A button representing a tab in the tab bar. public func button(withID buttonID: String) -> Button { return Button(id: buttonID, parent: self) } } extension TabBar { public var numberOfTabs: Int { await(.exists, .hittable) return underlyingXCUIElement.buttons.count } }
25.301887
83
0.680089
2334e476d22e01b18e5b6458913013c11010931d
1,111
import UIKit import SoraFoundation final class LanguageSelectionInteractor { weak var presenter: LanguageSelectionInteractorOutputProtocol! let localizationManager: LocalizationManagerProtocol init(localizationManager: LocalizationManagerProtocol) { self.localizationManager = localizationManager } var logger: LoggerProtocol? } extension LanguageSelectionInteractor: LanguageSelectionInteractorInputProtocol { func load() { let languages: [Language] = localizationManager.availableLocalizations.map { localization in Language(code: localization) } presenter.didLoad(languages: languages) presenter.didLoad(selectedLanguage: localizationManager.selectedLanguage) } func select(language: Language) -> Bool { if language.code != localizationManager.selectedLocalization { localizationManager.selectedLocalization = language.code presenter.didLoad(selectedLanguage: localizationManager.selectedLanguage) return true } else { return false } } }
28.487179
100
0.721872
d95f0eae9fcf844b9b406ad7e3890750821b7c39
6,444
// // QuickConnect.swift // StandUp-iOS // // Created by Peter on 12/01/19. // Copyright © 2019 BlockchainCommons. All rights reserved. // import Foundation import UIKit class QuickConnect { let aes = AESService() let cd = CoreDataService() var errorBool = Bool() var errorDescription = "" // MARK: QuickConnect url examples // btcstandup://rpcuser:[email protected]:1309/?label=Node%20Name // btcstandup://rpcuser:[email protected]:1309/? // btcstandup://rpcuser:[email protected]:1309? func addNode(vc: UIViewController, url: String, authkey: String, authPubKey: String, completion: @escaping () -> Void) { cd.retrieveEntity(entityName: .nodes) { if !self.cd.errorBool { var host = "" var rpcPassword = "" var rpcUser = "" var label = "StandUp" if let params = URLComponents(string: url)?.queryItems { if let hostCheck = URLComponents(string: url)?.host { host = hostCheck } if let portCheck = URLComponents(string: url)?.port { host += ":" + String(portCheck) } if let rpcPasswordCheck = URLComponents(string: url)?.password { rpcPassword = rpcPasswordCheck } if let rpcUserCheck = URLComponents(string: url)?.user { rpcUser = rpcUserCheck } if rpcUser == "" && rpcPassword == "" { if params.count == 2 { rpcUser = (params[0].description).replacingOccurrences(of: "user=", with: "") rpcPassword = (params[1].description).replacingOccurrences(of: "password=", with: "") if rpcPassword.contains("?label=") { let arr = rpcPassword.components(separatedBy: "?label=") rpcPassword = arr[0] if arr.count > 1 { label = arr[1] } } } } else { let url = URL(string: url) if let labelCheck = url?.value(for: "label") { label = labelCheck } } } else { self.errorBool = true completion() } guard host != "", rpcUser != "", rpcPassword != "", authkey != "" else { self.errorBool = true completion() return } var node = [String:Any]() let torNodeHost = self.aes.encryptKey(keyToEncrypt: host) let torNodeRPCPass = self.aes.encryptKey(keyToEncrypt: rpcPassword) let torNodeRPCUser = self.aes.encryptKey(keyToEncrypt: rpcUser) let torNodeLabel = self.aes.encryptKey(keyToEncrypt: label) let encauthkey = self.aes.encryptKey(keyToEncrypt: authkey) let encpubkey = self.aes.encryptKey(keyToEncrypt: authPubKey) node["onionAddress"] = torNodeHost node["label"] = torNodeLabel node["rpcuser"] = torNodeRPCUser node["rpcpassword"] = torNodeRPCPass node["authKey"] = encauthkey node["authPubKey"] = encpubkey self.cd.saveEntity(dict: node, entityName: .nodes) { if !self.cd.errorBool { let success = self.cd.boolToReturn if success { print("standup node added") self.errorBool = false completion() } else { self.errorBool = true self.errorDescription = "Error adding QuickConnect node" completion() } } else { self.errorBool = true self.errorDescription = self.cd.errorDescription completion() } } } else { self.errorBool = true self.errorDescription = "Error adding getting nodes from core data" completion() } } } } extension URL { func value(for paramater: String) -> String? { let queryItems = URLComponents(string: self.absoluteString)?.queryItems let queryItem = queryItems?.filter({$0.name == paramater}).first let value = queryItem?.value return value } }
36.202247
124
0.37694
edd308983b06687edb280cf894ee20740d90e8f5
2,706
// // IQSection.swift // https://github.com/hackiftekhar/IQListKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // MARK: - Section model of the table/collection public struct IQSection: Hashable { public static func == (lhs: IQSection, rhs: IQSection) -> Bool { return lhs.identifier == rhs.identifier && lhs.header == rhs.header && lhs.headerSize == rhs.headerSize && lhs.footer == rhs.footer && lhs.footerSize == rhs.footerSize } public func hash(into hasher: inout Hasher) { hasher.combine(identifier) } /// Unique identifier of the section public var identifier: AnyHashable /// Header text and size public var header: String? public var headerView: UIView? public var headerSize: CGSize? /// Footer text and size public var footer: String? public var footerView: UIView? public var footerSize: CGSize? /// Initialization /// - Parameters: /// - identifier: section identifier /// - header: header text to display /// - headerSize: header size /// - footer: footer text to display /// - footerSize: footer size public init(identifier: AnyHashable, header: String? = nil, headerView: UIView? = nil, headerSize: CGSize? = nil, footer: String? = nil, footerView: UIView? = nil, footerSize: CGSize? = nil) { self.identifier = identifier self.header = header self.footer = footer self.headerView = headerView self.footerView = footerView self.headerSize = headerSize self.footerSize = footerSize } }
37.068493
94
0.678862
0323bcbc3244844a21671d0caf01ee18395468db
286
// // PlayerWarFaceType.swift // SmartAILibrary // // Created by Michael Rommel on 11.02.20. // Copyright © 2020 Michael Rommel. All rights reserved. // import Foundation enum PlayerWarFaceType: Int, Codable { case none case hostile case friendly case neutral }
15.052632
57
0.692308
11bf82556b420ff781e00bfd96c1ccb828d7ea57
622
// // AVCaptureDeviceExtension.swift // // Created by Darktt on 21/9/23. // Copyright © 2021年 Darktt. All rights reserved. // import AVFoundation internal extension AVCaptureDevice { @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) static func requestAccess(to mediaType: AVMediaType) async -> Bool { let result: Bool = await withCheckedContinuation { contnuation in self.requestAccess(for: mediaType) { contnuation.resume(returning: $0) } } return result } }
22.214286
70
0.567524
8a948af62f2914fcbf3739830ecd43cf08091b65
1,720
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import XCTest import FBSimulatorControl @testable import FBSimulatorControlKit class EnvironmentTests : XCTestCase { let testEnvironment = [ "FBSIMCTL_CHILD_FOO" : "BAR", "PATH" : "IGNORE", "FBSIMCTL_CHILD_BING" : "BONG", ] func testAppendsEnvironmentToLaunchConfiguration() { let launchConfig = FBApplicationLaunchConfiguration(application: Fixtures.application, arguments: [], environment: [:], waitForDebugger: false, output: FBProcessOutputConfiguration.outputToDevNull()) let actual = Action.launchApp(launchConfig).appendEnvironment(testEnvironment) let expected = Action.launchApp(launchConfig.withEnvironmentAdditions([ "FOO" : "BAR", "BING" : "BONG", ])) XCTAssertEqual(expected, actual) } func testAppendsEnvironmentToXCTestLaunchConfiguration() { let launchConfig = FBApplicationLaunchConfiguration(application: Fixtures.application, arguments: [], environment: [:], waitForDebugger: false, output: FBProcessOutputConfiguration.outputToDevNull()) let actual = Action.launchXCTest(FBTestLaunchConfiguration().withApplicationLaunchConfiguration(launchConfig)).appendEnvironment(testEnvironment) let expected = Action.launchXCTest(FBTestLaunchConfiguration().withApplicationLaunchConfiguration(launchConfig.withEnvironmentAdditions([ "FOO" : "BAR", "BING" : "BONG", ]))) XCTAssertEqual(expected, actual) } }
40
203
0.755814
1d8e753736f724b2225b99fa6a95debb66ff2292
1,575
// // RxNFCTagReaderSession+Rx.swift // RxCoreNFC // // Created by Karibash on 2020/06/30. // Copyright © 2020 Karibash. All rights reserved. // import CoreNFC import RxSwift @available(iOS 13.0, *) extension Observable where Element: RxNFCTagReaderSession { // MARK: - Tags - public func tags() ->Observable<NFCTag> { flatMap { $0.tags } } } @available(iOS 13.0, *) extension Observable where Element: RxNFCTagReaderSession { // MARK: - Actions - public func begin() -> Observable<RxNFCTagReaderSession> { flatMap { $0.begin() } } public func invalidate() -> Observable<RxNFCTagReaderSession> { flatMap { $0.invalidate() } } public func restartPolling() -> Observable<RxNFCTagReaderSession> { flatMap { $0.restartPolling() } } } @available(iOS 13.0, *) extension Observable where Element: RxNFCTagReaderSession { // MARK: - Connect - public func connect(_ tag: NFCTag) -> Observable<NFCTag> { flatMap { $0.connect(tag) } } public func connect(_ tag: NFCFeliCaTag) -> Observable<NFCFeliCaTag> { flatMap { $0.connect(tag) } } public func connect(_ tag: NFCISO7816Tag) -> Observable<NFCISO7816Tag> { flatMap { $0.connect(tag) } } public func connect(_ tag: NFCISO15693Tag) -> Observable<NFCISO15693Tag> { flatMap { $0.connect(tag) } } public func connect(_ tag: NFCMiFareTag) -> Observable<NFCMiFareTag> { flatMap { $0.connect(tag) } } }
23.161765
78
0.612698
9b7b9bbe343f70a1da42c505322600f9ff3f8647
14,252
import Spectre @testable import Stencil import XCTest final class FilterTests: XCTestCase { func testRegistration() { let context: [String: Any] = ["name": "Kyle"] it("allows you to register a custom filter") { let template = Template(templateString: "{{ name|repeat }}") let repeatExtension = Extension() repeatExtension.registerFilter("repeat") { (value: Any?) in if let value = value as? String { return "\(value) \(value)" } return nil } let result = try template.render(Context( dictionary: context, environment: Environment(extensions: [repeatExtension]) )) try expect(result) == "Kyle Kyle" } it("allows you to register boolean filters") { let repeatExtension = Extension() repeatExtension.registerFilter(name: "isPositive", negativeFilterName: "isNotPositive") { (value: Any?) in if let value = value as? Int { return value > 0 } return nil } let result = try Template(templateString: "{{ value|isPositive }}") .render(Context(dictionary: ["value": 1], environment: Environment(extensions: [repeatExtension]))) try expect(result) == "true" let negativeResult = try Template(templateString: "{{ value|isNotPositive }}") .render(Context(dictionary: ["value": -1], environment: Environment(extensions: [repeatExtension]))) try expect(negativeResult) == "true" } it("allows you to register a custom which throws") { let template = Template(templateString: "{{ name|repeat }}") let repeatExtension = Extension() repeatExtension.registerFilter("repeat") { (_: Any?) in throw TemplateSyntaxError("No Repeat") } let context = Context(dictionary: context, environment: Environment(extensions: [repeatExtension])) try expect(try template.render(context)) .toThrow(TemplateSyntaxError(reason: "No Repeat", token: template.tokens.first)) } it("throws when you pass arguments to simple filter") { let template = Template(templateString: "{{ name|uppercase:5 }}") try expect(try template.render(Context(dictionary: ["name": "kyle"]))).toThrow() } } func testRegistrationOverrideDefault() throws { let template = Template(templateString: "{{ name|join }}") let context: [String: Any] = ["name": "Kyle"] let repeatExtension = Extension() repeatExtension.registerFilter("join") { (_: Any?) in "joined" } let result = try template.render(Context( dictionary: context, environment: Environment(extensions: [repeatExtension]) )) try expect(result) == "joined" } func testRegistrationWithArguments() { let context: [String: Any] = ["name": "Kyle"] it("allows you to register a custom filter which accepts single argument") { let template = Template(templateString: """ {{ name|repeat:'value1, "value2"' }} """) let repeatExtension = Extension() repeatExtension.registerFilter("repeat") { value, arguments in guard let value = value, let argument = arguments.first else { return nil } return "\(value) \(value) with args \(argument ?? "")" } let result = try template.render(Context( dictionary: context, environment: Environment(extensions: [repeatExtension]) )) try expect(result) == """ Kyle Kyle with args value1, "value2" """ } it("allows you to register a custom filter which accepts several arguments") { let template = Template(templateString: """ {{ name|repeat:'value"1"',"value'2'",'(key, value)' }} """) let repeatExtension = Extension() repeatExtension.registerFilter("repeat") { value, arguments in guard let value = value else { return nil } let args = arguments.compactMap { $0 } return "\(value) \(value) with args 0: \(args[0]), 1: \(args[1]), 2: \(args[2])" } let result = try template.render(Context( dictionary: context, environment: Environment(extensions: [repeatExtension]) )) try expect(result) == """ Kyle Kyle with args 0: value"1", 1: value'2', 2: (key, value) """ } it("allows whitespace in expression") { let template = Template(templateString: """ {{ value | join : ", " }} """) let result = try template.render(Context(dictionary: ["value": ["One", "Two"]])) try expect(result) == "One, Two" } } func testStringFilters() { it("transforms a string to be capitalized") { let template = Template(templateString: "{{ name|capitalize }}") let result = try template.render(Context(dictionary: ["name": "kyle"])) try expect(result) == "Kyle" } it("transforms a string to be uppercase") { let template = Template(templateString: "{{ name|uppercase }}") let result = try template.render(Context(dictionary: ["name": "kyle"])) try expect(result) == "KYLE" } it("transforms a string to be lowercase") { let template = Template(templateString: "{{ name|lowercase }}") let result = try template.render(Context(dictionary: ["name": "Kyle"])) try expect(result) == "kyle" } } func testStringFiltersWithArrays() { it("transforms a string to be capitalized") { let template = Template(templateString: "{{ names|capitalize }}") let result = try template.render(Context(dictionary: ["names": ["kyle", "kyle"]])) try expect(result) == """ ["Kyle", "Kyle"] """ } it("transforms a string to be uppercase") { let template = Template(templateString: "{{ names|uppercase }}") let result = try template.render(Context(dictionary: ["names": ["kyle", "kyle"]])) try expect(result) == """ ["KYLE", "KYLE"] """ } it("transforms a string to be lowercase") { let template = Template(templateString: "{{ names|lowercase }}") let result = try template.render(Context(dictionary: ["names": ["Kyle", "Kyle"]])) try expect(result) == """ ["kyle", "kyle"] """ } } func testDefaultFilter() { let template = Template(templateString: """ Hello {{ name|default:"World" }} """) it("shows the variable value") { let result = try template.render(Context(dictionary: ["name": "Kyle"])) try expect(result) == "Hello Kyle" } it("shows the default value") { let result = try template.render(Context(dictionary: [:])) try expect(result) == "Hello World" } it("supports multiple defaults") { let template = Template(templateString: """ Hello {{ name|default:a,b,c,"World" }} """) let result = try template.render(Context(dictionary: [:])) try expect(result) == "Hello World" } it("can use int as default") { let template = Template(templateString: "{{ value|default:1 }}") let result = try template.render(Context(dictionary: [:])) try expect(result) == "1" } it("can use float as default") { let template = Template(templateString: "{{ value|default:1.5 }}") let result = try template.render(Context(dictionary: [:])) try expect(result) == "1.5" } it("checks for underlying nil value correctly") { let template = Template(templateString: """ Hello {{ user.name|default:"anonymous" }} """) let nilName: String? = nil let user: [String: Any?] = ["name": nilName] let result = try template.render(Context(dictionary: ["user": user])) try expect(result) == "Hello anonymous" } } func testJoinFilter() { let template = Template(templateString: """ {{ value|join:", " }} """) it("joins a collection of strings") { let result = try template.render(Context(dictionary: ["value": ["One", "Two"]])) try expect(result) == "One, Two" } it("joins a mixed-type collection") { let result = try template.render(Context(dictionary: ["value": ["One", 2, true, 10.5, "Five"]])) try expect(result) == "One, 2, true, 10.5, Five" } it("can join by non string") { let template = Template(templateString: """ {{ value|join:separator }} """) let result = try template.render(Context(dictionary: ["value": ["One", "Two"], "separator": true])) try expect(result) == "OnetrueTwo" } it("can join without arguments") { let template = Template(templateString: """ {{ value|join }} """) let result = try template.render(Context(dictionary: ["value": ["One", "Two"]])) try expect(result) == "OneTwo" } } func testSplitFilter() { let template = Template(templateString: """ {{ value|split:", " }} """) it("split a string into array") { let result = try template.render(Context(dictionary: ["value": "One, Two"])) try expect(result) == """ ["One", "Two"] """ } it("can split without arguments") { let template = Template(templateString: """ {{ value|split }} """) let result = try template.render(Context(dictionary: ["value": "One, Two"])) try expect(result) == """ ["One,", "Two"] """ } } func testFilterSuggestion() { it("made for unknown filter") { let template = Template(templateString: "{{ value|unknownFilter }}") let filterExtension = Extension() filterExtension.registerFilter("knownFilter") { value, _ in value } try self.expectError( reason: "Unknown filter 'unknownFilter'. Found similar filters: 'knownFilter'.", token: "value|unknownFilter", template: template, extension: filterExtension ) } it("made for multiple similar filters") { let template = Template(templateString: "{{ value|lowerFirst }}") let filterExtension = Extension() filterExtension.registerFilter("lowerFirstWord") { value, _ in value } filterExtension.registerFilter("lowerFirstLetter") { value, _ in value } try self.expectError( reason: "Unknown filter 'lowerFirst'. Found similar filters: 'lowerFirstWord', 'lowercase'.", token: "value|lowerFirst", template: template, extension: filterExtension ) } it("not made when can't find similar filter") { let template = Template(templateString: "{{ value|unknownFilter }}") let filterExtension = Extension() filterExtension.registerFilter("lowerFirstWord") { value, _ in value } try self.expectError( reason: "Unknown filter 'unknownFilter'. Found similar filters: 'lowerFirstWord'.", token: "value|unknownFilter", template: template, extension: filterExtension ) } } func testIndentContent() throws { let template = Template(templateString: """ {{ value|indent:2 }} """) let result = try template.render(Context(dictionary: [ "value": """ One Two """ ])) try expect(result) == """ One Two """ } func testIndentWithArbitraryCharacter() throws { let template = Template(templateString: """ {{ value|indent:2,"\t" }} """) let result = try template.render(Context(dictionary: [ "value": """ One Two """ ])) try expect(result) == """ One \t\tTwo """ } func testIndentFirstLine() throws { let template = Template(templateString: """ {{ value|indent:2," ",true }} """) let result = try template.render(Context(dictionary: [ "value": """ One Two """ ])) try expect(result) == """ One Two """ } func testIndentNotEmptyLines() throws { let template = Template(templateString: """ {{ value|indent }} """) let result = try template.render(Context(dictionary: [ "value": """ One Two """ ])) try expect(result) == """ One Two """ } func testDynamicFilters() throws { it("can apply dynamic filter") { let template = Template(templateString: "{{ name|filter:somefilter }}") let result = try template.render(Context(dictionary: ["name": "Jhon", "somefilter": "uppercase"])) try expect(result) == "JHON" } it("can apply dynamic filter on array") { let template = Template(templateString: "{{ values|filter:joinfilter }}") let result = try template.render(Context(dictionary: ["values": [1, 2, 3], "joinfilter": "join:\", \""])) try expect(result) == "1, 2, 3" } it("throws on unknown dynamic filter") { let template = Template(templateString: "{{ values|filter:unknown }}") let context = Context(dictionary: ["values": [1, 2, 3], "unknown": "absurd"]) try expect(try template.render(context)).toThrow() } } private func expectError( reason: String, token: String, template: Template, extension: Extension, file: String = #file, line: Int = #line, function: String = #function ) throws { guard let range = template.templateString.range(of: token) else { fatalError("Can't find '\(token)' in '\(template)'") } let environment = Environment(extensions: [`extension`]) let expectedError: Error = { let lexer = Lexer(templateString: template.templateString) let location = lexer.rangeLocation(range) let sourceMap = SourceMap(filename: template.name, location: location) let token = Token.block(value: token, at: sourceMap) return TemplateSyntaxError(reason: reason, token: token, stackTrace: []) }() let error = try expect( environment.render(template: template, context: [:]), file: file, line: line, function: function ).toThrow() as TemplateSyntaxError let reporter = SimpleErrorReporter() try expect( reporter.renderError(error), file: file, line: line, function: function ) == reporter.renderError(expectedError) } }
31.39207
112
0.596267
218abdf4e40ab41623113800e1272cef1401a3ce
1,689
// // SearchTabbarController.swift // Searcher // // Created by Weerayoot Ngandee on 8/27/2559 BE. // Copyright © 2559 Weerayoot Ngandee. All rights reserved. // import UIKit class SearchTabbarController: UITabBarController { override func viewDidLoad() { // Sets the default color of the icon of the selected UITabBarItem and Title UITabBar.appearance().tintColor = UIColor.blackColor() // Sets the default color of the background of the UITabBar UITabBar.appearance().barTintColor = UIColor.whiteColor() // Sets the background color of the selected UITabBarItem (using and plain colored UIImage with the width = 1/5 of the tabBar (if you have 5 items) and the height of the tabBar) UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.init(red: 93/255.0, green: 173/255.0, blue: 226/255.0, alpha: 1), size: CGSizeMake(tabBar.frame.width/3, tabBar.frame.height)) // Uses the original colors for your images, so they aren't not rendered as grey automatically. for item in self.tabBar.items! as [UITabBarItem] { if let image = item.image { item.image = image.imageWithRenderingMode(.AlwaysOriginal) } } } } extension UIImage { func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(CGRectMake(0, 0, size.width, size.height)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
39.27907
226
0.677324
18e2b2c96baa240d29d03b148e2efe6592268398
2,214
// // Data+Extension.swift // SPTokenCore // // Created by SPARK-Daniel on 2020/4/13. // Copyright © 2020 SPARK-Daniel. All rights reserved. // import Foundation import CryptoSwift extension Data { public var hexString: String { return map({ String(format: "%02x", $0) }).joined() } init?(hexString: String) { var string: String if Hex.hasHexPrefix(hexString) { string = hexString.substring(from: 2) } else { string = hexString } guard let stringData = string.data(using: .ascii, allowLossyConversion: true) else { return nil } self.init(capacity: string.count / 2) let stringBytes = Array(stringData) for i in stride(from: 0, to: stringBytes.count, by: 2) { guard let high = Data.value(of: stringBytes[i]) else { return nil } if i < stringBytes.count - 1, let low = Data.value(of: stringBytes[i + 1]) { append((high << 4) | low) } else { append(high) } } } mutating public func clear() { resetBytes(in: 0 ..< count) } public func sp_toHexString() -> String { return toHexString() // From CryptoSwift } // https://stackoverflow.com/questions/55378409/swift-5-0-withunsafebytes-is-deprecated-use-withunsafebytesr public static func random(of length: Int) -> Data { var data = Data(count: length) data.withUnsafeMutableBytes { (ptr: UnsafeMutableRawBufferPointer) in guard let bytes = ptr.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } _ = SecRandomCopyBytes(kSecRandomDefault, length, bytes) } return data } //MARK: - Private /// Converts an ASCII byte to a hex value /// - Parameter nibble: ASCII byte /// - Returns: hex value private static func value(of nibble: UInt8) -> UInt8? { guard let letter = String(bytes: [nibble], encoding: .ascii) else { return nil } return UInt8(letter, radix: 16) } }
28.384615
112
0.560976
75deb9ae271c3dc9b59e900cd8d3d705392eecae
770
// // TableViewCell.swift // BasicTableView // // Created by Giftbot on 2020/05/25. // Copyright © 2020 giftbot. All rights reserved. // import UIKit class MyTableViewCell: UITableViewCell { // 코드로 생성 시 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) print("---------- [ init(style:reuserIdentifier) ] ----------") } // 스토리보드로 생성 시 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // 재사용 override func prepareForReuse() { super.prepareForReuse() print("---------- [ prepareForReuse ] ----------") } // 메모리 해제 deinit { print("Deinit") } }
22
79
0.575325
0e6110377f83b0bef2d90169d3c4ad9f1925c662
647
// // MovieCell.swift // Flix_w1_EricKim // // Created by kimeric on 1/18/18. // Copyright © 2018 EricKim. All rights reserved. // import UIKit class MovieCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var posterImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
19.029412
65
0.647604
e5d10edeca105b0a957bfb8ed60006fcff30b5a9
612
// // RlmAlbum.swift // ForumThreads // // Created by aSqar on 09.05.2018. // Copyright © 2018 Askar Bakirov. All rights reserved. // import Foundation import ObjectMapper import ObjectMapper_Realm class RlmAlbum : RlmEntity, Mappable { @objc dynamic var userId:Int = 0 @objc dynamic var title: String! @objc dynamic var user:RlmUser! // MARK: - Mapping directly from JSON required convenience init?(map: Map) { self.init() } func mapping(map: Map) { userId <- map["userId"] id <- map["id"] title <- map["title"] } }
19.125
56
0.602941
f7aef82378286a40efc9b76194969babd062a8e3
1,881
// // DataExtensionTest.swift // PwsafeSwift // // Created by Anton Selyanin on 11/02/2017. // Copyright © 2017 Anton Selyanin. All rights reserved. // import Foundation import Foundation import Quick import Nimble @testable import PwsafeSwift class DataExtensionTest: QuickSpec { override func spec() { describe("Data.suffixData") { it("returns suffix data, up to the end") { let data = Data([0, 1, 2, 3, 4]) expect(data.suffixData(2)) == Data([3, 4]) } it("returns suffix data, through the end") { let data = Data([0, 1, 2, 3, 4]) expect(data.suffixData(data.count + 1)) == data } it("works for empty data") { let data = Data() expect(data.suffixData(data.count + 1)) == data } it("returns empty") { let data = Data() expect(data.suffixData(0).count) == 0 } } describe("prefixData") { it("returns prefix data") { let data = Data([0, 1, 2, 3, 4]) expect(data.prefixData(2)) == Data([0, 1]) } it("returns suffix data") { let data = Data([0, 1, 2, 3, 4]) expect(data.prefixData(data.count + 1)) == data } it("works for empty data") { let data = Data() expect(data.prefixData(data.count + 1)) == data } it("returns empty") { let data = Data() expect(data.prefixData(0).count) == 0 } } } }
26.492958
63
0.421053
561cd10806f168848162e027c10b4d78075a11f3
3,615
import Foundation /** The data structure that represents an image that appears on the App Clip card for an advanced App Clip experience. Full documentation: <https://developer.apple.com/documentation/appstoreconnectapi/appclipadvancedexperienceimage> */ public struct AppClipAdvancedExperienceImage: Codable { /// The opaque resource ID that uniquely identifies the resource. public let id: String /// Navigational links that include the self-link. public let links: ResourceLinks /// The resource type. public var type: String { "appClipAdvancedExperienceImages" } /// The resource's attributes. public let attributes: Attributes? public init(id: String, links: ResourceLinks, attributes: Attributes? = nil) { self.id = id self.links = links self.attributes = attributes } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) links = try container.decode(ResourceLinks.self, forKey: .links) attributes = try container.decodeIfPresent(Attributes.self, forKey: .attributes) if try container.decode(String.self, forKey: .type) != type { throw DecodingError.dataCorruptedError(forKey: .type, in: container, debugDescription: "Not matching \(type)") } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(links, forKey: .links) try container.encode(type, forKey: .type) try container.encodeIfPresent(attributes, forKey: .attributes) } private enum CodingKeys: String, CodingKey { case id case links case type case attributes } /** The attributes that describe an Advanced App Clip Experience Images resource. Full documentation: <https://developer.apple.com/documentation/appstoreconnectapi/appclipadvancedexperienceimage/attributes> */ public struct Attributes: Codable { /// The state of the App Clip card image asset you uploaded. @NullCodable public var assetDeliveryState: AppMediaAssetState? /// The filename of the image asset that appears on the App Clip card for the advanced App Clip experience. public var fileName: String? /// The size of the image asset that appears on the App Clip card for the advanced App Clip experience. public var fileSize: Int? /// The image asset that appears on the App Clip card of an advanced App Clip experience. @NullCodable public var imageAsset: ImageAsset? /// A string that represents the MD5 checksum of the image asset you use for the App Clip card. public var sourceFileChecksum: String? /// Upload operations for the image asset that appears on the App Clip card for an advanced App Clip experience. @NullCodable public var uploadOperations: [UploadOperation]? public init(assetDeliveryState: AppMediaAssetState? = nil, fileName: String? = nil, fileSize: Int? = nil, imageAsset: ImageAsset? = nil, sourceFileChecksum: String? = nil, uploadOperations: [UploadOperation]? = nil) { self.assetDeliveryState = assetDeliveryState self.fileName = fileName self.fileSize = fileSize self.imageAsset = imageAsset self.sourceFileChecksum = sourceFileChecksum self.uploadOperations = uploadOperations } } }
45.1875
225
0.693776
e0d872e8da98badc9279e5079123fbf2ca1c8799
251
// // Generated file. Do not edit. // import FlutterMacOS import Foundation import dart_native func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { DartNativePlugin.register(with: registry.registrar(forPlugin: "DartNativePlugin")) }
19.307692
84
0.796813
5b164b0997f96ec40400700afaea3a86810a24c5
4,552
// // DBAide.swift // CICOPersistent // // Created by Ethan.Li on 2020/3/26. // Copyright © 2020 cico. All rights reserved. // import Foundation import FMDB class DBAide { static func isTableExist(database: FMDatabase, tableName: String) -> Bool { var result = false let querySQL = """ SELECT name FROM SQLITE_MASTER WHERE type = 'table' AND tbl_name = '\(tableName)'; """ guard let resultSet = database.executeQuery(querySQL, withArgumentsIn: []) else { return result } if resultSet.next() { result = true } resultSet.close() return result } static func createTableIfNotExists(database: FMDatabase, tableName: String, columnArray: [ColumnModel]) -> Bool { var result = false guard tableName.count > 0, columnArray.count > 0 else { return result } var createTableSQL = "CREATE TABLE IF NOT EXISTS \(tableName) (" var isFirst = true columnArray.forEach({ column in if isFirst { isFirst = false createTableSQL.append("\(column.name)") } else { createTableSQL.append(", \(column.name)") } createTableSQL.append(" \(column.type.rawValue)") if column.isPrimaryKey { createTableSQL.append(" NOT NULL PRIMARY KEY") if column.isAutoIncrement && column.type == .INTEGER { createTableSQL.append(" AUTOINCREMENT") } } }) createTableSQL.append(");") result = database.executeUpdate(createTableSQL, withArgumentsIn: []) if !result { print("[ERROR]: SQL = \(createTableSQL)") } return result } static func dropTable(database: FMDatabase, tableName: String) -> Bool { var result = false let dropSQL = "DROP TABLE \(tableName);" result = database.executeUpdate(dropSQL, withArgumentsIn: []) if !result { print("[ERROR]: SQL = \(dropSQL)") } return result } static func queryTableColumns(database: FMDatabase, tableName: String) -> Set<String> { var columnSet = Set<String>.init() let querySQL = "PRAGMA TABLE_INFO(\(tableName));" guard let resultSet = database.executeQuery(querySQL, withArgumentsIn: []) else { return columnSet } while resultSet.next() { if let name = resultSet.string(forColumn: "name") { columnSet.insert(name) } } resultSet.close() return columnSet } static func addColumn(database: FMDatabase, tableName: String, columnName: String, columnType: String) -> Bool { let alterSQL = "ALTER TABLE \(tableName) ADD COLUMN \(columnName) \(columnType);" let result = database.executeUpdate(alterSQL, withArgumentsIn: []) if !result { print("[ERROR]: SQL = \(alterSQL)") } return result } static func queryTableIndexs(database: FMDatabase, tableName: String) -> Set<String> { var indexSet = Set<String>.init() let querySQL = """ SELECT name FROM SQLITE_MASTER WHERE type = 'index' AND tbl_name = '\(tableName)' AND sql IS NOT NULL; """ guard let resultSet = database.executeQuery(querySQL, withArgumentsIn: []) else { return indexSet } while resultSet.next() { if let name = resultSet.string(forColumn: "name") { indexSet.insert(name) } } resultSet.close() return indexSet } static func createIndex(database: FMDatabase, indexName: String, tableName: String, indexColumnName: String) -> Bool { let createIndexSQL = "CREATE INDEX \(indexName) ON \(tableName)(\(indexColumnName));" let result = database.executeUpdate(createIndexSQL, withArgumentsIn: []) if !result { print("[ERROR]: SQL = \(createIndexSQL)") } return result } static func dropIndex(database: FMDatabase, indexName: String) -> Bool { let dropIndexSQL = "DROP INDEX \(indexName);" let result = database.executeUpdate(dropIndexSQL, withArgumentsIn: []) if !result { print("[ERROR]: SQL = \(dropIndexSQL)") } return result } }
28.45
117
0.563928
e6047299f94f7b1f954c0d8c49b64fdd29cf8739
1,105
// MIT license. Copyright (c) 2017 SwiftyFORM. All rights reserved. import Foundation public class SwitchFormItem: FormItem { override func accept(visitor: FormItemVisitor) { visitor.visit(object: self) } public var title: String = "" @discardableResult public func title(_ title: String) -> Self { self.title = title return self } public typealias SyncBlock = (_ value: Bool, _ animated: Bool) -> Void public var syncCellWithValue: SyncBlock = { (value: Bool, animated: Bool) in SwiftyFormLog("sync is not overridden") } internal var innerValue: Bool = false public var value: Bool { get { return self.innerValue } set { self.setValue(newValue, animated: false) } } public typealias SwitchDidChangeBlock = (_ value: Bool) -> Void public var switchDidChangeBlock: SwitchDidChangeBlock = { (value: Bool) in SwiftyFormLog("not overridden") } public func switchDidChange(_ value: Bool) { innerValue = value switchDidChangeBlock(value) } public func setValue(_ value: Bool, animated: Bool) { innerValue = value syncCellWithValue(value, animated) } }
23.510638
77
0.721267
d749f8a0a133f263add7aad249e1832d0f0c8eb3
2,407
import Foundation import CurrencyKit class FeeRateAdjustmentHelper { typealias Rule = (amountRange: Range<Decimal>, coefficient: Double) private let allowedCurrencyCodes: [String] private let fallbackCoefficient = 1.1 private let rules: [CoinType: [Rule]] = [ .bitcoin: [ (amountRange: 10000..<Decimal.greatestFiniteMagnitude, coefficient: 1.25), (amountRange: 5000..<10000, coefficient: 1.20), (amountRange: 1000..<5000, coefficient: 1.15), (amountRange: 500..<1000, coefficient: 1.10), (amountRange: 0..<500, coefficient: 1.05) ], .ethereum: [ (amountRange: 10000..<Decimal.greatestFiniteMagnitude, coefficient: 1.25), (amountRange: 5000..<10000, coefficient: 1.20), (amountRange: 1000..<5000, coefficient: 1.15), (amountRange: 200..<1000, coefficient: 1.11), (amountRange: 0..<200, coefficient: 1.05) ] ] init(currencyCodes: [String]) { allowedCurrencyCodes = currencyCodes } private func feeRateCoefficient(rules: [Rule], feeRateAdjustmentInfo: FeeRateAdjustmentInfo, feeRate: Int) -> Double { guard allowedCurrencyCodes.contains(feeRateAdjustmentInfo.currency.code) else { return fallbackCoefficient } var resolvedCoinAmount: Decimal? = nil switch feeRateAdjustmentInfo.amountInfo { case .max: resolvedCoinAmount = feeRateAdjustmentInfo.balance case .entered(let amount): resolvedCoinAmount = amount case .notEntered: resolvedCoinAmount = feeRateAdjustmentInfo.balance } guard let coinAmount = resolvedCoinAmount, let xRate = feeRateAdjustmentInfo.xRate else { return fallbackCoefficient } let fiatAmount = coinAmount * xRate if let rule = rules.first(where: { $0.amountRange.contains(fiatAmount) }) { return rule.coefficient } return fallbackCoefficient } func applyRule(coinType: CoinType, feeRateAdjustmentInfo: FeeRateAdjustmentInfo, feeRate: Int) -> Int { guard let rules = rules[coinType] else { return feeRate } let coefficient = feeRateCoefficient(rules: rules, feeRateAdjustmentInfo: feeRateAdjustmentInfo, feeRate: feeRate) return Int((Double(feeRate) * coefficient).rounded()) } }
37.030769
122
0.649356
bbf0fc6c4dc42f679c59899e62859d0759d5d5df
952
import SwiftUI extension View { func handleRemoteControlEvents() -> some View { self.background(RemoteControlEventHandler()) } } struct RemoteControlEventHandler: UIViewControllerRepresentable { func makeUIViewController(context: Context) -> ViewController { ViewController() } func updateUIViewController(_ uiViewController: ViewController, context: Context) {} class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.becomeFirstResponder() UIApplication.shared.beginReceivingRemoteControlEvents() } override var canBecomeFirstResponder: Bool { true } override func remoteControlReceived(with event: UIEvent?) { guard let event = event else { return } MusicPlayer.shared.handle(event) } } }
27.2
88
0.62605
f9dbfe82056f1ac6187bbf6c6e4ee7aa8183849e
3,172
import Foundation import TSCBasic import TuistCacheTesting import TuistCore import TuistSupport import XCTest @testable import TuistKit @testable import TuistSupportTesting final class CachePrintHashesServiceTests: TuistUnitTestCase { var subject: CachePrintHashesService! var generator: MockGenerator! var graphContentHasher: MockGraphContentHasher! var clock: Clock! var path: AbsolutePath! override func setUp() { super.setUp() path = AbsolutePath("/Test") generator = MockGenerator() graphContentHasher = MockGraphContentHasher() clock = StubClock() subject = CachePrintHashesService(generator: generator, graphContentHasher: graphContentHasher, clock: clock) } override func tearDown() { generator = nil graphContentHasher = nil clock = nil subject = nil super.tearDown() } func test_run_loads_the_graph() throws { // Given subject = CachePrintHashesService(generator: generator, graphContentHasher: graphContentHasher, clock: clock) // When _ = try subject.run(path: path, xcframeworks: false) // Then XCTAssertEqual(generator.invokedLoadParameterPath, path) } func test_run_content_hasher_gets_correct_graph() throws { // Given subject = CachePrintHashesService(generator: generator, graphContentHasher: graphContentHasher, clock: clock) let graph = Graph.test() generator.loadStub = { _ in graph } // When _ = try subject.run(path: path, xcframeworks: false) // Then XCTAssertEqual(graphContentHasher.invokedContentHashesParameters?.graph, graph) } func test_run_outputs_correct_hashes() throws { // Given let target1 = TargetNode.test(target: .test(name: "ShakiOne")) let target2 = TargetNode.test(target: .test(name: "ShakiTwo")) graphContentHasher.stubbedContentHashesResult = [target1: "hash1", target2: "hash2"] subject = CachePrintHashesService(generator: generator, graphContentHasher: graphContentHasher, clock: clock) // When _ = try subject.run(path: path, xcframeworks: false) // Then XCTAssertPrinterOutputContains("ShakiOne - hash1") XCTAssertPrinterOutputContains("ShakiTwo - hash2") } func test_run_gives_correct_artifact_type_to_hasher() throws { // When _ = try subject.run(path: path, xcframeworks: true) // Then XCTAssertEqual(graphContentHasher.invokedContentHashesParameters?.cacheOutputType, .xcframework) // When _ = try subject.run(path: path, xcframeworks: false) // Then XCTAssertEqual(graphContentHasher.invokedContentHashesParameters?.cacheOutputType, .framework) } }
32.040404
104
0.611917
e27078b2c9fa7a72f783767d2e34faf0c0bdd01f
7,391
import XCTest @testable import DominionDeckBuilder class CardsAPITests: XCTestCase { // MARK: - Subject under test var sut: CardsAPI! // MARK: - Test lifecycle override func setUp() { super.setUp() setupCardsAPI() } override func tearDown() { super.tearDown() } // MARK: - Test setup func setupCardsAPI() { sut = CardsAPI() } // MARK: - Test CRUD operations - Optional error func testFetchCardsShouldReturnListOfCards_OptionalError() { // Given // When var returnedCards = [Card]() let expect = expectation(description: "Wait for fetchCards() to return") sut.fetchCards { (cards: [Card], error: CardsStoreError?) -> Void in XCTAssertNil(error, "fetchCards() should not return an error: \(error)") returnedCards = cards expect.fulfill() } waitForExpectations(timeout: 5.0) { (error: Error?) -> Void in XCTAssertNil(error, "Timeout") } // Then XCTAssertGreaterThan(returnedCards.count, 0, "fetchCards() should return an card") } func testFetchCardsShouldReturnListOfCardsOfExpansion_OptionalError() { // Given // When var returnedCards = [Card]() let expect = expectation(description: "Wait for fetchCards() to return") sut.fetchCards(expansion: Expansion(name: "Dominion", numCards: 0)) { (cards: [Card], error: CardsStoreError?) -> Void in XCTAssertNil(error, "fetchCards() should not return an error: \(error)") returnedCards = cards expect.fulfill() } waitForExpectations(timeout: 5.0) { (error: Error?) -> Void in XCTAssertNil(error, "Timeout") } // Then XCTAssertGreaterThan(returnedCards.count, 0, "fetchCards() should return an card") } func testFetchCardShouldReturnCard_OptionalError() { // Given // When var returnedCard: Card? let expect = expectation(description: "Wait for fetchCard() to return") sut.fetchCard(id: "1") { (card: Card?, error: CardsStoreError?) -> Void in XCTAssertNil(error, "fetchCard() should not return an error: \(error)") returnedCard = card expect.fulfill() } waitForExpectations(timeout: 5.0) { (error: Error?) -> Void in XCTAssertNil(error, "Timeout") } // Then XCTAssertNotNil(returnedCard, "fetchCard() should return an card") } // MARK: - Test CRUD operations - Generic enum result type func testFetchCardsShouldReturnListOfCards_GenericEnumResultType() { // Given // When var returnedCards = [Card]() let expect = expectation(description: "Wait for fetchCards() to return") sut.fetchCards { (result: CardsStoreResult<[Card]>) -> Void in switch (result) { case .Success(let cards): returnedCards = cards case .Failure(let error): XCTFail("fetchCards() should not return an error: \(error)") } expect.fulfill() } waitForExpectations(timeout: 5.0) { (error: Error?) -> Void in XCTAssertNil(error, "Timeout") } // Then XCTAssertGreaterThan(returnedCards.count, 0, "fetchCards() should return an Card") } func testFetchCardsShouldReturnListOfCardsOfExpansion_GenericEnumResultType() { // Given // When var returnedCards = [Card]() let expect = expectation(description: "Wait for fetchCards() to return") sut.fetchCards(expansion: Expansion(name: "Dominion", numCards: 0)) { (result: CardsStoreResult<[Card]>) -> Void in switch (result) { case .Success(let cards): returnedCards = cards case .Failure(let error): XCTFail("fetchCards() should not return an error: \(error)") } expect.fulfill() } waitForExpectations(timeout: 5.0) { (error: Error?) -> Void in XCTAssertNil(error, "Timeout") } // Then XCTAssertGreaterThan(returnedCards.count, 0, "fetchCards() should return an Card") } func testFetchCardsShouldReturnCard_GenericEnumResultType() { // Given // When var returnedCard: Card? let expect = expectation(description: "Wait for fetchCard() to return") sut.fetchCard(id: "1") { (result: CardsStoreResult<Card>) in switch (result) { case .Success(let card): returnedCard = card case .Failure(let error): XCTFail("fetchCard() should not return an error: \(error)") } expect.fulfill() } waitForExpectations(timeout: 5.0) { (error: Error?) -> Void in XCTAssertNil(error, "Timeout") } // Then XCTAssertNotNil(returnedCard, "fetchCard() should return an Card") } // MARK: - Test CRUD operations - Inner closure func testFetchCardsShouldReturnListOfCards_InnerClosure() { // Given // When var returnedCards = [Card]() let expect = expectation(description: "Wait for fetchCards() to return") sut.fetchCards { (cards: () throws -> [Card]) -> Void in returnedCards = try! cards() expect.fulfill() } waitForExpectations(timeout: 5.0) { (error: Error?) -> Void in XCTAssertNil(error, "Timeout") } // Then XCTAssertGreaterThan(returnedCards.count, 0, "fetchCards() should return an Card") } func testFetchCardsShouldReturnListOfCardsOfExpansion_InnerClosure() { // Given // When var returnedCards = [Card]() let expect = expectation(description: "Wait for fetchCards() to return") sut.fetchCards(expansion: Expansion(name: "Dominion", numCards: 0)) { (cards: () throws -> [Card]) -> Void in returnedCards = try! cards() expect.fulfill() } waitForExpectations(timeout: 5.0) { (error: Error?) -> Void in XCTAssertNil(error, "Timeout") } // Then XCTAssertGreaterThan(returnedCards.count, 0, "fetchCards() should return an Card") } func testFetchCardShouldReturnCard_InnerClosure() { // Given // When var returnedCard: Card? let expect = expectation(description: "Wait for fetchCard() to return") sut.fetchCard(id: "1") { (card: () throws -> Card?) -> Void in do { returnedCard = try card() } catch { returnedCard = nil } expect.fulfill() } waitForExpectations(timeout: 5.0) { (error: Error?) -> Void in XCTAssertNil(error, "Timeout") } // Then XCTAssertNotNil(returnedCard, "fetchCard() should return an Card") } }
31.451064
129
0.553376
8a40d3f3b729f234fea626e922c0893e91cf42d2
2,129
// // CollectionsCell.swift // Chottky // // Created by Radi Barq on 5/14/17. // Copyright © 2017 Chottky. All rights reserved. // import UIKit class CollectionsCell: UICollectionViewCell { var imageView: UIImageView = { var imageView = UIImageView() return imageView }() var categoryLable: UILabel = { var label = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 10)) label.textAlignment = .right label.textColor = UIColor(red: 59/255, green: 59/255, blue: 59/255, alpha: 1) return label }() override init (frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupViews() { imageView.frame = CGRect(x: 0, y: 0, width: 80, height: 80) self.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.widthAnchor.constraint(equalToConstant: 80).isActive = true imageView.heightAnchor.constraint(equalToConstant: 80).isActive = true imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: -20).isActive = true self.addSubview(categoryLable) categoryLable.translatesAutoresizingMaskIntoConstraints = false // categoryLable.widthAnchor.constraint(equalToConstant: 100).isActive = true categoryLable.heightAnchor.constraint(equalToConstant: 10).isActive = true categoryLable.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true categoryLable.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 20).isActive = true } func setUpLabel(text: String) { categoryLable.text = text } func setImage(image: UIImage) -> Void { self.backgroundColor = UIColor.white imageView.image = image } }
29.569444
105
0.642085
de733f3778caf223ef9884b755237b220cd27c7b
2,278
// // DBManager.swift // CanGatewayApp // // Created by Emanuele Garolla on 02/01/18. // Copyright © 2018 Emanuele Garolla. All rights reserved. // import Foundation import RealmSwift import RxSwift class WordRealmObj: Object { @objc dynamic var word = "" @objc dynamic var meaning = "" @objc dynamic var count = 0 @objc dynamic var date = NSDate() // override static func primaryKey() -> String? { // return "word" // } } class DBManager { static let shared = DBManager() private(set) var words : Variable<[Word]> = Variable([Word]()) let realm : Realm var objects: Results<WordRealmObj> private init() { realm = try! Realm() objects = try! Realm().objects(WordRealmObj.self).sorted(byKeyPath: "date", ascending: false) updateWords() } func updateWords() { // objects = try! Realm().objects(WordRealmObj.self).sorted(byKeyPath: "date") var res = [Word] () for o in objects { res.append(Word(word: o.word, meaning: o.meaning, count: o.count)) } words.value = res } func updateCountOrCreate(word w: Word) { if let wordToEdit = objects.filter("word == %@",w.word).first { try! realm.write { wordToEdit.count = wordToEdit.count + 1 } } else { realm.beginWrite() realm.create(WordRealmObj.self, value: [w.word.lowercased(), w.meaning.lowercased(), w.count]) try! realm.commitWrite() } updateWords() } func delete(oldWord: Word) { if let wordToDelete = objects.filter("word == %@",oldWord.word).first { realm.beginWrite() realm.delete(wordToDelete) try! realm.commitWrite() } updateWords() } func edit(word w: Word, oldWord: Word) { if let wordToEdit = objects.filter("word == %@",oldWord.word).first { try! realm.write { wordToEdit.word = w.word wordToEdit.meaning = w.meaning wordToEdit.count = w.count wordToEdit.date = NSDate() } } updateWords() } }
26.8
106
0.546532
38bd01db7acb3ba34ee986879d80a05b86e4b078
3,046
// // MyProfileBlacklistViewModel.swift // Commun // // Created by Chung Tran on 11/13/19. // Copyright © 2019 Commun Limited. All rights reserved. // import Foundation import RxCocoa import RxSwift class MyProfileBlacklistViewModel: BaseViewModel { // MARK: - Nested item enum SegmentedItem: String, CaseIterable { case users = "users" case communities = "communities" static var allCases: [SegmentedItem] { return [.users, .communities] } var index: Int { switch self { case .users: return 0 case .communities: return 1 } } } // MARK: - Objects let listLoadingState = BehaviorRelay<ListFetcherState>(value: .loading(false)) lazy var segmentedItem = BehaviorRelay<SegmentedItem>(value: .users) lazy var usersVM = BlacklistViewModel(type: .users) lazy var communitiesVM = BlacklistViewModel(type: .communities) let items = BehaviorRelay<[ResponseAPIContentGetBlacklistItem]>(value: []) // MARK: - Initializers override init() { super.init() defer { bind() fetchNext(forceRetry: true) } } // MARK: - Methods func bind() { // segmented item change segmentedItem .subscribe(onNext: { [weak self] (_) in self?.reload() }) .disposed(by: disposeBag) // Loading state usersVM.state .do(onNext: { (state) in print("usersVM state \(state)") }) .filter {_ in self.segmentedItem.value == .users} .bind(to: listLoadingState) .disposed(by: disposeBag) communitiesVM.state .do(onNext: { (state) in print("communitiesVM state \(state)") }) .filter {_ in self.segmentedItem.value == .communities} .bind(to: listLoadingState) .disposed(by: disposeBag) listLoadingState .subscribe(onNext: { (state) in print(state) }) .disposed(by: disposeBag) // items usersVM.items.filter {_ in self.segmentedItem.value == .users} .bind(to: items) .disposed(by: disposeBag) communitiesVM.items.filter {_ in self.segmentedItem.value == .communities} .bind(to: items) .disposed(by: disposeBag) } func reload() { switch segmentedItem.value { case .users: usersVM.reload() case .communities: communitiesVM.reload() } } func fetchNext(forceRetry: Bool = false) { switch segmentedItem.value { case .users: usersVM.fetchNext(forceRetry: forceRetry) case .communities: communitiesVM.fetchNext(forceRetry: forceRetry) } } }
27.944954
85
0.535456
18758f8de7e9dcd72eb55e828c5aa359fa6bc233
1,413
// // AppDelegate.swift // VaporChatClient // // Created by Cody on 4/22/20. // Copyright © 2020 Servalsoft. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.184211
179
0.748054
f7b19c0eb819ccbc350a9172f669227918192e4b
1,180
// // GoalStreakSortOrder.swift // Emojical // // Created by Vladimir Svidersky on 10/03/21. // Copyright © 2021 Vladimir Svidersky. All rights reserved. // import Foundation /// Unified view model for statistics collection view enum GoalStatsSortOrder: Hashable { /// Sort by goal reached total count case totalCount /// Sort by streak length case streakLength /// Convinience method to iterate through values func next() -> GoalStatsSortOrder { switch self { case .totalCount: return .streakLength case .streakLength: return .totalCount } } } extension GoalStatsSortOrder { /// Readable column title value var columnTitle: String { switch self { case .totalCount: return "total_column".localized case .streakLength: return "streak_column".localized } } /// Readable report title value var title: String { switch self { case .totalCount: return "goal_totals_title".localized case .streakLength: return "goal_streaks_title".localized } } }
22.264151
61
0.614407
fb44d1a84ff94fce31925647c159a036246636bf
670
/** * @file BxInputStaticHeight.swift * @namespace BxInputController * * @details Implemention with this protocol garanted using stable size for a header/footer/row content * @date 23.01.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Implementation with this protocol should ensure using stable size for a header/footer/row content public protocol BxInputStaticHeight { /// size for a header/footer/row content var height : CGFloat {get} }
29.130435
102
0.734328
715fc7620a27bde680c16027d03572f54b49a162
2,256
// // QueueViewController.swift // SwiftAudio_Example // // Created by Jørgen Henrichsen on 25/03/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit import SwiftAudioEx class QueueViewController: UIViewController { let controller = AudioController.shared @IBOutlet weak var tableView: UITableView! let cellReuseId: String = "QueueCell" override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib.init(nibName: "QueueTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: cellReuseId) tableView.delegate = self tableView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func closeButton(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } } extension QueueViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return controller.player.nextItems.count default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseId, for: indexPath) as! QueueTableViewCell let item: AudioItem? switch indexPath.section { case 0: item = controller.player.currentItem case 1: item = controller.player.nextItems[indexPath.row] default: item = nil } if let item = item { cell.titleLabel.text = item.getTitle() cell.artistLabel.text = item.getArtist() } return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Playing Now" case 1: return "Up Next" default: return nil } } }
26.541176
127
0.621011
ed38608d624cd0880c4366320fe9a89859cec128
1,803
// // ViewController.swift // HWS-100Swift-M1 // // Created by Vicente on 16/12/21. // import UIKit class ViewController: UITableViewController { var countries = [String]() override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.prefersLargeTitles = true title = "Flags" let fm = FileManager.default let path = Bundle.main.resourcePath! let items = try! fm.contentsOfDirectory(atPath: path) for item in items { if item.hasSuffix(".png") { countries.append(item) } } countries.sort() print(countries) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return countries.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FlagRow", for: indexPath) var cellConfig = cell.defaultContentConfiguration() cellConfig.image = UIImage(named: countries[indexPath.row]) cellConfig.imageProperties.maximumSize = CGSize(width: 60, height: 30) cellConfig.text = (countries[indexPath.row] as NSString).deletingPathExtension.uppercased() cell.contentConfiguration = cellConfig return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let vc = storyboard?.instantiateViewController(withIdentifier: "DetailFlag") as? DetailViewController { vc.selectedFlag = countries[indexPath.row] navigationController?.pushViewController(vc, animated: true) } } }
32.196429
114
0.648918
89814c5715b9f7e870470c626b7f46fc181464bd
1,015
import SwiftUI import Combine struct PersonView: View { var viewModel: PersonViewModel var body: some View { VStack { DownloadPhotoView(viewModel: viewModel.photoViewModel()) .scaledToFit() .clipShape(Circle()) .clipped() Text(viewModel.person.name).font(.footnote) Spacer() }.padding(4) } } struct PersonView_Previews: PreviewProvider { class MockedAdapter: ImageDownloadAdapter { func getImage(at url: String) -> AnyPublisher<Image, Error> { Future<Image, Error> { $0(.success(Image.personPlaceholder)) } .eraseToAnyPublisher() } } static var previews: some View { PersonView(viewModel: PersonViewModel(person: .init(picture: "", name: "Person 01", eventId: "1", id: "1"), adapter: MockedAdapter() ) ).previewLayout(.fixed(width: 130, height: 130)) } }
28.194444
77
0.558621
33fbc62c0c521df907198b5e6d154af4983ea6b2
3,785
// Surf.Alarm import Rswift import UIKit class SurfAlarmTableVC: UIViewController { @IBOutlet var emptyAlarmsImage: UIImageView! @IBOutlet var tableView: UITableView! let alarms = store.allAlarms.sorted(byKeyPath: "hour") weak var delegate: SurfAlarmTableViewDelegate? private let goToSettings = "Enable Notifications in iOS Settings to set alarms" override func viewDidLoad() { super.viewDidLoad() setupTableView() checkNotificationAuthorization() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) emptyAlarmsImage.makeRound() tableView.reloadData() } @IBAction func closeButtonTapped(_: Any!) { dismiss(animated: true, completion: nil) } private func setupTableView() { tableView.delegate = self tableView.dataSource = self tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.isHidden = alarms.isEmpty } private func checkNotificationAuthorization() { NotificationAuthorizer.checkAuthorization { granted in if !granted, NotificationAuthorizer.userDisabledNotifications { DispatchQueue.main.async { self.showBottomMessage(self.goToSettings, lengthOfTime: 4.0) } } } } } extension SurfAlarmTableVC: SurfAlarmTableViewCellDelegate { func userTappedAlarmSettings(_ alarm: SurfAlarm) { guard let alarmBuilderNav = R.storyboard.surfAlarmBuilder.instantiateInitialViewController(), let alarmBuilder = alarmBuilderNav.topViewController as? SurfAlarmBuilderVC else { return } alarmBuilder.alarm = alarm present(alarmBuilderNav, animated: true, completion: nil) } } extension SurfAlarmTableVC: UITableViewDelegate, UITableViewDataSource { func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat { return 150 } func numberOfSections(in _: UITableView) -> Int { return alarms.count } func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return 1 } func tableView(_: UITableView, heightForHeaderInSection _: Int) -> CGFloat { return 10 } func tableView(_: UITableView, viewForHeaderInSection _: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = .clear return headerView } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseId = R.reuseIdentifier.surfAlarmDetailCell guard let cell = tableView.dequeueReusableCell(withIdentifier: reuseId, for: indexPath) else { return UITableViewCell() } cell.surfAlarm = alarms[indexPath.section] cell.delegate = self return cell } func tableView(_: UITableView, canEditRowAt _: IndexPath) -> Bool { return true } func tableView( _: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath ) -> UISwipeActionsConfiguration? { return UISwipeActionsConfiguration.deleteConfiguration { _, _, _ in NotificationScheduler.cancel(self.alarms[indexPath.section]) store.deleteAlarm(self.alarms[indexPath.section]) let indexSet = IndexSet(arrayLiteral: indexPath.section) self.tableView.deleteSections(indexSet, with: .automatic) self.tableView.reloadData() self.tableView.isHidden = self.alarms.isEmpty } } func tableView( _: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath ) -> UISwipeActionsConfiguration? { return UISwipeActionsConfiguration.viewMapConfiguration { _, _, _ in self.dismiss(animated: true, completion: nil) self.delegate?.userTappedViewMap(for: self.alarms[indexPath.section]) } } } protocol SurfAlarmTableViewDelegate: AnyObject { func userTappedViewMap(for alarm: SurfAlarm) }
30.039683
98
0.734214
76142ce2671c6437f3ac370674ca1f33f07b9566
430
// // TransactionRequest.swift // cyberpay // // Created by David Ehigiator on 07/02/2019. // Copyright © 2019 David Ehigiator. All rights reserved. // import Foundation /// MODEL PARAMETER REQUESTED FOR THE API struct TransactionRequest: Encodable { let Currency: String let MerchantRef: String let Amount: Double let Description: String let IntegrationKey: String let ReturnUrl: String }
19.545455
58
0.702326
e55cfab11a281dfb206eddb8da01d19b4b3a0ae9
6,103
import Flutter import Lottie public class SwiftFlotterPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { registrar.register(FlotterAnimationViewFactory(registrar.messenger()), withId: "FlotterAnimation") } } public class FlotterAnimationViewFactory: NSObject, FlutterPlatformViewFactory { var messenger: (NSObjectProtocol & FlutterBinaryMessenger)? init(_ messenger: (NSObjectProtocol & FlutterBinaryMessenger)?) { self.messenger = messenger! } public func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol { return FlutterStandardMessageCodec.sharedInstance() } public func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView { return FlotterAnimationView(frame, viewId: viewId, args: args, binaryMessenger: messenger) } } public class FlotterAnimationView: NSObject, FlutterPlatformView { let frame: CGRect let viewId: Int64 let animationId: String let methodChannel: FlutterMethodChannel let animationView: AnimationView var isReady = false init(_ frame: CGRect, viewId: Int64, args: Any?, binaryMessenger messenger: (NSObjectProtocol & FlutterBinaryMessenger)?) { self.frame = frame self.viewId = viewId // Parse args let arguments = args as? Dictionary<String, Any> if (arguments != nil) { animationId = arguments?["animationId"] as! String } else { animationId = "nil" } // Initialize methodChannel and animationView methodChannel = FlutterMethodChannel(name: "flotter-\(animationId)", binaryMessenger: messenger!) animationView = AnimationView(frame: frame) super.init() // Add handle call method methodChannel.setMethodCallHandler({ [weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in let args = call.arguments as? Dictionary<String, Any> switch (call.method) { case "initialize": self!.initialize( args!["animationData"] as! String, args!["loopMode"] as! Int ) result(self!.isReady) break; case "play": self!.play() break; case "playFrom": self!.playFrom( fromProgress: args!["from"] as! CGFloat, toProgress: args!["to"] as! CGFloat, loopModeInt: args!["loopMode"] as! Int ) break; case "pause": self!.pause() break; case "reverse": self!.reverse() break; case "stop": self!.stop() break; default: result(FlutterMethodNotImplemented) } }) } public func view() -> UIView { return animationView; } //* FlotterAnimationView functions *// private func initialize( _ animationData: String, _ loopModeInt: Int ) { if (!isReady) { // Try convert json string to json object do { // Set animationView let animation = try JSONDecoder().decode(Animation.self, from: animationData.data(using: .utf8)!) animationView.animation = animation var loopMode: LottieLoopMode switch (loopModeInt) { case 1: loopMode = .loop break case 2: loopMode = .repeatBackwards(1) break case 3: loopMode = .autoReverse break default: loopMode = .playOnce } animationView.loopMode = loopMode animationView.contentMode = .scaleAspectFill animationView.center = self.view().center isReady = true } catch { isReady = false } } } private func play() { if (isReady && !animationView.isAnimationPlaying) { animationView.play() } } private func playFrom(fromProgress: CGFloat, toProgress: CGFloat, loopModeInt: Int) { if (isReady && !animationView.isAnimationPlaying) { animationView.currentProgress = fromProgress var loopMode: LottieLoopMode var callback: ((Bool) -> Void) = { (Bool) -> Void in } switch (loopModeInt) { case 1: loopMode = .loop break case 2: loopMode = .playOnce callback = { (Bool) -> Void in self.animationView.play(fromProgress: toProgress, toProgress: fromProgress, loopMode: .playOnce, completion: nil) } break case 3: loopMode = .autoReverse break default: loopMode = .playOnce } animationView.play(fromProgress: fromProgress, toProgress: toProgress, loopMode: loopMode, completion: callback) } } private func pause() { if (isReady && animationView.isAnimationPlaying) { animationView.pause() } } private func reverse() { if (isReady) { animationView.play(fromProgress: 1, toProgress: 0, loopMode: .playOnce, completion: nil) } } private func stop() { if (isReady) { animationView.stop() } } }
31.458763
133
0.517942
2fed835a932cc9dd7b22207d1e0bc10f293cc8f8
2,020
// // Photos.swift // // Copyright (c) 2015-2019 Damien (http://delba.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #if PERMISSION_PHOTOS import Photos extension Permission { var statusPhotos: PermissionStatus { let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: return .authorized case .denied, .restricted: return .denied case .notDetermined: return .notDetermined case .limited: return .limited @unknown default: return .notDetermined } } func requestPhotos(_ callback: @escaping Callback) { guard let _ = Bundle.main.object(forInfoDictionaryKey: .photoLibraryUsageDescription) else { print("WARNING: \(String.photoLibraryUsageDescription) not found in Info.plist") return } PHPhotoLibrary.requestAuthorization { _ in callback(self.statusPhotos) } } } #endif
38.113208
100
0.70198
db41906ce5bbb325fb86abe70c378b057d44c271
549
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "LeafTest", dependencies: [ // 💧 A server-side Swift web framework. .package(url: "https://github.com/vapor/vapor.git", .upToNextMinor(from: "3.1.0")), .package(url: "https://github.com/vapor/leaf.git", .upToNextMinor(from: "3.0.0")) ], targets: [ .target(name: "App", dependencies: ["Vapor","Leaf"]), .target(name: "Run", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App"]), ] )
30.5
91
0.602914
db8d608abfbead74744de291f9342af08e9f9019
1,364
// // PullRefreshViewController.swift // Homework // // Created by Laura on 8/24/17. // Copyright © 2017 Laura. All rights reserved. // import UIKit class PullRefreshViewController: UIViewController { let refreshControl = UIRefreshControl() let errorMessageView = UIView(frame: CGRect(x: 0.0, y: 64.0, width: UIScreen.main.bounds.width, height: 20)) let errorMessageLabel = UILabel(frame: CGRect(x: 8.0, y: 4.0, width: UIScreen.main.bounds.width, height: 13)) override func viewDidLoad() { super.viewDidLoad() setupErrorMessage() setupRefreshControl() } private func setupErrorMessage() { errorMessageLabel.textColor = UIColor.white errorMessageLabel.font = errorMessageLabel.font.withSize(13.0) errorMessageLabel.textAlignment = NSTextAlignment.center errorMessageView.backgroundColor = UIColor.darkGray errorMessageView.addSubview(errorMessageLabel) view.addSubview(errorMessageView) errorMessageView.isHidden = true } private func setupRefreshControl() { refreshControl.addTarget(self, action: #selector(refreshControlAction), for: UIControlEvents.valueChanged) } @objc private func refreshControlAction() { loadDataAfterPullRefresh() } func loadDataAfterPullRefresh() {} }
29.652174
114
0.691349
abf59ddc4f0a068f0c9d16437f376c50cd95fe0d
980
// // NetworkManager.swift // TesteCidades // // Created by Andre Lucas Ota on 26/11/2017. // Copyright © 2017 AndreOta. All rights reserved. // import Foundation import Alamofire protocol NetworkManager: class { //Vazio :) } extension NetworkManager { typealias Parameters = [String: Any] typealias Headers = [String: String] typealias Method = Alamofire.HTTPMethod /** Cria conexão padrão do Alamofire, seu retorno é um JSON. */ static func requestJson(method: Method, url: String, parameters: Parameters? = nil, headers: Headers? = nil, completion: @escaping (DataResponse<Any>) -> Void) { Alamofire.request(url , method: method , parameters: parameters , encoding: JSONEncoding.default , headers: headers) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .responseJSON(completionHandler: completion) } }
27.222222
165
0.642857
18944cf3c7f1796faff367d406861916a889d35a
3,792
// // BalanceCell.swift // MoYu // // Created by Chris on 16/7/26. // Copyright © 2016年 Chris. All rights reserved. // import UIKit class BalanceCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.layout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class func cell(tableView:UITableView) -> BalanceCell{ let cellID = "balanceCellIdentifier" var cell = tableView.dequeueReusableCell(withIdentifier: cellID) as? BalanceCell if cell == nil{ cell = BalanceCell(style: .default, reuseIdentifier: cellID) } return cell! } func update( _ item: ConsumeHistoryItem ){ weakLabel.text = "星期\(item.date.mo_weekday())" dateLabel.text = String(format: "%02d-%d", item.date.mo_month(),item.date.mo_day()) consumeLabel.text = "-\(item.consume)元" sourceDetailLabel.text = item.detail sourceImageView.image = UIImage(named: "defalutHead") } fileprivate func layout(){ self.contentView.addSubview(weakLabel) weakLabel.snp.makeConstraints { (make) in make.left.equalTo(self.contentView).offset(20) make.top.equalTo(self.contentView).offset(8) make.width.equalTo(40) } self.contentView.addSubview(dateLabel) dateLabel.snp.makeConstraints { (make) in make.left.equalTo(self.contentView).offset(20) make.top.equalTo(weakLabel.snp.bottom).offset(8) make.width.equalTo(weakLabel) } self.contentView.addSubview(sourceImageView) sourceImageView.snp.makeConstraints { (make) in make.centerY.equalTo(self.contentView) make.left.equalTo(weakLabel.snp.right).offset(15) make.size.equalTo(CGSize(width: 32, height: 32)) } self.contentView.addSubview(consumeLabel) consumeLabel.snp.makeConstraints { (make) in make.left.equalTo(sourceImageView.snp.right).offset(15) make.centerY.equalTo(weakLabel) make.right.equalTo(self.contentView) } self.contentView.addSubview(sourceDetailLabel) sourceDetailLabel.snp.makeConstraints { (make) in make.left.equalTo(sourceImageView.snp.right).offset(15) make.centerY.equalTo(dateLabel) make.right.equalTo(self.contentView) } } //MARK: - var & let fileprivate let weakLabel: UILabel = { let label = UILabel() label.textColor = UIColor.mo_lightBlack label.font = UIFont.mo_font(.smaller) label.text = "周二" return label }() fileprivate let dateLabel: UILabel = { let label = UILabel() label.textColor = UIColor.mo_lightBlack label.font = UIFont.mo_font(.smaller) label.text = "07-26" return label }() fileprivate let sourceImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill return imageView }() fileprivate let consumeLabel: UILabel = { let label = UILabel() label.textColor = UIColor.mo_lightBlack label.font = UIFont.mo_font(.smaller) label.text = "-0.00元" return label }() fileprivate let sourceDetailLabel: UILabel = { let label = UILabel() label.textColor = UIColor.mo_silver label.font = UIFont.mo_font(.smaller) label.text = "消费详情" return label }() }
30.580645
91
0.606804
647d83828e02ca889f55c9dcf44445dbffd5c70d
2,061
// // CVCalendarDayViewControlCoordinator.swift // CVCalendar // // Created by E. Mozharovsky on 12/27/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit private let instance = CVCalendarDayViewControlCoordinator() class CVCalendarDayViewControlCoordinator: NSObject { var inOrderNumber = 0 class var sharedControlCoordinator: CVCalendarDayViewControlCoordinator { return instance } var selectedDayView: CVCalendarDayView? = nil var animator: CVCalendarViewAnimatorDelegate? lazy var appearance: CVCalendarViewAppearance = { return CVCalendarViewAppearance.sharedCalendarViewAppearance }() private override init() { super.init() } func performDayViewSelection(dayView: CVCalendarDayView) { if let selectedDayView = self.selectedDayView { if selectedDayView != dayView { if self.inOrderNumber < 2 { self.presentDeselectionOnDayView(self.selectedDayView!) self.selectedDayView = dayView self.presentSelectionOnDayView(self.selectedDayView!) } } } else { self.selectedDayView = dayView if self.animator == nil { self.animator = self.selectedDayView!.weekView!.monthView!.calendarView!.animator } self.presentSelectionOnDayView(self.selectedDayView!) } } private func presentSelectionOnDayView(dayView: CVCalendarDayView) { self.animator?.animateSelection(dayView, withControlCoordinator: CVCalendarDayViewControlCoordinator.sharedControlCoordinator) } private func presentDeselectionOnDayView(dayView: CVCalendarDayView) { self.animator?.animateDeselection(dayView, withControlCoordinator: CVCalendarDayViewControlCoordinator.sharedControlCoordinator) } func animationStarted() { self.inOrderNumber++ } func animationEnded() { self.inOrderNumber-- } }
31.227273
136
0.670548
287e093db247a0b9aa49f1dc6ce57745b73f0450
1,815
// // UpdateSelectionOperation.swift // NetNewsWire-iOS // // Created by Maurice Parker on 2/22/20. // Copyright © 2020 Ranchero Software. All rights reserved. // import UIKit import RSCore class UpdateSelectionOperation: MainThreadOperation { // MainThreadOperation public var isCanceled = false public var id: Int? public weak var operationDelegate: MainThreadOperationDelegate? public var name: String? = "UpdateSelectionOperation" public var completionBlock: MainThreadOperation.MainThreadOperationCompletionBlock? private var coordinator: SceneCoordinator private var dataSource: MasterFeedDataSource private var tableView: UITableView private var animations: Animations init(coordinator: SceneCoordinator, dataSource: MasterFeedDataSource, tableView: UITableView, animations: Animations) { self.coordinator = coordinator self.dataSource = dataSource self.tableView = tableView self.animations = animations } func run() { if dataSource.snapshot().numberOfItems > 0 { if let indexPath = coordinator.currentFeedIndexPath { CATransaction.begin() CATransaction.setCompletionBlock { self.operationDelegate?.operationDidComplete(self) } tableView.selectRowAndScrollIfNotVisible(at: indexPath, animations: animations) CATransaction.commit() } else { if animations.contains(.select) { CATransaction.begin() CATransaction.setCompletionBlock { self.operationDelegate?.operationDidComplete(self) } tableView.selectRow(at: nil, animated: true, scrollPosition: .none) CATransaction.commit() } else { tableView.selectRow(at: nil, animated: false, scrollPosition: .none) self.operationDelegate?.operationDidComplete(self) } } } else { self.operationDelegate?.operationDidComplete(self) } } }
29.754098
120
0.757025
bf65110820028c885a386bbe6d8f7bf08daa61b1
2,591
// Copyright (c) 2022 Razeware LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, // distribute, sublicense, create a derivative work, and/or sell copies of the // Software in any work that is designed, intended, or marketed for pedagogical or // instructional purposes related to programming, coding, application development, // or information technology. Permission for such use, copying, modification, // merger, publication, distribution, sublicensing, creation of derivative works, // or sale is expressly withheld. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. class BookmarksService: Service { // MARK: - Internal func bookmarks(parameters: [Parameter]? = nil, completion: @escaping (_ response: Result<GetBookmarksRequest.Response, RWAPIError>) -> Void) { let request = GetBookmarksRequest() makeAndProcessRequest(request: request, parameters: parameters, completion: completion) } func makeBookmark(for id: Int, completion: @escaping (_ response: Result<MakeBookmark.Response, RWAPIError>) -> Void) { let request = MakeBookmark(id: id) makeAndProcessRequest(request: request, completion: completion) } func destroyBookmark(for id: Int, completion: @escaping (_ response: Result<DestroyBookmarkRequest.Response, RWAPIError>) -> Void) { let request = DestroyBookmarkRequest(id: id) makeAndProcessRequest(request: request, completion: completion) } }
49.826923
134
0.725589
69e2550f3552a3edf73550d99901e45705399ba9
1,780
// // MasterTableViewCell.swift // PokedexGo // // Created by Yi Gu on 7/10/16. // Copyright © 2016 yigu. All rights reserved. // import UIKit class MasterTableViewCell: UITableViewCell { @IBOutlet weak var idLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var pokeImageView: UIImageView! fileprivate var indicator: UIActivityIndicatorView! func awakeFromNib(_ id: Int, name: String, pokeImageUrl: String) { super.awakeFromNib() setupUI(id, name: name) setupNotification(pokeImageUrl) } deinit { pokeImageView.removeObserver(self, forKeyPath: "image") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } fileprivate func setupUI(_ id: Int, name: String) { idLabel.text = NSString(format: "#%03d", id) as String nameLabel.text = name pokeImageView.image = UIImage(named: "default_img") indicator = UIActivityIndicatorView() indicator.center = CGPoint(x: pokeImageView.bounds.midX, y: pokeImageView.bounds.midY) indicator.activityIndicatorViewStyle = .whiteLarge indicator.startAnimating() pokeImageView.addSubview(indicator) pokeImageView.addObserver(self, forKeyPath: "image", options: [], context: nil) } fileprivate func setupNotification(_ pokeImageUrl: String) { NotificationCenter.default.post(name: Notification.Name(rawValue: downloadImageNotification), object: self, userInfo: ["pokeImageView":pokeImageView, "pokeImageUrl" : pokeImageUrl]) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "image" { indicator.stopAnimating() } } }
31.785714
185
0.721348
1df692722ad6f6298fd51c365b749ef56747312a
3,852
// // TwittaSaveAlbum.swift // TwittaSave // // Created by Emmanuel Kehinde on 26/07/2019. // Copyright © 2019 emmanuel.kehinde. All rights reserved. // import Foundation import Photos class TwittaSaveAlbum { static let albumName = "TwittaSave" static let shared = TwittaSaveAlbum() var assetCollection: PHAssetCollection! func initialize() { if !isAlbumExists() { createAlbum() } } func isAlbumExists() -> Bool { if let assetCollection = fetchAssetCollectionForAlbum() { Logger.log("Album Exists") self.assetCollection = assetCollection return true } else { return false } } func createAlbum() { PHPhotoLibrary.shared().performChanges({ PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: TwittaSaveAlbum.albumName) }) { success, _ in if success { self.assetCollection = self.fetchAssetCollectionForAlbum() } } } func fetchAssetCollectionForAlbum() -> PHAssetCollection! { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "title = %@", TwittaSaveAlbum.albumName) let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions) if let firstObject: PHAssetCollection = collection.firstObject { return firstObject } return nil } func saveAsset(_ destinationFileURL: URL, onSuccess: @escaping (_ url: URL) -> (), onFailure: @escaping (_ error: Error?) -> ()) { if isAlbumExists() { doSaveAsset(destinationFileURL, onSuccess: onSuccess, onFailure: onFailure) return } PHPhotoLibrary.shared().performChanges({ PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: TwittaSaveAlbum.albumName) }) { success, _ in if success { self.assetCollection = self.fetchAssetCollectionForAlbum() self.doSaveAsset(destinationFileURL, onSuccess: onSuccess, onFailure: onFailure) } } } func doSaveAsset(_ destinationFileURL: URL, onSuccess: @escaping (_ url: URL) -> (), onFailure: @escaping (_ error: Error?) -> ()) { if self.assetCollection == nil { Logger.log(self.assetCollection) return } Logger.log("Saving...") PHPhotoLibrary.shared().performChanges({ if let creationRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationFileURL) { if let assetCollection = self.assetCollection { let addAssetRequest = PHAssetCollectionChangeRequest(for: assetCollection) addAssetRequest?.addAssets([creationRequest.placeholderForCreatedAsset!] as NSArray) } } }) { saved, error in if saved { Logger.log("Saved") let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let fetchResult = PHAsset.fetchAssets(in: self.assetCollection, options: fetchOptions).firstObject PHImageManager().requestAVAsset(forVideo: fetchResult!, options: nil, resultHandler: { (avurlAsset, audioMix, dict) in let newObj = avurlAsset as! AVURLAsset Logger.log(newObj.url) onSuccess(newObj.url) }) } else { onFailure(error) } } } }
35.018182
136
0.591641
087b08aac6210955d6e31d7a14b4b3c91d4e627a
641
// // MovieCell.swift // Flix_MovieViewer // // Created by Jamila Duke-Smith on 9/19/18. // Copyright © 2018 Jamila Duke-Smith. All rights reserved. // import UIKit class MovieCell: UITableViewCell { @IBOutlet var titleLabel: UILabel! @IBOutlet var overviewLabel: UILabel! @IBOutlet var posterImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
20.677419
65
0.661466