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
9ba7b502c88ebe1e2d58266e982ebf9da6582d33
4,312
// // ViewController.swift // Milestone4 // // Created by RAJ RAVAL on 09/09/19. // Copyright © 2019 Buck. All rights reserved. // import UIKit class ViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var photos = [Image]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = "Captioner" navigationController?.navigationBar.prefersLargeTitles = true let defaults = UserDefaults.standard if let savedPeople = defaults.object(forKey: "Photos") as? Data { let jsonDecoder = JSONDecoder() do { photos = try jsonDecoder.decode([Image].self, from: savedPeople) } catch { print("Failed to load people") } } navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addImage)) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return photos.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "Image", for: indexPath) as? ImageCell else { fatalError("Image Cell not found") } let photo = photos[indexPath.row] cell.captionLabel.text = photo.caption let path = getDocumentsDirectory().appendingPathComponent(photo.image) cell.captionImage.image = UIImage(contentsOfFile: path.path) return cell } @objc func addImage() { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self present(picker, animated: true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { guard let image = info[.editedImage] as? UIImage else { return } let imageName = UUID().uuidString let imagePath = getDocumentsDirectory().appendingPathComponent(imageName) if let jpegData = image.jpegData(compressionQuality: 0.8) { try? jpegData.write(to: imagePath) } let captionImage = Image(image: imageName, caption: "What's it?") photos.append(captionImage) save() tableView.reloadData() dismiss(animated: true) } func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0] } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let photo = photos[indexPath.row] let path = getDocumentsDirectory().appendingPathComponent(photo.image) let ac = UIAlertController(title: "Image Details", message: "What do you want to do?", preferredStyle: .alert) ac.addTextField() ac.addAction(UIAlertAction(title: "Rename", style: .default) { [weak self, weak ac] _ in guard let newName = ac?.textFields?[0].text else { return } photo.caption = newName self?.save() self?.tableView.reloadData() }) ac.addAction(UIAlertAction(title: "Show Image", style: .default){ [weak self] _ in if let vc = self?.storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController { vc.selectedImage = path.path vc.imageTitle = photo.caption self?.navigationController?.pushViewController(vc, animated: true) } }) present(ac, animated: true) } func save() { let jsonEncoder = JSONEncoder() if let savedData = try? jsonEncoder.encode(photos) { let defaults = UserDefaults.standard defaults.set(savedData, forKey: "Photos") } else { print("Failed to save Photos") } } }
34.222222
144
0.609926
1d524b88ccaced5adbdcb24a57eb4b0b246a80fa
674
// // NonConfirmedSummitAttendee.swift // OpenStackSummit // // Created by Alsey Coleman Miller on 6/2/16. // Copyright © 2016 OpenStack. All rights reserved. // public struct NonConfirmedAttendee: Named { public let identifier: Identifier public var firstName: String public var lastName: String } public extension NonConfirmedAttendee { var name: String { return firstName + " " + lastName } } // MARK: - Equatable public func == (lhs: NonConfirmedAttendee, rhs: NonConfirmedAttendee) -> Bool { return lhs.identifier == rhs.identifier && lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName }
21.741935
79
0.672107
f42697908ca391f8fa911cacd40d1d1bfe86485f
4,869
import XCTest import SwiftAST import SwiftRewriterLib import GlobalsProviders class CLibGlobalsProvidersTests: BaseGlobalsProviderTestCase { override func setUp() { super.setUp() sut = CLibGlobalsProviders() globals = sut.definitionsSource() types = sut.knownTypeProvider() typealiases = sut.typealiasProvider() } func testDefinedMathLibFunctions() { assertDefined(function: "abs", paramTypes: [cInt], returnType: cInt) assertDefined(function: "abs", paramTypes: [.int], returnType: .int) assertDefined(function: "fabsf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "fabs", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "fabs", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "asinf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "asin", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "asin", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "acosf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "acos", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "acos", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "atanf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "atan", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "atan", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "tanf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "tan", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "tan", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "sinf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "sin", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "sin", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "cosf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "cos", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "cos", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "atan2f", paramTypes: [cFloat, cFloat], returnType: cFloat) assertDefined(function: "atan2", paramTypes: [cDouble, cDouble], returnType: cDouble) assertDefined(function: "atan2", paramTypes: [.cgFloat, .cgFloat], returnType: .cgFloat) assertDefined(function: "sqrtf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "sqrt", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "sqrt", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "ceilf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "ceil", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "ceil", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "floorf", paramTypes: [cFloat], returnType: cFloat) assertDefined(function: "floor", paramTypes: [cDouble], returnType: cDouble) assertDefined(function: "floor", paramTypes: [.cgFloat], returnType: .cgFloat) assertDefined(function: "fmodf", paramTypes: [cFloat, cFloat], returnType: cFloat) assertDefined(function: "fmod", paramTypes: [cDouble, cDouble], returnType: cDouble) assertDefined(function: "fmod", paramTypes: [.cgFloat, .cgFloat], returnType: .cgFloat) assertDefined(function: "max", paramTypes: [.int, .int], returnType: .int) assertDefined(function: "max", paramTypes: [cInt, cInt], returnType: cInt) assertDefined(function: "max", paramTypes: [.cgFloat, .cgFloat], returnType: .cgFloat) assertDefined(function: "max", paramTypes: [.float, .float], returnType: .float) assertDefined(function: "max", paramTypes: [cFloat, cFloat], returnType: cFloat) assertDefined(function: "max", paramTypes: [.double, .double], returnType: .double) assertDefined(function: "min", paramTypes: [.int, .int], returnType: .int) assertDefined(function: "min", paramTypes: [cInt, cInt], returnType: cInt) assertDefined(function: "min", paramTypes: [.cgFloat, .cgFloat], returnType: .cgFloat) assertDefined(function: "min", paramTypes: [.float, .float], returnType: .float) assertDefined(function: "min", paramTypes: [cFloat, cFloat], returnType: cFloat) assertDefined(function: "min", paramTypes: [.double, .double], returnType: .double) } }
57.282353
96
0.66872
dbece4f509a72e71eb3f54da7d77b84baa6bd262
731
// RUN: %target-resilience-test // REQUIRES: executable_test // UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic import StdlibUnittest import struct_change_stored_to_computed var ChangeStoredToComputedTest = TestSuite("ChangeStoredToComputed") ChangeStoredToComputedTest.test("ChangeStoredToComputed") { var t = ChangeStoredToComputed() do { expectEqual(t.celsius, 0) expectEqual(t.fahrenheit, 32) } do { t.celsius = 10 expectEqual(t.celsius, 10) expectEqual(t.fahrenheit, 50) } do { func increaseTemperature(_ t: inout Int) { t += 10 } increaseTemperature(&t.celsius) expectEqual(t.celsius, 20) expectEqual(t.fahrenheit, 68) } } runAllTests()
18.74359
68
0.722298
d633ffbda01e578afcab11ca187e8c5f287d9719
239
// // DebugNavigationController.swift // lendstar // // Created by ben on 22.08.17. // Copyright © 2017 Lendstar GmbH. All rights reserved. // import Foundation public class DebugNavigationController: UINavigationController { }
17.071429
64
0.728033
8add1576ae7786a28a02bcf3a76692d3d6df61db
439
// // MineViewController.swift // RPChat_iOS // // Created by rp.wang on 2020/12/11. // Copyright © 2020 Beijing Physical Fitness Sport Science and Technology Co.,Ltd. All rights reserved. // import UIKit class MineViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. title = NSLocalizedString("Me", comment: "") } }
23.105263
104
0.681093
2122ed9a59d957e44d18e0bfd3d5b675e9921d7f
1,066
// // PokemonListUseCase.swift // Domain // // Created by Tomosuke Okada on 2020/03/07. // import DataStore import Foundation public enum PokemonListUseCaseProvider { public static func provide() -> PokemonListUseCase { return PokemonListUseCaseImpl( repository: PokemonListRepositoryProvider.provide(), translator: PokemonListTranslatorProvider.provide() ) } } public protocol PokemonListUseCase { func get(completion: @escaping ((Result<PokemonListModel, Error>) -> Void)) } private struct PokemonListUseCaseImpl: PokemonListUseCase { let repository: PokemonListRepository let translator: PokemonListTranslator func get(completion: @escaping ((Result<PokemonListModel, Error>) -> Void)) { self.repository.get { result in switch result { case .success(let response): completion(.success(self.translator.convert(from: response))) case .failure(let error): completion(.failure(error)) } } } }
26
81
0.660413
6933b74efa12823f4478954d65dca01ccb712723
223
// // DecimalUtils.swift // Bankey // // Created by PARAIPAN SORIN on 18.02.2022. // import Foundation extension Decimal { var doubleValue: Double { return NSDecimalNumber(decimal:self).doubleValue } }
14.866667
56
0.672646
71fb4ea529216ff005cb28290b6f7adabc870397
877
// // DemoTests.swift // DemoTests // // Created by Stroman on 2021/9/1. // import XCTest @testable import Demo class DemoTests: 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. } } }
25.794118
111
0.656784
d60a032dd9d94b094e75bba4438fbbe3d37a3503
342
// // MovieDetailViewModel.swift // RedCarpetMVVM // // Created by Göksel Köksal on 16.10.2017. // Copyright © 2017 Packt. All rights reserved. // import Foundation import Commons final class MovieDetailViewModel: MovieDetailViewModelProtocol { let movie: Movie init(movie: Movie) { self.movie = movie } }
17.1
64
0.678363
09707382d9add21c299ee8bf30625f8966081a88
1,022
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** An array of values, each being the `id` value of a row header that is applicable to this body cell. */ public struct RowHeaderIDs: Codable, Equatable { /** The `id` values of a row header. */ public var id: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case id = "id" } }
29.2
100
0.704501
db0f0fe67ab97c9051d9ccfecafc63dc3521b6f7
719
// This class is automatically included in FastlaneRunner during build // This autogenerated file will be overwritten or replaced during build time, or when you initialize `match` // // ** NOTE ** // This file is provided by fastlane and WILL be overwritten in future updates // If you want to add extra functionality to this project, create a new file in a // new group so that it won't be marked for upgrade // class Matchfile: MatchfileProtocol { // If you want to enable `match`, run `fastlane match init` // After, this file will be replaced with a custom implementation that contains values you supplied // during the `init` process, and you won't see this message } // Generated with fastlane 2.141.0
32.681818
108
0.746871
e2a952f4387056fed83f9fddd0a63b708dd657b0
959
// // NotificationController.swift // WatchExampleApp WatchKit Extension // // Created by Sean Najera on 1/4/22. // import WatchKit import SwiftUI import UserNotifications class NotificationController: WKUserNotificationHostingController<NotificationView> { override var body: NotificationView { return NotificationView() } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func didReceive(_ notification: UNNotification) { // This method is called when a notification needs to be presented. // Implement it if you use a dynamic notification interface. // Populate your dynamic notification interface as quickly as possible. } }
28.205882
90
0.710115
39de922d394e907588a76aaf7a2322e7be8d6625
3,120
import Foundation import azureSwiftRuntime public protocol DefaultSecurityRulesGet { var headerParameters: [String: String] { get set } var resourceGroupName : String { get set } var networkSecurityGroupName : String { get set } var defaultSecurityRuleName : String { get set } var subscriptionId : String { get set } var apiVersion : String { get set } func execute(client: RuntimeClient, completionHandler: @escaping (SecurityRuleProtocol?, Error?) -> Void) -> Void ; } extension Commands.DefaultSecurityRules { // Get get the specified default network security rule. internal class GetCommand : BaseCommand, DefaultSecurityRulesGet { public var resourceGroupName : String public var networkSecurityGroupName : String public var defaultSecurityRuleName : String public var subscriptionId : String public var apiVersion = "2018-01-01" public init(resourceGroupName: String, networkSecurityGroupName: String, defaultSecurityRuleName: String, subscriptionId: String) { self.resourceGroupName = resourceGroupName self.networkSecurityGroupName = networkSecurityGroupName self.defaultSecurityRuleName = defaultSecurityRuleName self.subscriptionId = subscriptionId super.init() self.method = "Get" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules/{defaultSecurityRuleName}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{networkSecurityGroupName}"] = String(describing: self.networkSecurityGroupName) self.pathParameters["{defaultSecurityRuleName}"] = String(describing: self.defaultSecurityRuleName) self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.queryParameters["api-version"] = String(describing: self.apiVersion) } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) let result = try decoder.decode(SecurityRuleData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (SecurityRuleProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: SecurityRuleData?, error: Error?) in completionHandler(result, error) } } } }
50.322581
217
0.666987
e5276f704227bb79b5e867aaa49c4d98ac3d9935
379
import XCTest @testable import FabulaItemsProvider final class FabulaItemsProviderTests: XCTestCase { func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. // XCTAssertEqual(FabulaItemsProvider().text, "Hello, World!") } }
31.583333
87
0.699208
4b72e0b32fe73ed46c8d7387f160555f13d13d73
1,620
// // HCIWriteScanEnable.swift // Bluetooth // // Created by Carlos Duclos on 8/16/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// Write Scan Enable Command /// /// This command writes the value for the Scan_Enable configuration parameter. func writeScanEnable(scanEnable: HCIWriteScanEnable.ScanEnable, timeout: HCICommandTimeout = .default) throws { let command = HCIWriteScanEnable(scanEnable: scanEnable) return try deviceRequest(command, timeout: timeout) } } // MARK: - Command /// Write Scan Enable Command /// /// This command writes the value for the Scan_Enable configuration parameter. public struct HCIWriteScanEnable: HCICommandParameter { public static let command = HostControllerBasebandCommand.writeScanEnable public var scanEnable: ScanEnable public init(scanEnable: ScanEnable) { self.scanEnable = scanEnable } public var data: Data { return Data([scanEnable.rawValue]) } } extension HCIWriteScanEnable { public enum ScanEnable: UInt8 { /// No Scans enabled. Default. case noScans = 0x00 /// Inquiry Scan enabled. Page Scan disabled. case onlyInquiryScan = 0x01 /// Inquiry Scan disabled. Page Scan enabled. case onlyPageScan = 0x02 /// Inquiry Scan enabled. Page Scan enabled. case inquiryAndPageScan = 0x03 } }
24.545455
82
0.642593
ac787a31be308abf2aa3c2ef9dfc56d88c789963
17,536
import UIKit class PhotoObject { var pid: Int? //照片 id var uid: Int? //用户 id var origin: String? //原始图片 id var scale: Double? //图像比例 宽/高 var wbpid: String? //微博图片 id var preset: String? //滤镜名称 字符串 var unix: Int64? //发布时间 var aperture: Double? //光圈值 16-11-10 新增(最多1位小数) var iso: Int? //ISO 值 16-11-10 新增 var gps: String? //GPS 值 16-11-10 新增 var text: String? //图片标题 16-11-10 新增 //extern var user: UserObject? init?(_ dict: Any?) { if let tryDict = dict as? NSDictionary { pid = Int.fromJson(tryDict.value(forKey: "pid")) uid = Int.fromJson(tryDict.value(forKey: "uid")) origin = String.fromJson(tryDict.value(forKey: "origin")) scale = Double.fromJson(tryDict.value(forKey: "scale")) wbpid = String.fromJson(tryDict.value(forKey: "wbpid")) preset = String.fromJson(tryDict.value(forKey: "preset")) unix = Int64.fromJson(tryDict.value(forKey: "unix")) aperture = Double.fromJson(tryDict.value(forKey: "aperture")) iso = Int.fromJson(tryDict.value(forKey: "iso")) gps = String.fromJson(tryDict.value(forKey: "gps")) text = String.fromJson(tryDict.value(forKey: "text")) } else { return nil } } } class UserObject { var uid: Int? //用户 id var name: String? //用户名 var avatar: Int? //用户头像 id init?(uid: Int?, name: String?, avatar: Int?) { if let tryUid = uid, let tryName = name, let tryAvatar = avatar { self.uid = tryUid self.name = tryName self.avatar = tryAvatar } else { return nil } } init?(_ dict: Any?) { if let tryDict = dict as? NSDictionary { uid = Int.fromJson(tryDict.value(forKey: "uid")) name = String.fromJson(tryDict.value(forKey: "name")) avatar = Int.fromJson(tryDict.value(forKey: "avatar")) } else { return nil } } func avatarUrl(isBig: Bool = true) -> String? { if let tryAvatar = avatar { if tryAvatar != 0 { if let tryAvatar = uid { let emptyUrl = (isBig ? NetworkURL.avatarBig : NetworkURL.avatarSmall) return emptyUrl.replace(string: "{avatar}", with: "\(tryAvatar)") } } } return nil } } class ImageListObject { var grids: [PhotoObject]? //照片们 var users: [UserObject]? //用户们 init() { grids = [PhotoObject]() users = [UserObject]() } init?(_ dict: Any?) { if let tryDict = dict as? NSDictionary { if let dataList = tryDict["users"] as? NSArray { var tempList = [UserObject]() for data in dataList { if let tryObject = UserObject(data as? NSDictionary) { tempList.append(tryObject) } } users = tempList } if let dataList = tryDict["grids"] as? NSArray { var tempList = [PhotoObject]() for data in dataList { if let tryObject = PhotoObject(data as? NSDictionary) { if let tryUID = tryObject.uid { tryObject.user = getUserBy(UID: tryUID) } tempList.append(tryObject) } } grids = tempList } } else { return nil } } func getUserBy(UID: Int) -> UserObject? { if let tryUsers = users { for user in tryUsers { if user.uid == UID { return user } } } return nil } func append(newObject: ImageListObject) { var finalNewImageList = [PhotoObject]() if let tryNewImageList = newObject.grids, let tryOldImageList = grids { for newImage in tryNewImageList { var markHas = false for oldImage in tryOldImageList { if oldImage.pid == newImage.pid { markHas = true break } } if markHas == false { finalNewImageList.append(newImage) } } grids?.append(contentsOf: finalNewImageList) } var finalNewUserList = [UserObject]() if let tryNewUserList = newObject.users, let tryOldUserList = users { for newUser in tryNewUserList { var markHas = false for oldUser in tryOldUserList { if oldUser.uid == newUser.uid { markHas = true break } } if markHas == false { finalNewUserList.append(newUser) } } users?.append(contentsOf: finalNewUserList) } } } class COMPUTEDObject { var html: String? var Height: Int? var Width: Int? var IsColor: Int? var ByteOrderMotorola: Int? var ApertureFNumber: String? var Thumbnail_FileType: Int? var Thumbnail_MimeType: String? init?(_ dict: Any?) { if let tryDict = dict as? NSDictionary { html = String.fromJson(tryDict.value(forKey: "html")) Height = Int.fromJson(tryDict.value(forKey: "Height")) Width = Int.fromJson(tryDict.value(forKey: "Width")) IsColor = Int.fromJson(tryDict.value(forKey: "IsColor")) ByteOrderMotorola = Int.fromJson(tryDict.value(forKey: "ByteOrderMotorola")) ApertureFNumber = String.fromJson(tryDict.value(forKey: "ApertureFNumber")) Thumbnail_FileType = Int.fromJson(tryDict.value(forKey: "Thumbnail.FileType")) Thumbnail_MimeType = String.fromJson(tryDict.value(forKey: "Thumbnail.MimeType")) } else { return nil } } } class IFD0Object { var ImageWidth: Int? var ImageLength: Int? var BitsPerSample: [Int]? var PhotometricInterpretation: Int? var ImageDescription: String? var Make: String? var Model: String? var Orientation: Int? var SamplesPerPixel: Int? var XResolution: String? var YResolution: String? var ResolutionUnit: Int? var Software: String? var DateTime: String? var Exif_IFD_Pointer: Int? var GPS_IFD_Pointer: Int? init?(_ dict: Any?) { if let tryDict = dict as? NSDictionary { ImageWidth = Int.fromJson(tryDict.value(forKey: "ImageWidth")) ImageLength = Int.fromJson(tryDict.value(forKey: "ImageLength")) if let dataList = tryDict["BitsPerSample"] as? NSArray { var tempList = [Int]() for data in dataList { if let tryObject = Int.fromJson(data) { tempList.append(tryObject) } } BitsPerSample = tempList } PhotometricInterpretation = Int.fromJson(tryDict.value(forKey: "PhotometricInterpretation")) ImageDescription = String.fromJson(tryDict.value(forKey: "ImageDescription")) Make = String.fromJson(tryDict.value(forKey: "Make")) Model = String.fromJson(tryDict.value(forKey: "Model")) Orientation = Int.fromJson(tryDict.value(forKey: "Orientation")) SamplesPerPixel = Int.fromJson(tryDict.value(forKey: "SamplesPerPixel")) XResolution = String.fromJson(tryDict.value(forKey: "XResolution")) YResolution = String.fromJson(tryDict.value(forKey: "YResolution")) ResolutionUnit = Int.fromJson(tryDict.value(forKey: "ResolutionUnit")) Software = String.fromJson(tryDict.value(forKey: "Software")) DateTime = String.fromJson(tryDict.value(forKey: "DateTime")) Exif_IFD_Pointer = Int.fromJson(tryDict.value(forKey: "Exif_IFD_Pointer")) GPS_IFD_Pointer = Int.fromJson(tryDict.value(forKey: "GPS_IFD_Pointer")) } else { return nil } } } class EXIFObject { var ExposureTime: String? var FNumber: String? var ExposureProgram: Int? var ISOSpeedRatings: Int? var ExifVersion: String? var DateTimeOriginal: String? var DateTimeDigitized: String? var ComponentsConfiguration: String? var ShutterSpeedValue: String? var ApertureValue: String? var BrightnessValue: String? var ExposureBiasValue: String? var MeteringMode: Int? var Flash: Int? var FocalLength: String? var SubjectLocation: [Int]? var SubSecTimeOriginal: String? var SubSecTimeDigitized: String? var FlashPixVersion: String? var ColorSpace: Int? var ExifImageWidth: Int? var ExifImageLength: Int? var SensingMethod: Int? var SceneType: String? var ExposureMode: Int? var WhiteBalance: Int? var FocalLengthIn35mmFilm: Int? var SceneCaptureType: Int? var UndefinedTag_0xA432: [String]? var UndefinedTag_0xA433: String? var UndefinedTag_0xA434: String? init?(_ dict: Any?) { if let tryDict = dict as? NSDictionary { ExposureTime = String.fromJson(tryDict.value(forKey: "ExposureTime")) FNumber = String.fromJson(tryDict.value(forKey: "FNumber")) ExposureProgram = Int.fromJson(tryDict.value(forKey: "ExposureProgram")) ISOSpeedRatings = Int.fromJson(tryDict.value(forKey: "ISOSpeedRatings")) ExifVersion = String.fromJson(tryDict.value(forKey: "ExifVersion")) DateTimeOriginal = String.fromJson(tryDict.value(forKey: "DateTimeOriginal")) DateTimeDigitized = String.fromJson(tryDict.value(forKey: "DateTimeDigitized")) ComponentsConfiguration = String.fromJson(tryDict.value(forKey: "ComponentsConfiguration")) ShutterSpeedValue = String.fromJson(tryDict.value(forKey: "ShutterSpeedValue")) ApertureValue = String.fromJson(tryDict.value(forKey: "ApertureValue")) BrightnessValue = String.fromJson(tryDict.value(forKey: "BrightnessValue")) ExposureBiasValue = String.fromJson(tryDict.value(forKey: "ExposureBiasValue")) MeteringMode = Int.fromJson(tryDict.value(forKey: "MeteringMode")) Flash = Int.fromJson(tryDict.value(forKey: "Flash")) FocalLength = String.fromJson(tryDict.value(forKey: "FocalLength")) if let dataList = tryDict["SubjectLocation"] as? NSArray { var tempList = [Int]() for data in dataList { if let tryObject = Int.fromJson(data) { tempList.append(tryObject) } } SubjectLocation = tempList } SubSecTimeOriginal = String.fromJson(tryDict.value(forKey: "SubSecTimeOriginal")) SubSecTimeDigitized = String.fromJson(tryDict.value(forKey: "SubSecTimeDigitized")) FlashPixVersion = String.fromJson(tryDict.value(forKey: "FlashPixVersion")) ColorSpace = Int.fromJson(tryDict.value(forKey: "ColorSpace")) ExifImageWidth = Int.fromJson(tryDict.value(forKey: "ExifImageWidth")) ExifImageLength = Int.fromJson(tryDict.value(forKey: "ExifImageLength")) SensingMethod = Int.fromJson(tryDict.value(forKey: "SensingMethod")) SceneType = String.fromJson(tryDict.value(forKey: "SceneType")) ExposureMode = Int.fromJson(tryDict.value(forKey: "ExposureMode")) WhiteBalance = Int.fromJson(tryDict.value(forKey: "WhiteBalance")) FocalLengthIn35mmFilm = Int.fromJson(tryDict.value(forKey: "FocalLengthIn35mmFilm")) SceneCaptureType = Int.fromJson(tryDict.value(forKey: "SceneCaptureType")) if let dataList = tryDict["UndefinedTag:0xA432"] as? NSArray { var tempList = [String]() for data in dataList { if let tryObject = String.fromJson(data) { tempList.append(tryObject) } } UndefinedTag_0xA432 = tempList } UndefinedTag_0xA433 = String.fromJson(tryDict.value(forKey: "UndefinedTag:0xA433")) UndefinedTag_0xA434 = String.fromJson(tryDict.value(forKey: "UndefinedTag:0xA434")) } else { return nil } } } class ExifInfoObject { var COMPUTED: COMPUTEDObject? var IFD0: IFD0Object? var EXIF: EXIFObject? init?(_ dict: Any?) { if let tryDict = dict as? NSDictionary { COMPUTED = COMPUTEDObject(tryDict.value(forKey: "COMPUTED") as? NSDictionary) IFD0 = IFD0Object(tryDict.value(forKey: "IFD0") as? NSDictionary) EXIF = EXIFObject(tryDict.value(forKey: "EXIF") as? NSDictionary) } else { return nil } } } class PhotoDetailObject { var pid: Int? //图片 id var uid: Int? //用户 id var wbpid: String? //微博图片 id var scale: Double? //图像比例 宽/高 var origin: String? //原始图片 id var text: String? //图片简介文字 var preset: String? //滤镜名称 var gps: String? //GPS 地理信息 var look: String? //查看数 基本没用 var like: String? //喜欢数 基本没用 var state: String? //状态 基本没用 var unix: Int64? //新建时间 var exif: ExifInfoObject? //详细的 EXIF 信息 光圈 ISO 等信息都在这里 var user: UserObject? //用户信息 init?(_ dict: Any?) { if let tryDict = dict as? NSDictionary { pid = Int.fromJson(tryDict.value(forKey: "pid")) uid = Int.fromJson(tryDict.value(forKey: "uid")) wbpid = String.fromJson(tryDict.value(forKey: "wbpid")) scale = Double.fromJson(tryDict.value(forKey: "scale")) origin = String.fromJson(tryDict.value(forKey: "origin")) text = String.fromJson(tryDict.value(forKey: "text")) preset = String.fromJson(tryDict.value(forKey: "preset")) gps = String.fromJson(tryDict.value(forKey: "gps")) look = String.fromJson(tryDict.value(forKey: "look")) like = String.fromJson(tryDict.value(forKey: "like")) state = String.fromJson(tryDict.value(forKey: "state")) unix = Int64.fromJson(tryDict.value(forKey: "unix")) exif = ExifInfoObject(tryDict.value(forKey: "exif") as? NSDictionary) user = UserObject(tryDict.value(forKey: "user") as? NSDictionary) } else { return nil } } } class PhotoUploadObject { var uid: Int? //用户id var scale: Double? //比例 var origin: String? //原始图片地址 var aperture: Int? var iso: Int? var gps: String? var unix: Int64? //新建时间 var exif: String? var pid: Int? //图片 ID init?(_ dict: Any?) { if let tryDict = dict as? NSDictionary { uid = Int.fromJson(tryDict.value(forKey: "uid")) scale = Double.fromJson(tryDict.value(forKey: "scale")) origin = String.fromJson(tryDict.value(forKey: "origin")) aperture = Int.fromJson(tryDict.value(forKey: "aperture")) iso = Int.fromJson(tryDict.value(forKey: "iso")) gps = String.fromJson(tryDict.value(forKey: "gps")) unix = Int64.fromJson(tryDict.value(forKey: "unix")) exif = String.fromJson(tryDict.value(forKey: "exif")) pid = Int.fromJson(tryDict.value(forKey: "pid")) } else { return nil } } } class UserInfoObject: UserObject { var des: String? //简介 var url: String? //网站 init?(uid: Int?, name: String?, avatar: Int?, des: String?, url: String?) { super.init(uid: uid, name: name, avatar: avatar) if let tryDes = des, let tryUrl = url { self.des = tryDes self.url = tryUrl } else { return nil } } override init?(_ dict: Any?) { super.init(dict) if let tryDict = dict as? NSDictionary { des = String.fromJson(tryDict.value(forKey: "des")) url = String.fromJson(tryDict.value(forKey: "url")) } else { return nil } } } class UserSelfInfoObject: UserInfoObject { var group: Int? var look: Int? var like: Int? init?(uid: Int?, name: String?, avatar: Int?, des: String?, url: String?, group: Int?, look: Int?, like: Int?) { super.init(uid: uid, name: name, avatar: avatar, des: des, url: url) if let tryGroup = group, let tryLook = look, let tryLike = like { self.group = tryGroup self.look = tryLook self.like = tryLike } else { return nil } } override init?(_ dict: Any?) { super.init(dict) if let tryDict = dict as? NSDictionary { group = Int.fromJson(tryDict.value(forKey: "group")) look = Int.fromJson(tryDict.value(forKey: "look")) like = Int.fromJson(tryDict.value(forKey: "like")) } else { return nil } } }
36.917895
116
0.566834
e444848720ab47cd84ebec94c59d6580973761ea
1,726
// swift-tools-version:5.5 import PackageDescription let package = Package( name: "swift-composable-architecture", platforms: [ .iOS(.v13), .macOS(.v10_15), .tvOS(.v13), .watchOS(.v6), ], products: [ .library( name: "ComposableArchitecture", targets: ["ComposableArchitecture"] ) ], dependencies: [ .package(name: "Benchmark", url: "https://github.com/google/swift-benchmark", from: "0.1.0"), .package(url: "https://github.com/pointfreeco/combine-schedulers", from: "0.5.3"), .package(url: "https://github.com/pointfreeco/swift-case-paths", from: "0.8.0"), .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "0.3.0"), .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "0.3.2"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "0.2.1"), ], targets: [ .target( name: "ComposableArchitecture", dependencies: [ .product(name: "CasePaths", package: "swift-case-paths"), .product(name: "CombineSchedulers", package: "combine-schedulers"), .product(name: "CustomDump", package: "swift-custom-dump"), .product(name: "IdentifiedCollections", package: "swift-identified-collections"), .product(name: "XCTestDynamicOverlay", package: "xctest-dynamic-overlay"), ] ), .testTarget( name: "ComposableArchitectureTests", dependencies: [ "ComposableArchitecture" ] ), .executableTarget( name: "swift-composable-architecture-benchmark", dependencies: [ "ComposableArchitecture", .product(name: "Benchmark", package: "Benchmark"), ] ), ] )
32.566038
97
0.632677
719516e6f0ad0acbee51cea54980e5a018bb7a1d
9,555
// Copyright (c) 2014 Rob Rix. All rights reserved. /// An iterable stream. public enum Stream<T>: ArrayLiteralConvertible, NilLiteralConvertible, Printable, ReducibleType { // MARK: Lifecycle /// Initializes with a ReducibleType. public init<R: ReducibleType where R.Element == T>(_ reducible: R) { let reducer: Reducible<R, Stream, T>.Enumerator -> Reducible<R, Stream, T>.Enumerator = reducible.reducer() let reduce: Reducible<R, Stream, T>.Enumerator = fix { recur in reducer { reducible, initial, combine in initial.first.map { .cons($0, recur(reducible, nil, combine)) } ?? nil } } self = reduce(reducible, nil) { .right(.unit($1)) } } /// Initializes with a generating function. public init(_ f: () -> T?) { self = Stream.construct(f)() } /// Initializes with a `SequenceType`. public init<S: SequenceType where S.Generator.Element == T>(_ sequence: S) { var generator = sequence.generate() self.init({ generator.next() }) } /// Maps a generator of `T?` into a generator of `Stream`. public static func construct(generate: () -> T?) -> () -> Stream<T> { return fix { recur in { generate().map { self.cons($0, recur()) } ?? nil } } } /// Constructs a `Stream` from `first` and its `@autoclosure`’d continuation. public static func cons(first: T, _ rest: @autoclosure () -> Stream) -> Stream { return Cons(Box(first), Memo(unevaluated: rest)) } /// Constructs a `Stream` from `first` and its `Memo`ized continuation. public static func cons(first: T, _ rest: Memo<Stream>) -> Stream { return Cons(Box(first), rest) } /// Constructs a unary `Stream` of `x`. public static func unit(x: T) -> Stream { return Cons(Box(x), Memo(nil)) } /// Constructs a `Stream` of `reducible`. Unlike the corresponding `init`, this is suitable for function composition. public static func with<R: ReducibleType where R.Element == T>(reducible: R) -> Stream { return Stream(reducible) } // MARK: Properties /// The first element of the receiver, or `nil` if the receiver is the empty stream. public var first: T? { return uncons()?.0 } /// The remainder of the receiver after its first element. If the receiver is the empty stream, this will return the empty stream. public var rest: Stream { return uncons()?.1.value ?? nil } /// Unpacks the receiver into an optional tuple of its first element and the memoized remainder. /// /// Returns `nil` if the receiver is the empty stream. public func uncons() -> (T, Memo<Stream>)? { switch self { case let Cons(x, rest): return (x.value, rest) case Nil: return nil } } // MARK: Combinators /// Returns a `Stream` of the first `n` elements of the receiver. /// /// If `n` <= 0, returns the empty `Stream`. public func take(n: Int) -> Stream { if n <= 0 { return nil } return uncons().map { .cons($0, $1.value.take(n - 1)) } ?? nil } /// Returns a `Stream` without the first `n` elements of `stream`. /// /// If `n` <= 0, returns the receiver. /// /// If `n` <= the length of the receiver, returns the empty `Stream`. public func drop(n: Int) -> Stream { if n <= 0 { return self } return rest.drop(n - 1) } /// Returns a `Stream` produced by mapping the elements of the receiver with `f`. public func map<U>(f: T -> U) -> Stream<U> { return uncons().map { .cons(f($0), $1.value.map(f)) } ?? nil } /// Folds the receiver starting from a given `seed` using the left-associative function `combine`. public func foldLeft<Result>(seed: Result, _ combine: (Result, T) -> Result) -> Result { return foldLeft(seed, combine >>> Either.right) } /// Folds the receiver starting from a given `seed` using the left-associative function `combine`. /// /// `combine` should return `.Left(x)` to terminate the fold with `x`, or `.Right(x)` to continue the fold. public func foldLeft<Result>(seed: Result, _ combine: (Result, T) -> Either<Result, Result>) -> Result { return uncons().map { first, rest in combine(seed, first).either(id, { rest.value.foldLeft($0, combine) }) } ?? seed } /// Folds the receiver ending with a given `seed` using the right-associative function `combine`. public func foldRight<Result>(seed: Result, _ combine: (T, Result) -> Result) -> Result { return uncons().map { combine($0, $1.value.foldRight(seed, combine)) } ?? seed } /// Folds the receiver ending with a given `seed` using the right-associative function `combine`. /// /// `combine` receives the accumulator as a lazily memoized value. Thus, `combine` may terminate the fold simply by not evaluating the memoized accumulator. public func foldRight<Result>(seed: Result, _ combine: (T, Memo<Result>) -> Result) -> Result { return uncons().map { combine($0, $1.map { $0.foldRight(seed, combine) }) } ?? seed } /// Unfolds a new `Stream` starting from the initial state `state` and producing pairs of new states and values with `unspool`. /// /// This is dual to `foldRight`. Where `foldRight` takes a right-associative combine function which takes the current value and the current accumulator and returns the next accumulator, `unfoldRight` takes the current state and returns the current value and the next state. public static func unfoldRight<State>(state: State, unspool: State -> (T, State)?) -> Stream { return unspool(state).map { value, next in self.cons(value, self.unfoldRight(next, unspool)) } ?? nil } /// Unfolds a new `Stream` starting from the initial state `state` and producing pairs of new states and values with `unspool`. /// /// Since this unfolds to the left, it produces an eager `Stream` and thus is unsuitable for infinite `Stream`s. /// /// This is dual to `foldLeft`. Where `foldLeft` takes a right-associative combine function which takes the current value and the current accumulator and returns the next accumulator, `unfoldLeft` takes the current state and returns the current value and the next state. public static func unfoldLeft<State>(state: State, unspool: State -> (State, T)?) -> Stream { // An alternative implementation replaced the cons in `unfoldRight`’s definition with the concatenation of recurrence and the value. While quite elegant, it ended up being a third slower. // // This would be a recursive function definition, except that local functions are disallowed from recurring. return fix { prepend in { state, stream in unspool(state).map { next, value in prepend(next, self.cons(value, stream)) } ?? stream } } (state, nil) } /// Produces a `Stream` by mapping the elements of the receiver into reducibles and concatenating their elements. public func flattenMap<R: ReducibleType>(f: T -> R) -> Stream<R.Element> { return foldRight(nil, f >>> Stream<R.Element>.with >>> (++)) } // MARK: ArrayLiteralConvertible public init(arrayLiteral elements: T...) { self.init(elements) } // MARK: NilLiteralConvertible /// Constructs a `Nil` `Stream`. public init(nilLiteral: ()) { self = Nil } // MARK: Printable public var description: String { let internalDescription: Stream -> [String] = fix { internalDescription in { switch $0 { case let Cons(x, rest): return [toString(x.value)] + internalDescription(rest.value) default: return [] } } } return "(" + join(" ", internalDescription(self)) + ")" } // MARK: ReducibleType public func reducer<Result>() -> Reducible<Stream, Result, T>.Enumerator -> Reducible<Stream, Result, T>.Enumerator { return { recur in { stream, initial, combine in stream.first.map { combine(initial, $0).either(id, { recur(stream.rest, $0, combine) }) } ?? initial } } } // MARK: Cases /// A `Stream` of a `T` and the lazily memoized rest of the `Stream`. /// /// Avoid using this directly; instead, use `Stream.cons()` or `Stream.unit()` to construct streams, and `stream.first`, `stream.rest`, and `stream.uncons()` to deconstruct them: they don’t require you to `Box` or unbox, `Stream.cons()` comes in `@autoclosure` and `Memo` varieties, and `Stream.unit()`, `Stream.cons()`, and `stream.uncons()` are all usable as first-class functions. case Cons(Box<T>, Memo<Stream<T>>) /// The empty `Stream`. /// /// Avoid using this directly; instead, use `nil`: `Stream` conforms to `NilLiteralConvertible`, and `nil` has better properties with respect to type inferencing. case Nil } // MARK: Concatenation infix operator ++ { associativity right precedence 145 } /// Produces the concatenation of `left` and `right`. public func ++ <T> (left: Stream<T>, right: Stream<T>) -> Stream<T> { return left.uncons().map { .cons($0, Memo($1.value ++ right)) } ?? right } // MARK: Equality. /// Equality of `Stream`s of `Equatable` types. /// /// We cannot declare that `Stream<T: Equatable>` conforms to `Equatable`, so this is defined ad hoc. public func == <T: Equatable> (lhs: Stream<T>, rhs: Stream<T>) -> Bool { switch (lhs, rhs) { case let (.Cons(x, xs), .Cons(y, ys)) where x == y: return xs.value == ys.value case (.Nil, .Nil): return true default: return false } } /// Inequality of `Stream`s of `Equatable` types. /// /// We cannot declare that `Stream<T: Equatable>` conforms to `Equatable`, so this is defined ad hoc. public func != <T: Equatable> (lhs: Stream<T>, rhs: Stream<T>) -> Bool { switch (lhs, rhs) { case let (.Cons(x, xs), .Cons(y, ys)) where x == y: return xs.value != ys.value case (.Nil, .Nil): return false default: return true } } // MARK: Imports import Box import Either import Memo import Prelude
33.526316
384
0.673155
4afcff5b0e8a2af945ba0243a19cc8a42bb0a835
499
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // ProxyResourceProtocol is the Resource model definition. public protocol ProxyResourceProtocol : Codable { var id: String? { get set } var name: String? { get set } var type: String? { get set } var eTag: String? { get set } }
38.384615
96
0.701403
239201f779586dd03bbcccbe8b5a31a382cf76b3
1,239
// // GlobalState.swift // ProjectEuler100NEW // // Created by Jan-Erik LORFEO on 22.03.20. // Copyright © 2020 jel. All rights reserved. // import Foundation enum Constants { static let userDefaults = UserDefaults.standard static let challengesKey = "CHALLENGES" } class GlobalState: ObservableObject { @Published var challenges: [Challenge] { didSet { let encoded = try? JSONEncoder().encode(challenges) Constants.userDefaults.set(encoded, forKey: Constants.challengesKey) } } init() { if let challenges = Constants.userDefaults.array(forKey: Constants.challengesKey) as? [Challenge] { self.challenges = challenges } else { let challenges = Bundle.main.decode([Challenge].self, from: "initialChallenges.json") self.challenges = challenges } } func reset() { let challenges = Bundle.main.decode([Challenge].self, from: "initialChallenges.json") self.challenges = challenges } func finish(challenge: Challenge) { let completedChallenge = Challenge(id: challenge.id, name: challenge.name, status: .done) challenges[challenge.id - 1] = completedChallenge } }
28.813953
107
0.652139
29fe4aee781f00cbb9f2cb87e6c67daa78031f33
1,315
// // LineSDKConstant.swift // // Copyright (c) 2016-present, LINE Corporation. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by LINE Corporation. // // As with any software that integrates with the LINE Corporation platform, your use of this software // is subject to the LINE Developers Agreement [http://terms2.line.me/LINE_Developers_Agreement]. // This copyright notice shall be included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation #if !LineSDKCocoaPods import LineSDK #endif @objcMembers public class LineSDKConstant: NSObject { public static let SDKVersion = Constant.SDKVersion }
42.419355
102
0.7673
d67342c3e5fa43912f3edca271e2ebdfde71fdab
697
// // Logger.swift // Sample // // Created by Théophane Rupin on 5/20/18. // Copyright © 2018 Scribd. All rights reserved. // import Foundation public enum LogLevel: String { case error = "ERROR" case warning = "WARNING" case debug = "DEBUG" case info = "INFO" } public final class Logger { public init() { // no op } public func log(_ level: LogLevel, _ message: String, file: StringLiteralType = #file, function: StringLiteralType = #function, line: Int = #line) { print("[\(level.rawValue)] [\(file):\(function):\(line)] - \(message)") } }
21.121212
79
0.527977
ed85f77e059931bf429c5c1b109d8194bc3b2899
1,212
// Copyright © 2021 Brad Howes. All rights reserved. import CoreMIDI /** Protocol for an object that monitors MIDI input activity */ public protocol Monitor: AnyObject { /** Notification that the MIDI system is initialized and ready to receive messages - parameter uniqueId: the unique ID of the virtual MIDI endpoint that will receive incoming messages */ func initialized(uniqueId: MIDIUniqueID) /** Notification that the MIDI system has been torn down. */ func deinitialized() /** Notification that the known devices has changed */ func updatedDevices() /** Notification that active connections have changed */ func updatedConnections() /** Notification invoked when there is an incoming MIDI message. - parameter uniqueId: the unique ID of the MIDI endpoint that sent the message - parameter channel: the channel found in the MIDI message */ func seen(uniqueId: MIDIUniqueID, channel: Int) } extension Monitor { public func initialized(uniqueId: MIDIUniqueID) {} public func deinitialized() {} public func updatedDevices() {} public func updatedConnections() {} public func seen(uniqueId: MIDIUniqueID, channel: Int) {} }
22.867925
103
0.723597
4b7db6ad0731c266ccc90fee34def7a80a02b76a
344
// // VGSCheckoutCustomBillingAddressLine2Options.swift // VGSCheckoutSDK import Foundation /// Holds billing address, address line 2 field options for custom configuration. public struct VGSCheckoutCustomBillingAddressLine2Options { /// Field name in your route configuration. public var fieldName = "" /// no:doc public init() {} }
21.5
81
0.767442
e5944434e186b576d5c4186a08afed7fc894bbe6
2,364
// // SceneDelegate.swift // Gestures // // Created by Germán Santos Jaimes on 27/12/19. // Copyright © 2019 Germán Santos Jaimes. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.777778
147
0.714467
bb9f7128402bf405c2da47b8b017e8fdfb32bac6
416
// // ArtistModel.swift // FIRDB CRUD // // Created by Likhit Garimella on 22/04/20. // Copyright © 2020 Likhit Garimella. All rights reserved. // import Foundation class ArtistModel { var id: String? var name: String? var genre: String? init(id: String?, name: String?, genre: String?) { self.id = id self.name = name self.genre = genre } } // #24
17.333333
59
0.579327
f98dd91ddeb49f6e6282090492d031a3f97121e7
1,748
// // FakeWeather.swift // WeatherBrickTests // // Created by A A on 16.11.2021. // import UIKit @testable import WeatherBrick class FakeWeather { // MARK: - Properties var temperature = 0.0 var weatherConditions = "" var city = "" var country = "" var windSpeed = 0.0 var conditionsId = 0 var isVeryHot: Bool { return temperature > 30 ? true : false } var isFog: Bool { return 741 ~= conditionsId ? true : false } var isWindy: Bool { return windSpeed > Constant.WindSpeed.windy ? true : false } var isConnectedToNetwork: Bool = true var stoneImageView = UIImageView(image: UIImage(named: Constant.StoneImages.normal.rawValue)) var temperatureString: String { return String(format: "%.0f" + "ºC", temperature) } var locationString: String { return "\(city) \(country)" } var conditionsString: String { return weatherConditions.capitalized } func updateImage() { switch self.conditionsId { case 300 ... 531 : self.stoneImageView.image = UIImage(named: Constant.StoneImages.wet.rawValue) case 600 ... 622 : self.stoneImageView.image = UIImage(named: Constant.StoneImages.snow.rawValue) default: self.stoneImageView.image = UIImage(named: Constant.StoneImages.normal.rawValue) } if self.isVeryHot { self.stoneImageView.image = UIImage(named: Constant.StoneImages.cracks.rawValue) } if !self.isConnectedToNetwork { self.stoneImageView.image = UIImage() } if self.isFog { self.stoneImageView.setImageColor(color: Style.StoneView.fogColor) } if self.isWindy { self.stoneImageView.windSwinging() } if !self.isWindy { self.stoneImageView.layer.removeAllAnimations() } } }
40.651163
110
0.67849
904076bce8bd9ba7b35b4042e4e7251cd3714b96
162
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(CachiBrowserTests.allTests), ] } #endif
16.2
45
0.679012
20fe9ab87eac12ac272c6772ff1871ad979cdb40
772
// // IMessageCell.swift // iMessage // // Created by Timothy Barnard on 24/09/2017. // Copyright © 2017 Timothy Barnard. All rights reserved. // import Foundation import UIKit class IMessageCell: UITableViewCell { @IBOutlet weak var currentClass: UIView! @IBOutlet weak var className: UILabel! @IBOutlet weak var classTime: UILabel! @IBOutlet weak var classLecture: UILabel! @IBOutlet weak var classLocation: UILabel! @IBOutlet weak var classGroups: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
24.125
65
0.676166
69d5ff545970369edfe42cede1cd05fa4cb3be54
1,826
import XCTest @testable import Vapor import HTTP class ResourceTests: XCTestCase { static let allTests = [ ("testBasic", testBasic), ("testOptions", testOptions) ] func testBasic() throws { let drop = try Droplet() let user = User(name: "Hi") let node = try user.makeNode(in: nil) XCTAssertEqual(node, .object(["name":"Hi"])) drop.resource("users", User.self) { users in users.index = { req in return "index" } users.create = { req in return "create" } users.store = { req in return "store" } users.show = { req, user in return "user \(user.name)" } users.edit = { req, user in return "edit \(user.name)" } } XCTAssertEqual(try drop.responseBody(for: .get, "users"), "index") XCTAssertEqual(try drop.responseBody(for: .get, "users/create"), "create") XCTAssertEqual(try drop.responseBody(for: .get, "users/bob"), "user bob") XCTAssertEqual(try drop.responseBody(for: .get, "users/bob/edit"), "edit bob") XCTAssert(try drop.responseBody(for: .get, "users/ERROR").contains("Vapor.Abort.notFound")) } func testOptions() throws { let drop = try Droplet() drop.resource("users", User.self) { users in users.index = { req in return "index" } users.show = { req, user in return "user \(user.name)" } } XCTAssert(try drop.responseBody(for: .options, "users").contains("methods")) XCTAssert(try drop.responseBody(for: .options, "users/5").contains("methods")) } }
28.53125
99
0.523549
e5260a526dc169f7c5c95b4a0add584f46860e28
1,467
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift HELM Xcode Templates // https://github.com/HelmMobile/clean-swift-templates import UIKit // MARK: Connect View, Interactor, and Presenter extension ___FILEBASENAMEASIDENTIFIER___Interactor: ___FILEBASENAMEASIDENTIFIER___ViewControllerOutput, ___FILEBASENAMEASIDENTIFIER___RouterDataSource, ___FILEBASENAMEASIDENTIFIER___RouterDataDestination { } extension ___FILEBASENAMEASIDENTIFIER___Presenter: ___FILEBASENAMEASIDENTIFIER___InteractorOutput { } class ___FILEBASENAMEASIDENTIFIER___Configurator { // MARK: Object lifecycle static let sharedInstance = ___FILEBASENAMEASIDENTIFIER___Configurator() private init() {} // MARK: Configuration func configure(viewController: ___FILEBASENAMEASIDENTIFIER___ViewController) { let presenter = ___FILEBASENAMEASIDENTIFIER___Presenter() presenter.output = viewController let interactor = ___FILEBASENAMEASIDENTIFIER___Interactor() interactor.output = presenter let router = ___FILEBASENAMEASIDENTIFIER___Router(viewController: viewController, dataSource: interactor, dataDestination: interactor) viewController.output = interactor viewController.router = router } }
33.340909
205
0.766871
dd08783ed05f3d69ee2d2cc4b79f87f64af07c8c
194
// // View+anyView.swift // ExpertSystem // // Created by Artemii Shabanov on 01.06.2021. // import SwiftUI extension View { func toAnyView() -> AnyView { AnyView(self) } }
12.933333
46
0.613402
61dfbf042217e7b6aec400ba83be880d359f286a
3,551
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // MARK: _UInt24 /// A 24-bit unsigned integer value type. @usableFromInline struct _UInt24: ExpressibleByIntegerLiteral { @usableFromInline typealias IntegerLiteralType = UInt16 @usableFromInline var b12: UInt16 @usableFromInline var b3: UInt8 private init(b12: UInt16, b3: UInt8) { self.b12 = b12 self.b3 = b3 } @usableFromInline init(integerLiteral value: UInt16) { self.init(b12: value, b3: 0) } static let bitWidth: Int = 24 static var max: _UInt24 { return .init(b12: .max, b3: .max) } static let min: _UInt24 = 0 } extension UInt32 { init(_ value: _UInt24) { var newValue: UInt32 = 0 newValue = UInt32(value.b12) newValue |= UInt32(value.b3) << 16 self = newValue } } extension Int { init(_ value: _UInt24) { var newValue: Int = 0 newValue = Int(value.b12) newValue |= Int(value.b3) << 16 self = newValue } } extension _UInt24 { init(_ value: UInt32) { assert(value & 0xff_00_00_00 == 0, "value \(value) too large for _UInt24") self.b12 = UInt16(truncatingIfNeeded: value & 0xff_ff) self.b3 = UInt8(value >> 16) } } extension _UInt24: Equatable {} extension _UInt24: CustomStringConvertible { @usableFromInline var description: String { return Int(self).description } } // MARK: _UInt56 /// A 56-bit unsigned integer value type. struct _UInt56: ExpressibleByIntegerLiteral { typealias IntegerLiteralType = UInt32 @usableFromInline var b1234: UInt32 @usableFromInline var b56: UInt16 @usableFromInline var b7: UInt8 private init(b1234: UInt32, b56: UInt16, b7: UInt8) { self.b1234 = b1234 self.b56 = b56 self.b7 = b7 } init(integerLiteral value: UInt32) { self.init(b1234: value, b56: 0, b7: 0) } static let bitWidth: Int = 56 static var max: _UInt56 { return .init(b1234: .max, b56: .max, b7: .max) } static let min: _UInt56 = 0 } extension _UInt56 { init(_ value: UInt64) { assert(value & 0xff_00_00_00_00_00_00_00 == 0, "value \(value) too large for _UInt56") self.init(b1234: UInt32(truncatingIfNeeded: (value & 0xff_ff_ff_ff) >> 0 ), b56: UInt16(truncatingIfNeeded: (value & 0xff_ff_00_00_00_00) >> 32), b7: UInt8( value >> 48)) } init(_ value: Int) { self.init(UInt64(value)) } } extension UInt64 { init(_ value: _UInt56) { var newValue: UInt64 = 0 newValue = UInt64(value.b1234) newValue |= UInt64(value.b56 ) << 32 newValue |= UInt64(value.b7 ) << 48 self = newValue } } extension Int { init(_ value: _UInt56) { self = Int(UInt64(value)) } } extension _UInt56: Equatable {} extension _UInt56: CustomStringConvertible { var description: String { return UInt64(self).description } }
24.489655
94
0.581808
1e1c48430eb5daf0e8f0c26577acb35ba4605a22
225
// Copyright © 2017 Christian Tietze. All rights reserved. Distributed under the MIT License. import Cocoa protocol FieldEditor { func replaceAllCharacters(with string: String) func selectRange(_ range: NSRange) }
25
94
0.764444
38e8604976f6a86f4e9fddbbba9bfea84d8dad50
135
import XCTest import SwiftPrometheusTests var tests = [XCTestCaseEntry]() tests += SwiftPrometheusTests.__allTests() XCTMain(tests)
15
42
0.8
ebf8e398984395b07a6fd30978eab8cdbf235d42
1,866
/** * GraphicsState.swift * Copyright (c) 2018, Innovatics Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and / or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class GraphicsState { // Default values private var CA: Float = 1.0 private var ca: Float = 1.0 public init() { } public func set_CA(_ CA: Float) { if CA >= 0.0 && CA <= 1.0 { self.CA = CA } } public func get_CA() -> Float { return self.CA } public func set_ca(_ ca: Float) { if ca >= 0.0 && ca <= 1.0 { self.ca = ca } } public func get_ca() -> Float { return self.ca } }
30.590164
80
0.699893
5bc67fcc343b8f4f2eb446b4aa23b94e0067ad75
1,317
// // Solution47.swift // LeetCodeOffer2021 // // Created by Cocos on 2021/5/31. // import Foundation /* 剑指 Offer 47. 礼物的最大价值 在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物? 示例 1: 输入: [ [1,3,1], [1,5,1], [4,2,1] ] 输出: 12 解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物 提示: 0 < grid.length <= 200 0 < grid[0].length <= 200 通过次数86,477提交次数125,741 */ class Solution47 { func maxValue(_ grid: [[Int]]) -> Int { if grid.count == 0 { return 0 } // 一个数组用来存储每一行的最佳结果, 不存储历史行, 所以只需要一个数组即可 var state = Array<Int>(repeating: 0, count: grid[0].count) for i in 0 ..< grid.count { for j in 0 ..< grid[0].count { var left = 0 var up = 0 if i > 0 { up = state[j] } if j > 0 { left = state[j - 1] } if up > left { state[j] = up + grid[i][j] } else { state[j] = left + grid[i][j] } } } var max = 0 for e in state { if e > max { max = e } } return max } }
18.814286
123
0.431283
d517cca6158f05552dc1cd1584dd22f9deccfd4d
1,360
// // Const.swift // AliyunLOGiOS // // Created by 王佳玮 on 16/8/18. // Copyright © 2016年 wangjwchn. All rights reserved. // import Foundation let ALIYUN_LOG_SDK_VERSION = "2.0.1" let HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss" let KEY_HOST = "Host" let KEY_TIME = "__time__" let KEY_TOPIC = "__topic__" let KEY_SOURCE = "__source__" let KEY_LOGS = "__logs__" let KEY_CONTENT_LENGTH = "Content-Length" let KEY_AUTHORIZATION = "Authorization" let KEY_CONTENT_TYPE = "Content-Type" let KEY_CONTENT_MD5 = "Content-MD5" let KEY_REQUEST_UA = "User-Agent" let KEY_DATE = "Date" let KEY_LOG_APIVERSION = "x-log-apiversion" let KEY_LOG_BODYRAWSIZE = "x-log-bodyrawsize" let KEY_LOG_COMPRESSTYPE = "x-log-compresstype" let KEY_LOG_SIGNATUREMETHOD = "x-log-signaturemethod" let KEY_ACS_SECURITY_TOKEN = "x-acs-security-token" let POST_VALUE_LOG_APIVERSION = "0.6.0" let POST_VALUE_LOG_COMPRESSTYPE = "deflate" let POST_VALUE_LOG_CONTENTTYPE = "application/json" let POST_VALUE_LOG_SIGNATUREMETHOD = "hmac-sha1" let VALUE_REQUEST_UA = "aliyun-log-sdk-ios/\(ALIYUN_LOG_SDK_VERSION)" let POST_METHOD_NAME = "POST" let TOKEN_EXPIRE_TIME = 60 * 15 //15min enum SLS_TABLE_COLUMN_NAME: String { case id = "id" case endpoint = "endpoint" case project = "project" case logstore = "logstore" case log = "log" case timestamp = "timestamp" }
25.660377
69
0.744853
46031e2b5c64b2fbf229343902f7777807aef0c1
467
// // ViewController.swift // I Am Busy // // Created by 刘铭 on 2017/12/29. // Copyright © 2017年 刘铭. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
17.961538
76
0.691649
90c4463afa4e871315686a4eaebc3fa993632532
2,188
// // ReadWriteLock.swift // SCNRecorder // // Created by Vladislav Grigoryev on 17.05.2020. // Copyright © 2020 GORA Studio. https://gora.studio // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation final class ReadWriteLock { private var readWriteLock: pthread_rwlock_t init() { readWriteLock = pthread_rwlock_t() pthread_rwlock_init(&readWriteLock, nil) } deinit { pthread_rwlock_destroy(&readWriteLock) } func readLock() { pthread_rwlock_rdlock(&readWriteLock) } func writeLock() { pthread_rwlock_wrlock(&readWriteLock) } func unlock() { pthread_rwlock_unlock(&readWriteLock) } func tryRead() -> Bool { pthread_rwlock_tryrdlock(&readWriteLock) == 0 } func tryWrite() -> Bool { pthread_rwlock_trywrlock(&readWriteLock) == 0 } } extension ReadWriteLock { @discardableResult func readLocked<Result>(_ action: () throws -> Result) rethrows -> Result { readLock() defer { unlock() } return try action() } @discardableResult func writeLocked<Result>(_ action: () throws -> Result) rethrows -> Result { writeLock() defer { unlock() } return try action() } }
33.151515
81
0.728062
f50c0a2e119d1b9f0f8a1a85a86300f2ab4ed72e
4,341
// // ViewController.swift // SampleApp // // Created by Sachin Vas on 31/10/18. // Copyright © 2018 Amit Prabhu. All rights reserved. // import UIKit import NearBee import CoreData import UserNotifications import CoreLocation import Imaginary class ViewController: UITableViewController { var MY_TOKEN = "" // warning: Make sure to replace this var MY_ORGANIZATION = 0 // warning: Make sure to replace this var locationManager = CLLocationManager() var nearBee: NearBee! var viewBeacons:[NearBeeBeacon] = [] override func viewDidLoad() { super.viewDidLoad() locationManager.requestAlwaysAuthorization() UNUserNotificationCenter.current().delegate = self nearBee = NearBee.initNearBee() nearBee.delegate = self nearBee.enableBackgroundNotification(true) // Un-comment this for testing notifications // nearBee.debugMode = true nearBee.startScanning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) nearBee.delegate = self } } extension ViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard viewBeacons.count > indexPath.row else { return } let beacon = viewBeacons[indexPath.row] guard let eddystoneURL = beacon.getBestAvailableAttachment()?.getURL() else { return } nearBee.displayContentOf(eddystoneURL) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewBeacons.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: PhysicalWebTableViewCell.cellIdentifier, for: indexPath) as? PhysicalWebTableViewCell, viewBeacons.count > indexPath.row else { fatalError("Unexpected Index Path") } let beacon = viewBeacons[indexPath.row] // Configure Cell cell.configureCell(beacon: beacon) return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? GeoFenceViewController { destination.nearBee = nearBee } } } extension ViewController: NearBeeDelegate { // Callback for geofence enter event func didEnterGeofence(_ geofence: NearBeeGeoFence, _ attachment: GeoFenceAttachment) { } func didFindBeacons(_ beacons: [NearBeeBeacon]) { for beacon in beacons { if !viewBeacons.contains(beacon) { viewBeacons.insert(beacon, at: viewBeacons.count) } } tableView.reloadData() } func didLoseBeacons(_ beacons: [NearBeeBeacon]) { for beacon in beacons { if viewBeacons.contains(beacon) { viewBeacons.remove(at: viewBeacons.index(of: beacon)!) } } tableView.reloadData() } func didUpdateBeacons(_ beacons: [NearBeeBeacon]) { for beacon in beacons { if viewBeacons.contains(beacon) { viewBeacons.remove(at: viewBeacons.index(of: beacon)!) viewBeacons.insert(beacon, at: viewBeacons.count) } } tableView.reloadData() } func didThrowError(_ error: Error) { viewBeacons = [] tableView.reloadData() } func didUpdateState(_ state: NearBeeState) { } } extension ViewController: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let _ = nearBee.checkAndProcessNearbyNotification(response.notification) completionHandler() } }
30.570423
198
0.628427
0e2bbb40db504cf904028a8d078b0c3eb0033656
1,276
/* The MIT License * * Copyright © 2021 NBCO YooMoney 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. * * 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 Dispatch import Foundation struct PromiseObserver<L, R> { let queue: DispatchQueue let notify: (Either<L, R>) -> Void }
41.16129
80
0.753918
ed44260a1adfbc0ce8b84849f3cff115d020d9a5
1,864
// // TaxRate.swift // Stripe // // Created by Andrew Edwards on 5/12/19. // import Foundation /// The [Tax Rate Object](https://stripe.com/docs/api/tax_rates/object). public struct StripeTaxRate: StripeModel { /// Unique identifier for the object. public var id: String /// String representing the object’s type. Objects of the same type share the same value. public var object: String /// Defaults to true. When set to false, this tax rate cannot be applied to objects in the API, but will still be applied to subscriptions and invoices that already have it set. public var active: Bool? /// Time at which the object was created. Measured in seconds since the Unix epoch. public var created: Date /// An arbitrary string attached to the tax rate for your internal use only. It will not be visible to your customers. public var description: String? /// The display name of the tax rates as it will appear to your customer on their receipt email, PDF, and the hosted invoice page. public var displayName: String? /// This specifies if the tax rate is inclusive or exclusive. public var inclusive: Bool? /// The jurisdiction for the tax rate. public var jurisdiction: String? /// Has the value true if the object exists in live mode or the value false if the object exists in test mode. public var livemode: Bool? /// Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. public var metadata: [String: String]? /// This represents the tax rate percent out of 100. public var percentage: Decimal? } public struct StripeTaxRateList: StripeModel { public var object: String public var hasMore: Bool? public var url: String? public var data: [StripeTaxRate]? }
44.380952
181
0.719957
383e7ee31ab699bdf16c7f3ef8c0ede88d71d03d
2,377
// // URLRequest+ConstructionTestCase.swift // // Copyright © 2022 Aleksei Zaikin. // // 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 NON-INFRINGEMENT. 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. // @testable import Web import XCTest final class URLRequestConstructionTestCase: XCTestCase { private let url = try! URL( path: "test/endpoint", baseURL: URL(string: "https://api.service.com/v1/") ) // MARK: - Test Cases func test_urlRequest_isConstructedWithURLMethodAndHeaders() throws { let request = URLRequest(url: url, method: .get, headers: ["Header-Field": "Header Value"]) XCTAssertEqual(try XCTUnwrap(request.url?.absoluteString), url.absoluteString) XCTAssertEqual(request.httpMethod, "GET") XCTAssertEqual(request.allHTTPHeaderFields, ["Header-Field": "Header Value"]) } func test_urlRequest_isConstructedWithBody() throws { let request = try URLRequest( url: url, method: .post, body: Data([0x1, 0x2, 0x3]), converter: DataBodyConverter(contentType: "application/octet-stream") ) XCTAssertEqual(try XCTUnwrap(request.url?.absoluteString), url.absoluteString) XCTAssertEqual(request.httpMethod, "POST") XCTAssertEqual(request.allHTTPHeaderFields, ["Content-Type": "application/octet-stream"]) XCTAssertEqual(request.httpBody, Data([0x1, 0x2, 0x3])) } }
40.982759
97
0.72276
7691c87f69e09fd983068cab4b82b5be7433c452
2,240
// // Icon.swift // QuickTableViewController // // Created by Ben on 01/09/2015. // Copyright (c) 2015 bcylin. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit /// A struct that represents the image used in a row. public enum Icon: Equatable { /// Icon with an image of the given name for the normal state. /// The "-highlighted" suffix is appended to the name for the highlighted image. case named(String) /// Icon with an image for the normal state. case image(UIImage) /// Icon with images for the normal and highlighted states. case images(normal: UIImage, highlighted: UIImage) /// The image for the normal state. public var image: UIImage? { switch self { case let .named(name): return UIImage(named: name) case let .image(image): return image case let .images(normal: image, highlighted: _): return image } } /// The image for the highlighted state. public var highlightedImage: UIImage? { switch self { case let .named(name): return UIImage(named: name + "-highlighted") case .image: return nil case let .images(normal: _, highlighted: image): return image } } }
34.461538
82
0.708036
67a44c38e1f8cf19b3576916381bac33b6922f9c
8,502
import ProjectDescription import TSCBasic import TSCUtility import TuistCore import TuistGraph import TuistSupport // MARK: - Dependencies Controller Error enum DependenciesControllerError: FatalError, Equatable { /// Thrown when the same dependency is defined more than once. case duplicatedDependency(String, [ProjectDescription.TargetDependency], [ProjectDescription.TargetDependency]) /// Thrown when the same project is defined more than once. case duplicatedProject(Path, ProjectDescription.Project, ProjectDescription.Project) /// Thrown when platforms for dependencies to install are not determined in `Dependencies.swift`. case noPlatforms /// Error type. var type: ErrorType { switch self { case .duplicatedDependency, .duplicatedProject, .noPlatforms: return .abort } } // Error description. var description: String { switch self { case let .duplicatedDependency(name, first, second): return """ The \(name) dependency is defined twice across different dependency managers: First: \(first) Second: \(second) """ case let .duplicatedProject(name, first, second): return """ The \(name) project is defined twice across different dependency managers: First: \(first) Second: \(second) """ case .noPlatforms: return "Platforms were not determined. Select platforms in `Dependencies.swift` manifest file." } } } // MARK: - Dependencies Controlling /// `DependenciesControlling` controls: /// 1. Fetching/updating dependencies defined in `./Tuist/Dependencies.swift` by running appropriate dependencies managers (`Cocoapods`, `Carthage`, `SPM`). /// 2. Compiling fetched/updated dependencies into `.framework.`/`.xcframework.`. /// 3. Saving compiled frameworks under `./Tuist/Dependencies/*`. /// 4. Generating dependencies graph under `./Tuist/Dependencies/graph.json`. public protocol DependenciesControlling { /// Fetches dependencies. /// - Parameter path: Directory where project's dependencies will be fetched. /// - Parameter dependencies: List of dependencies to fetch. /// - Parameter swiftVersion: The specified version of Swift. If `nil` is passed then the environment’s version will be used. func fetch( at path: AbsolutePath, dependencies: TuistGraph.Dependencies, swiftVersion: TSCUtility.Version? ) throws -> TuistCore.DependenciesGraph /// Updates dependencies. /// - Parameters: /// - path: Directory where project's dependencies will be updated. /// - dependencies: List of dependencies to update. /// - swiftVersion: The specified version of Swift. If `nil` is passed then will use the environment’s version will be used. func update( at path: AbsolutePath, dependencies: TuistGraph.Dependencies, swiftVersion: TSCUtility.Version? ) throws -> TuistCore.DependenciesGraph /// Save dependencies graph. /// - Parameters: /// - dependenciesGraph: The dependencies graph to be saved. /// - path: Directory where dependencies graph will be saved. func save( dependenciesGraph: TuistGraph.DependenciesGraph, to path: AbsolutePath ) throws } // MARK: - Dependencies Controller public final class DependenciesController: DependenciesControlling { private let carthageInteractor: CarthageInteracting private let swiftPackageManagerInteractor: SwiftPackageManagerInteracting private let dependenciesGraphController: DependenciesGraphControlling public init( carthageInteractor: CarthageInteracting = CarthageInteractor(), swiftPackageManagerInteractor: SwiftPackageManagerInteracting = SwiftPackageManagerInteractor(), dependenciesGraphController: DependenciesGraphControlling = DependenciesGraphController() ) { self.carthageInteractor = carthageInteractor self.swiftPackageManagerInteractor = swiftPackageManagerInteractor self.dependenciesGraphController = dependenciesGraphController } public func fetch( at path: AbsolutePath, dependencies: TuistGraph.Dependencies, swiftVersion: TSCUtility.Version? ) throws -> TuistCore.DependenciesGraph { return try install( at: path, dependencies: dependencies, shouldUpdate: false, swiftVersion: swiftVersion ) } public func update( at path: AbsolutePath, dependencies: TuistGraph.Dependencies, swiftVersion: TSCUtility.Version? ) throws -> TuistCore.DependenciesGraph { return try install( at: path, dependencies: dependencies, shouldUpdate: true, swiftVersion: swiftVersion ) } public func save( dependenciesGraph: TuistGraph.DependenciesGraph, to path: AbsolutePath ) throws { if dependenciesGraph.externalDependencies.isEmpty { try dependenciesGraphController.clean(at: path) } else { try dependenciesGraphController.save(dependenciesGraph, to: path) } } // MARK: - Helpers private func install( at path: AbsolutePath, dependencies: TuistGraph.Dependencies, shouldUpdate: Bool, swiftVersion: TSCUtility.Version? ) throws -> TuistCore.DependenciesGraph { logger.warning( """ The integration of external dependencies is in alpha. \ Be aware some APIs might change as we iterate the functionality with the feedback we get from users. """ ) let dependenciesDirectory = path .appending(component: Constants.tuistDirectoryName) .appending(component: Constants.DependenciesDirectory.name) let platforms = dependencies.platforms guard !platforms.isEmpty else { throw DependenciesControllerError.noPlatforms } var dependenciesGraph = TuistCore.DependenciesGraph.none if let carthageDependencies = dependencies.carthage, !carthageDependencies.dependencies.isEmpty { let carthageDependenciesGraph = try carthageInteractor.install( dependenciesDirectory: dependenciesDirectory, dependencies: carthageDependencies, platforms: platforms, shouldUpdate: shouldUpdate ) dependenciesGraph = try dependenciesGraph.merging(with: carthageDependenciesGraph) } else { try carthageInteractor.clean(dependenciesDirectory: dependenciesDirectory) } if let swiftPackageManagerDependencies = dependencies.swiftPackageManager, !swiftPackageManagerDependencies.packages.isEmpty { let swiftPackageManagerDependenciesGraph = try swiftPackageManagerInteractor.install( dependenciesDirectory: dependenciesDirectory, dependencies: swiftPackageManagerDependencies, platforms: platforms, shouldUpdate: shouldUpdate, swiftToolsVersion: swiftVersion ) dependenciesGraph = try dependenciesGraph.merging(with: swiftPackageManagerDependenciesGraph) } else { try swiftPackageManagerInteractor.clean(dependenciesDirectory: dependenciesDirectory) } return dependenciesGraph } } extension TuistCore.DependenciesGraph { public func merging(with other: Self) throws -> Self { let mergedExternalDependencies = try other.externalDependencies.reduce(into: externalDependencies) { result, entry in if let alreadyPresent = result[entry.key] { throw DependenciesControllerError.duplicatedDependency(entry.key, alreadyPresent, entry.value) } result[entry.key] = entry.value } let mergedExternalProjects = try other.externalProjects.reduce(into: externalProjects) { result, entry in if let alreadyPresent = result[entry.key] { throw DependenciesControllerError.duplicatedProject(entry.key, alreadyPresent, entry.value) } result[entry.key] = entry.value } return .init(externalDependencies: mergedExternalDependencies, externalProjects: mergedExternalProjects) } }
39.361111
160
0.678781
014596e941725cc938665b13c8b24457fea6ff9b
29,846
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation public struct ASCBuild: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case builds = "builds" } public var links: ASCResourceLinks public var _id: String public var type: ASCType public var attributes: Attributes? public var relationships: Relationships? public struct Attributes: AppStoreConnectBaseModel { public enum ASCProcessingState: String, Codable, Equatable, CaseIterable { case processing = "PROCESSING" case failed = "FAILED" case invalid = "INVALID" case valid = "VALID" } public var expirationDate: DateTime? public var expired: Bool? public var iconAssetToken: ASCImageAsset? public var minOsVersion: String? public var processingState: ASCProcessingState? public var uploadedDate: DateTime? public var usesNonExemptEncryption: Bool? public var version: String? public init( expirationDate: DateTime? = nil, expired: Bool? = nil, iconAssetToken: ASCImageAsset? = nil, minOsVersion: String? = nil, processingState: ASCProcessingState? = nil, uploadedDate: DateTime? = nil, usesNonExemptEncryption: Bool? = nil, version: String? = nil ) { self.expirationDate = expirationDate self.expired = expired self.iconAssetToken = iconAssetToken self.minOsVersion = minOsVersion self.processingState = processingState self.uploadedDate = uploadedDate self.usesNonExemptEncryption = usesNonExemptEncryption self.version = version } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) expirationDate = try container.decodeIfPresent("expirationDate") expired = try container.decodeIfPresent("expired") iconAssetToken = try container.decodeIfPresent("iconAssetToken") minOsVersion = try container.decodeIfPresent("minOsVersion") processingState = try container.decodeIfPresent("processingState") uploadedDate = try container.decodeIfPresent("uploadedDate") usesNonExemptEncryption = try container.decodeIfPresent("usesNonExemptEncryption") version = try container.decodeIfPresent("version") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(expirationDate, forKey: "expirationDate") try container.encodeIfPresent(expired, forKey: "expired") try container.encodeIfPresent(iconAssetToken, forKey: "iconAssetToken") try container.encodeIfPresent(minOsVersion, forKey: "minOsVersion") try container.encodeIfPresent(processingState, forKey: "processingState") try container.encodeIfPresent(uploadedDate, forKey: "uploadedDate") try container.encodeIfPresent(usesNonExemptEncryption, forKey: "usesNonExemptEncryption") try container.encodeIfPresent(version, forKey: "version") } } public struct Relationships: AppStoreConnectBaseModel { public var app: App? public var appEncryptionDeclaration: AppEncryptionDeclaration? public var appStoreVersion: AppStoreVersion? public var betaAppReviewSubmission: BetaAppReviewSubmission? public var betaBuildLocalizations: BetaBuildLocalizations? public var buildBetaDetail: BuildBetaDetail? public var icons: Icons? public var individualTesters: IndividualTesters? public var preReleaseVersion: PreReleaseVersion? public struct App: AppStoreConnectBaseModel { public var data: DataType? public var links: Links? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case apps = "apps" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: DataType? = nil, links: Links? = nil) { self.data = data self.links = links } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeIfPresent("data") links = try container.decodeIfPresent("links") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") } } public struct AppEncryptionDeclaration: AppStoreConnectBaseModel { public var data: DataType? public var links: Links? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case appEncryptionDeclarations = "appEncryptionDeclarations" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: DataType? = nil, links: Links? = nil) { self.data = data self.links = links } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeIfPresent("data") links = try container.decodeIfPresent("links") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") } } public struct AppStoreVersion: AppStoreConnectBaseModel { public var data: DataType? public var links: Links? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case appStoreVersions = "appStoreVersions" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: DataType? = nil, links: Links? = nil) { self.data = data self.links = links } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeIfPresent("data") links = try container.decodeIfPresent("links") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") } } public struct BetaAppReviewSubmission: AppStoreConnectBaseModel { public var data: DataType? public var links: Links? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case betaAppReviewSubmissions = "betaAppReviewSubmissions" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: DataType? = nil, links: Links? = nil) { self.data = data self.links = links } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeIfPresent("data") links = try container.decodeIfPresent("links") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") } } public struct BetaBuildLocalizations: AppStoreConnectBaseModel { public var data: [DataType]? public var links: Links? public var meta: ASCPagingInformation? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case betaBuildLocalizations = "betaBuildLocalizations" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: [DataType]? = nil, links: Links? = nil, meta: ASCPagingInformation? = nil) { self.data = data self.links = links self.meta = meta } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeArrayIfPresent("data") links = try container.decodeIfPresent("links") meta = try container.decodeIfPresent("meta") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") try container.encodeIfPresent(meta, forKey: "meta") } } public struct BuildBetaDetail: AppStoreConnectBaseModel { public var data: DataType? public var links: Links? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case buildBetaDetails = "buildBetaDetails" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: DataType? = nil, links: Links? = nil) { self.data = data self.links = links } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeIfPresent("data") links = try container.decodeIfPresent("links") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") } } public struct Icons: AppStoreConnectBaseModel { public var data: [DataType]? public var links: Links? public var meta: ASCPagingInformation? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case buildIcons = "buildIcons" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: [DataType]? = nil, links: Links? = nil, meta: ASCPagingInformation? = nil) { self.data = data self.links = links self.meta = meta } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeArrayIfPresent("data") links = try container.decodeIfPresent("links") meta = try container.decodeIfPresent("meta") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") try container.encodeIfPresent(meta, forKey: "meta") } } public struct IndividualTesters: AppStoreConnectBaseModel { public var data: [DataType]? public var links: Links? public var meta: ASCPagingInformation? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case betaTesters = "betaTesters" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: [DataType]? = nil, links: Links? = nil, meta: ASCPagingInformation? = nil) { self.data = data self.links = links self.meta = meta } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeArrayIfPresent("data") links = try container.decodeIfPresent("links") meta = try container.decodeIfPresent("meta") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") try container.encodeIfPresent(meta, forKey: "meta") } } public struct PreReleaseVersion: AppStoreConnectBaseModel { public var data: DataType? public var links: Links? public struct DataType: AppStoreConnectBaseModel { public enum ASCType: String, Codable, Equatable, CaseIterable { case preReleaseVersions = "preReleaseVersions" } public var _id: String public var type: ASCType public init(_id: String, type: ASCType) { self._id = _id self.type = type } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) _id = try container.decode("id") type = try container.decode("type") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") } } public struct Links: AppStoreConnectBaseModel { public var related: String? public var _self: String? public init(related: String? = nil, _self: String? = nil) { self.related = related self._self = _self } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) related = try container.decodeIfPresent("related") _self = try container.decodeIfPresent("self") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(related, forKey: "related") try container.encodeIfPresent(_self, forKey: "self") } } public init(data: DataType? = nil, links: Links? = nil) { self.data = data self.links = links } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decodeIfPresent("data") links = try container.decodeIfPresent("links") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(data, forKey: "data") try container.encodeIfPresent(links, forKey: "links") } } public init( app: App? = nil, appEncryptionDeclaration: AppEncryptionDeclaration? = nil, appStoreVersion: AppStoreVersion? = nil, betaAppReviewSubmission: BetaAppReviewSubmission? = nil, betaBuildLocalizations: BetaBuildLocalizations? = nil, buildBetaDetail: BuildBetaDetail? = nil, icons: Icons? = nil, individualTesters: IndividualTesters? = nil, preReleaseVersion: PreReleaseVersion? = nil ) { self.app = app self.appEncryptionDeclaration = appEncryptionDeclaration self.appStoreVersion = appStoreVersion self.betaAppReviewSubmission = betaAppReviewSubmission self.betaBuildLocalizations = betaBuildLocalizations self.buildBetaDetail = buildBetaDetail self.icons = icons self.individualTesters = individualTesters self.preReleaseVersion = preReleaseVersion } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) app = try container.decodeIfPresent("app") appEncryptionDeclaration = try container.decodeIfPresent("appEncryptionDeclaration") appStoreVersion = try container.decodeIfPresent("appStoreVersion") betaAppReviewSubmission = try container.decodeIfPresent("betaAppReviewSubmission") betaBuildLocalizations = try container.decodeIfPresent("betaBuildLocalizations") buildBetaDetail = try container.decodeIfPresent("buildBetaDetail") icons = try container.decodeIfPresent("icons") individualTesters = try container.decodeIfPresent("individualTesters") preReleaseVersion = try container.decodeIfPresent("preReleaseVersion") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(app, forKey: "app") try container.encodeIfPresent(appEncryptionDeclaration, forKey: "appEncryptionDeclaration") try container.encodeIfPresent(appStoreVersion, forKey: "appStoreVersion") try container.encodeIfPresent(betaAppReviewSubmission, forKey: "betaAppReviewSubmission") try container.encodeIfPresent(betaBuildLocalizations, forKey: "betaBuildLocalizations") try container.encodeIfPresent(buildBetaDetail, forKey: "buildBetaDetail") try container.encodeIfPresent(icons, forKey: "icons") try container.encodeIfPresent(individualTesters, forKey: "individualTesters") try container.encodeIfPresent(preReleaseVersion, forKey: "preReleaseVersion") } } public init( links: ASCResourceLinks, _id: String, type: ASCType, attributes: Attributes? = nil, relationships: Relationships? = nil ) { self.links = links self._id = _id self.type = type self.attributes = attributes self.relationships = relationships } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) links = try container.decode("links") _id = try container.decode("id") type = try container.decode("type") attributes = try container.decodeIfPresent("attributes") relationships = try container.decodeIfPresent("relationships") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(links, forKey: "links") try container.encode(_id, forKey: "id") try container.encode(type, forKey: "type") try container.encodeIfPresent(attributes, forKey: "attributes") try container.encodeIfPresent(relationships, forKey: "relationships") } }
30.674203
100
0.650908
0e1cfb638b9263e348c96c8167489d298fdf8cf2
1,389
// // OperationViewController.swift // CoordinatorPatternExample // // Created by Echo on 5/10/19. // Copyright © 2019 Echo. All rights reserved. // import UIKit class OperationViewController: UIViewController, BackwardConscious { var backwardHandler: (([AnyHashable : Any]?) -> Void)? var number = 0 var mode: OperationMode = .add private let varibleNumber = 10 var result = 0 { didSet { resultLabel.text = "\(result)" } } @IBOutlet var numberLabel: UILabel! @IBOutlet var operationLabel: UILabel! @IBOutlet var varibleNumberLabel: UILabel! @IBOutlet var resultLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() switch mode { case .add: operationLabel.text = "+" default: operationLabel.text = "-" } result = number numberLabel.text = "\(number)" varibleNumberLabel.text = "\(varibleNumber)" } @IBAction func run(_ sender: Any) { switch mode { case .add: result += varibleNumber default: result -= varibleNumber } } @objc func close() { dismiss(animated: true) } func getPassingInfo() -> [AnyHashable : Any]? { return ["result": result] } }
22.403226
68
0.555796
6469becfeadb83b4bf8d5f8bb2f86fbe48ec5198
6,031
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import Fuzzilli let jsFileExtension = ".js" let protoBufFileExtension = ".fuzzil.protobuf" let jsPrefix = "" let jsSuffix = "" let jsLifter = JavaScriptLifter(prefix: jsPrefix, suffix: jsSuffix, inliningPolicy: InlineOnlyLiterals(), ecmaVersion: ECMAScriptVersion.es6) let fuzzILLifter = FuzzILLifter() // Loads a serialized FuzzIL program from the given file func loadProgram(from path: String) throws -> Program { let data = try Data(contentsOf: URL(fileURLWithPath: path)) let proto = try Fuzzilli_Protobuf_Program(serializedData: data) let program = try Program(from: proto) return program } func loadAllPrograms(in dirPath: String) -> [(filename: String, program: Program)] { var isDir: ObjCBool = false if !FileManager.default.fileExists(atPath: dirPath, isDirectory:&isDir) || !isDir.boolValue { print("\(dirPath) is not a directory!") exit(-1) } let fileEnumerator = FileManager.default.enumerator(atPath: dirPath) var results = [(String, Program)]() while let filename = fileEnumerator?.nextObject() as? String { guard filename.hasSuffix(protoBufFileExtension) else { continue } let path = dirPath + "/" + filename do { let program = try loadProgram(from: path) results.append((filename, program)) } catch FuzzilliError.programDecodingError(let reason) { print("Failed to load program \(path): \(reason)") } catch { print("Failed to load program \(path) due to unexpected error: \(error)") } } return results } // Take a program and lifts it to JavaScript func liftToJS(_ prog: Program) -> String { let res = jsLifter.lift(prog) return res.trimmingCharacters(in: .whitespacesAndNewlines) } // Take a program and lifts it to FuzzIL's text format func liftToFuzzIL(_ prog: Program) -> String { let res = fuzzILLifter.lift(prog) return res.trimmingCharacters(in: .whitespacesAndNewlines) } // Loads all .fuzzil.protobuf files in a directory, and lifts them to JS // Returns the number of files successfully converted func liftAllPrograms(in dirPath: String, with lifter: Lifter, fileExtension: String) -> Int { var numLiftedPrograms = 0 for (filename, program) in loadAllPrograms(in: dirPath) { let newFilePath = "\(dirPath)/\(filename.dropLast(protoBufFileExtension.count))\(fileExtension)" let content = lifter.lift(program) do { try content.write(to: URL(fileURLWithPath: newFilePath), atomically: false, encoding: String.Encoding.utf8) numLiftedPrograms += 1 } catch { print("Failed to write file \(newFilePath): \(error)") } } return numLiftedPrograms } func loadProgramOrExit(from path: String) -> Program { do { return try loadProgram(from: path) } catch { print("Failed to load program from \(path): \(error)") exit(-1) } } let args = Arguments.parse(from: CommandLine.arguments) if args["-h"] != nil || args["--help"] != nil || args.numPositionalArguments != 1 || args.numOptionalArguments != 1 { print(""" Usage: \(args.programName) option path Options: --liftToFuzzIL : Lifts the given protobuf program to FuzzIL's text format and prints it --liftToJS : Lifts the given protobuf program to JS and prints it --liftCorpusToJS : Loads all .fuzzil.protobuf files in a directory and lifts them to .js files in that same directory --dumpProtobuf : Dumps the raw content of the given protobuf file --dumpProgram : Dumps the internal representation of the program stored in the given protobuf file --checkCorpus : Attempts to load all .fuzzil.protobuf files in a directory and checks if they are statically valid """) exit(0) } let path = args[0] // Covert a single IL protobuf file to FuzzIL's text format and print to stdout if args.has("--liftToFuzzIL") { let program = loadProgramOrExit(from: path) print(liftToFuzzIL(program)) } // Covert a single IL protobuf file to JS and print to stdout else if args.has("--liftToJS") { let program = loadProgramOrExit(from: path) print(liftToJS(program)) } // Lift all protobuf programs to JavaScript else if args.has("--liftCorpusToJS") { let numLiftedPrograms = liftAllPrograms(in: path, with: jsLifter, fileExtension: jsFileExtension) print("Lifted \(numLiftedPrograms) programs to JS") } // Pretty print just the protobuf, without trying to load as a program // This allows the debugging of produced programs that are not syntactically valid else if args.has("--dumpProtobuf") { let data = try Data(contentsOf: URL(fileURLWithPath: path)) let proto = try Fuzzilli_Protobuf_Program(serializedData: data) dump(proto, maxDepth: 3) } // Pretty print a protobuf as a program on stdout else if args.has("--dumpProgram") { let program = loadProgramOrExit(from: path) dump(program) } // Combine multiple protobuf programs into a single corpus file else if args.has("--checkCorpus") { let numPrograms = loadAllPrograms(in: path).count print("Successfully loaded \(numPrograms) programs") } else { print("Invalid option: \(args.unusedOptionals.first!)") exit(-1) }
37.228395
137
0.679489
5013e1ddcf9394734cadc0631dd99b835c79b191
1,196
// // UBGradingMaterial.swift // UpgradeBelt // // Created by Julia Boichentsova on 12/04/2020. // Copyright © 2020 Julia Boichentsova. All rights reserved. // import Foundation struct UBGradingMaterial : Codable { let identifier: String let colorBelts: [UBGradingItem]? let blackBelts: [UBGradingItem]? enum CodingKeys: String, CodingKey { case identifier = "id" case colorBelts = "colorBelts" case blackBelts = "blackBelts" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.identifier = try container.decode(String.self, forKey: .identifier) self.colorBelts = try container.decode([UBGradingItem].self, forKey: .colorBelts) self.blackBelts = try container.decode([UBGradingItem].self, forKey: .blackBelts) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.identifier, forKey: .identifier) try container.encode(self.colorBelts, forKey: .colorBelts) try container.encode(self.blackBelts, forKey: .blackBelts) } }
33.222222
89
0.684783
61be944eb658da2631b75b48bd51795d7908d10a
5,968
// // Container.swift // uncomplicated-todo // // Created by Vladislav Morozov on 27/04/2019. // Copyright © 2019 misshapes. All rights reserved. // import Foundation class Container { private static let modelName = "uncomplicated_todo" //Here we declare single instances private lazy var network: Networking = Network() private lazy var networkManager: NetworkManaging = NetworkManager(network: network) private lazy var coreDataStack = CoreDataStack(modelName: Container.modelName) private lazy var todoPersistentStorage: TodoPersistentStoraging = TodoPersistentStorage(coreDataStack: coreDataStack) private lazy var todoStorage: TodoStoraging = TodoStorage(networkManager: networkManager, persistentStorage: todoPersistentStorage) private lazy var todoNameExamplesStorage: TodoNameExamplesStorage = TodoNameExamplesStorage(networkManager: networkManager) private lazy var settingsStorage: SettingsStoraging = SettingsStorage() //Here we make instances that might be created several times during app lifespan func makeTodoListViewModel() -> TodoListViewModeling { //TODO: replace storage with real one //return TodoListViewModel(todoStorage: TodoStorageMock(todos: testedTodos), weekRangeBuilder: WeekRangeBuilder(calendar: Calendar.current)) return TodoListViewModel(todoStorage: todoStorage, weekRangeBuilder: WeekRangeBuilder(calendar: Calendar.current)) } //TODO: remove these later private lazy var subject11 = Todo(id: UUID(), name: "11, order: 4", priority: .high, dueDate: self.date(from: "2019-05-13T00:00:00+0000"), creationDate: self.date(from: "2019-05-11T00:00:00+0000"), completedDate: nil) private lazy var subject12 = Todo(id: UUID(), name: "12, order: 6", priority: .medium, dueDate: self.date(from: "2019-05-19T00:00:00+0000"), creationDate: self.date(from: "2019-05-11T00:00:00+0000"), completedDate: nil) private lazy var subject13 = Todo(id: UUID(), name: "13, order: 51", priority: .low, dueDate: self.date(from: "2019-05-16T00:00:00+0000"), creationDate: self.date(from: "2019-05-11T00:00:00+0000"), completedDate: nil) private lazy var subject14 = Todo(id: UUID(), name: "14, order: 52", priority: .high, dueDate: self.date(from: "2019-05-16T00:00:00+0000"), creationDate: self.date(from: "2019-05-12T00:00:00+0000"), completedDate: nil) private lazy var subject21 = Todo(id: UUID(), name: "21, order: 21", priority: .medium, dueDate: self.date(from: "2019-05-03T00:00:00+0000"), creationDate: self.date(from: "2019-05-02T00:00:00+0000"), completedDate: nil) private lazy var subject22 = Todo(id: UUID(), name: "22, order: 22", priority: .low, dueDate: self.date(from: "2019-05-03T00:00:00+0000"), creationDate: self.date(from: "2019-05-01T00:00:00+0000"), completedDate: nil) private lazy var subject23 = Todo(id: UUID(), name: "23, order: 23", priority: .high, dueDate: self.date(from: "2019-05-03T00:00:00+0000"), creationDate: self.date(from: "2019-05-01T00:00:00+0000"), completedDate: nil) private lazy var subject24 = Todo(id: UUID(), name: "24, order: 1", priority: .medium, dueDate: self.date(from: "2019-04-29T00:00:00+0000"), creationDate: self.date(from: "2019-04-13T00:00:00+0000"), completedDate: nil) private lazy var subject25 = Todo(id: UUID(), name: "25, order: 3", priority: .low, dueDate: self.date(from: "2019-05-04T00:00:00+0000"), creationDate: self.date(from: "2019-05-02T00:00:00+0000"), completedDate: nil) private lazy var testedTodos: [Todo] = [ subject11, subject12, subject13, subject14, subject21, subject22, subject23, subject24, subject25 ] private func date(from string: String) -> Date { let dateFormatter = ISO8601DateFormatter() return dateFormatter.date(from: string)! } } //protocol TodoListViewModelingFactory { func makeTodoListViewModel() -> TodoListViewModeling } //extension Container: TodoListViewModelingFactory { // func makeTodoListViewModel() -> TodoListViewModeling { // return TodoListViewModel(todoStorage: todoStorage) // } //} //protocol TodoStorageFactory { func makeTodoStorage() -> TodoStoraging } //extension Container: TodoStorageFactory { // func makeTodoStorage() -> TodoStoraging { // return todoStorage // } //} // //protocol TodoNameExamplesStorageFactory { func makeTodoNameExamplesStorage() -> TodoNameExamplesStorage } //extension Container: TodoNameExamplesStorageFactory { // func makeTodoNameExamplesStorage() -> TodoNameExamplesStorage { // return todoNameExamplesStorage // } //} // //protocol SettingsStorageFactory { func makeSettingsStorage() -> SettingsStoraging } //extension Container: SettingsStorageFactory { // func makeSettingsStorage() -> SettingsStoraging { // return settingsStorage // } //}
48.520325
148
0.588807
08d61158e02b2aca201c22200633ac6b63a94a42
11,650
import Foundation import CoreLocation import MapboxDirections import Turf fileprivate let maximumSpeed: CLLocationSpeed = 30 // ~108 kmh fileprivate let minimumSpeed: CLLocationSpeed = 6 // ~21 kmh fileprivate var distanceFilter: CLLocationDistance = 10 fileprivate var verticalAccuracy: CLLocationAccuracy = 10 fileprivate var horizontalAccuracy: CLLocationAccuracy = 40 // minimumSpeed will be used when a location have maximumTurnPenalty fileprivate let maximumTurnPenalty: CLLocationDirection = 90 // maximumSpeed will be used when a location have minimumTurnPenalty fileprivate let minimumTurnPenalty: CLLocationDirection = 0 // Go maximum speed if distance to nearest coordinate is >= `safeDistance` fileprivate let safeDistance: CLLocationDistance = 50 fileprivate class SimulatedLocation: CLLocation { var turnPenalty: Double = 0 override var description: String { return "\(super.description) \(turnPenalty)" } } /** The `SimulatedLocationManager` class simulates location updates along a given route. The route will be replaced upon a `RouteControllerDidReroute` notification. */ open class SimulatedLocationManager: NavigationLocationManager { internal var currentDistance: CLLocationDistance = 0 fileprivate var currentSpeed: CLLocationSpeed = 30 fileprivate let accuracy: DispatchTimeInterval = .milliseconds(50) let updateInterval: DispatchTimeInterval = .milliseconds(1000) fileprivate var timer: DispatchTimer! fileprivate var locations: [SimulatedLocation]! fileprivate var routeShape: LineString! /** Specify the multiplier to use when calculating speed based on the RouteLeg’s `expectedSegmentTravelTimes`. */ public var speedMultiplier: Double = 1 fileprivate var simulatedLocation: CLLocation? override open var location: CLLocation? { get { return simulatedLocation } set { simulatedLocation = newValue } } var route: Route? { didSet { reset() } } open override func copy() -> Any { let copy = SimulatedLocationManager(route: route!) copy.currentDistance = currentDistance copy.simulatedLocation = simulatedLocation copy.currentSpeed = currentSpeed copy.locations = locations copy.routeShape = routeShape copy.speedMultiplier = speedMultiplier return copy } public override var simulatesLocation: Bool { get { return true } set { super.simulatesLocation = newValue } } private var routeProgress: RouteProgress? /** Initalizes a new `SimulatedLocationManager` with the given route. - parameter route: The initial route. - returns: A `SimulatedLocationManager` */ public init(route: Route) { super.init() commonInit(for: route, currentDistance: 0, currentSpeed: 30) } /** Initalizes a new `SimulatedLocationManager` with the given routeProgress. - parameter routeProgress: The routeProgress of the current route. - returns: A `SimulatedLocationManager` */ public init(routeProgress: RouteProgress) { super.init() let currentDistance = calculateCurrentDistance(routeProgress.distanceTraveled) commonInit(for: routeProgress.route, currentDistance: currentDistance, currentSpeed: 0) } private func commonInit(for route: Route, currentDistance: CLLocationDistance, currentSpeed: CLLocationSpeed) { self.currentSpeed = currentSpeed self.currentDistance = currentDistance self.route = route self.timer = DispatchTimer(countdown: .milliseconds(0), repeating: updateInterval, accuracy: accuracy, executingOn: .main) { [weak self] in self?.tick() } NotificationCenter.default.addObserver(self, selector: #selector(didReroute(_:)), name: .routeControllerDidReroute, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil) } private func reset() { if let shape = route?.shape { routeShape = shape locations = shape.coordinates.simulatedLocationsWithTurnPenalties() } } private func calculateCurrentDistance(_ distance: CLLocationDistance) -> CLLocationDistance { return distance + (currentSpeed * speedMultiplier) } @objc private func progressDidChange(_ notification: Notification) { routeProgress = notification.userInfo?[RouteController.NotificationUserInfoKey.routeProgressKey] as? RouteProgress } @objc private func didReroute(_ notification: Notification) { guard let router = notification.object as? Router else { return } self.currentDistance = calculateCurrentDistance(router.routeProgress.distanceTraveled) routeProgress = router.routeProgress route = router.routeProgress.route } deinit { NotificationCenter.default.removeObserver(self, name: .routeControllerDidReroute, object: nil) NotificationCenter.default.removeObserver(self, name: .routeControllerProgressDidChange, object: nil) } override open func startUpdatingLocation() { timer.arm() } override open func stopUpdatingLocation() { timer.disarm() } internal func tick() { guard let polyline = routeShape, let newCoordinate = polyline.coordinateFromStart(distance: currentDistance) else { return } // Closest coordinate ahead guard let lookAheadCoordinate = polyline.coordinateFromStart(distance: currentDistance + 10) else { return } guard let closestCoordinate = polyline.closestCoordinate(to: newCoordinate) else { return } let closestLocation = locations[closestCoordinate.index] let distanceToClosest = closestLocation.distance(from: CLLocation(newCoordinate)) let distance = min(max(distanceToClosest, 10), safeDistance) let coordinatesNearby = polyline.trimmed(from: newCoordinate, distance: 100)!.coordinates // Simulate speed based on expected segment travel time if let expectedSegmentTravelTimes = routeProgress?.currentLeg.expectedSegmentTravelTimes, let shape = routeProgress?.route.shape, let closestCoordinateOnRoute = shape.closestCoordinate(to: newCoordinate), let nextCoordinateOnRoute = shape.coordinates.after(element: shape.coordinates[closestCoordinateOnRoute.index]), let time = expectedSegmentTravelTimes.optional[closestCoordinateOnRoute.index] { let distance = shape.coordinates[closestCoordinateOnRoute.index].distance(to: nextCoordinateOnRoute) currentSpeed = max(distance / time, 2) } else { currentSpeed = calculateCurrentSpeed(distance: distance, coordinatesNearby: coordinatesNearby, closestLocation: closestLocation) } let location = CLLocation(coordinate: newCoordinate, altitude: 0, horizontalAccuracy: horizontalAccuracy, verticalAccuracy: verticalAccuracy, course: newCoordinate.direction(to: lookAheadCoordinate).wrap(min: 0, max: 360), speed: currentSpeed, timestamp: Date()) self.simulatedLocation = location delegate?.locationManager?(self, didUpdateLocations: [location]) currentDistance = calculateCurrentDistance(currentDistance) } private func calculateCurrentSpeed(distance: CLLocationDistance, coordinatesNearby: [CLLocationCoordinate2D]? = nil, closestLocation: SimulatedLocation) -> CLLocationSpeed { // More than 10 nearby coordinates indicates that we are in a roundabout or similar complex shape. if let coordinatesNearby = coordinatesNearby, coordinatesNearby.count >= 10 { return minimumSpeed } // Maximum speed if we are a safe distance from the closest coordinate else if distance >= safeDistance { return maximumSpeed } // Base speed on previous or upcoming turn penalty else { let reversedTurnPenalty = maximumTurnPenalty - closestLocation.turnPenalty return reversedTurnPenalty.scale(minimumIn: minimumTurnPenalty, maximumIn: maximumTurnPenalty, minimumOut: minimumSpeed, maximumOut: maximumSpeed) } } } extension Double { fileprivate func scale(minimumIn: Double, maximumIn: Double, minimumOut: Double, maximumOut: Double) -> Double { return ((maximumOut - minimumOut) * (self - minimumIn) / (maximumIn - minimumIn)) + minimumOut } } extension CLLocation { fileprivate convenience init(_ coordinate: CLLocationCoordinate2D) { self.init(latitude: coordinate.latitude, longitude: coordinate.longitude) } } extension Array where Element : Hashable { fileprivate struct OptionalSubscript { var elements: [Element] subscript (index: Int) -> Element? { return index < elements.count ? elements[index] : nil } } fileprivate var optional: OptionalSubscript { get { return OptionalSubscript(elements: self) } } } extension Array where Element : Equatable { fileprivate func after(element: Element) -> Element? { if let index = self.firstIndex(of: element), index + 1 <= self.count { return index + 1 == self.count ? self[0] : self[index + 1] } return nil } } extension Array where Element == CLLocationCoordinate2D { // Calculate turn penalty for each coordinate. fileprivate func simulatedLocationsWithTurnPenalties() -> [SimulatedLocation] { var locations = [SimulatedLocation]() for (coordinate, nextCoordinate) in zip(prefix(upTo: endIndex - 1), suffix(from: 1)) { let currentCoordinate = locations.isEmpty ? first! : coordinate let course = coordinate.direction(to: nextCoordinate).wrap(min: 0, max: 360) let turnPenalty = currentCoordinate.direction(to: coordinate).difference(from: coordinate.direction(to: nextCoordinate)) let location = SimulatedLocation(coordinate: coordinate, altitude: 0, horizontalAccuracy: horizontalAccuracy, verticalAccuracy: verticalAccuracy, course: course, speed: minimumSpeed, timestamp: Date()) location.turnPenalty = Swift.max(Swift.min(turnPenalty, maximumTurnPenalty), minimumTurnPenalty) locations.append(location) } locations.append(SimulatedLocation(coordinate: last!, altitude: 0, horizontalAccuracy: horizontalAccuracy, verticalAccuracy: verticalAccuracy, course: locations.last!.course, speed: minimumSpeed, timestamp: Date())) return locations } }
42.210145
177
0.654592
61e545d1a23b5635598823b6deff7740f7a6feed
9,635
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import Foundation import Amplify import AmplifyPlugins public class DataStoreHubEventStreamHandler: NSObject, FlutterStreamHandler { private var eventSink: FlutterEventSink? private var token: UnsubscribeToken? private var modelSchemaRegistry: FlutterSchemaRegistry? private var customTypeSchemaRegistry: FlutterSchemaRegistry? /// Protects `eventHistory` from mutual access. private let eventGuard = NSRecursiveLock() /// DataStore hub event history. Used to track events which may be lost on hot restart, such as sync and ready events. private var eventHistory: [HubPayload] = [] /// Event types which should be replayed on hot restart. private let replayableEvents: Set<String> = [ HubPayload.EventName.DataStore.networkStatus, HubPayload.EventName.DataStore.subscriptionsEstablished, HubPayload.EventName.DataStore.ready, HubPayload.EventName.DataStore.syncQueriesStarted, HubPayload.EventName.DataStore.syncQueriesReady, HubPayload.EventName.DataStore.modelSynced, ] public func registerModelsForHub(modelSchemaRegistry: FlutterSchemaRegistry, customTypeSchemaRegistry: FlutterSchemaRegistry) { self.modelSchemaRegistry = modelSchemaRegistry self.customTypeSchemaRegistry = customTypeSchemaRegistry } public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { self.eventSink = events setHubListener() return nil } func ensureSchemaRegistries() throws -> ( modelSchemaRegistry: FlutterSchemaRegistry, customTypeSchemaRegistry: FlutterSchemaRegistry ) { guard let modelSchemaRegistry = self.modelSchemaRegistry else { throw FlutterDataStoreError.acquireSchemaForHub } guard let customTypeSchemaRegistry = self.customTypeSchemaRegistry else { throw FlutterDataStoreError.acquireSchemaForHub } return (modelSchemaRegistry, customTypeSchemaRegistry) } func setHubListener() { // Replay events. On hot restart, `onListen` is called again with a new listener. However, // DataStore will not re-emit events such as ready and modelSynced. As a result, this info // is lost on the Flutter side unless we replay the history prior to the hot restart. #if DEBUG if !eventHistory.isEmpty { eventGuard.lock() defer { eventGuard.unlock() } for payload in eventHistory { sendPayload(payload) } } #endif token = Amplify.Hub.listen(to: .dataStore) { [unowned self] (payload) in #if DEBUG eventGuard.lock() defer { eventGuard.unlock() } if replayableEvents.contains(payload.eventName) { eventHistory.append(payload) } #endif sendPayload(payload) } } func sendPayload(_ payload: HubPayload) { var flutterEvent: [String: Any]? switch payload.eventName { case HubPayload.EventName.DataStore.networkStatus : do { let networkStatus = try FlutterNetworkStatusEvent (payload: payload) flutterEvent = networkStatus.toValueMap() } catch { print("Failed to parse and send networkStatus event: \(error)") } case HubPayload.EventName.DataStore.outboxStatus : do { let outboxStatus = try FlutterOutboxStatusEvent (payload: payload) flutterEvent = outboxStatus.toValueMap() } catch { print("Failed to parse and send outboxStatus event: \(error)") } case HubPayload.EventName.DataStore.subscriptionsEstablished : do { let subscriptionsEstablished = try FlutterSubscriptionsEstablishedEvent(payload: payload) flutterEvent = subscriptionsEstablished.toValueMap() } catch { print("Failed to parse and send subscriptionsEstablished event: \(error)") } case HubPayload.EventName.DataStore.syncQueriesStarted : do { let syncQueriesStarted = try FlutterSyncQueriesStartedEvent(payload: payload) flutterEvent = syncQueriesStarted.toValueMap() } catch { print("Failed to parse and send syncQueriesStarted event: \(error)") } case HubPayload.EventName.DataStore.modelSynced : do { let modelSynced = try FlutterModelSyncedEvent(payload: payload) flutterEvent = modelSynced.toValueMap() } catch { print("Failed to parse and send modelSynced event: \(error)") } case HubPayload.EventName.DataStore.syncQueriesReady : do { let syncQueriesReady = try FlutterSyncQueriesReadyEvent(payload: payload) flutterEvent = syncQueriesReady.toValueMap() } catch { print("Failed to parse and send syncQueriesReady event: \(error)") } case HubPayload.EventName.DataStore.ready : do { let ready = try FlutterReadyEvent(payload: payload) flutterEvent = ready.toValueMap() } catch { print("Failed to parse and send ready event: \(error)") } case HubPayload.EventName.DataStore.outboxMutationEnqueued : do { guard let outboxMutationEnqueued = payload.data as? OutboxMutationEvent else { throw FlutterDataStoreError.hubEventCast } let schemaRegistries = try self.ensureSchemaRegistries() let flutterOutboxMutationEnqueued = try FlutterOutboxMutationEnqueuedEvent( outboxMutationEnqueued: outboxMutationEnqueued, eventName: payload.eventName, modelSchemaRegistry: schemaRegistries.modelSchemaRegistry, customTypeSchemaRegistry: schemaRegistries.customTypeSchemaRegistry ) flutterEvent = flutterOutboxMutationEnqueued.toValueMap() } catch { print("Failed to parse and send outboxMutationEnqueued event: \(error)") } case HubPayload.EventName.DataStore.outboxMutationProcessed : do { guard let outboxMutationProcessed = payload.data as? OutboxMutationEvent else { throw FlutterDataStoreError.hubEventCast } let schemaRegistries = try self.ensureSchemaRegistries() let flutterOutboxMutationProcessed = try FlutterOutboxMutationProcessedEvent( outboxMutationProcessed: outboxMutationProcessed, eventName: payload.eventName, modelSchemaRegistry: schemaRegistries.modelSchemaRegistry, customTypeSchemaRegistry: schemaRegistries.customTypeSchemaRegistry ) flutterEvent = flutterOutboxMutationProcessed.toValueMap() } catch { print("Failed to parse and send outboxMutationProcessed event: \(error)") } case HubPayload.EventName.DataStore.syncReceived: do { guard let eventData = payload.data as? MutationEvent else { throw FlutterDataStoreError.hubEventCast } let schemaRegistries = try self.ensureSchemaRegistries() let syncReceived = try FlutterSyncReceivedEvent( event: eventData, eventName: payload.eventName, modelSchemaRegistry: schemaRegistries.modelSchemaRegistry, customTypeSchemaRegistry: schemaRegistries.customTypeSchemaRegistry ) flutterEvent = syncReceived.toValueMap() } catch { print("Failed to parse and send syncReceived event: \(error)") } case HubPayload.EventName.Amplify.configured: print("DataStorePlugin successfully initialized") default: print("Unhandled DataStoreHubEvent: \(payload.eventName) \(payload.data ?? "")" ) } if let flutterEvent = flutterEvent { sendEvent(flutterEvent: flutterEvent) } } func sendEvent(flutterEvent: [String: Any]) { DispatchQueue.main.async { self.eventSink?(flutterEvent) } } public func onCancel(withArguments arguments: Any?) -> FlutterError? { eventSink = nil if let token = token { Amplify.Hub.removeListener(token) } token = nil return nil } deinit { if let token = token { Amplify.Hub.removeListener(token) } } }
42.822222
131
0.626985
0a68a97eb4574c78bfba96a70e719650c2fe2b60
5,632
// // RunScriptIntentHandler.swift // Pyto Intents // // Created by Adrian Labbé on 30-07-19. // Copyright © 2019 Adrian Labbé. All rights reserved. // import Intents import ios_system class RunCommandIntentHandler: NSObject, RunCommandIntentHandling { private enum PythonVersion { case v2_7 case v3_7 } private func setPythonEnvironment(version: PythonVersion) { guard let py2Path = Bundle.main.path(forResource: "python27", ofType: "zip") else { fatalError() } let py2SitePackages = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask)[0].appendingPathComponent("site-packages2").path guard let py3Path = Bundle.main.path(forResource: "python37", ofType: "zip") else { fatalError() } let py3SitePackages = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask)[0].appendingPathComponent("site-packages3").path let bundledSitePackages = Bundle.main.bundleURL.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("site-packages").path let bundledSitePackages3 = Bundle.main.bundleURL.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("site-packages3").path putenv("PYTHONHOME=\(Bundle.main.bundlePath)".cValue) if version == .v2_7 { putenv("PYTHONPATH=\(py2SitePackages):\(py2Path):\(bundledSitePackages)".cValue) } else if version == .v3_7 { putenv("PYTHONPATH=\(py3SitePackages):\(py3Path):\(bundledSitePackages):\(bundledSitePackages3)".cValue) } } func handle(intent: RunCommandIntent, completion: @escaping (RunCommandIntentResponse) -> Void) { sideLoading = true let output = Pipe() let _stdout = fdopen(output.fileHandleForWriting.fileDescriptor, "w") let _stderr = fdopen(output.fileHandleForWriting.fileDescriptor, "w") let _stdin = fopen(Bundle.main.path(forResource: "input", ofType: "txt")!.cValue, "r") initializeEnvironment() unsetenv("TERM") unsetenv("LSCOLORS") unsetenv("CLICOLOR") try? FileManager.default.copyItem(at: Bundle.main.url(forResource: "cacert", withExtension: "pem")!, to: FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask)[0].appendingPathComponent("cacert.pem")) ios_switchSession(_stdout) ios_setStreams(_stdin, _stdout, _stderr) ios_setDirectoryURL(FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask)[0]) if intent.command?.hasPrefix("python2 ") == true { setPythonEnvironment(version: .v2_7) } else { setPythonEnvironment(version: .v3_7) } var command = intent.command ?? "" var arguments = command.arguments let scriptsDirectory = (FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.libtermbin") ?? FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask)[0]).appendingPathComponent("Documents") let url: URL let _command: String let llURL = scriptsDirectory.appendingPathComponent(arguments[0]+".ll") let bcURL = scriptsDirectory.appendingPathComponent(arguments[0]+".bc") let binURL = scriptsDirectory.appendingPathComponent(arguments[0]) let scriptURL = scriptsDirectory.appendingPathComponent(arguments[0]+".py") if FileManager.default.fileExists(atPath: binURL.path) { url = binURL _command = "lli" } else if FileManager.default.fileExists(atPath: llURL.path) { url = llURL _command = "lli" } else if FileManager.default.fileExists(atPath: bcURL.path) { url = bcURL _command = "lli" } else { url = scriptURL _command = "python" } if FileManager.default.fileExists(atPath: url.path) { arguments.insert(_command, at: 0) arguments.remove(at: 1) arguments.insert(url.path, at: 1) command = arguments.joined(separator: " ") } var retValue: Int32 = 0 if let cwd = intent.cwd, !cwd.isEmpty { ios_system("cd \(cwd.replacingOccurrences(of: " ", with: "\\ ").replacingOccurrences(of: "\"", with: "\\\"").replacingOccurrences(of: "'", with: "\\'"))") } retValue = ios_system(command) let response = RunCommandIntentResponse(code: retValue == 0 ? .success : .failure, userActivity: nil) let outputStr = String(data: output.fileHandleForReading.availableData, encoding: .utf8) ?? "" if !outputStr.replacingOccurrences(of: "\n", with: "").isEmpty { response.output = outputStr } return completion(response) } func resolveCommand(for intent: RunCommandIntent, with completion: @escaping (INStringResolutionResult) -> Void) { guard let command = intent.command else { return } return completion(.success(with: command)) } func resolveCwd(for intent: RunCommandIntent, with completion: @escaping (INStringResolutionResult) -> Void) { guard let cwd = intent.cwd else { return completion(.success(with: "")) } return completion(.success(with: cwd)) } }
40.811594
237
0.622692
6ae2271d0d77b14b315f7cd4dec0f7091e39b10c
1,478
// 1101. The Earliest Moment When Everyone Become Friends // https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/ // Runtime: 156 ms, faster than 60.00% of Swift online submissions for The Earliest Moment When Everyone Become Friends. // Memory Usage: 14.4 MB, less than 26.67% of Swift online submissions for The Earliest Moment When Everyone Become Friends. class Solution { func find(_ parents: inout [[Int]], _ i: Int) -> Int { var pi = parents[i][0] if pi != i { pi = find(&parents, pi) } parents[i][0] = pi return pi } func union(_ parents: inout [[Int]], _ i: Int, _ j: Int) -> Int { let pi = find(&parents, i) let pj = find(&parents, j) if pi == pj { return parents[pi][1] } if parents[pi][1] < parents[pj][1] { parents[pi][0] = pj parents[pj][1] += parents[pi][1] return parents[pj][1] } else { parents[pj][0] = pi parents[pi][1] += parents[pj][1] return parents[pi][1] } } func earliestAcq(_ logs: [[Int]], _ N: Int) -> Int { var parents = Array(repeating: [0, 1], count: N + 1) for i in 1...N { parents[i][0] = i } for log in logs.sorted{ $0[0] < $1[0] } { if union(&parents, log[1], log[2]) == N { return log[0] } } return -1 } }
33.590909
124
0.515562
2876f8ca1d295f88ab869e2a52f5df56b4422b06
9,314
// // Copyright (C) Schweizerische Bundesbahnen SBB, 2021. // import XCTest import AVFoundation @testable import SBBML class ObjectDetectionServiceTests: XCTestCase { private let timeout = TimeInterval(3.0) private var objectDetectionService: ObjectDetectionService! private var fakeCameraController: FakeCameraController! private var fakeObjectDetection: FakeObjectDetection! private var fakeObjectTracking: FakeObjectTracking! private let fakeDetectedObjects1 = [DetectedObject(label: "Object 1", confidence: 0.9, depth: nil, rect: CGRect(), rectInPreviewLayer: CGRect())] private let fakeDetectedObjects2 = [DetectedObject(label: "Object 2", confidence: 0.2, depth: nil, rect: CGRect(), rectInPreviewLayer: CGRect())] override func setUpWithError() throws { self.fakeCameraController = FakeCameraController() self.fakeObjectDetection = FakeObjectDetection() self.fakeObjectTracking = FakeObjectTracking() self.objectDetectionService = ObjectDetectionService(cameraController: fakeCameraController, objectDetection: fakeObjectDetection, objectTracking: fakeObjectTracking) } // MARK: detectedObjectsPublisher tests func testDetectedObjectsArePublished() throws { let expectation = self.expectation(description: "wait for detected objects") var counter = 0 let sub = objectDetectionService.detectedObjectsPublisher.sink { detectedObjects in counter += 1 switch counter { case 1: XCTAssertTrue(detectedObjects.isEmpty) self.fakeObjectDetection.detectedObjectsSubject.send(self.fakeDetectedObjects1) case 2: XCTAssertEqual(detectedObjects, self.fakeDetectedObjects1) self.fakeObjectDetection.detectedObjectsSubject.send(self.fakeDetectedObjects2) case 3: XCTAssertEqual(detectedObjects, self.fakeDetectedObjects2) self.fakeObjectDetection.detectedObjectsSubject.send([]) case 4: XCTAssertTrue(detectedObjects.isEmpty) expectation.fulfill() default: XCTFail() } } waitForExpectations(timeout: timeout) { _ in sub.cancel() } } func testObjectTrackingIsStarted() throws { self.objectDetectionService = ObjectDetectionService(configuration: ObjectDetectionServiceConfiguration(objectDetectionRate: 2, objectTrackingEnabled: true), cameraController: fakeCameraController, objectDetection: fakeObjectDetection, objectTracking: fakeObjectTracking) let expectation = self.expectation(description: "wait for detected objects") var counter = 0 let sub = objectDetectionService.detectedObjectsPublisher.sink { detectedObjects in counter += 1 switch counter { case 1: XCTAssertTrue(detectedObjects.isEmpty) XCTAssertNil(self.fakeObjectTracking.receivedObjects) self.fakeObjectDetection.detectedObjectsSubject.send(self.fakeDetectedObjects1) case 2: XCTAssertEqual(detectedObjects, self.fakeDetectedObjects1) XCTAssertEqual(detectedObjects, self.fakeObjectTracking.receivedObjects) expectation.fulfill() default: XCTFail() } } waitForExpectations(timeout: timeout) { _ in sub.cancel() } } func testTrackedObjectsArePublished() throws { self.objectDetectionService = ObjectDetectionService(configuration: ObjectDetectionServiceConfiguration(objectDetectionRate: 2, objectTrackingEnabled: true), cameraController: fakeCameraController, objectDetection: fakeObjectDetection, objectTracking: fakeObjectTracking) let expectation = self.expectation(description: "wait for detected objects") var counter = 0 let sub = objectDetectionService.detectedObjectsPublisher.sink { detectedObjects in counter += 1 switch counter { case 1: XCTAssertTrue(detectedObjects.isEmpty) self.fakeObjectDetection.detectedObjectsSubject.send(self.fakeDetectedObjects1) case 2: XCTAssertEqual(detectedObjects, self.fakeDetectedObjects1) XCTAssertEqual(detectedObjects, self.fakeObjectTracking.receivedObjects) self.fakeObjectTracking.trackedObjectsSubject.send(self.fakeDetectedObjects2) case 3: XCTAssertEqual(detectedObjects, self.fakeDetectedObjects2) self.fakeObjectTracking.trackedObjectsSubject.send([]) case 4: XCTAssertTrue(detectedObjects.isEmpty) expectation.fulfill() default: XCTFail() } } waitForExpectations(timeout: timeout) { _ in sub.cancel() } } func testObjectTrackingIsStoppedWhenNewObjectsAreDetected() throws { self.objectDetectionService = ObjectDetectionService(configuration: ObjectDetectionServiceConfiguration(objectDetectionRate: 1, objectTrackingEnabled: true), cameraController: fakeCameraController, objectDetection: fakeObjectDetection, objectTracking: fakeObjectTracking) let image = UIImage(named: "Sitz_1Klasse", in: Bundle(for: ObjectDetectionTests.self), compatibleWith: nil)! let cmSampleBuffer = CMSampleBufferCreator.cmSampleBuffer(from: image) let expectation = self.expectation(description: "wait for detected objects") self.fakeCameraController.cameraOutputSubject.send(CameraOutput(videoBuffer: cmSampleBuffer, depthBuffer: nil)) var counter = 0 let sub = objectDetectionService.detectedObjectsPublisher.sink { detectedObjects in counter += 1 switch counter { case 1: XCTAssertTrue(detectedObjects.isEmpty) self.fakeObjectDetection.detectedObjectsSubject.send(self.fakeDetectedObjects1) case 2: XCTAssertEqual(detectedObjects, self.fakeDetectedObjects1) XCTAssertEqual(detectedObjects, self.fakeObjectTracking.receivedObjects) self.fakeObjectTracking.trackedObjectsSubject.send(self.fakeDetectedObjects2) case 3: XCTAssertEqual(detectedObjects, self.fakeDetectedObjects2) DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { self.fakeCameraController.cameraOutputSubject.send(CameraOutput(videoBuffer: cmSampleBuffer, depthBuffer: nil)) DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { XCTAssertTrue(self.fakeObjectTracking.stoppedTracking) expectation.fulfill() } } default: XCTFail() } } waitForExpectations(timeout: timeout) { _ in sub.cancel() } } // MARK: errorPublisher tests func testObjectDetectionErrorsArePublished() throws { let expectation = self.expectation(description: "wait for errors") var counter = 0 let sub = objectDetectionService.errorPublisher.sink { error in counter += 1 switch counter { case 1: XCTAssertNil(error) self.fakeObjectDetection.errorSubject.send(.inputsAreInvalid) case 2: XCTAssertEqual(error, .inputsAreInvalid) self.fakeObjectDetection.errorSubject.send(nil) case 3: XCTAssertNil(error) self.fakeObjectDetection.errorSubject.send(.outputsAreInvalid) case 4: XCTAssertEqual(error, .outputsAreInvalid) expectation.fulfill() default: XCTFail() } } waitForExpectations(timeout: timeout) { _ in sub.cancel() } } func testCameraControllerErrorsArePublished() throws { let expectation = self.expectation(description: "wait for errors") var counter = 0 let sub = objectDetectionService.errorPublisher.sink { error in counter += 1 switch counter { case 1: XCTAssertNil(error) self.fakeCameraController.errorSubject.send(.noCamerasAvailable) case 2: XCTAssertEqual(error, .noCamerasAvailable) self.fakeCameraController.errorSubject.send(nil) case 3: XCTAssertNil(error) self.fakeCameraController.errorSubject.send(.cannotCreateImageBuffer) case 4: XCTAssertEqual(error, .cannotCreateImageBuffer) expectation.fulfill() default: XCTFail() } } waitForExpectations(timeout: timeout) { _ in sub.cancel() } } }
42.921659
279
0.633348
20417b78689580beb87c62d99fe3dae7c968886b
1,500
// // CardPartCenteredViewCardController.swift // CardParts_Example // // Created by Tumer, Deniz on 6/20/18. // Copyright © 2018 Intuit. All rights reserved. // import Foundation import CardParts class CardPartCenteredViewCardController: CardPartsViewController { override func viewDidLoad() { super.viewDidLoad() let separator = CardPartVerticalSeparatorView() let leftStack = CardPartStackView() leftStack.axis = .vertical leftStack.spacing = 10 let rightStack = CardPartStackView() rightStack.axis = .vertical rightStack.spacing = 10 let textView = CardPartTextView(type: .normal) textView.text = "This is a label with text" let textView2 = CardPartTextView(type: .normal) textView2.text = "This is a second label with text" let textView3 = CardPartTextView(type: .normal) textView3.text = "This is a third label with text" let textView4 = CardPartTextView(type: .normal) textView4.text = "This is a fourth label with text" leftStack.addArrangedSubview(textView) leftStack.addArrangedSubview(textView2) rightStack.addArrangedSubview(textView3) rightStack.addArrangedSubview(textView4) let centeredView = CardPartCenteredView(leftView: leftStack, centeredView: separator, rightView: rightStack) setupCardParts([centeredView]) } }
31.914894
116
0.661333
469dc572f25d61972d86833433741e2a0dd84853
245
// // WidgetProtocol.swift // MTMR // // Created by Anton Palgunov on 20/10/2018. // Copyright © 2018 Anton Palgunov. All rights reserved. // protocol Widget { static var name: String { get } static var identifier: String { get } }
18.846154
57
0.661224
8775643505a2c8160fd0e44992864b9c7611ca73
14,508
// // DownloadCommand.swift // SwiftyPoeditor // // Created by Oleksandr Vitruk on 10/4/19. // import Foundation import ConsoleKit enum DownloadCommandError: Error, LocalizedError { case settingsIncorrect var errorDescription: String? { switch self { case .settingsIncorrect: return "Entered settings are incorrect. Aborting execution" } } } class DownloadCommand: Command, PrettyOutput { // MARK: - Declarations /// describes allowed params with their description in current command struct Signature: CommandSignature { @Option(name: "token", short: "t", help: "POEditor API token") var token: String? @Option(name: "id", short: "i", help: "POEditor project id") var id: String? @Option(name: "language", short: "l", help: "POEditor language code for the localization that should be exported and downloaded. Default value is \(Constants.Defaults.language)") var language: String? @Option(name: "destination", short: "d", help: "Destination file path, where donwloaded localization should be saved") var destination: String? @Option(name: "export-type", short: "e", help: "In which format localization should be exported from POEditor. Default value s \(Constants.Defaults.exportType.rawValue)") var exportType: String? @Flag(name: "yes", short: "y", help: "Automaticly say \"yes\" in every y/n question. E.g for the parsed settings validation") var yesForAll: Bool @Flag(name: "short-output", short: "s", help: "Disables printing unnecessary information and disables colored output") var shortOutput: Bool init() {} } // MARK: - Private properties private var poeditorClient: Poeditor? // POEditor API client private var fileManager: LocalizationsFileManager? // FileManager // MARK: - Public properties var help: String { "This command will export and download specified language as *.strings from POEditor service." } var currentLoadingBar: ActivityIndicator<LoadingBar>? // console activity indicator var shortOutput: Bool = false // MARK: - Command protocol implementation /// execute command /// - Parameter context: console context /// - Parameter signature: signature that was received from console input func run(using context: CommandContext, signature: Signature) throws { // compose settings object from console input let settings = self.parseInput(context: context, signature: signature) // prints current settings in order to check them printSettings(settings: settings, context: context) do { // validate settings try validateSettings(settings: settings, context: context, signature: signature) // request localization download URL via POEditor API client let downloadURLPath = try requestLocalizationDownloadURL(with: settings, context: context) // downloads localization file data form requested URL let fileData = try downloadLocalization(with: settings, downloadURLPath: downloadURLPath, context: context) // writes downloaded data to destination file try writeDataToFile(with: settings, data: fileData, context: context) } catch { // show fail result in console currentLoadingBar?.fail() // redirect error to top level for further handling throw error } } // MARK: - Private methods /// parse input to settings struct /// if some required params not provided, ask them in console /// - Parameter context: current console context /// - Parameter signature: received signature private func parseInput(context: CommandContext, signature: Signature) -> DownloadSettings { self.shortOutput = signature.shortOutput let errorStyle: ConsoleStyle = shortOutput ? .plain : .error var token: String // use provided token or ask it if let argToken = signature.token { token = argToken } else { token = context.console.ask("You should provide your API token for the POEditor.\nEnter it now or use command (--help for details)?".consoleText(errorStyle)) } var id: String // use provided project id or ask it if let argID = signature.id { id = argID } else { id = context.console.ask("You should provide your POEditor project ID.\nEnter it now or use command (--help for details)?".consoleText(errorStyle)) } // use provided language or use default (optional param) var language: String if let argLanguage: String = signature.language { language = argLanguage } else { if signature.yesForAll == true { language = Constants.Defaults.language } else { let question: ConsoleText = .init(stringLiteral: "Use \(Constants.Defaults.language) as requested localization language?") let decision = context.console.confirm(question) if decision == true { language = Constants.Defaults.language } else { language = context.console.ask("You should provide language code of localization that should be downloaded.\nEnter it now or use command (--help for details)?".consoleText(errorStyle)) } } } var destination: String // use provided path or ask it if let argDestination = signature.destination { destination = argDestination } else { destination = context.console.ask("You should provide destination file path where downloaded localization should be saved.\nEnter it now or use command (--help for details)?".consoleText(errorStyle)) } var exportType: PoeditorExportType // use provided export type or ask it if let argExportType = signature.exportType { exportType = PoeditorExportType(rawValue: argExportType) ?? Constants.Defaults.exportType } else { if signature.yesForAll == true { exportType = Constants.Defaults.exportType } else { let title: ConsoleText = .init(stringLiteral: "Please select export format:") let cases = PoeditorExportType.allCases.map { $0.rawValue } let decision = context.console.choose(title, from: cases) if let type = PoeditorExportType(rawValue: decision) { exportType = type } else { printToConsole(context: context, string: "Unable to parse selected export type. \( Constants.Defaults.exportType.rawValue) will be used.", style: .warning) exportType = Constants.Defaults.exportType } } } let poeditorSettings: PoeditorSettings = PoeditorSettings(token: token, id: id, language: language) let fileManagerSettings: FileManagerSettings = FileManagerSettings(destinationPath: destination) return DownloadSettings(poeditorSettings: poeditorSettings, fileManagerSettings: fileManagerSettings, type: exportType) } /// print to user parsed settings /// - Parameter settings: parsed settings /// - Parameter context: current console context private func printSettings(settings: DownloadSettings, context: CommandContext) { let redStyle: ConsoleStyle = shortOutput ? .plain : .init(color: .red) let brightMagentaStyle: ConsoleStyle = shortOutput ? .plain : .init(color: .red) let rawToken = settings.poeditorSettings.token let tokenRange = rawToken.startIndex..<rawToken.index(rawToken.endIndex, offsetBy: -3) let tokenStar = rawToken[tokenRange].map { _ in "*" }.joined(separator: "") let token: String = rawToken.replacingCharacters(in: tokenRange, with: tokenStar) let rawProjectID = settings.poeditorSettings.id let projectIDRange = rawProjectID.startIndex..<rawProjectID.index(rawProjectID.endIndex, offsetBy: -3) let projectStar = rawProjectID[projectIDRange].map { _ in "*" }.joined(separator: "") let projectID: String = rawProjectID.replacingCharacters(in: projectIDRange, with: projectStar) let settingsText: ConsoleText = [ConsoleTextFragment(string: "\n", style: redStyle), ConsoleTextFragment(string: "Current settings that will be used:\n", style: brightMagentaStyle), ConsoleTextFragment(string: "token: \(token)\n", style: brightMagentaStyle), ConsoleTextFragment(string: "id: \(projectID)\n", style: brightMagentaStyle), ConsoleTextFragment(string: "language: \(settings.poeditorSettings.language)\n", style: brightMagentaStyle), ConsoleTextFragment(string: "destination: \(settings.fileManagerSettings.destinationPath)\n", style: brightMagentaStyle), ConsoleTextFragment(string: "export type: \(settings.type.rawValue)\n", style: brightMagentaStyle)] context.console.output(settingsText) } /// validate entered settings /// - Parameter settings: parsed settings /// - Parameter context: current console context /// - Parameter signature: received signature private func validateSettings(settings: DownloadSettings, context: CommandContext, signature: Signature) throws { guard signature.yesForAll == false else { return } let redStyle: ConsoleStyle = shortOutput ? .plain : .init(color: .red) let text = ConsoleText(arrayLiteral: ConsoleTextFragment(string: "Please check all settings carefully. Everything is correct?", style: redStyle)) let result = context.console.confirm(text) guard result == true else { throw UploadCommandError.settingsIncorrect } } /// request on POEditor API download URL for specified langugage /// - Parameter settings: parsed settings /// - Parameter context: current console context private func requestLocalizationDownloadURL(with settings: DownloadSettings, context: CommandContext) throws -> String { createLoadingBar(context: context, title: "Requesting \(settings.poeditorSettings.language) localization download url...") currentLoadingBar?.start() let client = getOrCreatePOEditorClient(settings: settings.poeditorSettings) let result = try client.requestExportLocalization(exportType: settings.type).wait() currentLoadingBar?.succeed() printToConsole(context: context, string: "Download url is \(result.urlPath)", style: .info) return result.urlPath } /// try to download localization with provided settings and url /// - Parameter settings: parsed settings /// - Parameter context: current console settings private func downloadLocalization(with settings: DownloadSettings, downloadURLPath: String, context: CommandContext) throws -> Data { createLoadingBar(context: context, title: "Downloading \(settings.poeditorSettings.language) localization...") currentLoadingBar?.start() let client = getOrCreatePOEditorClient(settings: settings.poeditorSettings) let result = try client.downloadLocalization(downloadPath: downloadURLPath).wait() currentLoadingBar?.succeed() printToConsole(context: context, string: "Download \(settings.poeditorSettings.language) localization success", style: .info) return result } /// write data to destination file /// - Parameter settings: parsed settings /// - Parameter data: downloaded data /// - Parameter context: current console settings private func writeDataToFile(with settings: DownloadSettings, data: Data, context: CommandContext) throws { createLoadingBar(context: context, title: "Writing data to file at path \(settings.fileManagerSettings.destinationPath)...") currentLoadingBar?.start() let manager = getOrCreateFileManager(settings: settings.fileManagerSettings) let result = try manager.writeData(data: data) currentLoadingBar?.succeed() printToConsole(context: context, string: "File successfully written at path \(result.path)", style: .info) } /// get or create new POEditor API client /// - Parameter settings: parsed settings private func getOrCreatePOEditorClient(settings: PoeditorSettings) -> Poeditor { if let client = self.poeditorClient { // returns existing client return client } // create and save new client let client = Poeditor(settings: settings) self.poeditorClient = client return client } /// get or create new file manager /// - Parameter settings: parsed settings private func getOrCreateFileManager(settings: FileManagerSettings) -> LocalizationsFileManager { if let manager = self.fileManager { // returns existing client return manager } // create and save new client let manager = LocalizationsFileManager(settings: settings) self.fileManager = manager return manager } }
46.8
211
0.617659
1ddfcb86d491a907c79b3e3c73817b02747da084
1,465
// // GAPCompleteListOf16BitServiceClassUUIDs.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// GAP Complete List of 16-bit Service Class UUIDs public struct GAPCompleteListOf16BitServiceClassUUIDs: GAPData, Equatable { public static let dataType: GAPDataType = .completeListOf16CitServiceClassUUIDs public var uuids: [UInt16] public init(uuids: [UInt16] = []) { self.uuids = uuids } } public extension GAPCompleteListOf16BitServiceClassUUIDs { init?(data: Data) { guard let list = GAPUUIDList<ArrayLiteralElement>(data: data) else { return nil } self.uuids = list.uuids } func append(to data: inout Data) { data += GAPUUIDList(uuids: uuids) } var dataLength: Int { return MemoryLayout<ArrayLiteralElement>.size * uuids.count } } // MARK: - ExpressibleByArrayLiteral extension GAPCompleteListOf16BitServiceClassUUIDs: ExpressibleByArrayLiteral { public init(arrayLiteral elements: UInt16...) { self.init(uuids: elements) } } // MARK: - CustomStringConvertible extension GAPCompleteListOf16BitServiceClassUUIDs: CustomStringConvertible { public var description: String { return uuids.map { BluetoothUUID.bit16($0) }.description } }
22.890625
83
0.65802
18b4f19039f5a977281d24116a04afc7e0720db0
4,443
// // Transition.swift // Practice3 // // Created by ITlearning on 2021/10/03. // import UIKit import SnapKit class Transition: NSObject { var startingFrame = CGRect.zero var destinationFrame = CGRect.zero var shadow = UIView() let durataion = 0.7 enum TransitionMode: Int { case present case dismiss case pop } var transitionMode: TransitionMode = .present } extension Transition: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return durataion } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView if transitionMode == .present { if let presentingView = transitionContext.view(forKey: UITransitionContextViewKey.to) { let initialFrame = startingFrame let finalFrame = destinationFrame let scaleX = initialFrame.width / finalFrame.width let scaleY = initialFrame.height / finalFrame.height shadow.backgroundColor = UIColor.lightGray shadow.frame = containerView.frame shadow.alpha = 0 containerView.addSubview(shadow) presentingView.frame = destinationFrame presentingView.transform = CGAffineTransform(scaleX: scaleX, y: scaleY) presentingView.center = CGPoint(x: initialFrame.midX, y: initialFrame.midY) presentingView.clipsToBounds = true presentingView.layer.cornerRadius = 30 containerView.addSubview(presentingView) containerView.bringSubviewToFront(presentingView) UIView.animate(withDuration: durataion, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseIn, animations: { self.shadow.alpha = 0.95 presentingView.transform = CGAffineTransform.identity presentingView.layer.cornerRadius = 0 presentingView.frame.origin = CGPoint(x:0, y:0) presentingView.frame.size = containerView.frame.size }) { (success) in transitionContext.completeTransition(success) } } } else { let transitionModeKey = (transitionMode == .pop) ? UITransitionContextViewKey.to : UITransitionContextViewKey.from if let returningView = transitionContext.view(forKey: transitionModeKey) { let initialFrame = destinationFrame let finalFrame = startingFrame print("\(finalFrame.width), \(initialFrame.width)") print("\(finalFrame.height), \(initialFrame.height)") let scaleX = finalFrame.width / initialFrame.width let scaleY = finalFrame.height / initialFrame.height shadow.backgroundColor = UIColor.lightGray shadow.frame = containerView.frame shadow.alpha = 0.95 containerView.addSubview(shadow) returningView.clipsToBounds = true containerView.addSubview(returningView) containerView.bringSubviewToFront(returningView) containerView.sendSubviewToBack(containerView) UIView.animate(withDuration: durataion, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: .curveEaseIn, animations: { self.shadow.alpha = 0.0 returningView.transform = CGAffineTransform(scaleX: scaleX, y: scaleY) returningView.layer.cornerRadius = 15 returningView.frame = finalFrame if self.transitionMode == .pop { containerView.insertSubview(returningView, belowSubview: returningView) } }) { success in returningView.removeFromSuperview() transitionContext.completeTransition(success) } } } } }
41.915094
157
0.587666
0a3ac60e7f15584df1ff56512fd8df4f9695e3f4
780
// // landmarksApp.swift // landmarks // // Created by Lohan Marques on 05/01/21. // import SwiftUI @main struct Main: App { @StateObject private var modelData = ModelData() var body: some Scene { let mainWindow = WindowGroup { ContentView() .environmentObject(modelData) } #if os(macOS) mainWindow .commands { LandmarkCommands() } #else mainWindow #endif #if os(watchOS) WKNotificationScene(controller: NotificationController.self, category: "LandmarkNear") #endif #if os(macOS) Settings { LandmarkSettings() } #endif } }
19.5
94
0.502564
87760f982e3d2cd69c3a8933a3d7c86803baf323
8,658
// // NLUTensorflowSlotParserTest.swift // SpokestackTests // // Created by Noel Weichbrodt on 2/25/20. // Copyright © 2020 Spokestack, Inc. All rights reserved. // import Foundation import Spokestack import XCTest class NLUTensorflowSlotParserTest: XCTestCase { let parser = NLUTensorflowSlotParser() var encoder: BertTokenizer? var metadata: NLUTensorflowMetadata? override func setUp() { super.setUp() let config = SpeechConfiguration() config.nluVocabularyPath = SharedTestMocks.createVocabularyPath() self.encoder = try! BertTokenizer(config) let metaData = createMetadata().data(using: .utf8) self.metadata = try! JSONDecoder().decode(NLUTensorflowMetadata.self, from: metaData!) } func testParseSelset() { let et = EncodedTokens(tokensByWhitespace: ["kitchen"], encodedTokensByWhitespaceIndex: [0], encoded: []) let parsedSelset = try! parser.parse(tags: ["b_location"], intent: metadata!.intents.filter({ $0.name == "request.lights.deactivate" }).first!, encoder: encoder!, encodedTokens: et) XCTAssertEqual(parsedSelset!["location"]!.value as! String, "room") XCTAssertEqual(parsedSelset!["location"]!.rawValue!, "kitchen") // selset value has appended punctuation let et2 = EncodedTokens(tokensByWhitespace: ["kitchen."], encodedTokensByWhitespaceIndex: [0], encoded: []) let parsedSelset2 = try! parser.parse(tags: ["b_location"], intent: metadata!.intents.filter({ $0.name == "request.lights.deactivate" }).first!, encoder: encoder!, encodedTokens: et2) XCTAssertEqual(parsedSelset2!["location"]!.value as! String, "room") } func testParseInteger() { let et1 = EncodedTokens(tokensByWhitespace: ["ten"], encodedTokensByWhitespaceIndex: [0], encoded: []) let parsedInteger10 = try! parser.parse(tags: ["b_rating"], intent: metadata!.intents.filter({ $0.name == "rate.app" }).first!, encoder: encoder!, encodedTokens: et1) XCTAssertEqual(parsedInteger10!["rating"]!.value as! Int, 10) XCTAssertEqual(parsedInteger10!["rating"]!.rawValue!, "ten") let et2 = EncodedTokens(tokensByWhitespace: ["fiftie", "one"], encodedTokensByWhitespaceIndex: [0, 0, 0, 1], encoded: []) let parsedInteger51 = try! parser.parse(tags: ["b_rating", "i_rating", "i_rating", "i_rating"], intent: metadata!.intents.filter({ $0.name == "rate.app" }).first!, encoder: encoder!, encodedTokens: et2) XCTAssertEqual(parsedInteger51!["rating"]!.value as! Int, 51) let et3 = EncodedTokens(tokensByWhitespace: ["fiftie", "six"], encodedTokensByWhitespaceIndex: [0, 0, 0, 1], encoded: []) let parsedIntegerNil = try! parser.parse(tags: ["b_rating", "i_rating", "i_rating", "i_rating"], intent: metadata!.intents.filter({ $0.name == "rate.app" }).first!, encoder: encoder!, encodedTokens: et3) XCTAssertNil(parsedIntegerNil!["rating"]!.value) let et4 = EncodedTokens(tokensByWhitespace: ["one", "million"], encodedTokensByWhitespaceIndex: [0, 1], encoded: []) let intent = metadata!.intents.filter({ $0.name == "i.i" }).first! let parsedIntegerMillion = try! parser.parse(tags: ["b_iMi", "i_iMi"], intent: intent, encoder: encoder!, encodedTokens: et4) XCTAssertEqual(parsedIntegerMillion!["iMi"]!.value as! Int, 1000000) } func testParseDigits() { let taggedInputPhoneNumeric = ["b_phone_number", "i_phone_number", "i_phone_number", "i_phone_number", "i_phone_number"] let et5 = EncodedTokens(tokensByWhitespace: ["4238341746"], encodedTokensByWhitespaceIndex: [0, 0, 0, 0, 0], encoded: []) let parsedDigitsNumeric = try! parser.parse(tags: taggedInputPhoneNumeric, intent: metadata!.intents.filter({ $0.name == "inform.phone_number" }).first!, encoder: encoder!, encodedTokens: et5) XCTAssertEqual(parsedDigitsNumeric!["phone_number"]!.value as! String, "4238341746") let taggedInputPhoneCardinal = ["b_phone_number", "i_phone_number", "i_phone_number", "i_phone_number", "i_phone_number", "i_phone_number", "i_phone_number", "i_phone_number", "i_phone_number", "i_phone_number"] let inputPhoneCardinal = ["4", "second", "three", "eighth", "three", "four", "one", "seven", "four", "six"] let et6 = EncodedTokens(tokensByWhitespace: inputPhoneCardinal, encodedTokensByWhitespaceIndex: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], encoded: []) let parsedDigitsCardinal = try! parser.parse(tags: taggedInputPhoneCardinal, intent: metadata!.intents.filter({ $0.name == "inform.phone_number" }).first!, encoder: encoder!, encodedTokens: et6) XCTAssertEqual(parsedDigitsCardinal!["phone_number"]!.value as! String, "4238341746") XCTAssertEqual(parsedDigitsCardinal!["phone_number"]!.rawValue!, inputPhoneCardinal.joined(separator: " ")) } func testParseEntity() { let taggedInputEntity = ["b_eponymous", "i_eponymous"] let et1 = EncodedTokens(tokensByWhitespace: ["dead", "beef"], encodedTokensByWhitespaceIndex: [0, 1], encoded: []) let parsedEntity = try! parser.parse(tags: taggedInputEntity, intent: metadata!.intents.filter({ $0.name == "identify" }).first!, encoder: encoder!, encodedTokens: et1) XCTAssertEqual(parsedEntity!["eponymous"]!.value as! String, "dead beef") let taggedInputEntityO = ["o", "b_eponymous", "i_eponymous", "o", "o", "b_eponymous", "o"] let etO = EncodedTokens(tokensByWhitespace: ["when", "dead", "beef", "appears", "in", "debug"], encodedTokensByWhitespaceIndex: [0, 1, 2, 3, 4, 5], encoded: []) let parsedEntityO = try! parser.parse(tags: taggedInputEntityO, intent: metadata!.intents.filter({ $0.name == "identify" }).first!, encoder: encoder!, encodedTokens: etO) XCTAssertEqual(parsedEntityO!["eponymous"]!.value as! String, "dead beef debug") } func testParseUnspecifiedSlot() { // Slots not declared by an intent but tagged by the model do not cause an error and are not returned to the caller let taggedInput = ["o", "b_eponymous"] let et = EncodedTokens(tokensByWhitespace: ["hey", "ma"], encodedTokensByWhitespaceIndex: [0, 1], encoded: []) let parsed = try! parser.parse(tags: taggedInput, intent: metadata!.intents.filter({ $0.name == "i.i" }).first!, encoder: encoder!, encodedTokens: et) XCTAssertNil(parsed!["iMi"]!.value) // Slots declared by an intent but not tagged by the model are returned to the caller in the output with a nil value let taggedInputEmpty = ["o", "o"] let parsedEmpty = try! parser.parse(tags: taggedInputEmpty, intent: metadata!.intents.filter({ $0.name == "i.i" }).first!, encoder: encoder!, encodedTokens: et) XCTAssertNil(parsedEmpty!["iMi"]!.value) } func createMetadata() -> String { return #""" { "intents": [ { "name": "request.lights.deactivate", "slots": [ { "name": "location", "type": "selset", "facets": "{\"selections\": [{\"name\": \"room\", \"aliases\": [\"kitchen\", \"bedroom\", \"washroom\"]}]}" } ] }, { "name": "rate.app", "slots": [ { "name": "rating", "type": "integer", "facets": "{\"range\": [1, 52]}" } ] }, { "name": "i.i", "slots": [ { "name": "iMi", "type": "integer", "facets": "{\"range\": [1, 1000000]}" } ] }, { "name": "inform.phone_number", "slots": [ { "name": "phone_number", "type": "digits", "facets": "{\"count\": 10}" } ] }, { "name": "identify", "slots": [ { "name": "eponymous", "type": "entity" } ] } ], "tags": [ "o", "b_rating", "i_rating", "b_iMi", "i_iMi", "b_location", "i_location", "b_phone_number", "i_phone_number", "b_eponymous", "i_eponymous" ] } """# } }
51.230769
219
0.590206
f801ca0ee6d0db15e52ec61d06444a7a98ea7207
6,240
import Foundation import Clibsodium public struct Utils {} extension Utils { public enum Base64Variant: CInt { case ORIGINAL = 1 case ORIGINAL_NO_PADDING = 3 case URLSAFE = 5 case URLSAFE_NO_PADDING = 7 } } extension Utils { /** Tries to effectively zero bytes in `data`, even if optimizations are being applied to the code. - Parameter data: The `Bytes` object to zero. */ public func zero(_ data: inout Bytes) { let count = data.count sodium_memzero(&data, count) } } extension Utils { /** Checks that two `Bytes` objects have the same content, without leaking information about the actual content of these objects. - Parameter b1: first object - Parameter b2: second object - Returns: `true` if the bytes in `b1` match the bytes in `b2`. Otherwise, it returns false. */ public func equals(_ b1: Bytes, _ b2: Bytes) -> Bool { guard b1.count == b2.count else { return false } return .SUCCESS == sodium_memcmp(b1, b2, b1.count).exitCode } /** Compares two `Bytes` objects without leaking information about the content of these objects. - Returns: `0` if the bytes in `b1` match the bytes in `b2`. `-1` if `b2` is less than `b1` (considered as little-endian values) and `1` if `b1` is less than `b2` (considered as little-endian values) */ public func compare(_ b1: Bytes, _ b2: Bytes) -> Int? { guard b1.count == b2.count else { return nil } return Int(sodium_compare(b1, b2, b1.count)) } } extension Utils { /** Converts bytes stored in `bin` into a hexadecimal string. - Parameter bin: The data to encode as hexdecimal. - Returns: The encoded hexdecimal string. */ public func bin2hex(_ bin: Bytes) -> String? { let hexBytesLen = bin.count * 2 + 1 var hexBytes = Bytes(count: hexBytesLen).map(Int8.init) guard sodium_bin2hex(&hexBytes, hexBytesLen, bin, bin.count) != nil else { return nil } return String(validatingUTF8: hexBytes) } /** Decodes a hexdecimal string, ignoring characters included for readability. - Parameter hex: The hexdecimal string to decode. - Parameter ignore: Optional string containing readability characters to ignore during decoding. - Returns: The decoded data. */ public func hex2bin(_ hex: String, ignore: String? = nil) -> Bytes? { let hexBytes = Bytes(hex.utf8) let hexBytesLen = hexBytes.count let binBytesCapacity = hexBytesLen / 2 var binBytes = Bytes(count: binBytesCapacity) var binBytesLen: size_t = 0 let ignore_nsstr = ignore.flatMap({ NSString(string: $0) }) let ignore_cstr = ignore_nsstr?.cString(using: String.Encoding.isoLatin1.rawValue) guard .SUCCESS == sodium_hex2bin( &binBytes, binBytesCapacity, hex, hexBytesLen, ignore_cstr, &binBytesLen, nil ).exitCode else { return nil } binBytes = binBytes[..<binBytesLen].bytes return binBytes } } extension Utils { /** Converts bytes stored in `bin` into a Base64 representation. - Parameter bin: The data to encode as Base64. - Parameter variant: the Base64 variant to use. By default: URLSAFE. - Returns: The encoded base64 string. */ public func bin2base64(_ bin: Bytes, variant: Base64Variant = .URLSAFE) -> String? { let b64BytesLen = sodium_base64_encoded_len(bin.count, variant.rawValue) var b64Bytes = Bytes(count: b64BytesLen).map(Int8.init) guard sodium_bin2base64(&b64Bytes, b64BytesLen, bin, bin.count, variant.rawValue) != nil else { return nil } return String(validatingUTF8: b64Bytes) } /* Decodes a Base64 string, ignoring characters included for readability. - Parameter b64: The Base64 string to decode. - Parameter ignore: Optional string containing readability characters to ignore during decoding. - Returns: The decoded data. */ public func base642bin(_ b64: String, variant: Base64Variant = .URLSAFE, ignore: String? = nil) -> Bytes? { let b64Bytes = Bytes(b64.utf8).map(Int8.init) let b64BytesLen = b64Bytes.count let binBytesCapacity = b64BytesLen * 3 / 4 + 1 var binBytes = Bytes(count: binBytesCapacity) var binBytesLen: size_t = 0 let ignore_nsstr = ignore.flatMap({ NSString(string: $0) }) let ignore_cstr = ignore_nsstr?.cString(using: String.Encoding.isoLatin1.rawValue) guard .SUCCESS == sodium_base642bin( &binBytes, binBytesCapacity, b64Bytes, b64BytesLen, ignore_cstr, &binBytesLen, nil, variant.rawValue ).exitCode else { return nil } binBytes = binBytes[..<binBytesLen].bytes return binBytes } } extension Utils { /* Adds padding to `data` so that its length becomes a multiple of `blockSize` - Parameter data: input/output buffer, will be modified in-place - Parameter blocksize: the block size */ public func pad(bytes: inout Bytes, blockSize: Int) -> ()? { let bytesCount = bytes.count bytes += Bytes(count: blockSize) var paddedLen: size_t = 0 guard .SUCCESS == sodium_pad( &paddedLen, &bytes, bytesCount, blockSize, bytesCount + blockSize ).exitCode else { return nil } bytes = bytes[..<paddedLen].bytes return () } /* Removes padding from `data` to restore its original size - Parameter data: input/output buffer, will be modified in-place - Parameter blocksize: the block size */ public func unpad(bytes: inout Bytes, blockSize: Int) -> ()? { var unpaddedLen: size_t = 0 let bytesLen = bytes.count guard .SUCCESS == sodium_unpad( &unpaddedLen, bytes, bytesLen, blockSize ).exitCode else { return nil } bytes = bytes[..<unpaddedLen].bytes return () } }
31.044776
111
0.623237
293795c6d2d0c9de3603a508ae904096fb2ee386
1,032
// // Question.swift // Questify // // Created by Coskun Appwox on 17.03.2019. // Copyright © 2019 Coskun Appwox. All rights reserved. // import Foundation import SwiftyJSON struct Question { let id:Int var title:String = "" var answers:[Answer]! = [Answer]() } extension Question { init() { self.id = 0 } init?(json:JSON) { guard json.count > 0 else {return nil} id = json["id"].intValue title = json["title"].stringValue answers = json["answers"].arrayValue.map { Answer(json: $0) }.compactMap { $0 } } } struct Answer { let id:Int var title:String = "" var isSelected:Bool = false var isCorrect:Bool = false } extension Answer { init() { self.id = 0 } init?(json:JSON) { guard json.count > 0 else {return nil} id = json["id"].intValue title = json["title"].stringValue isSelected = json["isSelected"].boolValue isCorrect = json["isCorrect"].boolValue } }
21.5
87
0.575581
1cffb99743007348566dbffacb19a3c9e0e5e8e9
713
// // AnswerRecordTableViewCell.swift // Meow // // Created by 林武威 on 2017/7/13. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit class AnswerRecordTableViewCell: UITableViewCell { @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var nicknameLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! func configure(model: AnswerSummary) { if let url = model.profile.avatar { avatarImageView.af_setImage(withURL: url) } nicknameLabel.text = model.profile.nickname contentLabel.text = model.content titleLabel.text = model.questionTitle } }
24.586207
53
0.673212
1657b39e8c0d01fb460e0744ee189f25a751ac2d
2,848
// // SpriteLegendViewController.swift // PokemonViewer // // Created by Alexandr Goncharov on 09.11.2020. // import UIKit import UITeststingSupport final class SpriteLegendViewController: UIViewController { typealias SpriteLegendCell = UICollectionViewContainerCell<TitledValueView> @available(*, unavailable, message: "Use `init(viewModel:)` instead") required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(viewModel: SpriteLegendViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Constants.backgroundColor view.accessibilityIdentifier = AccessibilityId.SpriteLegend.screen collectionView.backgroundColor = Constants.backgroundColor view.tintColor = Constants.tintColor title = viewModel.title view.addSubview(collectionView) collectionView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ collectionView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor), collectionView.topAnchor.constraint(equalTo: view.readableContentGuide.topAnchor), collectionView.bottomAnchor.constraint(equalTo: view.readableContentGuide.bottomAnchor) ]) collectionView.register(SpriteLegendCell.self) collectionView.dataSource = self collectionView.reloadData() } private lazy var collectionLayout = PokemonListCollectionViewLayout() private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionLayout) private let viewModel: SpriteLegendViewModel private enum Constants { static let tintColor = Colors.accent static let backgroundColor = Colors.background static let itemStyle = TitledValueView.Style(titleColor: Colors.primaryText, titleFont: Fonts.header, valueColor: Colors.secondaryText, valueFont: Fonts.title) static let itemHeight: CGFloat = 50 } } extension SpriteLegendViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { viewModel.items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = viewModel.items[indexPath.row] let cell: SpriteLegendCell = collectionView.dequeue(forIndexPath: indexPath) cell.view.apply(style: Constants.itemStyle) cell.view.set(title: item.title, value: item.value) return cell } }
36.987013
106
0.734199
26fbfa2dc4103061e5a3025b0b6bd9402628bf5c
626
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import Foundation /// A formatter that passthrough their textual representations. public struct PassthroughTextFieldFormatter: TextFieldFormatter { private let mask: Mask? public init(_ mask: Mask? = nil) { self.mask = mask } public func string(from value: String) -> String { mask?.string(from: value) ?? value } public func value(from string: String) -> String { mask?.value(from: string) ?? string } public func shouldChange(to string: String) -> Bool { true } }
21.586207
65
0.64377
e85231bda1269b799b43bcbf81b1b3ea83be64cc
8,160
// // ZHRefreshFooter.swift // apc // // Created by ovfun on 16/6/2. // Copyright © 2016年 @天意. All rights reserved. // import Foundation import RxSwift import RxCocoa public class ZHRefreshFooter: UIControl { fileprivate var myScrollView: UIScrollView! fileprivate var contentInset: UIEdgeInsets! private lazy var refreshView = UIActivityIndicatorView(style: .white) private var nomoreView: UIView? private var isShowNomore = false var disBag = DisposeBag() var hasContent: Bool { return myScrollView.contentSize.height > 44 } fileprivate(set) var refreshState: ZHRefreshState = .stopped { willSet{ if refreshState == .dragging && newValue == .animatingBounce { statAnimating() } else if newValue == .loading { beginRefreshing() } else if newValue == .animatingToStopped { stopAnimation() } else if newValue == .stopped { } } } init () { super.init(frame: CGRect.zero) self.addSubview(refreshView) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) guard let v = newSuperview as? UIScrollView else {return} self.backgroundColor = UIColor.clear self.myScrollView = v self.contentInset = v.contentInset addObserve() } public override func layoutSubviews() { super.layoutSubviews() guard refreshState != .animatingBounce else {return} let y = max(myScrollView.contentSize.height, 0) self.frame = CGRect(x: 0, y: y, width: myScrollView.frame.size.width, height: LoadingViewSize) self.refreshView.color = UIColor.black self.refreshView.frame = CGRect(x: 0, y: (self.frame.size.height - refreshView.frame.size.height) / 2, width: UIScreen.main.bounds.size.width, height: 44) } public func showNomore() { guard !isShowNomore else {return} isShowNomore = true print(myScrollView.contentInset, myScrollView.contentSize, myScrollView.contentOffset) self.nomoreView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)) self.nomoreView?.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0) self.addSubview(nomoreView!) let lv = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)) lv.font = UIFont.systemFont(ofSize: 14) lv.text = "没有更多" lv.textAlignment = .center lv.textColor = #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1) self.nomoreView?.addSubview(lv) self.myScrollView.contentInset.bottom += self.frame.size.height } public func hiddenNomore() { guard isShowNomore else {return} isShowNomore = false self.nomoreView?.removeFromSuperview() myScrollView.contentInset.bottom = contentInset.bottom } public func statAnimating() { guard !isHidden, !isShowNomore else {return} refreshView.startAnimating() UIView.animate(withDuration: 0.3, delay: 0, options: [], animations: { [weak self] in self?.myScrollView.contentInset.bottom += self?.frame.size.height ?? 0 }) { [weak self] _ in self?.refreshState = .loading } } public func stopAnimation() { UIView.animate(withDuration: 0.3, delay: 0, options: [], animations: { [weak self] in self?.myScrollView.contentInset.bottom = self?.contentInset.bottom ?? 0 }) { [weak self] _ in self?.refreshView.stopAnimating() self?.refreshState = .stopped } } public func beginRefreshing() { sendActions(for: .valueChanged) } public func endRefreshing() { if refreshState == .stopped {return} refreshState = .animatingToStopped } public override var isHidden: Bool { willSet{ if myScrollView.contentInset == contentInset { return } if !isHidden && newValue && refreshState == .animatingToStopped { refreshState = .stopped myScrollView.contentInset.bottom = self.contentInset.bottom }else if isHidden && !newValue && refreshState == .animatingToStopped { refreshState = .stopped myScrollView.contentInset.bottom += self.frame.size.height self.frame = CGRect(origin: CGPoint(x: self.frame.origin.x, y: myScrollView.contentSize.height), size: self.frame.size) }else { refreshState = .stopped myScrollView.contentInset.bottom = contentInset.bottom } } } } extension ZHRefreshFooter { public func addObserve() { self.myScrollView .rx.observe(CGPoint.self, "contentOffset") .distinctUntilChanged() .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] _ in self?.observeContentOfSet()}) .disposed(by: disBag) self.myScrollView .rx.observe(CGRect.self, "frame") .subscribe(onNext: { [weak self] _ in self?.observeFrame() }) .disposed(by: disBag) self.myScrollView .rx.observe(UIGestureRecognizer.State.self, "panGestureRecognizer.state") .subscribe(onNext: { [weak self] _ in self?.observePanGestureRecognizer() }) .disposed(by: disBag) } public func observeContentOfSet() { scrollViewDidChangeContentOffset(myScrollView.isDragging) layoutSubviews() } public func observePanGestureRecognizer() { let gestureState = myScrollView.panGestureRecognizer.state if gestureState.isAnyOf([.ended, .cancelled, .failed]) { scrollViewDidChangeContentOffset(false) } } public func observeFrame() { layoutSubviews() } private func scrollViewDidChangeContentOffset(_ dragging: Bool) { if refreshState == .stopped && dragging { refreshState = .dragging } else if refreshState == .dragging && dragging == false { if myScrollView.contentInset.top + myScrollView.contentSize.height <= myScrollView.frame.size.height {//不够一屏 guard self.myScrollView.contentOffset.y >= -self.myScrollView.contentInset.top else { refreshState = .stopped return } refreshState = .animatingBounce }else {//超出一屏 guard myScrollView.contentOffset.y >= myScrollView.contentSize.height - myScrollView.frame.size.height + myScrollView.contentInset.bottom else { refreshState = .stopped return } refreshState = .animatingBounce } } else if refreshState.isAnyOf([.dragging, .stopped]) { // let pullProgress: CGFloat = offsetY / MinOffsetToPull // print("progress:",pullProgress) } } } extension UIGestureRecognizer.State { func isAnyOf(_ values: [UIGestureRecognizer.State]) -> Bool { return values.contains(where: { $0 == self }) } }
32.125984
162
0.564583
4a4af78c5bdaedc7f9704c61c196440b9f40ec6f
3,753
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension TVDB.Authentication { /** Returns a session token to be included in the rest of the requests. Note that API key authentication is required for all subsequent requests and user auth is required for routes in the `User` section */ public enum PostLogin { public static let service = APIService<Response>(id: "postLogin", tag: "Authentication", method: "POST", path: "/login", hasBody: true) public final class Request: APIRequest<Response> { public var body: TVDBAuth public init(body: TVDBAuth) { self.body = body super.init(service: PostLogin.service) { let jsonEncoder = JSONEncoder() return try jsonEncoder.encode(body) } } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = TVDBToken /** Returns a JWT token for use with the rest of the API routes */ case status200(TVDBToken) /** Invalid credentials and/or API token */ case status401(TVDBNotAuthorized) public var success: TVDBToken? { switch self { case .status200(let response): return response default: return nil } } public var failure: TVDBNotAuthorized? { switch self { case .status401(let response): return response default: return nil } } /// either success or failure value. Success is anything in the 200..<300 status code range public var responseResult: APIResponseResult<TVDBToken, TVDBNotAuthorized> { if let successValue = success { return .success(successValue) } else if let failureValue = failure { return .failure(failureValue) } else { fatalError("Response does not have success or failure response") } } public var response: Any { switch self { case .status200(let response): return response case .status401(let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 case .status401: return 401 } } public var successful: Bool { switch self { case .status200: return true case .status401: return false } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode(TVDBToken.self, from: data)) case 401: self = try .status401(decoder.decode(TVDBNotAuthorized.self, from: data)) default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
35.40566
210
0.535039
21081c0d1c889088938ae942433bfddf41d92541
1,746
// // Realm+Extension.swift // AAShare // // Created by Chen Tom on 28/12/2016. // Copyright © 2016 Chen Zheng. All rights reserved. // import Foundation import RealmSwift extension Object { //Convert to Dictionary from Realm object func realmToDictionary() -> NSDictionary { let properties = self.objectSchema.properties.map { $0.name } let dictionary = self.dictionaryWithValues(forKeys: properties) let mutabledic = NSMutableDictionary() mutabledic.setValuesForKeys(dictionary) for prop in self.objectSchema.properties as [Property]! { // convert Date to String, because JSON parse will crash if type is 'Date' if let nestedObject = self[prop.name] as? Date { mutabledic.setValue(nestedObject.description, forKey: prop.name) } // find lists else if let nestedObject = self[prop.name] as? Object { mutabledic.setValue(nestedObject.realmToDictionary(), forKey: prop.name) } else if let nestedListObject = self[prop.name] as? ListBase { var objects = [AnyObject]() for index in 0..<nestedListObject._rlmArray.count { let object = nestedListObject._rlmArray[index] as AnyObject objects.append(object.realmToDictionary()) } mutabledic.setObject(objects, forKey: prop.name as NSCopying) } } return mutabledic } } extension Results { func realmToDictionary() -> Array<NSDictionary> { var array = Array<NSDictionary>() for obj in self { array.append(obj.realmToDictionary()) } return array } }
34.92
88
0.612257
169a592fcfa9078b1436d0a3d52d80cf65c55ebd
321
// // Planet.swift // DAOExample // // Created by n-borzenko on 18.02.17. // Copyright © 2017 nborzenko. All rights reserved. // import Foundation import DAO class Planet: BaseEntity { var id: Int var name: String init(id: Int, name: String) { self.id = id self.name = name } }
15.285714
52
0.598131
f4014f47957887b75cadebade7912e982a517fa7
323
// // SwlCardDescription.swift // WalletBase // // Created by Mark Jerde on 12/18/21. // import Foundation extension SwlDatabase { /// An swl database card description. struct CardDescription { /// The ID of this card. let id: SwlID /// The encrypted description of this card. let description: [UInt8]? } }
17
45
0.684211
2897205fd82dce59e74bdc086b2a42a0064ca9f2
2,595
// // This file is autogenerated // // // Constants.swift // Keybase // Copyright © 2016 Keybase. All rights reserved. // import Foundation import SwiftyJSON // // Constants // public enum StatusCode: Int { case scok = 0 case scinputerror = 100 case scloginrequired = 201 case scbadsession = 202 case scbadloginusernotfound = 203 case scbadloginpassword = 204 case scnotfound = 205 case scthrottlecontrol = 210 case scdeleted = 216 case scgeneric = 218 case scalreadyloggedin = 235 case scexists = 230 case sccanceled = 237 case scinputcanceled = 239 case screloginrequired = 274 case scresolutionfailed = 275 case scprofilenotpublic = 276 case scidentifyfailed = 277 case sctrackingbroke = 278 case scwrongcryptoformat = 279 case scdecryptionerror = 280 case scinvalidaddress = 281 case scbademail = 472 case scbadsignupusernametaken = 701 case scbadinvitationcode = 707 case scmissingresult = 801 case sckeynotfound = 901 case sckeyinuse = 907 case sckeybadgen = 913 case sckeynosecret = 914 case sckeybaduids = 915 case sckeynoactive = 916 case sckeynosig = 917 case sckeybadsig = 918 case sckeybadeldest = 919 case sckeynoeldest = 920 case sckeyduplicateupdate = 921 case scsibkeyalreadyexists = 922 case scdecryptionkeynotfound = 924 case sckeynopgpencryption = 927 case sckeynonaclencryption = 928 case sckeysyncedpgpnotfound = 929 case sckeynomatchinggpg = 930 case sckeyrevoked = 931 case scbadtracksession = 1301 case scdevicebadname = 1404 case scdevicenameinuse = 1408 case scdevicenotfound = 1409 case scdevicemismatch = 1410 case scdevicerequired = 1411 case scdeviceprevprovisioned = 1413 case scdevicenoprovision = 1414 case scstreamexists = 1501 case scstreamnotfound = 1502 case scstreamwrongkind = 1503 case scstreameof = 1504 case scgenericapierror = 1600 case scapinetworkerror = 1601 case sctimeout = 1602 case scprooferror = 1701 case scidentificationexpired = 1702 case scselfnotfound = 1703 case scbadkexphrase = 1704 case scnouidelegation = 1705 case scnoui = 1706 case scgpgunavailable = 1707 case scinvalidversionerror = 1800 case scoldversionerror = 1801 case scinvalidlocationerror = 1802 case scservicestatuserror = 1803 case scinstallerror = 1804 case scchatinternal = 2500 case scchatratelimit = 2501 case scchatconvexists = 2502 case scchatunknowntlfid = 2503 case scchatnotinconv = 2504 case scchatbadmsg = 2505 case scchatbroadcast = 2506 case scchatalreadysuperseded = 2507 case scchatalreadydeleted = 2508 case scchattlffinalized = 2509 case scchatcollision = 2510 }
24.951923
50
0.782274
50fac22cd0c75a87805d4e72f36dbaf0058dec4a
778
// Gymfile.swift // Copyright (c) 2022 FastlaneTools // This class is automatically included in FastlaneRunner during build // This autogenerated file will be overwritten or replaced during build time, or when you initialize `gym` // // ** NOTE ** // This file is provided by fastlane and WILL be overwritten in future updates // If you want to add extra functionality to this project, create a new file in a // new group so that it won't be marked for upgrade // public class Gymfile: GymfileProtocol { // If you want to enable `gym`, run `fastlane gym init` // After, this file will be replaced with a custom implementation that contains values you supplied // during the `init` process, and you won't see this message } // Generated with fastlane 2.200.0
37.047619
106
0.735219
ffbda9e0e0131dcc8f673ca168329cfc335de159
1,984
// // RootTabBarController.swift // TranslatorKing // // Created by skillist on 2022/01/24. // import UIKit class RootTabController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() layout() setupTabBars() } } private extension RootTabController { func layout() { view.backgroundColor = .systemBackground } func setupTabBars() { //번역VC View let translatorView = TranslatorView() translatorView.bind(TranslatorViewModel()) //ViewModel 바인딩 let translatorViewController = UINavigationController(rootViewController: translatorView) translatorViewController.tabBarItem = UITabBarItem( title: "translator_title".localize, image: UIImage(systemName: "doc.plaintext"), selectedImage: UIImage(systemName: "doc.plaintext.fill") ) //기록VC View let historyView = HistoryView() historyView.bind(HistoryViewModel()) //ViewModel 바인딩 let historyViewController = UINavigationController(rootViewController: historyView) historyViewController.tabBarItem = UITabBarItem( title: "history_title".localize, image: UIImage(systemName: "clock"), selectedImage: UIImage(systemName: "clock.fill") ) //보관함VC View let bookmarkView = BookMarkView() bookmarkView.bind(BookMarkViewModel()) //ViewModel 바인딩 let bookmarkViewController = UINavigationController(rootViewController: bookmarkView) bookmarkViewController.tabBarItem = UITabBarItem( title: "bookmark_title".localize, image: UIImage(systemName: "square.and.arrow.down"), selectedImage: UIImage(systemName: "square.and.arrow.down.fill") ) viewControllers = [ translatorViewController, historyViewController, bookmarkViewController ] } }
30.523077
97
0.645665
896e90b4fec362c77456743fecff79051008e9c5
751
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "TPInAppReceipt", platforms: [.macOS(.v10_12), .iOS(.v10), .tvOS(.v10), .watchOS("6.2")], products: [ .library(name: "TPInAppReceipt", targets: ["TPInAppReceipt"]), ], dependencies: [ .package(url: "https://github.com/tikhop/ASN1Swift", .upToNextMajor(from: "1.0.0")) ], targets: [ .target( name: "TPInAppReceipt", dependencies: ["ASN1Swift"], path: "Sources", exclude: ["Bundle+Extension.swift"], resources: [.process("AppleIncRootCertificate.cer"), .process("StoreKitTestCertificate.cer")] ), .testTarget( name: "TPInAppReceiptTests", dependencies: ["TPInAppReceipt"]) ] )
22.757576
96
0.624501
e25ccd88763314e060c5a4cfc29c9616fee88478
364
// // Separator.swift // SGUVIndex // // Created by Henry Javier Serrano Echeverria on 25/12/20. // import SwiftUI struct Separator: View { var body: some View { Rectangle() // .foregroundColor(Color.black) .frame(height: 2, alignment: .center) .padding(.leading, 16) .padding(.trailing, 16) } }
19.157895
59
0.574176
9c3327284ecc74355259d27d8606b3ca97ae2192
4,365
// // UIViewController+Extension.swift // SwiftBasics // // Created by 侯伟 on 17/1/11. // Copyright © 2017年 侯伟. All rights reserved. // import Foundation import UIKit // MARK: Top view controller extension UIViewController { /// 获取当前显示的 View Controller public static var topViewController: UIViewController? { var vc = UIApplication.shared.keyWindow?.rootViewController while true { if let nc = vc as? UINavigationController { vc = nc.visibleViewController } else if let tbc = vc as? UITabBarController { if let svc = tbc.selectedViewController { vc = svc } else { break } } else if let pvc = vc?.presentedViewController { vc = pvc } else { break } } return vc } } // MARK: 导航 extension UIViewController { /// 显示 view controller(根据当前上下文,自动选择 push 或 present 方式) public static func showViewController(_ controller: UIViewController, animated flag: Bool) { let topViewController = UIViewController.topViewController if let navigationController = topViewController as? UINavigationController { navigationController.pushViewController(controller, animated: flag) } else if let navigationController = topViewController?.navigationController { navigationController.pushViewController(controller, animated: flag) } else { topViewController?.present(controller, animated: flag, completion: nil) } } /// 显示 view controller(根据当前上下文,自动选择 push 或 present 方式) public func showViewControllerAnimated(_ animated: Bool) { UIViewController.showViewController(self, animated: animated) } /// 关闭 view controller(根据当前上下文,自动选择 pop 或 dismiss 方式) public static func closeViewControllerAnimated(_ animated: Bool) { UIViewController.topViewController?.closeViewControllerAnimated(animated) } /// 关闭 view controller(根据当前上下文,自动选择 pop 或 dismiss 方式) public func closeViewControllerAnimated(_ animated: Bool) { if let controller = navigationController, controller.viewControllers.count > 1 { controller.popViewController(animated: animated) } else { dismiss(animated: animated, completion: nil) } } } // MARK: NavigationBar extension UIViewController { fileprivate struct AssociatedKey { static var navigationBarAlpha: CGFloat = 0 } var navigationBarAlpha: CGFloat { get { return objc_getAssociatedObject(self, &AssociatedKey.navigationBarAlpha) as? CGFloat ?? 1 } set { self.setNavigationBarAlpha(newValue, animated: false) } } /// 设置内容透明度 func setNavigationBarAlpha(_ alpha: CGFloat, animated: Bool) { objc_setAssociatedObject(self, &AssociatedKey.navigationBarAlpha, alpha, .OBJC_ASSOCIATION_RETAIN) self.updateNavigationBarAlpha(alpha, animated: animated) } /// 根据内容透明度更新UI效果 func updateNavigationBarAlpha(_ alpha: CGFloat? = nil, animated: Bool) { guard let navigationBar = self.navigationController?.navigationBar else {return} if animated == true { UIView.beginAnimations(nil, context: nil) } let newAlpha = alpha ?? self.navigationBarAlpha for subview in navigationBar.subviews { let className = String(describing: subview.classForCoder) if className == "_UINavigationBarBackground" || className == "UINavigationItemView" { subview.alpha = newAlpha } } if animated == true { UIView.commitAnimations() } } /// 显示/隐藏 NavigationBar public func setNavigationBarHidden(_ hidden: Bool, animated: Bool) { self.navigationController?.isNavigationBarHidden = hidden } } // MARK: Storyboard extension UIViewController { /// 从 Storyboard 中获取 ViewController public static func viewControllerWithIdentifier(_ id: String, storyboardName name: String) -> UIViewController { let storyboard = UIStoryboard(name: name, bundle: nil) return storyboard.instantiateViewController(withIdentifier: id) } }
33.068182
116
0.645819
9bb80d81c2bfabaf7f1117252a62690d7fbe992c
867
// // ISSLocation.swift // iSSLocation // // Created by Aminjoni Abdullozoda on 7/19/18. // Copyright © 2018 Aminjoni Abdullozoda. All rights reserved. // import Foundation struct ISSLocation : Codable { let message: String let issPosition: IssPosition let timestamp: Int enum CodingKeys: String, CodingKey { case message case issPosition = "iss_position" case timestamp } //MARK: Just for showing in Console func getMessageLocation() -> String { return "Message :\(message), Lat :\(issPosition.latitude), Lon: \(issPosition.longitude), TimeStamp: \(timestamp))" } //MARK: Unix to UTC func getUTCTime() -> Date { return Date(timeIntervalSince1970: TimeInterval(timestamp)) } } struct IssPosition: Codable { let latitude, longitude: String }
21.146341
124
0.643599
75abf780d0b715f15fee29e2861c3bcdfefd6414
625
// // Extensions.swift // Cocktography // // Created by Jordan Koch on 9/16/18. // import Foundation extension String { func base64Encoded() -> String? { if let data = self.data(using: .utf8) { return data.base64EncodedString() } return nil } func base64Decoded() -> String? { if let data = Data(base64Encoded: self) { return String(data: data, encoding: .utf8) } return nil } } extension String { var isNumber: Bool { return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil } }
20.16129
93
0.5824
755149af2f6de01647ccf8498354e60d37e9af99
552
// // IMMessageProtocol.swift // LMPNPBox // // Created by Liam on 2020/1/19. // Copyright © 2020 Liam. All rights reserved. // import UIKit /// 消息包通用协议 public protocol IMMessageProtocol: Codable { /// destId /// TIM 会话Id /// 单聊类型(C2C) :为对方 userID; /// 群组类型(GROUP) :为群组 groupId; /// 系统类型(SYSTEM):为 @"" /// NIM 会话Id /// 如果当前session为team,则sessionId为teamId,如果是P2P则为对方帐号 accid /// Aliyun Topic var destId: String? { set get } /// 消息包内容 var content: String? { set get } }
19.714286
65
0.574275
db712f6d6557c0389be2170fef99ba0645e2db15
3,444
// // ViewController.swift // 31 -- TheHitList -- John Holsapple // // Created by John Holsapple on 7/27/15. // Copyright (c) 2015 John Holsapple -- The Iron Yard. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController, UITableViewDataSource { var people = [NSManagedObject]() @IBOutlet weak var tableView: UITableView! @IBAction func addName(sender: AnyObject) { let alert = UIAlertController(title: "New name", message: "Add a new name", preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Save", style: .Default) { (action: UIAlertAction) -> Void in let textField = alert.textFields![0] self.saveName(textField.text) self.tableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction) -> Void in } alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in } alert.addAction(saveAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } func saveName(name: String) { // 1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! // 2 let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext) let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) // 3 person.setValue(name, forKey: "name") // 4 var error: NSError? do { try managedContext.save() } catch let error1 as NSError { error = error1 print("Could not save \(error), \(error?.userInfo)") } //5 people.append(person) } override func viewDidLoad() { super.viewDidLoad() title = "\"The List\"" tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // 1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! // 2 let fetchRequest = NSFetchRequest(entityName:"Person") // 3 let error: NSError? let fetchedResults = managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject] if let results = fetchedResults { people = results } else { print("Could not fetch \(error), \(error!.userInfo)") } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell let person = people[indexPath.row] cell.textLabel!.text = person.valueForKey("name") as? String return cell } }
29.689655
111
0.618467
3965cc84dd4a7c5a045a9bafab83b74f074221fa
2,025
// // UIImageExt.swift // NIOFD // // Created by Teng Wang 王腾 on 2020/1/8. // Copyright © 2020 Teng Wang 王腾. All rights reserved. // import UIKit public extension SoSwiftHelperWrapper where Core == UIImage { /// Create and return a 1x1 point size image with the given color. /// - Parameter color: The color. /// - Returns: The UIImage. static func make(_ color: UIColor) -> UIImage? { UIImage.so.make(color, size: CGSize(width: 1, height: 1)) } /// Create and return a pure color image with the given color and size. /// - Parameters: /// - color: The color. /// - size: New image's type. /// - Returns: The UIImage. static func make(_ color: UIColor, size: CGSize) -> UIImage? { if (size.width <= 0 || size.height <= 0) { return nil } let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0); guard let context = UIGraphicsGetCurrentContext() else { return nil } context.setFillColor(color.cgColor); context.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } /// Returns a new image which is cropped from this image. /// - Parameter toRect: Image's inner rect. /// - Returns: The new image, or nil if an error occurs. func crop(toRect: CGRect) -> UIImage? { var rect = toRect rect.origin.x *= base.scale rect.origin.y *= base.scale rect.size.width *= base.scale rect.size.height *= base.scale guard rect.size.width > 0, rect.size.height > 0 else { return nil } guard let cgImage = base.cgImage, let imageRef = cgImage.cropping(to: rect) else { return nil } let image = UIImage(cgImage: imageRef, scale: base.scale, orientation: base.imageOrientation) return image } }
32.66129
101
0.605926
b9e7b46b7fd07340103c074dad67e9f3859d58c1
145
// Copyright © 2021 Yurii Lysytsia. All rights reserved. import XCTest @testable import AirKit final class UIWindowTests: XCTestCase { }
16.111111
57
0.744828
cc872faea7d935ed9a7468dcf40ecf11b74383a3
4,935
import UIKit import MiniApp class ViewController: UITableViewController { var decodeResponse: [MiniAppInfo]? var currentMiniAppInfo: MiniAppInfo? var config: MiniAppSdkConfig? override func viewDidLoad() { super.viewDidLoad() fetchAppList() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) config = Config.getCurrent() } func fetchAppList() { showProgressIndicator { MiniApp.shared(with: self.config).list { (result) in DispatchQueue.main.async { self.refreshControl?.endRefreshing() } switch result { case .success(let responseData): DispatchQueue.main.async { self.decodeResponse = responseData self.tableView.reloadData() self.dismissProgressIndicator() } case .failure(let error): print(error.localizedDescription) self.displayAlert(title: NSLocalizedString("error_title", comment: ""), message: NSLocalizedString("error_list_message", comment: ""), dismissController: false) } } } } func fetchAppInfo(for miniAppID: String) { self.showProgressIndicator { MiniApp.shared(with: self.config).info(miniAppId: miniAppID) { (result) in self.dismissProgressIndicator { switch result { case .success(let responseData): self.currentMiniAppInfo = responseData self.performSegue(withIdentifier: "DisplayMiniApp", sender: nil) case .failure(let error): print(error.localizedDescription) self.displayAlert( title: NSLocalizedString("error_title", comment: ""), message: NSLocalizedString("error_single_message", comment: ""), dismissController: false) } } } } } @IBAction func refreshList(_ sender: UIRefreshControl) { fetchAppList() } @IBAction func actionShowMiniAppById() { self.displayTextFieldAlert(title: NSLocalizedString("input_miniapp_title", comment: "")) { (_, textField) in self.dismiss(animated: true) { if let textField = textField, let miniAppID = textField.text, miniAppID.count > 0 { self.fetchAppInfo(for: miniAppID) } else { self.displayAlert( title: NSLocalizedString("error_title", comment: ""), message: NSLocalizedString("error_incorrect_appid_message", comment: ""), dismissController: false) } } } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return decodeResponse?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MiniAppCell", for: indexPath) let miniAppDetail = self.decodeResponse?[indexPath.row] cell.textLabel?.text = miniAppDetail?.displayName cell.imageView?.image = UIImage(named: "image_placeholder") cell.imageView?.loadImageURL(url: miniAppDetail!.icon) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "DisplayMiniApp" { if let indexPath = self.tableView.indexPathForSelectedRow?.row { currentMiniAppInfo = decodeResponse?[indexPath] } guard let miniAppInfo = self.currentMiniAppInfo else { self.displayAlert(title: NSLocalizedString("error_title", comment: ""), message: NSLocalizedString("error_miniapp_message", comment: ""), dismissController: false) return } let displayController = segue.destination as? DisplayController displayController?.miniAppInfo = miniAppInfo self.currentMiniAppInfo = nil } } } extension UIImageView { func loadImageURL(url: URL) { DispatchQueue.global().async { [weak self] in if let data = try? Data(contentsOf: url) { if let image = UIImage(data: data) { DispatchQueue.main.async { self?.image = image } } } } } }
38.255814
180
0.572239
9152d3851cd075781b59106247e2de5ca6990517
1,075
//: [DispatchWorkItems](@previous) /*: # Block Operations The BlockOperation class is a concrete subclass of Operation that manages the concurrent execution of one or more blocks on the default global queue but there's a catch. Execution blocks will run concurrently, but BlockOperation itself is not actually concurrent, it's serial and we can see that by calling BlockOperation().isConcurrent so the calling thread will be stuck until all the execution blocks finish their work. */ import Foundation let blockOperation = BlockOperation() for index in 0 ..< 4 { blockOperation.addExecutionBlock { Thread.sleep(forTimeInterval: TimeInterval(index)) print("Thread slept for \(index) seconds") } } blockOperation.completionBlock = { print("Thread woke up") } blockOperation.start() print("Block Operation is serial so this line will be executed after blockOperation ends.") //: So, if you want your operation to be fully concurrent, you must implement the appropriate functionality in an Operation's subclass. //: [Operation Queues](@next)
41.346154
423
0.76186
9b56e063b6944b6a251ab1d375d750a4cb9aba57
7,181
// // Entitlements.swift // AirLockSDK // // Created by Gil Fuchs on 12/02/2019. // import Foundation @objcMembers class Entitlements: NSObject,NSCoding,FeaturesMangement { var entitlementsDict:[String:Entitlement] override init() { entitlementsDict = [:] super.init() } init(other:Entitlements) { entitlementsDict = [:] for (name,entitlement) in other.entitlementsDict { entitlementsDict[name] = entitlement.cloneEntitlement() } super.init() setEntitlementRefernces() } init(featuresDict:[String:Feature]) { entitlementsDict = [:] super.init() for (name,feature) in featuresDict { if let entitlement = feature as? Entitlement { entitlementsDict[name] = entitlement } } setEntitlementRefernces() } func getEntitlement(name:String) -> Entitlement { if let retEntitlement = entitlementsDict[name.lowercased()] { return retEntitlement } else { let e = Entitlement(type:.ENTITLEMENT,uniqueId:"",name:name,source:Source.MISSING) e.trace = "entitlement \(name) not found" return e } } public required init?(coder aDecoder: NSCoder) { entitlementsDict = aDecoder.decodeObject(forKey:ENTITLEMENTS_PROP) as? [String:Entitlement] ?? [:] } public func encode(with aCoder: NSCoder) { aCoder.encode(entitlementsDict,forKey:ENTITLEMENTS_PROP) } deinit { for (_,e) in entitlementsDict { e.parent = nil } } func clone() -> Entitlements { return Entitlements(other:self) } func setEntitlementRefernces() { for (_,entitlement) in entitlementsDict { entitlement.parent = entitlementsDict[entitlement.parentName.lowercased()] entitlement.children.removeAll() for childName in entitlement.childrenNames { if let childEntitlement:Entitlement = entitlementsDict[childName.lowercased()] as? Entitlement { entitlement.children.append(childEntitlement) } else { print("Airlock child entitlement \(childName) not found") } } } } func addEntitlement(parentName:String?,newEntitlement:Entitlement) { if let parentName = parentName { if var parent = entitlementsDict[parentName.lowercased()] as? Entitlement { parent.children.append(newEntitlement) newEntitlement.parent = parent } else { print("addEntitlement failed parentName:\(parentName) not found") return } } else { //ROOT newEntitlement.parent = nil } entitlementsDict[newEntitlement.name.lowercased()] = newEntitlement } func getPurchasedEntitlements(_ purchasedproductIds:Set<String>) -> Set<String> { guard !purchasedproductIds.isEmpty else { return [] } var purchasedEntitlements:Set<String> = [] for (name,entitlement) in entitlementsDict { if entitlement.type != .ENTITLEMENT { continue } if !purchasedproductIds.isDisjoint(with:entitlement.productIdsSet) { var includedEntitlements:Set<String> = [] getPurchasedEntitlement(entitlement:entitlement,includedEntitlements:&includedEntitlements) for eName in includedEntitlements { purchasedEntitlements.insert(eName) } } } return purchasedEntitlements } func getPurchasedEntitlement(entitlement:Entitlement,includedEntitlements:inout Set<String>) { includedEntitlements.insert(entitlement.name.lowercased()) for entitlementName in entitlement.includedEntitlements { let includedEntitlement = getEntitlement(name:entitlementName) if includedEntitlement.source != .MISSING { getPurchasedEntitlement(entitlement:includedEntitlement,includedEntitlements:&includedEntitlements) } } } // FeaturesMangement func addFeature(parentName:String?,newFeature:Feature) { guard let newEntitlement = newFeature as? Entitlement else { return } addEntitlement(parentName:parentName,newEntitlement:newEntitlement) } func getFeature(featureName:String)-> Feature { return getEntitlement(name: featureName) } func getRoot() -> Feature? { return entitlementsDict[Feature.ROOT_NAME.lowercased()] } func getRootChildrean() -> [Feature] { guard let root:Feature = getRoot() else { return [] } return root.getChildren() } } struct ProductIdData { let productID:String let purchaseOption:String let srcEntitlement:String let entitlements:Set<String> init(productID:String,purchaseOption:String,srcEntitlement:String,entitlements:Set<String>) { self.productID = productID self.purchaseOption = purchaseOption self.srcEntitlement = srcEntitlement self.entitlements = entitlements } func print() -> String { var output = "ProductID: \(self.productID)\n\nPurchase Option: \(Feature.removeNameSpace(self.purchaseOption))\n\nEntitlement: \(Feature.removeNameSpace(self.srcEntitlement))\n\n" if entitlements.count > 1 { var includedlist = "Included Entitlements:\n\n" for eName in entitlements { if eName != srcEntitlement { includedlist += "\(Feature.removeNameSpace(eName))\n" } } output += includedlist } return output } } extension Entitlements { func genrateProductIdsData(productIds:Set<String>) -> [String:ProductIdData] { var storeIDsDataDict:[String:ProductIdData] = [:] for (entitlementName,entitlement) in entitlementsDict { for (purchaseOptionName,purchaseOption) in entitlement.purchaseOptionsDict { for storeProductId in purchaseOption.storeProductIds { if productIds.contains(storeProductId.productId) { var includedEntitlements:Set<String> = [] getPurchasedEntitlement(entitlement:entitlement,includedEntitlements:&includedEntitlements) storeIDsDataDict[storeProductId.productId] = ProductIdData(productID:storeProductId.productId,purchaseOption:purchaseOptionName, srcEntitlement:entitlementName,entitlements:includedEntitlements) } } } } return storeIDsDataDict } }
32.940367
187
0.594346
d751692993d7de861945bc58c143ba8c36477d9e
3,032
// // HYTabBarController.swift // Adam_20190709_U17 // // Created by Adonis_HongYang on 2019/7/10. // Copyright © 2019 Adonis_HongYang. All rights reserved. // import UIKit class HYTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() tabBar.isTranslucent = false ///首页 let onePageVC = UHomeViewController(titles: ["推荐", "VIP", "订阅", "排行"], vcs: [UBoutiqueListViewController(), UVIPListViewController(), USubscibeListViewController(), URankListViewController()], pageStyle: .navgationBarSegment) addChildViewController(onePageVC, title: "首页", image: UIImage(named: "tab_home"), selectedImage: UIImage(named: "tab_home_S")) ///分类 let classVC = UCateListViewController() addChildViewController(classVC, title: "分类", image: UIImage(named: "tab_class"), selectedImage: UIImage(named: "tab_class_S")) ///书架 let bookVC = UBookViewController(titles: ["收藏", "书单", "下载"], vcs: [UCollectListViewController(), UDocumentListViewController(), UDownloadListViewController()], pageStyle: .navgationBarSegment) addChildViewController(bookVC, title: "书架", image: UIImage(named: "tab_book"), selectedImage: UIImage(named: "tab_book_S")) ///我的 let mineVC = UMineViewController() addChildViewController(mineVC, title: "我的", image: UIImage(named: "tab_mine"), selectedImage: UIImage(named: "tab_mine_S")) } func addChildViewController(_ childController: UIViewController, title: String?, image: UIImage?, selectedImage: UIImage?) { childController.title = title childController.tabBarItem = UITabBarItem(title: nil, image: image?.withRenderingMode(.alwaysOriginal), selectedImage: selectedImage?.withRenderingMode(.alwaysOriginal)) if UIDevice.current.userInterfaceIdiom == .phone { childController.tabBarItem.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0) } addChild(HYNavigationController(rootViewController: childController)) } } extension HYTabBarController { override var preferredStatusBarStyle: UIStatusBarStyle { guard let select = selectedViewController else { return .lightContent } return select.preferredStatusBarStyle } }
44.588235
177
0.536609
2927dea3aed814d7848b07cc86e403c2aa96a9e3
381
// // MineViewController.swift // DCBasicKitSwift // // Created by 杜才 on 2020/8/8. // Copyright © 2020 Zhongyuan. All rights reserved. // import UIKit class MineViewController: DCBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationItem.title = "我的" } }
20.052632
58
0.664042
2019adb245d177b95632f6a834a64584bddcc0c1
772
// // LoginViewController.swift // NavigationControllerProgrammatically // // Created by soohyeon on 17/05/2019. // Copyright © 2019 loveapplepi. All rights reserved. // import UIKit class LoginViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.yellow // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
24.903226
106
0.681347
7a89801ffb37458df62b2dc82d9e4961f5f4099e
337
extension Array where Element == Argument { /// The GraphQL representation of an arguments array. var graphQLRepresentable: String { var components: [String] = [] forEach { components.append("\($0.key): \($0.value.argumentValue)") } return components.joined(separator: ", ") } }
25.923077
69
0.596439
71be7ac70d6c55a5ab8463e7fd1899980a152648
23,344
// Copyright SIX DAY LLC. All rights reserved. // Copyright © 2018 Stormbird PTE. LTD. import Foundation import UIKit import JSONRPCKit import APIKit import PromiseKit import BigInt import MBProgressHUD protocol SendViewControllerDelegate: class, CanOpenURL { func didPressConfirm(transaction: UnconfirmedTransaction, in viewController: SendViewController) func lookup(contract: AlphaWallet.Address, in viewController: SendViewController, completion: @escaping (ContractData) -> Void) func openQRCode(in controller: SendViewController) } // swiftlint:disable type_body_length class SendViewController: UIViewController, CanScanQRCode { private let roundedBackground = RoundedBackground() private let scrollView = UIScrollView() private let recipientHeader = SendViewSectionHeader() private let amountHeader = SendViewSectionHeader() private let recipientAddressLabel = UILabel() private let amountLabel = UILabel() private let buttonsBar = ButtonsBar(configuration: .green(buttons: 1)) private var viewModel: SendViewModel private var balanceViewModel: BalanceBaseViewModel? private let session: WalletSession private let account: AlphaWallet.Address private let ethPrice: Subscribable<Double> private let assetDefinitionStore: AssetDefinitionStore private var data = Data() private lazy var decimalFormatter: DecimalFormatter = { return DecimalFormatter() }() private var currentSubscribableKeyForNativeCryptoCurrencyBalance: Subscribable<BalanceBaseViewModel>.SubscribableKey? private var currentSubscribableKeyForNativeCryptoCurrencyPrice: Subscribable<Double>.SubscribableKey? private let amountViewModel = SendViewSectionHeaderViewModel( text: R.string.localizable.sendAmount().uppercased(), showTopSeparatorLine: false ) private let recipientViewModel = SendViewSectionHeaderViewModel( text: R.string.localizable.sendRecipient().uppercased() ) //We use weak link to make sure that token alert will be deallocated by close button tapping. //We storing link to make sure that only one alert is displaying on the screen. private weak var invalidTokenAlert: UIViewController? let targetAddressTextField = AddressTextField() lazy var amountTextField = AmountTextField(tokenObject: transferType.tokenObject) weak var delegate: SendViewControllerDelegate? var transferType: TransferType { return viewModel.transferType } var sendAllButton: Button = { let button = Button(size: .normal, style: .borderless) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Send All", for: .normal) button.titleLabel?.font = DataEntry.Font.accessory button.setTitleColor(DataEntry.Color.icon, for: .normal) button.setBackgroundColor(.clear, forState: .normal) button.contentHorizontalAlignment = .right button.addTarget(self, action: #selector(sendAllButtonPressed), for: .touchUpInside) return button }() @objc func sendAllButtonPressed() { print("send all Pressed") } let storage: TokensDataStore // swiftlint:disable function_body_length init( session: WalletSession, storage: TokensDataStore, account: AlphaWallet.Address, transferType: TransferType, cryptoPrice: Subscribable<Double>, assetDefinitionStore: AssetDefinitionStore ) { self.session = session self.account = account self.storage = storage self.ethPrice = cryptoPrice self.assetDefinitionStore = assetDefinitionStore self.viewModel = .init(transferType: transferType, session: session, storage: storage) super.init(nibName: nil, bundle: nil) configureBalanceViewModel() roundedBackground.translatesAutoresizingMaskIntoConstraints = false view.addSubview(roundedBackground) scrollView.translatesAutoresizingMaskIntoConstraints = false roundedBackground.addSubview(scrollView) targetAddressTextField.translatesAutoresizingMaskIntoConstraints = false targetAddressTextField.delegate = self targetAddressTextField.returnKeyType = .done amountTextField.translatesAutoresizingMaskIntoConstraints = false amountTextField.delegate = self amountTextField.accessoryButtonTitle = .next amountTextField.errorState = .none let addressControlsContainer = UIView() addressControlsContainer.translatesAutoresizingMaskIntoConstraints = false addressControlsContainer.backgroundColor = .clear targetAddressTextField.pasteButton.contentHorizontalAlignment = .right let addressControlsStackView = [ targetAddressTextField.pasteButton, targetAddressTextField.clearButton ].asStackView(axis: .horizontal, alignment: .trailing) addressControlsStackView.translatesAutoresizingMaskIntoConstraints = false addressControlsStackView.setContentHuggingPriority(.required, for: .horizontal) addressControlsStackView.setContentCompressionResistancePriority(.required, for: .horizontal) addressControlsContainer.addSubview(addressControlsStackView) let stackView = [ amountHeader, .spacer(height: ScreenChecker().isNarrowScreen ? 7 : 27), amountLabel, .spacer(height: ScreenChecker().isNarrowScreen ? 2 : 4), amountTextField, .spacer(height: 4), [amountTextField.statusLabelContainer, sendAllButton].asStackView(axis: .horizontal), amountTextField.alternativeAmountLabelContainer, .spacer(height: ScreenChecker().isNarrowScreen ? 7: 14), recipientHeader, .spacer(height: ScreenChecker().isNarrowScreen ? 7: 16), [.spacerWidth(16), recipientAddressLabel].asStackView(axis: .horizontal), .spacer(height: ScreenChecker().isNarrowScreen ? 2 : 4), targetAddressTextField, .spacer(height: 4), [ [.spacerWidth(16), targetAddressTextField.ensAddressView, targetAddressTextField.statusLabel].asStackView(axis: .horizontal, alignment: .leading), addressControlsContainer ].asStackView(axis: .horizontal), ].asStackView(axis: .vertical) stackView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(stackView) let footerBar = UIView() footerBar.translatesAutoresizingMaskIntoConstraints = false footerBar.backgroundColor = .clear roundedBackground.addSubview(footerBar) footerBar.addSubview(buttonsBar) NSLayoutConstraint.activate([ amountHeader.leadingAnchor.constraint(equalTo: roundedBackground.leadingAnchor, constant: 0), amountHeader.trailingAnchor.constraint(equalTo: roundedBackground.trailingAnchor, constant: 0), amountHeader.heightAnchor.constraint(equalToConstant: 50), recipientHeader.leadingAnchor.constraint(equalTo: roundedBackground.leadingAnchor, constant: 0), recipientHeader.trailingAnchor.constraint(equalTo: roundedBackground.trailingAnchor, constant: 0), recipientHeader.heightAnchor.constraint(equalToConstant: 50), recipientAddressLabel.heightAnchor.constraint(equalToConstant: 22), targetAddressTextField.leadingAnchor.constraint(equalTo: roundedBackground.leadingAnchor, constant: 16), targetAddressTextField.trailingAnchor.constraint(equalTo: roundedBackground.trailingAnchor, constant: -16), amountTextField.leadingAnchor.constraint(equalTo: roundedBackground.leadingAnchor, constant: 16), amountTextField.trailingAnchor.constraint(equalTo: roundedBackground.trailingAnchor, constant: -16), amountTextField.heightAnchor.constraint(equalToConstant: ScreenChecker().isNarrowScreen ? 30 : 50), stackView.leadingAnchor.constraint(equalTo: roundedBackground.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: roundedBackground.trailingAnchor), stackView.topAnchor.constraint(equalTo: scrollView.topAnchor), stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), buttonsBar.leadingAnchor.constraint(equalTo: footerBar.leadingAnchor), buttonsBar.trailingAnchor.constraint(equalTo: footerBar.trailingAnchor), buttonsBar.topAnchor.constraint(equalTo: footerBar.topAnchor), buttonsBar.heightAnchor.constraint(equalToConstant: ButtonsBar.buttonsHeight), footerBar.leadingAnchor.constraint(equalTo: view.leadingAnchor), footerBar.trailingAnchor.constraint(equalTo: view.trailingAnchor), footerBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -ButtonsBar.buttonsHeight - ButtonsBar.marginAtBottomScreen), footerBar.bottomAnchor.constraint(equalTo: view.bottomAnchor), scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollView.topAnchor.constraint(equalTo: view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: footerBar.topAnchor), addressControlsStackView.trailingAnchor.constraint(equalTo: addressControlsContainer.trailingAnchor, constant: -7), addressControlsStackView.topAnchor.constraint(equalTo: addressControlsContainer.topAnchor), addressControlsStackView.bottomAnchor.constraint(equalTo: addressControlsContainer.bottomAnchor), addressControlsStackView.leadingAnchor.constraint(greaterThanOrEqualTo: addressControlsContainer.leadingAnchor), addressControlsContainer.heightAnchor.constraint(equalToConstant: 30) ] + roundedBackground.createConstraintsWithContainer(view: view)) storage.updatePrices() } // swiftlint:enable function_body_length override func viewDidLoad() { super.viewDidLoad() activateAmountView() } @objc func closeKeyboard() { view.endEditing(true) } func configure(viewModel: SendViewModel, shouldConfigureBalance: Bool = true) { self.viewModel = viewModel //Avoids infinite recursion if shouldConfigureBalance { configureBalanceViewModel() } targetAddressTextField.configureOnce() view.backgroundColor = viewModel.backgroundColor amountHeader.configure(viewModel: amountViewModel) recipientHeader.configure(viewModel: recipientViewModel) recipientAddressLabel.text = viewModel.recipientsAddress recipientAddressLabel.font = viewModel.recipientLabelFont recipientAddressLabel.textColor = viewModel.recepientLabelTextColor amountLabel.font = viewModel.textFieldsLabelFont amountLabel.textColor = viewModel.textFieldsLabelTextColor amountTextField.currentPair = viewModel.amountTextFieldPair amountTextField.isAlternativeAmountEnabled = false amountTextField.selectCurrencyButton.isHidden = viewModel.currencyButtonHidden amountTextField.selectCurrencyButton.expandIconHidden = viewModel.selectCurrencyButtonHidden amountTextField.statusLabel.text = viewModel.availableLabelText amountTextField.availableTextHidden = viewModel.availableTextHidden switch transferType { case .nativeCryptocurrency(_, let recipient, let amount): if let recipient = recipient { targetAddressTextField.value = recipient.stringValue } if let amount = amount { amountTextField.ethCost = EtherNumberFormatter.full.string(from: amount, units: .ether) } currentSubscribableKeyForNativeCryptoCurrencyPrice = ethPrice.subscribe { [weak self] value in if let value = value { self?.amountTextField.cryptoToDollarRate = value } } case .ERC20Token(_, let recipient, let amount): currentSubscribableKeyForNativeCryptoCurrencyPrice.flatMap { ethPrice.unsubscribe($0) } amountTextField.cryptoToDollarRate = nil if let recipient = recipient { targetAddressTextField.value = recipient.stringValue } if let amount = amount { amountTextField.ethCost = amount } case .ERC875Token, .ERC875TokenOrder, .ERC721Token, .ERC721ForTicketToken, .dapp: currentSubscribableKeyForNativeCryptoCurrencyPrice.flatMap { ethPrice.unsubscribe($0) } amountTextField.cryptoToDollarRate = nil } buttonsBar.configure() let nextButton = buttonsBar.buttons[0] nextButton.setTitle(R.string.localizable.send(), for: .normal) nextButton.addTarget(self, action: #selector(send), for: .touchUpInside) updateNavigationTitle() } private func updateNavigationTitle() { title = "\(R.string.localizable.send()) \(transferType.symbol)" } @objc func send() { let input = targetAddressTextField.value.trimmed targetAddressTextField.errorState = .none amountTextField.errorState = .none let checkIfGreaterThanZero: Bool // allow users to input zero on native transactions as they may want to send custom data switch transferType { case .nativeCryptocurrency, .dapp: checkIfGreaterThanZero = false case .ERC20Token, .ERC875Token, .ERC875TokenOrder, .ERC721Token, .ERC721ForTicketToken: checkIfGreaterThanZero = true } guard let value = viewModel.validatedAmount(value: amountTextField.ethCost, checkIfGreaterThanZero: checkIfGreaterThanZero) else { amountTextField.errorState = .error return } guard let address = AlphaWallet.Address(string: input) else { targetAddressTextField.errorState = .error(Errors.invalidAddress.prettyError) return } let transaction = UnconfirmedTransaction( transferType: transferType, value: value, to: address, data: data, gasLimit: .none, tokenId: .none, gasPrice: .none, nonce: .none, v: .none, r: .none, s: .none, expiry: .none, indices: .none, tokenIds: .none ) delegate?.didPressConfirm(transaction: transaction, in: self) } func activateAmountView() { _ = amountTextField.becomeFirstResponder() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureBalanceViewModel() { currentSubscribableKeyForNativeCryptoCurrencyBalance.flatMap { session.balanceViewModel.unsubscribe($0) } currentSubscribableKeyForNativeCryptoCurrencyPrice.flatMap { ethPrice.unsubscribe($0) } switch transferType { case .nativeCryptocurrency(_, let recipient, let amount): currentSubscribableKeyForNativeCryptoCurrencyBalance = session.balanceViewModel.subscribe { [weak self] viewModel in guard let celf = self else { return } guard celf.storage.token(forContract: celf.viewModel.transferType.contract) != nil else { return } celf.configureFor(contract: celf.viewModel.transferType.contract, recipient: recipient, amount: amount, shouldConfigureBalance: false) } session.refresh(.ethBalance) case .ERC20Token(let token, let recipient, let amount): let amount = amount.flatMap { EtherNumberFormatter.full.number(from: $0, decimals: token.decimals) } configureFor(contract: viewModel.transferType.contract, recipient: recipient, amount: amount, shouldConfigureBalance: false) case .ERC875Token, .ERC875TokenOrder, .ERC721Token, .ERC721ForTicketToken, .dapp: break } } func didScanQRCode(_ result: String) { guard let result = QRCodeValueParser.from(string: result) else { return } switch result { case .address(let recipient): guard let tokenObject = storage.token(forContract: viewModel.transferType.contract) else { return } let amountAsIntWithDecimals = EtherNumberFormatter.full.number(from: amountTextField.ethCost, decimals: tokenObject.decimals) configureFor(contract: transferType.contract, recipient: .address(recipient), amount: amountAsIntWithDecimals) activateAmountView() case .eip681(let protocolName, let address, let functionName, let params): checkAndFillEIP681Details(protocolName: protocolName, address: address, functionName: functionName, params: params) } } private func showInvalidToken() { guard invalidTokenAlert == nil else { return } invalidTokenAlert = UIAlertController.alert( message: R.string.localizable.sendInvalidToken(), alertButtonTitles: [R.string.localizable.oK()], alertButtonStyles: [.cancel], viewController: self ) } private func checkAndFillEIP681Details(protocolName: String, address: AddressOrEnsName, functionName: String?, params: [String: String]) { //TODO error display on returns Eip681Parser(protocolName: protocolName, address: address, functionName: functionName, params: params).parse().done { result in guard let (contract: contract, optionalServer, recipient, maybeScientificAmountString) = result.parameters else { return } let amount = self.convertMaybeScientificAmountToBigInt(maybeScientificAmountString) //For user-safety and simpler implementation, we ignore the link if it is for a different chain if let server = optionalServer { guard self.session.server == server else { return } } if self.storage.token(forContract: contract) != nil { //For user-safety and simpler implementation, we ignore the link if it is for a different chain self.configureFor(contract: contract, recipient: recipient, amount: amount) self.activateAmountView() } else { self.delegate?.lookup(contract: contract, in: self) { data in switch data { case .name, .symbol, .balance, .decimals: break case .nonFungibleTokenComplete: self.showInvalidToken() case .fungibleTokenComplete(let name, let symbol, let decimals): //TODO update fetching to retrieve balance too so we can display the correct balance in the view controller let token = ERCToken( contract: contract, server: self.storage.server, name: name, symbol: symbol, decimals: Int(decimals), type: .erc20, balance: ["0"] ) self.storage.addCustom(token: token) self.configureFor(contract: contract, recipient: recipient, amount: amount) self.activateAmountView() case .delegateTokenComplete: self.showInvalidToken() case .failed: break } } } }.cauterize() } //This function is required because BigInt.init(String) doesn't handle scientific notation private func convertMaybeScientificAmountToBigInt(_ maybeScientificAmountString: String) -> BigInt? { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.usesGroupingSeparator = false let amountString = numberFormatter.number(from: maybeScientificAmountString).flatMap { numberFormatter.string(from: $0) } return amountString.flatMap { BigInt($0) } } private func configureFor(contract: AlphaWallet.Address, recipient: AddressOrEnsName?, amount: BigInt?, shouldConfigureBalance: Bool = true) { guard let tokenObject = storage.token(forContract: contract) else { return } let amount = amount.flatMap { EtherNumberFormatter.full.string(from: $0, decimals: tokenObject.decimals) } let transferType: TransferType if let amount = amount, amount != "0" { transferType = TransferType(token: tokenObject, recipient: recipient, amount: amount) } else { switch viewModel.transferType { case .nativeCryptocurrency(_, _, let amount): transferType = TransferType(token: tokenObject, recipient: recipient, amount: amount.flatMap { EtherNumberFormatter().string(from: $0, units: .ether) }) case .ERC20Token(_, _, let amount): transferType = TransferType(token: tokenObject, recipient: recipient, amount: amount) case .ERC875Token, .ERC875TokenOrder, .ERC721Token, .ERC721ForTicketToken, .dapp: transferType = TransferType(token: tokenObject, recipient: recipient, amount: nil) } } configure(viewModel: .init(transferType: transferType, session: session, storage: storage), shouldConfigureBalance: shouldConfigureBalance) } } // swiftlint:enable type_body_length extension SendViewController: AmountTextFieldDelegate { func shouldReturn(in textField: AmountTextField) -> Bool { _ = targetAddressTextField.becomeFirstResponder() return false } func changeAmount(in textField: AmountTextField) { textField.errorState = .none textField.statusLabel.text = viewModel.availableLabelText textField.availableTextHidden = viewModel.availableTextHidden guard viewModel.validatedAmount(value: textField.ethCost, checkIfGreaterThanZero: false) != nil else { textField.errorState = .error return } } func changeType(in textField: AmountTextField) { updateNavigationTitle() } } extension SendViewController: AddressTextFieldDelegate { func displayError(error: Error, for textField: AddressTextField) { textField.errorState = .error(error.prettyError) } func openQRCodeReader(for textField: AddressTextField) { delegate?.openQRCode(in: self) } func didPaste(in textField: AddressTextField) { textField.errorState = .none activateAmountView() } func shouldReturn(in textField: AddressTextField) -> Bool { _ = textField.resignFirstResponder() return true } func didChange(to string: String, in textField: AddressTextField) { } }
46.875502
168
0.682317
90363723a77bbfdc4e9fba9b8ad233c53889d562
719
// // JsonModel.swift // Hayy // // Created by Herlangga Wibi Yandi Nasution on 29/01/19. // Copyright © 2019 PT. Buana Kebenaran Informatika. All rights reserved. // import Foundation import SwiftyJSON struct JsonModel{ var name: String = "" var image: String = "" var id = Int() var user_id: String = "" var posts = Int() var following = Int() var followers = Int() init(){ } init(json: JSON){ name = json["name"].stringValue image = json["image"].stringValue id = json["id"].intValue user_id = json["user_id"].stringValue posts = json["posts"].intValue following = json["following"].intValue followers = json["followers"].intValue } }
18.435897
74
0.623088
cc4fdddabdbc3931319beb0b36e551b0e0e35bbb
4,843
import Foundation /// Однострочное поле ввода суммы, расширяет тип number. public struct AmountControl: Control { /// ControlProtocol public let type: FormType = .amount public let name: String public let value: String? public let autofillValue: Autofill? public let hint: String? public let label: String? public let alert: String? public let required: Bool public let readonly: Bool /// Минимально допустимое значение. public let min: Double /// Максимально допустимое значение. public let max: Double? /// Кратность значения суммы. public let step: Double /// Трёхсимвольный буквенный код валюты по стандарту ISO-4217. public let currency: String /// Информация о комиссии с покупателя. public let fee: Fee? public init(name: String, value: String?, autofillValue: Autofill?, hint: String?, label: String?, alert: String?, required: Bool, readonly: Bool, min: Double, max: Double?, step: Double, currency: String, fee: Fee?) { self.name = name self.value = value self.autofillValue = autofillValue self.hint = hint self.label = label self.alert = alert self.required = required self.readonly = readonly self.min = min self.max = max self.step = step self.currency = currency self.fee = fee } // MARK: - Decodable public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) guard case .amount = try container.decode(FormType.self, forKey: .type) else { throw DecodingError.invalidType } let name = try container.decode(String.self, forKey: .name) let value = try container.decodeIfPresent(String.self, forKey: .value) let autofillValue = try container.decodeIfPresent(Autofill.self, forKey: .autofill) let hint = try container.decodeIfPresent(String.self, forKey: .hint) let label = try container.decodeIfPresent(String.self, forKey: .label) let alert = try container.decodeIfPresent(String.self, forKey: .alert) let required = try container.decode(Bool.self, forKey: .required) let readonly = try container.decode(Bool.self, forKey: .readonly) let min = try container.decodeIfPresent(Double.self, forKey: .min) ?? 0.01 let max = try container.decodeIfPresent(Double.self, forKey: .max) let step = try container.decodeIfPresent(Double.self, forKey: .step) ?? 0.01 let currency = try container.decodeIfPresent(String.self, forKey: .currency) ?? "RUB" let fee = try container.decodeIfPresent(Fee.self, forKey: .fee) self.init(name: name, value: value, autofillValue: autofillValue, hint: hint, label: label, alert: alert, required: required, readonly: readonly, min: min, max: max, step: step, currency: currency, fee: fee) } enum DecodingError: Error { case invalidType } // MARK: - Encodable public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(type, forKey: .type) try container.encode(name, forKey: .name) try container.encodeIfPresent(value, forKey: .value) try container.encodeIfPresent(autofillValue, forKey: .autofill) try container.encodeIfPresent(hint, forKey: .hint) try container.encodeIfPresent(label, forKey: .label) try container.encodeIfPresent(alert, forKey: .alert) try container.encode(required, forKey: .required) try container.encode(readonly, forKey: .readonly) if min != 0.01 { try container.encode(min, forKey: .min) } try container.encodeIfPresent(max, forKey: .max) if step != 0.01 { try container.encode(step, forKey: .step) } if currency != "RUB" { try container.encode(currency, forKey: .currency) } try container.encodeIfPresent(fee, forKey: .fee) } private enum CodingKeys: String, CodingKey { case type case name case value case autofill = "value_autofill" case hint case label case alert case required case readonly case min case max case step case currency case fee } }
32.072848
93
0.590543
bb4479539c2abb68a1d4e5836627bb4c645c0557
974
import UIKit public protocol ThemeFonts { /// Avenir, Regular, 18 static var regular: UIFont { get } /// Avenir, Medium, 18 static var medium: UIFont { get } /// Avenir, Medium, 24 static var resultLabel: UIFont { get } /// Avenir, Regular, 22 static var buttonLabel: UIFont { get } /// Avenir, Bold, 28 static var handPoseLabel: UIFont { get } } public enum ThemeFont { case regular case medium case resultLabel case buttonLabel case handPoseLabel public var uiFont: UIFont { switch self { case .regular: return DefaultThemeFonts.regular case .medium: return DefaultThemeFonts.medium case .resultLabel: return DefaultThemeFonts.resultLabel case .buttonLabel: return DefaultThemeFonts.buttonLabel case .handPoseLabel: return DefaultThemeFonts.handPoseLabel } } }
23.190476
50
0.607803
7593878ec8590baad62e593d77c8bd757aa04097
811
import SwiftUI struct BlurView: UIViewRepresentable { let style: UIBlurEffect.Style func makeUIView(context: UIViewRepresentableContext<BlurView>) -> UIView { let blurEffect = UIBlurEffect(style: style) let blurView = UIVisualEffectView(effect: blurEffect) blurView.translatesAutoresizingMaskIntoConstraints = false let view = UIView(frame: .zero) view.backgroundColor = .clear view.insertSubview(blurView, at: 0) NSLayoutConstraint.activate([ blurView.heightAnchor.constraint(equalTo: view.heightAnchor), blurView.widthAnchor.constraint(equalTo: view.widthAnchor), ]) return view } func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<BlurView>) {} }
31.192308
78
0.678175
67daa2f37f4fca4ad827a26e9da695355f08ab68
723
// // LT_1_TwoSum.swift // YDLearn // // Created by gaoyuan on 2021/10/28. // import UIKit class LT_1_TwoSum: NSObject, LTSolution { func solution() { twoSum([2,7,11,15], 9) } func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var result: [Int] = [] for (i, num) in nums.enumerated() { let kNum = target - num if nums.contains(kNum) { let kIndex = nums.firstIndex(of: kNum)! if kIndex == i { continue } result.append(kIndex) result.append(i) break } // print(i, num) } return result } }
21.264706
56
0.445367
183559c8a2df4f88cab785d78b9da1f2c524fd99
2,280
import Foundation import Extensions import Models import PathLib /// Represents a single simulator wrapped into a folder which contains a simulator set with it. /// Simulator set is a private to simctl structure that desribes a set of simulators. public class Simulator: Hashable, CustomStringConvertible { public let index: UInt public let testDestination: TestDestination public let workingDirectory: AbsolutePath public var identifier: String { return "simulator_\(index)_\(testDestination.deviceType.removingWhitespaces())_\(testDestination.runtime.removingWhitespaces())" } public var description: String { return "Simulator \(index): \(testDestination.deviceType) \(testDestination.runtime) at: \(workingDirectory)" } public var simulatorInfo: SimulatorInfo { return SimulatorInfo( simulatorUuid: uuid, simulatorSetPath: simulatorSetContainerPath.pathString ) } /// A path to simctl's simulator set structure. If created, simulator will be placed inside this folder. public var simulatorSetContainerPath: AbsolutePath { return workingDirectory.appending(component: "sim") } /// Simulator's UUID/UDID if it has been created. Will return nil if it hasn't been created yet. /// Currently there is an assumption that simulator set contains only a single simulator. public var uuid: UUID? { let contents = (try? FileManager.default.contentsOfDirectory(atPath: simulatorSetContainerPath.pathString)) ?? [] return contents.compactMap({ UUID(uuidString: $0) }).first } init(index: UInt, testDestination: TestDestination, workingDirectory: AbsolutePath) { self.index = index self.testDestination = testDestination self.workingDirectory = workingDirectory } public static func == (left: Simulator, right: Simulator) -> Bool { return left.index == right.index && left.workingDirectory == right.workingDirectory && left.testDestination == right.testDestination } public func hash(into hasher: inout Hasher) { hasher.combine(index) hasher.combine(testDestination) hasher.combine(workingDirectory) } }
39.310345
136
0.699561