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
d6d46af18b571940e59572996221eb801977a29f
18,138
// // DO NOT EDIT. // // Generated by the protocol buffer compiler. // Source: ftp.proto // // // Copyright 2018, gRPC 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 GRPC import NIO import SwiftProtobuf /// Usage: instantiate Mavsdk_Rpc_Ftp_FtpServiceClient, then call methods of this protocol to make API calls. internal protocol Mavsdk_Rpc_Ftp_FtpServiceClientProtocol: GRPCClient { func reset( _ request: Mavsdk_Rpc_Ftp_ResetRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_ResetRequest, Mavsdk_Rpc_Ftp_ResetResponse> func subscribeDownload( _ request: Mavsdk_Rpc_Ftp_SubscribeDownloadRequest, callOptions: CallOptions?, handler: @escaping (Mavsdk_Rpc_Ftp_DownloadResponse) -> Void ) -> ServerStreamingCall<Mavsdk_Rpc_Ftp_SubscribeDownloadRequest, Mavsdk_Rpc_Ftp_DownloadResponse> func subscribeUpload( _ request: Mavsdk_Rpc_Ftp_SubscribeUploadRequest, callOptions: CallOptions?, handler: @escaping (Mavsdk_Rpc_Ftp_UploadResponse) -> Void ) -> ServerStreamingCall<Mavsdk_Rpc_Ftp_SubscribeUploadRequest, Mavsdk_Rpc_Ftp_UploadResponse> func listDirectory( _ request: Mavsdk_Rpc_Ftp_ListDirectoryRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_ListDirectoryRequest, Mavsdk_Rpc_Ftp_ListDirectoryResponse> func createDirectory( _ request: Mavsdk_Rpc_Ftp_CreateDirectoryRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_CreateDirectoryRequest, Mavsdk_Rpc_Ftp_CreateDirectoryResponse> func removeDirectory( _ request: Mavsdk_Rpc_Ftp_RemoveDirectoryRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_RemoveDirectoryRequest, Mavsdk_Rpc_Ftp_RemoveDirectoryResponse> func removeFile( _ request: Mavsdk_Rpc_Ftp_RemoveFileRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_RemoveFileRequest, Mavsdk_Rpc_Ftp_RemoveFileResponse> func rename( _ request: Mavsdk_Rpc_Ftp_RenameRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_RenameRequest, Mavsdk_Rpc_Ftp_RenameResponse> func areFilesIdentical( _ request: Mavsdk_Rpc_Ftp_AreFilesIdenticalRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_AreFilesIdenticalRequest, Mavsdk_Rpc_Ftp_AreFilesIdenticalResponse> func setRootDirectory( _ request: Mavsdk_Rpc_Ftp_SetRootDirectoryRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_SetRootDirectoryRequest, Mavsdk_Rpc_Ftp_SetRootDirectoryResponse> func setTargetCompid( _ request: Mavsdk_Rpc_Ftp_SetTargetCompidRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_SetTargetCompidRequest, Mavsdk_Rpc_Ftp_SetTargetCompidResponse> func getOurCompid( _ request: Mavsdk_Rpc_Ftp_GetOurCompidRequest, callOptions: CallOptions? ) -> UnaryCall<Mavsdk_Rpc_Ftp_GetOurCompidRequest, Mavsdk_Rpc_Ftp_GetOurCompidResponse> } extension Mavsdk_Rpc_Ftp_FtpServiceClientProtocol { /// /// Resets FTP server in case there are stale open sessions. /// /// - Parameters: /// - request: Request to send to Reset. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func reset( _ request: Mavsdk_Rpc_Ftp_ResetRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_ResetRequest, Mavsdk_Rpc_Ftp_ResetResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/Reset", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } /// /// Downloads a file to local directory. /// /// - Parameters: /// - request: Request to send to SubscribeDownload. /// - callOptions: Call options. /// - handler: A closure called when each response is received from the server. /// - Returns: A `ServerStreamingCall` with futures for the metadata and status. internal func subscribeDownload( _ request: Mavsdk_Rpc_Ftp_SubscribeDownloadRequest, callOptions: CallOptions? = nil, handler: @escaping (Mavsdk_Rpc_Ftp_DownloadResponse) -> Void ) -> ServerStreamingCall<Mavsdk_Rpc_Ftp_SubscribeDownloadRequest, Mavsdk_Rpc_Ftp_DownloadResponse> { return self.makeServerStreamingCall( path: "/mavsdk.rpc.ftp.FtpService/SubscribeDownload", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler ) } /// /// Uploads local file to remote directory. /// /// - Parameters: /// - request: Request to send to SubscribeUpload. /// - callOptions: Call options. /// - handler: A closure called when each response is received from the server. /// - Returns: A `ServerStreamingCall` with futures for the metadata and status. internal func subscribeUpload( _ request: Mavsdk_Rpc_Ftp_SubscribeUploadRequest, callOptions: CallOptions? = nil, handler: @escaping (Mavsdk_Rpc_Ftp_UploadResponse) -> Void ) -> ServerStreamingCall<Mavsdk_Rpc_Ftp_SubscribeUploadRequest, Mavsdk_Rpc_Ftp_UploadResponse> { return self.makeServerStreamingCall( path: "/mavsdk.rpc.ftp.FtpService/SubscribeUpload", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler ) } /// /// Lists items from a remote directory. /// /// - Parameters: /// - request: Request to send to ListDirectory. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func listDirectory( _ request: Mavsdk_Rpc_Ftp_ListDirectoryRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_ListDirectoryRequest, Mavsdk_Rpc_Ftp_ListDirectoryResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/ListDirectory", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } /// /// Creates a remote directory. /// /// - Parameters: /// - request: Request to send to CreateDirectory. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func createDirectory( _ request: Mavsdk_Rpc_Ftp_CreateDirectoryRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_CreateDirectoryRequest, Mavsdk_Rpc_Ftp_CreateDirectoryResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/CreateDirectory", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } /// /// Removes a remote directory. /// /// - Parameters: /// - request: Request to send to RemoveDirectory. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func removeDirectory( _ request: Mavsdk_Rpc_Ftp_RemoveDirectoryRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_RemoveDirectoryRequest, Mavsdk_Rpc_Ftp_RemoveDirectoryResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/RemoveDirectory", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } /// /// Removes a remote file. /// /// - Parameters: /// - request: Request to send to RemoveFile. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func removeFile( _ request: Mavsdk_Rpc_Ftp_RemoveFileRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_RemoveFileRequest, Mavsdk_Rpc_Ftp_RemoveFileResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/RemoveFile", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } /// /// Renames a remote file or remote directory. /// /// - Parameters: /// - request: Request to send to Rename. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func rename( _ request: Mavsdk_Rpc_Ftp_RenameRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_RenameRequest, Mavsdk_Rpc_Ftp_RenameResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/Rename", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } /// /// Compares a local file to a remote file using a CRC32 checksum. /// /// - Parameters: /// - request: Request to send to AreFilesIdentical. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func areFilesIdentical( _ request: Mavsdk_Rpc_Ftp_AreFilesIdenticalRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_AreFilesIdenticalRequest, Mavsdk_Rpc_Ftp_AreFilesIdenticalResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/AreFilesIdentical", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } /// /// Set root directory for MAVLink FTP server. /// /// - Parameters: /// - request: Request to send to SetRootDirectory. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func setRootDirectory( _ request: Mavsdk_Rpc_Ftp_SetRootDirectoryRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_SetRootDirectoryRequest, Mavsdk_Rpc_Ftp_SetRootDirectoryResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/SetRootDirectory", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } /// /// Set target component ID. By default it is the autopilot. /// /// - Parameters: /// - request: Request to send to SetTargetCompid. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func setTargetCompid( _ request: Mavsdk_Rpc_Ftp_SetTargetCompidRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_SetTargetCompidRequest, Mavsdk_Rpc_Ftp_SetTargetCompidResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/SetTargetCompid", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } /// /// Get our own component ID. /// /// - Parameters: /// - request: Request to send to GetOurCompid. /// - callOptions: Call options. /// - Returns: A `UnaryCall` with futures for the metadata, status and response. internal func getOurCompid( _ request: Mavsdk_Rpc_Ftp_GetOurCompidRequest, callOptions: CallOptions? = nil ) -> UnaryCall<Mavsdk_Rpc_Ftp_GetOurCompidRequest, Mavsdk_Rpc_Ftp_GetOurCompidResponse> { return self.makeUnaryCall( path: "/mavsdk.rpc.ftp.FtpService/GetOurCompid", request: request, callOptions: callOptions ?? self.defaultCallOptions ) } } internal final class Mavsdk_Rpc_Ftp_FtpServiceClient: Mavsdk_Rpc_Ftp_FtpServiceClientProtocol { internal let channel: GRPCChannel internal var defaultCallOptions: CallOptions /// Creates a client for the mavsdk.rpc.ftp.FtpService service. /// /// - Parameters: /// - channel: `GRPCChannel` to the service host. /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them. internal init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) { self.channel = channel self.defaultCallOptions = defaultCallOptions } } /// To build a server, implement a class that conforms to this protocol. internal protocol Mavsdk_Rpc_Ftp_FtpServiceProvider: CallHandlerProvider { /// /// Resets FTP server in case there are stale open sessions. func reset(request: Mavsdk_Rpc_Ftp_ResetRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_ResetResponse> /// /// Downloads a file to local directory. func subscribeDownload(request: Mavsdk_Rpc_Ftp_SubscribeDownloadRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Ftp_DownloadResponse>) -> EventLoopFuture<GRPCStatus> /// /// Uploads local file to remote directory. func subscribeUpload(request: Mavsdk_Rpc_Ftp_SubscribeUploadRequest, context: StreamingResponseCallContext<Mavsdk_Rpc_Ftp_UploadResponse>) -> EventLoopFuture<GRPCStatus> /// /// Lists items from a remote directory. func listDirectory(request: Mavsdk_Rpc_Ftp_ListDirectoryRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_ListDirectoryResponse> /// /// Creates a remote directory. func createDirectory(request: Mavsdk_Rpc_Ftp_CreateDirectoryRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_CreateDirectoryResponse> /// /// Removes a remote directory. func removeDirectory(request: Mavsdk_Rpc_Ftp_RemoveDirectoryRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_RemoveDirectoryResponse> /// /// Removes a remote file. func removeFile(request: Mavsdk_Rpc_Ftp_RemoveFileRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_RemoveFileResponse> /// /// Renames a remote file or remote directory. func rename(request: Mavsdk_Rpc_Ftp_RenameRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_RenameResponse> /// /// Compares a local file to a remote file using a CRC32 checksum. func areFilesIdentical(request: Mavsdk_Rpc_Ftp_AreFilesIdenticalRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_AreFilesIdenticalResponse> /// /// Set root directory for MAVLink FTP server. func setRootDirectory(request: Mavsdk_Rpc_Ftp_SetRootDirectoryRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_SetRootDirectoryResponse> /// /// Set target component ID. By default it is the autopilot. func setTargetCompid(request: Mavsdk_Rpc_Ftp_SetTargetCompidRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_SetTargetCompidResponse> /// /// Get our own component ID. func getOurCompid(request: Mavsdk_Rpc_Ftp_GetOurCompidRequest, context: StatusOnlyCallContext) -> EventLoopFuture<Mavsdk_Rpc_Ftp_GetOurCompidResponse> } extension Mavsdk_Rpc_Ftp_FtpServiceProvider { internal var serviceName: Substring { return "mavsdk.rpc.ftp.FtpService" } /// Determines, calls and returns the appropriate request handler, depending on the request's method. /// Returns nil for methods not handled by this service. internal func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? { switch methodName { case "Reset": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.reset(request: request, context: context) } } case "SubscribeDownload": return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in return { request in self.subscribeDownload(request: request, context: context) } } case "SubscribeUpload": return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in return { request in self.subscribeUpload(request: request, context: context) } } case "ListDirectory": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.listDirectory(request: request, context: context) } } case "CreateDirectory": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.createDirectory(request: request, context: context) } } case "RemoveDirectory": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.removeDirectory(request: request, context: context) } } case "RemoveFile": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.removeFile(request: request, context: context) } } case "Rename": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.rename(request: request, context: context) } } case "AreFilesIdentical": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.areFilesIdentical(request: request, context: context) } } case "SetRootDirectory": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.setRootDirectory(request: request, context: context) } } case "SetTargetCompid": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.setTargetCompid(request: request, context: context) } } case "GetOurCompid": return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return { request in self.getOurCompid(request: request, context: context) } } default: return nil } } }
38.591489
177
0.736355
e2199ab6724290500d36a8ac308d80576e1d6bed
2,141
// // // FolderSaver.swift // // Copyright © 2019 Mokten Pty Ltd. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public final class Counter<Key> where Key : Hashable { private let countQueue = DispatchQueue(label: "com.mokten.counter", qos: .utility) private let keysQueue = DispatchQueue(label: "com.mokten.counter", qos: .utility, attributes: .concurrent) private var _keys: [Key: Int] = [:] private(set) var keys: [Key: Int] { get { var keys: [Key: Int] = [:] keysQueue.sync { keys = self._keys } return keys } set { keysQueue.async(flags: .barrier) { self._keys = newValue } } } } extension Counter { public func count(for key: Key) -> Int { var requestCount : Int = 0 countQueue.sync { let count = self.keys[key, default: -1] + 1 self.keys[key] = count requestCount = count } return requestCount } }
35.098361
110
0.647361
29d96ba0e3c8ca27ed584f3ffc03f50645796803
2,253
// // ViewController.swift // SwiftCheatSheet // // Created by Qilin Hu on 2022/2/16. // import UIKit class ViewController: UIViewController { private let sections = Section.sectionsFromBundle() private var arrayDataSource: ArrayDataSource! { didSet { tableView.dataSource = arrayDataSource } } private lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .grouped) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.autoresizingMask = [.flexibleHeight, .flexibleWidth] tableView.backgroundColor = .systemBackground tableView.register(cellWithClass: UITableViewCell.self) tableView.delegate = self return tableView }() // 在 loadView() 方法中实例化视图并添加布局约束 override func loadView() { super.loadView() // 如果我们添加了 scrollviews,这个技巧可以防止导航栏折叠 // view.addSubview(UIView(frame: .zero)) view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ]) } // 在 viewDidLoad() 方法中配置视图 override func viewDidLoad() { super.viewDidLoad() // 加载数据源,设置代理 arrayDataSource = ArrayDataSource(sections: sections, cellReuseIdentifier: String(describing: UITableViewCell.self)) arrayDataSource.cellConfigureClosure = { tableViewCell, cell in tableViewCell.configureForCell(cell: cell) } self.tableView.reloadData() } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if let item = self.arrayDataSource?.getCellItem(at: indexPath), let controller = item.className.getViewController() { navigationController?.pushViewController(controller, animated: true) } } }
33.626866
124
0.684865
0a6f49e56ac5d892c4b9bc5ee96104e4de0b9c81
2,224
import Foundation import Reachability class NetworkManager: NSObject { var reachability: Reachability! static let sharedInstance: NetworkManager = { return NetworkManager() }() override init() { super.init() // Initialise reachability reachability = Reachability()! // Register an observer for the network status NotificationCenter.default.addObserver( self, selector: #selector(networkStatusChanged(_:)), name: .reachabilityChanged, object: reachability ) do { // Start the network status notifier try reachability.startNotifier() } catch { print("Unable to start notifier") } } @objc func networkStatusChanged(_ notification: Notification) { // Do something globally here! } static func stopNotifier() -> Void { do { // Stop the network status notifier try (NetworkManager.sharedInstance.reachability).startNotifier() } catch { print("Error stopping notifier") } } // Network is reachable static func isReachable(completed: @escaping (NetworkManager) -> Void) { if (NetworkManager.sharedInstance.reachability).connection != .none { completed(NetworkManager.sharedInstance) } } // Network is unreachable static func isUnreachable(completed: @escaping (NetworkManager) -> Void) { if (NetworkManager.sharedInstance.reachability).connection == .none { completed(NetworkManager.sharedInstance) } } // Network is reachable via WWAN/Cellular static func isReachableViaWWAN(completed: @escaping (NetworkManager) -> Void) { if (NetworkManager.sharedInstance.reachability).connection == .cellular { completed(NetworkManager.sharedInstance) } } // Network is reachable via WiFi static func isReachableViaWiFi(completed: @escaping (NetworkManager) -> Void) { if (NetworkManager.sharedInstance.reachability).connection == .wifi { completed(NetworkManager.sharedInstance) } } }
32.705882
83
0.624101
14d50fdf102157cb2a48f065be1ddd8f14083c8b
5,451
// RUN: %target-swift-frontend -O -emit-sil %s | FileCheck %s public protocol Foo { func foo(_ x:Int) -> Int } public extension Foo { func boo(_ x:Int) -> Int32 { return 2222 + x } func getSelf() -> Self { return self } } var gg = 1111 public class C : Foo { @inline(never) public func foo(_ x:Int) -> Int { gg += 1 return gg + x } } @_transparent func callfoo(_ f: Foo) -> Int { return f.foo(2) + f.foo(2) } @_transparent func callboo(_ f: Foo) -> Int32 { return f.boo(2) + f.boo(2) } @_transparent func callGetSelf(_ f: Foo) -> Foo { return f.getSelf() } // Check that methods returning Self are not devirtualized and do not crash the compiler. // CHECK-LABEL: sil [noinline] @_TF34devirt_protocol_method_invocations70test_devirt_protocol_extension_method_invocation_with_self_return_typeFCS_1CPS_3Foo_ // CHECK: init_existential_addr // CHECK: open_existential_addr // CHECK: return @inline(never) public func test_devirt_protocol_extension_method_invocation_with_self_return_type(_ c: C) -> Foo { return callGetSelf(c) } // It's not obvious why this isn't completely devirtualized. // CHECK: sil @_TF34devirt_protocol_method_invocations12test24114020FT_Si // CHECK: [[T0:%.*]] = alloc_stack $SimpleBase // CHECK: [[T1:%.*]] = witness_method $SimpleBase, #Base.x!getter.1 // CHECK: [[T2:%.*]] = apply [[T1]]<SimpleBase>([[T0]]) // CHECK: return [[T2]] // CHECK: sil @_TF34devirt_protocol_method_invocations14testExMetatypeFT_Si // CHECK: [[T0:%.*]] = builtin "sizeof"<Int> // CHECK: [[T1:%.*]] = builtin {{.*}}([[T0]] // CHECK: [[T2:%.*]] = struct $Int ([[T1]] : {{.*}}) // CHECK: return [[T2]] : $Int // Check that calls to f.foo() get devirtualized and are not invoked // via the expensive witness_method instruction. // To achieve that the information about a concrete type C should // be propagated from init_existential_addr into witness_method and // apply instructions. // CHECK-LABEL: sil [noinline] @_TTSf4g___TF34devirt_protocol_method_invocations38test_devirt_protocol_method_invocationFCS_1CSi // CHECK-NOT: witness_method // CHECK: checked_cast // CHECK-NOT: checked_cast // CHECK: bb1( // CHECK-NOT: checked_cast // CHECK: return // CHECK: bb2( // CHECK-NOT: checked_cast // CHECK: function_ref // CHECK: apply // CHECK: apply // CHECK: br bb1( // CHECK: bb3 // CHECK-NOT: checked_cast // CHECK: apply // CHECK: apply // CHECK: br bb1( @inline(never) public func test_devirt_protocol_method_invocation(_ c: C) -> Int { return callfoo(c) } // Check that calls of a method boo() from the protocol extension // get devirtualized and are not invoked via the expensive witness_method instruction // or by passing an existential as a parameter. // To achieve that the information about a concrete type C should // be propagated from init_existential_addr into apply instructions. // In fact, the call is expected to be inlined and then constant-folded // into a single integer constant. // CHECK-LABEL: sil [noinline] @_TTSf4d___TF34devirt_protocol_method_invocations48test_devirt_protocol_extension_method_invocationFCS_1CVs5Int32 // CHECK-NOT: checked_cast // CHECK-NOT: open_existential // CHECK-NOT: witness_method // CHECK-NOT: apply // CHECK: integer_literal // CHECK: return @inline(never) public func test_devirt_protocol_extension_method_invocation(_ c: C) -> Int32 { return callboo(c) } // Make sure that we are not crashing with an assertion due to specialization // of methods with the Self return type as an argument. // rdar://20868966 protocol Proto { func f() -> Self } class CC : Proto { func f() -> Self { return self } } func callDynamicSelfExistential(_ p: Proto) { p.f() } public func testSelfReturnType() { callDynamicSelfExistential(CC()) } // Make sure that we are not crashing with an assertion due to specialization // of methods with the Self return type. // rdar://20955745. protocol CP : class { func f() -> Self } func callDynamicSelfClassExistential(_ cp: CP) { cp.f() } class PP : CP { func f() -> Self { return self } } callDynamicSelfClassExistential(PP()) // Make sure we handle indirect conformances. // rdar://24114020 protocol Base { var x: Int { get } } protocol Derived : Base { } struct SimpleBase : Derived { var x: Int } public func test24114020() -> Int { let base: Derived = SimpleBase(x: 1) return base.x } protocol StaticP { static var size: Int { get } } struct HasStatic<T> : StaticP { static var size: Int { return sizeof(T.self) } } public func testExMetatype() -> Int { let type: StaticP.Type = HasStatic<Int>.self return type.size } // IRGen used to crash on the testPropagationOfConcreteTypeIntoExistential method. // rdar://26286278 protocol MathP { var sum: Int32 { get nonmutating set } func done() } extension MathP { func plus() -> Self { sum += 1 return self } func minus() { sum -= 1 if sum == 0 { done() } } } protocol MathA : MathP {} public final class V { var a: MathA init(a: MathA) { self.a = a } } // Check that all witness_method invocations are devirtualized. // CHECK-LABEL: sil @_TTSf4g_d___TF34devirt_protocol_method_invocations44testPropagationOfConcreteTypeIntoExistentialFT1vCS_1V1xVs5Int32_T_ // CHECK-NOT: witness_method // CHECK-NOT: class_method // CHECK: return public func testPropagationOfConcreteTypeIntoExistential(v: V, x: Int32) { let y = v.a.plus() defer { y.minus() } }
25.236111
157
0.708677
23c6620f0e1d7399f1015d9a1e12626a808b6aa0
1,990
// // RenderTemplate.swift // SiriIntents // // Created by Robert Trencheny on 2/19/19. // Copyright © 2019 Robbie Trencheny. All rights reserved. // import Foundation import UIKit import Shared import Intents import PromiseKit class RenderTemplateIntentHandler: NSObject, RenderTemplateIntentHandling { func resolveTemplate(for intent: RenderTemplateIntent, with completion: @escaping (INStringResolutionResult) -> Void) { if let templateStr = intent.template, templateStr.isEmpty == false { Current.Log.info("using provided '\(templateStr)'") completion(.success(with: templateStr)) } else { Current.Log.info("requesting a value") completion(.needsValue()) } } func handle(intent: RenderTemplateIntent, completion: @escaping (RenderTemplateIntentResponse) -> Void) { guard let templateStr = intent.template else { Current.Log.error("Unable to unwrap intent.template") let resp = RenderTemplateIntentResponse(code: .failure, userActivity: nil) resp.error = "Unable to unwrap intent.template" completion(resp) return } Current.Log.verbose("Rendering template \(templateStr)") Current.api.then(on: nil) { api in api.RenderTemplate(templateStr: templateStr) }.done { rendered in Current.Log.verbose("Successfully renderedTemplate") let resp = RenderTemplateIntentResponse(code: .success, userActivity: nil) resp.renderedTemplate = String(describing: rendered) completion(resp) }.catch { error in Current.Log.error("Error when rendering template in shortcut \(error)") let resp = RenderTemplateIntentResponse(code: .failure, userActivity: nil) resp.error = "Error during api.RenderTemplate: \(error.localizedDescription)" completion(resp) } } }
36.181818
109
0.649246
ddb243251c7fc2965f48543846381922a8b23fe3
1,114
// // UserCardDataModel.swift // SIFTool // // Created by CmST0us on 2018/2/25. // Copyright © 2018年 eki. All rights reserved. // import CoreData @objcMembers class UserCardDataModel: NSObject { var cardId: Int = 0 var idolized: Bool = false var cardSetName: String = "" var isImport: Bool = true var isKizunaMax: Bool = false init(withDictionary dictionary:[String: Any]) { cardId = dictionary["cardId"] as! Int idolized = dictionary["idolized"] as! Bool cardSetName = dictionary["cardSetName"] as! String isKizunaMax = dictionary["isKizunaMax"] as! Bool } override init() { super.init() } } extension UserCardDataModel: CoreDataModelBridgeProtocol { static var entityName: String = "UserCard" func copy(to managedObject: NSManagedObject) { managedObject.setValue(cardId, forKey: "cardId") managedObject.setValue(idolized, forKey: "idolized") managedObject.setValue(cardSetName, forKey: "cardSetName") managedObject.setValue(isKizunaMax, forKey: "isKizunaMax") } }
25.906977
66
0.66158
167881413b2bb936be18c779e7c118aea954d90e
702
// // VersionParseError.swift // PHP Monitor // // Created by Nico Verbruggen on 08/02/2022. // Copyright © 2022 Nico Verbruggen. All rights reserved. // import Foundation // MARK: - Alertable Errors // These errors must be resolved by the user. struct HomebrewPermissionError: Error, AlertableError { enum Kind: String { case applescriptNilError = "homebrew_permissions.applescript_returned_nil" } let kind: Kind func getErrorMessageKey() -> String { return "alert.errors.\(self.kind.rawValue)" } } // MARK: - Errors that do not have an associated alert message // The errors must be resolved by the developer. struct VersionParseError: Error {}
23.4
82
0.69943
ff22523a298c37484b1838dace2de6e9d76c3633
746
// // LittleBlueToothTests.swift // LittleBlueToothTests // // Created by Andrea Finollo on 10/06/2020. // Copyright © 2020 Andrea Finollo. All rights reserved. // import XCTest import CoreBluetoothMock import Combine @testable import LittleBlueToothForTest class LittleBlueToothTests: XCTestCase { var littleBT: LittleBlueTooth! var disposeBag: Set<AnyCancellable> = [] static var testInitialized: Bool = false override func setUpWithError() throws { try super.setUpWithError() if !Self.testInitialized { CBMCentralManagerMock.simulatePeripherals([blinky, blinkyWOR]) Self.testInitialized = true } CBMCentralManagerMock.simulateInitialState(.poweredOn) } }
25.724138
74
0.711796
2243d22d08df08f3456aea720306cfd8fcbf6c65
666
// // Bitrise app generated by SwagGen // https://github.com/yonaskolb/SwagGen // import ArgumentParser import API // List the existing open build requests of a specified Bitrise app struct BuildRequestListCommand: AuthenticatedCommand { static var configuration = CommandConfiguration( commandName: "BuildRequestList", abstract: "List the open build requests for an app" ) @OptionGroup var auth: AuthOptions @Argument var appSlug: String func run() throws { let request = Bitrise.BuildRequest.BuildRequestList.Request(appSlug: appSlug) client .call(request) .waitUntilDone() } }
23.785714
85
0.692192
e49cf2bad756ed3fca2a10066da52cb2bbe66bcd
1,356
// // StandardMode.swift // Nudge // // Created by Erik Gomez on 2/2/21. // import Foundation import SwiftUI // Standard Mode struct StandardMode: View { @ObservedObject var viewObserved: ViewState // Nudge UI var body: some View { HStack { // Left side of Nudge StandardModeLeftSide(viewObserved: viewObserved) // Vertical Line VStack{ Rectangle() .fill(Color.gray.opacity(0.5)) .frame(width: 1) } .frame(height: 525) // Right side of Nudge StandardModeRightSide(viewObserved: viewObserved) .padding(.bottom, -60.0) } .frame(width: 900, height: 450) } } #if DEBUG // Xcode preview for both light and dark mode struct StandardModePreviews: PreviewProvider { static var previews: some View { Group { ForEach(["en", "es"], id: \.self) { id in StandardMode(viewObserved: nudgePrimaryState) .preferredColorScheme(.light) .environment(\.locale, .init(identifier: id)) } ZStack { StandardMode(viewObserved: nudgePrimaryState) .preferredColorScheme(.dark) } } } } #endif
25.111111
65
0.528024
6919a35e861b25cccbdf210c31474d55ef9846c9
245
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A { let f = e.h> { extension g<b { enum A { deinit { class case c,
20.416667
87
0.726531
4b1c58fb1b2edef7e7705e8dd9a0fab8732f367b
3,944
// // MockableTypeInitializerTemplate.swift // MockingbirdGenerator // // Created by Andrew Chang on 9/14/19. // import Foundation struct MockableTypeInitializerTemplate: Template { let mockableTypeTemplate: MockableTypeTemplate let containingTypeNames: [String] init(mockableTypeTemplate: MockableTypeTemplate, containingTypeNames: [String]) { self.mockableTypeTemplate = mockableTypeTemplate self.containingTypeNames = containingTypeNames } func render() -> String { let nestedContainingTypeNames = containingTypeNames + [mockableTypeTemplate.mockableType.name] let initializers = [renderInitializer(with: containingTypeNames)] + mockableTypeTemplate.mockableType.containedTypes.map({ type -> String in let template = MockableTypeInitializerTemplate( mockableTypeTemplate: MockableTypeTemplate(mockableType: type), containingTypeNames: nestedContainingTypeNames ) return template.render() }) let allInitializers = initializers.joined(separator: "\n\n") let (preprocessorStart, preprocessorEnd) = mockableTypeTemplate.compilationDirectiveDeclaration guard !preprocessorStart.isEmpty else { return allInitializers } return [preprocessorStart, allInitializers, preprocessorEnd] .joined(separator: "\n\n") } private func renderInitializer(with containingTypeNames: [String]) -> String { let allGenericTypes = mockableTypeTemplate.allGenericTypes let kind = mockableTypeTemplate.mockableType.kind let scopedName = mockableTypeTemplate.createScopedName(with: containingTypeNames) let fullyQualifiedScopedName = "\(mockableTypeTemplate.mockableType.moduleName).\(scopedName)" let genericMethodAttribute: String let metatype: String let isSelfConstrainedProtocol = kind == .protocol && mockableTypeTemplate.mockableType.hasSelfConstraint if allGenericTypes.count > 0 || isSelfConstrainedProtocol { genericMethodAttribute = mockableTypeTemplate.allSpecializedGenericTypesList.isEmpty ? "" : ("<\(mockableTypeTemplate.allSpecializedGenericTypesList.joined(separator: ", "))>") let mockName = mockableTypeTemplate.createScopedName(with: containingTypeNames, suffix: "Mock") metatype = "\(mockName).Type" } else { genericMethodAttribute = "" let metatypeKeyword = (kind == .class ? "Type" : "Protocol") metatype = "\(fullyQualifiedScopedName).\(metatypeKeyword)" } let returnType: String let returnObject: String let returnTypeDescription: String let mockedScopedName = mockableTypeTemplate.createScopedName(with: containingTypeNames, suffix: "Mock") if !mockableTypeTemplate.shouldGenerateDefaultInitializer { // Requires an initializer proxy to create the partial class mock. returnType = "\(mockedScopedName).InitializerProxy.Type" returnObject = "\(mockedScopedName).InitializerProxy.self" returnTypeDescription = "class mock metatype" } else if kind == .class { // Does not require an initializer proxy. returnType = "\(mockedScopedName)" returnObject = "\(mockedScopedName)(sourceLocation: SourceLocation(file, line))" returnTypeDescription = "concrete class mock instance" } else { returnType = "\(mockedScopedName)" returnObject = "\(mockedScopedName)(sourceLocation: SourceLocation(file, line))" returnTypeDescription = "concrete protocol mock instance" } return """ /// Create a source-attributed `\(mockableTypeTemplate.fullyQualifiedName)\(allGenericTypes)` \(returnTypeDescription). public func mock\(genericMethodAttribute)(file: StaticString = #file, line: UInt = #line, _ type: \(metatype)) -> \(returnType) { return \(returnObject) } """ } }
44.818182
133
0.707404
1c64823c541ef25c381f4831934c5f2dbf7cab9f
2,881
/// Execution public class Execution { /// Execution ID. public let id: String /// Execution permissions. public let permissions: Permissions /// Function ID. public let functionId: String /// The execution creation date in Unix timestamp. public let dateCreated: Int /// The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`. public let trigger: String /// The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`. public let status: String /// The script exit code. public let exitCode: Int /// The script stdout output string. Logs the last 4,000 characters of the execution stdout output. public let stdout: String /// The script stderr output string. Logs the last 4,000 characters of the execution stderr output public let stderr: String /// The script execution time in seconds. public let time: Double init( id: String, permissions: Permissions, functionId: String, dateCreated: Int, trigger: String, status: String, exitCode: Int, stdout: String, stderr: String, time: Double ) { self.id = id self.permissions = permissions self.functionId = functionId self.dateCreated = dateCreated self.trigger = trigger self.status = status self.exitCode = exitCode self.stdout = stdout self.stderr = stderr self.time = time } public static func from(map: [String: Any]) -> Execution { return Execution( id: map["$id"] as! String, permissions: Permissions.from(map: map["$permissions"] as! [String: Any]), functionId: map["functionId"] as! String, dateCreated: map["dateCreated"] as! Int, trigger: map["trigger"] as! String, status: map["status"] as! String, exitCode: map["exitCode"] as! Int, stdout: map["stdout"] as! String, stderr: map["stderr"] as! String, time: map["time"] as! Double ) } public func toMap() -> [String: Any] { return [ "$id": id as Any, "$permissions": permissions.toMap() as Any, "functionId": functionId as Any, "dateCreated": dateCreated as Any, "trigger": trigger as Any, "status": status as Any, "exitCode": exitCode as Any, "stdout": stdout as Any, "stderr": stderr as Any, "time": time as Any ] } }
32.370787
196
0.541826
7a63880fdf05a859224e813178dd29c8f6e9f9ec
1,061
public struct CollectionAlignmentConfiguration: RuleConfiguration, Equatable { private(set) var severityConfiguration = SeverityConfiguration(.warning) private(set) var alignColons = false init() {} public var consoleDescription: String { return severityConfiguration.consoleDescription + ", align_colons: \(alignColons)" } public mutating func apply(configuration: Any) throws { guard let configuration = configuration as? [String: Any] else { throw ConfigurationError.unknownConfiguration } alignColons = configuration["align_colons"] as? Bool ?? false if let severityString = configuration["severity"] as? String { try severityConfiguration.apply(configuration: severityString) } } public static func == (lhs: CollectionAlignmentConfiguration, rhs: CollectionAlignmentConfiguration) -> Bool { return lhs.alignColons == rhs.alignColons && lhs.severityConfiguration == rhs.severityConfiguration } }
36.586207
90
0.68426
feb996b121fae1c27e655e2f42bd78be1a22bbfb
234
// // Timeoutable.swift // Dispatchito // // Created by Suresh Joshi on 2018-10-20. // Copyright © 2018 Robot Pajamas. All rights reserved. // public protocol Timeoutable { var timeout: Int { get }// ms func timedOut() }
18
56
0.65812
22873dd6d8b7866ef1bece2ed706c00ffe7a75a9
4,491
// // CodeEditorTextTokenizer.swift // LispPad // // Created by Matthias Zenger on 16/04/2021. // Copyright © 2021 Matthias Zenger. 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 UIKit class CodeEditorTextTokenizer: UITextInputStringTokenizer { // Seperate on symbols (except underscore) or whitespace static let wordSeperators: CharacterSet = { var charSet: CharacterSet = LETTERS charSet.formUnion(INITIALS) charSet.formUnion(DIGITS) charSet.formUnion(SUBSEQUENTS) return charSet }() let textInput: UIResponder & UITextInput override init(textInput: UIResponder & UITextInput) { self.textInput = textInput super.init(textInput: textInput) } // Returns range of the enclosing text unit of the given granularity, or nil if there is no // such enclosing unit. Whether a boundary position is enclosed depends on the given direction, // using the same rule as isPosition:withinTextUnit:inDirection: override func rangeEnclosingPosition(_ position: UITextPosition, with granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextRange? { if granularity == .word { let loc = self.textInput.offset(from: self.textInput.beginningOfDocument, to: position) let length = self.textInput.offset(from: self.textInput.beginningOfDocument, to: self.textInput.endOfDocument) if loc != NSNotFound, let textRange = self.textInput.textRange(from: self.textInput.beginningOfDocument, to: self.textInput.endOfDocument), let text = self.textInput.text(in: textRange) as NSString? { var wordStart = text.rangeOfCharacter(from: CodeEditorTextTokenizer.wordSeperators, options: [.backwards], range: NSMakeRange(0, loc)).location var wordEnd = text.rangeOfCharacter(from: CodeEditorTextTokenizer.wordSeperators, options: [], range: NSMakeRange(loc, length-loc)).location if wordStart == NSNotFound { wordStart = 0 } else { wordStart += 1 } if wordEnd == NSNotFound { wordEnd = length } let wordRange = NSMakeRange(wordStart, wordEnd - wordStart) return self.textRange(from: wordRange) } } return super.rangeEnclosingPosition(position, with: granularity, inDirection: direction) } private func textRange(from range: NSRange) -> UITextRange? { let beginning = self.textInput.beginningOfDocument guard let start = self.textInput.position(from: beginning, offset: range.location), let end = self.textInput.position(from: start, offset: range.length) else { return nil } return self.textInput.textRange(from: start, to: end) } override func isPosition(_ position: UITextPosition, atBoundary granularity: UITextGranularity, inDirection direction: UITextDirection) -> Bool { return super.isPosition(position, atBoundary: granularity, inDirection: direction) } override func isPosition(_ position: UITextPosition, withinTextUnit granularity: UITextGranularity, inDirection direction: UITextDirection) -> Bool { return super.isPosition(position, withinTextUnit: granularity, inDirection: direction) } override func position(from position: UITextPosition, toBoundary granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextPosition? { return super.position(from: position, toBoundary: granularity, inDirection: direction) } }
43.601942
97
0.648853
3340f35d5ade462acde5c83103e176a53933b0ac
176
type file; app (file o) copy (file i) { cp @i @o; } file f1<"201-input.txt">; // Will be transformed by CDM to 201/output.txt: file f2<"201-output.txt">; f2 = copy(f1);
11.733333
48
0.613636
760da0763179ef98309a61e83c58b66478acd0d6
721
// Copyright © 2020 Saleem Abdulrasool <[email protected]>. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause internal struct StringsHeap { let data: ArraySlice<UInt8> public init(data: ArraySlice<UInt8>) { self.data = data } public init?(from assembly: Assembly) { guard let stream = assembly.Metadata.stream(named: Metadata.Stream.Strings) else { return nil } self.init(data: stream) } public subscript(offset: Int) -> String { let index = data.index(data.startIndex, offsetBy: offset) return data[index...].withUnsafeBytes { String(decodingCString: $0.baseAddress!.assumingMemoryBound(to: UTF8.CodeUnit.self), as: UTF8.self) } } }
27.730769
90
0.683773
fe663f60516ffb382506a39922522c5d415b0265
1,341
// // ProductsVC.swift // Coder Shop // // Created by Hasan Elhussein on 31.07.2021. // import UIKit class ProductsVC: UIViewController { @IBOutlet weak var productsCollection: UICollectionView! private(set) public var products = [Product]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. productsCollection.dataSource = self productsCollection.delegate = self } func initProducts(category: Category){ products = DataService.instance.getProducts(forCategoryTitle: category.title) navigationItem.title = category.title } } extension ProductsVC: UICollectionViewDelegate, UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return products.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductCell", for: indexPath) as? ProductCell{ let product = products[indexPath.row] cell.updateViews(product: product) return cell }else{ return ProductCell() } } }
27.367347
125
0.680089
2f1a9a4930747451d96b2374e34cb049f224ece2
902
// // InterviewInstructionViewController.swift // Arobotherapy // // Created by Dan Schultz on 10/10/18. // Copyright © 2018 Bad Idea Factory. All rights reserved. // import UIKit class InterviewInstructionViewController: UIViewController, InterviewProtocol { // MARK: Properties var interviewModelController:InterviewModelController = InterviewModelController() @IBOutlet weak var okButton: UIButton! override func viewDidLoad() { super.viewDidLoad() okButton.layer.cornerRadius = 4 // Do any additional setup after loading the view. } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if var interviewProtocolViewController = segue.destination as? InterviewProtocol { interviewProtocolViewController.interviewModelController = interviewModelController } }}
29.096774
95
0.716186
11b406e70c9242c273f040d7bb349a88fc126f1c
1,026
// // CompletedDataObserver.swift // TaskemFoundation // // Created by Wilson on 9/2/18. // Copyright © 2018 Wilson. All rights reserved. // import Foundation extension CompletedPresenter: TableCoordinatorObserver { public func didBeginUpdate() { } public func didEndUpdate() { } public func didInsertRow(at index: IndexPath) { showAllDoneIfNeed() } public func didUpdateRow(at index: IndexPath) { showAllDoneIfNeed() } public func didDeleteRow(at index: IndexPath) { showAllDoneIfNeed() } public func didInsertSections(at indexes: IndexSet) { showAllDoneIfNeed() } public func didDeleteSections(at indexes: IndexSet) { showAllDoneIfNeed() } public func didMoveRow(from: IndexPath, to index: IndexPath) { showAllDoneIfNeed() } public func showAllDoneIfNeed() { view?.displayAllDone(view?.viewModel.sectionsCount() ?? 0 == 0) } }
20.938776
71
0.621832
790d7188552dd4e30ccc75501ae5c08a87ee3b74
3,440
// // LXFWeChatTools+Update.swift // LXFWeChat // // Created by 林洵锋 on 2017/2/3. // Copyright © 2017年 林洵锋. All rights reserved. // // GitHub: https://github.com/LinXunFeng // 简书: http://www.jianshu.com/users/31e85e7a22a2 import Foundation enum LXFWeChatToolsUpdateType { case nickName // 昵称 case avatar // 头像 case sign // 签名 case gender // 性别 } enum LXFWeChatToolsGender { case male // 男 case female // 女 case unknow // 未知 } extension LXFWeChatTools { // MARK: 更新头像 func updateAvatar(with image: UIImage) { let imgData = UIImageJPEGRepresentation(image, 0.5) let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first let totalPath = documentPath! + "userAvatar" guard ((try? imgData!.write(to: URL(fileURLWithPath: totalPath))) != nil) else { return } LXFProgressHUD.lxf_showWithStatus("正在上传") NIMSDK.shared().resourceManager.upload(totalPath, progress: nil) { [unowned self] (urlString, error) in if error != nil { LXFLog(error) LXFProgressHUD.lxf_showError(withStatus: "上传失败") } else { LXFLog(urlString) guard let urlStr = urlString else { LXFProgressHUD.lxf_showError(withStatus: "未获得头像地址") return } self.update(with: urlStr, type: .avatar) LXFProgressHUD.lxf_showSuccess(withStatus: "上传成功") } } } // MARK: 更新签名 func updateSign(with sign: String) { self.update(with: sign, type: .sign) } // MARK: 更新昵称 func updateNickName(with nickName: String) { self.update(with: nickName, type: .nickName) } // MARK: 更新性别 func updateGender(with gender: LXFWeChatToolsGender) { var userGender: NIMUserGender! switch gender { case .male: userGender = NIMUserGender.male case .female: userGender = NIMUserGender.female default: userGender = NIMUserGender.unknown break } self.update(with: "", type: .gender, gender: userGender) } } // MARK:- 修改用户信息(string) extension LXFWeChatTools { fileprivate func update(with str: String, type: LXFWeChatToolsUpdateType, gender: NIMUserGender? = nil) { var key: NSNumber! switch type { case .nickName: key = NSNumber(value: NIMUserInfoUpdateTag.nick.rawValue) case .avatar: key = NSNumber(value: NIMUserInfoUpdateTag.avatar.rawValue) case .sign: key = NSNumber(value: NIMUserInfoUpdateTag.sign.rawValue) case .gender: key = NSNumber(value: NIMUserInfoUpdateTag.gender.rawValue) } var dict: [NSNumber : String] = [key: str] if type == .gender { dict = [key: "\(gender!.rawValue)"] } NIMSDK.shared().userManager.updateMyUserInfo(dict) { (error) in if error != nil { LXFLog(error) } else { LXFLog("修改成功") // 返回通知 NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNoteWeChatGoBack), object: type) } } } }
29.152542
117
0.565698
0e080b7dcbcaea14c1f4ef3a05b55ee7f0c326de
1,218
class Solution { // Solution @ Sergey Leschev, Belarusian State University // 1781. Sum of Beauty of All Substrings // The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. // For example, the beauty of "abaacc" is 3 - 1 = 2. // Given a string s, return the sum of beauty of all of its substrings. // Example 1: // Input: s = "aabcb" // Output: 5 // Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1. // Example 2: // Input: s = "aabcbaa" // Output: 17 // Constraints: // 1 <= s.length <= 500 // s consists of only lowercase English letters. func beautySum(_ s: String) -> Int { var ans = 0 var counter = [Character:Int]() let n = s.count let chars = [Character](s) for i in 0..<(n - 1) { counter[chars[i], default: 0] += 1 for j in (i + 1)..<n { counter[chars[j], default: 0] += 1 ans += (counter.values.max() ?? 0) - (counter.values.min() ?? 0 ) } counter = [:] } return ans } }
31.230769
125
0.545156
23446ba14958aee15348e788fc3d3d721890c53b
347
import UIKit public class aUser : Codable { open var username : String? = "" open var email : String? = "" init(){ // Default constructor required for calls to DataSnapshot.getValue(aUser.class) } init(_ username: String?, _ email: String?){ self.username = username! self.email = email! } }
17.35
87
0.599424
56d37e8a0c0e346e145534f124c2ca692899bd59
6,110
// // ViewController.swift // laser-spirograph // // Created by Julian Tigler on 12/1/20. // import UIKit import CoreData class ViewController: UIViewController { // MARK: Properties var managedObjectContext: NSManagedObjectContext? @IBOutlet weak var canvas: LSCanvas! @IBOutlet weak var multisliderView: LSMultisliderView! @IBOutlet weak var loadSpiralButton: LSCircleButton! private var spiralController = LSSpiralController() private static let maxRotationsPerSecond: Float = pow(2, 7) // MARK: Initialization override func viewDidLoad() { super.viewDidLoad() spiralController.canvas = canvas spiralController.isAnimating = true multisliderView.maxValue = Self.maxRotationsPerSecond multisliderView.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.isIdleTimerDisabled = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIApplication.shared.isIdleTimerDisabled = false } // MARK: Navigation override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == "PresentSpiralsTableViewController" { return managedObjectContext != nil } return super.shouldPerformSegue(withIdentifier: identifier, sender: sender) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) guard let navigationController = segue.destination as? UINavigationController else { return } if let spiralsTVC = navigationController.topViewController as? SpiralsTableViewController { spiralsTVC.managedObjectContext = managedObjectContext spiralsTVC.delegate = self } else if let settingsTVC = navigationController.topViewController as? SettingsTableViewController { settingsTVC.managedObjectContext = managedObjectContext } willPresent(navigationController) } override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { super.dismiss(animated: flag) { completion?() self.didDismiss() } } // MARK: Saving @IBAction func saveButtonPressed(_ sender: Any) { guard let context = managedObjectContext else { let alert = UIAlertController.okAlert(title: "Failed to save spiral", message: "Couldn't connect to database") present(alert, animated: true) return } let parameterSet = spiralController.getParameterSet(context) if let error = parameterSet.save() { let alert = UIAlertController.okAlert(title: "Failed to save spiral", message: error.localizedDescription) self.present(alert, animated: true) return } spiralController.isAnimating = false showSaveAnimation(completion: { self.spiralController.loadParameterSet(parameterSet) self.spiralController.isAnimating = true }) } private func showSaveAnimation(completion: @escaping () -> ()) { canvas.layer.cornerRadius = canvas.bounds.width / 2 let previousBackgroundColor = canvas.backgroundColor canvas.backgroundColor = .secondarySystemFill UIView.animate(withDuration: 1) { self.canvas.transform = self.getTransform(from: self.canvas, to: self.loadSpiralButton) } completion: { (finished) in self.canvas.layer.cornerRadius = 0 self.canvas.backgroundColor = previousBackgroundColor self.canvas.transform = .identity completion() } } private func getTransform(from start: UIView, to destination: UIView) -> CGAffineTransform { let scaleX = destination.bounds.width / start.bounds.width let scaleY = destination.bounds.height / start.bounds.height let scaleTransform = CGAffineTransform(scaleX: scaleX, y: scaleY) let destinationMiddle = CGPoint(x: destination.bounds.midX, y: destination.bounds.midY) let convertedCenter = destination.convert(destinationMiddle, to: start) let centerDeltaX = convertedCenter.x - start.center.x let centerDeltaY = convertedCenter.y - start.center.y let translationTransform = CGAffineTransform(translationX: centerDeltaX, y: centerDeltaY) return scaleTransform.concatenating(translationTransform) } // MARK: Loading private func load(_ parameterSet: LSParameterSet) { multisliderView.setValues(parameterSet.rotationsPerSeconds) spiralController.loadParameterSet(parameterSet) } } // MARK: LSMultisliderViewDelegate extension ViewController: LSMultisliderViewDelegate { func multisliderView(_ sender: LSMultisliderView, didChange value: Float, at index: Int) { spiralController.updateCircleSpeed(Double(value), at: index) } } // MARK: SpiralsTableViewControllerDelegate extension ViewController: SpiralsTableViewControllerDelegate { func spiralsTableViewController(_ sender: SpiralsTableViewController, didSelect parameterSet: LSParameterSet) { load(parameterSet) } } // MARK: UIAdaptivePresentationControllerDelegate extension ViewController: UIAdaptivePresentationControllerDelegate { func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { didDismiss() } private func willPresent(_ navigationController: UINavigationController) { navigationController.presentationController?.delegate = self spiralController.isAnimating = false } private func didDismiss() { guard presentedViewController == nil else { return } spiralController.isAnimating = true } }
34.715909
122
0.677741
f87fc016f076a9ddf15ce423fa8cae3e086d43d4
719
// // BookmarksViewController.swift // AppFlavors-starter // // Created by Carlos Martin on 2020-07-10. // Copyright © 2020 Softhouse Nordic, AB. All rights reserved. // import UIKit class BookmarksViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Bookmarks" } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
23.966667
106
0.675939
1eb235912a14fcdaf6a1907563746271f2b7ed29
380
// // ContentView.swift // Landmarks // // Created by nukopy on 2021/10/18 // // import SwiftUI struct ContentView: View { var body: some View { LandmarkList() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { Group { ContentView() .environmentObject(ModelData()) } } }
15.2
47
0.576316
480f1bf7b229149a3df6baf2321e1b7dee61217b
20,947
import UIKit /** ``` .name: String? .idNum: Int? .colorTheme: KDColorTheme? .onTouch: ((KDView) -> ())? .gestureRecognizer: UIGestureRecognizer? .tap: UITapGestureRecognizer?, .longPress: UILongPressGestureRecognizer?, .swipe: UISwipeGestureRecognizer?, .pan: UIPanGestureRecognizer?, .pinch: UIPinchGestureRecognizer? ---- .addToSuperview(_ view: UIView) .setBackgroundColor(_ color: UIColor) .setColorTheme(_ colorTheme: KDColorTheme) .setBorderWidth(_ width: CGFloat) .setBorderColor(_ color: UIColor) .setRoundness(_ roundness: CGFloat) .setBorder(color: UIColor, width: CGFloat) .setBorder(width: CGFloat, roundness: CGFloat) .setBorder(color: UIColor, width: CGFloat, roundness: CGFloat) .setShadow(shadow: Shadow) .setShadowRadius(_ radius: CGFloat) .setShadowOffset(_ x: CGFloat, _ y: CGFloat) .setShadowOpacity(_ opacity: Float) .setShadowColor(_ color: UIColor) .setCenter(_ x: CGFloat, _ y: CGFloat) .setOriginX(_ x: CGFloat) .setOriginY(_ y: CGFloat) .setWidth(_ width: CGFloat) .setHeight(_ height: CGFloat) .setSize(_ width: CGFloat, _ height: CGFloat) .setOrigin(_ x: CGFloat, _ y: CGFloat) .setTopMargin(_ margin: CGFloat) .setBottomMargin(_ margin: CGFloat) .setLeftMargin(_ margin: CGFloat) .setRightMargin(_ margin: CGFloat) .setVerticalMargins(_ margin: CGFloat) .setHorizontalMargins(_ margin: CGFloat) .setMargins(_ margin: CGFloat) .addTap() .removeTap() .didTap(sender: UITapGestureRecognizer) .addLongPress() .addLongPress(duration: Double) .removeLongPress() .didLongPress(sender: UILongPressGestureRecognizer) .addSwipe() .removeSwipe() .didSwipe(sender: UISwipeGestureRecognizer) .addPan() .removePan() .didPan(sender: UIPanGestureRecognizer) .addPinch() .removePinch() .didPinch(sender: UIPinchGestureRecognizer) ``` */ class KDView: UIView { var name: String?, idNum: Int?, colorTheme: KDColorTheme?, onTouch: ((KDView) -> ())?, gestureRecognizer: UIGestureRecognizer? var tap: UITapGestureRecognizer?, longPress: UILongPressGestureRecognizer?, swipe: UISwipeGestureRecognizer?, pan: UIPanGestureRecognizer?, pinch: UIPinchGestureRecognizer? // these are used in subclasses var useHiddenTouch: Bool = false var onHiddenTouch: ((KDView) -> ())? override init(frame: CGRect) { super.init(frame: frame) } // ////////////////////////////// // MARK: Convenience Inits // ////////////////////////////// /** Convenience init with nullable frame. Sets frame to `CGRect.zero` if `frame:` is `nil`. */ convenience init(_ frame: CGRect?) { let rect: CGRect = frame != nil ? frame! : CGRect.zero self.init(frame: rect) } // //////////////////////////////////////////////////////////////////////////////////////////// // MARK: Unofficial KDView Protocol // //////////////////////////////////////////////////////////////////////////////////////////// // ////////////////////////////// // MARK: View Hierarchy // ////////////////////////////// /** Convenience function to mirror syntax for `UIView.removeFromSuperview()`. */ @discardableResult func addToSuperview(_ view: UIView) -> KDView { view.addSubview(self) return self } // ////////////////////////////// // MARK: Color // ////////////////////////////// /** Set the background color for this view. */ @discardableResult func setBackgroundColor(_ color: UIColor) -> KDView { self.backgroundColor = color return self } /** Sets `self.colorTheme` and updates the background, border, and shadow color to conform to the new theme. Use `self.colorTheme = newTheme` to set the theme property without updating the existing colors. */ @discardableResult func setColorTheme(_ colorTheme: KDColorTheme) -> KDView { self.colorTheme = colorTheme self.setBackgroundColor(colorTheme.background) .setBorderColor(colorTheme.border) .setShadowColor(colorTheme.shadow) return self } // ////////////////////////////// // MARK: Border // ////////////////////////////// /** Set the width of the border for this view. */ @discardableResult func setBorderWidth(_ width: CGFloat) -> KDView { self.layer.borderWidth = width return self } /** Set the color of the border for this view. */ @discardableResult func setBorderColor(_ color: UIColor) -> KDView { self.layer.borderColor = color.cgColor return self } /** Set the roundness of the corners for this view. Update shadow to account for changes. */ @discardableResult func setRoundness(_ roundness: CGFloat) -> KDView { self.layer.cornerRadius = roundness self.setShadowPath() return self } /** Convenience function for setting border properties for this view. */ @discardableResult func setBorder(color: UIColor, width: CGFloat) -> KDView { // store and remove roundess so order when setting corner radius doesn't matter let roundness = self.layer.cornerRadius self.layer.cornerRadius = 0 self.setBorderColor(color) .setBorderWidth(width) self.layer.cornerRadius = roundness return self } /** Convenience function for setting border properties for this view. */ @discardableResult func setBorder(width: CGFloat, roundness: CGFloat) -> KDView { setBorderWidth(width) setRoundness(roundness) return self } /** Convenience function for setting border properties for this view. */ @discardableResult func setBorder(color: UIColor, width: CGFloat, roundness: CGFloat) -> KDView { setBorder(color: color, width: width) setRoundness(roundness) return self } /** Returns `CGFloat` equal to half of the views short side length'. */ func getRadius() -> CGFloat { let shortSide = vw(self) <= vh(self) ? vw(self) : vh(self) return shortSide / 2 } // ////////////////////////////// // MARK: Shadow // ////////////////////////////// /** Ensure shadows respect rounded corners. */ private func setShadowPath() { let shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius) self.layer.masksToBounds = false self.layer.shadowPath = shadowPath.cgPath } /** Set the shadow for this object and update the shadow path. Pass `nil` to remove the shadow. */ @discardableResult func setShadow(_ shadow: Shadow?) -> KDView { if shadow != nil { self.layer.shadowRadius = shadow!.radius self.layer.shadowOffset = shadow!.offset self.layer.shadowColor = shadow!.color.cgColor self.layer.shadowOpacity = shadow!.opacity setShadowPath() } else { self.layer.shadowRadius = 0 self.layer.shadowOffset = CGSize(width: 0, height: 0) self.layer.shadowColor = KDColor.clear.cgColor self.layer.shadowOpacity = 0 setShadowPath() } return self } /** Set the shadow radius (size) and update the shadow path. */ @discardableResult func setShadowRadius(_ radius: CGFloat) -> KDView { self.layer.shadowRadius = radius setShadowPath() return self } /** Set the shadow offset and update the shadow path. */ @discardableResult func setShadowOffset(_ x: CGFloat, _ y: CGFloat) -> KDView { self.layer.shadowOffset = CGSize(width: x, height: y) setShadowPath() return self } /** Set the shadow opacity and update the shadow path. */ @discardableResult func setShadowOpacity(_ opacity: Float) -> KDView { self.layer.shadowOpacity = opacity setShadowPath() return self } /** Set the shadow color and update the shadow path. */ @discardableResult func setShadowColor(_ color: UIColor) -> KDView { self.layer.shadowColor = color.cgColor setShadowPath() return self } // ////////////////////////////// // MARK: Frame // ////////////////////////////// /** Set the center x position for this view. The center point is specified in points in the coordinate system of its superview. */ @discardableResult func setCenterX(_ x: CGFloat) -> KDView { self.center = CGPoint(x: x, y: self.center.y) return self } /** Set the center y position for this view. The center point is specified in points in the coordinate system of its superview. */ @discardableResult func setCenterY(_ y: CGFloat) -> KDView { self.center = CGPoint(x: self.center.x, y: y) return self } /** Set the center point for this view. The center point is specified in points in the coordinate system of its superview. */ @discardableResult func setCenter(_ x: CGFloat, _ y: CGFloat) -> KDView { self.center = CGPoint(x: x, y: y) return self } /** Set the center point for this view. */ @discardableResult func setCenter(_ center: CGPoint) -> KDView { self.center = center return self } @discardableResult func centerOnParent () -> KDView { guard let superview = self.superview else { return self } self.setCenter(superview.bounds.width / 2, superview.bounds.height / 2) return self } /** Set the x origin for this view. Specified in points in the coordinate system of its superview. */ @discardableResult func setOriginX(_ x: CGFloat) -> KDView { self.frame = CGRect(x: x, y: self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height) return self } /** Set the y origin for this view. Specified in points in the coordinate system of its superview. */ @discardableResult func setOriginY(_ y: CGFloat) -> KDView { self.frame = CGRect(x: self.frame.origin.x, y: y, width: self.frame.size.width, height: self.frame.size.height) return self } /** Set the width of this view. */ @discardableResult func setWidth(_ width: CGFloat) -> KDView { self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: width, height: self.frame.size.height) return self } /** Set the height of this view. */ @discardableResult func setHeight(_ height: CGFloat) -> KDView { self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: height) return self } /** Set the size of this view. */ @discardableResult func setSize(_ width: CGFloat, _ height: CGFloat) -> KDView { self.setWidth(width) self.setHeight(height) return self } /** Set the origin of this view. */ @discardableResult func setOrigin(_ x: CGFloat, _ y: CGFloat) -> KDView { self.setOriginX(x) self.setOriginY(y) return self } // ////////////////////////////// // MARK: Margins // ////////////////////////////// /** Changes the frame of this view to add a margin to the top. Moves the y origin and changes the height of the view. */ @discardableResult func setTopMargin(_ margin: CGFloat) -> KDView { if (margin * 2 >= self.frame.height) { print("\nVertical margins must be less than half the height of the view.") return self } self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y + margin, width: self.frame.size.width, height: self.frame.size.height - margin) return self } /** Changes the frame of this view to add a margin to the bottom. Changes the height of the view. */ @discardableResult func setBottomMargin(_ margin: CGFloat) -> KDView { if (margin * 2 >= self.frame.height) { print("\nVertical margins must be less than half the height of the view.") return self } self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height - margin) return self } /** Changes the frame of this view to add a margin to the left. Moves the x origin and changes the width of the view. */ @discardableResult func setLeftMargin(_ margin: CGFloat) -> KDView { if (margin * 2 >= self.frame.width) { print("\nHorizontal margins must be less than half the width of the view.") return self } self.frame = CGRect(x: self.frame.origin.x + margin, y: self.frame.origin.y, width: self.frame.size.width - margin, height: self.frame.size.height) return self } /** Changes the frame of this view to add a margin to the right. Changes the width of the view. */ @discardableResult func setRightMargin(_ margin: CGFloat) -> KDView { if (margin * 2 >= self.frame.width) { print("\nHorizontal margins must be less than half the width of the view.") return self } self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.size.width - margin, height: self.frame.size.height) return self } /** Changes the frame of this view to add margins to the top and bottom. Moves the y origin and changes the height of the view by calling `setTopMargin(margin:)` and `setBottomMargin(margin:)`. */ @discardableResult func setVerticalMargins(_ margin: CGFloat) -> KDView { setTopMargin(margin) setBottomMargin(margin) return self } /** Changes the frame of this view to add margins to the left and right. Moves the x origin and changes the width of the view by calling `setLeftMargin(margin:)` and `setRightMargin(margin:)`. */ @discardableResult func setHorizontalMargins(_ margin: CGFloat) -> KDView { setLeftMargin(margin) setRightMargin(margin) return self } /** Changes the frame of this view to add margins on all sides. Moves the x and y origins and changes the height and width of the view by calling `setVerticalMargins(margin:)` and `setHorizontalMargins(margin:)`. */ @discardableResult func setMargins(_ margin: CGFloat) -> KDView { setVerticalMargins(margin) setHorizontalMargins(margin) return self } // ////////////////////////////// // MARK: Tap // ////////////////////////////// private func doTouch() { self.onTouch?(self) if self.useHiddenTouch { self.onHiddenTouch?(self) } } /** Add a `UITapGestureRecognizer` as this views `tap` property. */ @discardableResult func addTap() -> KDView { tap = UITapGestureRecognizer(target: self, action: #selector(didTap(sender:))) self.addGestureRecognizer(tap!) return self } /** Remove the `UITapGestureRecognizer` from this view and set the `tap` property to `nil`. */ @discardableResult func removeTap() -> KDView { if tap != nil { self.removeGestureRecognizer(tap!) tap = nil } return self } /** Called by this views `tap` property. */ @objc private func didTap(sender: UITapGestureRecognizer) { sender.type = .tap self.gestureRecognizer = sender doTouch() } // ////////////////////////////// // MARK: Long Press // ////////////////////////////// /** Add a `UILongPressGestureRecognizer` as this views `tap` property. */ @discardableResult func addLongPress() -> KDView { longPress = UILongPressGestureRecognizer(target: self, action: #selector(didLongPress(sender:))) self.addGestureRecognizer(longPress!) return self } /** Add a `UILongPressGestureRecognizer` as this views `tap` property. `duration:` is the `minimumPressDuration` of the gesture, which represents how long the user must press before the gesture is recognized. */ @discardableResult func addLongPress(duration: Double) -> KDView { addLongPress() longPress?.minimumPressDuration = duration return self } /** Remove the `UILongPressGestureRecognizer` from this view and set the `longPress` property to `nil`. */ @discardableResult func removeLongPress() -> KDView { if longPress != nil { self.removeGestureRecognizer(longPress!) longPress = nil } return self } /** Called by this views `longPress` property. */ @objc private func didLongPress(sender: UILongPressGestureRecognizer) { sender.type = .longPress self.gestureRecognizer = sender doTouch() } // ////////////////////////////// // MARK: Swipe // ////////////////////////////// /** Add a `UISwipeGestureRecognizer` as this views `swipe` property. */ @discardableResult func addSwipe() -> KDView { swipe = UISwipeGestureRecognizer(target: self, action: #selector(didSwipe(sender:))) self.addGestureRecognizer(swipe!) return self } /** Add a `UISwipeGestureRecognizer` as this views `swipe` property. `direction:` is a `UISwipeGestureRecognizerDirection` case: - `.up` - `.down` - `.left` - `.right` */ @discardableResult func addSwipe(_ direction: UISwipeGestureRecognizer.Direction) -> KDView { addSwipe() swipe?.direction = direction return self } /** Remove the `UISwipeGestureRecognizer` from this view and set the `swipe` property to `nil`. */ @discardableResult func removeSwipe() -> KDView { if swipe != nil { self.removeGestureRecognizer(swipe!) swipe = nil } return self } /** Called by this views `swipe` property. */ @objc private func didSwipe(sender: UISwipeGestureRecognizer) { sender.type = .swipe self.gestureRecognizer = sender doTouch() } // ////////////////////////////// // MARK: Pan // ////////////////////////////// /** Add a `UIPanGestureRecognizer` as this views `swipe` property. */ @discardableResult func addPan() -> KDView { pan = UIPanGestureRecognizer(target: self, action: #selector(didPan(sender:))) self.addGestureRecognizer(pan!) return self } /** Remove the `UIPanGestureRecognizer` from this view and set the `pan` property to `nil`. */ @discardableResult func removePan() -> KDView { if pan != nil { self.removeGestureRecognizer(pan!) pan = nil } return self } /** Called by this views `swipe` property. */ @objc private func didPan(sender: UIPanGestureRecognizer) { sender.type = .pan self.gestureRecognizer = sender doTouch() } // ////////////////////////////// // MARK: Pinch // ////////////////////////////// /** Add a `UIPinchGestureRecognizer` as this views `swipe` property. */ @discardableResult func addPinch() -> KDView { pinch = UIPinchGestureRecognizer(target: self, action: #selector(didPinch(sender:))) self.addGestureRecognizer(pinch!) return self } /** Remove the `UIPinchGestureRecognizer` from this view and set the `pinch` property to `nil`. */ @discardableResult func removePinch() -> KDView { if pinch != nil { self.removeGestureRecognizer(pinch!) pinch = nil } return self } /** Called by this views `pinch` property. */ @objc private func didPinch(sender: UIPinchGestureRecognizer) { sender.type = .pinch self.gestureRecognizer = sender doTouch() } // ////////////////////////////// // MARK: Coder // ////////////////////////////// required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
29.924286
153
0.58438
e097eb10d3f34fe4d9637b7c8553b2a9f96ff686
904
// // SheetPreviewCollectionViewCell.swift // ImagePickerSheetController // // Created by Laurin Brandner on 06/09/14. // Copyright (c) 2014 Laurin Brandner. All rights reserved. // import UIKit class SheetPreviewCollectionViewCell: SheetCollectionViewCell { var collectionView: PreviewCollectionView? { willSet { if let collectionView = collectionView { collectionView.removeFromSuperview() } if let collectionView = newValue { addSubview(collectionView) } } } // MARK: - Other Methods override func prepareForReuse() { collectionView = nil } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() collectionView?.frame = UIEdgeInsetsInsetRect(bounds, backgroundInsets) } }
22.6
79
0.602876
bf135dd830124b215cbfb3974a3fbf97829d283e
363
// // WeatherData.swift // ARWeather // // Created by Diego Castro on 21/01/22. // import Foundation //We will define a template to get the data from the JSON struct struct WeatherData: Codable { let name: String let weather: [Weather] let main: Main } struct Weather: Codable { let id: Int } struct Main: Codable { let temp: Double }
14.52
64
0.666667
e68eab1c1515844e1cb8662417efebd6aa8321ce
193
// // Created by Papp Imre on 2019-02-13. // Copyright (c) 2019 CocoaPods. All rights reserved. // import NMDEF_Base struct MenuItemModel: BaseModel { var id: Menu var name: String }
16.083333
53
0.689119
89187f7ed0a6616b8796f97c7b6a406d601734a0
888
// // Lot6Tests.swift // Lot6Tests // // Created by 清水 一征 on 2015/01/15. // Copyright (c) 2015年 momiji-mac. All rights reserved. // import UIKit import XCTest class Lot6Tests: 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.measureBlock() { // Put the code you want to measure the time of here. } } }
24
111
0.608108
1c316f6b3af8e328acfcdffaf0c6d497aee585b7
161
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(PoetryClubTests.allTests) ] } #endif
16.1
47
0.670807
e2ebba668bce2a5047c376bad99f63137039c81f
3,666
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// import SwiftSyntax extension ModifierListSyntax { func has(modifier: String) -> Bool { return contains { $0.name.text == modifier } } func has(modifier: TokenKind) -> Bool { return contains { $0.name.tokenKind == modifier } } /// Returns the declaration's access level modifier, if present. var accessLevelModifier: DeclModifierSyntax? { for modifier in self { switch modifier.name.tokenKind { case .publicKeyword, .privateKeyword, .fileprivateKeyword, .internalKeyword: return modifier default: continue } } return nil } /// Returns modifier list without the given modifier. func remove(name: String) -> ModifierListSyntax { guard has(modifier: name) else { return self } for mod in self { if mod.name.text == name { return removing(childAt: mod.indexInParent) } } return self } /// Returns a foramatted declaration modifier token with the given name. func createModifierToken(name: String) -> DeclModifierSyntax { let id = SyntaxFactory.makeIdentifier(name, trailingTrivia: .spaces(1)) let newModifier = SyntaxFactory.makeDeclModifier( name: id, detailLeftParen: nil, detail: nil, detailRightParen: nil) return newModifier } /// Returns modifiers with the given modifier inserted at the given index. /// Preserves existing trivia and formats new trivia, given true for 'formatTrivia.' func insert( modifier: DeclModifierSyntax, at index: Int, formatTrivia: Bool = true ) -> ModifierListSyntax { guard index >= 0, index <= count else { return self } var newModifiers: [DeclModifierSyntax] = [] newModifiers.append(contentsOf: self) let modifier = formatTrivia ? replaceTrivia( on: modifier, token: modifier.name, trailingTrivia: .spaces(1)) : modifier if index == 0 { guard formatTrivia else { return inserting(modifier, at: index) } guard let firstMod = first, let firstTok = firstMod.firstToken else { return inserting(modifier, at: index) } let formattedMod = replaceTrivia( on: modifier, token: modifier.firstToken, leadingTrivia: firstTok.leadingTrivia) newModifiers[0] = replaceTrivia( on: firstMod, token: firstTok, leadingTrivia: [], trailingTrivia: .spaces(1)) newModifiers.insert(formattedMod, at: 0) return SyntaxFactory.makeModifierList(newModifiers) } else { return inserting(modifier, at: index) } } /// Returns modifier list with the given modifier at the end. /// Trivia manipulation optional by 'formatTrivia' func append(modifier: DeclModifierSyntax, formatTrivia: Bool = true) -> ModifierListSyntax { return insert(modifier: modifier, at: count, formatTrivia: formatTrivia) } /// Returns modifier list with the given modifier at the beginning. /// Trivia manipulation optional by 'formatTrivia' func prepend(modifier: DeclModifierSyntax, formatTrivia: Bool = true) -> ModifierListSyntax { return insert(modifier: modifier, at: 0, formatTrivia: formatTrivia) } }
34.261682
95
0.658211
ff02276f759aa15ca60a875af72ed821ee89011d
2,512
/// Check an SPI import of an SPI library to detect correct SPI access // RUN: %empty-directory(%t) // /// Compile the SPI lib // RUN: %target-swift-frontend -emit-module %S/Inputs/spi_helper.swift -module-name SPIHelper -emit-module-path %t/SPIHelper.swiftmodule -emit-module-interface-path %t/SPIHelper.swiftinterface -emit-private-module-interface-path %t/SPIHelper.private.swiftinterface -enable-library-evolution -swift-version 5 -parse-as-library /// Reading from swiftmodule // RUN: %target-typecheck-verify-swift -I %t -verify-ignore-unknown /// Reading from .private.swiftinterface // RUN: rm %t/SPIHelper.swiftmodule // RUN: %target-typecheck-verify-swift -I %t -verify-ignore-unknown //// Reading from .swiftinterface should fail as it won't find the decls // RUN: rm %t/SPIHelper.private.swiftinterface // RUN: not %target-swift-frontend -typecheck -I %t @_spi(HelperSPI) import SPIHelper // Use as SPI publicFunc() spiFunc() internalFunc() // expected-error {{cannot find 'internalFunc' in scope}} let c = SPIClass() c.spiMethod() c.spiVar = "write" print(c.spiVar) let s = SPIStruct() s.spiMethod() s.spiInherit() s.spiDontInherit() // expected-error {{'spiDontInherit' is inaccessible due to '@_spi' protection level}} s.spiExtensionHidden() s.spiExtension() s.spiExtensionInherited() s.spiVar = "write" print(s.spiVar) SPIEnum().spiMethod() SPIEnum.A.spiMethod() var ps = PublicStruct() let _ = PublicStruct(alt_init: 1) ps.spiMethod() ps.spiVar = "write" print(ps.spiVar) otherApiFunc() // expected-error {{cannot find 'otherApiFunc' in scope}} public func publicUseOfSPI(param: SPIClass) -> SPIClass {} // expected-error 2{{cannot use class 'SPIClass' here; it is an SPI imported from 'SPIHelper'}} public func publicUseOfSPI2() -> [SPIClass] {} // expected-error {{cannot use class 'SPIClass' here; it is an SPI imported from 'SPIHelper'}} @inlinable public func inlinable() -> SPIClass { // expected-error {{class 'SPIClass' is '@_spi' and cannot be referenced from an '@inlinable' function}} spiFunc() // expected-error {{global function 'spiFunc()' is '@_spi' and cannot be referenced from an '@inlinable' function}} _ = SPIClass() // expected-error {{class 'SPIClass' is '@_spi' and cannot be referenced from an '@inlinable' function}} _ = [SPIClass]() // expected-error {{class 'SPIClass' is '@_spi' and cannot be referenced from an '@inlinable' function}} } @_spi(S) @inlinable public func inlinable() -> SPIClass { spiFunc() _ = SPIClass() _ = [SPIClass]() }
36.405797
325
0.727309
112619d8a0792592779fb97bf8e450cd42f5a3c9
466
import Foundation internal let ClosureHandlerSelector = Selector(("handle")) internal class ClosureHandler<T: AnyObject>: NSObject { internal var handler: ((T) -> Void)? internal weak var control: T? internal init(handler: @escaping (T) -> Void, control: T? = nil) { self.handler = handler self.control = control } @objc func handle() { if let control = self.control { handler?(control) } } }
22.190476
70
0.609442
d60e68a0de8f4005cb41128c9b20ff8c467fad34
3,304
// // frid.swift // frid // // Created by Evgeny Kazakov on 02/02/2017. // Copyright © 2017 Evgeny Kazakov. All rights reserved. // import Foundation public struct FrId { private init() { } /// Provides current date. Needed for testing. internal static var now: () -> Date = { Date() } /// Fancy ID generator that creates 20-character string identifiers with the following properties: /// /// 1. They're based on timestamp so that they sort *after* any existing ids. /// 2. They contain 72-bits of random data after the timestamp so that IDs won't collide with other clients' IDs. /// 3. They sort *lexicographically* (so the timestamp is converted to characters that will sort properly). /// 4. They're monotonically increasing. Even if you generate more than one in the same timestamp, the /// latter ones will sort after the former ones. We do this by using the previous random bits /// but "incrementing" them by 1 (only in the case of a timestamp collision). /// /// - Returns: generated id public static func generate() -> String { let nowMilliseconds = UInt64(now().timeIntervalSince1970 * 1000) defer { lastMilliseconds = nowMilliseconds } // Convert timestamp to characters from alphabet. let timeStampChars = (0...7) .reversed() .map { (shiftMultiplier: Int) -> UInt64 in nowMilliseconds >> UInt64(6 * shiftMultiplier) } .map { (rnd: UInt64) -> Int in Int(rnd % 64) } .map { (index: Int) -> Character in alphabetCharacters[index] } let duplicateTime = nowMilliseconds == lastMilliseconds // If the timestamp hasn't changed since last generation, use the same random number, except incremented by 1. randomCharactersIndexes = duplicateTime ? inc(randomCharactersIndexes) : generateNewRandomIndexes() let randomCharacters = randomCharactersIndexes.map { alphabetCharacters[$0] } let idCharacters = timeStampChars + randomCharacters return String(idCharacters) } } /// Modeled after base64 web-safe chars, but ordered by ASCII. private let alphabet = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" private let alphabetCharacters = [Character](alphabet.characters) /// Timestamp of last generation, used to prevent local collisions if you generate twice in one ms. private var lastMilliseconds: UInt64 = 0 /// We generate 72-bits of randomness which get turned into 12 characters and appended to the /// timestamp to prevent collisions with other clients. We store the last characters we /// generated because in the event of a collision, we'll use those same characters except /// "incremented" by one. private var randomCharactersIndexes: [Int] = generateNewRandomIndexes() private func generateNewRandomIndexes() -> [Int] { return (0...11).map { _ in Int(arc4random_uniform(64)) } } /// Increment random number by 1. /// Number is presented in form of array of 'digits'. /// Base == `alphabetCharacters.count` /// /// - Parameter rnd: random number /// - Returns: incremented private func inc(_ rnd: [Int]) -> [Int] { let base = alphabetCharacters.count var incremented = rnd var index = incremented.count - 1 while incremented[index] == base - 1 { incremented[index] = 0 index -= 1 } incremented[index] += 1 return incremented }
38.418605
115
0.71701
7a0065038aac9862d725eb6a32309aebface6755
186
// // ErrorView.swift // ARPlacer // // Created by alok subedi on 24/11/2021. // public protocol ErrorView { func display(error: String) func displayAndHide(error: String) }
15.5
41
0.672043
f71d96e2d4e0fe576784015b371f8161ada2521c
7,716
// // RideActionView.swift // uber-clone // // Created by Ted Hyeong on 21/10/2020. // import UIKit import MapKit protocol RideActionViewDelegate: class { func uploadTrip(_ view: RideActionView) func cancelTrip() func pickupPassenger() func dropOffPassenger() } enum RideActionViewConfiguration { case requestRide case tripAccepted case driverArrived case pickupPassenger case tripInProgress case endTrip init() { self = .requestRide } } enum ButtonAction: CustomStringConvertible { case requestRide case cancel case getDirections case pickup case dropoff var description: String { switch self { case .requestRide: return "CONFIRM UBERX" case .cancel: return "CANCEL RIDE" case .getDirections: return "GET DIRECTIONS" case .pickup: return "PICKUP PASSENGER" case .dropoff: return "DROP OFF PASSENGER" } } init() { self = .requestRide } } class RideActionView: UIView { // MARK: - Properties var destination: MKPlacemark? { didSet { titleLabel.text = destination?.name addressLabel.text = destination?.address } } var buttonAction = ButtonAction() weak var delegate: RideActionViewDelegate? var user: User? var config = RideActionViewConfiguration() { didSet { configureUI(withConfig: config) } } private let titleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 18) label.textAlignment = .center return label }() private let addressLabel: UILabel = { let label = UILabel() label.textColor = .lightGray label.font = UIFont.systemFont(ofSize: 16) label.textAlignment = .center return label }() private lazy var infoView: UIView = { let view = UIView() view.backgroundColor = .black view.addSubview(infoViewLabel) infoViewLabel.centerX(inView: view) infoViewLabel.centerY(inView: view) return view }() private let infoViewLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 30) label.textColor = .white label.text = "X" return label }() private let uberInfoLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 18) label.text = "UberX" label.textAlignment = .center return label }() private let actionButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = .black button.setTitle("CONFIRM UBERX", for: .normal) button.setTitleColor(.white, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20) button.addTarget(self, action: #selector(actionButtonPressed), for: .touchUpInside) return button }() // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white addShadow() let stack = UIStackView(arrangedSubviews: [titleLabel, addressLabel]) stack.axis = .vertical stack.spacing = 4 stack.distribution = .fillEqually addSubview(stack) stack.centerX(inView: self) stack.anchor(top: topAnchor, paddingTop: 12) addSubview(infoView) infoView.centerX(inView: self) infoView.anchor(top: stack.bottomAnchor, paddingTop: 16) infoView.setDimensions(height: 60, width: 60) infoView.layer.cornerRadius = 60 / 2 addSubview(uberInfoLabel) uberInfoLabel.anchor(top: infoView.bottomAnchor, paddingTop: 8) uberInfoLabel.centerX(inView: self) let separatorView = UIView() separatorView.backgroundColor = .lightGray addSubview(separatorView) separatorView.anchor(top: uberInfoLabel.bottomAnchor, left: leftAnchor, right: rightAnchor, paddingTop: 4, height: 0.75) addSubview(actionButton) actionButton.anchor(left: leftAnchor, bottom: safeAreaLayoutGuide.bottomAnchor, right: rightAnchor, paddingLeft: 12, paddingBottom: 12, paddingRight: 12, height: 50) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Selectors @objc func actionButtonPressed() { switch buttonAction { case .requestRide: delegate?.uploadTrip(self) case .cancel: delegate?.cancelTrip() case .getDirections: print("DEBUG: Handle get directions..") case .pickup: delegate?.pickupPassenger() case .dropoff: delegate?.dropOffPassenger() } } // MARK: - Helpers private func configureUI(withConfig config: RideActionViewConfiguration) { switch config { case .requestRide: buttonAction = .requestRide actionButton.setTitle(buttonAction.description, for: .normal) case .tripAccepted: guard let user = user else { return } if user.accountType == .passenger { titleLabel.text = "En Route To Passenger" buttonAction = .getDirections actionButton.setTitle(buttonAction.description, for: .normal) } else { buttonAction = .cancel actionButton.setTitle(buttonAction.description, for: .normal) titleLabel.text = "Driver En Route" } infoViewLabel.text = String(user.fullname.first ?? "X") uberInfoLabel.text = user.fullname case .driverArrived: guard let user = user else { return } if user.accountType == .driver { titleLabel.text = "Driver Has Arrived" addressLabel.text = "Please meet driver at pickup location" } case .pickupPassenger: titleLabel.text = "Arrived At Passenger Location" buttonAction = .pickup actionButton.setTitle(buttonAction.description, for: .normal) case .tripInProgress: guard let user = user else { return } if user.accountType == .driver { actionButton.setTitle("TRIP IN PROGRESS", for: .normal) actionButton.isEnabled = false } else { buttonAction = .getDirections actionButton.setTitle(buttonAction.description, for: .normal) } titleLabel.text = "En Route To Destination" case .endTrip: guard let user = user else { return } if user.accountType == .driver { actionButton.setTitle("ARRIVED AT DESTINATION", for: .normal) actionButton.isEnabled = false } else { buttonAction = .dropoff actionButton .setTitle(buttonAction.description, for: .normal) } titleLabel.text = "Arrived To Destination" } } }
30.023346
91
0.560524
20704ed5b055f5cae7c5e9150cc4758fab5e1097
7,048
// // TwoStepVerificationResetController.swift // Telegram // // Created by keepcoder on 18/10/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TelegramCoreMac import SwiftSignalKitMac import TGUIKit private func twoStepVerificationResetControllerEntries(state: TwoStepVerificationResetControllerState, emailPattern: String) -> [TwoStepVerificationResetEntry] { var entries: [TwoStepVerificationResetEntry] = [] var sectionId:Int32 = 0 entries.append(.section(sectionId)) sectionId += 1 entries.append(.codeEntry(sectionId : sectionId, state.codeText)) entries.append(.codeInfo(sectionId : sectionId, tr(L10n.twoStepAuthRecoveryCodeHelp) + "\n\n[\(tr(L10n.twoStepAuthRecoveryEmailUnavailable(emailPattern)))]()")) return entries } fileprivate func prepareTransition(left:[AppearanceWrapperEntry<TwoStepVerificationResetEntry>], right: [AppearanceWrapperEntry<TwoStepVerificationResetEntry>], initialSize:NSSize, arguments:TwoStepVerificationResetControllerArguments) -> TableUpdateTransition { let (removed, inserted, updated) = proccessEntriesWithoutReverse(left, right: right) { entry -> TableRowItem in return entry.entry.item(arguments, initialSize: initialSize) } return TableUpdateTransition(deleted: removed, inserted: inserted, updated: updated, animated: true) } class TwoStepVerificationResetController : TableViewController { fileprivate let emailPattern: String fileprivate let result: Promise<Bool> fileprivate let disposable = MetaDisposable() fileprivate var nextAction:(()->Void)? init(account: Account, emailPattern: String, result: Promise<Bool>) { self.emailPattern = emailPattern self.result = result super.init(account) } override var defaultBarTitle: String { return tr(L10n.twoStepAuthRecoveryTitle) } deinit { disposable.dispose() } override func viewDidLoad() { let account = self.account let result = self.result let emailPattern = self.emailPattern let initialSize = self.atomicSize let initialState = TwoStepVerificationResetControllerState(codeText: "", checking: false) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((TwoStepVerificationResetControllerState) -> TwoStepVerificationResetControllerState) -> Void = { f in statePromise.set(stateValue.modify { f($0) }) } let actionsDisposable = DisposableSet() let resetPasswordDisposable = MetaDisposable() actionsDisposable.add(resetPasswordDisposable) let checkCode: () -> Void = { [weak self] in if self?.rightBarView.isEnabled == false { NSSound.beep() return } var code: String? updateState { state in if state.checking || state.codeText.isEmpty { return state } else { code = state.codeText return state.withUpdatedChecking(true) } } if let code = code { resetPasswordDisposable.set((recoverTwoStepVerificationPassword(network: account.network, code: code) |> deliverOnMainQueue).start(error: { error in updateState { return $0.withUpdatedChecking(false) } let alertText: String switch error { case .generic: alertText = tr(L10n.twoStepAuthGenericError) case .invalidCode: alertText = tr(L10n.twoStepAuthRecoveryCodeInvalid) case .codeExpired: alertText = tr(L10n.twoStepAuthRecoveryCodeExpired) case .limitExceeded: alertText = tr(L10n.twoStepAuthFloodError) } alert(for: mainWindow, info: alertText) }, completed: { updateState { return $0.withUpdatedChecking(false) } result.set(.single(true)) })) } } let arguments = TwoStepVerificationResetControllerArguments(updateEntryText: { updatedText in updateState { $0.withUpdatedCodeText(updatedText) } }, next: { checkCode() }, openEmailInaccessible: { alert(for: mainWindow, info: tr(L10n.twoStepAuthErrorHaventEmail)) }) self.nextAction = checkCode let previous: Atomic<[AppearanceWrapperEntry<TwoStepVerificationResetEntry>]> = Atomic(value: []) let signal = combineLatest(appearanceSignal, statePromise.get()) |> deliverOnMainQueue |> map { appearance, state -> (TableUpdateTransition, Bool) in var nextEnabled = true if state.checking { nextEnabled = false } else { if state.codeText.isEmpty { nextEnabled = false } } let entries = twoStepVerificationResetControllerEntries(state: state, emailPattern: emailPattern).map{AppearanceWrapperEntry(entry: $0, appearance: appearance)} return (prepareTransition(left: previous.swap(entries), right: entries, initialSize: initialSize.modify{$0}, arguments: arguments), nextEnabled) } |> afterDisposed { actionsDisposable.dispose() } disposable.set(signal.start(next: { [weak self] transition, enabled in self?.genericView.merge(with: transition) self?.readyOnce() self?.rightBarView.isEnabled = enabled })) } override func getRightBarViewOnce() -> BarView { let button = TextButtonBarView(controller: self, text: tr(L10n.composeNext)) button.set(handler: { [weak self] _ in self?.nextAction?() }, for: .Click) return button } override func returnKeyAction() -> KeyHandlerResult { nextAction?() return .invoked } override func firstResponder() -> NSResponder? { if genericView.count > 1 { return (genericView.viewNecessary(at: 1) as? GeneralInputRowView)?.firstResponder } return nil } override func backKeyAction() -> KeyHandlerResult { return .invokeNext } override func becomeFirstResponder() -> Bool? { return true } override var removeAfterDisapper: Bool { return true } }
35.417085
262
0.593927
295de88c438f9ad6f92f6e06a3a67383a6d2ca8b
2,947
// // RightThirdCalculation.swift // Rectangle // // Created by Ryan Hanson on 7/26/19. // Copyright © 2019 Ryan Hanson. All rights reserved. // import Foundation class LastThirdCalculation: WindowCalculation, RepeatedExecutionsCalculation { private var firstThirdCalculation: FirstThirdCalculation? private var centerThirdCalculation: CenterThirdCalculation? init(repeatable: Bool = true) { if repeatable && Defaults.subsequentExecutionMode.value != .none { firstThirdCalculation = FirstThirdCalculation(repeatable: false) centerThirdCalculation = CenterThirdCalculation() } } func calculateRect(_ windowRect: CGRect, lastAction: RectangleAction?, visibleFrameOfScreen: CGRect, action: WindowAction) -> CGRect? { if Defaults.subsequentExecutionMode.value == .none || lastAction == nil { return calculateFirstRect(windowRect, lastAction: lastAction, visibleFrameOfScreen: visibleFrameOfScreen, action: action) } return calculateRepeatedRect(windowRect, lastAction: lastAction, visibleFrameOfScreen: visibleFrameOfScreen, action: action) } func calculateFirstRect(_ windowRect: CGRect, lastAction: RectangleAction?, visibleFrameOfScreen: CGRect, action: WindowAction) -> CGRect { return isLandscape(visibleFrameOfScreen) ? rightThird(visibleFrameOfScreen) : bottomThird(visibleFrameOfScreen) } func calculateSecondRect(_ windowRect: CGRect, lastAction: RectangleAction?, visibleFrameOfScreen: CGRect, action: WindowAction) -> CGRect { return centerThirdCalculation?.calculateRect(windowRect, lastAction: lastAction, visibleFrameOfScreen: visibleFrameOfScreen, action: action) ?? calculateFirstRect(windowRect, lastAction: lastAction, visibleFrameOfScreen: visibleFrameOfScreen, action: action) } func calculateThirdRect(_ windowRect: CGRect, lastAction: RectangleAction?, visibleFrameOfScreen: CGRect, action: WindowAction) -> CGRect { return firstThirdCalculation?.calculateRect(windowRect, lastAction: lastAction, visibleFrameOfScreen: visibleFrameOfScreen, action: action) ?? calculateFirstRect(windowRect, lastAction: lastAction, visibleFrameOfScreen: visibleFrameOfScreen, action: action) } private func rightThird(_ visibleFrameOfScreen: CGRect) -> CGRect { var oneThirdRect = visibleFrameOfScreen oneThirdRect.size.width = floor(visibleFrameOfScreen.width / 3.0) oneThirdRect.origin.x = visibleFrameOfScreen.origin.x + visibleFrameOfScreen.width - oneThirdRect.width return oneThirdRect } private func bottomThird(_ visibleFrameOfScreen: CGRect) -> CGRect { var oneThirdRect = visibleFrameOfScreen oneThirdRect.size.height = floor(visibleFrameOfScreen.height / 3.0) return oneThirdRect } }
45.338462
148
0.727859
0188eda7ce8515c002e6303000041394396e1018
4,459
// // Stash.swift // Stash // // import Foundation import FileKit import SwiftyJSON class Stash { struct Paths { static let scenes = Path("~/.stash/scenes", expandingTilde: true) static let performers = Path("~/.stash/performers", expandingTilde: true) static let mappings = Path("~/.stash/mappings.json", expandingTilde: true) } static func initialize() { do { if !Paths.scenes.exists { try Paths.scenes.createDirectory() } if !Paths.performers.exists { try Paths.performers.createDirectory() } } catch { fatalError("Failed to create directories!") } } static func addPerformer(imageUrl url: URL) { guard let path = Path(url: url) else { return } let checksum = path.calculateChecksum() let performerPath = Paths.performers + "\(checksum).\(path.pathExtension)" do { try path.copyFile(to: performerPath) if Database.shared.performer(fromChecksum: checksum) == nil { let performer = Performer(context: Database.shared.viewContext) performer.checksum = checksum performer.name = path.fileName Database.shared.saveContext() } } catch { debugPrint("Error adding performer \(error)") } } struct Images { static func performer(withChecksum checksum: String) -> Image? { let path = Paths.performers + "\(checksum).jpg" do { return try ImageFile(path: path).read() } catch { return nil } } } struct Json { static func scene(withChecksum checksum: String) -> JSON? { do { let file = DataFile(path: Paths.scenes + "\(checksum).json") if !file.exists { return nil } let data = try file.read() return JSON(data: data) } catch { return nil } } static func saveScene(checksum: String, json: JSON) { do { let file = DataFile(path: Paths.scenes + "\(checksum).json") createIfNeeded(file) try file.write(json.rawData(options: .prettyPrinted), options: .atomic) debugPrint("Saved scene json \(checksum).json") } catch { } } static func performer(withChecksum checksum: String) -> JSON? { do { let file = DataFile(path: Paths.performers + "\(checksum).json") if !file.exists { return nil } let data = try file.read() return JSON(data: data) } catch { return nil } } static func savePerformer(checksum: String, json: JSON) { do { let file = DataFile(path: Paths.performers + "\(checksum).json") createIfNeeded(file) try file.write(json.rawData(options: .prettyPrinted), options: .atomic) debugPrint("Saved performer json \(checksum).json") } catch { } } static func mappings() -> JSON? { do { let file = DataFile(path: Paths.mappings) if !file.exists { return nil } let data = try file.read() return JSON(data: data) } catch { return nil } } static func saveMappings(json: JSON) { do { let file = DataFile(path: Paths.mappings) createIfNeeded(file) try file.write(json.rawData(options: .prettyPrinted), options: .atomic) debugPrint("Saved mappings file") } catch { debugPrint("Error saving mappings file \(error)") } } private static func createIfNeeded(_ file: DataFile) { do { if !file.exists { try file.create() debugPrint("Created json file \(file.name)") } } catch { print("Failed to create file") } } } }
32.079137
87
0.486432
18c37df459122203958c6a2cca89d4b65546f5a1
1,919
// The MIT License (MIT) // Copyright © 2017 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 extension SPPermissionStyle { enum DefaultColors { static let white = UIColor.white static let black = UIColor.black static let blue = UIColor.init(red: 0/255, green: 118/255, blue: 255/255, alpha: 1) static let gray = UIColor.init(red: 142/255, green: 142/255, blue: 147/255, alpha: 1) static let lightGray = UIColor.init(red: 240/255, green: 241/255, blue: 246/255, alpha: 1) static let darkIcon = UIColor.init(red: 0/255, green: 122/255, blue: 255/255, alpha: 1) static let mediumIcon = UIColor.init(red: 122/255, green: 169/255, blue: 248/255, alpha: 1) static let lightIcon = UIColor.init(red: 196/255, green: 216/255, blue: 251/255, alpha: 1) } }
49.205128
99
0.711829
18084be37ddb2a25eb092035f1d42e4ceed514b4
119
import XCTest @testable import swift_fp_animationsTests XCTMain([ testCase(swift_fp_animationsTests.allTests), ])
17
48
0.815126
629cead87c1988c6d9ca0b85fc9bdf440766618d
387
// // Problem_165Tests.swift // Problem 165Tests // // Created by sebastien FOCK CHOW THO on 2019-11-06. // Copyright © 2019 sebastien FOCK CHOW THO. All rights reserved. // import XCTest @testable import Problem_165 class Problem_165Tests: XCTestCase { func test_example() { XCTAssert([3, 4, 9, 6, 1].mapToTotalSmallerElementToTheRight() == [1, 1, 2, 1, 0]) } }
20.368421
90
0.677003
1a323e12ceb9725fec657a1c229434c3837e0f0e
1,976
// // ViewController+SearchBar.swift // MapDraw // // Created by Bobby Westman on 6/17/19. // Copyright © 2019 Bobby Westman. All rights reserved. // import Foundation import UIKit import MapKit extension ViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard let text = searchBar.text, !text.isEmpty else { searchResults = [] return } completer.queryFragment = text } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard searchResults.count > 0 else { return } searchBar.endEditing(true) let completion = searchResults[0] let searchRequest = MKLocalSearch.Request(completion: completion) let search = MKLocalSearch(request: searchRequest) search.start { [weak self] (response, error) in guard let self = self else { return } if let coordinate = response?.mapItems[0].placemark.coordinate { MapHelper.updateMap(self.map, location: coordinate) self.searchBar.text = self.searchResults[0].title self.searchResults = [] } } } } extension ViewController: MKLocalSearchCompleterDelegate { func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) { // there is a delay for showing results, so if we clear text in search bar, results may still show // only display results if there is still text in the search bar guard let text = searchBar.text, !text.isEmpty else { searchResults = [] return } searchResults = completer.results } } extension ViewController { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { searchBar.endEditing(true) guard searchResults.count > 0 else { return } searchResults = [] } }
31.870968
106
0.63664
e28c5e91ee59b6bd5678e3a2348b938d338fa1b0
8,445
// Copyright SIX DAY LLC. All rights reserved. import Foundation import Eureka open class SliderTextFieldCell: Cell<Float>, CellType, UITextFieldDelegate { private var awakeFromNibCalled = false @IBOutlet open weak var titleLabel: UILabel! @IBOutlet open weak var valueLabel: UILabel! @IBOutlet open weak var slider: UISlider! lazy var textField: UITextField = { let textField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: .editingChanged) textField.keyboardType = .numberPad textField.delegate = self textField.returnKeyType = .done textField.textAlignment = .right textField.layer.cornerRadius = 5 textField.layer.borderColor = Colors.lightGray.cgColor textField.layer.borderWidth = 0.3 textField.rightViewMode = .always textField.rightView = UIView.spacerWidth(5) return textField }() open var formatter: NumberFormatter? public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) // swiftlint:disable all NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: nil) { [weak self] _ in guard let me = self else { return } if me.shouldShowTitle { me.titleLabel = me.textLabel me.valueLabel = me.detailTextLabel me.addConstraints() } } // swiftlint:enable all } deinit { guard !awakeFromNibCalled else { return } NotificationCenter.default.removeObserver(self, name: UIContentSizeCategory.didChangeNotification, object: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) awakeFromNibCalled = true } open override func setup() { super.setup() if !awakeFromNibCalled { // title let title = textLabel textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal) titleLabel = title // let value = detailTextLabel // value?.translatesAutoresizingMaskIntoConstraints = false // value?.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal) // valueLabel = value detailTextLabel?.isHidden = true let slider = UISlider() slider.translatesAutoresizingMaskIntoConstraints = false slider.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal) self.slider = slider if shouldShowTitle { contentView.addSubview(titleLabel) //contentView.addSubview(valueLabel!) contentView.addSubview(textField) } contentView.addSubview(slider) addConstraints() } textField.leftView = .spacerWidth(16) textField.leftViewMode = .always textField.rightView = .spacerWidth(16) textField.rightViewMode = .always textField.font = Fonts.regular(size: ScreenChecker().isNarrowScreen ? 10: 13) textField.borderStyle = .none textField.backgroundColor = .white textField.layer.borderWidth = DataEntry.Metric.borderThickness textField.backgroundColor = DataEntry.Color.searchTextFieldBackground textField.layer.borderColor = UIColor.clear.cgColor textField.cornerRadius = DataEntry.Metric.cornerRadius selectionStyle = .none slider.minimumValue = sliderRow.minimumValue slider.maximumValue = sliderRow.maximumValue slider.addTarget(self, action: #selector(SliderTextFieldCell.valueChanged), for: .valueChanged) } open override func update() { super.update() titleLabel.text = row.title //valueLabel.text = row.displayValueFor?(row.value) //valueLabel.isHidden = !shouldShowTitle && !awakeFromNibCalled titleLabel.isHidden = textField.isHidden slider.value = row.value ?? 0.0 slider.isEnabled = !row.isDisabled textField.text = row.displayValueFor?(row.value) } func addConstraints() { guard !awakeFromNibCalled else { return } textField.heightAnchor.constraint(equalToConstant: 30).isActive = true textField.widthAnchor.constraint(equalToConstant: 140).isActive = true let views: [String: Any] = ["titleLabel": titleLabel, "textField": textField, "slider": slider] let metrics = ["vPadding": 12, "spacing": 12.0] if shouldShowTitle { contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[textField]-|", options: .alignAllLastBaseline, metrics: metrics, views: views)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPadding-[titleLabel]-spacing-[slider]-vPadding-|", options: .alignAllLeft, metrics: metrics, views: views)) } else { contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPadding-[slider]-vPadding-|", options: .alignAllLeft, metrics: metrics, views: views)) } contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[slider]-|", options: .alignAllLastBaseline, metrics: metrics, views: views)) } @objc func valueChanged() { let roundedValue: Float let steps = Float(sliderRow.steps) if steps > 0 { let stepValue = round((slider.value - slider.minimumValue) / (slider.maximumValue - slider.minimumValue) * steps) let stepAmount = (slider.maximumValue - slider.minimumValue) / steps roundedValue = stepValue * stepAmount + slider.minimumValue } else { roundedValue = slider.value } row.value = roundedValue row.updateCell() textField.text = "\(Int(roundedValue))" } var shouldShowTitle: Bool { return row?.title?.isEmpty == false } private var sliderRow: SliderTextFieldRow { return row as! SliderTextFieldRow } @objc func textFieldDidChange(textField: UITextField) { let value = Float(textField.text ?? "0") ?? sliderRow.minimumValue let minValue = min(value, sliderRow.minimumValue) let maxValue = max(value, sliderRow.maximumValue) sliderRow.minimumValue = minValue sliderRow.maximumValue = maxValue slider.maximumValue = minValue slider.maximumValue = maxValue row.value = value slider.value = value } open func textFieldDidEndEditing(_ textField: UITextField) { textField.layer.borderColor = UIColor.clear.cgColor textField.backgroundColor = DataEntry.Color.searchTextFieldBackground textField.dropShadow(color: .clear, radius: DataEntry.Metric.shadowRadius) } open func textFieldDidBeginEditing(_ textField: UITextField) { textField.backgroundColor = Colors.appWhite textField.layer.borderColor = DataEntry.Color.textFieldShadowWhileEditing.cgColor textField.dropShadow(color: DataEntry.Color.textFieldShadowWhileEditing, radius: DataEntry.Metric.shadowRadius) } @objc public func textFieldShouldReturn(_ textField: UITextField) -> Bool { return true } open override func cellCanBecomeFirstResponder() -> Bool { return !row.isDisabled && textField.canBecomeFirstResponder == true } open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool { return textField.becomeFirstResponder() } open override func cellResignFirstResponder() -> Bool { return textField.resignFirstResponder() } } /// A row that displays a UISlider. If there is a title set then the title and value will appear above the UISlider. public final class SliderTextFieldRow: Row<SliderTextFieldCell>, RowType { public var minimumValue: Float = 0.0 public var maximumValue: Float = 10.0 public var steps: UInt = 20 required public init(tag: String?) { super.init(tag: tag) } }
39.462617
201
0.670574
566237cacd89cad6bdcc14e6b6ab83995046ae84
858
import Substate extension Action { @MainActor public static func reject(when condition: @escaping (Self) -> Bool) -> ActionTriggerStep1<Self> { ActionTriggerStep1 { action, _ in AsyncStream { continuation in if let action = action as? Self, condition(action) != true { continuation.yield(action) } continuation.finish() } } } @MainActor public static func reject(when condition: @escaping (Self) -> Bool?) -> ActionTriggerStep1<Self> { ActionTriggerStep1 { action, _ in AsyncStream { continuation in if let action = action as? Self, condition(action) != true { continuation.yield(action) } continuation.finish() } } } }
28.6
113
0.539627
67f42359f2869d674963fbc1e3b6a35386e9e29a
4,412
// RUN: %target-swift-ide-test -dump-importer-lookup-table -source-filename %s -import-objc-header %S/Inputs/swift_name_objc.h > %t.log 2>&1 // RUN: FileCheck %s < %t.log // RUN: %target-swift-ide-test -dump-importer-lookup-table -source-filename %s -import-objc-header %S/Inputs/swift_name_objc.h -enable-omit-needless-words -enable-strip-ns-prefix > %t-omit-needless-words.log 2>&1 // RUN: FileCheck -check-prefix=CHECK-OMIT-NEEDLESS-WORDS %s < %t-omit-needless-words.log // REQUIRES: objc_interop // REQUIRES: OS=macosx // CHECK-LABEL: <<Foundation lookup table>> // CHECK: NSTimeIntervalSince1970: // CHECK: TU: Macro // CHECK: Categories:{{.*}}NSValue(NSValueCreation){{.*}} // CHECK-LABEL: <<ObjectiveC lookup table>> // CHECK-NEXT: Base name -> entry mappings: // CHECK-NOT: lookup table // CHECK: NSObject: // CHECK-NEXT: TU: NSObject // CHECK-NEXT: NSObjectProtocol: // CHECK-NEXT: TU: NSObject // CHECK-LABEL: <<Bridging header lookup table>> // CHECK-NEXT: Base name -> entry mappings: // CHECK-NEXT: CCItem: // CHECK-NEXT: TU: CCItemRef // CHECK-NEXT: CCItemRef: // CHECK-NEXT: TU: CCItemRef // CHECK-NEXT: CFTypeRef: // CHECK-NEXT: TU: CFTypeRef // CHECK-NEXT: NSAccessibility: // CHECK-NEXT: TU: NSAccessibility{{$}} // CHECK-NEXT: NSError: // CHECK-NEXT: TU: NSError // CHECK-NEXT: NSErrorImports: // CHECK-NEXT: TU: NSErrorImports // CHECK-NEXT: SNCollision: // CHECK-NEXT: TU: SNCollision{{$}} // CHECK-NEXT: SNCollisionProtocol: // CHECK-NEXT: TU: SNCollision{{$}} // CHECK-NEXT: SomeClass: // CHECK-NEXT: TU: SNSomeClass // CHECK-NEXT: SomeProtocol: // CHECK-NEXT: TU: SNSomeProtocol // CHECK-NEXT: UIActionSheet: // CHECK-NEXT: TU: UIActionSheet // CHECK-NEXT: __CCItem: // CHECK-NEXT: TU: __CCItem // CHECK-NEXT: __swift: // CHECK-NEXT: TU: __swift // CHECK-NEXT: accessibilityFloat: // CHECK-NEXT: NSAccessibility: -[NSAccessibility accessibilityFloat] // CHECK-NEXT: categoryMethodWith: // CHECK-NEXT: SNSomeClass: -[SNSomeClass categoryMethodWithX:y:], -[SNSomeClass categoryMethodWithX:y:z:] // CHECK-NEXT: doubleProperty: // CHECK-NEXT: SNSomeClass: SNSomeClass.doubleProperty // CHECK-NEXT: extensionMethodWith: // CHECK-NEXT: SNSomeClass: -[SNSomeClass extensionMethodWithX:y:] // CHECK-NEXT: floatProperty: // CHECK-NEXT: SNSomeClass: SNSomeClass.floatProperty // CHECK-NEXT: init: // CHECK-NEXT: SNSomeClass: -[SNSomeClass initWithFloat:], -[SNSomeClass initWithDefault], +[SNSomeClass someClassWithDouble:], +[SNSomeClass someClassWithTry:], +[SNSomeClass buildWithUnsignedChar:] // CHECK-NEXT: UIActionSheet: -[UIActionSheet initWithTitle:delegate:cancelButtonTitle:destructiveButtonTitle:otherButtonTitles:] // CHECK-NEXT: NSErrorImports: -[NSErrorImports initAndReturnError:], -[NSErrorImports initWithFloat:error:] // CHECK-NEXT: instanceMethodWith: // CHECK-NEXT: SNSomeClass: -[SNSomeClass instanceMethodWithX:Y:Z:] // CHECK-NEXT: method: // CHECK-NEXT: NSErrorImports: -[NSErrorImports methodAndReturnError:], -[NSErrorImports methodWithFloat:error:] // CHECK-NEXT: objectAtIndexedSubscript: // CHECK-NEXT: SNSomeClass: -[SNSomeClass objectAtIndexedSubscript:] // CHECK-NEXT: optSetter: // CHECK-NEXT: SNCollision: SNCollision.optSetter // CHECK-NEXT: protoInstanceMethodWith: // CHECK-NEXT: SNSomeProtocol: -[SNSomeProtocol protoInstanceMethodWithX:y:] // CHECK-NEXT: reqSetter: // CHECK-NEXT: SNCollision: SNCollision.reqSetter // CHECK-NEXT: setAccessibilityFloat: // CHECK-NEXT: NSAccessibility: -[NSAccessibility setAccessibilityFloat:] // CHECK-NEXT: subscript: // CHECK-NEXT: SNSomeClass: -[SNSomeClass objectAtIndexedSubscript:] // CHECK: Categories: SNSomeClass(), SNSomeClass(Category1) // CHECK-OMIT-NEEDLESS-WORDS-LABEL: <<Foundation lookup table>> // CHECK-OMIT-NEEDLESS-WORDS: timeIntervalSince1970: // CHECK-OMIT-NEEDLESS-WORDS: TU: Macro // CHECK-OMIT-NEEDLESS-WORDS: <<ObjectiveC lookup table>> // CHECK-OMIT-NEEDLESS-WORDS-NOT: lookup table // CHECK-OMIT-NEEDLESS-WORDS: responds: // CHECK-OMIT-NEEDLESS-WORDS-NEXT: -[NSObject respondsToSelector:] // CHECK-OMIT-NEEDLESS-WORDS: Base name -> entry mappings: // CHECK-OMIT-NEEDLESS-WORDS: method: // CHECK-OMIT-NEEDLESS-WORDS: NSErrorImports: {{.*}}-[NSErrorImports methodWithFloat:error:]
45.958333
212
0.713055
e9252df8093462e76aaf77ab72300f18aa3079bb
5,576
import UIKit final class RepoSettingsViewController: UITableViewController, UITextFieldDelegate { var repo: Repo? private var allPrsIndex = -1 private var allIssuesIndex = -1 private var allHidingIndex = -1 @IBOutlet weak var groupField: UITextField! @IBOutlet weak var repoNameTitle: UILabel! private var settingsChangedTimer: PopTimer! override func viewDidLoad() { super.viewDidLoad() navigationItem.largeTitleDisplayMode = .automatic if repo == nil { repoNameTitle.text = "All Repositories (You don't need to pick values for each setting below, you can set only a specific setting if you prefer)" groupField.isHidden = true } else { repoNameTitle.text = repo?.fullName groupField.text = repo?.groupLabel } settingsChangedTimer = PopTimer(timeInterval: 1.0) { DataManager.postProcessAllItems() } } override func viewDidLayoutSubviews() { if let s = tableView.tableHeaderView?.systemLayoutSizeFitting(CGSize(width: tableView.bounds.size.width, height: 500)) { tableView.tableHeaderView?.frame = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: s.height) } super.viewDidLayoutSubviews() } override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 2 { return RepoHidingPolicy.labels.count } return RepoDisplayPolicy.labels.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! if repo == nil { switch indexPath.section { case 0: cell.accessoryType = (allPrsIndex==indexPath.row) ? .checkmark : .none cell.textLabel?.text = RepoDisplayPolicy.labels[indexPath.row] cell.textLabel?.textColor = RepoDisplayPolicy.colors[indexPath.row] case 1: cell.accessoryType = (allIssuesIndex==indexPath.row) ? .checkmark : .none cell.textLabel?.text = RepoDisplayPolicy.labels[indexPath.row] cell.textLabel?.textColor = RepoDisplayPolicy.colors[indexPath.row] case 2: cell.accessoryType = (allHidingIndex==indexPath.row) ? .checkmark : .none cell.textLabel?.text = RepoHidingPolicy.labels[indexPath.row] cell.textLabel?.textColor = RepoHidingPolicy.colors[indexPath.row] default: break } } else { switch indexPath.section { case 0: cell.accessoryType = (Int(repo?.displayPolicyForPrs ?? 0)==indexPath.row) ? .checkmark : .none cell.textLabel?.text = RepoDisplayPolicy.labels[indexPath.row] cell.textLabel?.textColor = RepoDisplayPolicy.colors[indexPath.row] case 1: cell.accessoryType = (Int(repo?.displayPolicyForIssues ?? 0)==indexPath.row) ? .checkmark : .none cell.textLabel?.text = RepoDisplayPolicy.labels[indexPath.row] cell.textLabel?.textColor = RepoDisplayPolicy.colors[indexPath.row] case 2: cell.accessoryType = (Int(repo?.itemHidingPolicy ?? 0)==indexPath.row) ? .checkmark : .none cell.textLabel?.text = RepoHidingPolicy.labels[indexPath.row] cell.textLabel?.textColor = RepoHidingPolicy.colors[indexPath.row] default: break } } cell.selectionStyle = cell.accessoryType == .checkmark ? .none : .default return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Pull Request Sections" case 1: return "Issue Sections" case 2: return "Author Based Hiding" default: return nil } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if repo == nil { let repos = Repo.allItems(of: Repo.self, in: DataManager.main) if indexPath.section == 0 { allPrsIndex = indexPath.row for r in repos { r.displayPolicyForPrs = Int64(allPrsIndex) if allPrsIndex != RepoDisplayPolicy.hide.intValue { r.resetSyncState() } } } else if indexPath.section == 1 { allIssuesIndex = indexPath.row for r in repos { r.displayPolicyForIssues = Int64(allIssuesIndex) if allIssuesIndex != RepoDisplayPolicy.hide.intValue { r.resetSyncState() } } } else { allHidingIndex = indexPath.row for r in repos { r.itemHidingPolicy = Int64(allHidingIndex) } } } else if indexPath.section == 0 { repo?.displayPolicyForPrs = Int64(indexPath.row) if indexPath.row != RepoDisplayPolicy.hide.intValue { repo?.resetSyncState() } } else if indexPath.section == 1 { repo?.displayPolicyForIssues = Int64(indexPath.row) if indexPath.row != RepoDisplayPolicy.hide.intValue { repo?.resetSyncState() } } else { repo?.itemHidingPolicy = Int64(indexPath.row) } tableView.reloadData() commit() } private func commit() { DataManager.saveDB() preferencesDirty = true settingsChangedTimer.push() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) let newText = (groupField.text?.isEmpty ?? true) ? nil : groupField.text if let r = repo, r.groupLabel != newText { r.groupLabel = newText commit() atNextEvent { popupManager.masterController.updateStatus(becauseOfChanges: true) } } if settingsChangedTimer.isRunning { settingsChangedTimer.abort() DataManager.postProcessAllItems() } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string == "\n" { textField.resignFirstResponder() return false } return true } }
32.8
148
0.721844
ebab659c78ae41832fba3058caae56aada3befc2
2,266
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency %import-libdispatch -parse-as-library) // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // UNSUPPORTED: use_os_stdlib import Dispatch enum HomeworkError: Error, Equatable { case dogAteIt(String) } func formGreeting(name: String) async -> String { return "Hello \(name) from async world" } func testSimple( name: String, dogName: String, shouldThrow: Bool, doSuspend: Bool ) async { print("Testing name: \(name), dog: \(dogName), shouldThrow: \(shouldThrow) doSuspend: \(doSuspend)") var completed = false let taskHandle: Task.Handle<String, Error> = Task.runDetached { let greeting = await formGreeting(name: name) // If the intent is to test suspending, wait a bit so the second task // can complete. if doSuspend { print("- Future sleeping") await Task.sleep(1_000_000_000) } if (shouldThrow) { print("- Future throwing") throw HomeworkError.dogAteIt(dogName + " the dog") } print("- Future returning normally") return greeting + "!" } // If the intent is not to test suspending, wait a bit so the first task // can complete. if !doSuspend { print("+ Reader sleeping") await Task.sleep(1_000_000_000) } do { print("+ Reader waiting for the result") let result = try await taskHandle.get() completed = true print("+ Normal return: \(result)") assert(result == "Hello \(name) from async world!") } catch HomeworkError.dogAteIt(let badDog) { completed = true print("+ Error return: HomeworkError.dogAteIt(\(badDog))") assert(badDog == dogName + " the dog") } catch { fatalError("Caught a different exception?") } assert(completed) print("Finished test") } @main struct Main { static func main() async { await testSimple(name: "Ted", dogName: "Hazel", shouldThrow: false, doSuspend: false) await testSimple(name: "Ted", dogName: "Hazel", shouldThrow: true, doSuspend: false) await testSimple(name: "Ted", dogName: "Hazel", shouldThrow: false, doSuspend: true) await testSimple(name: "Ted", dogName: "Hazel", shouldThrow: true, doSuspend: true) print("Done") } }
27.634146
116
0.675199
4b8c38060b582453cf930c9290250fd350b5c0d3
963
// // CustomOverlayView.swift // Koloda // // Created by Eugene Andreyev on 7/27/15. // Copyright (c) 2015 CocoaPods. All rights reserved. // import UIKit import Koloda private let overlayRightImageName = "overlay_like" private let overlayLeftImageName = "overlay_skip" class CustomOverlayView: OverlayView { @IBOutlet lazy var overlayImageView: UIImageView! = { [unowned self] in var imageView = UIImageView() self.addSubview(imageView) return imageView }() override var overlayState: SwipeResultDirection? { didSet { switch overlayState { case .left? : overlayImageView.image = UIImage(named: overlayLeftImageName) case .right? : overlayImageView.image = UIImage(named: overlayRightImageName) default: overlayImageView.image = nil } } } }
23.487805
78
0.599169
e99163788debf732c94c086bb632928eb3759ac9
373
import Core public struct LookupRequest: GoogleCloudModel { public init(keys: [Key]? = nil, readOptions: ReadOptions? = nil) { self.keys = keys self.readOptions = readOptions } /// Keys of entities to look up. public let keys: [Key]? /// The options for this lookup request. public let readOptions: ReadOptions? }
24.866667
51
0.624665
0ecaff7062ca74daa9a8653bddea99cd876ae658
2,350
// // SceneDelegate.swift // swapi // // Created by Benoit Pasquier on 19/2/20. // Copyright © 2020 Benoit Pasquier. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.518519
147
0.713617
725175208b19f49bd092c973e39e10bfe3249615
648
// // MsgOutGoingCell.swift // Up+ // // Created by Dreamup on 3/9/17. // Copyright © 2017 Dreamup. All rights reserved. // import UIKit class MsgOutGoingCell: UITableViewCell { @IBOutlet weak var bubbleView: UIView! @IBOutlet weak var messageLb: UILabel! override func awakeFromNib() { super.awakeFromNib() bubbleView.layer.cornerRadius = 10 bubbleView.clipsToBounds = true } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
19.058824
65
0.631173
6a30949f77e2d061d5d85a49559227ec6e6b53ed
983
// // RNCallKitLearnTests.swift // RNCallKitLearnTests // // Created by 婉卿容若 on 16/9/18. // Copyright © 2016年 婉卿容若. All rights reserved. // import XCTest @testable import RNCallKitLearn class RNCallKitLearnTests: 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. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.567568
111
0.638861
917986f51d35b7905b848acb79ef590ab88a302b
1,310
// // iOSImageDetectionExampleUITests.swift // iOSImageDetectionExampleUITests // // Created by Christopher Williams on 11/3/15. // Copyright © 2015 Christopher Williams. All rights reserved. // import XCTest class iOSImageDetectionExampleUITests: 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. } }
35.405405
182
0.679389
e517e764afd16d45ec1ce428031bedde6065f648
6,658
// Notes // // Created by farshad on 9/4/18. // Copyright © 2018 FarshadJahanmanesh. All rights reserved. // import CoreData import RxSwift ///storage errors enum StorageError: Error { case NoteNotCreated } final class Storage: NSObject { //RX Variables //keep a reference to our current and editing note fileprivate var selectedNote: Variable<NoteProtocol?> = Variable(nil) //a subject to subscribe for note changes fileprivate var allNotes: Variable<[NoteProtocol]> = Variable([NoteProtocol]()) //a subject of string which is editing fileprivate var editingContent: Variable<String> = Variable("") //CoreData Variables private let persistentContainer: NSPersistentContainer fileprivate let readContext: NSManagedObjectContext fileprivate let writeContext: NSManagedObjectContext override init() { //managed object name let momdName = "Notes" guard let modelURL = Bundle(for: type(of: self)).url(forResource: momdName, withExtension:"momd") else { fatalError("Error loading model from bundle") } //managed object model guard let mom = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("Error initializing mom from: \(modelURL)") } //initializing our container persistentContainer = NSPersistentContainer(name: momdName, managedObjectModel: mom) //load date persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error { fatalError("Unresolved error \(error), \(storeDescription)") } }) self.readContext = persistentContainer.viewContext self.readContext.automaticallyMergesChangesFromParent = true self.writeContext = persistentContainer.newBackgroundContext() super.init() } fileprivate func fetchNotes() { let reading = self.readContext do { let request: NSFetchRequest<NoteObject> = NoteObject.fetchRequest() let objects = try reading.fetch(request) //fetch items from storage and sort them based on editing date (recent/top) let notes: [NoteProtocol] = objects.compactMap({ (object) -> NoteProtocol? in return object }).sorted(by: { (p1, p2) -> Bool in p1.date > p2.date }) DispatchQueue.main.async { self.allNotes.value = notes } } catch { return } } } extension Storage: NoteListUseCase { func create() -> Completable { return Completable.create { [weak self] (completable) -> Disposable in //get writing context guard let writingContext = self?.writeContext else { completable(.error(StorageError.NoteNotCreated)) return Disposables.create{} } //create a new object let item = NSEntityDescription.insertNewObject(forEntityName: "Note", into: writingContext) as! NoteObject item.content = "" do { //update our context try writingContext.save() //notify our subscriptions and dispose this observable DispatchQueue.main.async { self?.allNotes.value.insert(item, at: 0) self?.selectedNote.value = item self?.editingContent.value = item.content ?? "" completable(.completed) } } catch { completable(.error(StorageError.NoteNotCreated)) debugPrint(error) } return Disposables.create{} } } func select(note: NoteProtocol) { //notify our subscription that a note selected selectedNote.value = note editingContent.value = note.text } func notes() -> Observable<[NoteProtocol]> { //fetch notes and create a observale of them fetchNotes() return Observable.of(self.allNotes.asObservable()).merge() } } extension Storage: NoteEditUseCase { func delete() -> Completable { return Completable.create { [weak self] (completable) -> Disposable in guard let noteToDelete = self?.selectedNote.value else { completable(.error(StorageError.NoteNotCreated)) return Disposables.create{} } let noteObjectId = (noteToDelete as! NoteObject).objectID if var allNotes = self?.allNotes.value { var indexOfDeletion: Int? for (index, note) in allNotes.enumerated() { if (note as! NoteObject).objectID == noteObjectId { indexOfDeletion = index break } } if indexOfDeletion != nil { allNotes.remove(at: indexOfDeletion!) DispatchQueue.main.async { self?.allNotes.value = allNotes } } else { completable(.error(StorageError.NoteNotCreated)) return Disposables.create{} } } if let writeNote = self?.writeContext.object(with: noteObjectId) { self?.writeContext.delete(writeNote) do { try self?.writeContext.save() completable(.completed) } catch { completable(.error(StorageError.NoteNotCreated)) } } return Disposables.create{} } } func update(string: String) { editingContent.value = string (selectedNote.value as? NoteObject)?.content = string // if readContext.hasChanges { let readedNoteId = (selectedNote.value as! NoteObject).objectID guard let writeNote = self.writeContext.object(with: readedNoteId) as? NoteObject else { return } writeNote.content = string writeNote.date = Date().timeIntervalSince1970 do { try self.writeContext.save() } catch { debugPrint("couldn't save the note updated content") } // } } var content: Observable<String> { return editingContent.asObservable() } }
36.78453
118
0.562481
e22f3ca69cab67e848643eb0cd13de9dc1258c93
3,149
// // FolderCell.swift // iTorrent // // Created by Daniil Vinogradov on 31.03.2020. // Copyright © 2020  XITRIX. All rights reserved. // import ITorrentFramework import UIKit class FolderCell: ThemedUITableViewCell, UpdatableModel { static let id = "FolderCell" static let nib = UINib(nibName: id, bundle: Bundle.main) @IBOutlet var title: UILabel! @IBOutlet var size: UILabel! @IBOutlet var moreButton: UIButton! @IBOutlet var titleConstraint: NSLayoutConstraint! var titleConstraintValue: CGFloat { isEditing ? 16 : 34 } weak var model: FolderModel! var moreAction: ((FolderModel) -> ())? override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) titleConstraint?.constant = titleConstraintValue UIView.animate(withDuration: animated ? 0.3 : 0) { self.moreButton.alpha = editing ? 0 : 1 self.layoutIfNeeded() } } func setModel(_ model: FolderModel) { self.model = model updateModel() setEditing(isEditing, animated: false) } func updateModel() { title.text = model.name if model.isPreview { size.text = Utils.getSizeText(size: model.size) } else { let percent = Float(model.downloadedSize) / Float(model.size) * 100 size.text = "\(Utils.getSizeText(size: model.downloadedSize)) / \(Utils.getSizeText(size: model.size)) (\(String(format: "%.2f", percent))%)" } } @IBAction func more(_ sender: UIButton) { let controller = ThemedUIAlertController(title: NSLocalizedString("Download content of folder", comment: ""), message: model.name, preferredStyle: .actionSheet) let download = UIAlertAction(title: NSLocalizedString("Download", comment: ""), style: .default) { _ in self.model.files.forEach { $0.priority = .normalPriority } self.moreAction?(self.model) } let notDownload = UIAlertAction(title: NSLocalizedString("Don't Download", comment: ""), style: .destructive) { _ in self.model.files.forEach { file in if file.size != 0, file.downloadedBytes == file.size { file.priority = .normalPriority } else { file.priority = .dontDownload } self.moreAction?(self.model) } } let cancel = UIAlertAction(title: NSLocalizedString("Close", comment: ""), style: .cancel) controller.addAction(download) controller.addAction(notDownload) controller.addAction(cancel) if controller.popoverPresentationController != nil { controller.popoverPresentationController?.sourceView = sender controller.popoverPresentationController?.sourceRect = sender.bounds controller.popoverPresentationController?.permittedArrowDirections = .any } Utils.topViewController?.present(controller, animated: true) } }
35.784091
168
0.616069
b9327e914729b13c9e565bad735ecec590c0ff06
1,189
// // EffectCollectionViewCell.swift // Animatify // // Created by Shubham Singh on 17/06/20. // Copyright © 2020 Shubham Singh. All rights reserved. // import UIKit class EffectCollectionViewCell: UICollectionViewCell { override class func description() -> String { return "EffectCollectionViewCell" } // MARK:- outlets for the viewController @IBOutlet weak var containerView: UIView! @IBOutlet weak var titleLabel: UILabel! var collectionViewHeight: CGFloat = 180 override func awakeFromNib() { super.awakeFromNib() self.containerView.roundCorners(cornerRadius: 12) } // MARK:- functions for the cell func setupCell(effect: Effect){ self.titleLabel.text = effect.title ///add the gradient to the view DispatchQueue.main.asyncAfter(deadline: .now()) { let gradient = CAGradientLayer() gradient.setGradientLayer(color1: effect.gradientColor1,color2: effect.gradientColor2, for: self.containerView, cornerRadius: self.containerView.layer.cornerRadius) self.containerView.layer.addSublayer(gradient) } } }
29
176
0.667788
bbf6287fd0a980f12e54ca1cb5a57f1906a7b389
2,313
// // NativecryptoBalanceViewModel.swift // AlphaWallet // // Created by Vladyslav Shepitko on 02.06.2021. // import Foundation import BigInt struct NativecryptoBalanceViewModel: BalanceBaseViewModel { var isZero: Bool { balance.value.isZero } private let server: RPCServer private let balance: BalanceProtocol private (set) var ticker: CoinTicker? init(server: RPCServer, balance: BalanceProtocol, ticker: CoinTicker?) { self.server = server self.balance = balance self.ticker = ticker } var value: BigInt { balance.value } var amount: Double { return EtherNumberFormatter.plain.string(from: balance.value, units: .ether).doubleValue } var amountString: String { guard !isZero else { return "0.00 \(server.symbol)" } return "\(balance.amountFull) \(server.symbol)" } var currencyAmount: String? { guard let totalAmount = currencyAmountWithoutSymbol else { return nil } return Formatter.usd.string(from: totalAmount) } var currencyAmountWithoutSymbol: Double? { guard let currentRate = cryptoRate(forServer: server) else { return nil } return amount * currentRate.price } var amountFull: String { return balance.amountFull } var amountShort: String { return balance.amountShort } var symbol: String { return server.symbol } } extension BalanceBaseViewModel { func cryptoRate(forServer server: RPCServer) -> Rate? { guard let rate = ticker?.rate else { return nil } let code = mapSymbolToCodeInRates(server) let symbol = server.symbol.lowercased() if let value = rate.rates.first(where: { $0.code == code }) { return value } else if let value = rate.rates.first(where: { $0.code == "gno" }), server == .xDai { return value } else if let value = rate.rates.first(where: { $0.code == symbol }) { return value } else { return nil } } private func mapSymbolToCodeInRates(_ server: RPCServer) -> String { let symbol = server.symbol.lowercased() let mapping = ["xdai": "dai", "aeth": "eth"] return mapping[symbol] ?? symbol } }
26.586207
96
0.622568
1e5461f2ebc6a25e73febabc6e664e427931f617
1,694
// // ViewController.swift // Example-image-in-text // // Created by Rodrigo De Luca on 25/7/15. // Copyright (c) 2015 iOS Makers. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet private weak var label: UILabel! @IBOutlet private weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() label.layer.masksToBounds = true label.layer.cornerRadius = 5 button.layer.masksToBounds = true button.layer.cornerRadius = 5 label.attributedText = generateText(" Like us!", withImageName: "image1") button.setAttributedTitle(generateText(" Cool!", withImageName: "image2"), for: .normal) } func generateText(_ text:String, withImageName image: String) -> NSAttributedString? { /* attach image */ let imageForText = NSTextAttachment() imageForText.image = UIImage(named: image) /* dictionary with attributes */ let textAttributes = [NSForegroundColorAttributeName:UIColor.white, NSFontAttributeName:UIFont.systemFont(ofSize: 15)] /* add attributes to text */ let attributedString = NSMutableAttributedString() attributedString.append(NSAttributedString(attachment: imageForText)) attributedString.append(NSAttributedString(string: text, attributes: textAttributes)) /* set vertical aligment for text */ let range = NSMakeRange(1, text.characters.count) attributedString.addAttribute(NSBaselineOffsetAttributeName, value: 8.0, range: range); return attributedString } }
31.37037
96
0.659976
de1ded5cb152bb4d16f9a4cf461651500d9e9c37
501
// // SemiTransparentLabel.swift // DNA.iOS // // Created by Khachatur Hakobyan on 4/26/19. // Copyright © 2019 Khachatur Hakobyan. All rights reserved. // import UIKit class SemiTransparentLabel: UILabel { init(font: UIFont? = nil) { super.init(frame: .zero) self.font = font self.setupColor() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupColor() } private func setupColor() { self.textColor = UIColor.App.transparentWhite.value } }
17.892857
61
0.694611
b92b2d15fbb56fa76159cb2ef9515238e5506df1
1,489
// swift-tools-version:5.2 import PackageDescription let package = Package( name: "SkateBudapestVapor", platforms: [ .macOS(.v10_15) ], dependencies: [ // 💧 A server-side Swift web framework. .package(url: "https://github.com/vapor/vapor.git", from: "4.48.2"), .package(url: "https://github.com/vapor/fluent.git", from: "4.3.1"), .package(url: "https://github.com/vapor/fluent-postgres-driver.git", from: "2.1.3") ], targets: [ .target( name: "App", dependencies: [ .product(name: "Fluent", package: "fluent"), .product(name: "FluentPostgresDriver", package: "fluent-postgres-driver"), .product(name: "Vapor", package: "vapor") ], swiftSettings: [ // Enable better optimizations when building in Release configuration. Despite the use of // the `.unsafeFlags` construct required by SwiftPM, this flag is recommended for Release // builds. See <https://github.com/swift-server/guides#building-for-production> for details. .unsafeFlags(["-cross-module-optimization"], .when(configuration: .release)) ] ), .target(name: "Run", dependencies: [.target(name: "App")]), .testTarget(name: "AppTests", dependencies: [ .target(name: "App"), .product(name: "XCTVapor", package: "vapor"), ]) ] )
40.243243
108
0.56548
093cab68050f089f8c4f3dd734d2f10cde08e6f0
718
// // YQProgramer.swift // YQNavigationControllerSwift // // Created by 杨雯德 on 16/3/3. // Copyright © 2016年 杨雯德. All rights reserved. // import Foundation import UIKit func HexRGB(rgbValue:Int) ->UIColor{ let r = CGFloat((rgbValue & 0xffffff) >> 16)/255.0 let g = CGFloat((rgbValue & 0xFF00) >> 8)/255.0 let b = CGFloat(rgbValue & 0xFF)/255.0 return UIColor(red: r, green: g, blue: b, alpha: 1) } func HexColor() ->UIColor{ let a:Double = Double(arc4random() % 255) let b:Double = Double(arc4random() % 255) let c:Double = Double(arc4random() % 255) return UIColor(red:CGFloat( a/Double(255.0)), green: CGFloat(b/Double(255.0)), blue: CGFloat(c/Double(255.0)), alpha: 1) }
28.72
124
0.647632
b9033fcacd02ee758d1fea91c0c2137a55ac6f31
7,732
// // BookDetailView.swift // prolificCodeChallenge // // Created by Karen Fuentes on 8/15/18. // Copyright © 2018 Karen Fuentes. All rights reserved. // import UIKit class BookDetailView: UIView { // MARK: - Properties let stackView = UIStackView() // MARK: init methods override init(frame: CGRect) { super.init(frame: frame) viewHierarchy() configureConstraints() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = .clear viewHierarchy() configureConstraints() } // MARK: - Constraints func configureConstraints() { stackView.translatesAutoresizingMaskIntoConstraints = false checkoutButton.translatesAutoresizingMaskIntoConstraints = false deleteButton.translatesAutoresizingMaskIntoConstraints = false titleLabel.translatesAutoresizingMaskIntoConstraints = false authorLabel.translatesAutoresizingMaskIntoConstraints = false publisherLabel.translatesAutoresizingMaskIntoConstraints = false lastCheckedOutByLabel.translatesAutoresizingMaskIntoConstraints = false categoriesLabel.translatesAutoresizingMaskIntoConstraints = false let _ = [ stackView.centerXAnchor.constraint(equalTo: self.centerXAnchor), stackView.topAnchor.constraint(equalTo: self.topAnchor, constant: 100), stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8), stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8), checkoutButton.topAnchor.constraint(equalTo: lastCheckedOutByLabel.bottomAnchor, constant: 20), checkoutButton.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 15), checkoutButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -15), titleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8), titleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8), authorLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8), authorLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8), publisherLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8), publisherLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8), categoriesLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8), categoriesLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8), lastCheckedOutByLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8), lastCheckedOutByLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8), deleteButton.topAnchor.constraint(equalTo: checkoutButton.bottomAnchor, constant: 20), deleteButton.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 15), deleteButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -15), edit.topAnchor.constraint(equalTo: deleteButton.bottomAnchor, constant: 20), edit.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 15), edit.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -15) ].map({$0.isActive = true }) } // MARK: - View hierarchy func viewHierarchy() { stackView.axis = UILayoutConstraintAxis.vertical stackView.distribution = UIStackViewDistribution.equalSpacing stackView.alignment = UIStackViewAlignment.center stackView.backgroundColor = .black stackView.spacing = 16.0 stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(authorLabel) stackView.addArrangedSubview(publisherLabel) stackView.addArrangedSubview(categoriesLabel) stackView.addArrangedSubview(lastCheckedOutByLabel) stackView.addArrangedSubview(checkoutButton) stackView.addArrangedSubview(deleteButton) stackView.addArrangedSubview(edit) self.addSubview(stackView) } //MARK: - UI Objects lazy var titleLabel: UILabel = { let lbl = UILabel() lbl.textColor = .black lbl.numberOfLines = 2 lbl.lineBreakMode = .byWordWrapping lbl.textAlignment = .left lbl.backgroundColor = .lightBlue lbl.layer.borderColor = UIColor.blue.cgColor lbl.layer.cornerRadius = 5 lbl.layer.masksToBounds = true return lbl }() lazy var authorLabel: UILabel = { let lbl = UILabel() lbl.textColor = .black lbl.numberOfLines = 2 lbl.lineBreakMode = .byWordWrapping lbl.textAlignment = .left lbl.backgroundColor = .lightBlue lbl.layer.borderColor = UIColor.blue.cgColor lbl.layer.cornerRadius = 5 lbl.layer.masksToBounds = true return lbl }() lazy var publisherLabel: UILabel = { let lbl = UILabel() lbl.textColor = .black lbl.numberOfLines = 2 lbl.font = UIFont(name: "Avenir", size: 14) lbl.lineBreakMode = .byWordWrapping lbl.textAlignment = .left lbl.backgroundColor = .lightBlue lbl.layer.borderColor = UIColor.blue.cgColor lbl.layer.cornerRadius = 5 lbl.layer.masksToBounds = true return lbl }() lazy var categoriesLabel: UILabel = { let lbl = UILabel() lbl.textColor = .black lbl.font = UIFont(name: "Avenir", size: 14) lbl.numberOfLines = 2 lbl.lineBreakMode = .byWordWrapping lbl.textAlignment = .left lbl.backgroundColor = .lightBlue lbl.layer.borderColor = UIColor.blue.cgColor lbl.layer.cornerRadius = 5 lbl.layer.masksToBounds = true return lbl }() lazy var lastCheckedOutByLabel: UILabel = { let lbl = UILabel() lbl.textColor = .black lbl.font = UIFont(name: "Avenir", size: 14) lbl.numberOfLines = 2 lbl.lineBreakMode = .byWordWrapping lbl.textAlignment = .left lbl.backgroundColor = .lightBlue lbl.layer.borderColor = UIColor.blue.cgColor lbl.layer.cornerRadius = 5 lbl.layer.masksToBounds = true return lbl }() lazy var checkoutButton: UIButton = { let button = UIButton() button.setTitle("Check Out", for: .normal) button.setTitleColor(.white, for: .normal) button.layer.borderWidth = 1 button.layer.borderColor = UIColor.black.cgColor button.layer.cornerRadius = 5 button.clipsToBounds = true button.backgroundColor = .blue return button }() lazy var deleteButton: UIButton = { let button = UIButton() button.setTitle("Delete Book", for: .normal) button.setTitleColor(.white, for: .normal) button.backgroundColor = .red button.layer.borderWidth = 1 button.layer.cornerRadius = 5 button.clipsToBounds = true return button }() lazy var edit: UIButton = { let button = UIButton() button.setTitle("Edit Book", for: .normal) button.setTitleColor(.white, for: .normal) button.backgroundColor = .lilac button.layer.borderWidth = 1 button.layer.cornerRadius = 5 button.clipsToBounds = true return button }() }
39.44898
107
0.656105
694ce2352bf3e2acffa3bd64a885c4248d6f4edf
15,655
// // MinimedPumpManagerState.swift // Loop // // Copyright © 2018 LoopKit Authors. All rights reserved. // import LoopKit import RileyLinkKit import RileyLinkBLEKit public struct ReconciledDoseMapping: Equatable { let startTime: Date let uuid: UUID let eventRaw: Data } extension ReconciledDoseMapping: RawRepresentable { public typealias RawValue = [String:Any] public init?(rawValue: [String : Any]) { guard let startTime = rawValue["startTime"] as? Date, let uuidString = rawValue["uuid"] as? String, let uuid = UUID(uuidString: uuidString), let eventRawString = rawValue["eventRaw"] as? String, let eventRaw = Data(hexadecimalString: eventRawString) else { return nil } self.startTime = startTime self.uuid = uuid self.eventRaw = eventRaw } public var rawValue: [String : Any] { return [ "startTime": startTime, "uuid": uuid.uuidString, "eventRaw": eventRaw.hexadecimalString, ] } } public struct MinimedPumpManagerState: RawRepresentable, Equatable { public typealias RawValue = PumpManager.RawStateValue public static let version = 2 public var batteryChemistry: BatteryChemistryType public var batteryPercentage: Double? public var suspendState: SuspendState public var lastReservoirReading: ReservoirReading? public var lastTuned: Date? // In-memory only public var lastValidFrequency: Measurement<UnitFrequency>? public var preferredInsulinDataSource: InsulinDataSource public var useMySentry: Bool public let pumpColor: PumpColor public let pumpModel: PumpModel public let pumpFirmwareVersion: String public let pumpID: String public let pumpRegion: PumpRegion public var pumpSettings: PumpSettings { get { return PumpSettings(pumpID: pumpID, pumpRegion: pumpRegion) } } public var pumpState: PumpState { get { var state = PumpState() state.pumpModel = pumpModel state.timeZone = timeZone state.lastValidFrequency = lastValidFrequency state.lastTuned = lastTuned state.useMySentry = useMySentry return state } set { lastValidFrequency = newValue.lastValidFrequency lastTuned = newValue.lastTuned timeZone = newValue.timeZone } } public var rileyLinkConnectionManagerState: RileyLinkConnectionManagerState? public var timeZone: TimeZone public var unfinalizedBolus: UnfinalizedDose? public var unfinalizedTempBasal: UnfinalizedDose? // Doses we're tracking that haven't shown up in history yet public var pendingDoses: [UnfinalizedDose] // Maps public var reconciliationMappings: [Data:ReconciledDoseMapping] public var lastReconciliation: Date? public var rileyLinkBatteryAlertLevel: Int? public var lastRileyLinkBatteryAlertDate: Date = .distantPast public var insulinType: InsulinType? public init(batteryChemistry: BatteryChemistryType = .alkaline, preferredInsulinDataSource: InsulinDataSource = .pumpHistory, useMySentry: Bool = false, pumpColor: PumpColor, pumpID: String, pumpModel: PumpModel, pumpFirmwareVersion: String, pumpRegion: PumpRegion, rileyLinkConnectionManagerState: RileyLinkConnectionManagerState?, timeZone: TimeZone, suspendState: SuspendState, lastValidFrequency: Measurement<UnitFrequency>? = nil, batteryPercentage: Double? = nil, lastReservoirReading: ReservoirReading? = nil, unfinalizedBolus: UnfinalizedDose? = nil, unfinalizedTempBasal: UnfinalizedDose? = nil, pendingDoses: [UnfinalizedDose]? = nil, recentlyReconciledEvents: [Data:ReconciledDoseMapping]? = nil, lastReconciliation: Date? = nil, insulinType: InsulinType? = nil) { self.batteryChemistry = batteryChemistry self.preferredInsulinDataSource = preferredInsulinDataSource self.useMySentry = useMySentry self.pumpColor = pumpColor self.pumpID = pumpID self.pumpModel = pumpModel self.pumpFirmwareVersion = pumpFirmwareVersion self.pumpRegion = pumpRegion self.rileyLinkConnectionManagerState = rileyLinkConnectionManagerState self.timeZone = timeZone self.suspendState = suspendState self.lastValidFrequency = lastValidFrequency self.batteryPercentage = batteryPercentage self.lastReservoirReading = lastReservoirReading self.unfinalizedBolus = unfinalizedBolus self.unfinalizedTempBasal = unfinalizedTempBasal self.pendingDoses = pendingDoses ?? [] self.reconciliationMappings = recentlyReconciledEvents ?? [:] self.lastReconciliation = lastReconciliation self.insulinType = insulinType } public init?(rawValue: RawValue) { guard let version = rawValue["version"] as? Int, let useMySentry = rawValue["useMySentry"] as? Bool, let batteryChemistryRaw = rawValue["batteryChemistry"] as? BatteryChemistryType.RawValue, let insulinDataSourceRaw = rawValue["insulinDataSource"] as? InsulinDataSource.RawValue, let pumpColorRaw = rawValue["pumpColor"] as? PumpColor.RawValue, let pumpID = rawValue["pumpID"] as? String, let pumpModelNumber = rawValue["pumpModel"] as? PumpModel.RawValue, let pumpRegionRaw = rawValue["pumpRegion"] as? PumpRegion.RawValue, let timeZoneSeconds = rawValue["timeZone"] as? Int, let batteryChemistry = BatteryChemistryType(rawValue: batteryChemistryRaw), let insulinDataSource = InsulinDataSource(rawValue: insulinDataSourceRaw), let pumpColor = PumpColor(rawValue: pumpColorRaw), let pumpModel = PumpModel(rawValue: pumpModelNumber), let pumpRegion = PumpRegion(rawValue: pumpRegionRaw), let timeZone = TimeZone(secondsFromGMT: timeZoneSeconds) else { return nil } var rileyLinkConnectionManagerState: RileyLinkConnectionManagerState? = nil // Migrate if version == 1 { if let oldRileyLinkPumpManagerStateRaw = rawValue["rileyLinkPumpManagerState"] as? [String : Any], let connectedPeripheralIDs = oldRileyLinkPumpManagerStateRaw["connectedPeripheralIDs"] as? [String] { rileyLinkConnectionManagerState = RileyLinkConnectionManagerState(autoConnectIDs: Set(connectedPeripheralIDs)) } } else { if let rawState = rawValue["rileyLinkConnectionManagerState"] as? RileyLinkConnectionManagerState.RawValue { rileyLinkConnectionManagerState = RileyLinkConnectionManagerState(rawValue: rawState) } } let suspendState: SuspendState if let isPumpSuspended = rawValue["isPumpSuspended"] as? Bool { // migrate if isPumpSuspended { suspendState = .suspended(Date()) } else { suspendState = .resumed(Date()) } } else if let rawSuspendState = rawValue["suspendState"] as? SuspendState.RawValue, let storedSuspendState = SuspendState(rawValue: rawSuspendState) { suspendState = storedSuspendState } else { return nil } let lastValidFrequency: Measurement<UnitFrequency>? if let frequencyRaw = rawValue["lastValidFrequency"] as? Double { lastValidFrequency = Measurement<UnitFrequency>(value: frequencyRaw, unit: .megahertz) } else { lastValidFrequency = nil } let pumpFirmwareVersion = (rawValue["pumpFirmwareVersion"] as? String) ?? "" let batteryPercentage = rawValue["batteryPercentage"] as? Double let lastReservoirReading: ReservoirReading? if let rawLastReservoirReading = rawValue["lastReservoirReading"] as? ReservoirReading.RawValue { lastReservoirReading = ReservoirReading(rawValue: rawLastReservoirReading) } else { lastReservoirReading = nil } let unfinalizedBolus: UnfinalizedDose? if let rawUnfinalizedBolus = rawValue["unfinalizedBolus"] as? UnfinalizedDose.RawValue { unfinalizedBolus = UnfinalizedDose(rawValue: rawUnfinalizedBolus) } else { unfinalizedBolus = nil } let unfinalizedTempBasal: UnfinalizedDose? if let rawUnfinalizedTempBasal = rawValue["unfinalizedTempBasal"] as? UnfinalizedDose.RawValue { unfinalizedTempBasal = UnfinalizedDose(rawValue: rawUnfinalizedTempBasal) } else { unfinalizedTempBasal = nil } let pendingDoses: [UnfinalizedDose] if let rawPendingDoses = rawValue["pendingDoses"] as? [UnfinalizedDose.RawValue] { pendingDoses = rawPendingDoses.compactMap( { UnfinalizedDose(rawValue: $0) } ) } else { pendingDoses = [] } let recentlyReconciledEvents: [Data:ReconciledDoseMapping] if let rawRecentlyReconciledEvents = rawValue["recentlyReconciledEvents"] as? [ReconciledDoseMapping.RawValue] { let mappings = rawRecentlyReconciledEvents.compactMap { ReconciledDoseMapping(rawValue: $0) } recentlyReconciledEvents = Dictionary(mappings.map{ ($0.eventRaw, $0) }, uniquingKeysWith: { (old, new) in new } ) } else { recentlyReconciledEvents = [:] } let lastReconciliation = rawValue["lastReconciliation"] as? Date let insulinType: InsulinType? if let rawInsulinType = rawValue["insulinType"] as? InsulinType.RawValue { insulinType = InsulinType(rawValue: rawInsulinType) } else { insulinType = nil } self.init( batteryChemistry: batteryChemistry, preferredInsulinDataSource: insulinDataSource, useMySentry: useMySentry, pumpColor: pumpColor, pumpID: pumpID, pumpModel: pumpModel, pumpFirmwareVersion: pumpFirmwareVersion, pumpRegion: pumpRegion, rileyLinkConnectionManagerState: rileyLinkConnectionManagerState, timeZone: timeZone, suspendState: suspendState, lastValidFrequency: lastValidFrequency, batteryPercentage: batteryPercentage, lastReservoirReading: lastReservoirReading, unfinalizedBolus: unfinalizedBolus, unfinalizedTempBasal: unfinalizedTempBasal, pendingDoses: pendingDoses, recentlyReconciledEvents: recentlyReconciledEvents, lastReconciliation: lastReconciliation, insulinType: insulinType ) } public var rawValue: RawValue { var value: [String : Any] = [ "batteryChemistry": batteryChemistry.rawValue, "insulinDataSource": preferredInsulinDataSource.rawValue, "pumpColor": pumpColor.rawValue, "pumpID": pumpID, "pumpModel": pumpModel.rawValue, "pumpFirmwareVersion": pumpFirmwareVersion, "pumpRegion": pumpRegion.rawValue, "timeZone": timeZone.secondsFromGMT(), "suspendState": suspendState.rawValue, "version": MinimedPumpManagerState.version, "pendingDoses": pendingDoses.map { $0.rawValue }, "recentlyReconciledEvents": reconciliationMappings.values.map { $0.rawValue }, ] value["useMySentry"] = useMySentry value["batteryPercentage"] = batteryPercentage value["lastReservoirReading"] = lastReservoirReading?.rawValue value["lastValidFrequency"] = lastValidFrequency?.converted(to: .megahertz).value value["rileyLinkConnectionManagerState"] = rileyLinkConnectionManagerState?.rawValue value["unfinalizedBolus"] = unfinalizedBolus?.rawValue value["unfinalizedTempBasal"] = unfinalizedTempBasal?.rawValue value["lastReconciliation"] = lastReconciliation value["rileyLinkBatteryAlertLevel"] = rileyLinkBatteryAlertLevel value["lastRileyLinkBatteryAlertDate"] = lastRileyLinkBatteryAlertDate value["insulinType"] = insulinType?.rawValue return value } } extension MinimedPumpManagerState { static let idleListeningEnabledDefaults: RileyLinkDevice.IdleListeningState = .enabled(timeout: .minutes(4), channel: 0) } extension MinimedPumpManagerState: CustomDebugStringConvertible { public var debugDescription: String { return [ "## MinimedPumpManagerState", "batteryChemistry: \(batteryChemistry)", "batteryPercentage: \(String(describing: batteryPercentage))", "suspendState: \(suspendState)", "lastValidFrequency: \(String(describing: lastValidFrequency))", "preferredInsulinDataSource: \(preferredInsulinDataSource)", "useMySentry: \(useMySentry)", "pumpColor: \(pumpColor)", "pumpID: ✔︎", "pumpModel: \(pumpModel.rawValue)", "pumpFirmwareVersion: \(pumpFirmwareVersion)", "pumpRegion: \(pumpRegion)", "reservoirUnits: \(String(describing: lastReservoirReading?.units))", "reservoirValidAt: \(String(describing: lastReservoirReading?.validAt))", "unfinalizedBolus: \(String(describing: unfinalizedBolus))", "unfinalizedTempBasal: \(String(describing: unfinalizedTempBasal))", "pendingDoses: \(pendingDoses)", "timeZone: \(timeZone)", "recentlyReconciledEvents: \(reconciliationMappings.values.map { "\($0.eventRaw.hexadecimalString) -> \($0.uuid)" })", "lastReconciliation: \(String(describing: lastReconciliation))", "rileyLinkBatteryAlertLevel: \(String(describing: rileyLinkBatteryAlertLevel))", "lastRileyLinkBatteryAlertDate \(String(describing: lastRileyLinkBatteryAlertDate))", "insulinType: \(String(describing: insulinType))", String(reflecting: rileyLinkConnectionManagerState), ].joined(separator: "\n") } } public enum SuspendState: Equatable, RawRepresentable { public typealias RawValue = [String: Any] private enum SuspendStateType: Int { case suspend, resume } case suspended(Date) case resumed(Date) private var identifier: Int { switch self { case .suspended: return 1 case .resumed: return 2 } } public init?(rawValue: RawValue) { guard let suspendStateType = rawValue["case"] as? SuspendStateType.RawValue, let date = rawValue["date"] as? Date else { return nil } switch SuspendStateType(rawValue: suspendStateType) { case .suspend?: self = .suspended(date) case .resume?: self = .resumed(date) default: return nil } } public var rawValue: RawValue { switch self { case .suspended(let date): return [ "case": SuspendStateType.suspend.rawValue, "date": date ] case .resumed(let date): return [ "case": SuspendStateType.resume.rawValue, "date": date ] } } }
39.433249
779
0.65436
e56d80f5d58ede27e7955730a4225ad26e998bee
464
// // UIScreen+Extension.swift // ZPOperator // // Created by 杜进新 on 2017/7/3. // Copyright © 2017年 dujinxin. All rights reserved. // import UIKit extension UIScreen { var screenSize : CGSize { get{ return bounds.size } } var screenWidth : CGFloat { get{ return bounds.width } } var screenHeight : CGFloat { get{ return bounds.height } } }
15.466667
52
0.519397
268bed6b1c4aac7a6e50568d795de70f683e0a0b
2,699
// // AddressBookViewModel.swift // AlphaWallet // // Created by Jili Bernadett on 2021. 07. 03.. // import UIKit class AddressBookViewModel { var contacts: [ContactWithAddress] func reloadFilteredContacts() { filteredContacts = filteredAndSortedContacts() } var filterKeyword: String = "" { didSet { filteredContacts = filteredAndSortedContacts() } } lazy var filteredContacts: [ContactWithAddress] = { return filteredAndSortedContacts() }() var headerBackgroundColor: UIColor { return Colors.appBackground } var backgroundColor: UIColor { return Colors.appBackground } var hasContent: Bool { return !filteredContacts.isEmpty } func numberOfItems() -> Int { return filteredContacts.count } func item(for row: Int, section: Int) -> ContactWithAddress? { if filteredContacts.count > row { return filteredContacts[row] } else { return nil } } init(contacts: [ContactWithAddress]) { self.contacts = contacts } func addContact(contact: ContactWithAddress) { contacts.removeAll(where: { $0.address.eip55String == contact.address.eip55String }) contacts.append(contact) contacts.sort(by: { $0.name < $1.name }) filteredContacts = filteredAndSortedContacts() } func removeContact(contact: ContactWithAddress) -> Bool { if let index = contacts.firstIndex(where: { $0.address == contact.address }) { contacts.remove(at: index) filteredContacts = filteredAndSortedContacts() return true } return false } private func filteredAndSortedContacts() -> [ContactWithAddress] { let displayedContacts = filterContacts(contacts: contacts, keyword: filterKeyword) return sortContacts(contacts: displayedContacts) } } fileprivate func filterContacts(contacts: [ContactWithAddress], keyword: String) -> [ContactWithAddress] { let filteredContacts: [ContactWithAddress] let lowercasedKeyword = keyword.trimmed.lowercased() if lowercasedKeyword.isEmpty { filteredContacts = contacts } else { filteredContacts = contacts.filter { return $0.name.trimmed.lowercased().contains(lowercasedKeyword) // || $0.address.eip55String.lowercased().contains(lowercasedKeyword) } } return filteredContacts } fileprivate func sortContacts(contacts: [ContactWithAddress]) -> [ContactWithAddress] { return contacts.sorted(by: { $0.name < $1.name }) }
26.722772
106
0.638755
875ff1f197515b3f26f1ae55e5e4b595714a355e
2,171
// // ContentView.swift // StockInfo // // Created by Александр Дремов on 12.08.2020. // Copyright © 2020 alexdremov. All rights reserved. // import SwiftUI import SwiftYFinance struct ContentView: View { @State var searchString:String = "AAPL" @State var foundContainer:[YFQuoteSearchResult] = [] @State var sheetVisible = false @ObservedObject var selection = SelectedSymbolWrapper() var body: some View { return VStack{ HStack{ Text("Stock Info") .font(.largeTitle) .fontWeight(.heavy) .multilineTextAlignment(.leading) Spacer() }.padding([.top, .leading, .trailing]) TextField("Search", text: $searchString, onCommit: self.searchObjects) .textFieldStyle(RoundedBorderTextFieldStyle()) .cornerRadius(5).padding(.horizontal) Group{ List{ ForEach(self.foundContainer, id: \.symbol){result in Button(action: { self.selection.symbol = result.symbol self.sheetVisible = true }){ ListUnoView(result:result).listRowInsets(EdgeInsets()) } }.listRowInsets(EdgeInsets()) }.padding(0.0) } Spacer() }.sheet(isPresented: self.$sheetVisible, content: { SheetView(selection: self.selection) }).onAppear(perform: self.searchObjects) } func searchObjects(){ SwiftYFinance.fetchSearchDataBy(searchTerm: self.searchString) {data, error in if error != nil{ return } self.foundContainer = data! } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } class SelectedSymbolWrapper: ObservableObject{ @Published var symbol:String? init(symbol:String){ self.symbol = symbol } init(){ } }
28.565789
82
0.532934
bb4533f043592d12b820119c4adea84c1b5d89ad
321
import UIKit var str = "Hello World!" func reverse(normal: inout String) -> String { if (normal.count <= 0){ return normal } var normalCopy = String(normal.suffix(normal.count-1)) return reverse(normal: &normalCopy) + "\(Array(normal)[0])" } var test = reverse(normal: &str) print(test)
18.882353
63
0.632399
fc66edb831fbd56c09b022795c31075148d16bc3
38,237
import Foundation import Postbox import SwiftSignalKit import TelegramApi import MtProtoKit import SyncCore func messageFilterForTagMask(_ tagMask: MessageTags) -> Api.MessagesFilter? { if tagMask == .photoOrVideo { return Api.MessagesFilter.inputMessagesFilterPhotoVideo } else if tagMask == .photo { return Api.MessagesFilter.inputMessagesFilterPhotos } else if tagMask == .video { return Api.MessagesFilter.inputMessagesFilterVideo } else if tagMask == .file { return Api.MessagesFilter.inputMessagesFilterDocument } else if tagMask == .music { return Api.MessagesFilter.inputMessagesFilterMusic } else if tagMask == .webPage { return Api.MessagesFilter.inputMessagesFilterUrl } else if tagMask == .voiceOrInstantVideo { return Api.MessagesFilter.inputMessagesFilterRoundVoice } else if tagMask == .gif { return Api.MessagesFilter.inputMessagesFilterGif } else if tagMask == .pinned { return Api.MessagesFilter.inputMessagesFilterPinned } else { return nil } } enum FetchMessageHistoryHoleSource { case network(Network) case download(Download) func request<T>(_ data: (FunctionDescription, Buffer, DeserializeFunctionResponse<T>)) -> Signal<T, MTRpcError> { switch self { case let .network(network): return network.request(data) case let .download(download): return download.request(data) } } } func withResolvedAssociatedMessages<T>(postbox: Postbox, source: FetchMessageHistoryHoleSource, peers: [PeerId: Peer], storeMessages: [StoreMessage], _ f: @escaping (Transaction, [Peer], [StoreMessage]) -> T) -> Signal<T, NoError> { return postbox.transaction { transaction -> Signal<T, NoError> in var storedIds = Set<MessageId>() var referencedIds = Set<MessageId>() for message in storeMessages { guard case let .Id(id) = message.id else { continue } storedIds.insert(id) for attribute in message.attributes { referencedIds.formUnion(attribute.associatedMessageIds) } } referencedIds.subtract(storedIds) referencedIds.subtract(transaction.filterStoredMessageIds(referencedIds)) if referencedIds.isEmpty { return .single(f(transaction, [], [])) } else { var signals: [Signal<([Api.Message], [Api.Chat], [Api.User]), NoError>] = [] for (peerId, messageIds) in messagesIdsGroupedByPeerId(referencedIds) { if let peer = transaction.getPeer(peerId) ?? peers[peerId] { var signal: Signal<Api.messages.Messages, MTRpcError>? if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup { signal = source.request(Api.functions.messages.getMessages(id: messageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) }))) } else if peerId.namespace == Namespaces.Peer.CloudChannel { if let inputChannel = apiInputChannel(peer) { signal = source.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) }))) } } if let signal = signal { signals.append(signal |> map { result in switch result { case let .messages(messages, chats, users): return (messages, chats, users) case let .messagesSlice(_, _, _, _, messages, chats, users): return (messages, chats, users) case let .channelMessages(_, _, _, _, messages, chats, users): return (messages, chats, users) case .messagesNotModified: return ([], [], []) } } |> `catch` { _ in return Signal<([Api.Message], [Api.Chat], [Api.User]), NoError>.single(([], [], [])) }) } } } let fetchMessages = combineLatest(signals) return fetchMessages |> mapToSignal { results -> Signal<T, NoError> in var additionalPeers: [Peer] = [] var additionalMessages: [StoreMessage] = [] for (messages, chats, users) in results { if !messages.isEmpty { for message in messages { if let message = StoreMessage(apiMessage: message) { additionalMessages.append(message) } } } for chat in chats { if let peer = parseTelegramGroupOrChannel(chat: chat) { additionalPeers.append(peer) } } for user in users { additionalPeers.append(TelegramUser(user: user)) } } return postbox.transaction { transaction -> T in return f(transaction, additionalPeers, additionalMessages) } } } } |> switchToLatest } enum FetchMessageHistoryHoleThreadInput: CustomStringConvertible { case direct(peerId: PeerId, threadId: Int64?) case threadFromChannel(channelMessageId: MessageId) var description: String { switch self { case let .direct(peerId, threadId): return "direct(\(peerId), \(String(describing: threadId))" case let .threadFromChannel(channelMessageId): return "threadFromChannel(peerId: \(channelMessageId.peerId), postId: \(channelMessageId.id)" } } var requestThreadId: MessageId? { switch self { case let .direct(peerId, threadId): if let threadId = threadId { return makeThreadIdMessageId(peerId: peerId, threadId: threadId) } else { return nil } case let .threadFromChannel(channelMessageId): return channelMessageId } } } struct FetchMessageHistoryHoleResult: Equatable { var removedIndices: IndexSet var strictRemovedIndices: IndexSet var actualPeerId: PeerId? var actualThreadId: Int64? } func fetchMessageHistoryHole(accountPeerId: PeerId, source: FetchMessageHistoryHoleSource, postbox: Postbox, peerInput: FetchMessageHistoryHoleThreadInput, namespace: MessageId.Namespace, direction: MessageHistoryViewRelativeHoleDirection, space: MessageHistoryHoleSpace, count rawCount: Int) -> Signal<FetchMessageHistoryHoleResult?, NoError> { let count = min(100, rawCount) return postbox.stateView() |> mapToSignal { view -> Signal<AuthorizedAccountState, NoError> in if let state = view.state as? AuthorizedAccountState { return .single(state) } else { return .complete() } } |> take(1) |> mapToSignal { _ -> Signal<FetchMessageHistoryHoleResult?, NoError> in return postbox.transaction { transaction -> (Api.InputPeer?, Int32) in switch peerInput { case let .direct(peerId, _): return (transaction.getPeer(peerId).flatMap(forceApiInputPeer), 0) case let .threadFromChannel(channelMessageId): return (transaction.getPeer(channelMessageId.peerId).flatMap(forceApiInputPeer), 0) } } |> mapToSignal { (inputPeer, hash) -> Signal<FetchMessageHistoryHoleResult?, NoError> in guard let inputPeer = inputPeer else { return .single(FetchMessageHistoryHoleResult(removedIndices: IndexSet(), strictRemovedIndices: IndexSet(), actualPeerId: nil, actualThreadId: nil)) } print("fetchMessageHistoryHole for \(peerInput) direction \(direction) space \(space)") Logger.shared.log("fetchMessageHistoryHole", "fetch for \(peerInput) direction \(direction) space \(space)") let request: Signal<Api.messages.Messages, MTRpcError> var implicitelyFillHole = false let minMaxRange: ClosedRange<MessageId.Id> switch space { case .everywhere: if let requestThreadId = peerInput.requestThreadId { let offsetId: Int32 let addOffset: Int32 let selectedLimit = count let maxId: Int32 let minId: Int32 switch direction { case let .range(start, end): if start.id <= end.id { offsetId = start.id <= 1 ? 1 : (start.id - 1) addOffset = Int32(-selectedLimit) maxId = end.id minId = start.id - 1 let rangeStartId = start.id let rangeEndId = min(end.id, Int32.max - 1) if rangeStartId <= rangeEndId { minMaxRange = rangeStartId ... rangeEndId } else { minMaxRange = rangeStartId ... rangeStartId assertionFailure() } } else { offsetId = start.id == Int32.max ? start.id : (start.id + 1) addOffset = 0 maxId = start.id == Int32.max ? start.id : (start.id + 1) minId = end.id let rangeStartId = end.id let rangeEndId = min(start.id, Int32.max - 1) if rangeStartId <= rangeEndId { minMaxRange = rangeStartId ... rangeEndId } else { minMaxRange = rangeStartId ... rangeStartId assertionFailure() } } case let .aroundId(id): offsetId = id.id addOffset = Int32(-selectedLimit / 2) maxId = Int32.max minId = 1 minMaxRange = 1 ... (Int32.max - 1) } request = source.request(Api.functions.messages.getReplies(peer: inputPeer, msgId: requestThreadId.id, offsetId: offsetId, offsetDate: 0, addOffset: addOffset, limit: Int32(selectedLimit), maxId: maxId, minId: minId, hash: hash)) } else { let offsetId: Int32 let addOffset: Int32 let selectedLimit = count let maxId: Int32 let minId: Int32 switch direction { case let .range(start, end): if start.id <= end.id { offsetId = start.id <= 1 ? 1 : (start.id - 1) addOffset = Int32(-selectedLimit) maxId = end.id minId = start.id - 1 let rangeStartId = start.id let rangeEndId = min(end.id, Int32.max - 1) if rangeStartId <= rangeEndId { minMaxRange = rangeStartId ... rangeEndId } else { minMaxRange = rangeStartId ... rangeStartId assertionFailure() } } else { offsetId = start.id == Int32.max ? start.id : (start.id + 1) addOffset = 0 maxId = start.id == Int32.max ? start.id : (start.id + 1) minId = end.id == 1 ? 0 : end.id let rangeStartId = end.id let rangeEndId = min(start.id, Int32.max - 1) if rangeStartId <= rangeEndId { minMaxRange = rangeStartId ... rangeEndId } else { minMaxRange = rangeStartId ... rangeStartId assertionFailure() } } case let .aroundId(id): offsetId = id.id addOffset = Int32(-selectedLimit / 2) maxId = Int32.max minId = 1 minMaxRange = 1 ... Int32.max - 1 } request = source.request(Api.functions.messages.getHistory(peer: inputPeer, offsetId: offsetId, offsetDate: 0, addOffset: addOffset, limit: Int32(selectedLimit), maxId: maxId, minId: minId, hash: 0)) } case let .tag(tag): assert(tag.containsSingleElement) if tag == .unseenPersonalMessage { let offsetId: Int32 let addOffset: Int32 let selectedLimit = count let maxId: Int32 let minId: Int32 switch direction { case let .range(start, end): if start.id <= end.id { offsetId = start.id <= 1 ? 1 : (start.id - 1) addOffset = Int32(-selectedLimit) maxId = end.id minId = start.id - 1 let rangeStartId = start.id let rangeEndId = min(end.id, Int32.max - 1) if rangeStartId <= rangeEndId { minMaxRange = rangeStartId ... rangeEndId } else { minMaxRange = rangeStartId ... rangeStartId assertionFailure() } } else { offsetId = start.id == Int32.max ? start.id : (start.id + 1) addOffset = 0 maxId = start.id == Int32.max ? start.id : (start.id + 1) minId = end.id let rangeStartId = end.id let rangeEndId = min(start.id, Int32.max - 1) if rangeStartId <= rangeEndId { minMaxRange = rangeStartId ... rangeEndId } else { minMaxRange = rangeStartId ... rangeStartId assertionFailure() } } case let .aroundId(id): offsetId = id.id addOffset = Int32(-selectedLimit / 2) maxId = Int32.max minId = 1 minMaxRange = 1 ... Int32.max - 1 } request = source.request(Api.functions.messages.getUnreadMentions(peer: inputPeer, offsetId: offsetId, addOffset: addOffset, limit: Int32(selectedLimit), maxId: maxId, minId: minId)) } else if tag == .liveLocation { let selectedLimit = count switch direction { case .aroundId, .range: implicitelyFillHole = true } minMaxRange = 1 ... (Int32.max - 1) request = source.request(Api.functions.messages.getRecentLocations(peer: inputPeer, limit: Int32(selectedLimit), hash: 0)) } else if let filter = messageFilterForTagMask(tag) { let offsetId: Int32 let addOffset: Int32 let selectedLimit = count let maxId: Int32 let minId: Int32 switch direction { case let .range(start, end): if start.id <= end.id { offsetId = start.id <= 1 ? 1 : (start.id - 1) addOffset = Int32(-selectedLimit) maxId = end.id minId = start.id - 1 let rangeStartId = start.id let rangeEndId = min(end.id, Int32.max - 1) if rangeStartId <= rangeEndId { minMaxRange = rangeStartId ... rangeEndId } else { minMaxRange = rangeStartId ... rangeStartId assertionFailure() } } else { offsetId = start.id == Int32.max ? start.id : (start.id + 1) addOffset = 0 maxId = start.id == Int32.max ? start.id : (start.id + 1) minId = end.id let rangeStartId = end.id let rangeEndId = min(start.id, Int32.max - 1) if rangeStartId <= rangeEndId { minMaxRange = rangeStartId ... rangeEndId } else { minMaxRange = rangeStartId ... rangeStartId assertionFailure() } } case let .aroundId(id): offsetId = id.id addOffset = Int32(-selectedLimit / 2) maxId = Int32.max minId = 1 minMaxRange = 1 ... (Int32.max - 1) } request = source.request(Api.functions.messages.search(flags: 0, peer: inputPeer, q: "", fromId: nil, topMsgId: nil, filter: filter, minDate: 0, maxDate: 0, offsetId: offsetId, addOffset: addOffset, limit: Int32(selectedLimit), maxId: maxId, minId: minId, hash: 0)) } else { assertionFailure() minMaxRange = 1 ... 1 request = .never() } } return request |> retry(retryOnError: { error in if error.errorDescription == "CHANNEL_PRIVATE" { switch peerInput { case let .direct(_, threadId): if threadId != nil { return false } case .threadFromChannel: return false } } return true }, delayIncrement: 0.1, maxDelay: 2.0, maxRetries: 0, onQueue: .concurrentDefaultQueue()) |> map(Optional.init) |> `catch` { _ -> Signal<Api.messages.Messages?, NoError> in return .single(nil) } |> mapToSignal { result -> Signal<FetchMessageHistoryHoleResult?, NoError> in guard let result = result else { return .single(nil) } let messages: [Api.Message] let chats: [Api.Chat] let users: [Api.User] var channelPts: Int32? switch result { case let .messages(messages: apiMessages, chats: apiChats, users: apiUsers): messages = apiMessages chats = apiChats users = apiUsers case let .messagesSlice(_, _, _, _, messages: apiMessages, chats: apiChats, users: apiUsers): messages = apiMessages chats = apiChats users = apiUsers case let .channelMessages(_, pts, _, _, apiMessages, apiChats, apiUsers): messages = apiMessages chats = apiChats users = apiUsers channelPts = pts case .messagesNotModified: messages = [] chats = [] users = [] } var peers: [Peer] = [] var peerPresences: [PeerId: PeerPresence] = [:] for chat in chats { if let groupOrChannel = parseTelegramGroupOrChannel(chat: chat) { peers.append(groupOrChannel) } } for user in users { let telegramUser = TelegramUser(user: user) peers.append(telegramUser) if let presence = TelegramUserPresence(apiUser: user) { peerPresences[telegramUser.id] = presence } } var storeMessages: [StoreMessage] = [] for message in messages { if let storeMessage = StoreMessage(apiMessage: message, namespace: namespace) { if let channelPts = channelPts { var attributes = storeMessage.attributes attributes.append(ChannelMessageStateVersionAttribute(pts: channelPts)) storeMessages.append(storeMessage.withUpdatedAttributes(attributes)) } else { storeMessages.append(storeMessage) } } } return withResolvedAssociatedMessages(postbox: postbox, source: source, peers: Dictionary(peers.map({ ($0.id, $0) }), uniquingKeysWith: { lhs, _ in lhs }), storeMessages: storeMessages, { transaction, additionalPeers, additionalMessages -> FetchMessageHistoryHoleResult in let _ = transaction.addMessages(storeMessages, location: .Random) let _ = transaction.addMessages(additionalMessages, location: .Random) var filledRange: ClosedRange<MessageId.Id> var strictFilledIndices: IndexSet let ids = storeMessages.compactMap { message -> MessageId.Id? in switch message.id { case let .Id(id): switch space { case let .tag(tag): if !message.tags.contains(tag) { return nil } else { return id.id } case .everywhere: return id.id } case .Partial: return nil } } if ids.count == 0 || implicitelyFillHole { filledRange = minMaxRange strictFilledIndices = IndexSet() } else { let messageRange = ids.min()! ... ids.max()! switch direction { case let .aroundId(aroundId): filledRange = min(aroundId.id, messageRange.lowerBound) ... max(aroundId.id, messageRange.upperBound) strictFilledIndices = IndexSet(integersIn: Int(min(aroundId.id, messageRange.lowerBound)) ... Int(max(aroundId.id, messageRange.upperBound))) if peerInput.requestThreadId != nil { if ids.count <= count / 2 - 1 { filledRange = minMaxRange } } case let .range(start, end): if start.id <= end.id { let minBound = start.id let maxBound = messageRange.upperBound filledRange = min(minBound, maxBound) ... max(minBound, maxBound) var maxStrictIndex = max(minBound, maxBound) maxStrictIndex = min(maxStrictIndex, messageRange.upperBound) strictFilledIndices = IndexSet(integersIn: Int(min(minBound, maxBound)) ... Int(maxStrictIndex)) } else { let minBound = messageRange.lowerBound let maxBound = start.id filledRange = min(minBound, maxBound) ... max(minBound, maxBound) var maxStrictIndex = max(minBound, maxBound) maxStrictIndex = min(maxStrictIndex, messageRange.upperBound) strictFilledIndices = IndexSet(integersIn: Int(min(minBound, maxBound)) ... Int(maxStrictIndex)) } } } switch peerInput { case let .direct(peerId, threadId): if let threadId = threadId { for range in strictFilledIndices.rangeView { transaction.removeThreadIndexHole(peerId: peerId, threadId: threadId, namespace: namespace, space: space, range: Int32(range.lowerBound) ... Int32(range.upperBound)) } } else { transaction.removeHole(peerId: peerId, namespace: namespace, space: space, range: filledRange) } case .threadFromChannel: break } updatePeers(transaction: transaction, peers: peers + additionalPeers, update: { _, updated -> Peer in return updated }) updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: peerPresences) print("fetchMessageHistoryHole for \(peerInput) space \(space) done") return FetchMessageHistoryHoleResult( removedIndices: IndexSet(integersIn: Int(filledRange.lowerBound) ... Int(filledRange.upperBound)), strictRemovedIndices: strictFilledIndices, actualPeerId: storeMessages.first?.id.peerId, actualThreadId: storeMessages.first?.threadId ) }) } } } } func groupBoundaryPeer(_ peerId: PeerId, accountPeerId: PeerId) -> Api.Peer { switch peerId.namespace { case Namespaces.Peer.CloudUser: return Api.Peer.peerUser(userId: peerId.id) case Namespaces.Peer.CloudGroup: return Api.Peer.peerChat(chatId: peerId.id) case Namespaces.Peer.CloudChannel: return Api.Peer.peerChannel(channelId: peerId.id) default: return Api.Peer.peerUser(userId: accountPeerId.id) } } func fetchChatListHole(postbox: Postbox, network: Network, accountPeerId: PeerId, groupId: PeerGroupId, hole: ChatListHole) -> Signal<Never, NoError> { let location: FetchChatListLocation switch groupId { case .root: location = .general case .group: location = .group(groupId) } return fetchChatList(postbox: postbox, network: network, location: location, upperBound: hole.index, hash: 0, limit: 100) |> mapToSignal { fetchedChats -> Signal<Never, NoError> in guard let fetchedChats = fetchedChats else { return postbox.transaction { transaction -> Void in transaction.replaceChatListHole(groupId: groupId, index: hole.index, hole: nil) } |> ignoreValues } return withResolvedAssociatedMessages(postbox: postbox, source: .network(network), peers: Dictionary(fetchedChats.peers.map({ ($0.id, $0) }), uniquingKeysWith: { lhs, _ in lhs }), storeMessages: fetchedChats.storeMessages, { transaction, additionalPeers, additionalMessages in updatePeers(transaction: transaction, peers: fetchedChats.peers + additionalPeers, update: { _, updated -> Peer in return updated }) updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: fetchedChats.peerPresences) transaction.updateCurrentPeerNotificationSettings(fetchedChats.notificationSettings) let _ = transaction.addMessages(fetchedChats.storeMessages, location: .UpperHistoryBlock) let _ = transaction.addMessages(additionalMessages, location: .Random) transaction.resetIncomingReadStates(fetchedChats.readStates) transaction.replaceChatListHole(groupId: groupId, index: hole.index, hole: fetchedChats.lowerNonPinnedIndex.flatMap(ChatListHole.init)) for peerId in fetchedChats.chatPeerIds { if let peer = transaction.getPeer(peerId) { transaction.updatePeerChatListInclusion(peerId, inclusion: .ifHasMessagesOrOneOf(groupId: groupId, pinningIndex: transaction.getPeerChatListIndex(peerId)?.1.pinningIndex, minTimestamp: minTimestampForPeerInclusion(peer))) } else { assertionFailure() } } for (peerId, peerGroupId) in fetchedChats.peerGroupIds { if let peer = transaction.getPeer(peerId) { transaction.updatePeerChatListInclusion(peerId, inclusion: .ifHasMessagesOrOneOf(groupId: peerGroupId, pinningIndex: nil, minTimestamp: minTimestampForPeerInclusion(peer))) } else { assertionFailure() } } for (peerId, pts) in fetchedChats.channelStates { if let current = transaction.getPeerChatState(peerId) as? ChannelState { transaction.setPeerChatState(peerId, state: current.withUpdatedPts(pts)) } else { transaction.setPeerChatState(peerId, state: ChannelState(pts: pts, invalidatedPts: nil, synchronizedUntilMessageId: nil)) } } if let replacePinnedItemIds = fetchedChats.pinnedItemIds { transaction.setPinnedItemIds(groupId: groupId, itemIds: replacePinnedItemIds.map(PinnedItemId.peer)) } for (peerId, summary) in fetchedChats.mentionTagSummaries { transaction.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud, count: summary.count, maxId: summary.range.maxId) } for (groupId, summary) in fetchedChats.folderSummaries { transaction.resetPeerGroupSummary(groupId: groupId, namespace: Namespaces.Message.Cloud, summary: summary) } return }) |> ignoreValues } } func fetchCallListHole(network: Network, postbox: Postbox, accountPeerId: PeerId, holeIndex: MessageIndex, limit: Int32 = 100) -> Signal<Void, NoError> { let offset: Signal<(Int32, Int32, Api.InputPeer), NoError> offset = single((holeIndex.timestamp, min(holeIndex.id.id, Int32.max - 1) + 1, Api.InputPeer.inputPeerEmpty), NoError.self) return offset |> mapToSignal { (timestamp, id, peer) -> Signal<Void, NoError> in let searchResult = network.request(Api.functions.messages.search(flags: 0, peer: .inputPeerEmpty, q: "", fromId: nil, topMsgId: nil, filter: .inputMessagesFilterPhoneCalls(flags: 0), minDate: 0, maxDate: holeIndex.timestamp, offsetId: 0, addOffset: 0, limit: limit, maxId: holeIndex.id.id, minId: 0, hash: 0)) |> retryRequest |> mapToSignal { result -> Signal<Void, NoError> in let messages: [Api.Message] let chats: [Api.Chat] let users: [Api.User] switch result { case let .messages(messages: apiMessages, chats: apiChats, users: apiUsers): messages = apiMessages chats = apiChats users = apiUsers case let .messagesSlice(_, _, _, _, messages: apiMessages, chats: apiChats, users: apiUsers): messages = apiMessages chats = apiChats users = apiUsers case let .channelMessages(_, _, _, _, apiMessages, apiChats, apiUsers): messages = apiMessages chats = apiChats users = apiUsers case .messagesNotModified: messages = [] chats = [] users = [] } return postbox.transaction { transaction -> Void in var storeMessages: [StoreMessage] = [] var topIndex: MessageIndex? for message in messages { if let storeMessage = StoreMessage(apiMessage: message) { storeMessages.append(storeMessage) if let index = storeMessage.index, topIndex == nil || index < topIndex! { topIndex = index } } } var updatedIndex: MessageIndex? if let topIndex = topIndex { updatedIndex = topIndex.predecessor() } transaction.replaceGlobalMessageTagsHole(globalTags: [.Calls, .MissedCalls], index: holeIndex, with: updatedIndex, messages: storeMessages) var peers: [Peer] = [] var peerPresences: [PeerId: PeerPresence] = [:] for chat in chats { if let groupOrChannel = parseTelegramGroupOrChannel(chat: chat) { peers.append(groupOrChannel) } } for user in users { if let telegramUser = TelegramUser.merge(transaction.getPeer(user.peerId) as? TelegramUser, rhs: user) { peers.append(telegramUser) if let presence = TelegramUserPresence(apiUser: user) { peerPresences[telegramUser.id] = presence } } } updatePeers(transaction: transaction, peers: peers, update: { _, updated -> Peer in return updated }) updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: peerPresences) } } return searchResult } }
52.307798
345
0.467165
acbac3fe5bc7c34b6caa40f474924681127d0cb0
1,189
/* * Copyright (c) 2020-Present, Okta, Inc. and/or its affiliates. All rights reserved. * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 #if SWIFT_PACKAGE @testable import OktaJWT #else @testable import OktaJWTLib #endif class MockKeyStorageManager: PublicKeyStorageProtocol { var dataDictionary: [String: Data] = [:] func data(with key: String) throws -> Data { if let value = dataDictionary[key]{ return value } return Data() } func delete(with key: String) throws { dataDictionary.removeValue(forKey: key) } func save(data: Data, with key: String) throws { dataDictionary[key] = data } }
32.135135
120
0.699748
f7b27ef349f6985cb3c1e7e2fdf41bbcfcbd3be5
311
// // StringsExtensions.swift // PokemonSDK // // Created by Abbas on 1/6/21. // import Foundation extension String { var url : URL? { get { return URL(string: self) } } } func LocalizedString(_ key: String) -> String { return NSLocalizedString(key, comment: "") }
14.809524
47
0.585209
5bbd82b1fd57c462dd85f9d75f5007fec76525a4
2,121
// // NotificationsVC.swift // Ribbit // // Created by Ahsan Ali on 31/05/2021. // import UIKit class NotificationsVC: UIViewController { // MARK: - Ouletlets @IBOutlet var tableView: UITableView! { didSet { tableView.tableFooterView = UIView() tableView.dataSource = self tableView.delegate = self } } // MARK: - Vars // MARK: - Cycles override func viewDidLoad() { super.viewDidLoad() setupNavTitle() } func setupNavTitle() { let navigationTitleView: NavigationTitleView = .fromNib() self.navigationItem.titleView = navigationTitleView let ticketView: TicketView = .fromNib() ticketView.backgroundTint = ._FFE68B ticketView.titleTint = ._230B34F ticketView.starTint = ._230B34F self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: ticketView) } } extension NotificationsVC: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 75 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: NotificationCell.identifier) as? NotificationCell ?? NotificationCell() return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as? NotificationCell ?? NotificationCell() cell.contentView.backgroundColor = #colorLiteral(red: 0.9568627451, green: 0.9490196078, blue: 1, alpha: 1) } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as? NotificationCell ?? NotificationCell() cell.contentView.backgroundColor = .white } }
35.949153
136
0.682697
9b4a89ba95aa807e9fa293db5ce5892113e7bd5c
862
// // NetworkTool.swift // DouYuTV // // Created by 王建伟 on 2016/11/18. // Copyright © 2016年 jifusheng. All rights reserved. // import UIKit import Alamofire enum HttpMethodType { case get case post } class NetworkTool { class func requestData(urlString: String, type: HttpMethodType, parameters: [String : Any]? = nil, completionHandler: @escaping (_ result : Any) -> Void) { let method = type == .get ? HTTPMethod.get : HTTPMethod.post Alamofire.request(urlString, method: method, parameters: parameters).responseJSON { (response) in guard let result = response.result.value else { print("请求失败\(response.result.error)") return } completionHandler(result) } } }
26.121212
105
0.568445
21c09746b96a3fc3716a41d00f1338f8453f6042
147
// // dummy.swift // AudioVerse // // Created by AV Media on 5/29/18. // Copyright © 2018 Facebook. All rights reserved. // import Foundation
14.7
51
0.659864
90b131cad5498c7b6caa4955a344918e11831d7d
9,861
// // LibraryViewController.swift // Quaggify // // Created by Jonathan Bijos on 31/01/17. // Copyright © 2017 Quaggie. All rights reserved. // import UIKit class LibraryViewController: ViewController { var spotifyObject: SpotifyObject<Playlist>? var playlists: [Playlist] = [] { didSet { collectionView.reloadData() } } lazy var logoutButton: UIBarButtonItem = { let button = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logout)) button.tintColor = ColorPalette.white return button }() var limit = 20 var offset = 0 var isFetching = false let lineSpacing: CGFloat = 16 let interItemSpacing: CGFloat = 8 let contentInset: CGFloat = 8 lazy var refreshControl: UIRefreshControl = { let rc = UIRefreshControl() rc.addTarget(self, action: #selector(refreshPlaylists), for: .valueChanged) return rc }() lazy var collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.scrollDirection = .vertical flowLayout.minimumLineSpacing = self.lineSpacing flowLayout.minimumInteritemSpacing = self.interItemSpacing let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout) cv.addSubview(self.refreshControl) cv.keyboardDismissMode = .onDrag cv.alwaysBounceVertical = true cv.showsVerticalScrollIndicator = false cv.contentInset = UIEdgeInsets(top: self.contentInset, left: self.contentInset, bottom: self.contentInset, right: self.contentInset) cv.backgroundColor = .clear cv.delegate = self cv.dataSource = self cv.register(PlaylistCell.self, forCellWithReuseIdentifier: PlaylistCell.identifier) cv.register(LoadingFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: LoadingFooterView.identifier) return cv }() // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() setupViews() addListeners() fetchPlaylists() addCreateNewPlaylistCell() } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { collectionView.collectionViewLayout.invalidateLayout() } // MARK: Layout override func setupViews() { super.setupViews() navigationItem.title = "Your Library".uppercased() navigationItem.rightBarButtonItem = logoutButton view.addSubview(collectionView) collectionView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) } } // MARK: Actions extension LibraryViewController { func addCreateNewPlaylistCell () { if let createNewPlaylistItem = Playlist(JSON: ["name": "Create new playlist"]) { playlists.append(createNewPlaylistItem) } } @objc func logout () { SpotifyService.shared.logout() } func addListeners () { NotificationCenter.default.addObserver(self, selector: #selector(onUserPlaylistUpdate), name: .onUserPlaylistUpdate, object: nil) } @objc func onUserPlaylistUpdate (notification: Notification) { guard let playlist = notification.object as? Playlist else { return } if playlists[safe: 1] != nil { playlists.insert(playlist, at: 1) collectionView.reloadData() } } func fetchPlaylists () { isFetching = true print("Fetching albums offset(\(offset)) ") API.fetchCurrentUsersPlaylists(limit: limit, offset: offset) { [weak self] (spotifyObject, error) in guard let strongSelf = self else { return } strongSelf.isFetching = false strongSelf.refreshControl.endRefreshing() strongSelf.offset += strongSelf.limit if let error = error { print(error) Alert.shared.show(title: "Error", message: "Error communicating with the server") } else if let items = spotifyObject?.items { strongSelf.playlists.append(contentsOf: items) strongSelf.spotifyObject = spotifyObject } } } @objc func refreshPlaylists () { if isFetching { return } isFetching = true print("Refreshing playlists") API.fetchCurrentUsersPlaylists(limit: limit, offset: 0) { [weak self] (spotifyObject, error) in guard let strongSelf = self else { return } strongSelf.isFetching = false strongSelf.refreshControl.endRefreshing() strongSelf.offset = strongSelf.limit if let error = error { print(error) Alert.shared.show(title: "Error", message: "Error communicating with the server") } else if let items = spotifyObject?.items { strongSelf.playlists.removeAll() strongSelf.addCreateNewPlaylistCell() strongSelf.playlists.append(contentsOf: items) strongSelf.spotifyObject = spotifyObject } } } func showNewPlaylistModal () { let alertController = UIAlertController(title: "Create new Playlist".uppercased(), message: nil, preferredStyle: .alert) alertController.addTextField { textfield in textfield.placeholder = "Playlist name" textfield.addTarget(self, action: #selector(self.textDidChange(textField:)), for: .editingChanged) } let cancelAction = UIAlertAction(title: "Cancel".uppercased(), style: .destructive, handler: nil) let createAction = UIAlertAction(title: "Create".uppercased(), style: .default) { _ in if let textfield = alertController.textFields?.first, let playlistName = textfield.text { API.createNewPlaylist(name: playlistName) { [weak self] (playlist, error) in if let error = error { print(error) // Showing error message Alert.shared.show(title: "Error", message: "Error communicating with the server") } else if let playlist = playlist { if self?.playlists[safe: 1] != nil { self?.collectionView.performBatchUpdates({ self?.playlists.insert(playlist, at: 1) self?.collectionView.insertItems(at: [IndexPath(item: 1, section: 0)]) }, completion: nil) } } } } } createAction.isEnabled = false alertController.addAction(cancelAction) alertController.addAction(createAction) present(alertController, animated: true, completion: nil) } @objc func textDidChange (textField: UITextField) { if let topVc = UIApplication.topViewController() as? UIAlertController, let createAction = topVc.actions[safe: 1] { if let text = textField.text, text != "" { createAction.isEnabled = true } else { createAction.isEnabled = false } } } } // MARK: UICollectionViewDelegate extension LibraryViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.item == 0 { showNewPlaylistModal() } else { let playlistVC = PlaylistViewController() playlistVC.playlist = playlists[safe: indexPath.item] navigationController?.pushViewController(playlistVC, animated: true) } } } // MARK: UICollectionViewDataSource extension LibraryViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return playlists.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PlaylistCell.identifier, for: indexPath) as? PlaylistCell { let playlist = playlists[safe: indexPath.item] cell.playlist = playlist // Create ne playlist if indexPath.item == 0 { cell.imageView.image = #imageLiteral(resourceName: "icon_add_playlist").withRenderingMode(.alwaysTemplate) cell.subTitleLabel.isHidden = true cell.imageView.tintColor = ColorPalette.white } if let totalItems = spotifyObject?.items?.count, indexPath.item == totalItems - 1, spotifyObject?.next != nil { if !isFetching { fetchPlaylists() } } return cell } return UICollectionViewCell() } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionFooter: if let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: LoadingFooterView.identifier, for: indexPath) as? LoadingFooterView { return footerView } default: break } return UICollectionReusableView() } } // MARK: UICollectionViewDelegateFlowLayout extension LibraryViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width - (contentInset * 2), height: 72) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { if spotifyObject?.next != nil { return CGSize(width: view.frame.width, height: 36) } return .zero } } extension LibraryViewController: ScrollDelegate { func scrollToTop() { if spotifyObject?.items?.count ?? 0 > 0 { collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: true) } } }
33.540816
223
0.699929
760452336dc0b1b8941b47dba33a6a2c2ae5776d
1,259
// // Pitch_PerfectUITests.swift // Pitch PerfectUITests // // Created by Carmen Berros on 13/10/15. // Copyright © 2015 mcberros. All rights reserved. // import XCTest class Pitch_PerfectUITests: 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. } }
34.027027
182
0.666402
c1772d5c0fa0b1068854ebe73f84c3757cdac724
262
// // Int64Message.swift // // Created by wesgoodhoofd on 2019-01-22. // import UIKit import ObjectMapper public class Int64Message: RBSMessage { public var data: int64 = 0 public override func mapping(map: Map) { data <- map["data"] } }
14.555556
44
0.652672
75fed6b37052dd9c7edbba6311f3ed606622d9da
6,805
// // DBManager.swift // DataBase // // Created by HeMu on 05/07/17. // Copyright © 2017 HeMu. All rights reserved. // import UIKit class DBManager: NSObject { static let shared : DBManager = { let instance = DBManager() return instance }() var pathToDatabase: String! let databaseFileName = "DataBase.sqlite" var database:FMDatabase! override init() { super.init() let documentsDirectory = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString) as String pathToDatabase = documentsDirectory.appending("/\(databaseFileName)") // UserDefaultsModel.shared.setUserDefaultsValues(value: "\(self.getDocumentsDirectory())", key: "localDBBaseURL") print(pathToDatabase) } //register let person_id = "p_id" let person_Fname = "F_Name" let person_Lname = "L_Name" let person_city = "city" let person_address = "address" func createDatabase() -> Bool { var created = false if !FileManager.default.fileExists(atPath: pathToDatabase) { database = FMDatabase(path: pathToDatabase!) if database != nil { // Open the database. if database.open() { let createRegisterTable = "create table person (\(person_id) integer primary key autoincrement not null, \(person_Fname) text, \(person_Lname) text , \(person_city) text , \(person_address) text )" do { try database.executeUpdate(createRegisterTable, values: nil) created = true } catch { print("Could not create table.") print(error.localizedDescription) } database.close() } else { print("Could not open the database.") } } } return created } func insertIntoPerson(p_info : NSDictionary ,completion : @escaping () -> Void) { if openDatabase(){ let p_fname = p_info.value(forKey: "p_fname") as! String let p_lname = p_info.value(forKey: "p_lname") as! String let p_add = p_info.value(forKey: "p_add") as! String let p_city = p_info.value(forKey: "p_city") as! String let sql = "INSERT INTO person ('\(person_Fname)','\(person_Lname)','\(person_city)','\(person_address)') VALUES('\(p_fname)','\(p_lname)','\(p_city)','\(p_add)')" do { try database.executeUpdate(sql, values: nil) } catch { print("error in insert \n\n\n======== \(error.localizedDescription) ") } database.close() } completion() } func UpdateInfoPerson(p_info : NSDictionary ,completion : @escaping () -> Void) { if openDatabase() { let p_id = p_info.value(forKey: "p_id") as! String let p_fname = p_info.value(forKey: "p_fname") as! String let p_lname = p_info.value(forKey: "p_lname") as! String let p_add = p_info.value(forKey: "p_add") as! String let p_city = p_info.value(forKey: "p_city") as! String let sql = "UPDATE person SET '\(person_Fname)' = '\(p_fname)','\(person_Lname)' = '\(p_lname)' ,'\(person_city)' = '\(p_city)','\(person_address)' = '\(p_add)' where p_id = '\(p_id)' " do { try database.executeUpdate(sql, values: nil) } catch { print("error in insert \n\n\n======== \(error.localizedDescription) ") } database.close() } completion() } func removeInfoPerson(p_info : NSDictionary ,completion : @escaping () -> Void) { if openDatabase() { let p_id = p_info.value(forKey: "p_id") as! String let sql = "DELETE From person where p_id = '\(p_id)' " do { try database.executeUpdate(sql, values: nil) } catch { print("error in insert \n\n\n======== \(error.localizedDescription) ") } database.close() } completion() } func insertIntoPerson(completion : @escaping () -> Void) { if openDatabase() { let sql = "Select * From person" do { try database.executeQuery(sql, values: nil) } catch { print("error in insert \n\n\n======== \(error.localizedDescription) ") } database.close() } completion() } func getPersonInfo(completion : @escaping (_ result : NSMutableArray) -> Void ) { var result : FMResultSet let person_data : NSMutableArray = NSMutableArray() if openDatabase() { do { let sql = "Select * From person Order By F_Name ASC" result = try database.executeQuery(sql, values: nil) while (result.next()) { let id = Int(result.int(forColumn: self.person_id)) let Fname = result.string(forColumn: self.person_Fname) let Lname = result.string(forColumn: self.person_Lname) let city = result.string(forColumn: self.person_city) let address = result.string(forColumn: self.person_address) let person : PersonModel = PersonModel.init(person_id: "\(id)", person_Fname: Fname!, person_Lname: Lname!, person_city: city!, person_address: address!) person_data.add(person) } } catch { print("error \(error.localizedDescription)") } database.close() } completion(person_data as NSMutableArray) } func checkDbExsistence() -> Bool{ var exsist = false if FileManager.default.fileExists(atPath: pathToDatabase) { exsist = true } return exsist } func openDatabase() -> Bool { if database == nil { if FileManager.default.fileExists(atPath: pathToDatabase) { database = FMDatabase(path: pathToDatabase) } } if database != nil { if database.open() { return true } } return false } }
35.259067
217
0.513299
bbe9e7bcb247d2c66e3e2da668141d285e27e566
1,010
// // AwesomeDataSourceTests.swift // AwesomeDataSourceTests // // Created by Vincent Lin on 2018/6/25. // Copyright © 2018 Vincent Lin. All rights reserved. // import XCTest @testable import AwesomeDataSource class AwesomeDataSourceTests: 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. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.297297
111
0.646535
29a11041f77907c3bd290ad3d36adc7ff388f8c5
3,198
// // ViewController.swift // GitHub Friends // // Created by Pedro Trujillo on 10/29/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit class DetailViewController: UIViewController { var userImageView:UIImageView! var imagePath = "gravatar.png" var userImage:UIImage! var gitHubFriend: GitHubFriend! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.whiteColor() // self.loadImage(gitHubFriend.largeImageURL) self.setLabels(gitHubFriend.login,x: view.center.x, y: userImageView.center.y * 0.4) self.setLabels(gitHubFriend.name,x: view.center.x, y: userImageView.center.y * 1.6) self.setLabels(gitHubFriend.email,x: view.center.x, y: userImageView.center.y * 1.7) self.setLabels(gitHubFriend.location,x: view.center.x, y: userImageView.center.y * 1.8) self.setLabels(gitHubFriend.company,x: view.center.x, y: userImageView.center.y * 1.9) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setLabels( labelString:String = "Penpenuche", x :CGFloat = 0, y :CGFloat = 0) { let loginLabel:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 60)) //self.loginLabel.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width * 0.9 , height: self.view.frame.size.width * 0.1) loginLabel.text = labelString loginLabel.center.x = x loginLabel.center.y = y loginLabel.numberOfLines = 1 loginLabel.textAlignment = .Center view.addSubview(loginLabel) } func loadImage(var ImagePath:String = "") { if ImagePath == "" {ImagePath = self.imagePath} else {self.imagePath = ImagePath} if let url = NSURL(string: ImagePath) { if let data = NSData(contentsOfURL: url) { self.userImage = UIImage(data: data) self.userImageView = UIImageView(image: userImage!) self.userImageView!.contentMode = UIViewContentMode.ScaleAspectFit self.userImageView.frame = CGRect(x: 0, y: 0 , width: self.view.frame.size.width * 0.9 , height: self.view.frame.size.width * 0.9 ) self.userImageView.center.x = view.center.x self.userImageView.center.y = UIScreen.mainScreen().bounds.height * 0.5 view.addSubview(userImageView) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
32.632653
147
0.611945
087f054a59b796aec3fe5b677c9de5bfeb32f9f2
552
// // SettingsView.swift // MoBlog // // Created by Filip Palmqvist on 2020-04-18. // Copyright © 2020 Filip Palmqvist. All rights reserved. // import SwiftUI struct SettingsView: View { var body: some View { MoBlogView { HStack { Text("Subscriptions") .font(.title) .bold() Spacer() } } } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView() } }
18.4
58
0.509058
16794e350ae281099ec490f9d8e05340529f30ac
6,008
// // Linkage.swift // HealthSoftware // // Generated from FHIR 3.0.1.11917 (http://hl7.org/fhir/StructureDefinition/Linkage) // Copyright 2020 Apple Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import FMCore /** Links records for 'same' item. Identifies two or more records (resource instances) that are referring to the same real-world "occurrence". */ open class Linkage: DomainResource { override open class var resourceType: ResourceType { return .linkage } /// Whether this linkage assertion is active or not public var active: FHIRPrimitive<FHIRBool>? /// Who is responsible for linkages public var author: Reference? /// Item to be linked public var item: [LinkageItem] /// Designated initializer taking all required properties public init(item: [LinkageItem]) { self.item = item super.init() } /// Convenience initializer public convenience init( active: FHIRPrimitive<FHIRBool>? = nil, author: Reference? = nil, contained: [ResourceProxy]? = nil, `extension`: [Extension]? = nil, id: FHIRPrimitive<FHIRString>? = nil, implicitRules: FHIRPrimitive<FHIRURI>? = nil, item: [LinkageItem], language: FHIRPrimitive<FHIRString>? = nil, meta: Meta? = nil, modifierExtension: [Extension]? = nil, text: Narrative? = nil) { self.init(item: item) self.active = active self.author = author self.contained = contained self.`extension` = `extension` self.id = id self.implicitRules = implicitRules self.language = language self.meta = meta self.modifierExtension = modifierExtension self.text = text } // MARK: - Codable private enum CodingKeys: String, CodingKey { case active; case _active case author case item } /// Initializer for Decodable public required init(from decoder: Decoder) throws { let _container = try decoder.container(keyedBy: CodingKeys.self) // Decode all our properties self.active = try FHIRPrimitive<FHIRBool>(from: _container, forKeyIfPresent: .active, auxiliaryKey: ._active) self.author = try Reference(from: _container, forKeyIfPresent: .author) self.item = try [LinkageItem](from: _container, forKey: .item) try super.init(from: decoder) } /// Encodable public override func encode(to encoder: Encoder) throws { var _container = encoder.container(keyedBy: CodingKeys.self) // Encode all our properties try active?.encode(on: &_container, forKey: .active, auxiliaryKey: ._active) try author?.encode(on: &_container, forKey: .author) try item.encode(on: &_container, forKey: .item) try super.encode(to: encoder) } // MARK: - Equatable & Hashable public override func isEqual(to _other: Any?) -> Bool { guard let _other = _other as? Linkage else { return false } guard super.isEqual(to: _other) else { return false } return active == _other.active && author == _other.author && item == _other.item } public override func hash(into hasher: inout Hasher) { super.hash(into: &hasher) hasher.combine(active) hasher.combine(author) hasher.combine(item) } } /** Item to be linked. Identifies one of the records that is considered to refer to the same real-world occurrence as well as how the items hould be evaluated within the collection of linked items. */ open class LinkageItem: BackboneElement { /// Distinguishes which item is "source of truth" (if any) and which items are no longer considered to be current /// representations. public var type: FHIRPrimitive<LinkageType> /// Resource being linked public var resource: Reference /// Designated initializer taking all required properties public init(resource: Reference, type: FHIRPrimitive<LinkageType>) { self.resource = resource self.type = type super.init() } /// Convenience initializer public convenience init( `extension`: [Extension]? = nil, id: FHIRPrimitive<FHIRString>? = nil, modifierExtension: [Extension]? = nil, resource: Reference, type: FHIRPrimitive<LinkageType>) { self.init(resource: resource, type: type) self.`extension` = `extension` self.id = id self.modifierExtension = modifierExtension } // MARK: - Codable private enum CodingKeys: String, CodingKey { case resource case type; case _type } /// Initializer for Decodable public required init(from decoder: Decoder) throws { let _container = try decoder.container(keyedBy: CodingKeys.self) // Decode all our properties self.resource = try Reference(from: _container, forKey: .resource) self.type = try FHIRPrimitive<LinkageType>(from: _container, forKey: .type, auxiliaryKey: ._type) try super.init(from: decoder) } /// Encodable public override func encode(to encoder: Encoder) throws { var _container = encoder.container(keyedBy: CodingKeys.self) // Encode all our properties try resource.encode(on: &_container, forKey: .resource) try type.encode(on: &_container, forKey: .type, auxiliaryKey: ._type) try super.encode(to: encoder) } // MARK: - Equatable & Hashable public override func isEqual(to _other: Any?) -> Bool { guard let _other = _other as? LinkageItem else { return false } guard super.isEqual(to: _other) else { return false } return resource == _other.resource && type == _other.type } public override func hash(into hasher: inout Hasher) { super.hash(into: &hasher) hasher.combine(resource) hasher.combine(type) } }
29.024155
117
0.706225
792f8766d0c864e1ed8a8f3b4348e73618a6622d
2,658
// // HUDWindow.swift // PKHUD // // Created by Philip Kluz on 6/16/14. // Copyright (c) 2014 NSExceptional. All rights reserved. // import UIKit /// The window used to display the PKHUD within. Placed atop the applications main window. internal class Window: UIWindow { internal let frameView: FrameView internal init(frameView: FrameView = FrameView()) { self.frameView = frameView super.init(frame: UIApplication.sharedApplication().delegate!.window!!.bounds) commonInit() } required init?(coder aDecoder: NSCoder) { frameView = FrameView() super.init(coder: aDecoder) commonInit() } private func commonInit() { rootViewController = WindowRootViewController() windowLevel = UIWindowLevelNormal + 1.0 backgroundColor = UIColor.clearColor() addSubview(backgroundView) addSubview(frameView) } internal override func layoutSubviews() { super.layoutSubviews() frameView.center = center backgroundView.frame = bounds } internal func showFrameView() { layer.removeAllAnimations() makeKeyAndVisible() frameView.center = center frameView.alpha = 1.0 hidden = false } private var willHide = false internal func hideFrameView(animated anim: Bool) { let completion: (finished: Bool) -> (Void) = { finished in if finished { self.hidden = true self.resignKeyWindow() } self.willHide = false } if hidden { return } willHide = true if anim { UIView.animateWithDuration(0.8, animations: { self.frameView.alpha = 0.0 }, completion: completion) } else { completion(finished: true) } } private let backgroundView: UIView = { let view = UIView() view.backgroundColor = UIColor(white:0.0, alpha:0.25) view.alpha = 0.0; return view; }() internal func showBackground(animated anim: Bool) { if anim { UIView.animateWithDuration(0.175) { self.backgroundView.alpha = 1.0 } } else { backgroundView.alpha = 1.0; } } internal func hideBackground(animated anim: Bool) { if anim { UIView.animateWithDuration(0.65) { self.backgroundView.alpha = 0.0 } } else { backgroundView.alpha = 0.0; } } }
25.805825
111
0.557938
18fb3de02ffdb527fd2d01ef0774c52dc1c9b03d
786
// // AddAddressTableCell.swift // O3 // // Created by Andrei Terentiev on 9/26/17. // Copyright © 2017 drei. All rights reserved. // import Foundation import UIKit protocol AddAddressCellDelegate: class { func segueToAdd() } class AddAddressTableViewCell: UITableViewCell { @IBOutlet weak var addAddressButton: ShadowedButton! weak var delegate: AddAddressCellDelegate? override func awakeFromNib() { addAddressButton.setTitle(SettingsStrings.addWatchAddressButton, for: UIControlState()) contentView.theme_backgroundColor = O3Theme.backgroundColorPicker theme_backgroundColor = O3Theme.backgroundColorPicker super.awakeFromNib() } @IBAction func addAddressTapped(_ sender: Any) { delegate?.segueToAdd() } }
25.354839
95
0.731552
feab128f138a1fd7661cc516c4c8b081d0979641
820
// // Appearance.swift // ToastNotifications // // Created by pman215 on 8/8/16. // Copyright © 2016 Erick Andrade. All rights reserved. // import UIKit struct Appearance { let style: Style let position: Position let size: Size init() { let style = Style() let position = Position.center let size = Size.relative(xRatio: 0.9, yRatio: 0.1) self.init(style: style, position: position, size: size) } init(style: Style, position: Position, size: Size) { self.style = style self.position = position self.size = size } func configure(with view: UIView) { style.configure(view: view) position.addPositionConstraints(to: view) size.addSizeConstraints(to: view) } }
21.025641
58
0.589024
7666cad6a6929e05bb284fa562aab8f24f7544cc
444
// // Utility.swift // insta-search // // Created by Blaine Rothrock on 12/17/17. // Copyright © 2017 Blaine Rothrock. All rights reserved. // import UIKit extension UIColor { static let lightPink = UIColor(red: 236/255, green: 92/255, blue: 110/255, alpha: 1) static let john = UIColor(red: 67/255, green: 61/255, blue: 63/255, alpha: 1) static let wafer = UIColor(red: 206/255, green: 188/255, blue: 179/255, alpha: 1.0) }
26.117647
88
0.666667
9c840cfe10675a828926e25799dae66fcb795395
5,382
// // Squidward // // Copyright (c) 2019 - Present Brandon Erbschloe - https://github.com/berbschloe // // 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 /// Any object that can store a group of constraints public protocol LayoutConstraintGroup: AnyObject { /// The constraints that are grouped together. var constraints: [NSLayoutConstraint] { get } } extension LayoutConstraintGroup { /** Activates the current constraint then returns them to allow for assignment or method chaining. - returns: The activated constraints. */ @discardableResult public func activate() -> Self { constraints.forEach { $0.isActive = true } return self } /** Dectivates the current constraints then returns them to allow for assignment or method chaining. - returns: The deactivated constraints. */ @discardableResult public func deactivate() -> Self { constraints.forEach { $0.isActive = true } return self } /** Sets the priority for the current constraints then returns them to allow for assignment or method chaining. - parameter priority: The priority of the constraints. - returns: The deactivated constraints. */ @discardableResult public func prioritize(at priority: UILayoutPriority) -> Self { constraints.forEach { $0.priority = priority } return self } /** Assigns passed in constraint to self. This allows for fluent assignment inside NSLayoutConstraint.activate() - parameter constraint: The constraint address that self will be assigned to. - returns: self */ @discardableResult public func assign(to target: inout Self) -> Self { target = self return self } /** Assigns passed in constraint to self. This allows for fluent assignment inside NSLayoutConstraint.activate() - parameter constraint: The constraint address that self will be assigned to. - returns: self */ @discardableResult public func assign(to target: inout Self?) -> Self { target = self return self } } extension NSLayoutConstraint: LayoutConstraintGroup { /// Returns a list of one constraint only containing itself. public var constraints: [NSLayoutConstraint] { return [self] } } extension NSLayoutConstraint { /** Activates a list of constraints. This is much more efficient than calling activate one at a time. - parameter constraints: The list of constraints to actiavte. - parameter priority: The layout priority all the constraints should be activated at. */ public class func activate(_ constraints: [NSLayoutConstraint], at priority: UILayoutPriority) { constraints.forEach { $0.priority = priority } activate(constraints) } /// Activates a block of constraints. public class func activate(@LayoutConstraintBuilder _ constraints: () -> [NSLayoutConstraint]) { activate(constraints()) } /** Activates a list of constraint groups. - parameter constraints: The list of constraint groups to activate. - parameter priority: The layout priority all the constraints should be activated at. */ public class func activate(_ constraints: [LayoutConstraintGroup], at priority: UILayoutPriority = .required) { activate(constraints.flatMap { $0.constraints }, at: priority) } /// Activates a block of constraint groups. public class func activate(@LayoutConstraintGroupBuilder _ constraints: () -> [LayoutConstraintGroup]) { activate(constraints()) } /** Deactivates a list of constraint groups. - parameter constraints: The list of constraint groups to deactivate. */ public class func deactivate(_ constraints: [LayoutConstraintGroup]) { deactivate(constraints.flatMap { return $0.constraints }) } } @resultBuilder public enum LayoutConstraintBuilder { public static func buildBlock(_ partialResults: NSLayoutConstraint...) -> [NSLayoutConstraint] { return partialResults } } @resultBuilder public enum LayoutConstraintGroupBuilder { public static func buildBlock(_ partialResults: LayoutConstraintGroup...) -> [LayoutConstraintGroup] { return partialResults } }
34.063291
115
0.703084
3933a27dfc0532ab043287339271f9506956f729
12,680
// // Coverage.swift // SwiftFHIR // // Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Coverage) on 2019-03-01. // 2019, SMART Health IT. // import Foundation /** Insurance or medical plan or a payment agreement. Financial instrument which may be used to reimburse or pay for health care products and services. Includes both insurance and self-payment. */ open class Coverage: DomainResource { override open class var resourceType: String { get { return "Coverage" } } /// Additional coverage classifications. public var `class`: [CoverageClass]? /// Plan beneficiary. public var beneficiary: Reference? /// Contract details. public var contract: [Reference]? /// Patient payments for services/products. public var costToBeneficiary: [CoverageCostToBeneficiary]? /// Dependent number. public var dependent: FHIRString? /// Business Identifier for the coverage. public var identifier: [Identifier]? /// Insurer network. public var network: FHIRString? /// Relative order of the coverage. public var order: FHIRInteger? /// Issuer of the policy. public var payor: [Reference]? /// Coverage start and end dates. public var period: Period? /// Owner of the policy. public var policyHolder: Reference? /// Beneficiary relationship to the subscriber. public var relationship: CodeableConcept? /// The status of the resource instance. public var status: FinancialResourceStatusCodes? /// Reimbursement to insurer. public var subrogation: FHIRBool? /// Subscriber to the policy. public var subscriber: Reference? /// ID assigned to the subscriber. public var subscriberId: FHIRString? /// Coverage category such as medical or accident. public var type: CodeableConcept? /** Convenience initializer, taking all required properties as arguments. */ public convenience init(beneficiary: Reference, payor: [Reference], status: FinancialResourceStatusCodes) { self.init() self.beneficiary = beneficiary self.payor = payor self.status = status } override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) { super.populate(from: json, context: &instCtx) `class` = createInstances(of: CoverageClass.self, for: "class", in: json, context: &instCtx, owner: self) ?? `class` beneficiary = createInstance(type: Reference.self, for: "beneficiary", in: json, context: &instCtx, owner: self) ?? beneficiary if nil == beneficiary && !instCtx.containsKey("beneficiary") { instCtx.addError(FHIRValidationError(missing: "beneficiary")) } contract = createInstances(of: Reference.self, for: "contract", in: json, context: &instCtx, owner: self) ?? contract costToBeneficiary = createInstances(of: CoverageCostToBeneficiary.self, for: "costToBeneficiary", in: json, context: &instCtx, owner: self) ?? costToBeneficiary dependent = createInstance(type: FHIRString.self, for: "dependent", in: json, context: &instCtx, owner: self) ?? dependent identifier = createInstances(of: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier network = createInstance(type: FHIRString.self, for: "network", in: json, context: &instCtx, owner: self) ?? network order = createInstance(type: FHIRInteger.self, for: "order", in: json, context: &instCtx, owner: self) ?? order payor = createInstances(of: Reference.self, for: "payor", in: json, context: &instCtx, owner: self) ?? payor if (nil == payor || payor!.isEmpty) && !instCtx.containsKey("payor") { instCtx.addError(FHIRValidationError(missing: "payor")) } period = createInstance(type: Period.self, for: "period", in: json, context: &instCtx, owner: self) ?? period policyHolder = createInstance(type: Reference.self, for: "policyHolder", in: json, context: &instCtx, owner: self) ?? policyHolder relationship = createInstance(type: CodeableConcept.self, for: "relationship", in: json, context: &instCtx, owner: self) ?? relationship status = createEnum(type: FinancialResourceStatusCodes.self, for: "status", in: json, context: &instCtx) ?? status if nil == status && !instCtx.containsKey("status") { instCtx.addError(FHIRValidationError(missing: "status")) } subrogation = createInstance(type: FHIRBool.self, for: "subrogation", in: json, context: &instCtx, owner: self) ?? subrogation subscriber = createInstance(type: Reference.self, for: "subscriber", in: json, context: &instCtx, owner: self) ?? subscriber subscriberId = createInstance(type: FHIRString.self, for: "subscriberId", in: json, context: &instCtx, owner: self) ?? subscriberId type = createInstance(type: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type } override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) { super.decorate(json: &json, errors: &errors) arrayDecorate(json: &json, withKey: "class", using: self.`class`, errors: &errors) self.beneficiary?.decorate(json: &json, withKey: "beneficiary", errors: &errors) if nil == self.beneficiary { errors.append(FHIRValidationError(missing: "beneficiary")) } arrayDecorate(json: &json, withKey: "contract", using: self.contract, errors: &errors) arrayDecorate(json: &json, withKey: "costToBeneficiary", using: self.costToBeneficiary, errors: &errors) self.dependent?.decorate(json: &json, withKey: "dependent", errors: &errors) arrayDecorate(json: &json, withKey: "identifier", using: self.identifier, errors: &errors) self.network?.decorate(json: &json, withKey: "network", errors: &errors) self.order?.decorate(json: &json, withKey: "order", errors: &errors) arrayDecorate(json: &json, withKey: "payor", using: self.payor, errors: &errors) if nil == payor || self.payor!.isEmpty { errors.append(FHIRValidationError(missing: "payor")) } self.period?.decorate(json: &json, withKey: "period", errors: &errors) self.policyHolder?.decorate(json: &json, withKey: "policyHolder", errors: &errors) self.relationship?.decorate(json: &json, withKey: "relationship", errors: &errors) self.status?.decorate(json: &json, withKey: "status", errors: &errors) if nil == self.status { errors.append(FHIRValidationError(missing: "status")) } self.subrogation?.decorate(json: &json, withKey: "subrogation", errors: &errors) self.subscriber?.decorate(json: &json, withKey: "subscriber", errors: &errors) self.subscriberId?.decorate(json: &json, withKey: "subscriberId", errors: &errors) self.type?.decorate(json: &json, withKey: "type", errors: &errors) } } /** Additional coverage classifications. A suite of underwriter specific classifiers. */ open class CoverageClass: BackboneElement { override open class var resourceType: String { get { return "CoverageClass" } } /// Human readable description of the type and value. public var name: FHIRString? /// Type of class such as 'group' or 'plan'. public var type: CodeableConcept? /// Value associated with the type. public var value: FHIRString? /** Convenience initializer, taking all required properties as arguments. */ public convenience init(type: CodeableConcept, value: FHIRString) { self.init() self.type = type self.value = value } override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) { super.populate(from: json, context: &instCtx) name = createInstance(type: FHIRString.self, for: "name", in: json, context: &instCtx, owner: self) ?? name type = createInstance(type: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type if nil == type && !instCtx.containsKey("type") { instCtx.addError(FHIRValidationError(missing: "type")) } value = createInstance(type: FHIRString.self, for: "value", in: json, context: &instCtx, owner: self) ?? value if nil == value && !instCtx.containsKey("value") { instCtx.addError(FHIRValidationError(missing: "value")) } } override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) { super.decorate(json: &json, errors: &errors) self.name?.decorate(json: &json, withKey: "name", errors: &errors) self.type?.decorate(json: &json, withKey: "type", errors: &errors) if nil == self.type { errors.append(FHIRValidationError(missing: "type")) } self.value?.decorate(json: &json, withKey: "value", errors: &errors) if nil == self.value { errors.append(FHIRValidationError(missing: "value")) } } } /** Patient payments for services/products. A suite of codes indicating the cost category and associated amount which have been detailed in the policy and may have been included on the health card. */ open class CoverageCostToBeneficiary: BackboneElement { override open class var resourceType: String { get { return "CoverageCostToBeneficiary" } } /// Exceptions for patient payments. public var exception: [CoverageCostToBeneficiaryException]? /// Cost category. public var type: CodeableConcept? /// The amount or percentage due from the beneficiary. public var valueMoney: Money? /// The amount or percentage due from the beneficiary. public var valueQuantity: Quantity? /** Convenience initializer, taking all required properties as arguments. */ public convenience init(value: Any) { self.init() if let value = value as? Quantity { self.valueQuantity = value } else if let value = value as? Money { self.valueMoney = value } else { fhir_warn("Type “\(Swift.type(of: value))” for property “\(value)” is invalid, ignoring") } } override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) { super.populate(from: json, context: &instCtx) exception = createInstances(of: CoverageCostToBeneficiaryException.self, for: "exception", in: json, context: &instCtx, owner: self) ?? exception type = createInstance(type: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type valueMoney = createInstance(type: Money.self, for: "valueMoney", in: json, context: &instCtx, owner: self) ?? valueMoney valueQuantity = createInstance(type: Quantity.self, for: "valueQuantity", in: json, context: &instCtx, owner: self) ?? valueQuantity // check if nonoptional expanded properties (i.e. at least one "answer" for "answer[x]") are present if nil == self.valueQuantity && nil == self.valueMoney { instCtx.addError(FHIRValidationError(missing: "value[x]")) } } override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) { super.decorate(json: &json, errors: &errors) arrayDecorate(json: &json, withKey: "exception", using: self.exception, errors: &errors) self.type?.decorate(json: &json, withKey: "type", errors: &errors) self.valueMoney?.decorate(json: &json, withKey: "valueMoney", errors: &errors) self.valueQuantity?.decorate(json: &json, withKey: "valueQuantity", errors: &errors) // check if nonoptional expanded properties (i.e. at least one "value" for "value[x]") are present if nil == self.valueQuantity && nil == self.valueMoney { errors.append(FHIRValidationError(missing: "value[x]")) } } } /** Exceptions for patient payments. A suite of codes indicating exceptions or reductions to patient costs and their effective periods. */ open class CoverageCostToBeneficiaryException: BackboneElement { override open class var resourceType: String { get { return "CoverageCostToBeneficiaryException" } } /// The effective period of the exception. public var period: Period? /// Exception category. public var type: CodeableConcept? /** Convenience initializer, taking all required properties as arguments. */ public convenience init(type: CodeableConcept) { self.init() self.type = type } override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) { super.populate(from: json, context: &instCtx) period = createInstance(type: Period.self, for: "period", in: json, context: &instCtx, owner: self) ?? period type = createInstance(type: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type if nil == type && !instCtx.containsKey("type") { instCtx.addError(FHIRValidationError(missing: "type")) } } override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) { super.decorate(json: &json, errors: &errors) self.period?.decorate(json: &json, withKey: "period", errors: &errors) self.type?.decorate(json: &json, withKey: "type", errors: &errors) if nil == self.type { errors.append(FHIRValidationError(missing: "type")) } } }
39.501558
162
0.722555
c1127684ecb2cee8b029213d4702d89cd331d546
1,431
// // iMileDriverUITests.swift // iMileDriverUITests // // Created by Takeshi on 2/14/22. // import XCTest class iMileDriverUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } }
33.27907
182
0.657582
1650ac9413b0438a6df4a3212f0ed15efc34a0f4
1,378
// // ChildViewController.swift // PriconneDB // // Created by Kazutoshi Baba on 2019/05/02. // Copyright © 2019 Kazutoshi Baba. All rights reserved. // import UIKit extension UIViewController { // MARK: - Methods public func addFullScreen(childViewController child: UIViewController, to view: UIView) { guard child.parent == nil else { return } addChild(child) view.addSubview(child.view) child.view.translatesAutoresizingMaskIntoConstraints = false let constraints = [ view.leadingAnchor.constraint(equalTo: child.view.leadingAnchor), view.trailingAnchor.constraint(equalTo: child.view.trailingAnchor), view.topAnchor.constraint(equalTo: child.view.topAnchor), view.bottomAnchor.constraint(equalTo: child.view.bottomAnchor) ] constraints.forEach { $0.isActive = true } view.addConstraints(constraints) child.didMove(toParent: self) } public func remove(childViewController child: UIViewController?) { guard let child = child else { return } guard child.parent != nil else { return } child.willMove(toParent: nil) child.view.removeFromSuperview() child.removeFromParent() } }
28.122449
93
0.617562
db8b11f13327076a935521f258ba406de31428cf
257
// RUN: %target-typecheck-verify-swift -module-name test -primary-file %S/Inputs/require-layout-call-result-primary.swift class C<T> { dynamic func broken() { } // expected-error{{'dynamic'}} } func bar<T, U: C<T>>(_ t: T, _ u: U) -> C<T> { return u }
28.555556
121
0.645914
33d6c4ed833b9ed03fd9857e2ee2c543853e5414
3,174
// // MsgpackTranslator + wrapingMeta.swift // swift-msgpack-serialization-iOS // // Created by cherrywoods on 02.11.17. // import Foundation import MetaSerialization extension MsgpackTranslator { func wrappingMeta<T>(for value: T) -> Meta? { if value is GenericNil { // msgpack supports nil return NilMeta.nil } else if value is Bool { // there's no invalid configuration for a Bool return SimpleGenericMeta<T>() } else if value is Int || value is UInt || value is Int8 || value is UInt8 || value is Int16 || value is UInt16 || value is Int32 || value is UInt32 || value is Int64 || value is UInt64 { // note that there is no invalid configuration for an int, // that might be detected during the intermediate encoding step return SimpleGenericMeta<T>() } else if value is Float || value is Double { // both Float (float 32) and Double (float 64) are supported by msgpack // (including infinity, negative infinity and NaN) return SimpleGenericMeta<T>() } else if value is String { // StrFormatFamilyMeta makes sure, // that the given Strings are short enough to be converted to msgpack // (below 2^32 characters). return StringMeta() } else if value is Data && self.optionSet.encodeDataAsBinary { // MsgpackBinaryData makes sure, // that the passed Data is short enough to be converted to msgpack // (below 2^32 bytes). return DataMeta() } else if value is [UInt8] && self.optionSet.encodeDataAsBinary { // same as with Data return ByteArrayMeta() } else if value is Date && self.optionSet.convertSwiftDateToMsgpackTimestamp { // if the option is not set, let Date encode/decode itself // encoding by this frmaework will lead to possible loosy conversion return SimpleGenericMeta<Date>() } else if value is MsgpackExtensionValue { return SimpleGenericMeta<T>() } else if value is Dictionary<AnyHashable, Any> && self.optionSet.encodeDictionarysJavaCompatibel { // provide a msgpack-java compatible encoding for dictionarys // with this meta, we skip the first encoding process and // therefor also the encoding code from Dictionary return SkipMeta() } else { return nil } } func keyedContainerMeta() -> KeyedContainerMeta { return MapMeta() } func generalContainerMeta() -> MapMeta { return MapMeta() } // we use the default implementations for the unkeyedContainer method }
32.721649
107
0.543793
1114108b5c61f1b131912c366efbd5e612f2fdee
2,303
// // SceneDelegate.swift // SwiftComponents // // Created by Tharindu Darshana on 13/12/20. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.45283
147
0.714286
3310755e43347229689a6613699b68d61c5698a6
3,004
// // logger.swift // unchained // // Created by Johannes Schriewer on 17/12/15. // Copyright © 2015 Johannes Schriewer. All rights reserved. // #if os(Linux) import Glibc #else import Darwin #endif import UnchainedFile import UnchainedDate public class Log { public static var logLevel: LogLevel = .Debug public static var logFileName: String? = nil { didSet { self.logFile = nil if let filename = self.logFileName { do { self.logFile = try File(filename: filename, mode: .AppendOnly) } catch { self.logFileName = nil } } } } private static var logFile: File? = nil public enum LogLevel: Int { case Debug = 0 case Info = 1 case Warn = 2 case Error = 3 case Fatal = 4 } public class func debug(msg: Streamable...) { guard Log.logLevel.rawValue <= LogLevel.Debug.rawValue else { return } self.log("DEBUG", msg) } public class func info(msg: Streamable...) { guard Log.logLevel.rawValue <= LogLevel.Info.rawValue else { return } self.log("INFO ", msg) } public class func warn(msg: Streamable...) { guard Log.logLevel.rawValue <= LogLevel.Warn.rawValue else { return } self.log("WARN ", msg) } public class func error(msg: Streamable...) { guard Log.logLevel.rawValue <= LogLevel.Error.rawValue else { return } self.log("ERROR", msg) } public class func fatal(msg: Streamable...) { guard Log.logLevel.rawValue <= LogLevel.Fatal.rawValue else { return } self.log("FATAL", msg) } // MARK: - Private private class func log(level: String, _ msg: [Streamable]) { let date = Date(timestamp: time(nil)) if self.logFile != nil { date.isoDateString!.write(to: &logFile!) " [\(level)]: ".write(to: &logFile!) for item in msg { item.write(to: &logFile!) " ".write(to: &logFile!) } "\n".write(to: &logFile!) } else { if let logFileName = self.logFileName { do { self.logFile = try File(filename: logFileName, mode: .AppendOnly) self.log(level, msg) return } catch { print("\(date.isoDateString!) [FATAL]: Could not open logfile \(logFileName)!") } } print("\(date.isoDateString!) [\(level)]: ", terminator: "") for item in msg { var tmp = "" item.write(to: &tmp) print(tmp + " ", terminator: "") } print("") } } private init() { } }
25.675214
99
0.491012
5b68ea9dc500a0eb9e4fd434400fb03f0f6ab103
5,005
// // FirstViewController.swift // homeswitch // // Created by Moritz Kanzler on 25.03.16. // Copyright © 2016 Moritz Kanzler. All rights reserved. // import UIKit class SwitchesViewController: UIViewController { var switches: [HSSwitch]? { didSet { self.switchTable.reloadData() } } @IBOutlet weak var switchTable: UITableView! @IBOutlet weak var loadingActivity: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() switchTable.dataSource = self switchTable.delegate = self switches = HSSwitch.loadSwitches() loadingActivity.alpha = 0 // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) switches = HSSwitch.loadSwitches() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func toggleAllOff(sender: AnyObject) { let urlStr = ServerGlobal.ServerConnection.serverAddrBaseUrl + "/setSwitch.php?switch_id=all&state=0" let url = NSURL(string: urlStr) let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in // your condition on success and failure } task.resume() } @IBAction func toggleAllOn(sender: AnyObject) { let urlStr = ServerGlobal.ServerConnection.serverAddrBaseUrl + "/setSwitch.php?switch_id=all&state=1" let url = NSURL(string: urlStr) let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in // your condition on success and failure } task.resume() } @IBAction func cancelToSwitchesView(segue: UIStoryboardSegue) { } @IBAction func saveToSwitchesView(segue: UIStoryboardSegue) { if let switchAddController = segue.sourceViewController as? SwitchesAddTableViewController { let sw_name = switchAddController.switchName.text! let sw_sc = switchAddController.switchSystemCode.text! let sw_uc = switchAddController.switchUnitCode.text! let urlStr = ServerGlobal.ServerConnection.serverAddrBaseUrl + "/addSwitch.php?sw_name=" + sw_name + "&sw_label=" + "5" + "&sw_sc=" + sw_sc + "&sw_uc=" + sw_uc let url = NSURL(string: urlStr) let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in self.switches = HSSwitch.loadSwitches() } task.resume() } } } extension SwitchesViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:SwitchTableViewCell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath: indexPath) as! SwitchTableViewCell if let switch_arr = switches { let model = switch_arr[indexPath.row] cell.switchModel = model cell.switchName.text = model.name cell.switchIcon.image = model.typeimage } return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let switch_arr = switches { return switch_arr.count } else { return 0 } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // the cells you would like the actions to appear needs to be editable return true } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let swOn = UITableViewRowAction(style: .Normal , title: " An ") { action, index in if let switch_arr = self.switches { let thisSwitch = switch_arr[indexPath.row] thisSwitch.turnOnOff(true) } tableView.setEditing(false, animated: true) } swOn.backgroundColor = UIColor.init(red: 0/255, green: 153/255, blue: 0/255, alpha: 1.0) let swOff = UITableViewRowAction(style: .Normal, title: " Aus ") { action, index in if let switch_arr = self.switches { let thisSwitch = switch_arr[indexPath.row] thisSwitch.turnOnOff(false) } tableView.setEditing(false, animated: true) } swOff.backgroundColor = UIColor.init(red: 179/255, green: 0/255, blue: 0/255, alpha: 1.0) return [swOff, swOn] } }
33.817568
171
0.610589
2885bba54202aaa9f8020268d9d6217c49a88917
6,756
// Copyright 2016 LinkedIn Corp. // 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. import UIKit /// Runs benchmarks for different kinds of layouts. class BenchmarkViewController: UITableViewController { private let reuseIdentifier = "cell" private let viewControllers: [ViewControllerData] = [ // // Ordered alphabetically // ViewControllerData(title: "Auto Layout", factoryBlock: { viewCount in let data = FeedItemData.generate(count: viewCount) return CollectionViewControllerFeedItemAutoLayoutView(data: data) }), ViewControllerData(title: "FlexLayout 1.3", factoryBlock: { viewCount in let data = FeedItemData.generate(count: viewCount) return CollectionViewControllerFeedItemFlexLayoutView(data: data) }), ViewControllerData(title: "LayoutKit 7.0", factoryBlock: { viewCount in let data = FeedItemData.generate(count: viewCount) return CollectionViewControllerFeedItemLayoutKitView(data: data) }), ViewControllerData(title: "Manual Layout", factoryBlock: { viewCount in let data = FeedItemData.generate(count: viewCount) return CollectionViewControllerFeedItemManualView(data: data) }), ViewControllerData(title: "NKFrameLayoutKit", factoryBlock: { viewCount in let data = FeedItemData.generate(count: viewCount) return CollectionViewControllerFeedItemNKFrameLayoutKitView(data: data) }), ViewControllerData(title: "NotAutoLayout", factoryBlock: { viewCount in let data = FeedItemData.generate(count: viewCount) return CollectionViewControllerFeedItemNotAutoLayoutView(data: data) }), ViewControllerData(title: "PinLayout 1.7", factoryBlock: { viewCount in let data = FeedItemData.generate(count: viewCount) return CollectionViewControllerFeedItemPinLayoutView(data: data) }), ViewControllerData(title: "UIStackView", factoryBlock: { viewCount in if #available(iOS 9.0, *) { let data = FeedItemData.generate(count: viewCount) return CollectionViewControllerFeedItemUIStackView(data: data) } else { NSLog("UIStackView only supported on iOS 9+") return nil } }) ] convenience init() { self.init(style: .grouped) title = "Benchmarks" } override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewControllers.count + 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = UITableViewCell() cell.textLabel?.text = "Run all benchmarks" return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) cell.textLabel?.text = viewControllers[indexPath.row - 1].title return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("\nseconds/ops for each iterations (10, 20, ..., 100)") print("-------------------------------------") if indexPath.row == 0 { runAllBenchmarks() } else { let viewControllerData = viewControllers[indexPath.row - 1] runBenchmark(viewControllerData: viewControllerData, logResults: true, completed: { (results) in self.printResults(name: viewControllerData.title, results: results) }) } } private func runAllBenchmarks() { var benchmarkIndex = 0 func benchmarkCompleted(_ results: [Result]) { printResults(name: viewControllers[benchmarkIndex].title, results: results) DispatchQueue.main.async { self.navigationController?.popViewController(animated: false) benchmarkIndex += 1 if benchmarkIndex < self.viewControllers.count { self.runBenchmark(viewControllerData: self.viewControllers[benchmarkIndex], logResults: false, completed: benchmarkCompleted) } else { print("Completed!") } } } runBenchmark(viewControllerData: viewControllers[benchmarkIndex], logResults: false, completed: benchmarkCompleted) } private func printResults(name: String, results: [Result]) { var resultsString = "\(name)\t" results.forEach { (result) in resultsString += "\(result.secondsPerOperation)\t" } print(resultsString) } private func runBenchmark(viewControllerData: ViewControllerData, logResults: Bool, completed: ((_ results: [Result]) -> Void)?) { guard let viewController = viewControllerData.factoryBlock(20) else { return } benchmark(viewControllerData, logResults: logResults, completed: completed) viewController.title = viewControllerData.title navigationController?.pushViewController(viewController, animated: logResults) } private func benchmark(_ viewControllerData: ViewControllerData, logResults: Bool, completed: ((_ results: [Result]) -> Void)?) { // let iterations = [1] let iterations = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] var results: [Result] = [] for i in iterations { let description = "\(i)\tsubviews\t\(viewControllerData.title)" let result = Stopwatch.benchmark(description, logResults: logResults, block: { (stopwatch: Stopwatch) -> Void in let vc = viewControllerData.factoryBlock(i) stopwatch.resume() vc?.view.layoutIfNeeded() stopwatch.pause() }) results.append(result) } completed?(results) } } private struct ViewControllerData { let title: String let factoryBlock: (_ viewCount: Int) -> UIViewController? }
39.052023
145
0.638099