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
1eb0fa1d217c10bc6794a9eb15bd36c1149ea356
2,019
// // EditLocalisationTableViewCell.swift // ThunderCloud // // Created by Simon Mitchell on 06/07/2017. // Copyright © 2017 threesidedcube. All rights reserved. // import UIKit import ThunderBasics import ThunderTable /// A cell for allowing the user to edit a localisation for a certain language class EditLocalisationTableViewCell: InputTextViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() setup() } private var separatorView: UIView? private func setup() { contentView.backgroundColor = .clear backgroundColor = .clear backgroundView = UIView() backgroundView?.backgroundColor = .white backgroundView?.layer.borderWidth = 1/UIScreen.main.scale backgroundView?.layer.borderColor = UIColor(hexString: "9B9B9B")?.cgColor backgroundView?.layer.cornerRadius = 2.0 backgroundView?.layer.masksToBounds = true contentView.addSubview(backgroundView!) contentView.sendSubviewToBack(backgroundView!) separatorView = UIView() separatorView?.backgroundColor = UIColor(hexString: "9B9B9B") backgroundView!.addSubview(separatorView!) } override func layoutSubviews() { super.layoutSubviews() backgroundView?.frame = CGRect(x: 8, y: 8, width: contentView.bounds.width-16, height: contentView.bounds.height - 8) guard let cellTextLabelContainer = cellTextLabel?.superview else { separatorView?.frame = .zero return } separatorView?.frame = CGRect(x: cellTextLabelContainer.frame.maxX, y: 0, width: 1/UIScreen.main.scale, height: backgroundView?.frame.height ?? 0) } }
32.047619
154
0.662209
abc2c9fbc73dd61b5946c9ce15d2154f00334965
399
// // VersionFlag.swift // Taylor // // Created by Dmitrii Celpan on 11/10/15. // Copyright © 2015 YOPESO. All rights reserved. // let VersionLong = "--version" let VersionShort = "-v" struct VersionFlag: Flag { let name = "VersionFlag" func execute() { let infoPrinter = Printer(verbosityLevel: .info) infoPrinter.printInfo("Taylor \(version)") } }
18.136364
56
0.619048
4814f806e5b09f86a1dd0f41e6e25b5a18eef2b2
16,517
// // ApiRequests.swift // GlorySDK // // Created by John Kricorian on 12/07/2021. // import Foundation protocol RequestDelegate { var urlRequest: URLRequest { get } } class ClientURL { let clientIP: String internal init(clientIP: String) { self.clientIP = clientIP } var url: URL { let url = URL(string: "http://\(clientIP)/axis2/services/BrueBoxService")! return url } } class AdjustTimeRequest: RequestDelegate { private let sessionId: String private let parameter: RequestParameter private let operation: Operation private let clientIP: String private let year: String private let month: String private let day: String private let hour: String private let minute: String private let second: String internal init(sessionId: String, parameter: RequestParameter, operation: Operation, clientIP: String, year: String, month: String, day: String, hour: String, minute: String, second: String) { self.sessionId = sessionId self.parameter = parameter self.operation = operation self.clientIP = clientIP self.year = year self.month = month self.day = day self.hour = hour self.minute = minute self.second = second } var allHTTPHeaderFields = [ "content-type": "text/xml" ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: parameter.result, sessionId: sessionId, month: month, day: day, year: year, hour: hour, minute: minute, second: second).adjustTimeRequest return request } } class GetStatusRequest: RequestDelegate { private let sessionId: String private let parameter: RequestParameter private let operation: Operation private let clientIP: String internal init(sessionId: String, parameter: RequestParameter, operation: Operation, clientIP: String) { self.sessionId = sessionId self.parameter = parameter self.operation = operation self.clientIP = clientIP } var allHTTPHeaderFields = [ "content-type": "text/xml" ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: parameter.result, sessionId: sessionId).statusRequest return request } } class OpenOperationRequest: RequestDelegate { private let parameter: RequestParameter private let operation: Operation private let clientIP: String private let user: String private let pwd: String internal init(parameter: RequestParameter, operation: Operation, clientIP: String, user: String, pwd: String) { self.parameter = parameter self.operation = operation self.clientIP = clientIP self.user = user self.pwd = pwd } private var allHTTPHeaderFields = [ "content-type": "text/xml", ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: parameter.result).openRequest return request } } class OccupyOperationRequest: RequestDelegate { private let sessionId: String private let parameter: RequestParameter private let operation: Operation private let clientIP: String internal init(sessionId: String, parameter: RequestParameter, operation: Operation, clientIP: String) { self.sessionId = sessionId self.parameter = parameter self.operation = operation self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml" ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: parameter.result, sessionId: sessionId).occupyOperation return request } } class ChangeOperationRequest: RequestDelegate { private let sessionId: String private let amount: String private let parameter: RequestParameter private let operation: Operation private let clientIP: String internal init(sessionId: String, amount: String, parameter: RequestParameter, operation: Operation, clientIP: String) { self.sessionId = sessionId self.amount = amount self.parameter = parameter self.operation = operation self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml" ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: parameter.result, sessionId: sessionId, amount: amount).changeOperation return request } } class ReleaseOperationRequest: RequestDelegate { private let sessionId: String private let operation: Operation private let requestParameter: RequestParameter private let clientIP: String internal init(sessionId: String, operation: Operation, requestParameter: RequestParameter, clientIP: String) { self.sessionId = sessionId self.operation = operation self.requestParameter = requestParameter self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml" ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: requestParameter.result, sessionId: sessionId).releaseOperation return request } } class CloseOperationRequest: RequestDelegate { private let sessionId: String private let operation: Operation private let requestParameter: RequestParameter private let clientIP: String internal init(sessionId: String, operation: Operation, requestParameter: RequestParameter, clientIP: String) { self.sessionId = sessionId self.operation = operation self.requestParameter = requestParameter self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml", ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: requestParameter.result, sessionId: sessionId).closeOperation return request } } class CancelOperationRequest: RequestDelegate { private let sessionId: String private let operation: Operation private let requestParameter: RequestParameter private let clientIP: String internal init(sessionId: String, operation: Operation, requestParameter: RequestParameter, clientIP: String) { self.sessionId = sessionId self.operation = operation self.requestParameter = requestParameter self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml", ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: requestParameter.result, sessionId: sessionId).changeCancelOperation return request } } class RegisterEventOperationRequest: RequestDelegate { private let sessionId: String private let operation: Operation private let requestParameter: RequestParameter private let destination: Destination private let clientIP: String internal init(sessionId: String, operation: Operation, requestParameter: RequestParameter, destination: Destination, clientIP: String) { self.sessionId = sessionId self.operation = operation self.requestParameter = requestParameter self.destination = destination self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml", ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: requestParameter.result, sessionId: sessionId, destination: destination, IPAddress: Host().IPAddress()).registerEventOperation return request } } class UnRegisterEventOperationRequest: RequestDelegate { private let operation: Operation private let requestParameter: RequestParameter private let id: String private let sessionId: String private let clientIP: String internal init(operation: Operation, requestParameter: RequestParameter, id: String, sessionId: String, clientIP: String) { self.operation = operation self.requestParameter = requestParameter self.id = id self.sessionId = sessionId self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml", ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: requestParameter.result, sessionId: sessionId, IPAddress: Host().IPAddress()).unregisterEventOperation return request } } class InventoryOperationRequest: RequestDelegate { private let sessionId: String private let operation: Operation private let requestParameter: RequestParameter private let inventoryOption: String private let clientIP: String internal init(sessionId: String, operation: Operation, requestParameter: RequestParameter, inventoryOption: String, clientIP: String) { self.sessionId = sessionId self.operation = operation self.requestParameter = requestParameter self.inventoryOption = inventoryOption self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml", ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: requestParameter.result, sessionId: sessionId, inventoryOption: inventoryOption).inventoryOperation return request } } class ResetOperationRequest: RequestDelegate { private let sessionId: String private let operation: Operation private let requestParameter: RequestParameter private let clientIP: String internal init(sessionId: String, operation: Operation, requestParameter: RequestParameter, clientIP: String) { self.sessionId = sessionId self.operation = operation self.requestParameter = requestParameter self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml", ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: requestParameter.result, sessionId: sessionId).resetOperation return request } } class OpenExitCoverOperationRequest: RequestDelegate { private let sessionId: String private let operation: Operation private let requestParameter: RequestParameter private let clientIP: String internal init(sessionId: String, operation: Operation, requestParameter: RequestParameter, clientIP: String) { self.sessionId = sessionId self.operation = operation self.requestParameter = requestParameter self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml", ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: requestParameter.result, sessionId: sessionId).openExitCoverOperation return request } } class CloseExitCoverOperationRequest: RequestDelegate { private let sessionId: String private let operation: Operation private let requestParameter: RequestParameter private let clientIP: String internal init(sessionId: String, operation: Operation, requestParameter: RequestParameter, clientIP: String) { self.sessionId = sessionId self.operation = operation self.requestParameter = requestParameter self.clientIP = clientIP } private var allHTTPHeaderFields = [ "content-type": "text/xml", ] var urlRequest: URLRequest { let url = ClientURL(clientIP: clientIP).url var request = URLRequest(url: url) request.setHTTPMethod("POST") allHTTPHeaderFields.updateValue(operation.name, forKey: "SOAPAction") request.allHTTPHeaderFields = allHTTPHeaderFields request.httpBody = Request(parameter: requestParameter.result, sessionId: sessionId).closeExitCoverOperation return request } }
34.338877
195
0.650481
fb59d8061d55b5aaca0811c1c819ea5a588d5319
993
// // User.swift // Study Saga // // Created by Trần Đình Tôn Hiếu on 3/2/21. // import Foundation enum Gender { case male case female } struct User: Hashable, Identifiable { var id: String = UUID().uuidString var name: String = "" var email: String = "" var phone: String = "" var avatarUrl: String = "" var departmentId: String = "" var departmentName: String = "" var isEnable: Bool = true var gender: Gender = .male } extension User { init(from json: [String: Any]) { self.name = json.stringValueForKey("fullName") self.email = json.stringValueForKey("email") self.departmentId = json.stringValueForKey("departmentID") self.departmentName = json.stringValueForKey("departmentName") self.avatarUrl = json.stringValueForKey("avatar") self.gender = json.stringValueForKey("sex") == "Male" ? .male : .female self.isEnable = json.boolValueForKey("isEnabled") } }
23.642857
79
0.628399
ff9d0433c127cd734513437cfcdd5de294c50fa0
3,833
// // YandexGeocodingService.swift // RememberPoint // // Created by Pavel Chehov on 04/01/2019. // Copyright © 2019 Pavel Chehov. All rights reserved. // import Moya enum YandexGeocodingService { case getSuggestions(address: String) case getGeocoding(address: String) case getReverseGeocoding(point: GeoPoint) } extension YandexGeocodingService: TargetType { var baseURL: URL { switch self { case .getGeocoding, .getReverseGeocoding: return URL(string: Constants.YandexGeocodingBaseUrl)! case .getSuggestions: return URL(string: Constants.YandexSuggestionsBaseUrl)! } } var path: String { switch self { case .getGeocoding, .getReverseGeocoding: return "/1.x" case .getSuggestions: return "/suggest-geo" } } var method: Moya.Method { return .get } var sampleData: Data { switch self { case .getSuggestions: guard let url = Bundle.main.url(forResource: "suggestions", withExtension: "json"), let data = try? Data(contentsOf: url) else { return Data() } return data case .getGeocoding: guard let url = Bundle.main.url(forResource: "geocodingByAddress", withExtension: "json"), let data = try? Data(contentsOf: url) else { return Data() } return data case .getReverseGeocoding: guard let url = Bundle.main.url(forResource: "geocodingByPoint", withExtension: "json"), let data = try? Data(contentsOf: url) else { return Data() } return data } } var task: Moya.Task { let settingsProvider: SettingsProviderProtocol = DIContainer.instance.resolve() switch self { case let .getSuggestions(address): var parameters = ["part": address, "lang": "\(Constants.locale)", "format": "json", "results": "\(Constants.autocompleteMaximumResults)", "spn": "0.2,0.2", "search_type": "all", "v": "7"] var locationValue: String? if let latitude = settingsProvider.currentLocation?.latitude, let longitude = settingsProvider.currentLocation?.longitude { locationValue = "\(longitude),\(latitude)" parameters["ll"] = locationValue } return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) case let .getGeocoding(address): let parameters = ["geocode": address, "lang": "\(Constants.locale)", "format": "json", "results": "\(Constants.autocompleteMaximumResults)", "spn": "0.2,0.2", "kind": "house"] return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) case let .getReverseGeocoding(point): let parameters = ["apikey": Constants.YandexApiKey, "geocode": "\(point.longitude!),\(point.latitude!)", "lang": "\(Constants.locale)", "format": "json", "results": "\(Constants.autocompleteMaximumResults)", "kind": "house"] return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString) } } var headers: [String: String]? { return ["Content-type": "application/json"] } }
37.213592
135
0.531959
d67b66849d5a5866c6ecd7c2183a3ebfce5ed233
898
// // RWExampleTests.swift // RWExampleTests // // Created by Joe Zobkiw on 1/24/15. // Copyright (c) 2015 Roundware. All rights reserved. // import UIKit import XCTest class RWExampleTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
24.27027
111
0.613586
d998b34e21d8fb2d6669353cf56d84de757072fc
219
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let b { var f : b protocol b { struct S<T: S<Int>
24.333333
87
0.73516
0e17307e00f9811826d0ea1fa30c73d455e4bdd7
10,385
// // UIDevice+Model.swift // FZBuildingBlock // // Created by FranZhou on 2020/9/1. // // https://www.theiphonewiki.com/wiki/Models#iPhone // import Foundation extension FZBuildingBlockWrapper where Base: UIDevice { /// 获取设备型号 /// - Returns: 设备型号 public func getModelName() -> String { func getDeviceModelName(machine: String) -> String { var modelName = base.model switch machine { // Apple Watch case "Watch1,1": modelName = "Apple Watch (1st generation) (38mm)" case "Watch1,2": modelName = "Apple Watch (1st generation) (42mm)" case "Watch2,6": modelName = "Apple Watch Series 1 (38mm)" case "Watch2,7": modelName = "Apple Watch Series 1 (42mm)" case "Watch2,3": modelName = "Apple Watch Series 2 (38mm)" case "Watch2,4": modelName = "Apple Watch Series 2 (42mm)" case "Watch3,1", "Watch3,3": modelName = "Apple Watch Series 3 (38mm)" case "Watch3,2", "Watch3,4": modelName = "Apple Watch Series 3 (42mm)" case "Watch4,1", "Watch4,3": modelName = "Apple Watch Series 4 (40mm)" case "Watch4,2", "Watch4,4": modelName = "Apple Watch Series 4 (44mm)" case "Watch5,1", "Watch5,3": modelName = "Apple Watch Series 5 (40mm)" case "Watch5,2", "Watch5,4": modelName = "Apple Watch Series 5 (44mm)" case "Watch5,9", "Watch5,11": modelName = "Apple Watch SE (40mm)" case "Watch5,10", "Watch5,12": modelName = "Apple Watch SE (44mm)" case "Watch6,1", "Watch6,3": modelName = "Apple Watch Series 6 (40mm)" case "Watch6,2", "Watch6,4": modelName = "Apple Watch Series 6 (44mm)" // HomePod case "AudioAccessory1,1", "AudioAccessory1,2": modelName = "HomePod" case "AudioAccessory5,1": modelName = "HomePod mini" // iPad case "iPad1,1": modelName = "iPad" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": modelName = "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": modelName = "iPad (3rd generation)" case "iPad3,4", "iPad3,5", "iPad3,6": modelName = "iPad (4th generation)" case "iPad6,11", "iPad6,12": modelName = "iPad (5th generation)" case "iPad7,5", "iPad7,6": modelName = "iPad (6th generation)" case "iPad7,11", "iPad7,12": modelName = "iPad (7th generation)" case "iPad11,6", "iPad11,7": modelName = "iPad (8th generation)" // Apple Pencil // identifier Unknown // Smart Keyboard // identifier Unknown // iPad Air case "iPad4,1", "iPad4,2", "iPad4,3": modelName = "iPad Air" case "iPad5,3", "iPad5,4": modelName = "iPad Air 2" case "iPad11,3", "iPad11,4": modelName = "iPad Air (3rd generation)" case "iPad13,1", "iPad13,2": modelName = "iPad Air (4th generation)" // iPad Pro case "iPad6,3", "iPad6,4": modelName = "iPad Pro (9.7-inch)" case "iPad6,7", "iPad6,8": modelName = "iPad Pro (12.9-inch)" case "iPad7,1", "iPad7,2": modelName = "iPad Pro (12.9-inch) (2nd generation)" case "iPad7,3", "iPad7,4": modelName = "iPad Pro (10.5-inch)" case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": modelName = "iPad Pro (11-inch)" case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": modelName = "iPad Pro (12.9-inch) (3rd generation)" case "iPad8,9", "iPad8,10": modelName = "iPad Pro (11-inch) (2nd generation)" case "iPad8,11", "iPad8,12": modelName = "iPad Pro (12.9-inch) (4th generation)" // iPad mini case "iPad2,5", "iPad2,6", "iPad2,7": modelName = "iPad mini" case "iPad4,4", "iPad4,5", "iPad4,6": modelName = "iPad mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": modelName = "iPad mini 3" case "iPad5,1", "iPad5,2": modelName = "iPad mini 4" case "iPad11,1", "iPad11,2": modelName = "iPad mini (5th generation)" // iPhone case "iPhone1,1": modelName = "iPhone" case "iPhone1,2": modelName = "iPhone 3G" case "iPhone2,1": modelName = "iPhone 3GS" case "iPhone3,1", "iPhone3,2", "iPhone3,3": modelName = "iPhone 4" case "iPhone4,1": modelName = "iPhone 4S" case "iPhone5,1", "iPhone5,2": modelName = "iPhone 5" case "iPhone5,3", "iPhone5,4": modelName = "iPhone 5c" case "iPhone6,1", "iPhone6,2": modelName = "iPhone 5s" case "iPhone7,1": modelName = "iPhone 6 Plus" case "iPhone7,2": modelName = "iPhone 6" case "iPhone8,1": modelName = "iPhone 6s" case "iPhone8,2": modelName = "iPhone 6s Plus" case "iPhone8,4": modelName = "iPhone SE (1st generation)" case "iPhone9,1", "iPhone9,3": modelName = "iPhone 7" case "iPhone9,2": modelName = "iPhone 7 Plus" case "iPhone10,1", "iPhone10,4": modelName = "iPhone 8" case "iPhone10,2", "iPhone10,5": modelName = "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": modelName = "iPhone X" case "iPhone11,2": modelName = "iPhone XS" case "iPhone11,4", "iPhone11,6": modelName = "iPhone XS Max" case "iPhone11,8": modelName = "iPhone XR" case "iPhone12,1": modelName = "iPhone 11" case "iPhone12,3": modelName = "iPhone 11 Pro" case "iPhone12,5": modelName = "iPhone 11 Pro Max" case "iPhone12,8": modelName = "iPhone SE (2nd generation)" case "iPhone13,1": modelName = "iPhone 12 mini" case "iPhone13,2": modelName = "iPhone 12" case "iPhone13,3": modelName = "iPhone 12 Pro" case "iPhone13,4": modelName = "iPhone 12 Pro Max" // iPod touch case "iPod1,1": modelName = "iPod touch" case "iPod2,1": modelName = "iPod touch (2nd generation)" case "iPod3,1": modelName = "iPod touch (3rd generation)" case "iPod4,1": modelName = "iPod touch (4th generation)" case "iPod5,1": modelName = "iPod touch (5th generation)" case "iPod7,1": modelName = "iPod touch (6th generation)" case "iPod9,1": modelName = "iPod touch (7th generation)" case "i386": modelName = base.model + "(i386)" case "x86_64": modelName = base.model + "(x86_64)" default: modelName = base.model } return modelName } var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let machine = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } return getDeviceModelName(machine: machine) } }
29.336158
91
0.381704
0ae2043278b1b1288eb5285d477b3f6db53411aa
1,829
// // Models.swift // DownloadKit // // Created by Moiz on 08/01/2019. // Copyright © 2019 Moiz Ullah. All rights reserved. // import Foundation /// Default completion handler for raw data downloads public typealias CompletionHandler = (Data?, Error?) -> Void /// A completion handler with a reference id which can be used to reference the handler public struct HandlerReference { let id: String let completion: CompletionHandler } /// The `DownloadKitTask` represents a download task created by `DownloadKit`. /// Each download task consists of a `URLSessionTask` generated by the `URLSession` utilised by `DownloadKit` /// and an array of `HandlerReference`s which contain the completion handlers associated to the task. public class DownloadKitTask { public let task: URLSessionTask public var handlers = [HandlerReference]() init(sessionTask: URLSessionTask, requestID: String, completion: CompletionHandler?) { self.task = sessionTask if completion != nil { self.handlers.append(HandlerReference(id: requestID, completion: completion!)) } } } /// The `RequestReference` is returned by the `DownloadKit` whenever a new request is made. /// It serves as a refrence for the caller, which can be utilized to cancel a request. public class RequestReference { public let request: URLRequest public let requestID: String init(request: URLRequest, requestID: String) { self.request = request self.requestID = requestID } } /// Custom Error types for `DownloadKit` /// /// - DataNotFound: For cases where the requested data is not found /// - CancelledByUser: For cases where the user cancels the request public enum DownloadKitErrors: Error { case DataNotFound case CancelledByUser case CancelledBySystem }
32.087719
109
0.721159
296ef2fbb5f8175615475691b6b067b1c286e2b3
2,647
// // Copyright (c) 2018 KxCoding <[email protected]> // // 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 /*: # Comparing Arrays */ let a = ["A", "B", "C"] let b = ["a", "b", "c"] // 개별요소 및 저장순서 비교. a == b // false. a.elementsEqual(b) // 위와 통일. false. a.elementsEqual(b) { (lhs, rhs) -> Bool in return lhs.caseInsensitiveCompare(rhs) == .orderedSame } // 대소문자 무시 비교. true. /*: # Finding Elements */ // 검색 let nums = [1, 2, 3, 1, 4, 5, 2, 6, 7, 5, 0] // 특정요소가 존재하는지 확인. nums.contains(1) // true. nums.contains(8) // false. // 짝수가 포함되어있는지 확인해보자. nums.contains { (n) -> Bool in return n % 2 == 0 } // true. // 직접 검색. nums.first { (n) -> Bool in return n % 2 == 0 } // 가장먼저 true를 리턴하는 요소를 return해준다. 2가 리턴. nums.firstIndex { (n) -> Bool in return n % 2 == 0 } // 가장 먼저 true를 리턴하는 요소의 Index를 리턴한다. 1이 리턴. nums.firstIndex(of: 1) // 가장먼저 1이 나올 때의, Index를 리턴. 0. nums.lastIndex(of: 1) // 뒤에서부터 1이나올떄의, Index를 리턴. 3. /*: # Sorting on Array */ // 정렬. // 1. 직접정렬. nums.sorted() // 오름차순으로 정렬해버림. 배열을 새로리턴해서 nums는 안바뀜. nums // 내림차순 정렬. // 1. 클로져를 통해, 정렬코드 구현. 항상 좌변이 우변보다 크게 하는걸 만족해야하게 만드나 보네. nums.sorted { (a, b) -> Bool in return a > b } // 2. 인벌스 nums.sorted().reversed() // reversedCollection을 리턴한다. 배열의 메모리를 공유하면서, 역순으로 정렬된걸 리턴해준다. // 역순으로 정렬된 새로운 배열을 생성하고 싶다면, 배열생성자로 만든다. [Int](nums.sorted().reversed()) // 가변배열의 정렬. var mutableNums = nums mutableNums.sort() // 배열을 직접 정렬해버림. mutableNums.reverse() // 리턴형 없다. 그냥 역순처리. // 특정 위치의 요소를 교체. mutableNums mutableNums.swapAt(0, 1) // index로 교체. // 랜덤으로 섞기. mutableNums.shuffle()
18.255172
86
0.661881
1d2fdbbd28ef189387cfcd32840dd0883c03e331
2,233
// // Service.swift // AfricasTalking // // Created by Salama Balekage on 07/12/2017. // import Foundation import Alamofire open class Service { internal static let PRODUCTION_DOMAIN = "africastalking.com" internal static let SANDBOX_DOMAIN = "sandbox.africastalking.com" internal static var HOST = "localhost" internal static var PORT = 35897 internal static var DISABLE_TLS = false internal static var USERNAME: String? = nil internal static var API_KEY: String? = nil internal static var AUTH_TOKEN: Africastalking_ClientTokenResponse? = nil internal static let GrpcClient: Africastalking_SdkServerServiceService = { let address = "\(Service.HOST):\(Service.PORT)" if (Service.DISABLE_TLS) { return Africastalking_SdkServerServiceService(address: address) } else { return Africastalking_SdkServerServiceService(address: address, certificates: "", host: Service.HOST) // FIXME } }() internal var baseUrl: String? = nil internal var isSandbox: Bool { get { return Service.USERNAME == "sandbox" } } internal var headers: HTTPHeaders { get { let authHeader = Service.API_KEY != nil ? "apiKey" : "authToken" var authValue = Service.API_KEY if (authValue == nil) { if (Service.AUTH_TOKEN == nil || Service.AUTH_TOKEN!.expiration < Date().millisecondsSince1970) { Service.fetchToken() } authValue = Service.AUTH_TOKEN?.token } return [ authHeader : authValue ?? "not set", "Accept": "application/json" ] } } init() { if (Service.API_KEY == nil && Service.AUTH_TOKEN == nil) { // init token Service.fetchToken() } } private static func fetchToken() { do { let req = Africastalking_ClientTokenRequest() Service.AUTH_TOKEN = try Service.GrpcClient.gettoken(req) Service.USERNAME = Service.AUTH_TOKEN?.username ?? nil } catch { } } }
30.175676
122
0.585311
d92ae4ae2c57181ec0f51031c08b8b40292b10bc
5,738
// // SessionManager.swift // NuguAgents // // Created by MinChul Lee on 2020/05/28. // Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import NuguCore import NuguUtils import RxSwift final public class SessionManager: SessionManageable { private let sessionDispatchQueue = DispatchQueue(label: "com.sktelecom.romaine.session", qos: .userInitiated) private lazy var sessionScheduler = SerialDispatchQueueScheduler( queue: sessionDispatchQueue, internalSerialQueueName: "com.sktelecom.romaine.session" ) /// Active sessions sorted chronologically. public var activeSessions = [Session]() { didSet { if oldValue != activeSessions { log.debug(activeSessions) } } } // private private var activeTimers = [String: Disposable]() private var sessions = [String: Session]() { didSet { updateActiveSession() } } private var activeList = [String: Set<CapabilityAgentCategory>]() { didSet { updateActiveSession() } } public init() {} public func set(session: Session) { sessionDispatchQueue.async { [weak self] in guard let self = self else { return } log.debug(session.dialogRequestId) self.sessions[session.dialogRequestId] = session self.addTimer(session: session) self.addActiveSession(dialogRequestId: session.dialogRequestId) self.post(NuguAgentNotification.Session.Set(session: session)) } } public func activate(dialogRequestId: String, category: CapabilityAgentCategory) { sessionDispatchQueue.async { [weak self] in guard let self = self else { return } log.debug(dialogRequestId) self.removeTimer(dialogRequestId: dialogRequestId) if self.activeList[dialogRequestId] == nil { self.activeList[dialogRequestId] = [] } self.activeList[dialogRequestId]?.insert(category) self.addActiveSession(dialogRequestId: dialogRequestId) } } public func deactivate(dialogRequestId: String, category: CapabilityAgentCategory) { sessionDispatchQueue.async { [weak self] in guard let self = self else { return } log.debug(dialogRequestId) self.activeList[dialogRequestId]?.remove(category) if self.activeList[dialogRequestId]?.count == 0 { self.activeList[dialogRequestId] = nil if let session = self.sessions[dialogRequestId] { self.addTimer(session: session) } } } } } private extension SessionManager { func addTimer(session: Session) { activeTimers[session.dialogRequestId] = Single<Int>.timer(SessionConst.sessionTimeout, scheduler: sessionScheduler) .subscribe(onSuccess: { [weak self] _ in log.debug("Timer fired. \(session.dialogRequestId)") self?.sessions[session.dialogRequestId] = nil self?.post(NuguAgentNotification.Session.UnSet(session: session)) }) } func removeTimer(dialogRequestId: String) { activeTimers[dialogRequestId]?.dispose() activeTimers[dialogRequestId] = nil } func addActiveSession(dialogRequestId: String) { guard let session = sessions[dialogRequestId], activeList[dialogRequestId] != nil else { return } activeSessions.removeAll { $0.dialogRequestId == dialogRequestId } activeSessions.append(session) } func updateActiveSession() { activeSessions.removeAll { (session) -> Bool in sessions[session.dialogRequestId] == nil || activeList[session.dialogRequestId] == nil } } } // MARK: - Observers extension Notification.Name { static let sessionDidSet = Notification.Name("com.sktelecom.romaine.notification.name.session_did_set") static let sessionDidUnSet = Notification.Name("com.sktelecom.romaine.notification.name.session_did_unset") } public extension NuguAgentNotification { enum Session { public struct Set: TypedNotification { public static let name: Notification.Name = .sessionDidSet public let session: NuguAgents.Session public static func make(from: [String: Any]) -> Set? { guard let session = from["session"] as? NuguAgents.Session else { return nil } return Set(session: session) } } public struct UnSet: TypedNotification { public static let name: Notification.Name = .sessionDidUnSet public let session: NuguAgents.Session public static func make(from: [String: Any]) -> UnSet? { guard let session = from["session"] as? NuguAgents.Session else { return nil } return UnSet(session: session) } } } }
35.202454
123
0.628791
902acf2f3a83754bfa7b31673ad62b354cd566d2
1,636
import XcodeServer import CoreDataPlus import Foundation #if canImport(CoreData) import CoreData //@objc(Filter) class Filter: NSManagedObject { } extension Filter { @nonobjc class func fetchRequest() -> NSFetchRequest<Filter> { return NSFetchRequest<Filter>(entityName: "Filter") } @NSManaged var architectureTypeRawValue: Int16 @NSManaged var filterTypeRawValue: Int16 @NSManaged var deviceSpecification: DeviceSpecification? @NSManaged var platform: Platform? } extension Filter { func update(_ filter: XcodeServer.Device.Filter, context: NSManagedObjectContext) { if platform == nil { InternalLog.persistence.debug("Creating PLATFORM for Filter") platform = context.make() } filterTypeRawValue = Int16(filter.type) architectureTypeRawValue = Int16(filter.architecture) platform?.update(filter.platform, context: context) } } extension XcodeServer.Device.Filter { init(_ filter: Filter) { self.init() if let platform = filter.platform { self.platform = XcodeServer.Device.Platform(platform) } type = Int(filter.filterTypeRawValue) architecture = Int(filter.architectureTypeRawValue) } } internal func == (lhs: Filter, rhs: XcodeServer.Device.Filter) -> Bool { guard Int(lhs.architectureTypeRawValue) == rhs.architecture else { return false } guard Int(lhs.filterTypeRawValue) == rhs.type else { return false } guard let p = lhs.platform, p == rhs.platform else { return false } return true } #endif
26.387097
87
0.674205
9132e6631de3a3f8e1277f0ffb240e205821d3d1
1,247
// // AppStoreUITests.swift // AppStoreUITests // // Created by Jameasy on 2018. 1. 2.. // Copyright © 2018년 kwanghyun.won. All rights reserved. // import XCTest class AppStoreUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.702703
182
0.661588
8a74b95d45825fb5dad7f5dfc93029ea9fc6e6fa
1,468
// // Schedules_XCTEST.swift // RsyncOSX // // Created by Thomas Evensen on 13/09/2019. // Copyright © 2019 Thomas Evensen. All rights reserved. // import Foundation class SchedulesXCTEST: Schedules { override func addschedule(hiddenID: Int, schedule: Scheduletype, start: Date) { var stop: Date? if schedule == .once { stop = start } else { stop = "01 Jan 2100 00:00".en_us_date_from_string() } let dict = NSMutableDictionary() let offsiteserver = self.configurations?.getResourceConfiguration(hiddenID, resource: .offsiteServer) dict.setObject(hiddenID, forKey: "hiddenID" as NSCopying) dict.setObject(start.en_us_string_from_date(), forKey: "dateStart" as NSCopying) dict.setObject(stop!.en_us_string_from_date(), forKey: "dateStop" as NSCopying) dict.setObject(offsiteserver as Any, forKey: "offsiteserver" as NSCopying) switch schedule { case .once: dict.setObject("once", forKey: "schedule" as NSCopying) case .daily: dict.setObject("daily", forKey: "schedule" as NSCopying) case .weekly: dict.setObject("weekly", forKey: "schedule" as NSCopying) } let newSchedule = ConfigurationSchedule(dictionary: dict, log: nil, nolog: true) self.schedules!.append(newSchedule) } override init(profile: String?) { super.init(profile: profile) } }
35.804878
109
0.64782
9cf7353dd6f5c9fe8b67617fe76a238f267f54c2
1,897
// // Array2D.swift // TreasureDungeons // // Created by Michael Rommel on 22.06.17. // Copyright © 2017 BurtK. All rights reserved. // import Foundation public class Array2D <T: Equatable> { fileprivate var columns: Int = 0 fileprivate var rows: Int = 0 fileprivate var array: Array<T?> = Array<T?>() public init(columns: Int, rows: Int) { self.columns = columns self.rows = rows self.array = Array<T?>(repeating: nil, count: rows * columns) } public subscript(column: Int, row: Int) -> T? { get { return array[(row * columns) + column] } set(newValue) { array[(row * columns) + column] = newValue } } public func columnCount() -> Int { return columns } public func rowCount() -> Int { return rows } } extension Array2D { subscript(point: Point) -> T? { get { return array[(point.y * columns) + point.x] } set(newValue) { array[(point.y * columns) + point.x] = newValue } } } extension Array2D { public func fill(with value: T) { for x in 0..<columns { for y in 0..<rows { self[x, y] = value } } } } extension Array2D: Sequence { public func makeIterator() -> Array2DIterator<T> { return Array2DIterator<T>(self) } } public struct Array2DIterator<T: Equatable>: IteratorProtocol { let array: Array2D<T> var index = 0 init(_ array: Array2D<T>) { self.array = array } mutating public func next() -> T? { let nextNumber = self.array.array.count - index guard nextNumber > 0 else { return nil } index += 1 return self.array.array[nextNumber] } }
20.397849
69
0.524512
5080710d9348ccf4421f8f0d0703349eb2afc522
306
// // MainState.swift // Couleur // // Created by HiDeo on 15/01/2020. // Copyright © 2020 HiDeoo. All rights reserved. // import Foundation import SwiftUI class PickerModel: ObservableObject { /** * The color at the center of the picker while picking. */ @Published var color: HSBColor? }
17
57
0.683007
eb54df45599441e55305f5d6aa3a87c430520798
1,527
// // Validator+Email.swift // QHValidator // // Created by Daniel Koster on 5/12/21. // import Foundation struct Predicates { /// General Email Regex (RFC 5322 Official Standard) (http://emailregex.com) static var emailPredicate: NSPredicate { let emailRegex = "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" + "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" + "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" + "z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" + "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" + "9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" + "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])" return NSPredicate(format: "SELF MATCHES %@", emailRegex) } /// 1 capital, 1 lower case letter, 1 number and 8 characters static var passwordPredicate: NSPredicate { let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$" return NSPredicate(format: "SELF MATCHES %@", passwordRegex) } } public extension Validator where Input == String { func isEmailAddress() -> Validator<String> { return match(pattern: Predicates.emailPredicate) } func isPassword() -> Validator<String> { return match(pattern: Predicates.passwordPredicate) } }
38.175
104
0.494434
5dace8cd8113ec2244cbfc43032ca1c9e441b4a0
2,595
// // Mastering iOS // Copyright (c) KxCoding <[email protected]> // // 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 class TextFieldOverlayViewViewController: UIViewController { @IBOutlet weak var inputField: UITextField! @objc func showPredefinedValue() { let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let one = UIAlertAction(title: "One", style: .default) { (action) in self.inputField.text = action.title } sheet.addAction(one) let two = UIAlertAction(title: "Two", style: .default) { (action) in self.inputField.text = action.title } sheet.addAction(two) let three = UIAlertAction(title: "Three", style: .default) { (action) in self.inputField.text = action.title } sheet.addAction(three) let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: nil) sheet.addAction(cancel) present(sheet, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() let btn = UIButton(type: .custom) btn.frame = CGRect(x: 0, y: 0, width: 20, height: 20) btn.setImage(#imageLiteral(resourceName: "menu"), for: .normal) btn.addTarget(self, action: #selector(showPredefinedValue), for: .touchUpInside) inputField.leftView = btn inputField.leftViewMode = .always } }
38.731343
93
0.665511
90b4443132350de7cf15754787cda14815f946f1
3,008
//===----------------------------------------------------------------------===// // // 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 // swift-tools-version:4.0 // // swift-tools-version:4.0 // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if canImport(Network) import Network import NIO /// A tag protocol that can be used to cover all network events emitted by `NIOTS`. /// /// Users are strongly encouraged not to conform their own types to this protocol. public protocol NIOTSNetworkEvent: Equatable { } public enum NIOTSNetworkEvents { /// This event is fired whenever the OS has informed NIO that there is a better /// path available to the endpoint that this `Channel` is currently connected to, /// e.g. the current connection is using an expensive cellular connection and /// a cheaper WiFi connection has become available. /// /// If you can handle this event, you should make a new connection attempt, and then /// transfer your work to that connection before closing this one. public struct BetterPathAvailable: NIOTSNetworkEvent { } /// This event is fired when the OS has informed NIO that no better path to the /// to the remote endpoint than the one currently being used by this `Channel` is /// currently available. public struct BetterPathUnavailable: NIOTSNetworkEvent { } /// This event is fired whenever the OS has informed NIO that a new path is in use /// for this `Channel`. public struct PathChanged: NIOTSNetworkEvent { /// The new path for this `Channel`. public let newPath: NWPath /// Create a new `PathChanged` event. public init(newPath: NWPath) { self.newPath = newPath } } /// This event is fired as an outbound event when NIO would like to ask Network.framework /// to handle the connection logic (e.g. its own DNS resolution and happy eyeballs racing). /// This is temporary workaround until NIO 2.0 which should allow us to use the regular /// `Channel.connect` method instead. public struct ConnectToNWEndpoint: NIOTSNetworkEvent { /// The endpoint to which we want to connect. public let endpoint: NWEndpoint } /// This event is fired as an outbound event when NIO would like to ask Network.framework /// to handle the binding logic (e.g. its own support for bonjour and interface selection). /// This is temporary workaround until NIO 2.0 which should allow us to use the regular /// `Channel.bind` method instead. public struct BindToNWEndpoint: NIOTSNetworkEvent { /// The endpoint to which we want to bind. public let endpoint: NWEndpoint } } #endif
41.777778
95
0.667886
e8b490e87679cf5098695c629ac7e44d6071099b
4,762
// // KPRippleLayer.swift // KPRippleAnimation // // Created By: Kushal Panchal, KP // Created on: 25/01/18 10:34 AM // // Copyright © 2017 KP. All rights reserved. // // import Foundation import UIKit class KPRippleLayer: CAReplicatorLayer { /* how to use : let rippleLayer = KPRippleLayer() rippleLayer.position = CGPoint(x: self.view.layer.bounds.midX, y: self.view.layer.bounds.midY) self.view.layer.addSublayer(rippleLayer) rippleLayer.startAnimation() */ // MARK: - Private Properties /// The Ripple Effect layer object private var rippleEffect: CALayer? /// The Animation Group Object private var animationGroup: CAAnimationGroup? // MARK: - Public Properties /// Radius of the Ripple. Default value is `100.0` public var rippleRadius: CGFloat = 100.0 /// Number of Ripple you wanted to show. Default value is `3` public var rippleCount: Int = 3 /// Color of the Ripple border. Default value is `UIColor.orange` public var rippleColor: UIColor = UIColor.orange /// Color of the Ripple Backgroud Color. Default value is `UIColor.yellow` public var rippleBackgroudColor: UIColor = UIColor.yellow /// Number of times you wanted to repeate the Ripple animation. Default value is `1000.0` public var rippleRepeatCount: CGFloat = 1000.0 /// Width of the Ripple border. Default value is `4` public var rippleWidth: CGFloat = 4 /// Default Init method override init() { super.init() setupRippleEffect() repeatCount = Float(rippleRepeatCount) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSublayers() { super.layoutSublayers() rippleEffect?.bounds = CGRect(x: 0, y: 0, width: rippleRadius*2, height: rippleRadius*2) rippleEffect?.cornerRadius = rippleRadius instanceCount = rippleCount instanceDelay = 0.45 } /// This method will start the ripple animation. /// /// let objRippleLayer = KPRippleLayer() /// objRippleLayer.position = CGPoint(x: view.layer.bounds.midX, y: view.layer.bounds.midY) /// view.layer.addSublayer(objRippleLayer) /// objRippleLayer.startAnimation() /// public func startAnimation() { setupAnimationGroup() rippleEffect?.add(animationGroup!, forKey: "ripple") } /// This method will stop the ripple animation. /// /// objRippleLayer.stopAnimation() /// public func stopAnimation() { rippleEffect?.removeAnimation(forKey: "ripple") } } extension KPRippleLayer { /// This method will create a object for Ripple Effect Layer private func setupRippleEffect() { rippleEffect = CALayer() rippleEffect?.borderWidth = CGFloat(rippleWidth) rippleEffect?.borderColor = rippleColor.cgColor rippleEffect?.backgroundColor = rippleBackgroudColor.withAlphaComponent(0.5).cgColor rippleEffect?.opacity = 0 addSublayer(rippleEffect!) } /// This method will create a Animation group private func setupAnimationGroup() { // Define animation duration. let animationDuration: CFTimeInterval = 3 // Create Animation Group. let group = CAAnimationGroup() group.duration = animationDuration group.repeatCount = self.repeatCount group.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) // Create scale Animation. let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy") scaleAnimation.fromValue = 0.0; scaleAnimation.toValue = 1.0; scaleAnimation.duration = animationDuration // Create alpha(opacity) Animation. let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.duration = animationDuration let fromAlpha = 1.0 opacityAnimation.values = [fromAlpha, (fromAlpha * 0.5), 0]; opacityAnimation.keyTimes = [0, 0.2, 1]; // Add animations to group. group.animations = [scaleAnimation, opacityAnimation] animationGroup = group; animationGroup!.delegate = self; } } extension KPRippleLayer: CAAnimationDelegate { func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if let count = rippleEffect?.animationKeys()?.count , count > 0 { rippleEffect?.removeAllAnimations() } } }
30.139241
103
0.634607
b98c3e639fa982afab66e08efc787dcb697e0bd3
6,464
import UIKit import RenderNeutrino func makePolygon() -> UINode<UIPolygonView> { // By using the create closure instead of the configuration one, the view settings are // applied only once. // - note: You need to specify a custom 'reuseIdentifier. return UINode<UIPolygonView>(reuseIdentifier: "polygon", create: { let view = UIPolygonView() view.foregroundColor = S.palette.white.color view.yoga.width = 44 view.yoga.height = 44 view.yoga.marginRight = S.margin.medium.cgFloat view.depthPreset = .depth1 return view }) } // MARK: - UIBezierPath // Forked from louisdh/bezierpath-polygons. extension UIBezierPath { private func addPointsAsRoundedPolygon(points: [CGPoint], cornerRadius: CGFloat) { lineCapStyle = .round usesEvenOddFillRule = true let len = points.count let prev = points[len - 1] let curr = points[0 % len] let next = points[1 % len] addPoint(prev: prev, curr: curr, next: next, cornerRadius: cornerRadius, first: true) for i in 0..<len { let p = points[i] let c = points[(i + 1) % len] let n = points[(i + 2) % len] addPoint(prev: p, curr: c, next: n, cornerRadius: cornerRadius, first: false) } close() } private func polygonPoints(sides: Int, x: CGFloat, y: CGFloat, radius: CGFloat) -> [CGPoint] { let angle = degreesToRadians(360 / CGFloat(sides)) let cx = x // x origin let cy = y // y origin let r = radius // radius of circle var i = 0 var points = [CGPoint]() while i < sides { let xP = cx + r * cos(angle * CGFloat(i)) let yP = cy + r * sin(angle * CGFloat(i)) points.append(CGPoint(x: xP, y: yP)) i += 1 } return points } private func addPoint(prev: CGPoint, curr: CGPoint, next: CGPoint, cornerRadius: CGFloat, first: Bool) { // prev <- curr var c2p = CGPoint(x: prev.x - curr.x, y: prev.y - curr.y) // next <- curr var c2n = CGPoint(x: next.x - curr.x, y: next.y - curr.y) // normalize let magP = sqrt(c2p.x * c2p.x + c2p.y * c2p.y) let magN = sqrt(c2n.x * c2n.x + c2n.y * c2n.y) c2p.x /= magP c2p.y /= magP c2n.x /= magN c2n.y /= magN // angles let ω = acos(c2n.x * c2p.x + c2n.y * c2p.y) let θ = (.pi / 2) - (ω / 2) let adjustedCornerRadius = cornerRadius / θ * (.pi / 4) // r tan(θ) let rTanTheta = adjustedCornerRadius * tan(θ) var startPoint = CGPoint() startPoint.x = curr.x + rTanTheta * c2p.x startPoint.y = curr.y + rTanTheta * c2p.y var endPoint = CGPoint() endPoint.x = curr.x + rTanTheta * c2n.x endPoint.y = curr.y + rTanTheta * c2n.y if !first { // Go perpendicular from start point by corner radius var centerPoint = CGPoint() centerPoint.x = startPoint.x + c2p.y * adjustedCornerRadius centerPoint.y = startPoint.y - c2p.x * adjustedCornerRadius let startAngle = atan2(c2p.x, -c2p.y) let endAngle = startAngle + (2 * θ) addLine(to: startPoint) addArc(withCenter: centerPoint, radius: adjustedCornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) } else { move(to: endPoint) } } } public extension UIBezierPath { @objc public convenience init(roundedRegularPolygon rect: CGRect, numberOfSides: Int, cornerRadius: CGFloat) { guard numberOfSides > 2 else { self.init() return } self.init() let points = polygonPoints(sides: numberOfSides, x: rect.width / 2, y: rect.height / 2, radius: min(rect.width, rect.height) / 2) self.addPointsAsRoundedPolygon(points: points, cornerRadius: cornerRadius) } } public extension UIBezierPath { @objc public func applyRotation(angle: CGFloat) { let bounds = self.cgPath.boundingBox let center = CGPoint(x: bounds.midX, y: bounds.midY) let toOrigin = CGAffineTransform(translationX: -center.x, y: -center.y) self.apply(toOrigin) self.apply(CGAffineTransform(rotationAngle: degreesToRadians(angle))) let fromOrigin = CGAffineTransform(translationX: center.x, y: center.y) self.apply(fromOrigin) } @objc public func applyScale(scale: CGPoint) { let center = CGPoint(x: bounds.midX, y: bounds.midY) let toOrigin = CGAffineTransform(translationX: -center.x, y: -center.y) apply(toOrigin) apply(CGAffineTransform(scaleX: scale.x, y: scale.y)) let fromOrigin = CGAffineTransform(translationX: center.x, y: center.y) apply(fromOrigin) } } public func degreesToRadians(_ value: Double) -> CGFloat { return CGFloat(value * .pi / 180.0) } public func degreesToRadians(_ value: CGFloat) -> CGFloat { return degreesToRadians(Double(value)) } public func radiansToDegrees(_ value: Double) -> CGFloat { return CGFloat((180.0 / .pi) * value) } public func radiansToDegrees(_ value: CGFloat) -> CGFloat { return radiansToDegrees(Double(value)) } @objc @IBDesignable public class UIPolygonView: UIView { public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { backgroundColor = .clear cornerRadius = 2 } @objc @IBInspectable public var rotation: CGFloat = 0.0 { didSet { self.setNeedsDisplay() } } @objc @IBInspectable public var foregroundColor: UIColor = .black { didSet { self.setNeedsDisplay() } } @objc @IBInspectable public var scale: CGPoint = CGPoint(x: 1, y: 1) { didSet { self.setNeedsDisplay() } } @objc @IBInspectable public var numberOfSides: Int = 6 { didSet { self.setNeedsDisplay() } } override public func draw(_ rect: CGRect) { let polygonPath = UIBezierPath(roundedRegularPolygon: rect, numberOfSides: numberOfSides, cornerRadius: cornerRadius) polygonPath.applyRotation(angle: rotation) polygonPath.applyScale(scale: scale) polygonPath.close() foregroundColor.setFill() polygonPath.fill() } public override func layoutSubviews() { super.layoutSubviews() clipsToBounds = true } }
31.531707
96
0.624845
1aad67adf190f373bd478be4559c1fc874b3dc3b
226
public class TextTag : TagType { public let text:String public init(text:String) { self.text = text } public func render(_ context:Context) throws -> String { return self.text } }
18.833333
60
0.588496
bfa6235c1c8a23d4a17a1b02b9e4fe29b2bc9bf6
391
// // Variables.swift // CalendarTexting // // Created by Jairo Millan on 8/20/19. // Copyright © 2019 Jairo Millan. All rights reserved. // import Foundation var date = Date() var date0 = date.date_0() let calendar = Calendar.current var month = calendar.component(.month, from: date) var year = calendar.component(.year, from: date) var monthCaracter = calendar.monthSymbols[month-1]
24.4375
55
0.726343
5d796bd8b9c55509443b4524de1cd5db693e5c45
847
import Vapor /// Custom Failures to throw in case of error. enum Failure: AbortError { case missingValidJson case notUnique case noOAuthTokensFound case requiredParamMissing(_ paramName: String) case invalidParam(_ paramName: String) case failed var reason: String { switch self { case .missingValidJson: return "A valid Json is missing." case .notUnique: return "Not unique." case .noOAuthTokensFound: return "Could not find any OAuth Tokens." case .requiredParamMissing(let paramName): return "Required parameter `\(paramName)` is missing." case .invalidParam(let paramName): return "Parameter `\(paramName)` is invalid for this request." case .failed: return "Failed" } } var status: HTTPResponseStatus { .badRequest } }
31.37037
105
0.668241
5d5c533b0d57f6bc1dfb3c1b4de02c41a9d77751
188
@testable import SuperbGitHub import Quick import Nimble final class SuperbGitHubSpec: QuickSpec { override func spec() { it("works") { expect(1 + 1).to(equal(2)) } } }
15.666667
41
0.654255
ed92120fedc425109310516b9a834d48acc93137
319
// // Actions.swift // ReSwiftThunkDemo // // Created by Mike Cole on 11/21/16. // Copyright © 2016 iOS Mike. All rights reserved. // import ReSwift struct ActionLogin: Action { } struct ActionLoginSuccess: Action { } struct ActionLoginFailure: Action { var error: String } struct ActionLogout: Action { }
13.869565
51
0.702194
1d54edbbce0cff9eadf0860d3d963205668179a4
8,539
// // This source file is part of the Apodini open source project // // SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]> // // SPDX-License-Identifier: MIT // // swiftlint:disable missing_docs // MARK: - Tree // swiftlint:disable syntactic_sugar /// `Tree.none` is to `Node`, what `[]` is to `Array` or `Set`. public typealias Tree<T> = Optional<Node<T>> // swiftlint:enable syntactic_sugar public extension Tree { var isEmpty: Bool { self == nil } } // MARK: - Node /// `Node` is a wrapper that enables values to be structured in a tree. public struct Node<T> { public let value: T public let children: [Node<T>] public init(value: T, children: [Node<T>]) { self.value = value self.children = children } } extension Node { /// Initializes an instance of `Node`. /// /// Initialize a `Node` tree from a data structure that already resembles a tree. /// - Parameters: /// - root: The value of the root node. /// - getChildren: Get node values for a parent's children, recursively. /// - Throws: Rethrows any error of `getChildren` public init(root: T, _ getChildren: (T) throws -> [T]) rethrows { let children = try getChildren(root).map { try Node(root: $0, getChildren) } self.init(value: root, children: children) } } // MARK: - Node higher-order functions extension Node { /// Returns a node containing the results of mapping the given closure over the node’s values. /// - Parameter transform: A mapping closure. `transform` accepts a value of this node as its /// parameter and returns a transformed value of the same or of a different type. /// - Returns: A node containing the transformed values of this node. public func map<U>(_ transform: (T) throws -> U) rethrows -> Node<U> { let value = try transform(self.value) let children = try self.children.compactMap { child in try child.map(transform) } return Node<U>(value: value, children: children) } /// Returns a node containing the non-nil results of calling the given transformation with each /// value of this node. /// /// The child of a node, that is nil, is also not contained. /// - Parameter transform: A closure that accepts a value of this node as its argument and /// returns an optional value. /// - Returns: A node of the non-nil results of calling transform with each value of the node. public func compactMap<U>(_ transform: (T) throws -> U?) rethrows -> Tree<U> { guard let value = try transform(self.value) else { return nil } let children = try self.children.compactMap { child in try child.compactMap(transform) } return Node<U>(value: value, children: children) } /// Returns a node containing the values that pass the predicate `isIncluded`. /// /// The child of a node, that is not included in the result, is also not included. /// - Parameter isIncluded: A closure that takes a value of the node as its argument and returns /// a Boolean value that indicates whether the passed value is included. /// - Returns: A tree of values that public func filter(_ isIncluded: (T) throws -> Bool) rethrows -> Tree<T> { guard try isIncluded(self.value) else { return nil } let children = try self.children.compactMap { child in try child.filter(isIncluded) } return Node(value: value, children: children) } /// Returns a Boolean value indicating whether the node contains a value that satisfies the /// given predicate. /// - Parameter predicate: A closure that takes a value of the node as its argument and returns /// a Boolean value that indicates whether the passed value represents a match. /// - Returns: `true` if the node contains a value that satisfies `predicate`; otherwise, /// `false`. public func contains(where predicate: (T) throws -> Bool) rethrows -> Bool { if try predicate(value) { return true } return try children.contains { child in try child.contains(where: predicate) } } /// Returns the result of combining the values of the node using the given closure. /// - Parameters: /// - nextPartialResult: A closure that combines the node's children values and the value of /// the node into a new accumulating value, to be used in the next call of the /// `nextPartialResult` closure or returned to the caller. /// - Returns: The final accumulated value. public func reduce<Result>(_ nextPartialResult: ([Result], T) throws -> Result) rethrows -> Result { let partialResults = try children.map { child in try child.reduce(nextPartialResult) } return try nextPartialResult(partialResults, value) } /// Calls the given closure on each value in the node. /// - Parameter body: A closure that takes a value of the node as a parameter. public func forEach(_ body: (T) throws -> Void) rethrows { _ = try map(body) } } public extension Node { /// Returns a tree edited by `transform`. Allows to modify the node freely with the information /// of a node and its children, but not the parent. /// /// Editing is performed from the root to the leafs. If a child is removed in the step of its /// parent, `transform` is no longer called with the child. /// - Parameter transform: A closure that accepts a node as its argument and returns a tree. A /// return value of `Tree.none` or `nil` is pruned from the tree. /// - Returns: A tree of the non-nil results of calling `transform` with each value of the node. func edited(_ transform: (Node<T>) throws -> Tree<T>) rethrows -> Tree<T> { guard let intermediate = try transform(self) else { return nil } let children = try intermediate.children.compactMap { child in try child.edited(transform) } return Node(value: intermediate.value, children: children) } /// Returns a node containing the results of mapping the given closure over the node. /// /// The exact arrangement of the node and its children is preserved. /// - Parameter transform: A mapping closure. `transform` accepts the node with all of its /// children as its parameter and returns a transformed value of the same or of a different type. /// - Returns: A node containing the transformed values of this node. func contextMap<U>(_ transform: (Node<T>) throws -> U) rethrows -> Node<U> { let value = try transform(self) let children = try self.children.map { child in try child.contextMap(transform) } return Node<U>(value: value, children: children) } /// Collect every value in the node. /// - Returns: A set of all values in the node. func collectValues() -> Set<T> where T: Hashable { reduce { partialResults, next in var set: Set = [next] for result in partialResults { set.formUnion(result) } return set } } /// Collect every element of an array that is a value in the node. /// - Returns: A set of all elements in the node that contains an array. func collectValues<U>() -> Set<U> where T == [U], U: Hashable { reduce { partialResults, next in var set = Set(next) for result in partialResults { set.formUnion(result) } return set } } } // MARK: - Node: CustomStringConvertible extension Node: CustomStringConvertible where T: CustomStringConvertible { private var lines: [Substring] { let children = self.children .map { child in child.lines .enumerated() .map { index, substring -> Substring in let prefix: Substring = index == 0 ? "→ " : " " return prefix + substring } } .flatMap { $0 } return value.description.split(separator: "\n") + children } public var description: String { lines.joined(separator: "\n") } }
37.783186
135
0.623024
237a864c9bc37f870f185027a7afb17c330aa899
2,953
// The MIT License (MIT) // Copyright © 2020 Ivan Vorobei ([email protected]) // // 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 /** SPDiffable: Basic diffable collection controller. For common init call `setCellProviders` with default data and providers for it models. If need init manually, shoud init `diffableDataSource` first, and next apply content when you need it. */ @available(iOS 13.0, *) open class SPDiffableCollectionController: UICollectionViewController { open var diffableDataSource: SPDiffableCollectionDataSource? // MARK: - Lifecycle open override func viewDidLoad() { super.viewDidLoad() collectionView.delaysContentTouches = false } // MARK: - Init /** SPDiffable: Init `diffableDataSource` and apply content to data source without animation. If need custom logic, you can manually init and apply data when you need. - warning: Changes applied not animatable. - parameter cellProviders: Cell providers with valid order for processing. - parameter headerFooterProviders: Header and Footer providers with valid order for processing. - parameter headerAsFirstCell: Flag for use header as cell or supplementary. - parameter sections: Content as array of `SPDiffableSection`. */ open func setCellProviders( _ cellProviders: [SPDiffableCollectionCellProvider], headerFooterProviders: [SPDiffableCollectionHeaderFooterProvider] = [], headerAsFirstCell: Bool = true, sections: [SPDiffableSection] ) { diffableDataSource = SPDiffableCollectionDataSource( collectionView: collectionView, cellProviders: cellProviders, headerFooterProviders: headerFooterProviders, headerAsFirstCell: headerAsFirstCell ) diffableDataSource?.apply(sections, animated: false) } }
42.185714
103
0.729766
fb49239b434f876df36f095b5d91983d726b6d4a
201
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var a{()as a class a<T where T:a
33.5
87
0.756219
ace172fae7fe9a6998a5ad0cb0ead09c07b81d9e
1,413
/// A value describing an instance of Swift source code that is considered invalid by a SwiftLint rule. public struct StyleViolation: CustomStringConvertible, Equatable, Codable { /// The description of the rule that generated this violation. public let ruleDescription: RuleDescription /// The severity of this violation. public let severity: ViolationSeverity /// The location of this violation. public let location: Location /// The justification for this violation. public let reason: String /// A printable description for this violation. public var description: String { return XcodeReporter.generateForSingleViolation(self) } /// Creates a `StyleViolation` by specifying its properties directly. /// /// - parameter ruleDescription: The description of the rule that generated this violation. /// - parameter severity: The severity of this violation. /// - parameter location: The location of this violation. /// - parameter reason: The justification for this violation. public init(ruleDescription: RuleDescription, severity: ViolationSeverity = .warning, location: Location, reason: String? = nil) { self.ruleDescription = ruleDescription self.severity = severity self.location = location self.reason = reason ?? ruleDescription.description } }
41.558824
103
0.701345
46bf82555a5e3f66614bee532010ec3034533f8a
622
//// //// MessageSM.swift //// //// //// Created by Vũ Quý Đạt on 25/04/2021. //// // //import Foundation //import Vapor //import MongoKitten // //struct MessageSM: Codable { // static let collection = "message" // // let _id: ObjectId // let text: String // let creationDate: Date // let fileId: ObjectId? // let creator: ObjectId //} // //struct ResolvedMessage: Codable { // let _id: ObjectId // let text: String // let creationDate: Date // let fileId: ObjectId? // let creator: UserSM //} // //struct CreateMessage: Codable { // let text: String // let file: Data? //}
18.294118
43
0.596463
9cb36bc495403ba627ddd8ecd2db441772661d5e
7,925
// RUN: %target-parse-verify-swift -enable-experimental-patterns -I %S/Inputs -enable-source-import import imported_enums // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int,Int), y: (Int,Int,Int)) -> Bool { return true } var x:Int func square(_ x: Int) -> Int { return x*x } struct A<B> { struct C<D> { } // expected-error{{generic type 'C' nested in type}} } switch x { // Expressions as patterns. case 0: () case 1 + 2: () case square(9): () // 'var' and 'let' patterns. case var a: a = 1 case let a: a = 1 // expected-error {{cannot assign}} case var var a: // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} a += 1 case var let a: // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} print(a, terminator: "") case var (var b): // expected-error {{'var' cannot appear nested inside another 'var'}} b += 1 // 'Any' pattern. case _: () // patterns are resolved in expression-only positions are errors. case 1 + (_): // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} () } switch (x,x) { case (var a, var a): // expected-error {{definition conflicts with previous value}} expected-note {{previous definition of 'a' is here}} fallthrough case _: () } var e : protocol<> = 0 switch e { // 'is' pattern. case is Int, is A<Int>, is A<Int>.C<Int>, is (Int, Int), is (a: Int, b: Int): () } // Enum patterns. enum Foo { case A, B, C } func == <T>(_: Voluntary<T>, _: Voluntary<T>) -> Bool { return true } enum Voluntary<T> : Equatable { case Naught case Mere(T) case Twain(T, T) func enumMethod(_ other: Voluntary<T>, foo: Foo) { switch self { case other: () case .Naught, .Naught(), .Naught(_, _): // expected-error{{tuple pattern has the wrong length for tuple type '()'}} () case .Mere, .Mere(), // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}} .Mere(_), .Mere(_, _): // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}} () case .Twain(), // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}} .Twain(_), .Twain(_, _), .Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}} () } switch foo { case .Naught: // expected-error{{enum case 'Naught' not found in type 'Foo'}} () case .A, .B, .C: () } } } var n : Voluntary<Int> = .Naught switch n { case Foo.A: // expected-error{{enum case 'A' is not a member of type 'Voluntary<Int>'}} () case Voluntary<Int>.Naught, Voluntary<Int>.Naught(), Voluntary<Int>.Naught(_, _), // expected-error{{tuple pattern has the wrong length for tuple type '()'}} Voluntary.Naught, .Naught: () case Voluntary<Int>.Mere, Voluntary<Int>.Mere(_), Voluntary<Int>.Mere(_, _), // expected-error{{tuple pattern cannot match values of the non-tuple type 'Int'}} Voluntary.Mere, Voluntary.Mere(_), .Mere, .Mere(_): () case .Twain, .Twain(_), .Twain(_, _), .Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(Int, Int)'}} () } var notAnEnum = 0 switch notAnEnum { case .Foo: // expected-error{{enum case 'Foo' not found in type 'Int'}} () } struct ContainsEnum { enum Possible<T> { // expected-error{{generic type 'Possible' nested in type}} case Naught case Mere(T) case Twain(T, T) } func member(_ n: Possible<Int>) { switch n { case ContainsEnum.Possible<Int>.Naught, ContainsEnum.Possible.Naught, Possible<Int>.Naught, Possible.Naught, .Naught: () } } } func nonmemberAccessesMemberType(_ n: ContainsEnum.Possible<Int>) { switch n { case ContainsEnum.Possible<Int>.Naught, .Naught: () } } var m : ImportedEnum = .Simple switch m { case imported_enums.ImportedEnum.Simple, ImportedEnum.Simple, .Simple: () case imported_enums.ImportedEnum.Compound, imported_enums.ImportedEnum.Compound(_), ImportedEnum.Compound, ImportedEnum.Compound(_), .Compound, .Compound(_): () } // Check that single-element tuple payloads work sensibly in patterns. enum LabeledScalarPayload { case Payload(name: Int) } var lsp: LabeledScalarPayload = .Payload(name: 0) func acceptInt(_: Int) {} func acceptString(_: String) {} switch lsp { case .Payload(0): () case .Payload(name: 0): () case let .Payload(x): acceptInt(x) acceptString("\(x)") case let .Payload(name: x): acceptInt(x) acceptString("\(x)") case let .Payload((name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let (name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let (name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let x): acceptInt(x) acceptString("\(x)") case .Payload((let x)): acceptInt(x) acceptString("\(x)") } // Property patterns. struct S { static var stat: Int = 0 var x, y : Int var comp : Int { return x + y } func nonProperty() {} } struct T {} var s: S switch s { case S(): () case S(stat: _): // expected-error{{cannot match type property 'stat' of type 'S' in a 'case' pattern}} () case S(x: 0, y: 0, comp: 0): () case S(w: 0): // expected-error{{property 'w' not found in type 'S'}} () case S(nonProperty: 0): // expected-error{{member 'nonProperty' of type 'S' is not a property}} () case S(0): // expected-error{{subpattern of a struct or class pattern must have a keyword name}} () case S(x: 0, 0): // expected-error{{subpattern of a struct or class pattern must have a keyword name}} () case T(): // expected-error{{type 'T' of pattern does not match deduced type 'S'}} () } struct SG<A> { var x: A } var sgs: SG<S> switch sgs { case SG(x: S()): () case SG<S>(x: S()): () case SG<T>(x: T()): // expected-error{{type 'SG<T>' of pattern does not match deduced type 'SG<S>'}} () } func sg_generic<B : Equatable>(_ sgb: SG<B>, b: B) { switch sgb { case SG(x: b): () } } typealias NonNominal = (foo: Int, bar: UnicodeScalar) var nn = NonNominal.self switch nn { case NonNominal(): // expected-error{{non-nominal type 'NonNominal' (aka '(foo: Int, bar: UnicodeScalar)') cannot be used with property pattern syntax}} () } // Tuple patterns. var t = (1, 2, 3) prefix operator +++ {} infix operator +++ {} prefix func +++(x: (Int,Int,Int)) -> (Int,Int,Int) { return x } func +++(x: (Int,Int,Int), y: (Int,Int,Int)) -> (Int,Int,Int) { return (x.0+y.0, x.1+y.1, x.2+y.2) } switch t { case (_, var a, 3): a += 1 case var (_, b, 3): b += 1 case var (_, var c, 3): // expected-error{{'var' cannot appear nested inside another 'var'}} c += 1 case (1, 2, 3): () // patterns in expression-only positions are errors. case +++(_, var d, 3): // expected-error{{invalid pattern}} () case (_, var e, 3) +++ (1, 2, 3): // expected-error{{invalid pattern}} () } // FIXME: We don't currently allow subpatterns for "isa" patterns that // require interesting conditional downcasts. class Base { } class Derived : Base { } switch [Derived(), Derived(), Base()] { case let ds as [Derived]: // expected-error{{downcast pattern value of type '[Derived]' cannot be used}} () default: () } // Optional patterns. let op1 : Int? = nil let op2 : Int?? = nil switch op1 { case nil: break case 1?: break case _?: break } switch op2 { case nil: break case _?: break case (1?)?: break case (_?)?: break } // <rdar://problem/20365753> Bogus diagnostic "refutable pattern match can fail" let (responseObject: Int?) = op1 // expected-error @-1 2 {{expected ',' separator}} {{25-25=,}} {{25-25=,}} // expected-error @-2 {{expected pattern}}
22.136872
152
0.615016
b97cc9b66faf0c69438b2d63bbd4d9754fed61ad
873
// // SQLiteOrderBy.swift // Swift Toolbox // // Created by Stevo on 7/23/20. // Copyright © 2020 Stevo Brock. All rights reserved. // //---------------------------------------------------------------------------------------------------------------------- // MARK: SQLiteOrderBy public class SQLiteOrderBy { // MARK: Types public enum Order { case ascending case descending } // MARK: Properties let string :String // MARK: Lifecycle methods //------------------------------------------------------------------------------------------------------------------ public init(table :SQLiteTable? = nil, tableColumn :SQLiteTableColumn, order :Order = .ascending) { // Setup self.string = " ORDER BY " + ((table != nil) ? "`\(table!.name)`.`\(tableColumn.name)`" : "`\(tableColumn.name)`") + ((order == .ascending) ? " ASC" : " DESC") } }
27.28125
120
0.455899
dbfe17b7765da0192666101ccf27ddf5e8ca5f6a
2,023
import Foundation import StoreKit struct SKProductWrapperKeys { static let localizedDescription = "description" static let localizedTitle = "title" static let price = "price" static let priceNumeric = "priceNumeric" static let currencyCode = "currencyCode" static let productIdentifier = "productIdentifier" static let isDownloadable = "isDownloadable" static let downloadContentLengths = "downloadContentLengths" static let contentVersion = "contentVersion" static let downloadContentVersion = "downloadContentVersion" static let subscriptionPeriod = "subscriptionPeriod" static let productType = "productType" } extension SKProduct { class func wrappProducts(products: [SKProduct]) -> [[String: Any]] { products.map { wrappProductToDictionary(product: $0) } } class func wrappProductToDictionary(product: SKProduct) -> [String: Any] { var retVal: [String: Any] = [:] retVal[SKProductWrapperKeys.localizedDescription] = product.localizedDescription retVal[SKProductWrapperKeys.localizedTitle] = product.localizedTitle retVal[SKProductWrapperKeys.price] = product.localizedPrice() retVal[SKProductWrapperKeys.productIdentifier] = product.productIdentifier retVal[SKProductWrapperKeys.isDownloadable] = product.isDownloadable retVal[SKProductWrapperKeys.downloadContentLengths] = product.downloadContentLengths retVal[SKProductWrapperKeys.contentVersion] = product.contentVersion retVal[SKProductWrapperKeys.downloadContentVersion] = product.downloadContentVersion retVal[SKProductWrapperKeys.priceNumeric] = product.price retVal[SKProductWrapperKeys.currencyCode] = product.priceLocale.currencyCode return retVal } func localizedPrice() -> String? { let priceFormatter = NumberFormatter() priceFormatter.numberStyle = .currency priceFormatter.locale = priceLocale return priceFormatter.string(from: price) } }
43.042553
92
0.744933
69a07c5f6dce70a405e8c6254474f3c6de9e35e8
7,620
import XCTest import Perfidy class ServerTests: XCTestCase { func testTimeout() { let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 1.0 let quickTimeoutSession = URLSession(configuration: config) let shouldTimeOut = expectation(description: "times out") FakeServer.runWith { server in server.add("/", response: 666) quickTimeoutSession.resumeRequest("GET", "/") { _, _, error in guard let someError = error as NSError? else { XCTFail() return } XCTAssertEqual(someError.code, URLError.timedOut.rawValue) XCTAssertEqual(someError.domain, URLError.errorDomain) shouldTimeOut.fulfill() } wait(for: [shouldTimeOut], timeout: 2) } } func testDefaultShouldConnect(){ let expectResponse = expectation(description: "Response received.") FakeServer.runWith { _ in session.resumeRequest("GET", "/") { data, res, error in XCTAssertEqual(res!.statusCode, 404) expectResponse.fulfill() } wait(for: [expectResponse], timeout: 1) } } func testShouldErrorOnDuplicateConnections(){ let shouldThrow = expectation(description: "Should throw") FakeServer.runWith { server in do { try server.start() } catch NetworkError.portAlreadyInUse(let port) { XCTAssertEqual(port, 10175) shouldThrow.fulfill() } catch { XCTFail() } wait(for: [shouldThrow], timeout: 2) } } func testStatusCodes(){ let expect201 = expectation(description: "201 status code") let expect300 = expectation(description: "300 status code") let expect400 = expectation(description: "400 status code") let expect800 = expectation(description: "Nonexistant status code") FakeServer.runWith { server in server.add("/201", response: 201) server.add("/300", response: 300) server.add("/400", response: 400) server.add("/800", response: 800) session.resumeRequest("GET", "/201") { _, res, _ in XCTAssertEqual(res!.statusCode, 201) expect201.fulfill() } session.resumeRequest("GET", "/300") { _, res, _ in XCTAssertEqual(res!.statusCode, 300) expect300.fulfill() } session.resumeRequest("GET", "/400") { _, res, _ in XCTAssertEqual(res!.statusCode, 400) expect400.fulfill() } session.resumeRequest("GET", "/800") { _, res, _ in XCTAssertEqual(res!.statusCode, 800) expect800.fulfill() } wait(for: [expect201, expect300, expect400, expect800], timeout: 1) } } func testSetDefaultStatusCode(){ let shouldBurn = expectation(description: "should implicitly return `defaultStatusCode` when no response given") FakeServer.runWith(defaultStatusCode: 541) { server in session.resumeRequest("GET", "/foo/bar/baz") { _, res, _ in XCTAssertEqual(res!.statusCode, 541) shouldBurn.fulfill() } wait(for: [shouldBurn], timeout: 1) } } func testDefaultStatusCodeOfAddedRoute() { let should200 = expectation(description: "routes without status codes are assumed to be 200") FakeServer.runWith { server in server.add("/real/route") session.resumeRequest("GET", "/real/route") { _, res, _ in XCTAssertEqual(res!.statusCode, 200) should200.fulfill() } wait(for: [should200], timeout: 1) } } func testHeaders() { let shouldReceive = expectation(description: "receive request with header") let shouldRespond = expectation(description: "respond") FakeServer.runWith { server in server.add("/", response: 200) { req in XCTAssertEqual(req.value(forHTTPHeaderField: "foo"), "bar") shouldReceive.fulfill() } session.resumeRequest("GET", "/", headers: ["foo": "bar"]) { _, res, error in XCTAssertNil(error) XCTAssertEqual(res!.statusCode, 200) shouldRespond.fulfill() } wait(for: [shouldReceive, shouldRespond], timeout: 1) } } func testRawJSONResponse(){ let expectedResponse = expectation(description: "Should get response") FakeServer.runWith { server in server.add("/path", response: try! Response(status: 201, rawJSON:"{\"thing\":42}")) session.resumeRequest("GET", "/path") { data, res, _ in XCTAssertEqual(res?.statusCode, 201) let json = try! JSONDecoder().decode([String: Int].self, from: data!) XCTAssertEqual(json["thing"], 42) expectedResponse.fulfill() } wait(for: [expectedResponse], timeout: 1) } } func testJSONObjectResponse(){ let expectedResponse = expectation(description: "Should get response") FakeServer.runWith { server in server.add("/path", response: try! Response(status: 202, jsonObject:["fred":"barney"])) session.resumeRequest("GET", "/path") { data, res, _ in XCTAssertEqual(res!.statusCode, 202) let json = try! JSONDecoder().decode([String: String].self, from: data!) XCTAssertEqual(json["fred"], "barney") expectedResponse.fulfill() } wait(for: [expectedResponse], timeout: 1) } } func testJSONArrayResponse(){ let expectResponse = expectation(description: "Should get response") FakeServer.runWith { server in server.add("/some/path", response: try! Response(status: 203, jsonArray:["fred","barney"])) session.resumeRequest("GET", "/some/path") { data, res, _ in XCTAssertEqual(res!.statusCode, 203) let json = try! JSONDecoder().decode([String].self, from: data!) XCTAssertEqual(json, ["fred","barney"]) expectResponse.fulfill() } wait(for: [expectResponse], timeout: 1) } } func testPostingData() { let expectSent = expectation(description: "Sent data") let expectReceived = expectation(description: "Received data") FakeServer.runWith { server in server.add("POST /") { req in XCTAssertEqual(String(data: req.httpBody!, encoding: .utf8), "{\"foo\":\"bar\"}") expectReceived.fulfill() } let data = try! JSONEncoder().encode(["foo": "bar"]) session.resumeRequest("POST", "/", body: data) { _, _, _ in expectSent.fulfill() } wait(for: [expectSent, expectReceived], timeout: 1) } } func testDefaultURL() { XCTAssertEqual(FakeServer.defaultURL.absoluteString, "http://localhost:10175") } func testFakeServerURL() { FakeServer.runWith(port: 11111) { server in XCTAssertEqual(server.url.absoluteString, "http://localhost:11111") } } func testFakeServerListensOnCustomPort() { let answerOnCustomPort = expectation(description: "should answer on custom port") let defaulPortStillOpen = expectation(description: "default port is still available") FakeServer.runWith(port: 11111, defaultStatusCode: 200) { _ in session.dataTask(with: URL(string: "http://localhost:11111/foo")!) { data, res, error in XCTAssertNil(error) XCTAssertEqual((res as? HTTPURLResponse)?.statusCode, 200) answerOnCustomPort.fulfill() let server = FakeServer() defer { server.stop() } do { try server.start() defaulPortStillOpen.fulfill() } catch { XCTFail() } }.resume() wait(for: [answerOnCustomPort, defaulPortStillOpen], timeout: 1) } } }
29.420849
116
0.627428
6965842b6c7db4c214deb1787397fc5a634d68e8
10,482
// // AppDelegate.swift // notatod // // Created by utsman on 03/03/21. // // import Cocoa import SwiftUI import KeyboardShortcuts @main class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate { let userDefaultController = UserDefaultController() let featureApiController = FeatureApiController() var cloudApi: CloudApi? = nil var cloudUserDefault: CloudUserDefault? = nil let startingViewModel = StartingViewModel() var authViewModel: AuthViewModel! var mainViewModel: MainViewModel! var statusBarItem: NSStatusItem! var popover: NSPopover! var preferencesWindow: NSWindow! var accountWindow: NSWindow! var startingWindow: NSWindow! typealias UserNotification = NSUserNotification typealias UserNotificationCenter = NSUserNotificationCenter let UserNotificationDefaultSoundName = NSUserNotificationDefaultSoundName func applicationDidFinishLaunching(_ aNotification: Notification) { for (key, value) in UserDefaults.standard.dictionaryRepresentation() { if key.contains(UserDefaultController.TAG) { log("\n\(key) : \n\(value) \n") } } openStartingWindow() checkUpdateAvailable() setupCloudApiFeature { authEnable in self.setupInit(authType: authEnable) } setupKeyboardShortcut() } private func setupInit(authType: AuthType) { authViewModel = AuthViewModel(cloudApi: cloudApi) mainViewModel = MainViewModel(cloudApi: cloudApi) authViewModel.authType = authType authViewModel.checkSession { entity in self.mainViewModel.hasLogon = entity != nil self.mainViewModel.searchFileInDrive() } let contentView = ContentView() .environmentObject(mainViewModel) UserNotificationCenter.default.delegate = self statusBarItem = NSStatusBar.system.statusItem(withLength: 28) let popover = NSPopover() if userDefaultController.popoverWindowSize() == 2 { popover.contentSize = NSSize(width: 1000, height: 600) } else { popover.contentSize = NSSize(width: 800, height: 400) } popover.behavior = .transient popover.contentViewController = NSHostingController(rootView: contentView) self.popover = popover self.popover.appearance = userDefaultController.theme() if let button = statusBarItem.button { button.image = #imageLiteral(resourceName: "AppIcon") button.image?.size = NSSize(width: 22, height: 22) button.action = #selector(togglePopover(_:)) } DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { self.startingViewModel.isReady = true } NSApp.activate(ignoringOtherApps: true) } func checkUpdateAvailable() { featureApiController.checkUpdateAvailable { os in if self.mainViewModel != nil && self.authViewModel != nil { let isUpdateAvailable = NSApplication.shared.AppVersionInt! < os.versionCode self.mainViewModel.isUpdateAvailable = isUpdateAvailable self.mainViewModel.version = os } } } func setupCloudApiFeature(authType: @escaping (AuthType) -> ()) { featureApiController.authServiceEnable { featureEnable in self.userDefaultController.saveAuthType(authType: featureEnable) switch featureEnable { case .google: self.cloudApi = GDriveController() self.cloudUserDefault = GoogleUserDefault() case .dropbox: self.cloudApi = DropboxController() self.cloudUserDefault = DropboxUserDefault() case .disable: self.cloudApi = nil self.cloudUserDefault = nil } DispatchQueue.main.async { authType(featureEnable) } } } func applicationWillTerminate(_ aNotification: Notification) { userDefaultController.saveNotes(notes: mainViewModel.notes) log("quit...") } func setupKeyboardShortcut() { KeyboardShortcuts.onKeyUp(for: .openNote) { self.togglePopover(nil) } KeyboardShortcuts.onKeyUp(for: .newNote) { self.mainViewModel.addNewNote() self.togglePopover(nil) } KeyboardShortcuts.onKeyUp(for: .saveNote) { self.mainViewModel.userDefault.saveNotes(notes: self.mainViewModel.notes) if self.mainViewModel.hasLogon == true { self.mainViewModel.uploadToDrive { b in var message = "" if b { message = "Upload to Drive success" } else { message = "Upload to Drive failed!" } self.showNotification(message: message) } } else { self.showNotification(message: "Success saved on local") } } } func application(_ application: NSApplication, open urls: [URL]) { cloudApi?.getTokenResponse(using: urls[0]) { result in result.doOnSuccess { entity in log(entity.accessToken) self.cloudUserDefault?.saveAccessToken(token: entity.accessToken) self.cloudUserDefault?.saveAccountId(accountId: entity.profileId) self.showNotification(message: "Account linked") self.authViewModel.checkSession { entity in self.mainViewModel.hasLogon = entity != nil self.mainViewModel.searchFileInDrive() } } result.doOnFailure { error in log("reason --> \(error.localizedDescription)") self.showNotification(message: "Account failed") } } } @objc func togglePopover(_ sender: AnyObject?) { if mainViewModel != nil && authViewModel != nil { mainViewModel.setLocalNotes() if let button = statusBarItem.button { if popover.isShown { popover.performClose(sender) } else { popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY) } } } } func showNotification(message: String) { log("show notification...") let notification: UserNotification = UserNotification() notification.title = "Account" notification.informativeText = message notification.soundName = UserNotificationDefaultSoundName UserNotificationCenter.default.deliver(notification) } func openStartingWindow() { if startingWindow == nil { let startingView = StartingView() .environmentObject(startingViewModel) let windowView = NSHostingController(rootView: startingView) startingWindow = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 500, height: 300), styleMask: [.titled, .closable], backing: .buffered, defer: false) startingWindow.title = "notatod!" startingWindow.center() startingWindow.setFrameAutosaveName("Preferences") startingWindow.isReleasedWhenClosed = false startingWindow.contentView = windowView.view startingWindow.appearance = userDefaultController.theme() } startingWindow.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) } func openPreferencesWindow() { checkUpdateAvailable() userDefaultController.saveNotes(notes: mainViewModel.notes) if preferencesWindow == nil { let preferencesView = PreferencesView() .environmentObject(authViewModel) .environmentObject(mainViewModel) let windowView = NSHostingController(rootView: preferencesView) preferencesWindow = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled, .closable], backing: .buffered, defer: false) preferencesWindow.title = "Preferences" preferencesWindow.center() preferencesWindow.setFrameAutosaveName("Preferences") preferencesWindow.isReleasedWhenClosed = false preferencesWindow.contentView = windowView.view preferencesWindow.appearance = userDefaultController.theme() } preferencesWindow.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) } func openAccountWindow() { checkUpdateAvailable() userDefaultController.saveNotes(notes: mainViewModel.notes) if accountWindow == nil { let accountView = AccountView() .frame(width: 480, height: 300) .environmentObject(authViewModel) let windowView = NSHostingController(rootView: accountView) accountWindow = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 480, height: 300), styleMask: [.titled, .closable], backing: .buffered, defer: false) accountWindow.title = "Account" accountWindow.center() accountWindow.setFrameAutosaveName("Account") accountWindow.isReleasedWhenClosed = false accountWindow.contentView = windowView.view accountWindow.appearance = userDefaultController.theme() } accountWindow.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) } func changeThemeNow() { popover.appearance = userDefaultController.theme() preferencesWindow.appearance = userDefaultController.theme() } func changeSize() { if userDefaultController.popoverWindowSize() == 1 { popover.contentSize = NSSize(width: 1000, height: 600) userDefaultController.savePopoverWindow(typeSize: 2) } else { popover.contentSize = NSSize(width: 800, height: 400) userDefaultController.savePopoverWindow(typeSize: 1) } } }
36.020619
103
0.613051
ede75bd85d4fb776e2ded931e7a9c04d7f406288
4,437
// // AppDelegate.swift // ToDoList // // Created by Burak Firik on 11/29/17. // Copyright © 2017 Code Path. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "ToDoList") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
47.202128
281
0.71039
f44883c8ef0c5550e0bccc5a829700b8bf9d677a
349
import XCTest @testable import MagicTimer final class MagicTimerTests: 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(MagicTimer().text, "Hello, World!") } }
29.083333
87
0.681948
b97bfd433130bb02cbe039d4448525c58a4f59c4
2,254
// // Copyright © 2021 osy. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SwiftUI @available(macOS 12, *) struct VMConfigAppleDriveCreateView: View { private let mibToGib = 1024 let minSizeMib = 1 @Binding var driveSize: Int @State private var isGiB: Bool = true var body: some View { Form { HStack { NumberTextField("Size", number: Binding<NSNumber?>(get: { NSNumber(value: convertToDisplay(fromSizeMib: driveSize)) }, set: { driveSize = convertToMib(fromSize: $0?.intValue ?? 0) }), onEditingChanged: validateSize) .multilineTextAlignment(.trailing) Button(action: { isGiB.toggle() }, label: { Text(isGiB ? "GB" : "MB") .foregroundColor(.blue) }).buttonStyle(PlainButtonStyle()) } } } private func validateSize(editing: Bool) { guard !editing else { return } if driveSize < minSizeMib { driveSize = minSizeMib } } private func convertToMib(fromSize size: Int) -> Int { if isGiB { return size * mibToGib } else { return size } } private func convertToDisplay(fromSizeMib sizeMib: Int) -> Int { if isGiB { return sizeMib / mibToGib } else { return sizeMib } } } @available(macOS 12, *) struct VMConfigAppleDriveCreateView_Previews: PreviewProvider { static var previews: some View { VMConfigAppleDriveCreateView(driveSize: .constant(100)) } }
29.657895
77
0.587844
eb4551e7b8aa3d47871b025f12925e9a0ea4b37e
2,448
// // SceneDelegate.swift // TabControllerNavigation // // Created by Mac on 11.01.2020. // Copyright © 2020 Lammax. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow(windowScene: windowScene) let storyboard = UIStoryboard(name: "Main", bundle: nil) // let nc = storyboard.instantiateViewController(withIdentifier: "NC14") as! UINavigationController let vc = storyboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController // nc.pushViewController(vc, animated: true) window?.rootViewController = vc window?.makeKeyAndVisible() } 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. } }
40.131148
141
0.706291
62f15de98fc43962e8ac7dfba3c45fb81120d480
16,091
import Foundation import Stencil import PathKit import StencilSwiftKit import SourceryFramework import SourceryRuntime final class StencilTemplate: StencilSwiftKit.StencilSwiftTemplate, SourceryFramework.Template { private(set) var sourcePath: Path = "" convenience init(path: Path) throws { self.init(templateString: try path.read(), environment: StencilTemplate.sourceryEnvironment(templatePath: path)) sourcePath = path } convenience init(templateString: String) { self.init(templateString: templateString, environment: StencilTemplate.sourceryEnvironment()) } func render(_ context: TemplateContext) throws -> String { do { var stencilContext = context.stencilContext ObjectBoxGenerator.exposeObjects(to: &stencilContext) return try super.render(stencilContext) } catch { throw "\(sourcePath): \(error)" } } private static func sourceryEnvironment(templatePath: Path? = nil) -> Stencil.Environment { let ext = Stencil.Extension() ext.registerFilter("json") { (value, arguments) -> Any? in guard let value = value else { return nil } guard arguments.isEmpty || arguments.count == 1 && arguments.first is Bool else { throw TemplateSyntaxError("'json' filter takes a single boolean argument") } var options: JSONSerialization.WritingOptions = [] let prettyPrinted = arguments.first as? Bool ?? false if prettyPrinted { options = [.prettyPrinted] } let data = try JSONSerialization.data(withJSONObject: value, options: options) return String(data: data, encoding: .utf8) } ext.registerStringFilters() ext.registerBoolFilter("definedInExtension", filter: { (t: Definition) in t.definedInType?.isExtension ?? false }) ext.registerBoolFilter("computed", filter: { (v: SourceryVariable) in v.isComputed && !v.isStatic }) ext.registerBoolFilter("stored", filter: { (v: SourceryVariable) in !v.isComputed && !v.isStatic }) ext.registerBoolFilter("tuple", filter: { (v: SourceryVariable) in v.isTuple }) ext.registerBoolFilter("optional", filter: { (m: SourceryVariable) in m.isOptional }) ext.registerAccessLevelFilters(.open) ext.registerAccessLevelFilters(.public) ext.registerAccessLevelFilters(.private) ext.registerAccessLevelFilters(.fileprivate) ext.registerAccessLevelFilters(.internal) ext.registerBoolFilterOrWithArguments("based", filter: { (t: Type, name: String) in t.based[name] != nil }, other: { (t: Typed, name: String) in t.type?.based[name] != nil }) ext.registerBoolFilterOrWithArguments("implements", filter: { (t: Type, name: String) in t.implements[name] != nil }, other: { (t: Typed, name: String) in t.type?.implements[name] != nil }) ext.registerBoolFilterOrWithArguments("inherits", filter: { (t: Type, name: String) in t.inherits[name] != nil }, other: { (t: Typed, name: String) in t.type?.inherits[name] != nil }) ext.registerBoolFilterOrWithArguments("extends", filter: { (t: Type, name: String) in t.isExtension && t.name == name }, other: { (t: Typed, name: String) in guard let type = t.type else { return false }; return type.isExtension && type.name == name }) ext.registerBoolFilter("extension", filter: { (t: Type) in t.isExtension }) ext.registerBoolFilter("enum", filter: { (t: Type) in t is Enum }) ext.registerBoolFilter("struct", filter: { (t: Type) in t is Struct }) ext.registerBoolFilter("protocol", filter: { (t: Type) in t is SourceryProtocol }) ext.registerFilter("count", filter: count) ext.registerFilter("isEmpty", filter: isEmpty) ext.registerFilter("reversed", filter: reversed) ext.registerFilter("toArray", filter: toArray) ext.registerFilterWithArguments("sorted") { (array, propertyName: String) -> Any? in switch array { case let array as NSArray: let sortDescriptor = NSSortDescriptor(key: propertyName, ascending: true, selector: #selector(NSString.caseInsensitiveCompare)) return array.sortedArray(using: [sortDescriptor]) default: return nil } } ext.registerFilterWithArguments("sortedDescending") { (array, propertyName: String) -> Any? in switch array { case let array as NSArray: let sortDescriptor = NSSortDescriptor(key: propertyName, ascending: false, selector: #selector(NSString.caseInsensitiveCompare)) return array.sortedArray(using: [sortDescriptor]) default: return nil } } ext.registerBoolFilter("initializer", filter: { (m: SourceryMethod) in m.isInitializer }) ext.registerBoolFilterOr("class", filter: { (t: Type) in t is Class }, other: { (m: SourceryMethod) in m.isClass }) ext.registerBoolFilterOr("static", filter: { (v: SourceryVariable) in v.isStatic }, other: { (m: SourceryMethod) in m.isStatic }) ext.registerBoolFilterOr("instance", filter: { (v: SourceryVariable) in !v.isStatic }, other: { (m: SourceryMethod) in !(m.isStatic || m.isClass) }) ext.registerBoolFilterWithArguments("annotated", filter: { (a: Annotated, annotation) in a.isAnnotated(with: annotation) }) var extensions = stencilSwiftEnvironment().extensions extensions.append(ext) let loader = templatePath.map({ FileSystemLoader(paths: [$0.parent()]) }) return Environment(loader: loader, extensions: extensions, templateClass: StencilTemplate.self) } } extension Annotated { func isAnnotated(with annotation: String) -> Bool { if annotation.contains("=") { let components = annotation.components(separatedBy: "=").map({ $0.trimmingCharacters(in: .whitespaces) }) var keyPath = components[0].components(separatedBy: ".") var annotationValue: Annotations? = annotations while !keyPath.isEmpty && annotationValue != nil { let key = keyPath.removeFirst() let value = annotationValue?[key] if keyPath.isEmpty { return value?.description == components[1] } else { annotationValue = value as? Annotations } } return false } else { return annotations[annotation] != nil } } } extension Stencil.Extension { func registerStringFilters() { let lowercase = FilterOr<String, TypeName>.make({ $0.lowercased() }, other: { $0.name.lowercased() }) registerFilter("lowercase", filter: lowercase) let uppercase = FilterOr<String, TypeName>.make({ $0.uppercased() }, other: { $0.name.uppercased() }) registerFilter("uppercase", filter: uppercase) let capitalise = FilterOr<String, TypeName>.make({ $0.capitalized }, other: { $0.name.capitalized }) registerFilter("capitalise", filter: capitalise) } func registerFilterWithTwoArguments<T, A, B>(_ name: String, filter: @escaping (T, A, B) throws -> Any?) { registerFilter(name) { (any, args) throws -> Any? in guard let type = any as? T else { return any } guard args.count == 2, let argA = args[0] as? A, let argB = args[1] as? B else { throw TemplateSyntaxError("'\(name)' filter takes two arguments: \(A.self) and \(B.self)") } return try filter(type, argA, argB) } } func registerFilterOrWithTwoArguments<T, Y, A, B>(_ name: String, filter: @escaping (T, A, B) throws -> Any?, other: @escaping (Y, A, B) throws -> Any?) { registerFilter(name) { (any, args) throws -> Any? in guard args.count == 2, let argA = args[0] as? A, let argB = args[1] as? B else { throw TemplateSyntaxError("'\(name)' filter takes two arguments: \(A.self) and \(B.self)") } if let type = any as? T { return try filter(type, argA, argB) } else if let type = any as? Y { return try other(type, argA, argB) } else { return any } } } func registerFilterWithArguments<A>(_ name: String, filter: @escaping (Any?, A) throws -> Any?) { registerFilter(name) { (any: Any?, args: [Any?]) throws -> Any? in guard args.count == 1, let arg = args.first as? A else { throw TemplateSyntaxError("'\(name)' filter takes a single \(A.self) argument") } return try filter(any, arg) } } func registerBoolFilterWithArguments<U, A>(_ name: String, filter: @escaping (U, A) -> Bool) { registerFilterWithArguments(name, filter: Filter.make(filter)) registerFilterWithArguments("!\(name)", filter: Filter.make({ !filter($0, $1) })) } func registerBoolFilter<U>(_ name: String, filter: @escaping (U) -> Bool) { registerFilter(name, filter: Filter.make(filter)) registerFilter("!\(name)", filter: Filter.make({ !filter($0) })) } func registerBoolFilterOrWithArguments<U, V, A>(_ name: String, filter: @escaping (U, A) -> Bool, other: @escaping (V, A) -> Bool) { registerFilterWithArguments(name, filter: FilterOr.make(filter, other: other)) registerFilterWithArguments("!\(name)", filter: FilterOr.make({ !filter($0, $1) }, other: { !other($0, $1) })) } func registerBoolFilterOr<U, V>(_ name: String, filter: @escaping (U) -> Bool, other: @escaping (V) -> Bool) { registerFilter(name, filter: FilterOr.make(filter, other: other)) registerFilter("!\(name)", filter: FilterOr.make({ !filter($0) }, other: { !other($0) })) } func registerAccessLevelFilters(_ accessLevel: AccessLevel) { registerBoolFilterOr(accessLevel.rawValue, filter: { (t: Type) in t.accessLevel == accessLevel.rawValue && t.accessLevel != AccessLevel.none.rawValue }, other: { (m: SourceryMethod) in m.accessLevel == accessLevel.rawValue && m.accessLevel != AccessLevel.none.rawValue } ) registerBoolFilterOr("!\(accessLevel.rawValue)", filter: { (t: Type) in t.accessLevel != accessLevel.rawValue && t.accessLevel != AccessLevel.none.rawValue }, other: { (m: SourceryMethod) in m.accessLevel != accessLevel.rawValue && m.accessLevel != AccessLevel.none.rawValue } ) registerBoolFilter("\(accessLevel.rawValue)Get", filter: { (v: SourceryVariable) in v.readAccess == accessLevel.rawValue && v.readAccess != AccessLevel.none.rawValue }) registerBoolFilter("!\(accessLevel.rawValue)Get", filter: { (v: SourceryVariable) in v.readAccess != accessLevel.rawValue && v.readAccess != AccessLevel.none.rawValue }) registerBoolFilter("\(accessLevel.rawValue)Set", filter: { (v: SourceryVariable) in v.writeAccess == accessLevel.rawValue && v.writeAccess != AccessLevel.none.rawValue }) registerBoolFilter("!\(accessLevel.rawValue)Set", filter: { (v: SourceryVariable) in v.writeAccess != accessLevel.rawValue && v.writeAccess != AccessLevel.none.rawValue }) } } private func toArray(_ value: Any?) -> Any? { switch value { case let array as NSArray: return array case .some(let something): return [something] default: return nil } } private func reversed(_ value: Any?) -> Any? { guard let array = value as? NSArray else { return value } return array.reversed() } private func count(_ value: Any?) -> Any? { guard let array = value as? NSArray else { return value } return array.count } private func isEmpty(_ value: Any?) -> Any? { guard let array = value as? NSArray else { return false } // swiftlint:disable:next empty_count return array.count == 0 } private struct Filter<T> { static func make(_ filter: @escaping (T) -> Bool) -> (Any?) throws -> Any? { return { (any) throws -> Any? in switch any { case let type as T: return filter(type) case let array as NSArray: return array.compactMap { $0 as? T }.filter(filter) default: return any } } } static func make<U>(_ filter: @escaping (T) -> U?) -> (Any?) throws -> Any? { return { (any) throws -> Any? in switch any { case let type as T: return filter(type) case let array as NSArray: return array.compactMap { $0 as? T }.compactMap(filter) default: return any } } } static func make<A>(_ filter: @escaping (T, A) -> Bool) -> (Any?, A) throws -> Any? { return { (any, arg) throws -> Any? in switch any { case let type as T: return filter(type, arg) case let array as NSArray: return array.compactMap { $0 as? T }.filter { filter($0, arg) } default: return any } } } } private struct FilterOr<T, Y> { static func make(_ filter: @escaping (T) -> Bool, other: @escaping (Y) -> Bool) -> (Any?) throws -> Any? { return { (any) throws -> Any? in switch any { case let type as T: return filter(type) case let type as Y: return other(type) case let array as NSArray: if array.firstObject is T { return array.compactMap { $0 as? T }.filter(filter) } else { return array.compactMap { $0 as? Y }.filter(other) } default: return any } } } static func make<U>(_ filter: @escaping (T) -> U?, other: @escaping (Y) -> U?) -> (Any?) throws -> Any? { return { (any) throws -> Any? in switch any { case let type as T: return filter(type) case let type as Y: return other(type) case let array as NSArray: if array.firstObject is T { return array.compactMap { $0 as? T }.compactMap(filter) } else { return array.compactMap { $0 as? Y }.compactMap(other) } default: return any } } } static func make<A>(_ filter: @escaping (T, A) -> Bool, other: @escaping (Y, A) -> Bool) -> (Any?, A) throws -> Any? { return { (any, arg) throws -> Any? in switch any { case let type as T: return filter(type, arg) case let type as Y: return other(type, arg) case let array as NSArray: if array.firstObject is T { return array.compactMap { $0 as? T }.filter({ filter($0, arg) }) } else { return array.compactMap { $0 as? Y }.filter({ other($0, arg) }) } default: return any } } } }
42.344737
179
0.565409
260c441d9f42e4fcc21f0fa70a21a585d66bc443
1,080
// // PositionController.swift // PlayCall // // Created by Jarren Campos on 2/28/20. // Copyright © 2020 Lambda. All rights reserved. // import Foundation class PositionController { var footballPositions = [ "Quarterback", "Running Back", "Fullback", "X Wide Receiver", "Y Wide Receiver", "Tight End", "Right Tackle", "Left Tackle", "Right Guard", "Left Guard", "Center", ] var soccerPositions = [ "Goalkeeper", "Right Forward", "Left Forward", "Right Midfield", "Center Midfield", "Left Midfield", "Wing Back Right", "Center Back Right", "Center Back Middle", "Center Back Left", "Wing Back Left", "Goal Keeper" ] var basketballPositions = [ "Point Guard", "Shooting Guard", "Small Forward", "Power Foward", "Center" ] var baseballPositions = [ "Catcher", "Pitcher", "First Baseman", "Second Baseman", "Shortstop", "Third Baseman", "Right Fielder", "Center Fielder", "Left Fielder", ] }
18.305085
49
0.577778
1422f98047c7edfd98c4548b80566e2bd6efb631
490
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class a<g{let C{class d<T where g:a{class a{func e{class A:a}}}protocol a{{{{}}}typealias a
49
91
0.740816
489fcc6e9cf948c14b56b1688387bfc5c5c8fad7
1,056
public struct SQLiteColumn: CustomStringConvertible { public let name: String public let data: SQLiteData public var description: String { "\(self.name): \(self.data)" } } public struct SQLiteRow { let columnOffsets: SQLiteColumnOffsets let data: [SQLiteData] public var columns: [SQLiteColumn] { self.columnOffsets.offsets.map { (name, offset) in SQLiteColumn(name: name, data: self.data[offset]) } } public func column(_ name: String) -> SQLiteData? { guard let offset = self.columnOffsets.lookupTable[name] else { return nil } return self.data[offset] } } extension SQLiteRow: CustomStringConvertible { public var description: String { self.columns.description } } final class SQLiteColumnOffsets { let offsets: [(String, Int)] let lookupTable: [String: Int] init(offsets: [(String, Int)]) { self.offsets = offsets self.lookupTable = .init(offsets, uniquingKeysWith: { a, b in a }) } }
24.55814
74
0.63447
46ee52e7606a21a78897fa3aaa8072dbb5912dda
2,850
// // ItemDetailController.swift // Karrot // // Created by User on 2021/07/18. // import UIKit import RxSwift import RxCocoa class ItemDetailController: BaseController { // MARK: - Properties private let itemImageListView:ItemImageListView = ItemImageListView() private let pageControl:UIPageControl = UIPageControl() private let itemTitleLabel:BaseLabel = BaseLabel() var item:Item? // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() self.view.addSubviews(views: [ self.itemImageListView, self.itemTitleLabel, self.itemImageListView ]) self.setupLayouts() self.setImageCollectionView() // self.bindUI() } // MARK: - Function override func setupLayouts() { NSLayoutConstraint.activate([ self.itemImageListView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor), self.itemImageListView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.itemImageListView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), self.itemImageListView.heightAnchor.constraint(equalToConstant: 250), self.itemTitleLabel.topAnchor.constraint(equalTo: self.itemImageListView.bottomAnchor), self.itemTitleLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.itemTitleLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), ]) } override func bindUI() { } fileprivate func setImageCollectionView() { self.itemImageListView.itemImageCollectionView.register(ItemImageCell.self, forCellWithReuseIdentifier: "cell") self.itemImageListView.itemImageCollectionView.rx.setDelegate(self).disposed(by: self.disposeBag) let cellType = Observable.of(item?.imageUrl).flatMap { (imageUrl:[String]?) -> Observable<[String]> in guard let imageUrl:[String] = imageUrl else { return .empty() } return .just(imageUrl) } let pageControlCount = cellType.map { $0.count } pageControlCount.bind(to: self.itemImageListView.pageControl.rx.numberOfPages) .disposed(by: self.disposeBag) pageControlCount.map { $0 > 0 ? false : true }.bind(to: self.itemImageListView.pageControl.rx.isHidden) .disposed(by: self.disposeBag) cellType.bind(to: self.itemImageListView.itemImageCollectionView.rx.items(cellIdentifier: "cell", cellType: ItemImageCell.self)) { (row:Int, imageUrl: String, cell:ItemImageCell) in cell.imageUrl = imageUrl }.disposed(by: self.disposeBag) self.itemImageListView.itemImageCollectionView.reloadData() } }
36.075949
189
0.671579
69cfe0993c4e367723e65182b98aa59bc43b9a00
744
// // ProfileLabel.swift // berkeley-mobile // // Created by Oscar Bjorkman on 1/30/21. // Copyright © 2021 ASUC OCTO. All rights reserved. // import UIKit class ProfileLabel: UILabel { init(text: String, radius: CGFloat, fontSize: CGFloat) { super.init(frame: .zero) self.text = text self.textAlignment = .center self.font = Font.bold(fontSize) self.layer.cornerRadius = radius self.layer.masksToBounds = true self.backgroundColor = Color.StudyPact.Profile.defaultProfileBackground self.textColor = Color.StudyPact.Profile.defaultProfileLetter } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
26.571429
79
0.65457
62cb677301378b699e43d4bfdfd32791a2a1549c
8,041
// // AppusApp.swift // AppusApplications // // Created by Feather52 on 1/17/17. // Copyright © 2017 Appus. All rights reserved. // import UIKit import SwiftyJSON class AppusApp: NSObject { fileprivate enum Keys { // Image static let appIconURL100 = "artworkUrl100" static let appIconURL512 = "artworkUrl512" static let screenshotsUrls = "screenshotUrls" static let iPadScreenshotsUrls = "ipadScreenshotUrls" // Name static let appName = "trackName" static let appCensoredName = "trackCensoredName" static let developerName = "artistName" static let companyName = "sellerName" // Details static let description = "description" static let genres = "genres" static let iTunesURL = "trackViewUrl" static let formattedPrice = "formattedPrice" static let currency = "currency" static let languageCodes = "languageCodesISO2A" static let version = "version" static let minimumOsVersion = "minimumOsVersion" static let supportedDevices = "supportedDevices" // Date static let releaseDate = "releaseDate" static let currentVersionReleaseDate = "currentVersionReleaseDate" // Rating static let currentRating = "userRatingCountForCurrentVersion" static let currrentAverageRating = "averageUserRatingForCurrentVersion" static let averageUserRating = "averageUserRating" static let contentRating = "trackContentRating" static let contentAdvisoryRating = "contentAdvisoryRating" static let userRatingCount = "userRatingCount" } // Image fileprivate(set) var appImagePath = "" fileprivate(set) var appImagePathForCell = "" fileprivate(set) var screenshots : [String] = [] fileprivate(set) var isIPadScreenshots = false // Name fileprivate(set) var appName = "" fileprivate(set) var appCensoredName = "" fileprivate(set) var companyName = "" fileprivate(set) var sellerName = "" // Details fileprivate(set) var appDescription = "" fileprivate(set) var genres : [String] = [] fileprivate(set) var primaryGenre = "" fileprivate(set) var url = "" fileprivate(set) var price = "" fileprivate(set) var currency = "" fileprivate(set) var languageCodes : [String] = [] fileprivate(set) var versionNumber = "" fileprivate(set) var minVersion = "" fileprivate(set) var suportedDevices : [String] = [] // Date fileprivate(set) var date = "" fileprivate(set) var currentVersionDate = "" // Rating fileprivate(set) var currentRating = "" fileprivate(set) var currrentAverageRating = "" fileprivate(set) var averageRating = "" fileprivate(set) var contentRating = "" fileprivate(set) var contentAdvisoryRating = "" fileprivate(set) var userRatingCount = "" override var description : String { var text = "Name: \(self.appName)\n" text.append("Censored name: \(self.appCensoredName)\n") text.append("Company name: \(self.companyName)\n") text.append("Seller name: \(self.sellerName)\n") text.append("Price: \(self.price)\n") text.append("Screenshots: \(self.screenshots)") return text } func initWith(_ json: JSON) { print (json) let idiom = UIDevice.current.userInterfaceIdiom self.appImagePathForCell = json[Keys.appIconURL100].stringValue if idiom == .pad { self.appImagePath = json[Keys.appIconURL512].stringValue if json[Keys.iPadScreenshotsUrls].count > 0 { self.screenshots = json[Keys.iPadScreenshotsUrls].arrayValue.map({$0.stringValue}) self.isIPadScreenshots = true } else { self.screenshots = json[Keys.screenshotsUrls].arrayValue.map({$0.stringValue}) } } else { self.appImagePath = json[Keys.appIconURL100].stringValue if json[Keys.screenshotsUrls].count > 0 { self.screenshots = json[Keys.screenshotsUrls].arrayValue.map({$0.stringValue}) } else { self.screenshots = json[Keys.iPadScreenshotsUrls].arrayValue.map({$0.stringValue}) self.isIPadScreenshots = true } } self.appName = json[Keys.appName].stringValue self.appCensoredName = json[Keys.appCensoredName].stringValue self.companyName = json[Keys.developerName].stringValue self.sellerName = json[Keys.companyName].stringValue self.appDescription = json[Keys.description].stringValue self.genres = json[Keys.genres].arrayValue.map({$0.stringValue}) self.primaryGenre = json[Keys.genres][0].stringValue self.url = json[Keys.iTunesURL].stringValue self.price = json[Keys.formattedPrice].stringValue self.currency = json[Keys.currency].stringValue self.languageCodes = json[Keys.languageCodes].arrayValue.map({$0.stringValue}) self.versionNumber = json[Keys.version].stringValue self.minVersion = json[Keys.minimumOsVersion].stringValue self.suportedDevices = json[Keys.supportedDevices].arrayValue.map({$0.stringValue}) self.date = json[Keys.releaseDate].stringValue self.currentVersionDate = json[Keys.currentVersionReleaseDate].stringValue self.currentRating = json[Keys.currentRating].stringValue self.currrentAverageRating = json[Keys.currrentAverageRating].stringValue self.averageRating = json[Keys.averageUserRating].stringValue self.contentRating = json[Keys.contentRating].stringValue self.contentAdvisoryRating = json[Keys.contentAdvisoryRating].stringValue self.userRatingCount = json[Keys.userRatingCount].stringValue } func initWith(dictionary: [String: Any]) { self.appImagePath = dictionary[Keys.appIconURL100] as? String ?? "" self.screenshots = dictionary[Keys.screenshotsUrls] as? [String] ?? [] if (self.screenshots.count == 0){ self.screenshots = dictionary[Keys.iPadScreenshotsUrls] as? [String] ?? [] } self.appName = dictionary[Keys.appName] as? String ?? "" self.appCensoredName = dictionary[Keys.appCensoredName] as? String ?? "" self.companyName = dictionary[Keys.developerName] as? String ?? "" self.sellerName = dictionary[Keys.companyName] as? String ?? "" self.appDescription = dictionary[Keys.description] as? String ?? "" self.genres = dictionary[Keys.genres] as? [String] ?? [] self.primaryGenre = ((dictionary[Keys.genres] as! Array)[0] as? String)! self.url = dictionary[Keys.iTunesURL] as? String ?? "" self.price = dictionary[Keys.formattedPrice] as? String ?? "" self.currency = dictionary[Keys.currency] as? String ?? "" self.languageCodes = dictionary[Keys.languageCodes] as? [String] ?? [] self.versionNumber = dictionary[Keys.version] as? String ?? "" self.minVersion = dictionary[Keys.minimumOsVersion] as? String ?? "" self.suportedDevices = dictionary[Keys.supportedDevices] as? [String] ?? [] self.date = dictionary[Keys.releaseDate] as? String ?? "" self.currentVersionDate = dictionary[Keys.currentVersionReleaseDate] as? String ?? "" self.currentRating = dictionary[Keys.currentRating] as? String ?? "" self.currrentAverageRating = dictionary[Keys.currrentAverageRating] as? String ?? "" self.averageRating = dictionary[Keys.averageUserRating] as? String ?? "" self.contentRating = dictionary[Keys.contentRating] as? String ?? "" self.contentAdvisoryRating = dictionary[Keys.contentAdvisoryRating] as? String ?? "" self.userRatingCount = dictionary[Keys.userRatingCount] as? String ?? "" } }
44.425414
98
0.652282
231461320a7b39580cd9dd74a968469195331228
1,148
// // RedelegateCell.swift // Cosmostation // // Created by yongjoo on 24/05/2019. // Copyright © 2019 wannabit. All rights reserved. // import UIKit class RedelegateCell: UITableViewCell { @IBOutlet weak var rootCard: CardView! @IBOutlet weak var valImg: UIImageView! @IBOutlet weak var valjailedImg: UIImageView! @IBOutlet weak var valCheckedImg: UIImageView! @IBOutlet weak var valMonikerLabel: UILabel! @IBOutlet weak var valPowerLabel: UILabel! @IBOutlet weak var valCommissionLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() valImg.layer.borderWidth = 1 valImg.layer.masksToBounds = false valImg.layer.borderColor = UIColor(hexString: "#4B4F54").cgColor valImg.layer.cornerRadius = valImg.frame.height/2 valImg.clipsToBounds = true self.selectionStyle = .none } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func prepareForReuse() { self.valImg.image = UIImage(named: "validatorNoneImg") } }
28
72
0.679443
646c7947446d4a7aeeb80bd13138f2eda3050f5b
2,939
// // PZImageBoardCollectionViewLayout.swift // PZImageBoardCollectionViewLayout // // Created by Paul Zhang on 31/12/2016. // Copyright © 2016 Paul Zhang. All rights reserved. // import UIKit protocol PZImageBoardCollectionViewLayoutDelegate: class { func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, heightForCellAtIndexPath indexPath: IndexPath) -> CGFloat } class PZImageBoardCollectionViewLayout: UICollectionViewLayout { weak var delegate: PZImageBoardCollectionViewLayoutDelegate? { return collectionView?.delegate as? PZImageBoardCollectionViewLayoutDelegate } var numberOfColumn = 2 { didSet { invalidateLayout() } } var contentWidth: CGFloat = 0.0 { didSet { invalidateLayout() } } var cellMargin: CGFloat = 10.0 { didSet { invalidateLayout() } } var columnWidth: CGFloat { return (contentWidth - CGFloat(numberOfColumn + 1) * cellMargin ) / CGFloat(numberOfColumn) } private var heightForColumn: [CGFloat] = [] private var layoutAttributes: [UICollectionViewLayoutAttributes] = [] override func prepare() { layoutAttributes = [] heightForColumn = [CGFloat](repeating: cellMargin, count: numberOfColumn) for index in 0..<collectionView!.numberOfItems(inSection: 0) { let indexForColumn = heightForColumn.index(of: heightForColumn.min()!)! let indexPath = IndexPath(row: index, section: 0) let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath) let offsetY = heightForColumn[indexForColumn] let offsetX = cellMargin + (columnWidth + cellMargin) * CGFloat(indexForColumn) if let cellHeight = delegate?.collectionView(collectionView!, layout: self, heightForCellAtIndexPath: indexPath) { let frame = CGRect(x: offsetX, y: offsetY, width: columnWidth, height: cellHeight) attr.frame = frame layoutAttributes.append(attr) heightForColumn[indexForColumn] += cellHeight + cellMargin } } } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return layoutAttributes[indexPath.row] } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var array: [UICollectionViewLayoutAttributes] = [] for attr in layoutAttributes { if attr.frame.intersects(rect) { array.append(attr) } } return array } override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: heightForColumn.max()!) } }
33.022472
149
0.639673
6749a39d3db7289ccf5402956714079c5092255f
643
// // MovieCell.swift // flix_demo_03 // // Created by Calvin Thang on 9/8/18. // Copyright © 2018 Calvin Thang. All rights reserved. // import UIKit class MovieCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var posterImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
20.09375
65
0.657854
d529f1726f5a8363a4df69dc5cc187c5551e7434
2,387
import UIKit public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init() { val = 0; left = nil; right = nil } public init(_ val: Int) { self.val = val; left = nil; right = nil } public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { self.val = val self.left = left self.right = right } } func createTreeNode(data: [Int?]) -> TreeNode? { var root: TreeNode? guard !data.isEmpty else { return root } var index = 1 var nodeArray = [TreeNode]() if let firstValue = data[0] { root = TreeNode(firstValue) nodeArray.append(root!) } while index < data.count { var newNodeArray = [TreeNode]() for i in 0 ..< nodeArray.count { let node = nodeArray[i] if index < data.count, let value = data[index] { let newNode = TreeNode(value) node.left = newNode newNodeArray.append(newNode) } index += 1 if index < data.count, let value = data[index] { let newNode = TreeNode(value) node.right = newNode newNodeArray.append(newNode) } index += 1 } nodeArray = newNodeArray } return root } func getData(root: TreeNode?) { if root != nil { getData(root: root?.left) // print(root?.val) getData(root: root?.right) print(root?.val) } } func maxAncestorDiff(_ root: TreeNode?) -> Int { guard let root = root else { return 0 } var result = 0 calculateDifference(root, root.val, root.val, &result) return result } func calculateDifference(_ node: TreeNode?, _ currentMax: Int, _ currentMin: Int, _ result: inout Int) { guard let node = node else { return } let possibleResult = max(abs(currentMax - node.val), abs(currentMin - node.val)) result = max(result, possibleResult) let currentMax = max(currentMax, node.val) let currentMin = min(currentMin, node.val) calculateDifference(node.left, currentMax, currentMin, &result) calculateDifference(node.right, currentMax, currentMin, &result) } let root = createTreeNode(data: [8, 3, 10, 1, 6, nil, 14, nil, nil, 4, 7, 13]) getData(root: root) print(maxAncestorDiff(root))
30.602564
104
0.585253
698386a97ed71699aff0049b143377232a2b6bc2
956
import Foundation extension URLSession { func synchronousDataTask(with url: URL) -> (Data?, URLResponse?, Error?) { var data: Data? var response: URLResponse? var error: Error? let semaphore = DispatchSemaphore(value: 0) let dataTask = self.dataTask(with: url) { data = $0 response = $1 error = $2 semaphore.signal() } dataTask.resume() _ = semaphore.wait(timeout: .distantFuture) return (data, response, error) } func synchronousDataTask(with request: URLRequest) -> (Data?, URLResponse?, Error?) { var data: Data? var response: URLResponse? var error: Error? let semaphore = DispatchSemaphore(value: 0) let dataTask = self.dataTask(with: request) { data = $0 response = $1 error = $2 semaphore.signal() } dataTask.resume() _ = semaphore.wait(timeout: .distantFuture) return (data, response, error) } }
23.9
87
0.617155
28423a467d32c036876c717be7b19ba02167283a
3,142
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import MaterialComponents.MaterialFlexibleHeader class FlexibleHeaderScrollViewObservationTests: XCTestCase { var fhvc: MDCFlexibleHeaderViewController! override func setUp() { super.setUp() fhvc = MDCFlexibleHeaderViewController() // The behavior we're testing fhvc.headerView.observesTrackingScrollViewScrollEvents = true } override func tearDown() { fhvc = nil super.tearDown() } // MARK: Tracked table view func testTrackedTableViewTopContentOffsetIsObserved() { // Given let contentViewController = UITableViewController() contentViewController.tableView.contentSize = CGSize(width: contentViewController.tableView.bounds.width, height: contentViewController.tableView.bounds.height * 2) fhvc.headerView.trackingScrollView = contentViewController.tableView contentViewController.addChild(fhvc) contentViewController.view.addSubview(fhvc.view) fhvc.didMove(toParent: contentViewController) // When let overshoot: CGFloat = 10 contentViewController.tableView.contentOffset = CGPoint(x: 0, y: -contentViewController.tableView.contentInset.top - overshoot) // Then XCTAssertEqual(fhvc.headerView.frame.size.height, fhvc.headerView.maximumHeight + overshoot) // Required teardown when observation is enabled on pre-iOS 11 devices fhvc.headerView.trackingScrollView = nil } func testTrackedTableViewTopContentOffsetCausesShadowLayerOpacityChange() { // Given let contentViewController = UITableViewController() contentViewController.tableView.contentSize = CGSize(width: contentViewController.tableView.bounds.width, height: contentViewController.tableView.bounds.height * 2) fhvc.headerView.trackingScrollView = contentViewController.tableView contentViewController.addChild(fhvc) contentViewController.view.addSubview(fhvc.view) fhvc.didMove(toParent: contentViewController) // When let scrollAmount: CGFloat = fhvc.headerView.maximumHeight contentViewController.tableView.contentOffset = CGPoint(x: 0, y: -contentViewController.tableView.contentInset.top + scrollAmount) // Then XCTAssertGreaterThan(fhvc.headerView.layer.shadowOpacity, 0, "Shadow opacity was expected to be non-zero due to scrolling amount.") // Required teardown when observation is enabled on pre-iOS 11 devices fhvc.headerView.trackingScrollView = nil } }
34.527473
96
0.754933
fb39a46fe70b5924bf0a404c2d078980ec5df169
2,813
// https://gist.github.com/martinhoeller/7a1d41e3744f4191d3b3f38868be5190 // // NSStackView+Animations.swift // // Created by Martin Höller on 18.06.16. // Copyright © 2016 blue banana software. All rights reserved. // // Based on http://prod.lists.apple.com/archives/cocoa-dev/2015/Jan/msg00314.html import Cocoa extension NSStackView { func hideViews(views: [NSView], animated: Bool) { views.forEach { view in view.isHidden = true view.wantsLayer = true view.layer!.opacity = 0.0 } if animated { NSAnimationContext.runAnimationGroup({ context in context.duration = 0.3 context.allowsImplicitAnimation = true self.window?.layoutIfNeeded() }, completionHandler: nil) } } func showViews(views: [NSView], animated: Bool) { views.forEach { view in // unhide the view so the stack view knows how to layout… view.isHidden = false if animated { view.wantsLayer = true // …but set opacity to 0 so the view is not visible during the animation view.layer!.opacity = 0.0 } } if animated { views.forEach { view in view.layoutSubtreeIfNeeded() } NSAnimationContext.runAnimationGroup({ context in context.duration = 0.3 context.allowsImplicitAnimation = true // views.forEach { view in // view.layer!.opacity = 1.0 // } self.window?.layoutIfNeeded() }, completionHandler: { views.forEach { view in view.layer!.opacity = 1.0 } }) } } convenience init(views: [NSView], orientation: NSUserInterfaceLayoutOrientation, stretched: Bool = false) { self.init() self.orientation = orientation for view in views { addArrangedSubview(view, stretched: stretched) } } func addArrangedSubview(_ view: NSView, stretched: Bool, padding: CGFloat = 0) { addArrangedSubview(view) if stretched { switch orientation { case .horizontal: view.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true case .vertical: view.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: padding).isActive = true view.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -padding).isActive = true // view.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true @unknown default: print("unknown orientation") } } } }
32.709302
112
0.575187
011b48ab76eaf683ea4312bfe95dbc3874175de6
1,254
// // MoviesAppUITests.swift // MoviesAppUITests // // Created by Cristian Tovar on 11/16/17. // Copyright © 2017 Cristian Tovar. All rights reserved. // import XCTest class MoviesAppUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.891892
182
0.665072
4bf1cb2765659722d338b24078a9d43547df0f20
2,747
// // RoundedButton.swift // // Copyright 2018-2021 Twitter, Inc. // Licensed under the MoPub SDK License Agreement // http://www.mopub.com/legal/sdk-license-agreement/ // import UIKit @IBDesignable class RoundedButton: UIButton { // MARK: - View Lifecycle override func layoutSubviews() { super.layoutSubviews() updateCornerRadius() } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { guard let cgColor = layer.borderColor else { return nil } return UIColor(cgColor: cgColor) } set { layer.borderColor = newValue?.cgColor } } @IBInspectable var rounded: Bool = false { didSet { updateCornerRadius() } } func updateCornerRadius() { layer.cornerRadius = rounded ? frame.size.height / 2 : 0 } // MARK: - Overrides /** Previous border color set when the button is disabled */ private var originalBorderColor: UIColor? = nil /** Previous background color set when the button is disabled */ private var originalBackgroundColor: UIColor? = nil override var isEnabled: Bool { didSet { // Transition from enabled to disabled if oldValue && !isEnabled { // Border color exists, save it's current color and apply the // disabled color scheme if let border = borderColor { originalBorderColor = border borderColor = titleColor(for: .disabled) } // Background color exists, save it's current color and apply // the disabled color scheme if let bgColor = backgroundColor { originalBackgroundColor = bgColor backgroundColor = UIColor.lightGray } } // Transition from disabled to enabled else if !oldValue && isEnabled { // Border color previously existed, reapply it if let border = originalBorderColor { borderColor = border originalBorderColor = nil } // Background color previously existed, reapply it if let bgColor = originalBackgroundColor { backgroundColor = bgColor originalBackgroundColor = nil } } } } }
29.223404
77
0.530033
0a22b5586574c3a014c55dabc1f0f9baaeb16336
2,053
// // BadgeBackground.swift // Landmarks // // Created by hgp on 1/12/21. // import SwiftUI struct BadgeBackground: View { var body: some View { GeometryReader { geometry in Path {path in var width: CGFloat = min(geometry.size.width, geometry.size.height) let height = width let xScale: CGFloat = 0.832 let xOffset = (width * (1.0 - xScale)) / 2.0 width *= xScale path.move(to: CGPoint( x: width * 0.95 + xOffset, y: height * (0.20 + HexagonParameters.adjustment) )) HexagonParameters.segments.forEach {segment in path.addLine( to: CGPoint( x: width * segment.line.x + xOffset, y: height * segment.line.y )) path.addQuadCurve( to: CGPoint( x: width * segment.curve.x + xOffset, y: height * segment.curve.y ), control: CGPoint( x: width * segment.control.x + xOffset, y: height * segment.control.y ) ) } } .fill(LinearGradient( gradient: Gradient(colors: [Self.gradientStart, Self.gradientEnd]), startPoint: UnitPoint(x: 0.5, y: 0), endPoint: UnitPoint(x: 0.5, y: 0.6) )) } .aspectRatio(1, contentMode: .fit) } static let gradientStart = Color(red: 239.0 / 255, green: 120.0 / 255, blue: 221.0 / 255) static let gradientEnd = Color(red: 239.0 / 255, green: 172.0 / 255, blue: 120.0 / 255) } struct BadgeBackground_Previews: PreviewProvider { static var previews: some View { BadgeBackground() } }
33.655738
93
0.446176
5600a14fa7b0d291df1a192784674b442ea9dabb
1,255
// // FXChatViewDemoUITests.swift // FXChatViewDemoUITests // // Created by bailun on 2018/1/13. // Copyright © 2018年 bailun. All rights reserved. // import XCTest class FXChatViewDemoUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.918919
182
0.666932
763453fb006d4fc608859732ebf51e36acdfb04f
3,605
class URLSessionDataTaskMocker: URLSessionDataTask { @objc var sessionDelegate: (URLSessionDataDelegate & URLSessionTaskDelegate)? @objc let session: URLSession @objc let request: URLRequest @objc init(session: URLSession, request: URLRequest) { self.session = session self.request = request } private func mockGetResponse() { let responseMocker = ResponseMocker.validateHeader(request.allHTTPHeaderFields) sessionDelegate?.urlSession?(session, dataTask: self, didReceive: responseMocker.response(forURL: request.url!), completionHandler: { _ in }) sessionDelegate?.urlSession?(session, dataTask: self, didReceive: responseMocker.data) sessionDelegate?.urlSession?(session, task: self, didCompleteWithError: nil) } private func mockFormDataPostResponse() { if request.httpBody?.count == APIMocker.mocker.formData.data.count { let responseMocker = ResponseMocker.validateHeader(request.allHTTPHeaderFields) sessionDelegate?.urlSession?(session, dataTask: self, didReceive: responseMocker.response(forURL: request.url!), completionHandler: { _ in }) sessionDelegate?.urlSession?(session, dataTask: self, didReceive: responseMocker.data) sessionDelegate?.urlSession?(session, task: self, didCompleteWithError: nil) } else { sessionDelegate?.urlSession?(session, task: self, didCompleteWithError: ErrorMocker.body) } } private func mockPostResponse() { if request.httpBody?.count == APIMocker.mocker.body.count { let responseMocker = ResponseMocker.validateHeader(request.allHTTPHeaderFields) sessionDelegate?.urlSession?(session, dataTask: self, didReceive: responseMocker.response(forURL: request.url!), completionHandler: { _ in }) sessionDelegate?.urlSession?(session, dataTask: self, didReceive: responseMocker.data) sessionDelegate?.urlSession?(session, task: self, didCompleteWithError: nil) } else { sessionDelegate?.urlSession?(session, task: self, didCompleteWithError: ErrorMocker.body) } } private func mockDeleteResponse() { let responseMocker = ResponseMocker.validateHeader(request.allHTTPHeaderFields) sessionDelegate?.urlSession?(session, dataTask: self, didReceive: responseMocker.response(forURL: request.url!), completionHandler: { _ in }) sessionDelegate?.urlSession?(session, dataTask: self, didReceive: responseMocker.data) sessionDelegate?.urlSession?(session, task: self, didCompleteWithError: nil) } override var originalRequest: URLRequest? { return request } override func resume() { guard request.url?.absoluteString == APIMocker.mocker.rawValue else { sessionDelegate?.urlSession?(session, task: self, didCompleteWithError: ErrorMocker.api) return } if request.httpMethod == NetworkRequestType.get.rawValue { mockGetResponse() } else if (request.httpMethod == NetworkRequestType.post.rawValue) && (request.value(forHTTPHeaderField: "Content-Type") == NetworkBodyType.formData.rawValue) { mockFormDataPostResponse() } else if request.httpMethod == NetworkRequestType.post.rawValue { mockPostResponse() } else if request.httpMethod == NetworkRequestType.delete.rawValue { mockDeleteResponse() } } override func cancel() {} } import Foundation @testable import AdvancedFoundation
49.383562
168
0.695978
ef5c79b489df86cd6133a324867cbe7358919cae
2,584
// // MasterViewController.swift // Test // // Created by Hossam Ghareeb on 6/25/16. // Copyright © 2016 Hossam Ghareeb. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var objects = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MasterViewController.insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton self.navigationController?.hidesBarsOnSwipe = true } func insertNewObject(_ sender: AnyObject) { objects.insert(Date() as AnyObject, at: 0) let indexPath = IndexPath(row: 0, section: 0) self.tableView.insertRows(at: [indexPath], with: .automatic) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! Date let controller = segue.destination as! DetailViewController controller.detailItem = object as AnyObject? } } } // MARK: - Table View override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let object = objects[indexPath.row] as! Date cell.textLabel!.text = object.description return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { objects.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
34
141
0.6637
26279f8b0d5bc741ef5c55aa512553d6156845de
26,032
// // SKTileset.swift // SKTiled // // Created by Michael Fessenden. // // Web: https://github.com/mfessenden // Email: [email protected] // // 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 SpriteKit /** ## Overview The tileset class manages a set of `SKTilesetData` objects, which store tile data including global id, texture and animation. Tile data is accessed via a local id, and tiles can be instantiated with the resulting `SKTilesetData` instance: ```swift if let data = tileset.getTileData(localID: 56) { let tile = SKTile(data: data) } ``` ### Properties | Property | Description | |-----------------------|-------------------------------------------------| | name | Tileset name. | | tilemap | Reference to parent tilemap. | | tileSize | Tile size (in pixels). | | columns | Number of columns. | | tilecount | Tile count. | | firstGID | First tile global id. | | lastGID | Last tile global id. | | tileData | Set of tile data structures. | ### Instance Methods ### | Method | Description | |-----------------------|-------------------------------------------------| | addTextures() | Generate textures from a spritesheet image. | | addTilesetTile() | Add & return new tile data object. | */ public class SKTileset: NSObject, SKTiledObject { /// Tileset url (external tileset). public var url: URL! /// Tiled tsx filename (external tileset). public var filename: String! = nil /// Unique object id. public var uuid: String = UUID().uuidString /// Tileset name public var name: String /// Object type. public var type: String! /// Custom tileset properties. public var properties: [String: String] = [:] /// Ignore custom properties. public var ignoreProperties: Bool = false /// Reference to parent tilemap. public var tilemap: SKTilemap! /// Tile size (in pixels). public var tileSize: CGSize /// Tileset logging level. internal var loggingLevel: LoggingLevel = LoggingLevel.warning /// The number of tile columns. public var columns: Int = 0 /// The number of tiles contained in this set. public internal(set) var tilecount: Int = 0 /// Tile data count. public var dataCount: Int { return tileData.count } /// Tile offset value. public var firstGID: Int = 0 /// Returns the last global tile id in the tileset. public var lastGID: Int { return tileData.map { $0.id }.max() ?? firstGID } /// Returns a range of localized tile ids. public var localRange: ClosedRange<Int> { return 0...(dataCount - 1) } /// Returns a range of global tile id values. public var globalRange: ClosedRange<Int> { return firstGID...(firstGID + lastGID) } /// Cached alpha bitasks in a dict [id -> [[Int]]] public var alphaBitmasks: [Int: [[Int]]] = [:] // MARK: - Spacing /// Spritesheet spacing between tiles. public var spacing: Int = 0 /// Spritesheet border margin. public var margin: Int = 0 /// Offset for drawing tiles. public var tileOffset = CGPoint.zero /// Texture name (if created from source) public var source: String! /// Tile data set. private var tileData: Set<SKTilesetData> = [] /// Indicates the tileset is a collection of images. public var isImageCollection: Bool = false /// The tileset is stored in an external file. public var isExternalTileset: Bool { return filename != nil } /// Source image transparency color. public var transparentColor: SKColor? /// Indicates all of the tile data textures have been set. public internal(set) var isRendered: Bool = false /// Returns the difference in tile size vs. map tile size. internal var mapOffset: CGPoint { guard let tilemap = tilemap else { return .zero } return CGPoint(x: tileSize.width - tilemap.tileSize.width, y: tileSize.height - tilemap.tileSize.height) } /// Scaling factor for text objects, etc. public var renderQuality: CGFloat = 8 { didSet { guard renderQuality != oldValue else { return } tileData.forEach { $0.renderQuality = renderQuality } } } /** Initialize with basic properties. - parameter name: `String` tileset name. - parameter size: `CGSize` tile size. - parameter firstgid: `Int` first gid value. - parameter columns: `Int` number of columns. - parameter offset: `CGPoint` tileset offset value. - returns: `SKTileset` tileset object. */ public init(name: String, tileSize size: CGSize, firstgid: Int = 1, columns: Int = 0, offset: CGPoint = CGPoint.zero) { self.name = name self.tileSize = size super.init() self.firstGID = firstgid self.columns = columns self.tileOffset = offset } /** Initialize with an external tileset (only source and first gid are given). - parameter source: `String` source file name. - parameter firstgid: `Int` first gid value. - parameter tilemap: `SKTilemap` parent tile map node. - returns: `SKTileset` tile set. */ public init(source: String, firstgid: Int, tilemap: SKTilemap, offset: CGPoint = CGPoint.zero) { let filepath = source.components(separatedBy: "/").last! self.filename = filepath self.firstGID = firstgid self.tilemap = tilemap self.tileOffset = offset // setting these here, even though it may different later self.name = filepath.components(separatedBy: ".")[0] self.tileSize = tilemap.tileSize super.init() self.ignoreProperties = tilemap.ignoreProperties } /** Initialize with attributes directly from TMX file. - parameter attributes: `[String: String]` attributes dictionary. - parameter offset: `CGPoint` pixel offset in x/y. */ public init?(attributes: [String: String], offset: CGPoint = CGPoint.zero) { // name, width and height are required guard let setName = attributes["name"], let width = attributes["tilewidth"], let height = attributes["tileheight"] else { return nil } // columns is optional in older maps if let columnCount = attributes["columns"] { self.columns = Int(columnCount)! } // first gid won't be in an external tileset if let firstgid = attributes["firstgid"] { self.firstGID = Int(firstgid)! } if let tileCount = attributes["tilecount"] { self.tilecount = Int(tileCount)! } // optionals if let spacing = attributes["spacing"] { self.spacing = Int(spacing)! } if let margins = attributes["margin"] { self.margin = Int(margins)! } self.name = setName self.tileSize = CGSize(width: Int(width)!, height: Int(height)!) super.init() self.tileOffset = offset } /** Initialize with a TSX file name. - parameter fileNamed: `String` tileset file name. - parameter delegate: `SKTilemapDelegate?` optional tilemap delegate. */ public init(fileNamed: String) { self.name = "" self.tileSize = CGSize.zero super.init() } // MARK: - Loading /** Loads Tiled tsx files and returns an array of `SKTileset` objects. - parameter tsxFiles: `[String]` Tiled tileset filenames. - parameter delegate: `SKTilemapDelegate?` optional [`SKTilemapDelegate`](Protocols/SKTilemapDelegate.html) instance. - parameter ignoreProperties: `Bool` ignore custom properties from Tiled. - returns: `[SKTileset]` tileset objects. */ public class func load(tsxFiles: [String], delegate: SKTilemapDelegate? = nil, ignoreProperties noparse: Bool = false) -> [SKTileset] { let startTime = Date() let queue = DispatchQueue(label: "com.sktiled.renderqueue", qos: .userInteractive) let tilesets = SKTilemapParser().load(tsxFiles: tsxFiles, delegate: delegate, ignoreProperties: noparse, renderQueue: queue) let renderTime = Date().timeIntervalSince(startTime) let timeStamp = String(format: "%.\(String(3))f", renderTime) Logger.default.log("\(tilesets.count) tilesets rendered in: \(timeStamp)s", level: .success) return tilesets } // MARK: - Textures /** Add tile texture data from a sprite sheet image. - parameter source: `String` image named referenced in the tileset. - parameter replace: `Bool` replace the current texture. - parameter transparent: `String?` optional transparent color hex value. */ public func addTextures(fromSpriteSheet source: String, replace: Bool = false, transparent: String? = nil) { let timer = Date() self.source = source // parse the transparent color if let transparent = transparent { transparentColor = SKColor(hexString: transparent) } if (replace == true) { let url = URL(fileURLWithPath: source) self.log("replacing spritesheet with: \"\(url.lastPathComponent)\"", level: .info) } let inputURL = URL(fileURLWithPath: self.source!) self.log("spritesheet: \"\(inputURL.relativePath.filename)\"", level: .debug) // read image from file guard let imageDataProvider = CGDataProvider(url: inputURL as CFURL) else { self.log("Error reading image: \"\(source)\"", level: .fatal) fatalError("Error reading image: \"\(source)\"") } // creare an image data provider let image = CGImage(pngDataProviderSource: imageDataProvider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)! // create the texture let sourceTexture = SKTexture(cgImage: image) sourceTexture.filteringMode = .nearest let textureWidth = Int(sourceTexture.size().width) let textureHeight = Int(sourceTexture.size().height) // calculate the number of tiles in the texture let marginReal = margin * 2 let rowTileCount = (textureHeight - marginReal + spacing) / (Int(tileSize.height) + spacing) // number of tiles (height) let colTileCount = (textureWidth - marginReal + spacing) / (Int(tileSize.width) + spacing) // number of tiles (width) // set columns property if columns == 0 { columns = colTileCount } // tile count let totalTileCount = colTileCount * rowTileCount tilecount = tilecount > 0 ? tilecount : totalTileCount let rowHeight = Int(tileSize.height) * rowTileCount // row height (minus spacing) let rowSpacing = spacing * (rowTileCount - 1) // actual row spacing // initial x/y coordinates var x = margin let usableHeight = margin + rowHeight + rowSpacing let tileSizeHeight = Int(tileSize.height) let heightDifference = textureHeight - usableHeight // invert the y-coord var y = (usableHeight - tileSizeHeight) + heightDifference var tilesAdded: Int = 0 for tileID in 0..<totalTileCount { let rectStartX = CGFloat(x) / CGFloat(textureWidth) let rectStartY = CGFloat(y) / CGFloat(textureHeight) let rectWidth = self.tileSize.width / CGFloat(textureWidth) let rectHeight = self.tileSize.height / CGFloat(textureHeight) // create texture rectangle let tileRect = CGRect(x: rectStartX, y: rectStartY, width: rectWidth, height: rectHeight) let tileTexture = SKTexture(rect: tileRect, in: sourceTexture) tileTexture.filteringMode = .nearest // add the tile data properties, or replace the texture if (replace == false) { _ = self.addTilesetTile(tileID, texture: tileTexture) } else { _ = self.setDataTexture(tileID, texture: tileTexture) } x += Int(self.tileSize.width) + self.spacing if x >= textureWidth { x = self.margin y -= Int(self.tileSize.height) + self.spacing } tilesAdded += 1 } self.isRendered = true let tilesetBuildTime = Date().timeIntervalSince(timer) // time results if (replace == false) { let timeStamp = String(format: "%.\(String(3))f", tilesetBuildTime) Logger.default.log("tileset \"\(name)\" built in: \(timeStamp)s (\(tilesAdded) tiles)", level: .debug, symbol: self.logSymbol) } else { let animatedData: [SKTilesetData] = self.tileData.filter { $0.isAnimated == true } // update animated data NotificationCenter.default.post( name: Notification.Name.Tileset.SpriteSheetUpdated, object: self, userInfo: ["animatedTiles": animatedData] ) } } // MARK: - Tile Data /** Add tileset tile data attributes. Returns a new `SKTilesetData` object, or nil if tile data already exists with the given id. - parameter tileID: `Int` local tile ID. - parameter texture: `SKTexture` texture for tile at the given id. - returns: `SKTilesetData?` tileset data (or nil if the data exists). */ public func addTilesetTile(_ tileID: Int, texture: SKTexture) -> SKTilesetData? { guard !(self.tileData.contains(where: { $0.hashValue == tileID.hashValue })) else { log("tile data exists at id: \(tileID)", level: .error) return nil } texture.filteringMode = .nearest let data = SKTilesetData(id: tileID, texture: texture, tileSet: self) // add to tile cache data.ignoreProperties = ignoreProperties self.tileData.insert(data) data.parseProperties(completion: nil) return data } /** Add tileset data from an image source (tileset is a collections tileset). - parameter tileID: `Int` local tile ID. - parameter source: `String` source image name. - returns: `SKTilesetData?` tileset data (or nil if the data exists). */ public func addTilesetTile(_ tileID: Int, source: String) -> SKTilesetData? { guard !(self.tileData.contains(where: { $0.hashValue == tileID.hashValue })) else { log("tile data exists at id: \(tileID)", level: .error) return nil } isImageCollection = true let inputURL = URL(fileURLWithPath: source) let filename = inputURL.deletingPathExtension().lastPathComponent let fileExtension = inputURL.pathExtension guard let urlPath = Bundle.main.url(forResource: filename, withExtension: fileExtension) else { return nil } // read image from file let imageDataProvider = CGDataProvider(url: urlPath as CFURL)! // create a data provider let image = CGImage(pngDataProviderSource: imageDataProvider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)! let sourceTexture = SKTexture(cgImage: image) sourceTexture.filteringMode = .nearest let data = SKTilesetData(id: tileID, texture: sourceTexture, tileSet: self) data.ignoreProperties = ignoreProperties // add the image name to the source attribute data.source = source self.tileData.insert(data) data.parseProperties(completion: nil) return data } /** Create new data from the given texture image path. Returns a new tileset data instance & the local id associated with it. - parameter source: source image name. - returns: local tile id & tileset data (or nil if the data exists). */ public func addTilesetTile(source: String) -> (id: UInt32, data: SKTilesetData)? { let nextTileId = tilecount + 1 let nextData = SKTilesetData(id: nextTileId, texture: SKTexture(imageNamed: source), tileSet: self) return (UInt32(nextTileId), nextData) } /** Set(replace) the texture for a given tile id. - parameter tileID: `Int` tile ID. - parameter texture: `SKTexture` texture for tile at the given id. - returns: `SKTexture?` previous tile data texture. */ @discardableResult public func setDataTexture(_ id: Int, texture: SKTexture) -> SKTexture? { guard let data = getTileData(localID: id) else { if (loggingLevel.rawValue <= 1) { log("tile data not found for id: \(id)", level: .error) } return nil } let current = data.texture.copy() as? SKTexture let userInfo: [String: Any] = (current != nil) ? ["old": current!] : [:] texture.filteringMode = .nearest data.texture = texture // update observers NotificationCenter.default.post( name: Notification.Name.TileData.TextureChanged, object: data, userInfo: userInfo ) return current } /** Set(replace) the texture for a given tile id. - parameter tileID: `Int` tile ID. - parameter imageNamed: `String` source texture name. - returns: `SKTexture?` old tile data texture. */ @discardableResult public func setDataTexture(_ id: Int, imageNamed: String) -> SKTexture? { let inputURL = URL(fileURLWithPath: imageNamed) // read image from file guard let imageDataProvider = CGDataProvider(url: inputURL as CFURL) else { return nil } // creare an image data provider let image = CGImage(pngDataProviderSource: imageDataProvider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)! let texture = SKTexture(cgImage: image) return setDataTexture(id, texture: texture) } /** Returns true if the tileset contains the given ID (local). - parameter localID: `UInt32` local tile id. - returns: `Bool` tileset contains the local id. */ internal func contains(localID: UInt32) -> Bool { return localRange ~= Int(localID) } /** Returns true if the tileset contains the global ID. - parameter globalID: `UInt32` global tile id. - returns: `Bool` tileset contains the global id. */ public func contains(globalID gid: UInt32) -> Bool { return globalRange ~= Int(gid) } /** Returns tile data for the given global tile ID. ** Tiled ID == GID + 1 - parameter globalID: `Int` global tile id. - returns: `SKTilesetData?` tile data object. */ public func getTileData(globalID gid: Int) -> SKTilesetData? { // parse out flipped flags var id = rawTileID(id: gid) id = getLocalID(forGlobalID: id) if let index = tileData.firstIndex(where: { $0.id == id }) { return tileData[index] } return nil } /** Returns tile data for the given local tile ID. - parameter localID: `Int` local tile id. - returns: `SKTilesetData?` tile data object. */ public func getTileData(localID id: Int) -> SKTilesetData? { let localID = rawTileID(id: id) if let index = tileData.firstIndex(where: { $0.id == localID }) { return tileData[index] } return nil } /** Returns tile data with the given property. - parameter withProperty: `String` property name. - returns: `[SKTilesetData]` array of tile data. */ public func getTileData(withProperty property: String) -> [SKTilesetData] { return tileData.filter { $0.properties[property] != nil } } /** Returns tile data with the given name & animated state. - parameter named: `String` data name. - parameter isAnimated: `Bool` filter data that is animated. - returns: `[SKTilesetData]` array of tile data. */ public func getTileData(named name: String, isAnimated: Bool = false) -> [SKTilesetData] { return tileData.filter { ($0.name == name) && ($0.isAnimated == isAnimated) } } /** Returns tile data with the given type. - parameter ofType: `String` data type. - returns: `[SKTilesetData]` array of tile data. */ public func getTileData(ofType: String) -> [SKTilesetData] { return tileData.filter { $0.type == ofType } } /** Returns tile data with the given property. - parameter property: `String` property name. - parameter value: `AnyObject` value - returns: `[SKTilesetData]` array of tile data. */ public func getTileData(withProperty property: String, _ value: Any) -> [SKTilesetData] { var result: [SKTilesetData] = [] let tiledata = getTileData(withProperty: property) for data in tiledata { if data.stringForKey(property)! == value as? String { result.append(data) } } return result } /** Returns animated tile data. - returns: `[SKTilesetData]` array of animated tile data. */ public func getAnimatedTileData() -> [SKTilesetData] { return tileData.filter { $0.isAnimated == true } } /** Convert a global ID to the tileset's local ID. - parameter gid: `Int` global id. - returns: `Int` local tile ID. */ public func getLocalID(forGlobalID gid: Int) -> Int { // firstGID is greater than 0 only when added to a tilemap let id = (firstGID > 0) ? (gid - firstGID) : gid // if the id is less than zero, return the gid return (id < 0) ? gid : id } /** Convert a global ID to the tileset's local ID. - parameter id: `Int` local id. - returns: `Int` global tile ID. */ public func getGlobalID(forLocalID id: Int) -> Int { let gid = (firstGID > 0) ? (firstGID + id) - 1 : id return gid } /** Check for tile ID flip flags. - parameter id: `Int` tile ID. - returns: `Int` translated ID. */ internal func rawTileID(id: Int) -> Int { let uid: UInt32 = UInt32(id) // masks for tile flipping let flippedDiagonalFlag: UInt32 = 0x20000000 let flippedVerticalFlag: UInt32 = 0x40000000 let flippedHorizontalFlag: UInt32 = 0x80000000 let flippedAll = (flippedHorizontalFlag | flippedVerticalFlag | flippedDiagonalFlag) let flippedMask = ~(flippedAll) // get the actual gid from the mask let gid = uid & flippedMask return Int(gid) } // MARK: - Rendering /** Refresh textures for animated tile data. */ internal func setupAnimatedTileData() { let animatedData = getAnimatedTileData() var framesAdded = 0 var dataFixed = 0 if (animatedData.isEmpty == false) { animatedData.forEach { data in for frame in data.frames where frame.texture == nil{ if let frameData = getTileData(localID: frame.id) { if frameData.texture != nil { frame.texture = frameData.texture framesAdded += 1 } } } dataFixed += 1 } } if (framesAdded > 0) { log("updated \(dataFixed) tile data animations for tileset: \"\(name)\"", level: .debug) } } } public func == (lhs: SKTileset, rhs: SKTileset) -> Bool { return (lhs.hash == rhs.hash) } extension SKTileset { override public var hash: Int { return name.hashValue } /// String representation of the tileset object. override public var description: String { var desc = "Tileset: \"\(name)\" @ \(tileSize), firstgid: \(firstGID), \(dataCount) tiles" if tileOffset.x != 0 || tileOffset.y != 0 { desc += ", offset: \(tileOffset.x)x\(tileOffset.y)" } return desc } override public var debugDescription: String { return description } }
33.676585
138
0.600953
fc0745e784a98e27186ab82ab0aa0ea1a93d07ee
658
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "FloatingSwitch", platforms: [ .iOS(.v13), ], products: [ .library( name: "FloatingSwitch", targets: ["FloatingSwitch"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ .target( name: "FloatingSwitch", path: "Sources"), ], swiftLanguageVersions: [SwiftVersion.v5] )
24.37037
96
0.603343
798c4ca94cbab66794f20e766533d5316edcd5c0
526
// // BackgroundColor.swift // SwiftCss // // Created by Tibor Bodecs on 2021. 07. 10.. // public func BackgroundColor(_ value: String) -> Property { Property(name: "background-color", value: value) } /// Specifies the background color of an element public func BackgroundColor(_ value: CSSColorValue = .transparent) -> Property { BackgroundColor(value.rawValue) } /// Specifies the background color of an element public func BackgroundColor(_ value: CSSColor) -> Property { BackgroundColor(.color(value)) }
25.047619
80
0.720532
7ae161b5ac734ecd54c158f6ebabde85c2a2dad9
10,590
// // TweenControl.swift // Tweener // // Created by Alejandro Ramirez Varela on 9/7/18. // Copyright © 2018 Alejandro Ramirez Varela. All rights reserved. // import Foundation /// A Control wrapper class. class TweenControl { /// Calculated Tween's Time start var timeStart:Double = 0.0 /// Calculated Tween's Time complete var timeComplete:Double = 0.0 /// Stores time when Tween is paused. var timePaused:Double = 0.0 /// Tween's current state. var state:TweenState = .initial /// Stores last Tween's state. var lastState:TweenState = .initial /**Updates Tween's animation values. - Parameter time: Engine's current time value as Double. */ func update(_ time:Double){ //Warning print("Error, tween nil") } /// Control's accesor to `Tween` instance. /// - Returns: Control's AnyTween instance. func getTween() -> AnyTween { print("Error, tween nil") return AnyTween() } /// Tween's reset function. func reset(){ state = .initial timePaused = 0 } /// Get Tween's keyPath count. /// - Returns: Int value. func getKeysCount() -> Int{ print("Error, tween nil") return -1 } /// Tween's Keypath and Values accesor. /// - Returns: Tween's collection of keypaths and Values. func getKeys() -> [AnyKeyPath : TweenArray] { print("Error, tween nil") return [:] } /// Function to check if it is the same target /// - Parameter target: Target to check. /// - Returns: A Bool value indicating if target is the same. func isTarget<U>( _ target:U) -> Bool{ print("Error, tween nil") return false } /// Gets unsafeBitCast of Tween's target. /// - Returns: An Int representing the unsafeBitCast. func getTargetAddress()->Int{ print("Error, tween nil") return 0 } ///Removes current Tween from Engine. func remove(){ print("Error, tween nil") } ///Removes specific KeyPaths from Tween instance. /// - Parameter keys: A collection of KeyPaths to remove. /// - Returns: An Int number representing total of keypaths that were removed. func remove<U>(_ keys:[PartialKeyPath<U>])->Int { print("Error, tween nil") return 0 } /// Checks if Tween instance contains KeyPaths. /// - Parameter keys: A collection of KeyPaths to check. /// - Returns: An Int number representing total of matches found. func contains<U>(_ keys:[PartialKeyPath<U>]) -> Int { print("Error, tween nil") return 0 } /// Splts Tween's keyPaths into a new Tween instance and creates a new TweenControl. /// - Parameter keys: A collection of KeyPaths to split. /// - Returns: A new TweenControl instance containing split keypaths. func split<U>(_ keys:[PartialKeyPath<U>]) -> TweenControl? { print("Error, tween nil") return nil } } /// Class that handles Tween animation updates associated to Tween's target Type. class Control<T>: TweenControl { override var timeStart:Double{ didSet {updateTimeComplete()} } ///Tween instance for animation handling. var tween :Tween<T> public init(_ tween:Tween<T>, time:Double){ self.tween = tween super.init() timeStart = time } /// Get Tween's keyPath count. /// - Returns: Int value. override func getKeysCount() -> Int{ return tween.keys.count } /// Tween's Keypath and Values accesor. /// - Returns: Tween's collection of keypaths and Values. override func getKeys() -> [AnyKeyPath : TweenArray] { var list:[AnyKeyPath : TweenArray] = [:] for keyValue in self.tween.keys { list[keyValue.key] = keyValue.value } return list } /// Function to check if it is the same target /// - Parameter target: Target to check. /// - Returns: A Bool value indicating if target is the same. override func isTarget<U>( _ target:U) -> Bool{ if U.self == T.self { return unsafeBitCast(target, to:Int.self) == unsafeBitCast(tween.target, to:Int.self) } return false } ///Removes current Tween from Engine. override func remove(){ TweenList.remove(self) } ///Removes specific KeyPaths from Tween instance. /// - Parameter keys: A collection of KeyPaths to remove. /// - Returns: An Int number representing total of keypaths that were removed. override func remove<U>(_ keys:[PartialKeyPath<U>]) -> Int { //Verify if is same object type. if U.self == T.self { //Cast array. let replacingKeys = keys as! [PartialKeyPath<T>] //Create empty array. var newKeys:[PartialKeyPath<T>:TweenArray] = [:] //Use original key-value pairs to replace existing. for (key, value) in tween.keys { //Verify if contains key if !replacingKeys.contains(key){ //Tween doesn't contain key, insert. newKeys[key] = value } } //Verify if all keys were replaced. if newKeys.count != tween.keys.count{ //One or more keys were replaced, Tween has overwritten. if tween.onOverwrite != nil { DispatchQueue.main.async { self.tween.onOverwrite!() } } } //Replace non-affected keys to original tween. (tween as Tween<T>).keys = newKeys } return tween.keys.count } /// Checks if Tween instance contains KeyPaths. /// - Parameter keys: A collection of KeyPaths to check. /// - Returns: An Int number representing total of matches found. override func contains<U>(_ keys:[PartialKeyPath<U>]) -> Int { var count:Int = 0 if U.self == T.self { let keys_t = keys as? [PartialKeyPath<T>] for (key, _) in tween.keys{ //Verify if contains key. if keys_t!.contains(key){ //Doesn't contain key, insert value. count = count + 1 } } } return count } /// Splts Tween's keyPaths into a new Tween instance and creates a new TweenControl. /// - Parameter keys: A collection of KeyPaths to split. /// - Returns: A new TweenControl instance containing split keypaths. override func split<U>(_ keys:[PartialKeyPath<U>]) -> TweenControl?{ var splittedKeys:[PartialKeyPath<T>:TweenArray] = [:] //Verify if is same object type. if U.self == T.self { let replacingKeys = keys as? [PartialKeyPath<T>] for (key, value) in tween.keys { //Verify if keypath is added if replacingKeys!.contains(key) == false { //Insert value splittedKeys[key] = value } } } return clone( splittedKeys ) } ///Creates a new Tween instance for current Tween's target. /// - Parameter keys: A collection of KeyPaths to animate. /// - Returns: A new TweenControl instance for created Tween.S func clone(_ keys:[PartialKeyPath<T>:TweenArray]) -> TweenControl { let newTween:Tween<T> = Tween(tween.target) //Set keys directly newTween.keys = keys newTween.duration = tween.duration newTween.ease = tween.ease newTween.delay = tween.delay newTween.onStart = tween.onStart newTween.onUpdate = tween.onUpdate newTween.onComplete = tween.onComplete newTween.onOverwrite = tween.onOverwrite return Control(newTween, time:self.timeStart) } /// Gets unsafeBitCast of Tween's target. /// - Returns: An Int representing the unsafeBitCast. override public func getTargetAddress()->Int { return unsafeBitCast(tween.target, to:Int.self) } /**Function that calls to update the Tween's values. - Parameter time: Engine's current value time. */ override func update(_ time:Double) { updateKeys(tween.target!, keys:tween.keys, time:time) } /**Updates Tween's animation values. - Parameter target: Target instance to perform animations. - Parameter keys: Collection of KeyPaths and values to animate. */ func updateKeys<T>(_ target:T, keys: [PartialKeyPath<T> : TweenArray], time:Double) { for (key, values) in keys { //Array for interpolated values var i:[Double] = [] if time >= self.timeComplete { //Tween completed, set complete values i = values.to } else if time < self.timeStart { //Tween hasn't started, set start values i = values.from } else { //Calculate values using easing equations. let t = time - self.timeStart let d = self.timeComplete - self.timeStart //Apply equation for (index, b) in values.from.enumerated() { let c = values.to[ index ] - b i.append(self.tween.ease.equation(t, b, c, d)) } } //Update only certain types for (j, t) in SupportedTypes.list.enumerated() { if type(of: type(of: key).valueType ) == type(of: t) { SupportedTypes.interpreters[j].write(target: target, key: key, values: i) break } } } } ///Updates Tween's time complete. func updateTimeComplete(){timeComplete = timeStart + (tween.duration / timeScale)} /// Control's accesor to `Tween` instance. /// - Returns: Control's AnyTween instance. override func getTween() -> AnyTween{ return self.tween } }
32.484663
102
0.552975
9154b41114f20b4d9d7eb36d069677c86103c8bc
4,832
// // TYWNewFeatureViewController.swift // LearnSwift // // Created by apple on 2016/11/23. // Copyright © 2016年 tyw. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class TYWNewFeatureViewController: UICollectionViewController { private var layout: UICollectionViewFlowLayout = TYWNewFeatureLayout() init() { super.init(collectionViewLayout: layout) collectionView?.showsHorizontalScrollIndicator = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.collectionView!.backgroundColor = UIColor.red self.collectionView!.register(TYWNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier) } } // MARK: UICollectionViewDataSource extension TYWNewFeatureViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, retu rn the number of items return kNewFeatureCount } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! TYWNewFeatureCell cell.imageIndex = indexPath.item return cell } override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let path = collectionView.indexPathsForVisibleItems.last! if path.item == (kNewFeatureCount - 1) { let cell = collectionView.cellForItem(at: path) as! TYWNewFeatureCell cell.startBtnAnimation() } } } /// TYWNewFeatureCell private class TYWNewFeatureCell: UICollectionViewCell { var imageIndex: Int? { didSet { iconView.image = UIImage(named: "walkthrough_\(imageIndex! + 1)") } } private lazy var iconView = UIImageView() private lazy var startButton: UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "btn_begin"), for: .normal) btn.addTarget(self, action: #selector(startButtonClick), for: .touchUpInside) btn.layer.masksToBounds = true btn.isHidden = true return btn }() func startButtonClick() -> () { UIApplication.shared.keyWindow?.rootViewController = TYWTabBarController() } func startBtnAnimation() -> () { startButton.isHidden = false startButton.transform = CGAffineTransform.init(scaleX: 0.0, y: 0.0) startButton.isUserInteractionEnabled = false UIView.animate(withDuration: 2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { self.startButton.transform = CGAffineTransform.identity }) { (true) in self.startButton.isUserInteractionEnabled = true } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI() -> () { contentView.addSubview(iconView) contentView.addSubview(startButton) iconView.snp.makeConstraints { (make) in make.edges.equalTo(contentView) } startButton.snp.makeConstraints { (make) in make.bottom.equalTo(contentView.snp.bottom).offset(-50) make.size.equalTo(CGSize.init(width: 150, height: 40)) make.centerX.equalTo(75) } } } private class TYWNewFeatureLayout: UICollectionViewFlowLayout { override func prepare() { itemSize = UIScreen.main.bounds.size minimumLineSpacing = 0 minimumInteritemSpacing = 0 scrollDirection = .horizontal collectionView?.showsVerticalScrollIndicator = false collectionView?.bounces = false collectionView?.isPagingEnabled = true } }
25.566138
164
0.603891
0e113f8b89ca3e87aaebda1aa4a34c363ff22bce
4,319
// // 🦠 Corona-Warn-App // #if !RELEASE import UIKit protocol DMStore: AnyObject { var dmLastSubmissionRequest: Data? { get set } } extension UserDefaults: DMStore { var dmLastSubmissionRequest: Data? { get { data(forKey: "dmLastSubmissionRequest") } set { set(newValue, forKey: "dmLastSubmissionRequest") } } var dmLastOnBehalfCheckinSubmissionRequest: Data? { get { data(forKey: "dmLastOnBehalfCheckinSubmissionRequest") } set { set(newValue, forKey: "dmLastOnBehalfCheckinSubmissionRequest") } } } /// If enabled, the developer can be revealed by tripple-tapping anywhere within the `presentingViewController`. final class DMDeveloperMenu { // MARK: - Init /// Parameters: /// - presentingViewController: The instance of `UIViewController` which should receive a developer menu. /// - client: The `Client` to use. /// - store: The `Store` is used to retrieve debug information. init( presentingViewController: UIViewController, client: Client, wifiClient: WifiOnlyHTTPClient, store: Store, exposureManager: ExposureManager, developerStore: DMStore, exposureSubmissionService: ExposureSubmissionService, environmentProvider: EnvironmentProviding, otpService: OTPServiceProviding, coronaTestService: CoronaTestService, eventStore: EventStoringProviding, qrCodePosterTemplateProvider: QRCodePosterTemplateProviding, ppacService: PrivacyPreservingAccessControl ) { self.client = client self.wifiClient = wifiClient self.presentingViewController = presentingViewController self.store = store self.exposureManager = exposureManager self.developerStore = developerStore self.exposureSubmissionService = exposureSubmissionService self.environmentProvider = environmentProvider self.otpService = otpService self.coronaTestService = coronaTestService self.eventStore = eventStore self.qrCodePosterTemplateProvider = qrCodePosterTemplateProvider self.ppacService = ppacService } // MARK: - Internal /// Enables the developer menu if it is currently allowed to do so. /// /// Whether or not the developer menu is allowed is determined at build time by looking at the active build configuration. It is only allowed for `RELEASE` and `DEBUG` builds. Builds that target the app store (configuration `APP_STORE`) are built without support for a developer menu. func enableIfAllowed() { guard isAllowed() else { return } let showDeveloperMenuGesture = UITapGestureRecognizer(target: self, action: #selector(_showDeveloperMenu(_:))) showDeveloperMenuGesture.numberOfTapsRequired = 3 presentingViewController.view.addGestureRecognizer(showDeveloperMenuGesture) } func showDeveloperMenu() { let vc = DMViewController( client: client, wifiClient: wifiClient, exposureSubmissionService: exposureSubmissionService, otpService: otpService, coronaTestService: coronaTestService, eventStore: eventStore, qrCodePosterTemplateProvider: qrCodePosterTemplateProvider, ppacService: ppacService ) let closeBarButtonItem = UIBarButtonItem( title: "❌", style: .done, target: self, action: #selector(closeDeveloperMenu) ) vc.navigationItem.rightBarButtonItem = closeBarButtonItem let navigationController = UINavigationController( rootViewController: vc ) presentingViewController.present( navigationController, animated: true, completion: nil ) } @objc func closeDeveloperMenu() { presentingViewController.dismiss(animated: true) } // MARK: - Private private let presentingViewController: UIViewController private let client: Client private let wifiClient: WifiOnlyHTTPClient private let store: Store private let eventStore: EventStoringProviding private let exposureManager: ExposureManager private let exposureSubmissionService: ExposureSubmissionService private let developerStore: DMStore private let environmentProvider: EnvironmentProviding private let otpService: OTPServiceProviding private let coronaTestService: CoronaTestService private let qrCodePosterTemplateProvider: QRCodePosterTemplateProviding private let ppacService: PrivacyPreservingAccessControl @objc private func _showDeveloperMenu(_: UITapGestureRecognizer) { showDeveloperMenu() } private func isAllowed() -> Bool { true } } #endif
29.380952
285
0.780968
75565c83152f2d979cd705095e67665f29c00748
6,434
/* The MIT License (MIT) Copyright (c) 2015 Yari D'areglia @bitwaker Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public enum WalkthroughAnimationType:String{ case Linear = "Linear" case Curve = "Curve" case Zoom = "Zoom" case InOut = "InOut" init(_ name:String){ if let tempSelf = WalkthroughAnimationType(rawValue: name){ self = tempSelf }else{ self = .Linear } } } open class BWWalkthroughPageViewController: UIViewController, BWWalkthroughPage { fileprivate var animation:WalkthroughAnimationType = .Linear fileprivate var subsWeights:[CGPoint] = Array() fileprivate var notAnimatableViews:[Int] = [] // Array of views' tags that should not be animated during the scroll/transition // MARK: Inspectable Properties // Edit these values using the Attribute inspector or modify directly the "User defined runtime attributes" in IB @IBInspectable var speed:CGPoint = CGPoint(x: 0.0, y: 0.0); // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var speedVariance:CGPoint = CGPoint(x: 0.0, y: 0.0) // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var animationType:String { set(value){ self.animation = WalkthroughAnimationType(rawValue: value)! } get{ return self.animation.rawValue } } @IBInspectable var animateAlpha:Bool = false @IBInspectable var staticTags:String { // A comma separated list of tags that you don't want to animate during the transition/scroll set(value){ self.notAnimatableViews = value.components(separatedBy: ",").map{Int($0)!} } get{ return notAnimatableViews.map{String($0)}.joined(separator: ",") } } // MARK: BWWalkthroughPage Implementation override open func viewDidLoad() { super.viewDidLoad() self.view.layer.masksToBounds = true subsWeights = Array() for v in view.subviews{ speed.x += speedVariance.x speed.y += speedVariance.y if !notAnimatableViews.contains(v.tag) { subsWeights.append(speed) } } } open func walkthroughDidScroll(_ position: CGFloat, offset: CGFloat) { for i in (0..<subsWeights.count){ // Perform Transition/Scale/Rotate animations switch animation{ case .Linear: animationLinear(i, offset) case .Zoom: animationZoom(i, offset) case .Curve: animationCurve(i, offset) case .InOut: animationInOut(i, offset) } // Animate alpha if(animateAlpha){ animationAlpha(i, offset) } } } // MARK: Animations (WIP) private func animationAlpha(_ index:Int, _ offset:CGFloat){ var offset = offset let cView = view.subviews[index] if(offset > 1.0){ offset = 1.0 + (1.0 - offset) } cView.alpha = (offset) } fileprivate func animationCurve(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity let x:CGFloat = (1.0 - offset) * 10 transform = CATransform3DTranslate(transform, (pow(x,3) - (x * 25)) * subsWeights[index].x, (pow(x,3) - (x * 20)) * subsWeights[index].y, 0 ) applyTransform(index, transform: transform) } fileprivate func animationZoom(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } let scale:CGFloat = (1.0 - tmpOffset) transform = CATransform3DScale(transform, 1 - scale , 1 - scale, 1.0) applyTransform(index, transform: transform) } fileprivate func animationLinear(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity let mx:CGFloat = (1.0 - offset) * 100 transform = CATransform3DTranslate(transform, mx * subsWeights[index].x, mx * subsWeights[index].y, 0 ) applyTransform(index, transform: transform) } fileprivate func animationInOut(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity //var x:CGFloat = (1.0 - offset) * 20 var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } transform = CATransform3DTranslate(transform, (1.0 - tmpOffset) * subsWeights[index].x * 100, (1.0 - tmpOffset) * subsWeights[index].y * 100, 0) applyTransform(index, transform: transform) } fileprivate func applyTransform(_ index:Int, transform:CATransform3D){ let subview = view.subviews[index] if !notAnimatableViews.contains(subview.tag){ view.subviews[index].layer.transform = transform } } }
36.765714
230
0.625583
2069690e85e36cf4fa81eaa1a90e6fabe05ef777
1,041
// // korgLowPassFilter.swift // AudioKit // // Autogenerated by scripts by Aurelius Prochazka. Do not edit directly. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation extension AKComputedParameter { /// Analogue model of the Korg 35 Lowpass Filter /// /// - returns: AKOperation /// - parameter input: Input audio signal /// - parameter cutoffFrequency: Filter cutoff (Default: 1000.0, Minimum: 0.0, Maximum: 22050.0) /// - parameter resonance: Filter resonance (should be between 0-2) (Default: 1.0, Minimum: 0.0, Maximum: 2.0) /// - parameter saturation: Filter saturation. (Default: 0.0, Minimum: 0.0, Maximum: 10.0) /// public func korgLowPassFilter( cutoffFrequency cutoffFrequency: AKParameter = 1000.0, resonance: AKParameter = 1.0, saturation: AKParameter = 0.0 ) -> AKOperation { return AKOperation(module: "wpkorg35", inputs: self.toMono(), cutoffFrequency, resonance, saturation) } }
34.7
114
0.648415
8f6b5d602e9e2331e3aa136c8caa1da9a5284d3a
609
// // Driver+Cast.swift // MJCore // // Created by Martin Janák on 16/08/2018. // import RxSwift import RxCocoa extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { public func cast<Input, Output>(_ valueType: Output.Type) -> Driver<Output> where E == Input? { return self .filter { $0 != nil && $0 is Output } .map { $0 as! Output } } public func cast<Output>(_ valueType: Output.Type) -> Driver<Output> { return self .filter { $0 is Output } .map { $0 as! Output } } }
23.423077
100
0.581281
215006ce884aadf8f06c28bb0e453625069bd56e
211
// // Base.swift // SwiftGraph // // Created by Eugen Fedchenko on 9/3/17. // // import Foundation public protocol VertexProtocol: Hashable { } public protocol EdgeProtocol { var weight: Int { get } }
12.411765
42
0.668246
2fe864aa7679509ff94893ae80205d6b90b19580
5,164
// // Style.swift // // // Created by Masashi Aso on 2020/10/24. // public struct Style { public var foregroundColor: Color? public var backgroundColor: Color? public var isBoldfaced: Bool public var isDimmed: Bool public var isItalicized: Bool public var isUnderlined: Bool public var isBlinked: Bool public var isReversed: Bool public var isHidden: Bool public var isStrikethrough: Bool public init( foreground: Color? = nil, background: Color? = nil, bold: Bool = false, dim: Bool = false, italic: Bool = false, underline: Bool = false, blink: Bool = false, reverse: Bool = false, hide: Bool = false, strikethrough: Bool = false ) { self.foregroundColor = foreground self.backgroundColor = background self.isBoldfaced = bold self.isDimmed = dim self.isItalicized = italic self.isUnderlined = underline self.isBlinked = blink self.isReversed = reverse self.isHidden = hide self.isStrikethrough = strikethrough } } // MARK: - Modifiers extension Style: StyleModifier { public typealias Modified = Style @inline(__always) @inlinable public func bold(_ isOn: Bool = true) -> Modified { var new = self new.isBoldfaced = isOn return new } @inline(__always) @inlinable public func dim(_ isOn: Bool = true) -> Modified { var new = self new.isDimmed = isOn return new } @inline(__always) @inlinable public func italic(_ isOn: Bool = true) -> Modified { var new = self new.isItalicized = isOn return new } @inline(__always) @inlinable public func underline(_ isOn: Bool = true) -> Modified { var new = self new.isUnderlined = isOn return new } @inline(__always) @inlinable public func blink(_ isOn: Bool = true) -> Modified { var new = self new.isBlinked = isOn return new } @inline(__always) @inlinable public func reverse(_ isOn: Bool = true) -> Modified { var new = self new.isReversed = isOn return new } @inline(__always) @inlinable public func hide(_ isOn: Bool = true) -> Modified { var new = self new.isHidden = isOn return new } @inline(__always) @inlinable public func strikethrough(_ isOn: Bool = true) -> Modified { var new = self new.isStrikethrough = isOn return new } @inline(__always) @inlinable public func foreground(_ color: Color?) -> Modified { var new = self new.foregroundColor = color return new } @inline(__always) @inlinable public func background(_ color: Color?) -> Modified { var new = self new.backgroundColor = color return new } } // MARK: - Generate Code public extension Style { func prefix() -> String { if isPlain { return "" } var text = "\u{1b}[" if isBoldfaced { text += "1;" } if isDimmed { text += "2;" } if isItalicized { text += "3;" } if isUnderlined { text += "4;" } if isBlinked { text += "5;" } if isReversed { text += "7;" } if isHidden { text += "8;" } if isStrikethrough { text += "9;" } if let fb = foregroundColor { text += fb.foregroundCode() } if let bg = backgroundColor { text += bg.backgroundCode() } // remove last ';' text.removeLast() text += "m" return text } func infix(next: Style) -> String { if self == next { return "" } if next.isPlain { return "\u{1b}[0m" } var text = "\u{1b}[" func modifyCode( for keyPath: KeyPath<Style, Bool>, toOn: UInt8, toOff: UInt8 ) { switch (self[keyPath: keyPath], next[keyPath: keyPath]) { case (true, true), (false, false): break case (false, true): text += "\(toOn);" case (true, false): text += "\(toOff);" } } // bold and dim's disable code are same, 22. if self.isBoldfaced || self.isDimmed { text += "22;" } if next.isBoldfaced { text += "1;" } if next.isDimmed { text += "2;" } modifyCode(for: \.isItalicized, toOn: 3, toOff: 23) modifyCode(for: \.isUnderlined, toOn: 4, toOff: 24) modifyCode(for: \.isBlinked, toOn: 5, toOff: 25) modifyCode(for: \.isReversed, toOn: 7, toOff: 27) modifyCode(for: \.isHidden, toOn: 8, toOff: 28) modifyCode(for: \.isStrikethrough, toOn: 9, toOff: 29) switch (self.foregroundColor, next.foregroundColor) { case (.none, .none): break case (.some(let a), .some(let b)) where a == b: break case (_, .some(let new)): text += new.foregroundCode() case (.some(_), .none): text += "39;" } switch (self.backgroundColor, next.backgroundColor) { case (.none, .none): break case (.some(let a), .some(let b)) where a == b: break case (_, .some(let new)): text += new.backgroundCode() case (.some(_), .none): text += "49;" } // remove last ';' text.removeLast() text += "m" return text } func suffix() -> String { isPlain ? "" : "\u{1b}[0m" } } // MARK: Other extension Style: Equatable, Hashable { var isPlain: Bool { self == Style() } }
25.190244
66
0.597405
337263fb0e403f7d3dff414a58d7030cda6fa078
2,927
// // MPMediaLibraryQueue.swift // Pods // // Created by ZhiFei on 2018/5/14. // import Foundation import MediaPlayer class MPMediaLibraryQueue: NSObject { fileprivate let queue = DispatchQueue(label: "com.apple.music.zf.media.sync") fileprivate var configs: [MPMediaPlaylist: MPMediaLibraryQueueConfig] = [:] @available(iOS 9.3, *) open func addItems(_ items: [String], mediaPlaylist: MPMediaPlaylist) { let config = self.getConfig(mediaPlaylist: mediaPlaylist) if config.items.count != 0 { config.add(items: items) return } config.add(items: items) self.queue.async { self.startSyncTask(config: config) } } @available(iOS 9.3, *) open func addItem(_ item: String, mediaPlaylist: MPMediaPlaylist) { self.addItems([item], mediaPlaylist: mediaPlaylist) } } fileprivate extension MPMediaLibraryQueue { func startSyncTask(config: MPMediaLibraryQueueConfig) { guard let item = config.items.first else { return } if #available(iOS 9.3, *) { config.mediaPlaylist.addItem(withProductID: item) { [weak self] (err) in guard let `self` = self else { return } if let err = err as? MPError { if err.code == MPError.Code.permissionDenied || err.code == MPError.Code.cloudServiceCapabilityMissing { // 不支持 sync,停止 sync self.endSyncTask(config: config) return } } self.syncTaskCompleted(config: config, item: item, err: err) } } else { // Fallback on earlier versions } } func syncTaskCompleted(config: MPMediaLibraryQueueConfig, item: String, err: Error?) { config.remove(item: item) self.queue.async { self.startSyncTask(config: config) } } func endSyncTask(config: MPMediaLibraryQueueConfig) { config.items = [] } func getConfig(mediaPlaylist: MPMediaPlaylist) -> MPMediaLibraryQueueConfig { if let value = self.configs[mediaPlaylist] { return value } let config = MPMediaLibraryQueueConfig(mediaPlaylist: mediaPlaylist) self.configs[mediaPlaylist] = config return config } } fileprivate class MPMediaLibraryQueueConfig: NSObject { internal fileprivate(set) var items: [String] = [] internal fileprivate(set) var mediaPlaylist: MPMediaPlaylist! init(mediaPlaylist: MPMediaPlaylist) { super.init() self.mediaPlaylist = mediaPlaylist } func configure(items: [String]) { self.items = items } func add(items: [String]) { var result = self.items let addItems = items.filter{ !self.items.contains($0) } result.append(contentsOf: addItems) self.configure(items: result) } func add(item: String) { self.items.append(item) } func remove(item: String) { if let index = self.items.index(of: item) { self.items.remove(at: index) } } }
24.805085
114
0.652204
ef1252f4aaaa997a1518e64326a84b7b2f66bcac
2,437
//------------------------------------------------------------------------------ // Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: enums.fbe // FBE version: 1.10.0.0 //------------------------------------------------------------------------------ import Foundation public enum EnumInt16Enum { typealias RawValue = Int16 case ENUM_VALUE_0 case ENUM_VALUE_1 case ENUM_VALUE_2 case ENUM_VALUE_3 case ENUM_VALUE_4 case ENUM_VALUE_5 var rawValue: RawValue { switch self { case .ENUM_VALUE_0: return 0 + 0 case .ENUM_VALUE_1: return -32768 + 0 case .ENUM_VALUE_2: return -32768 + 1 case .ENUM_VALUE_3: return 32766 + 0 case .ENUM_VALUE_4: return 32766 + 1 case .ENUM_VALUE_5: return Self.ENUM_VALUE_3.rawValue } } init(value: Int8) { self = EnumInt16Enum(rawValue: NSNumber(value: value).int16Value) } init(value: Int16) { self = EnumInt16Enum(rawValue: NSNumber(value: value).int16Value) } init(value: Int32) { self = EnumInt16Enum(rawValue: NSNumber(value: value).int16Value) } init(value: Int64) { self = EnumInt16Enum(rawValue: NSNumber(value: value).int16Value) } init(value: EnumInt16Enum) { self = EnumInt16Enum(rawValue: value.rawValue) } init(rawValue: Int16) { self = Self.mapValue(value: rawValue)! } var description: String { switch self { case .ENUM_VALUE_0: return "ENUM_VALUE_0" case .ENUM_VALUE_1: return "ENUM_VALUE_1" case .ENUM_VALUE_2: return "ENUM_VALUE_2" case .ENUM_VALUE_3: return "ENUM_VALUE_3" case .ENUM_VALUE_4: return "ENUM_VALUE_4" case .ENUM_VALUE_5: return "ENUM_VALUE_5" } } static let rawValuesMap: [RawValue: EnumInt16Enum] = { var value = [RawValue: EnumInt16Enum]() value[EnumInt16Enum.ENUM_VALUE_0.rawValue] = .ENUM_VALUE_0 value[EnumInt16Enum.ENUM_VALUE_1.rawValue] = .ENUM_VALUE_1 value[EnumInt16Enum.ENUM_VALUE_2.rawValue] = .ENUM_VALUE_2 value[EnumInt16Enum.ENUM_VALUE_3.rawValue] = .ENUM_VALUE_3 value[EnumInt16Enum.ENUM_VALUE_4.rawValue] = .ENUM_VALUE_4 value[EnumInt16Enum.ENUM_VALUE_5.rawValue] = .ENUM_VALUE_5 return value }() static func mapValue(value: Int16) -> EnumInt16Enum? { return rawValuesMap[value] } }
38.68254
92
0.63808
e21947008d93826f49c4421f2a7f635239d1d04a
1,322
import UIKit import WoWonderTimelineSDK class MyPointSectionThreeTableItem: UITableViewCell { @IBOutlet weak var tapView: RoundButton! @IBOutlet weak var earbLBl: UILabel! @IBOutlet weak var waleetLbl: UILabel! var vc:MyPointsVC? override func awakeFromNib() { super.awakeFromNib() let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:))) tapView.addGestureRecognizer(tap) self.earbLBl.text = NSLocalizedString("You erarned points will automatically go to", comment: "You erarned points will automatically go to") self.waleetLbl.text = NSLocalizedString("#Wallet", comment: "#Wallet") } @objc func handleTap(_ sender: UITapGestureRecognizer? = nil) { let storyBoard = UIStoryboard(name: "Main", bundle: nil) let vc = storyBoard.instantiateViewController(withIdentifier: "WalletVC") as! WalletMainController vc.mybalance = AppInstance.instance.profile?.userData?.wallet ?? "" if (ControlSettings.showPaymentVC == true){ self.vc?.navigationController?.pushViewController(vc, animated: true) } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
35.72973
148
0.681543
ed0a0522f296bf90ac640662f77630e18f42118d
4,111
// // SmartSleep.swift // SmartSleep // // Created by Michael Greb on 6/27/19. // Copyright © 2019 Michael Greb. All rights reserved. // import SwiftUI import Combine class SmartSleep: BindableObject { var didChange = PassthroughSubject<Void,Never>() var output = "" { didSet { didChange.send() } } static var shared = SmartSleep() private init() {} func sleepWhenClear() { _ = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: true) { timer in self.sleepIfClear() print("Waiting...") } } func sleepIfClear() { update() if !backupRunning() { #if DEBUG print("Would have slept") #else let task = Process() task.launchPath = "/usr/bin/pmset" task.arguments = [ "sleepnow" ] task.launch() exit(0) #endif } } func update() { let task = Process() task.launchPath = "/usr/bin/tmutil" task.arguments = ["status"] let pipe = Pipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let stdoutput = String(bytes: data, encoding: .utf8) // let stdoutput = """ //{ // BackupPhase = Copying; // ClientID = "com.apple.backupd"; // DateOfStateChange = "2019-06-27 14:39:36 +0000"; // DestinationID = "E233207A-397B-4D95-B25F-99281FD6F679"; // Progress = { // Percent = "0.3652448416872661"; // TimeRemaining = 232; // "_raw_Percent" = "0.3652448416872661"; // "_raw_totalBytes" = 622970323; // bytes = 227536697; // files = 5962; // totalBytes = 622970323; // totalFiles = 5962; // }; // Running = 1; // Stopping = 0; //} //""" output = stdoutput! } private func extractMatch(pattern: String) -> Substring? { let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) if let match = regex?.firstMatch(in: output, options: [], range: NSRange(location: 0, length: output.utf16.count)) { if let matchRange = Range(match.range(at: 1), in: output) { return output[matchRange] } } return nil } func backupRunning() -> Bool { if extractMatch(pattern: "Running = (\\d+);") == "1" { return true } else { return false } } func phase() -> String { return String(extractMatch(pattern:"BackupPhase = (\\S+);") ?? "Unknown") } func percentComplete() -> String { if let percent = extractMatch(pattern:"Percent = \"(\\S+)\";") { return String(format: "%.0f", Double(percent)! * 100) } return "Unknown" } private func formatBytes(bytes: Double) -> String { var size = bytes if size < 1024 { return String(format: "%.0f B", size) } size = size / 1024 if size < 1024 { return String(format: "%.0f KB", size) } size = size / 1024 return String(format: "%.0f MB", size) } func bytesDone() -> String { let bytes = Double(extractMatch(pattern:"bytes = (\\d+);") ?? Substring("0")) return formatBytes(bytes: bytes ?? 0) } func bytesTotal() -> String { let bytes = Double(extractMatch(pattern:"totalBytes = (\\d+);") ?? Substring("0")) return formatBytes(bytes: bytes ?? 0) } func timeRemaining() -> String { if let text = extractMatch(pattern:"TimeRemaining = (\\d+);") { return TimeInterval(Double(text)!).stringFormatted() } return "Unknown" } } extension TimeInterval { func stringFormatted() -> String { let interval = Int(self) let seconds = interval % 60 let minutes = (interval / 60) % 60 return String(format: "%02d:%02d", minutes, seconds) } }
27.965986
124
0.530041
fc50eda52fc3580083cab0115826ed5545fce34e
5,207
// // EMLocationViewController.swift // Hyphenate-Demo-Swift // // Created by dujiepeng on 2017/6/26. // Copyright © 2017 dujiepeng. All rights reserved. // import UIKit import MapKit import CoreLocation import MBProgressHUD @objc protocol EMLocationViewDelegate { func sendLocation(_ latitude: Double, _ longitude: Double, _ address: String) } class EMLocationViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var sendButton: UIButton! var _addressString: String? var _backAction: UIButton? private var _locationManager: CLLocationManager? private var _currentLocationCoordinate: CLLocationCoordinate2D? private var _isShowLocation: Bool = false private var _annotation: MKPointAnnotation? weak var delegate: EMLocationViewDelegate? init(location: CLLocationCoordinate2D) { super.init(nibName: "EMLocationViewController", bundle: nil) _currentLocationCoordinate = location _isShowLocation = true } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupView() { _backAction = UIButton(type: UIButtonType.custom) _backAction!.frame = CGRect(x: 0, y: 0, width: 8, height: 15) _backAction!.setImage(UIImage(named:"Icon_Back"), for: UIControlState.normal) _backAction!.addTarget(self, action: #selector(backAction), for: UIControlEvents.touchUpInside) } override func viewDidLoad() { super.viewDidLoad() setupView() if _isShowLocation { removeToLocation(locationCoordinate: _currentLocationCoordinate!) sendButton.isHidden = true } else { mapView.showsUserLocation = true mapView.delegate = self _startLocation() view.bringSubview(toFront: sendButton) } navigationItem.leftBarButtonItem = UIBarButtonItem(customView: _backAction!) } func backAction() { navigationController?.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: Action @IBAction func sendLocationAction(_ sender: Any) { if delegate != nil && _currentLocationCoordinate != nil { delegate?.sendLocation((_currentLocationCoordinate?.latitude)!, (_currentLocationCoordinate?.longitude)!, _addressString!) } navigationController?.popViewController(animated: true) } // MARK: - MKMapViewDelegate func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { let geocorde = CLGeocoder() weak var weakSelf = self geocorde.reverseGeocodeLocation(userLocation.location!) { (array, error) in if error == nil && (array?.count)! > 0 { let placeMark = array?.first weakSelf?._addressString = placeMark?.name weakSelf?.removeToLocation(locationCoordinate: userLocation.coordinate) } } } func mapViewDidFailLoadingMap(_ mapView: MKMapView, withError error: Error) { } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case CLAuthorizationStatus.notDetermined: _locationManager?.requestAlwaysAuthorization() break default: break } } // MARK: - Private func createAnnotation(withCoord coord: CLLocationCoordinate2D) { if _annotation == nil { _annotation = MKPointAnnotation.init() }else { mapView.removeAnnotation(_annotation!) } _annotation?.coordinate = coord mapView.addAnnotation(_annotation!) } func removeToLocation(locationCoordinate: CLLocationCoordinate2D) { MBProgressHUD.hide(for: view, animated: true) _currentLocationCoordinate = locationCoordinate let zoomLevel: Float = 0.01 let region = MKCoordinateRegion.init(center: _currentLocationCoordinate!, span: MKCoordinateSpanMake(CLLocationDegrees(zoomLevel), CLLocationDegrees(zoomLevel))) mapView.setRegion(mapView.regionThatFits(region), animated: true) if _isShowLocation { navigationItem.rightBarButtonItem?.isEnabled = true } self.createAnnotation(withCoord: _currentLocationCoordinate!) } func _startLocation() { MBProgressHUD.showAdded(to: view, animated: true) if CLLocationManager.locationServicesEnabled() { _locationManager = CLLocationManager() _locationManager?.delegate = self _locationManager?.distanceFilter = 5 _locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation _locationManager?.requestAlwaysAuthorization() } } }
34.713333
169
0.669675
465a6c0b9546f8e39566e4ac913bc380563b0136
7,857
// // AppDelegate.swift // rgby-ios // // Created by John D. Gaffney on 11/9/18. // Copyright © 2018 gffny.com. All rights reserved. // import UIKit import CoreData import RealmSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { static var RGBY_IOS_PERSISTENT_CONTAINER_NAME = "rgby_ios" // FIXME change this to be a user when handling logins static var COACH_ID = "12345" static var TEAM_ID = "team-1" var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // FIXME no need to use a specific Realm configuration just yet let realm = try! Realm() if realm.objects(RGBYCoach.self).count == 0 { // check if we want to load demo data RGBYDemoData.loadDemoData(in: realm) } // check if there have been any updates to the data in the API RGBYDataAPI.getCoach(id: AppDelegate.COACH_ID, onSuccess: { (result) -> Void in print("retrieved coach data for coach with id: \(result.id)") // get the logged in coaches detail var coach = RGBYCoach.get(id: result.id, in: try! Realm()) if coach == nil { coach = RGBYCoach.create(coach: result, in: try! Realm()) } // check if the api data last update is newer than the stored last update else if result.lastUpdate > coach!.lastUpdate { print("current coach data is behind api data; requesting data update") // request update of core data //FIXME Match List RGBYDataAPI.getMatchList(teamId: AppDelegate.TEAM_ID, onSuccess: { (result) -> Void in // TODO store updated data in local repo print(result.count) }, onFailure: {_ in print("error") }) // TODO Squad List RGBYDataAPI.getSquadList(onSuccess: { (result) in // TODO store updated player data in local repo print(result.count) }, onFailure: {_ in print("error") }) } coach = RGBYCoach.updateLastLogin(coach: coach!, in: try! Realm()) print("updated coach last login to "+RGBYUtils.mmddyyyhhmm().string(from: (coach?.lastLogin)!)) }, onFailure: {_ in print("error") }, onOffline: { print("iPad is offline") }) if let matchDetailDO = RGBYMatchDetailDO.getActiveDetail() { print("there's an active detail") // TODO need to figure out how we make the correct view open up? // Do we prompt the user to go to the active match screen? // Do we jump directly to the active match screen? let matchDetail = RGBYMatchDetail(mddo: matchDetailDO) } self.configureStyle() return true } func configureStyle() { UINavigationBar.appearance().barTintColor = UIColor.darkGray UINavigationBar.appearance().isTranslucent = true UINavigationBar.appearance().tintColor = UIColor.white UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "Helvetica Neue", size: 16.0)!] } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { return false } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: AppDelegate.RGBY_IOS_PERSISTENT_CONTAINER_NAME) container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
48.202454
285
0.649357
26a8dd9c6d8b5b0b8dd523fd1b7678fc63a0b64c
368
// // EighthCutsceneViewController.swift // ChinchillOut-GAM720 // // Created by Rachel Saunders on 18/05/2020. // Copyright © 2020 Rachel Saunders. All rights reserved. // import UIKit class EighthCutsceneViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // ITS SILENT SO NO BIRD SOUNDS } }
17.52381
58
0.679348
defbbf016f22cc8aa6c839697515b945d10309f2
2,216
// // AppDelegate.swift // SwiftPlayer // // Created by iTSangar on 04/07/2016. // Copyright (c) 2016 iTSangar. All rights reserved. // import UIKit import AVFoundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UIApplication.shared.statusBarStyle = .lightContent return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
43.45098
281
0.767599
28721bb475ef010beb710cbf0be97152b024e8a8
1,063
/* * Copyright (C) 2019-2021 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } }
32.212121
115
0.723424
d7bf725642985e4df13a601cbc77cb15e1d6741e
2,963
// Copyright © 2018 Stormbird PTE. LTD. import Foundation import PromiseKit import web3swift //TODO maybe we should cache promises that haven't resolved yet. This is useful/needed because users can switch between Wallet and Transactions tab multiple times quickly and trigger the same call to fire many times before any of them have been completed func callSmartContract(withServer server: RPCServer, contract: AlphaWallet.Address, functionName: String, abiString: String, parameters: [AnyObject] = [AnyObject]()) -> Promise<[String: Any]> { return firstly { () -> Promise<(EthereumAddress)> in let contractAddress = EthereumAddress(address: contract) return .value(contractAddress) }.then { contractAddress -> Promise<[String: Any]> in guard let webProvider = Web3HttpProvider(server.rpcURL, network: server.web3Network) else { return Promise(error: Web3Error(description: "Error creating web provider for: \(server.rpcURL) + \(server.web3Network)")) } let web3 = web3swift.web3(provider: webProvider) guard let contractInstance = web3swift.web3.web3contract(web3: web3, abiString: abiString, at: contractAddress, options: web3.options) else { return Promise(error: Web3Error(description: "Error creating web3swift contract instance to call \(functionName)()")) } guard let promiseCreator = contractInstance.method(functionName, parameters: parameters, options: nil) else { return Promise(error: Web3Error(description: "Error calling \(contract.eip55String).\(functionName)() with parameters: \(parameters)")) } //callPromise() creates a promise. It doesn't "call" a promise. Bad name return promiseCreator.callPromise(options: nil) } } func getEventLogs( withServer server: RPCServer, contract: AlphaWallet.Address, eventName: String, abiString: String, filter: EventFilter ) -> Promise<[EventParserResultProtocol]> { firstly { () -> Promise<(EthereumAddress)> in let contractAddress = EthereumAddress(address: contract) return .value(contractAddress) }.then { contractAddress -> Promise<[EventParserResultProtocol]> in guard let webProvider = Web3HttpProvider(server.rpcURL, network: server.web3Network) else { return Promise(error: Web3Error(description: "Error creating web provider for: \(server.rpcURL) + \(server.web3Network)")) } let web3 = web3swift.web3(provider: webProvider) guard let contractInstance = web3swift.web3.web3contract(web3: web3, abiString: abiString, at: contractAddress, options: web3.options) else { return Promise(error: Web3Error(description: "Error creating web3swift contract instance to call \(eventName)()")) } return contractInstance.getIndexedEventsPromise( eventName: eventName, filter: filter ) } }
51.982456
254
0.701316
16ba22064fed0ccba16fbbb56f0a318d52dcfdfd
2,563
// // ViewController.swift // WikiFace // // Created by Allen on 16/2/10. // Copyright © 2016年 Allen. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var faceImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() nameTextField.delegate = self self.faceImageView.alpha = 0 self.faceImageView.transform = CGAffineTransform(scaleX: 0.2, y: 0.2) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() if let textFieldContent = textField.text { do { try WikiFace.faceForPerson(textFieldContent, size: CGSize(width: 300, height: 400), completion: { (image:UIImage?, imageFound:Bool!) -> () in if imageFound == true { DispatchQueue.main.async(execute: { () -> Void in self.faceImageView.image = image UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseIn, animations: { () -> Void in self.faceImageView.transform = CGAffineTransform(scaleX: 1, y: 1) self.faceImageView.alpha = 1 //Fuck! Useless...LOL self.faceImageView.layer.shadowOpacity = 0.4 self.faceImageView.layer.shadowOffset = CGSize(width: 3.0, height: 2.0) self.faceImageView.layer.shadowRadius = 15.0 self.faceImageView.layer.shadowColor = UIColor.black.cgColor }, completion: nil ) WikiFace.centerImageViewOnFace(self.faceImageView) }) } }) }catch WikiFace.WikiFaceError.couldNotDownloadImage{ print("Could not access wikipedia for downloading an image") } catch { print(error) } } return true } }
35.109589
177
0.504097
016739633416eda8c0f96aa9997e68db3e009d1d
393
import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) return true } }
35.727273
145
0.748092
e91ec21a9ddc522ad63959933a1b15b8548c3214
663
import UIKit import Foundation public extension UIView { public func alignToView(_ view: UIView) { addConstraintToView(view, attribute: .top, constant: 0) addConstraintToView(view, attribute: .bottom, constant: 0) addConstraintToView(view, attribute: .leading, constant: 0) addConstraintToView(view, attribute: .trailing, constant: 0) } private func addConstraintToView(_ view: UIView, attribute: NSLayoutAttribute, constant: CGFloat) { addConstraint(NSLayoutConstraint(item: view, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1.0, constant: constant)) } }
41.4375
167
0.719457
28f9f6a3792309b431c2968729ac8bbbdeb9b050
158
// // Deal.swift // geekTime // // Created by ChenZhen on 2021/9/23. // import Foundation struct Deal { var product: Product var progress: Int }
11.285714
37
0.632911
75f9959a13d20d96d6209c3b1f438122f1891c03
471
// Copyright (c) 2017-2019 Coinbase Inc. See LICENSE import Foundation /// Dependencies-related Error public enum DependenciesError: Error { /// Error thrown when unable to resolve dependency case unableToResolveDependency(InjectionKeys) /// Error thrown when injection doesn't supply the correct list of parameters case missingParameters /// Error thrown when injection is not implemented while resolving a key case injectionNotImplemented }
29.4375
81
0.766454
cc45f9ce4355cb49e36d88ba4ddeb3def25f5b3b
4,077
// // MGNavController.swift // MGDYZB // // Created by ming on 16/10/25. // Copyright © 2016年 ming. All rights reserved. // import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class MGNavController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() /* // 1.获取系统的Pop手势 guard let systemGes = interactivePopGestureRecognizer else { return } // 2.获取target/action // 2.1.利用运行时机制查看所有的属性名称 var count : UInt32 = 0 let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)! for i in 0..<count { let ivar = ivars[Int(i)] let name = ivar_getName(ivar) print(String(cString: name!)) } */ // 0.设置导航栏的颜色 setUpNavAppearance () // 1.创建Pan手势 let target = navigationController?.interactivePopGestureRecognizer?.delegate let pan = UIPanGestureRecognizer(target: target, action: Selector(("handleNavigationTransition:"))) pan.delegate = self self.view.addGestureRecognizer(pan) // 2.禁止系统的局部返回手势 navigationController?.interactivePopGestureRecognizer?.isEnabled = false self.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - 拦截Push操作 override func pushViewController(_ viewController: UIViewController, animated: Bool) { // 这里判断是否进入push视图 if (self.childViewControllers.count > 0) { let backBtn = UIButton(image: #imageLiteral(resourceName: "back"), highlightedImage: #imageLiteral(resourceName: "backBarButtonItem"), title: "返回",target: self, action: #selector(MGNavController.backClick)) // 设置按钮内容左对齐 backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left; // 内边距 backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0); viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) // 隐藏要push的控制器的tabbar viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } @objc fileprivate func backClick() { popViewController(animated: true) } } extension MGNavController : UIGestureRecognizerDelegate{ func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { ///判断是否是根控制器 if self.childViewControllers.count == 1 { return false } return true } } extension MGNavController { fileprivate func setUpNavAppearance () { let navBar = UINavigationBar.appearance() if(Double(UIDevice.current.systemVersion)) > 8.0 { navBar.isTranslucent = true } else { self.navigationBar.isTranslucent = true } navBar.tintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1.00) navBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white,NSFontAttributeName:UIFont.boldSystemFont(ofSize: 18)] } } extension MGNavController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { if viewController is LiveViewController { navigationController.navigationBar.barTintColor = UIColor.yellow }else { navigationController.navigationBar.barTintColor = UIColor.orange } } }
31.604651
218
0.628649
e94e566f88a34c5314ded3e8610983930f42dd1a
13,401
// // UIView+AutoLayout.swift // XMGWeibo // // Created by 李南江 on 15/9/1. // Copyright © 2015年 xiaomage. All rights reserved. // import UIKit /** 对齐类型枚举,设置控件相对于父视图的位置 - TopLeft: 左上 - TopRight: 右上 - TopCenter: 中上 - BottomLeft: 左下 - BottomRight: 右下 - BottomCenter: 中下 - CenterLeft: 左中 - CenterRight: 右中 - Center: 中中 */ public enum XMG_AlignType { case TopLeft case TopRight case TopCenter case BottomLeft case BottomRight case BottomCenter case CenterLeft case CenterRight case Center private func layoutAttributes(isInner: Bool, isVertical: Bool) -> XMG_LayoutAttributes { let attributes = XMG_LayoutAttributes() switch self { case .TopLeft: attributes.horizontals(.Left, to: .Left).verticals(.Top, to: .Top) if isInner { return attributes } else if isVertical { return attributes.verticals(.Bottom, to: .Top) } else { return attributes.horizontals(.Right, to: .Left) } case .TopRight: attributes.horizontals(.Right, to: .Right).verticals(.Top, to: .Top) if isInner { return attributes } else if isVertical { return attributes.verticals(.Bottom, to: .Top) } else { return attributes.horizontals(.Left, to: .Right) } case .BottomLeft: attributes.horizontals(.Left, to: .Left).verticals(.Bottom, to: .Bottom) if isInner { return attributes } else if isVertical { return attributes.verticals(.Top, to: .Bottom) } else { return attributes.horizontals(.Right, to: .Left) } case .BottomRight: attributes.horizontals(.Right, to: .Right).verticals(.Bottom, to: .Bottom) if isInner { return attributes } else if isVertical { return attributes.verticals(.Top, to: .Bottom) } else { return attributes.horizontals(.Left, to: .Right) } // 仅内部 & 垂直参照需要 case .TopCenter: attributes.horizontals(.CenterX, to: .CenterX).verticals(.Top, to: .Top) return isInner ? attributes : attributes.verticals(.Bottom, to: .Top) // 仅内部 & 垂直参照需要 case .BottomCenter: attributes.horizontals(.CenterX, to: .CenterX).verticals(.Bottom, to: .Bottom) return isInner ? attributes : attributes.verticals(.Top, to: .Bottom) // 仅内部 & 水平参照需要 case .CenterLeft: attributes.horizontals(.Left, to: .Left).verticals(.CenterY, to: .CenterY) return isInner ? attributes : attributes.horizontals(.Right, to: .Left) // 仅内部 & 水平参照需要 case .CenterRight: attributes.horizontals(.Right, to: .Right).verticals(.CenterY, to: .CenterY) return isInner ? attributes : attributes.horizontals(.Left, to: .Right) // 仅内部参照需要 case .Center: return XMG_LayoutAttributes(horizontal: .CenterX, referHorizontal: .CenterX, vertical: .CenterY, referVertical: .CenterY) } } } extension UIView { /** 填充子视图 :param: referView 参考视图 :param: insets 间距 :returns: 约束数组 */ public func xmg_Fill(referView: UIView, insets: UIEdgeInsets = UIEdgeInsetsZero) -> [NSLayoutConstraint] { translatesAutoresizingMaskIntoConstraints = false var cons = [NSLayoutConstraint]() cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-\(insets.left)-[subView]-\(insets.right)-|", options: NSLayoutFormatOptions.AlignAllLastBaseline, metrics: nil, views: ["subView" : self]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(insets.top)-[subView]-\(insets.bottom)-|", options: NSLayoutFormatOptions.AlignAllLastBaseline, metrics: nil, views: ["subView" : self]) superview?.addConstraints(cons) return cons } /** 参照参考视图内部对齐 :param: type 对齐方式 :param: referView 参考视图 :param: size 视图大小,如果是 nil 则不设置大小 :param: offset 偏移量,默认是 CGPoint(x: 0, y: 0) :returns: 约束数组 */ public func xmg_AlignInner(type type: XMG_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPointZero) -> [NSLayoutConstraint] { return xmg_AlignLayout(referView, attributes: type.layoutAttributes(true, isVertical: true), size: size, offset: offset) } /** 参照参考视图垂直对齐 :param: type 对齐方式 :param: referView 参考视图 :param: size 视图大小,如果是 nil 则不设置大小 :param: offset 偏移量,默认是 CGPoint(x: 0, y: 0) :returns: 约束数组 */ public func xmg_AlignVertical(type type: XMG_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPointZero) -> [NSLayoutConstraint] { return xmg_AlignLayout(referView, attributes: type.layoutAttributes(false, isVertical: true), size: size, offset: offset) } /** 参照参考视图水平对齐 :param: type 对齐方式 :param: referView 参考视图 :param: size 视图大小,如果是 nil 则不设置大小 :param: offset 偏移量,默认是 CGPoint(x: 0, y: 0) :returns: 约束数组 */ public func xmg_AlignHorizontal(type type: XMG_AlignType, referView: UIView, size: CGSize?, offset: CGPoint = CGPointZero) -> [NSLayoutConstraint] { return xmg_AlignLayout(referView, attributes: type.layoutAttributes(false, isVertical: false), size: size, offset: offset) } /** 在当前视图内部水平平铺控件 :param: views 子视图数组 :param: insets 间距 :returns: 约束数组 */ public func xmg_HorizontalTile(views: [UIView], insets: UIEdgeInsets) -> [NSLayoutConstraint] { assert(!views.isEmpty, "views should not be empty") var cons = [NSLayoutConstraint]() let firstView = views[0] firstView.xmg_AlignInner(type: XMG_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: insets.left, y: insets.top)) cons.append(NSLayoutConstraint(item: firstView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -insets.bottom)) // 添加后续视图的约束 var preView = firstView for i in 1..<views.count { let subView = views[i] cons += subView.xmg_sizeConstraints(firstView) subView.xmg_AlignHorizontal(type: XMG_AlignType.TopRight, referView: preView, size: nil, offset: CGPoint(x: insets.right, y: 0)) preView = subView } let lastView = views.last! cons.append(NSLayoutConstraint(item: lastView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -insets.right)) addConstraints(cons) return cons } /** 在当前视图内部垂直平铺控件 :param: views 子视图数组 :param: insets 间距 :returns: 约束数组 */ public func xmg_VerticalTile(views: [UIView], insets: UIEdgeInsets) -> [NSLayoutConstraint] { assert(!views.isEmpty, "views should not be empty") var cons = [NSLayoutConstraint]() let firstView = views[0] firstView.xmg_AlignInner(type: XMG_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: insets.left, y: insets.top)) cons.append(NSLayoutConstraint(item: firstView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -insets.right)) // 添加后续视图的约束 var preView = firstView for i in 1..<views.count { let subView = views[i] cons += subView.xmg_sizeConstraints(firstView) subView.xmg_AlignVertical(type: XMG_AlignType.BottomLeft, referView: preView, size: nil, offset: CGPoint(x: 0, y: insets.bottom)) preView = subView } let lastView = views.last! cons.append(NSLayoutConstraint(item: lastView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -insets.bottom)) addConstraints(cons) return cons } /** 从约束数组中查找指定 attribute 的约束 :param: constraintsList 约束数组 :param: attribute 约束属性 :returns: 对应的约束 */ public func xmg_Constraint(constraintsList: [NSLayoutConstraint], attribute: NSLayoutAttribute) -> NSLayoutConstraint? { for constraint in constraintsList { if constraint.firstItem as! NSObject == self && constraint.firstAttribute == attribute { return constraint } } return nil } // MARK: - 私有函数 /** 参照参考视图对齐布局 :param: referView 参考视图 :param: attributes 参照属性 :param: size 视图大小,如果是 nil 则不设置大小 :param: offset 偏移量,默认是 CGPoint(x: 0, y: 0) :returns: 约束数组 */ private func xmg_AlignLayout(referView: UIView, attributes: XMG_LayoutAttributes, size: CGSize?, offset: CGPoint) -> [NSLayoutConstraint] { translatesAutoresizingMaskIntoConstraints = false var cons = [NSLayoutConstraint]() cons += xmg_positionConstraints(referView, attributes: attributes, offset: offset) if size != nil { cons += xmg_sizeConstraints(size!) } superview?.addConstraints(cons) return cons } /** 尺寸约束数组 :param: size 视图大小 :returns: 约束数组 */ private func xmg_sizeConstraints(size: CGSize) -> [NSLayoutConstraint] { var cons = [NSLayoutConstraint]() cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: size.width)) cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: size.height)) return cons } /** 尺寸约束数组 :param: referView 参考视图,与参考视图大小一致 :returns: 约束数组 */ private func xmg_sizeConstraints(referView: UIView) -> [NSLayoutConstraint] { var cons = [NSLayoutConstraint]() cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0)) cons.append(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 0)) return cons } /** 位置约束数组 :param: referView 参考视图 :param: attributes 参照属性 :param: offset 偏移量 :returns: 约束数组 */ private func xmg_positionConstraints(referView: UIView, attributes: XMG_LayoutAttributes, offset: CGPoint) -> [NSLayoutConstraint] { var cons = [NSLayoutConstraint]() cons.append(NSLayoutConstraint(item: self, attribute: attributes.horizontal, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: attributes.referHorizontal, multiplier: 1.0, constant: offset.x)) cons.append(NSLayoutConstraint(item: self, attribute: attributes.vertical, relatedBy: NSLayoutRelation.Equal, toItem: referView, attribute: attributes.referVertical, multiplier: 1.0, constant: offset.y)) return cons } } /// 布局属性 private final class XMG_LayoutAttributes { var horizontal: NSLayoutAttribute var referHorizontal: NSLayoutAttribute var vertical: NSLayoutAttribute var referVertical: NSLayoutAttribute init() { horizontal = NSLayoutAttribute.Left referHorizontal = NSLayoutAttribute.Left vertical = NSLayoutAttribute.Top referVertical = NSLayoutAttribute.Top } init(horizontal: NSLayoutAttribute, referHorizontal: NSLayoutAttribute, vertical: NSLayoutAttribute, referVertical: NSLayoutAttribute) { self.horizontal = horizontal self.referHorizontal = referHorizontal self.vertical = vertical self.referVertical = referVertical } private func horizontals(from: NSLayoutAttribute, to: NSLayoutAttribute) -> Self { horizontal = from referHorizontal = to return self } private func verticals(from: NSLayoutAttribute, to: NSLayoutAttribute) -> Self { vertical = from referVertical = to return self } }
35.640957
222
0.611969
fc6aee1492dd952be71e329d930bfb8cad268ef9
2,179
// // HotspotChildController1.swift // CFStreamingVideo // // Created by chenfeng on 2019/10/9. // Copyright © 2019 chenfeng. All rights reserved. // import UIKit class HotspotChildController1: CFBaseController { var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: view.mj_w, height: view.mj_h - TABBAR_HEIGHT - navItemViewHeight - searchViewHeight - (STATUS_AND_NAV_BAR_HEIGHT - 40)), style: .plain) tableView.backgroundColor = .white tableView.dataSource = self; tableView.delegate = self; view.addSubview(tableView) if #available(iOS 11.0, *) { tableView.contentInsetAdjustmentBehavior = .never } self.headFillView.bringSubviewToFront(tableView) } /* // 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. } */ } extension HotspotChildController1: UITableViewDelegate { } extension HotspotChildController1: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 200 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: HotspotCell1? = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier") as? HotspotCell1 if cell == nil { cell = HotspotCell1.init(style: .default, reuseIdentifier: "CellIdentifier") } cell?.imageVW.image = UIImage.init(named: "ad1"); cell?.titleStr.text = "广告" return cell! } }
28.298701
205
0.648922
792a857dadc20143b86a1e39896add36300b406e
1,339
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" public struct SNStack<T> { // Create Array and use it for stacking // LIFO fileprivate var array = Array<T>() /** checks for stack emptiness */ public var isEmpty: Bool { return array.isEmpty } /** returns stack count */ public var count: Int { return array.count } /** Appends the new element on the stack */ public mutating func push(_ element: T) { array.append(element) } /** Removes and returns the last element */ public mutating func pop() -> T? { return array.popLast() } /** Returns the top element on the stack */ public func topElement() -> T? { return array.last } } // Int type var stackedArray = SNStack<Int>() print(stackedArray.isEmpty) stackedArray.push(4) stackedArray.push(10) stackedArray.push(20) print(stackedArray) print(stackedArray.topElement()) stackedArray.pop() print(stackedArray) print(stackedArray.count) // Any type var strStack = SNStack<Any>() strStack.push("First") strStack.push(5) strStack.push(4.5) strStack.push(stackedArray) print(strStack) print(strStack.topElement()) strStack.pop() print(strStack)
16.530864
52
0.626587
e2a3b1cd744baec91836a4774fcf15931d7363cf
15,533
// // WalletConnectCoordinator.swift // AlphaWallet // // Created by Vladyslav Shepitko on 02.07.2020. // import UIKit import WalletConnectSwift import PromiseKit import Result typealias WalletConnectURL = WCURL typealias WalletConnectSession = Session enum SessionsToDisconnect { case allExcept(_ servers: [RPCServer]) case all } typealias SessionsToURLServersMap = (sessions: [WalletConnectSession], urlToServer: [WCURL: RPCServer]) class WalletConnectCoordinator: NSObject, Coordinator { private lazy var server: WalletConnectServer = { let server = WalletConnectServer(wallet: sessions.anyValue.account.address) server.delegate = self return server }() private let navigationController: UINavigationController var coordinators: [Coordinator] = [] var sessionsToURLServersMap: Subscribable<SessionsToURLServersMap> = .init(nil) private let keystore: Keystore private let sessions: ServerDictionary<WalletSession> private let analyticsCoordinator: AnalyticsCoordinator private let config: Config private let nativeCryptoCurrencyPrices: ServerDictionary<Subscribable<Double>> private weak var notificationAlertController: UIViewController? private var serverChoices: [RPCServer] { ServersCoordinator.serversOrdered.filter { config.enabledServers.contains($0) } } private weak var sessionsViewController: WalletConnectSessionsViewController? init(keystore: Keystore, sessions: ServerDictionary<WalletSession>, navigationController: UINavigationController, analyticsCoordinator: AnalyticsCoordinator, config: Config, nativeCryptoCurrencyPrices: ServerDictionary<Subscribable<Double>>) { self.config = config self.sessions = sessions self.keystore = keystore self.navigationController = navigationController self.analyticsCoordinator = analyticsCoordinator self.nativeCryptoCurrencyPrices = nativeCryptoCurrencyPrices super.init() start() server.sessions.subscribe { [weak self, weak server] sessions in guard let strongSelf = self, let strongServer = server else { return } strongSelf.sessionsToURLServersMap.value = (sessions ?? [], strongServer.urlToServer) } } //NOTE: we are using disconnection to notify dapp that we get disconnect, in other case dapp still stay connected func disconnect(sessionsToDisconnect: SessionsToDisconnect) { let walletConnectSessions = UserDefaults.standard.walletConnectSessions let filteredSessions: [WalletConnectSession] switch sessionsToDisconnect { case .all: filteredSessions = walletConnectSessions case .allExcept(let servers): //NOTE: as we got stored session urls mapped with rpc servers we can filter urls and exclude unused session let sessionURLsToDisconnect = UserDefaults.standard.urlToServer.map { (key: $0.key, server: $0.value) }.filter { !servers.contains($0.server) }.map { $0.key } filteredSessions = walletConnectSessions.filter { sessionURLsToDisconnect.contains($0.url) } } for each in filteredSessions { try? server.disconnect(session: each) } } private func start() { for each in UserDefaults.standard.walletConnectSessions { try? server.reconnect(session: each) } } func openSession(url: WalletConnectURL) { navigationController.setNavigationBarHidden(false, animated: true) showSessions(state: .loading, navigationController: navigationController) { try? self.server.connect(url: url) } } func showSessionDetails(inNavigationController navigationController: UINavigationController) { guard let sessions = server.sessions.value, !sessions.isEmpty else { return } if sessions.count == 1 { let session = sessions[0] display(session: session, withNavigationController: navigationController) } else { showSessions(state: .sessions, navigationController: navigationController) } } private func showSessions(state: WalletConnectSessionsViewController.State, navigationController: UINavigationController, completion: @escaping (() -> Void) = {}) { let viewController = WalletConnectSessionsViewController(sessionsToURLServersMap: sessionsToURLServersMap) viewController.delegate = self viewController.configure(state: state) self.sessionsViewController = viewController navigationController.pushViewController(viewController, animated: true, completion: completion) } private func display(session: WalletConnectSession, withNavigationController navigationController: UINavigationController) { let coordinator = WalletConnectSessionCoordinator(navigationController: navigationController, server: server, session: session) coordinator.delegate = self coordinator.start() addCoordinator(coordinator) } } extension WalletConnectCoordinator: WalletConnectSessionCoordinatorDelegate { func didDismiss(in coordinator: WalletConnectSessionCoordinator) { removeCoordinator(coordinator) } } extension WalletConnectCoordinator: WalletConnectServerDelegate { func server(_ server: WalletConnectServer, didConnect session: WalletConnectSession) { if let viewController = sessionsViewController { viewController.set(state: .sessions) } } func server(_ server: WalletConnectServer, action: WalletConnectServer.Action, request: WalletConnectRequest) { if let rpcServer = server.urlToServer[request.url] { let session = sessions[rpcServer] firstly { Promise<Void> { seal in switch session.account.type { case .real: seal.fulfill(()) case .watch: seal.reject(PMKError.cancelled) } } }.then { _ -> Promise<WalletConnectServer.Callback> in let account = session.account.address switch action.type { case .signTransaction(let transaction): return self.executeTransaction(session: session, callbackID: action.id, url: action.url, transaction: transaction, type: .sign) case .sendTransaction(let transaction): return self.executeTransaction(session: session, callbackID: action.id, url: action.url, transaction: transaction, type: .signThenSend) case .signMessage(let hexMessage): return self.signMessage(with: .message(hexMessage.toHexData), account: account, callbackID: action.id, url: action.url) case .signPersonalMessage(let hexMessage): return self.signMessage(with: .personalMessage(hexMessage.toHexData), account: account, callbackID: action.id, url: action.url) case .signTypedMessageV3(let typedData): return self.signMessage(with: .eip712v3And4(typedData), account: account, callbackID: action.id, url: action.url) case .sendRawTransaction(let raw): return self.sendRawTransaction(session: session, rawTransaction: raw, callbackID: action.id, url: action.url) case .getTransactionCount: return self.getTransactionCount(session: session, callbackID: action.id, url: action.url) case .unknown: throw PMKError.cancelled } }.done { callback in try? server.fulfill(callback, request: request) }.catch { _ in server.reject(request) } } else { server.reject(request) } } private func signMessage(with type: SignMessageType, account: AlphaWallet.Address, callbackID id: WalletConnectRequestID, url: WalletConnectURL) -> Promise<WalletConnectServer.Callback> { firstly { SignMessageCoordinator.promise(navigationController, keystore: keystore, coordinator: self, signType: type, account: account) }.map { data -> WalletConnectServer.Callback in return .init(id: id, url: url, value: data) } } private func executeTransaction(session: WalletSession, callbackID id: WalletConnectRequestID, url: WalletConnectURL, transaction: UnconfirmedTransaction, type: ConfirmType) -> Promise<WalletConnectServer.Callback> { guard let rpcServer = server.urlToServer[url] else { return Promise(error: WalletConnectError.connectionInvalid) } let ethPrice = nativeCryptoCurrencyPrices[rpcServer] let configuration: TransactionConfirmationConfiguration = .dappTransaction(confirmType: type, keystore: keystore, ethPrice: ethPrice) return firstly { TransactionConfirmationCoordinator.promise(navigationController, session: session, coordinator: self, account: session.account.address, transaction: transaction, configuration: configuration, analyticsCoordinator: analyticsCoordinator, source: .walletConnect) }.map { data -> WalletConnectServer.Callback in switch data { case .signedTransaction(let data): return .init(id: id, url: url, value: data) case .sentTransaction(let transaction): let data = Data(_hex: transaction.id) return .init(id: id, url: url, value: data) case .sentRawTransaction: //NOTE: Doesn't support sentRawTransaction for TransactionConfirmationCoordinator, for it we are using another function throw PMKError.cancelled } }.map { callback in //NOTE: Show transaction in progress only for sent transactions switch type { case .sign: break case .signThenSend: TransactionInProgressCoordinator.promise(self.navigationController, coordinator: self).done { _ in //no op }.cauterize() } return callback }.recover { error -> Promise<WalletConnectServer.Callback> in if case DAppError.cancelled = error { //no op } else { self.navigationController.displayError(error: error) } throw error } } func server(_ server: WalletConnectServer, didFail error: Error) { let errorMessage = R.string.localizable.walletConnectFailureTitle() if let presentedController = notificationAlertController { presentedController.dismiss(animated: true) { [weak self] in guard let strongSelf = self else { return } strongSelf.notificationAlertController = strongSelf.navigationController.displaySuccess(message: errorMessage) } } else { notificationAlertController = navigationController.displaySuccess(message: errorMessage) } } func server(_ server: WalletConnectServer, shouldConnectFor connection: WalletConnectConnection, completion: @escaping (WalletConnectServer.ConnectionChoice) -> Void) { firstly { WalletConnectToSessionCoordinator.promise(navigationController, coordinator: self, connection: connection, serverChoices: serverChoices) }.done { choise in completion(choise) }.catch { _ in completion(.cancel) } } //TODO after we support sendRawTransaction in dapps (and hence a proper UI, be it the actionsheet for transaction confirmation or a simple prompt), let's modify this to use the same flow private func sendRawTransaction(session: WalletSession, rawTransaction: String, callbackID id: WalletConnectRequestID, url: WalletConnectURL) -> Promise<WalletConnectServer.Callback> { return firstly { showSignRawTransaction(title: R.string.localizable.walletConnectSendRawTransactionTitle(), message: rawTransaction) }.then { shouldSend -> Promise<ConfirmResult> in guard shouldSend else { return .init(error: DAppError.cancelled) } let coordinator = SendTransactionCoordinator(session: session, keystore: self.keystore, confirmType: .sign) return coordinator.send(rawTransaction: rawTransaction) }.map { data in switch data { case .signedTransaction, .sentTransaction: throw PMKError.cancelled case .sentRawTransaction(let transactionId, _): let data = Data(_hex: transactionId) return .init(id: id, url: url, value: data) } }.then { callback -> Promise<WalletConnectServer.Callback> in return self.showFeedbackOnSuccess(callback) } } private func getTransactionCount(session: WalletSession, callbackID id: WalletConnectRequestID, url: WalletConnectURL) -> Promise<WalletConnectServer.Callback> { firstly { GetNextNonce(server: session.server, wallet: session.account.address).promise() }.map { if let data = Data(fromHexEncodedString: String(format: "%02X", $0)) { return .init(id: id, url: url, value: data) } else { throw PMKError.badInput } } } private func showSignRawTransaction(title: String, message: String) -> Promise<Bool> { return Promise { seal in let style: UIAlertController.Style = UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet let alertViewController = UIAlertController(title: title, message: message, preferredStyle: style) let startAction = UIAlertAction(title: R.string.localizable.oK(), style: .default) { _ in seal.fulfill(true) } let cancelAction = UIAlertAction(title: R.string.localizable.cancel(), style: .cancel) { _ in seal.fulfill(false) } alertViewController.addAction(startAction) alertViewController.addAction(cancelAction) navigationController.present(alertViewController, animated: true) } } private func showFeedbackOnSuccess<T>(_ value: T) -> Promise<T> { return Promise { seal in UINotificationFeedbackGenerator.show(feedbackType: .success) { seal.fulfill(value) } } } } extension WalletConnectCoordinator: WalletConnectSessionsViewControllerDelegate { func didClose(in viewController: WalletConnectSessionsViewController) { //NOTE: even if we haven't sessions view controller pushed to navigation stack, we need to make sure that root NavigationBar will be hidden navigationController.setNavigationBarHidden(true, animated: true) guard let navigationController = viewController.navigationController else { return } navigationController.popViewController(animated: true) } func didSelect(session: WalletConnectSession, in viewController: WalletConnectSessionsViewController) { guard let navigationController = viewController.navigationController else { return } display(session: session, withNavigationController: navigationController) } }
45.820059
271
0.672117
48163b9c3a371f7873d3f9ebf5df22e4bcc83cde
80
import UIKit public protocol ViewViewModel { func apply(to view: UIView) }
13.333333
31
0.7375
6175881a408d751938446ce7ed6306c2595940e1
13,273
// // UIImage+AlamofireImage.swift // // Copyright (c) 2015-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(iOS) || os(tvOS) || os(watchOS) import CoreGraphics import Foundation import UIKit // MARK: Initialization private let lock = NSLock() extension UIImage { /// Initializes and returns the image object with the specified data in a thread-safe manner. /// /// It has been reported that there are thread-safety issues when initializing large amounts of images /// simultaneously. In the event of these issues occurring, this method can be used in place of /// the `init?(data:)` method. /// /// - parameter data: The data object containing the image data. /// /// - returns: An initialized `UIImage` object, or `nil` if the method failed. public static func af_threadSafeImage(with data: Data) -> UIImage? { lock.lock() let image = UIImage(data: data) lock.unlock() return image } /// Initializes and returns the image object with the specified data and scale in a thread-safe manner. /// /// It has been reported that there are thread-safety issues when initializing large amounts of images /// simultaneously. In the event of these issues occurring, this method can be used in place of /// the `init?(data:scale:)` method. /// /// - parameter data: The data object containing the image data. /// - parameter scale: The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 /// results in an image whose size matches the pixel-based dimensions of the image. Applying a /// different scale factor changes the size of the image as reported by the size property. /// /// - returns: An initialized `UIImage` object, or `nil` if the method failed. public static func af_threadSafeImage(with data: Data, scale: CGFloat) -> UIImage? { lock.lock() let image = UIImage(data: data, scale: scale) lock.unlock() return image } } // MARK: - Inflation extension UIImage { private struct AssociatedKey { static var inflated = "af_UIImage.Inflated" } /// Returns whether the image is inflated. public var af_inflated: Bool { get { if let inflated = objc_getAssociatedObject(self, &AssociatedKey.inflated) as? Bool { return inflated } else { return false } } set { objc_setAssociatedObject(self, &AssociatedKey.inflated, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Inflates the underlying compressed image data to be backed by an uncompressed bitmap representation. /// /// Inflating compressed image formats (such as PNG or JPEG) can significantly improve drawing performance as it /// allows a bitmap representation to be constructed in the background rather than on the main thread. public func af_inflate() { guard !af_inflated else { return } af_inflated = true _ = cgImage?.dataProvider?.data } } // MARK: - Alpha extension UIImage { /// Returns whether the image contains an alpha component. public var af_containsAlphaComponent: Bool { let alphaInfo = cgImage?.alphaInfo return ( alphaInfo == .first || alphaInfo == .last || alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast ) } /// Returns whether the image is opaque. public var af_isOpaque: Bool { return !af_containsAlphaComponent } } // MARK: - Scaling extension UIImage { /// Returns a new version of the image scaled to the specified size. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageScaled(to size: CGSize) -> UIImage { assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) draw(in: CGRect(origin: .zero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within /// a specified size. /// /// The resulting image contains an alpha component used to pad the width or height with the necessary transparent /// pixels to fit the specified size. In high performance critical situations, this may not be the optimal approach. /// To maintain an opaque image, you could compute the `scaledSize` manually, then use the `af_imageScaledToSize` /// method in conjunction with a `.Center` content mode to achieve the same visual result. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageAspectScaled(toFit size: CGSize) -> UIImage { assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.width / self.size.width } else { resizeFactor = size.height / self.size.height } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a /// specified size. Any pixels that fall outside the specified size are clipped. /// /// - parameter size: The size to use when scaling the new image. /// /// - returns: A new image object. public func af_imageAspectScaled(toFill size: CGSize) -> UIImage { assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.height / self.size.height } else { resizeFactor = size.width / self.size.width } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } } // MARK: - Rounded Corners extension UIImage { /// Returns a new version of the image with the corners rounded to the specified radius. /// /// - parameter radius: The radius to use when rounding the new image. /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the /// image has the same resolution for all screen scales such as @1x, @2x and /// @3x (i.e. single image from web server). Set to `false` for images loaded /// from an asset catalog with varying resolutions for each screen scale. /// `false` by default. /// /// - returns: A new image object. public func af_imageRounded(withCornerRadius radius: CGFloat, divideRadiusByImageScale: Bool = false) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let scaledRadius = divideRadiusByImageScale ? radius / scale : radius let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: scaledRadius) clippingPath.addClip() draw(in: CGRect(origin: CGPoint.zero, size: size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } /// Returns a new version of the image rounded into a circle. /// /// - returns: A new image object. public func af_imageRoundedIntoCircle() -> UIImage { let radius = min(size.width, size.height) / 2.0 var squareImage = self if size.width != size.height { let squareDimension = min(size.width, size.height) let squareSize = CGSize(width: squareDimension, height: squareDimension) squareImage = af_imageAspectScaled(toFill: squareSize) } UIGraphicsBeginImageContextWithOptions(squareImage.size, false, 0.0) let clippingPath = UIBezierPath( roundedRect: CGRect(origin: CGPoint.zero, size: squareImage.size), cornerRadius: radius ) clippingPath.addClip() squareImage.draw(in: CGRect(origin: CGPoint.zero, size: squareImage.size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } } #endif #if os(iOS) || os(tvOS) import CoreImage // MARK: - Core Image Filters @available(iOS 9.0, *) extension UIImage { /// Returns a new version of the image using a CoreImage filter with the specified name and parameters. /// /// - parameter name: The name of the CoreImage filter to use on the new image. /// - parameter parameters: The parameters to apply to the CoreImage filter. /// /// - returns: A new image object, or `nil` if the filter failed for any reason. public func af_imageFiltered(withCoreImageFilter name: String, parameters: [String: Any]? = nil) -> UIImage? { var image: CoreImage.CIImage? = ciImage if image == nil, let CGImage = self.cgImage { image = CoreImage.CIImage(cgImage: CGImage) } guard let coreImage = image else { return nil } #if swift(>=4.2) let context = CIContext(options: [.priorityRequestLow: true]) #else let context = CIContext(options: convertToOptionalCIContextOptionDictionary([convertFromCIContextOption(CIContextOption.priorityRequestLow): true])) #endif var parameters: [String: Any] = parameters ?? [:] parameters[kCIInputImageKey] = coreImage #if swift(>=4.2) guard let filter = CIFilter(name: name, parameters: parameters) else { return nil } #else guard let filter = CIFilter(name: name, parameters: parameters) else { return nil } #endif guard let outputImage = filter.outputImage else { return nil } let cgImageRef = context.createCGImage(outputImage, from: outputImage.extent) return UIImage(cgImage: cgImageRef!, scale: scale, orientation: imageOrientation) } } #endif // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalCIContextOptionDictionary(_ input: [String: Any]?) -> [CIContextOption: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (CIContextOption(rawValue: key), value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromCIContextOption(_ input: CIContextOption) -> String { return input.rawValue }
39.739521
156
0.665637
e839a23a07d91c6017c425f6a3003bf44a609914
1,024
class ImageViewController: UIViewController { // MARK: - Properties let url: NSURL? // MARK: - View Elements let imageView: UIImageView // MARK: - Initializers init(url: NSURL) { self.url = url imageView = UIImageView() super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() title = "Photo" configureNavigationBar() addSubviews() configureSubviews() addConstraints() imageView.sd_setImageWithURL(url) } // MARK: - View Setup private func configureNavigationBar() {} private func addSubviews() { view.addSubview(imageView) } private func configureSubviews() {} private func addConstraints() { imageView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero) } }
21.333333
74
0.624023
2f13ba0bfb070699795c0e83e823b1135094f201
4,792
// // AcknowledgementViewController.swift // SwiftyAcknowledgements // // Created by Mathias Nagler on 08.09.15. // Copyright (c) 2015 Mathias Nagler. All rights reserved. // import UIKit internal class AcknowledgementViewController: UIViewController { // MARK: Properties /// The font size used for displaying the acknowledgement's text internal var fontSize: CGFloat = UIFontDescriptor.preferredFontSize(withTextStyle: UIFont.TextStyle.body.rawValue) { didSet { textView.font = UIFont.systemFont(ofSize: fontSize) } } /// The Acknowledgement instance that is displayed by the ViewController. internal let acknowledgement: Acknowledgement /// The textView used for displaying the acknowledgement's text internal private(set) lazy var textView: UITextView = { let textView = UITextView(frame: CGRect.zero) textView.translatesAutoresizingMaskIntoConstraints = false textView.alwaysBounceVertical = true textView.font = UIFont.systemFont(ofSize: self.fontSize) textView.textContainerInset = UIEdgeInsets(top: 12, left: 10, bottom: 12, right: 10) textView.isUserInteractionEnabled = true #if os(iOS) textView.isEditable = false textView.dataDetectorTypes = .link #endif #if os(tvOS) textView.isSelectable = true textView.panGestureRecognizer.allowedTouchTypes = [NSNumber(value: UITouchType.indirect.rawValue)] #endif return textView }() #if os(tvOS) private var gradientLayer: CAGradientLayer = { let gradientLayer = CAGradientLayer() gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor, UIColor.black.cgColor, UIColor.clear.cgColor] gradientLayer.locations = [0, 0.06, 1, 1] return gradientLayer }() #endif override internal var preferredFocusedView: UIView? { return textView } // MARK: Initialization /// Initializes a new AcknowledgementViewController instance and configures it using the given acknowledgement. /// - Parameter acknowledgement: The acknowledgement that the viewController should display /// - Returns: A newly initialized AcknowledgementViewController instance configured with the acknowledgements title and text. public required init(acknowledgement: Acknowledgement) { self.acknowledgement = acknowledgement super.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented, use init(acknowledgement:) instead.") } // MARK: UIViewController Overrides override func viewDidLoad() { view.addSubview(textView) #if os(tvOS) view.addConstraint(NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: textView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: textView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: textView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 0.7, constant: 0)) #else view.addConstraint(NSLayoutConstraint(item: textView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: textView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: textView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: textView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)) #endif textView.text = acknowledgement.text title = acknowledgement.title textView.contentOffset = CGPoint.zero #if os(tvOS) textView.superview?.layer.mask = gradientLayer #endif super.viewDidLoad() } override func viewDidLayoutSubviews() { #if os(tvOS) gradientLayer.frame = textView.frame #endif super.viewDidLayoutSubviews() } }
42.785714
174
0.666736
9cf739d488b6ff543ace1573da9680791ec6ca3d
1,397
// // MacOsValidationOperation.swift // Mendoza // // Created by Tomas Camin on 22/03/2019. // import Foundation class MacOsValidationOperation: BaseOperation<Void> { private let configuration: Configuration private lazy var pool: ConnectionPool = { makeConnectionPool(sources: configuration.nodes) }() private let syncQueue = DispatchQueue(label: String(describing: MacOsValidationOperation.self)) init(configuration: Configuration) { self.configuration = configuration } override func main() { guard !isCancelled else { return } do { didStart?() var versions = Set<String>() try pool.execute { executer, _ in let macOsVersion = try executer.execute("defaults read loginwindow SystemVersionStampAsString") guard !macOsVersion.isEmpty else { throw Error("Failed getting mac os version") } self.syncQueue.sync { _ = versions.insert(macOsVersion) } } guard versions.count == 1 else { throw Error("Multiple versions of mac os found: `\(versions.joined(separator: "`, `"))`") } didEnd?(()) } catch { didThrow?(error) } } override func cancel() { if isExecuting { pool.terminate() } super.cancel() } }
25.4
111
0.592699
397a7e7a8365852edce797d9a86b55e7726bb23b
3,011
// ------------------------------------------------------------------------------------------------- // Copyright (C) 2016-2019 HERE Europe B.V. // // 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. // // SPDX-License-Identifier: Apache-2.0 // License-Filename: LICENSE // // ------------------------------------------------------------------------------------------------- import XCTest import hello class AttributesTests: XCTestCase { let attributes: Attributes = Attributes() func testBuiltInTypeAttribute() { attributes.builtInTypeAttribute = 42 XCTAssertEqual(42, attributes.builtInTypeAttribute) } func testReadonlyAttribute() { XCTAssertEqual(3.14, attributes.readonlyAttribute, accuracy: 1e-6) } func testStructAttribute() { let expectedStruct = Attributes.ExampleStruct(value: 2.71, intValue: []) attributes.structAttribute = expectedStruct let actualStruct = attributes.structAttribute XCTAssertEqual(expectedStruct.value, actualStruct.value, accuracy: 1e-6) } func testStructArrayLiteralAttribute() { var expectedStruct = Attributes.ExampleStruct(value: 2.71, intValue: []) expectedStruct.intValue = [1, 2, 3, 4] XCTAssertEqual(expectedStruct.intValue, [1, 2, 3, 4]) } func testStaticAttribute() { Attributes.staticAttribute = "fooBar" XCTAssertEqual("fooBar", Attributes.staticAttribute) } func testCachedProperty() { let instance = CachedProperties() XCTAssertEqual(0, instance.callCount) let result1 = instance.cachedProperty let _ = instance.cachedProperty XCTAssertEqual(1, instance.callCount) XCTAssertEqual(["foo", "bar"], result1) } func testStaticCachedProperty() { XCTAssertEqual(0, CachedProperties.staticCallCount) let result1 = CachedProperties.staticCachedProperty let _ = CachedProperties.staticCachedProperty XCTAssertEqual(1, CachedProperties.staticCallCount) XCTAssertEqual(Data([0, 1, 2]), result1) } static var allTests = [ ("testBuiltInTypeAttribute", testBuiltInTypeAttribute), ("testReadonlyAttribute", testReadonlyAttribute), ("testStructAttribute", testStructAttribute), ("testStructArrayLiteralAttribute", testStructArrayLiteralAttribute), ("testStaticAttribute", testStaticAttribute), ("testCachedProperty", testCachedProperty), ("testStaticCachedProperty", testStaticCachedProperty) ] }
33.455556
100
0.665892
757f6a9ba365127f3cb29812725b422dc58d9d46
3,165
/// Copyright (c) 2020 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// 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 SwiftUI struct Track: Identifiable { let id = UUID() let title: String let artist: String let duration: String let thumbnail = Image(systemName: "heart") let gradient: LinearGradient = { let colors: [Color] = [.orange, .pink, .purple, .red, .yellow] return LinearGradient(gradient: Gradient(colors: [colors.randomElement()!, colors.randomElement()!]), startPoint: .center, endPoint: .topTrailing) }() } struct MeowMix { let tracks = [ Track(title: "Cool Cat", artist: "Keyboard Cat", duration: "0:29"), Track(title: "The Lovecats", artist: "The Cure", duration: "3:40"), Track(title: "Katamari on the Moog", artist: "Akitaka Tohyama, Yu Miyake", duration: "0:33"), Track(title: "A Sunday Morning Meditation", artist: "ambientcat", duration: "1:17"), Track(title: "Here Comes Santa Claws", artist: "Jingle Cats", duration: "2:21"), Track(title: "Be a Safe Rider", artist: "Safe-T Rider", duration: "5:05"), Track(title: "Jellicle Songs For Jellicle Cats", artist: "Andrew Lloyd Webber & 'Cats' 1983 Broadway Cast", duration: "5:17"), Track(title: "Cat Scratch Fever", artist: "Ted Nugent", duration: "3:37"), Track(title: "This Cat's On a Hot Tin Roof", artist: "The Brian Setzer Orchestra", duration: "2:55") ] }
51.885246
150
0.722591
9b8b6ea2ac7d27f2f14b9bd4884de55a97b17bc0
1,496
//===--- LinkedList.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of linked lists. It is based on LinkedList from // utils/benchmark, with modifications for performance measuring. import TestsUtils // 47% _swift_retain // 43% _swift_release public let benchmarks = BenchmarkInfo( name: "LinkedList", runFunction: run_LinkedList, tags: [.runtime, .cpubench, .refcount], setUpFunction: { for i in 0..<size { head = Node(n:head, d:i) } }, tearDownFunction: { head = Node(n:nil, d:0) }, legacyFactor: 40) let size = 100 var head = Node(n:nil, d:0) final class Node { var next: Node? var data: Int init(n: Node?, d: Int) { next = n data = d } } @inline(never) public func run_LinkedList(_ n: Int) { var sum = 0 let ref_result = size*(size-1)/2 var ptr = head for _ in 1...125*n { ptr = head sum = 0 while let nxt = ptr.next { sum += ptr.data ptr = nxt } if sum != ref_result { break } } check(sum == ref_result) }
25.355932
80
0.591578