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
226453ccde50e76aad7beb8df46f84e5cdc48dd8
7,872
// // SessionContextHolderTest.swift // harray-ios-sdkTests // // Created by YILDIRIM ADIGÜZEL on 21.04.2020. // Copyright © 2020 xennio. All rights reserved. // import XCTest class SessionContextHolderTest: XCTestCase { func test_it_should_initialize_session_id_and_session_start_time() { ClockUtils.freeze() RandomValueUtils.freeze() let sessionStartTime = ClockUtils.getTime() let sessionId = RandomValueUtils.randomUUID() let sessionContextHolder = SessionContextHolder() XCTAssertEqual(sessionId, sessionContextHolder.getSessionId()) XCTAssertTrue(sessionStartTime == sessionContextHolder.getSessionStartTime()) XCTAssertTrue(sessionStartTime == sessionContextHolder.getLastActivityTime()) XCTAssertTrue(sessionContextHolder.getExternalParameters().isEmpty) XCTAssertEqual(SessionState.SESSION_INITIALIZED, sessionContextHolder.getSessionState()) ClockUtils.unFreeze() RandomValueUtils.unFreeze() } func test_it_should_get_session_id_and_extend_session_time() { let expectedTime: Int64 = 1587133370000 ClockUtils.freeze(expectedTime: expectedTime) RandomValueUtils.freeze() let sessionId = RandomValueUtils.randomUUID() let sessionContextHolder = SessionContextHolder() let resolvedSessionId = sessionContextHolder.getSessionIdAndExtendSession(); let lastActivityTime = sessionContextHolder.getLastActivityTime(); XCTAssertEqual(sessionId, resolvedSessionId) XCTAssertEqual(lastActivityTime, expectedTime) ClockUtils.unFreeze() RandomValueUtils.unFreeze() } func test_it_should_get_create_new_session_id_when_session_expired() { let expectedTime: Int64 = 1587133370000 ClockUtils.freeze(expectedTime: expectedTime) RandomValueUtils.freeze() let sessionContextHolder = SessionContextHolder() let resolvedSessionId = sessionContextHolder.getSessionIdAndExtendSession() RandomValueUtils.unFreeze(); let expectedTimeInFuture: Int64 = expectedTime + 60 * 60 * 1000 ClockUtils.freeze(expectedTime: expectedTimeInFuture) let resolvedSessionId2 = sessionContextHolder.getSessionIdAndExtendSession() let lastActivityTime = sessionContextHolder.getLastActivityTime() let sessionStartTime = sessionContextHolder.getSessionStartTime() XCTAssertNotEqual(resolvedSessionId, resolvedSessionId2) XCTAssertTrue(lastActivityTime == expectedTimeInFuture) XCTAssertTrue(sessionStartTime == expectedTimeInFuture) XCTAssertTrue(sessionContextHolder.getExternalParameters().isEmpty) XCTAssertEqual(SessionState.SESSION_RESTARTED, sessionContextHolder.getSessionState()) ClockUtils.unFreeze(); } func test_it_should_log_in_member() { let sessionContextHolder = SessionContextHolder() let memberId = "memberId"; sessionContextHolder.login(memberId: memberId) XCTAssertEqual(memberId, sessionContextHolder.getMemberId()) } func test_it_should_log_out_member() { let sessionContextHolder = SessionContextHolder() let memberId = "memberId"; sessionContextHolder.login(memberId: memberId) XCTAssertEqual(memberId, sessionContextHolder.getMemberId()) sessionContextHolder.logout() XCTAssertNil(sessionContextHolder.getMemberId()) } func test_it_should_change_session_state_when_session_started() { let sessionContextHolder = SessionContextHolder() sessionContextHolder.startSession() XCTAssertEqual(SessionState.SESSION_STARTED, sessionContextHolder.getSessionState()) } func test_it_should_update_external_parameters() { let sessionContextHolder = SessionContextHolder() let externalParameters: Dictionary<String, Any> = [ "a": "b", "c": "e", "d": "f", "campaignId": "campaignId", "campaignDate": "campaignDate", "pushId": "pushId", "url": "url", "utm_source": "utm_source", "utm_medium": "utm_medium", "utm_campaign": "utm_campaign", "utm_term": "utm_term", "utm_content": "utm_content" ] sessionContextHolder.updateExternalParameters(data: externalParameters) let boundedExternalParameters = sessionContextHolder.getExternalParameters() XCTAssertNil(boundedExternalParameters["a"]) XCTAssertNil(boundedExternalParameters["c"]) XCTAssertNil(boundedExternalParameters["d"]) XCTAssertTrue("campaignId" == boundedExternalParameters["campaignId"] as! String) XCTAssertTrue("campaignDate" == boundedExternalParameters["campaignDate"] as! String) XCTAssertTrue("pushId" == boundedExternalParameters["pushId"] as! String) XCTAssertTrue("url" == boundedExternalParameters["url"] as! String) XCTAssertTrue("utm_source" == boundedExternalParameters["utm_source"] as! String) XCTAssertTrue("utm_medium" == boundedExternalParameters["utm_medium"] as! String) XCTAssertTrue("utm_campaign" == boundedExternalParameters["utm_campaign"] as! String) XCTAssertTrue("utm_term" == boundedExternalParameters["utm_term"] as! String) XCTAssertTrue("utm_content" == boundedExternalParameters["utm_content"] as! String) } func test_it_should_update_external_parameters_when_parameter_present() { let sessionContextHolder = SessionContextHolder() let externalParameters: Dictionary<String, Any> = [ "a": "b", "campaignId": "campaignId" ] sessionContextHolder.updateExternalParameters(data: externalParameters) let boundedExternalParameters = sessionContextHolder.getExternalParameters() XCTAssertNil(boundedExternalParameters["a"]) XCTAssertNil(boundedExternalParameters["utm_campaign"]) XCTAssertTrue("campaignId" == boundedExternalParameters["campaignId"] as! String) } func test_it_should_update_external_parameters_with_any_hashable() { let sessionContextHolder = SessionContextHolder() let externalParameters: Dictionary<AnyHashable, Any> = [ "a": "b", "c": "e", "d": "f", "campaignId": "campaignId", "campaignDate": "campaignDate", "pushId": "pushId", "url": "url", "utm_source": "utm_source", "utm_medium": "utm_medium", "utm_campaign": "utm_campaign", "utm_term": "utm_term", "utm_content": "utm_content", 1: "asa" ] sessionContextHolder.updateExternalParameters(data: externalParameters) let boundedExternalParameters = sessionContextHolder.getExternalParameters() XCTAssertNil(boundedExternalParameters["a"]) XCTAssertNil(boundedExternalParameters["c"]) XCTAssertNil(boundedExternalParameters["d"]) XCTAssertTrue("campaignId" == boundedExternalParameters["campaignId"] as! String) XCTAssertTrue("campaignDate" == boundedExternalParameters["campaignDate"] as! String) XCTAssertTrue("pushId" == boundedExternalParameters["pushId"] as! String) XCTAssertTrue("url" == boundedExternalParameters["url"] as! String) XCTAssertTrue("utm_source" == boundedExternalParameters["utm_source"] as! String) XCTAssertTrue("utm_medium" == boundedExternalParameters["utm_medium"] as! String) XCTAssertTrue("utm_campaign" == boundedExternalParameters["utm_campaign"] as! String) XCTAssertTrue("utm_term" == boundedExternalParameters["utm_term"] as! String) XCTAssertTrue("utm_content" == boundedExternalParameters["utm_content"] as! String) } }
45.50289
96
0.701347
d78b1e4f969f54a861d6ac3d74f4245e596c3a74
587
// // PlayerView.swift // PlayerKit // // Created by Balatbat, Bryant on 12/20/17. // /// This file creates a `typealias` called `PlayerView` that determines which core view component to use depending on /// which platform the binary is being compiled for. If iOS or tvOS, `UIKit` will be imported and `UIView` will be used. /// otherwise, if macOS is used, `AppKit` will be imported and `NSView` will be used. #if canImport(UIKit) import UIKit public typealias PlayerView = UIView #elseif canImport(AppKit) import AppKit public typealias PlayerView = NSView #endif
30.894737
120
0.72402
abdf0d5dcd9910a30664d8b2f5a6124d1f368757
1,940
/*: Copyright (c) 2019 Razeware LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, distribute, sublicense, create a derivative work, and/or sell copies of the Software in any work that is designed, intended, or marketed for pedagogical or instructional purposes related to programming, coding, application development, or information technology. Permission for such use, copying, modification, merger, publication, distribution, sublicensing, creation of derivative works, or sale is expressly withheld. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --- */ //: # Part 1: Functions //: ## Episode 01: Introduction //: //: This playground contains all of the companion exercises and challenges for the Programming in Swift: Functions and Types course, at [www.raywenderlich.com](www.raywenderlich.com). //: //: You can get started with the first exercise in the course at the link below: //: //: [⇒ Next: 02 - Functions](@next)
46.190476
183
0.785052
75b746f7321f8063c289408d18ed7c7890caa3f1
801
// // FHIRAbstractBase+Factory.swift // SwiftFHIR // // Generated from FHIR {{ info.version }} on {{ info.date }}. // {{ info.year }}, SMART Health IT. // // Updated for Realm support by Ryan Baldwin on {{ info.date }} // Copyright @ {{ info.year }} Bunnyhug. All rights fall under Apache 2 // /** * Extension to FHIRAbstractBase to be able to instantiate by class name. */ extension FHIRAbstractBase { public class func factory(_ className: String, json: FHIRJSON, owner: FHIRAbstractBase?) -> FHIRAbstractBase { switch className { {%- for klass in classes %}{% if klass.resource_name %} case "{{ klass.resource_name }}": return {{ klass.name }}(json: json, owner: owner) {%- endif %}{% endfor %} default: return FHIRAbstractBase(json: json, owner: owner) } } }
26.7
111
0.657928
4826f72fd851e371956634e82ec3d7e37c3b7171
677
// // PokeAPI.swift // iOS Bootcamp Challenge // // Created by Jorge Benavides on 26/09/21. // import Foundation import RxSwift class PokeAPI { static let baseURL = "https://pokeapi.co/api/v2/" private let session: NetworkSession init(session: NetworkSession = URLSession.shared.rx) { self.session = session } func get<T: Decodable>(urlPath: String) -> Observable<T> { let urlString = PokeAPI.baseURL + urlPath return session.loadData(from: urlString) .map { result in try JSONDecoder().decode(T.self, from: result.data) } .observe(on: MainScheduler.asyncInstance) } }
23.344828
67
0.626292
7213d6fd45d411ca7a8454524e8f9197a1dd4d53
2,708
import UIKit import AVFoundation import Fritz class ViewController: UIViewController { var timer: Timer? private lazy var cameraSession = AVCaptureSession() private let sessionQueue = DispatchQueue(label: "com.fritzdemo.pizzadetector.session") private let captureQueue = DispatchQueue(label: "com.fritzdemo.pizzadetector.capture", qos: DispatchQoS.userInitiated) private lazy var previewLayer: AVCaptureVideoPreviewLayer = { let preview = AVCaptureVideoPreviewLayer(session: cameraSession) preview.videoGravity = .resizeAspectFill return preview }() override func viewDidLoad() { super.viewDidLoad() // Setup camera guard let device = AVCaptureDevice.default( .builtInWideAngleCamera, for: .video, position: .back), let input = try? AVCaptureDeviceInput(device: device) else { return } let output = AVCaptureVideoDataOutput() // Configure pixelBuffer format for use in model output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA as UInt32] output.alwaysDiscardsLateVideoFrames = true output.setSampleBufferDelegate(self, queue: captureQueue) sessionQueue.async { self.cameraSession.beginConfiguration() self.cameraSession.addInput(input) self.cameraSession.addOutput(output) self.cameraSession.commitConfiguration() self.cameraSession.sessionPreset = .photo } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Set the preview layer to the frame of the screen and start running. previewLayer.frame = view.layer.bounds view.layer.insertSublayer(previewLayer, at: 0) sessionQueue.async { self.cameraSession.startRunning() } } } extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate { func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { // 1 // 2 // 3 // 4 } } extension ViewController { /// Generates a random pizza destination along the edge func generateRandomPizzaDestination() -> CGPoint { let width = view.frame.width let height = view.frame.height let multiplier = Int.random(in: 0..<2) let sendPizzaToLeftOrRight = Bool.random() if sendPizzaToLeftOrRight { let randomHeight = CGFloat.random(in: 0..<height) return CGPoint(x: width * CGFloat(multiplier), y: randomHeight) } let randomWidth = CGFloat.random(in: 0..<height) return CGPoint(x: randomWidth, y: height * CGFloat(multiplier)) } /// Creates a new Pizza animation @objc func createNewPizzaSlice() { // 1 // 2 // 3 } }
27.632653
127
0.721566
89a706ab6140572d22d34200168feef1c5a12552
1,294
// // InfiniteScrollActivityView.swift // twitter_alamofire_demo // // Created by Luis Mendez on 10/15/18. // Copyright © 2018 Charles Hieger. All rights reserved. // import UIKit class InfiniteScrollActivityView: UIView { var activityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView() static let defaultHeight:CGFloat = 40.0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupActivityIndicator() } override init(frame aRect: CGRect) { super.init(frame: aRect) setupActivityIndicator() } override func layoutSubviews() { super.layoutSubviews() activityIndicatorView.center = CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2) } func setupActivityIndicator() { activityIndicatorView.activityIndicatorViewStyle = .gray activityIndicatorView.color = .black activityIndicatorView.hidesWhenStopped = true self.addSubview(activityIndicatorView) } func stopAnimating() { self.activityIndicatorView.stopAnimating() self.isHidden = true } func startAnimating() { self.isHidden = false self.activityIndicatorView.startAnimating() } }
26.408163
105
0.671561
56c47ebd7ee0e809ce90436f4f8176730f0a3ada
1,519
// // AppDelegate.swift // // Copyright (c) 2020 Daniel Murfin // // 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 Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
37.975
81
0.746544
f470fe871c9423b4ffbd4ca3bcdb933d96e4b722
457
// // Copyright © 2020. Orynko Artem // // MIT license, see LICENSE file for details // import Foundation extension Cell { open class Configurator<Item, Cell: Identifiable, ReusableType: Reusable>: Configurable { public final var configurator: (Cell, Item, IndexPath, ReusableType) -> Cell @inline(__always) @inlinable public init(_ configure: @escaping (Cell, Item, IndexPath, ReusableType) -> Cell) { self.configurator = configure } } }
22.85
90
0.717724
c1bf422c0d26a67229cf76d14ba704ab614288d5
416
import Html func projectsIndex(_ projects: [ProjectLi]) -> Node { return baseHtml([ baseHead(title: "Gofake1 - Projects", styles: [.list, .navbar]), body([ navbar(selection: .projects), div([`class`("list")], [ ul(projects.map { li([ h3([a([href($0.href)], [.text($0.name)])]), p([.text($0.subheading)]) ]) }) ]) ]) ]) }
21.894737
68
0.475962
61a19f938af0fa3a696cb897fddb7fc83f2aabc0
1,901
// // BikeRideFilterSheetView.swift // Go Cycling // // Created by Anthony Hopkins on 2021-08-14. // import SwiftUI struct BikeRideFilterSheetView: View { @EnvironmentObject var bikeRides: BikeRideStorage @Environment(\.presentationMode) var presentationMode @Binding var showingSheet: Bool @Binding private var selectedName: String var categories: [Category] init(showingSheet: Binding<Bool>, selectedName: Binding<String>, names: [Category]) { self._showingSheet = showingSheet self._selectedName = selectedName self.categories = names } var body: some View { VStack { Text("Select a Category to View") .font(.headline) .padding() if (self.categories.count > 0) { List { ForEach(0 ..< self.categories.count) { index in HStack { Button (self.categories[index].name) { self.selectedName = index == 0 ? "" : self.categories[index].name self.presentationMode.wrappedValue.dismiss() } Spacer() Text("\(self.categories[index].number)") } } } .listStyle(InsetGroupedListStyle()) } Spacer() Divider() Button (action: {self.presentationMode.wrappedValue.dismiss()}) { Text("Cancel") .foregroundColor(Color.blue) .bold() } .padding() Divider() } } } //struct BikeRideFilterSheetView_Previews: PreviewProvider { // static var previews: some View { // BikeRideFilterSheetView() // } //}
29.703125
97
0.502893
1a2b70a286c6f1b861911fb67aba616e222bb146
1,229
// // ConnectionCheck.swift // tumbly // // Created by Andriana Aivazians on 9/28/18. // Copyright © 2018 Andriana Aivazians. All rights reserved. // /* Code used from: https://stackoverflow.com/questions/39558868/check-internetconnection-ios-10/40148883#40148883 */ import Foundation import SystemConfiguration public class ConnectionCheck { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags: SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } }
31.512821
113
0.647681
7adab8b795a7cae6b2f1d75adfdb6ccb1dffb778
1,634
// // VisitorAskNameViewController.swift // ReceptionKit // // Created by Andy Cho on 2015-04-23. // Copyright (c) 2015 Andy Cho. All rights reserved. // import UIKit class VisitorAskNameViewController: ReturnToHomeViewController, UITextFieldDelegate { @IBOutlet weak var yourNameLabel: UILabel! @IBOutlet weak var nameTextField: UITextField! let visitorEnteredNameSegue = "VisitorEnteredNameSegue" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.nameTextField.delegate = self nameTextField.borderStyle = UITextBorderStyle.RoundedRect yourNameLabel.text = Text.get("your name") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Not doing this in viewDidLoad() as that raises the keyboard before the segue nameTextField.becomeFirstResponder() } // // MARK: - UITextViewDelegate // // Segue to the VisitorViewController when the name is entered func textFieldShouldReturn(textField: UITextField) -> Bool { performSegueWithIdentifier(visitorEnteredNameSegue, sender: self) return false } // // MARK: - Navigation // // Set the visitor's name before the segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let visitorViewController = segue.destinationViewController as? VisitorViewController { visitorViewController.visitorName = nameTextField.text } } }
28.172414
98
0.673195
ff29c2c467a4ce3b4a0c4731c02baa4a137d5e09
2,533
// // BootpayUser.swift // CryptoSwift // // Created by YoonTaesup on 2019. 4. 12.. // import ObjectMapper //MARK: Bootpay Models public class BootpayUser: NSObject, BootpayParams, Mappable { public required init?(map: Map) { } public func mapping(map: Map) { id <- map["id"] username <- map["username"] email <- map["email"] gender <- map["gender"] birth <- map["birth"] phone <- map["phone"] area <- map["area"] addr <- map["addr"] } public override init() {} var user_id = "" @objc public var id = "" @objc public var username = "" @objc public var email = "" @objc public var gender = 0 @objc public var birth = "" @objc public var phone = "" @objc public var area = "" @objc public var addr = "" func toString() -> String { return [ "{", "id: '\(id.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'").replace(target: "'\n", withString: ""))',", "username: '\(username.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'").replace(target: "'\n", withString: ""))',", "user_id: '\(user_id.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'").replace(target: "'\n", withString: ""))',", "email: '\(email.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'").replace(target: "'\n", withString: ""))',", "gender: \(Int(gender)),", "birth: '\(birth.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'").replace(target: "'\n", withString: ""))',", "phone: '\(phone.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'").replace(target: "'\n", withString: ""))',", "area: '\(area.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'").replace(target: "'\n", withString: ""))',", "addr: '\(addr.replace(target: "\"", withString: "'").replace(target: "'", withString: "\\'").replace(target: "'\n", withString: ""))'", "}" ].reduce("", +) } // @objc public func toJson() -> String { // do { // let jsonEncoder = JSONEncoder() // let jsonData = try jsonEncoder.encode(self) // return String(data: jsonData, encoding: String.Encoding.utf16) ?? "" // } catch { // return "" // } // } }
40.206349
157
0.512041
0a516068fea1608b1faba314e9d44e90434774d8
4,032
import XCTest @testable import SQLighter final class SelectTests: XCTestCase { func testSelectAll() { let result = "SELECT * FROM User" let sql = SQL.select(from: "User") XCTAssertEqual(sql.sqlString(), result) } func testSelectAllAliased() { let result = "SELECT u.* FROM User AS u" let sql = SQL.select(from: "User", as: "u") XCTAssertEqual(sql.sqlString(), result) } func testSelectColumn() { let result = "SELECT id, name FROM User" let sql = SQL .select(column: "id") .column("name") .from(table: "User") XCTAssertEqual(sql.sqlString(), result) } func testSelectColumnAliased() { let result = "SELECT id AS _id, name AS _name FROM User" let sql = SQL .select(column: "id", as: "_id") .column("name", as: "_name") .from(table: "User") XCTAssertEqual(sql.sqlString(), result) } func testSelectAliasedTable() { let result = "SELECT u.id FROM User AS u" let sql = SQL .select(column: "id") .from(table: "User", as: "u") XCTAssertEqual(sql.sqlString(), result) } func testSelectAliasedTableAliasedColumn() { let result = "SELECT u.id AS _id FROM User AS u" let sql = SQL .select(column: "id", as: "_id") .from(table: "User", as: "u") XCTAssertEqual(sql.sqlString(), result) } func testSelectWhereClause() { let sql = SQL.select(from: "User").where("id" == 12) XCTAssertEqual(sql.sqlQuery().sql, "SELECT * FROM User WHERE id = ?") XCTAssertEqual(sql.sqlString(), "SELECT * FROM User WHERE id = 12") } func testOrderByColumn() { let sql = SQL.select(from: "User").order(by: "id").order(by: "name") XCTAssertEqual(sql.sqlQuery().sql, "SELECT * FROM User ORDER BY id, name") } func testOrderAscColumn() { let sql = SQL.select(from: "User").order(by: "id").ascending().order(by: "name").ascending() XCTAssertEqual(sql.sqlQuery().sql, "SELECT * FROM User ORDER BY id ASC, name ASC") } func testOrderDescColumn() { let sql = SQL.select(from: "User").order(by: "id").descending().order(by: "name").descending() XCTAssertEqual(sql.sqlQuery().sql, "SELECT * FROM User ORDER BY id DESC, name DESC") } func testOrderNullsFirst() { let sql = SQL.select(from: "User").order(by: "id").nullsFirst().order(by: "name").nullsFirst() XCTAssertEqual(sql.sqlQuery().sql, "SELECT * FROM User ORDER BY id NULLS FIRST, name NULLS FIRST") } func testOrderNullsLast() { let sql = SQL.select(from: "User").order(by: "id").nullsLast().order(by: "name").nullsLast() XCTAssertEqual(sql.sqlQuery().sql, "SELECT * FROM User ORDER BY id NULLS LAST, name NULLS LAST") } func testOrderAnyColumn() { let sql = SQL.select(from: "User").order(by: "id").ascending().nullsFirst().order(by: "name").descending().nullsLast() XCTAssertEqual(sql.sqlQuery().sql, "SELECT * FROM User ORDER BY id ASC NULLS FIRST, name DESC NULLS LAST") } func testLimitSelect() { let sql = SQL.select(column: "id").from(table: "User").limit(10) XCTAssertEqual(sql.sqlQuery().sql, "SELECT id FROM User LIMIT 10") XCTAssertEqual(sql.sqlString(), "SELECT id FROM User LIMIT 10") } func testOffsetSelect() { let sql = SQL.select(from: "User").limit(10, offset: 20) XCTAssertEqual(sql.sqlQuery().sql, "SELECT * FROM User LIMIT 10 OFFSET 20") XCTAssertEqual(sql.sqlString(), "SELECT * FROM User LIMIT 10 OFFSET 20") } func testSelectCountColumn() { let sql = SQL.count(column: "id", as: "_id", distinct: false).from(table: "User", as: "u") XCTAssertEqual(sql.sqlString(), "SELECT count(ALL u.id) AS _id FROM User AS u") } func testSelectCount() { let sql = SQL.count(from: "User") XCTAssertEqual(sql.sqlString(), "SELECT count(*) FROM User") } func testSelectMultipleCountColumn() { let sql = SQL.count(column: "id").count("name").from(table: "User") XCTAssertEqual(sql.sqlString(), "SELECT count(ALL id), count(ALL name) FROM User") } }
35.368421
122
0.643601
8f14a40bf9bec2ab5ca501ba4f0fb21665e59831
9,315
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. #if compiler(>=5.5) && canImport(_Concurrency) import SotoCore @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension MediaPackage { // MARK: Async API Calls /// Changes the Channel's properities to configure log subscription public func configureLogs(_ input: ConfigureLogsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ConfigureLogsResponse { return try await self.client.execute(operation: "ConfigureLogs", path: "/channels/{Id}/configure_logs", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a new Channel. public func createChannel(_ input: CreateChannelRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateChannelResponse { return try await self.client.execute(operation: "CreateChannel", path: "/channels", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a new HarvestJob record. public func createHarvestJob(_ input: CreateHarvestJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateHarvestJobResponse { return try await self.client.execute(operation: "CreateHarvestJob", path: "/harvest_jobs", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a new OriginEndpoint record. public func createOriginEndpoint(_ input: CreateOriginEndpointRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateOriginEndpointResponse { return try await self.client.execute(operation: "CreateOriginEndpoint", path: "/origin_endpoints", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes an existing Channel. public func deleteChannel(_ input: DeleteChannelRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteChannelResponse { return try await self.client.execute(operation: "DeleteChannel", path: "/channels/{Id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes an existing OriginEndpoint. public func deleteOriginEndpoint(_ input: DeleteOriginEndpointRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteOriginEndpointResponse { return try await self.client.execute(operation: "DeleteOriginEndpoint", path: "/origin_endpoints/{Id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets details about a Channel. public func describeChannel(_ input: DescribeChannelRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribeChannelResponse { return try await self.client.execute(operation: "DescribeChannel", path: "/channels/{Id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets details about an existing HarvestJob. public func describeHarvestJob(_ input: DescribeHarvestJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribeHarvestJobResponse { return try await self.client.execute(operation: "DescribeHarvestJob", path: "/harvest_jobs/{Id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets details about an existing OriginEndpoint. public func describeOriginEndpoint(_ input: DescribeOriginEndpointRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribeOriginEndpointResponse { return try await self.client.execute(operation: "DescribeOriginEndpoint", path: "/origin_endpoints/{Id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a collection of Channels. public func listChannels(_ input: ListChannelsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListChannelsResponse { return try await self.client.execute(operation: "ListChannels", path: "/channels", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a collection of HarvestJob records. public func listHarvestJobs(_ input: ListHarvestJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListHarvestJobsResponse { return try await self.client.execute(operation: "ListHarvestJobs", path: "/harvest_jobs", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a collection of OriginEndpoint records. public func listOriginEndpoints(_ input: ListOriginEndpointsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListOriginEndpointsResponse { return try await self.client.execute(operation: "ListOriginEndpoints", path: "/origin_endpoints", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListTagsForResourceResponse { return try await self.client.execute(operation: "ListTagsForResource", path: "/tags/{ResourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Changes the Channel's first IngestEndpoint's username and password. WARNING - This API is deprecated. Please use RotateIngestEndpointCredentials instead @available(*, deprecated, message: "This API is deprecated. Please use RotateIngestEndpointCredentials instead") public func rotateChannelCredentials(_ input: RotateChannelCredentialsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> RotateChannelCredentialsResponse { return try await self.client.execute(operation: "RotateChannelCredentials", path: "/channels/{Id}/credentials", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Rotate the IngestEndpoint's username and password, as specified by the IngestEndpoint's id. public func rotateIngestEndpointCredentials(_ input: RotateIngestEndpointCredentialsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> RotateIngestEndpointCredentialsResponse { return try await self.client.execute(operation: "RotateIngestEndpointCredentials", path: "/channels/{Id}/ingest_endpoints/{IngestEndpointId}/credentials", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws { return try await self.client.execute(operation: "TagResource", path: "/tags/{ResourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws { return try await self.client.execute(operation: "UntagResource", path: "/tags/{ResourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates an existing Channel. public func updateChannel(_ input: UpdateChannelRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateChannelResponse { return try await self.client.execute(operation: "UpdateChannel", path: "/channels/{Id}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates an existing OriginEndpoint. public func updateOriginEndpoint(_ input: UpdateOriginEndpointRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdateOriginEndpointResponse { return try await self.client.execute(operation: "UpdateOriginEndpoint", path: "/origin_endpoints/{Id}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } #endif // compiler(>=5.5) && canImport(_Concurrency)
76.983471
253
0.738808
48805a12d2f65585a42619338782ccdd5bbe7c8e
2,413
// // MainTabbarController.swift // MyRx // // Created by Hony on 2016/12/29. // Copyright © 2016年 Hony. All rights reserved. // import UIKit class MainTabbarController: UITabBarController { struct TabbarItemModel { var name: String var image: String var selectedImage: String var className: String } // 命名空间 let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String let items: [TabbarItemModel] = [ TabbarItemModel(name: "火柴", image: "Social_One", selectedImage: "Social_One_Select" ,className: "MatchViewController"), TabbarItemModel(name: "话题", image: "Social_Topic", selectedImage: "Social_Topic_Select",className: "TopicViewController"), // TabbarItemModel(name: "消息", image: "Social_Messages", selectedImage: "Social_Messages_Select",className: "MessageViewController"), TabbarItemModel(name: "盒子", image: "Social_Box", selectedImage: "Social_Box_Select",className: "BoxViewController"), // TabbarItemModel(name: "我", image: "Social_Private", selectedImage: "Social_Private_Select" ,className: "ProfileViewController") ] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white tabBar.backgroundColor = .white tabBar.backgroundImage = UIImage() items.forEach { self.addChildController(with: $0) } } init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addChildController(with model:TabbarItemModel){ guard let nameClass = NSClassFromString(nameSpace + "." + model.className)else{ return } let vcClass = nameClass as! UIViewController.Type let vc = vcClass.init() vc.navigationItem.title = model.name vc.tabBarItem.image = UIImage(named: model.image)?.withRenderingMode(.alwaysOriginal) vc.tabBarItem.selectedImage = UIImage(named: model.selectedImage)?.withRenderingMode(.alwaysOriginal) // MARK: 这里会发现,系统的tabbarItem 图片位置不正常, top 和bottom 两个数最好绝对值相同.不然会改变图片 vc.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0) let wraped = MainNavigationController(rootViewController: vc) addChildViewController(wraped) } }
38.919355
140
0.668877
463e6c8a7c406502e1fd27c937d7a2274483faf8
22,492
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import class Foundation.ProcessInfo import enum POSIX.SystemError import func POSIX.getenv import SPMLibc import Dispatch /// Process result data which is available after process termination. public struct ProcessResult: CustomStringConvertible { public enum Error: Swift.Error { /// The output is not a valid UTF8 sequence. case illegalUTF8Sequence /// The process had a non zero exit. case nonZeroExit(ProcessResult) } public enum ExitStatus: Equatable { /// The process was terminated normally with a exit code. case terminated(code: Int32) /// The process was terminated due to a signal. case signalled(signal: Int32) } /// The arguments with which the process was launched. public let arguments: [String] /// The exit status of the process. public let exitStatus: ExitStatus /// The output bytes of the process. Available only if the process was /// asked to redirect its output and no stdout output closure was set. public let output: Result<[UInt8], AnyError> /// The output bytes of the process. Available only if the process was /// asked to redirect its output and no stderr output closure was set. public let stderrOutput: Result<[UInt8], AnyError> /// Create an instance using a POSIX process exit status code and output result. /// /// See `waitpid(2)` for information on the exit status code. public init( arguments: [String], exitStatusCode: Int32, output: Result<[UInt8], AnyError>, stderrOutput: Result<[UInt8], AnyError> ) { let exitStatus: ExitStatus if WIFSIGNALED(exitStatusCode) { exitStatus = .signalled(signal: WTERMSIG(exitStatusCode)) } else { precondition(WIFEXITED(exitStatusCode), "unexpected exit status \(exitStatusCode)") exitStatus = .terminated(code: WEXITSTATUS(exitStatusCode)) } self.init(arguments: arguments, exitStatus: exitStatus, output: output, stderrOutput: stderrOutput) } /// Create an instance using an exit status and output result. public init( arguments: [String], exitStatus: ExitStatus, output: Result<[UInt8], AnyError>, stderrOutput: Result<[UInt8], AnyError> ) { self.arguments = arguments self.output = output self.stderrOutput = stderrOutput self.exitStatus = exitStatus } /// Converts stdout output bytes to string, assuming they're UTF8. public func utf8Output() throws -> String { return String(decoding: try output.dematerialize(), as: Unicode.UTF8.self) } /// Converts stderr output bytes to string, assuming they're UTF8. public func utf8stderrOutput() throws -> String { return String(decoding: try stderrOutput.dematerialize(), as: Unicode.UTF8.self) } public var description: String { return """ <ProcessResult: exit: \(exitStatus), output: \((try? utf8Output()) ?? "") > """ } } /// Process allows spawning new subprocesses and working with them. /// /// Note: This class is thread safe. public final class Process: ObjectIdentifierProtocol { /// Errors when attempting to invoke a process public enum Error: Swift.Error { /// The program requested to be executed cannot be found on the existing search paths, or is not executable. case missingExecutableProgram(program: String) } public enum OutputRedirection { /// Do not redirect the output case none /// Collect stdout and stderr output and provide it back via ProcessResult object case collect /// Stream stdout and stderr via the corresponding closures case stream(stdout: OutputClosure, stderr: OutputClosure) public var redirectsOutput: Bool { switch self { case .none: return false case .collect, .stream: return true } } public var outputClosures: (stdoutClosure: OutputClosure, stderrClosure: OutputClosure)? { switch self { case .stream(let stdoutClosure, let stderrClosure): return (stdoutClosure: stdoutClosure, stderrClosure: stderrClosure) case .collect, .none: return nil } } } /// Typealias for process id type. public typealias ProcessID = pid_t /// Typealias for stdout/stderr output closure. public typealias OutputClosure = ([UInt8]) -> Void /// Global default setting for verbose. public static var verbose = false /// If true, prints the subprocess arguments before launching it. public let verbose: Bool /// The current environment. static public var env: [String: String] { return ProcessInfo.processInfo.environment } /// The arguments to execute. public let arguments: [String] /// The environment with which the process was executed. public let environment: [String: String] /// The process id of the spawned process, available after the process is launched. public private(set) var processID = ProcessID() /// If the subprocess has launched. /// Note: This property is not protected by the serial queue because it is only mutated in `launch()`, which will be /// called only once. public private(set) var launched = false /// The result of the process execution. Available after process is terminated. public var result: ProcessResult? { return self.serialQueue.sync { self._result } } /// How process redirects its output. public let outputRedirection: OutputRedirection /// The result of the process execution. Available after process is terminated. private var _result: ProcessResult? /// If redirected, stdout result and reference to the thread reading the output. private var stdout: (result: Result<[UInt8], AnyError>, thread: Thread?) = (Result([]), nil) /// If redirected, stderr result and reference to the thread reading the output. private var stderr: (result: Result<[UInt8], AnyError>, thread: Thread?) = (Result([]), nil) /// Queue to protect concurrent reads. private let serialQueue = DispatchQueue(label: "org.swift.swiftpm.process") /// Queue to protect reading/writing on map of validated executables. private static let executablesQueue = DispatchQueue( label: "org.swift.swiftpm.process.findExecutable") /// Indicates if a new progress group is created for the child process. private let startNewProcessGroup: Bool /// Cache of validated executables. /// /// Key: Executable name or path. /// Value: Path to the executable, if found. static private var validatedExecutablesMap = [String: AbsolutePath?]() /// Create a new process instance. /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - outputRedirection: How process redirects its output. Default value is .collect. /// - verbose: If true, launch() will print the arguments of the subprocess before launching it. /// - startNewProcessGroup: If true, a new progress group is created for the child making it /// continue running even if the parent is killed or interrupted. Default value is true. public init( arguments: [String], environment: [String: String] = env, outputRedirection: OutputRedirection = .collect, verbose: Bool = Process.verbose, startNewProcessGroup: Bool = true ) { self.arguments = arguments self.environment = environment self.outputRedirection = outputRedirection self.verbose = verbose self.startNewProcessGroup = startNewProcessGroup } /// Returns the path of the the given program if found in the search paths. /// /// The program can be executable name, relative path or absolute path. public static func findExecutable(_ program: String) -> AbsolutePath? { return Process.executablesQueue.sync { // Check if we already have a value for the program. if let value = Process.validatedExecutablesMap[program] { return value } // FIXME: This can be cached. let envSearchPaths = getEnvSearchPaths( pathString: getenv("PATH"), currentWorkingDirectory: localFileSystem.currentWorkingDirectory ) // Lookup and cache the executable path. let value = lookupExecutablePath( filename: program, searchPaths: envSearchPaths) Process.validatedExecutablesMap[program] = value return value } } /// Launch the subprocess. public func launch() throws { precondition(arguments.count > 0 && !arguments[0].isEmpty, "Need at least one argument to launch the process.") precondition(!launched, "It is not allowed to launch the same process object again.") // Set the launch bool to true. launched = true // Print the arguments if we are verbose. if self.verbose { stdoutStream <<< arguments.map({ $0.spm_shellEscaped() }).joined(separator: " ") <<< "\n" stdoutStream.flush() } // Look for executable. guard Process.findExecutable(arguments[0]) != nil else { throw Process.Error.missingExecutableProgram(program: arguments[0]) } // Initialize the spawn attributes. #if canImport(Darwin) var attributes: posix_spawnattr_t? = nil #else var attributes = posix_spawnattr_t() #endif posix_spawnattr_init(&attributes) defer { posix_spawnattr_destroy(&attributes) } // Unmask all signals. var noSignals = sigset_t() sigemptyset(&noSignals) posix_spawnattr_setsigmask(&attributes, &noSignals) // Reset all signals to default behavior. #if os(macOS) var mostSignals = sigset_t() sigfillset(&mostSignals) sigdelset(&mostSignals, SIGKILL) sigdelset(&mostSignals, SIGSTOP) posix_spawnattr_setsigdefault(&attributes, &mostSignals) #else // On Linux, this can only be used to reset signals that are legal to // modify, so we have to take care about the set we use. var mostSignals = sigset_t() sigemptyset(&mostSignals) for i in 1 ..< SIGSYS { if i == SIGKILL || i == SIGSTOP { continue } sigaddset(&mostSignals, i) } posix_spawnattr_setsigdefault(&attributes, &mostSignals) #endif // Set the attribute flags. var flags = POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF if startNewProcessGroup { // Establish a separate process group. flags |= POSIX_SPAWN_SETPGROUP posix_spawnattr_setpgroup(&attributes, 0) } posix_spawnattr_setflags(&attributes, Int16(flags)) // Setup the file actions. #if canImport(Darwin) var fileActions: posix_spawn_file_actions_t? = nil #else var fileActions = posix_spawn_file_actions_t() #endif posix_spawn_file_actions_init(&fileActions) defer { posix_spawn_file_actions_destroy(&fileActions) } // Workaround for https://sourceware.org/git/gitweb.cgi?p=glibc.git;h=89e435f3559c53084498e9baad22172b64429362 let devNull = strdup("/dev/null") defer { free(devNull) } // Open /dev/null as stdin. posix_spawn_file_actions_addopen(&fileActions, 0, devNull, O_RDONLY, 0) var outputPipe: [Int32] = [0, 0] var stderrPipe: [Int32] = [0, 0] if outputRedirection.redirectsOutput { // Open the pipes. try open(pipe: &outputPipe) try open(pipe: &stderrPipe) // Open the write end of the pipe as stdout and stderr, if desired. posix_spawn_file_actions_adddup2(&fileActions, outputPipe[1], 1) posix_spawn_file_actions_adddup2(&fileActions, stderrPipe[1], 2) // Close the other ends of the pipe. for pipe in [outputPipe, stderrPipe] { posix_spawn_file_actions_addclose(&fileActions, pipe[0]) posix_spawn_file_actions_addclose(&fileActions, pipe[1]) } } else { posix_spawn_file_actions_adddup2(&fileActions, 1, 1) posix_spawn_file_actions_adddup2(&fileActions, 2, 2) } let argv = CStringArray(arguments) let env = CStringArray(environment.map({ "\($0.0)=\($0.1)" })) let rv = posix_spawnp(&processID, argv.cArray[0], &fileActions, &attributes, argv.cArray, env.cArray) guard rv == 0 else { throw SystemError.posix_spawn(rv, arguments) } if outputRedirection.redirectsOutput { let outputClosures = outputRedirection.outputClosures // Close the write end of the output pipe. try close(fd: &outputPipe[1]) // Create a thread and start reading the output on it. var thread = Thread { [weak self] in if let readResult = self?.readOutput(onFD: outputPipe[0], outputClosure: outputClosures?.stdoutClosure) { self?.stdout.result = readResult } } thread.start() self.stdout.thread = thread // Close the write end of the stderr pipe. try close(fd: &stderrPipe[1]) // Create a thread and start reading the stderr output on it. thread = Thread { [weak self] in if let readResult = self?.readOutput(onFD: stderrPipe[0], outputClosure: outputClosures?.stderrClosure) { self?.stderr.result = readResult } } thread.start() self.stderr.thread = thread } } /// Blocks the calling process until the subprocess finishes execution. @discardableResult public func waitUntilExit() throws -> ProcessResult { return try serialQueue.sync { precondition(launched, "The process is not yet launched.") // If the process has already finsihed, return it. if let existingResult = _result { return existingResult } // If we're reading output, make sure that is finished. stdout.thread?.join() stderr.thread?.join() // Wait until process finishes execution. var exitStatusCode: Int32 = 0 var result = waitpid(processID, &exitStatusCode, 0) while result == -1 && errno == EINTR { result = waitpid(processID, &exitStatusCode, 0) } if result == -1 { throw SystemError.waitpid(errno) } // Construct the result. let executionResult = ProcessResult( arguments: arguments, exitStatusCode: exitStatusCode, output: stdout.result, stderrOutput: stderr.result ) self._result = executionResult return executionResult } } /// Reads the given fd and returns its result. /// /// Closes the fd before returning. private func readOutput(onFD fd: Int32, outputClosure: OutputClosure?) -> Result<[UInt8], AnyError> { // Read all of the data from the output pipe. let N = 4096 var buf = [UInt8](repeating: 0, count: N + 1) var out = [UInt8]() var error: Swift.Error? = nil loop: while true { let n = read(fd, &buf, N) switch n { case -1: if errno == EINTR { continue } else { error = SystemError.read(errno) break loop } case 0: break loop default: let data = buf[0..<n] if let outputClosure = outputClosure { outputClosure(Array(data)) } else { out += data } } } // Close the read end of the output pipe. close(fd) // Construct the output result. return error.map(Result.init) ?? Result(out) } /// Send a signal to the process. /// /// Note: This will signal all processes in the process group. public func signal(_ signal: Int32) { assert(launched, "The process is not yet launched.") _ = SPMLibc.kill(startNewProcessGroup ? -processID : processID, signal) } } extension Process { /// Execute a subprocess and block until it finishes execution /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - Returns: The process result. @discardableResult static public func popen(arguments: [String], environment: [String: String] = env) throws -> ProcessResult { let process = Process(arguments: arguments, environment: environment, outputRedirection: .collect) try process.launch() return try process.waitUntilExit() } @discardableResult static public func popen(args: String..., environment: [String: String] = env) throws -> ProcessResult { return try Process.popen(arguments: args, environment: environment) } /// Execute a subprocess and get its (UTF-8) output if it has a non zero exit. /// /// - Parameters: /// - arguments: The arguments for the subprocess. /// - environment: The environment to pass to subprocess. By default the current process environment /// will be inherited. /// - Returns: The process output (stdout + stderr). @discardableResult static public func checkNonZeroExit(arguments: [String], environment: [String: String] = env) throws -> String { let process = Process(arguments: arguments, environment: environment, outputRedirection: .collect) try process.launch() let result = try process.waitUntilExit() // Throw if there was a non zero termination. guard result.exitStatus == .terminated(code: 0) else { throw ProcessResult.Error.nonZeroExit(result) } return try result.utf8Output() } @discardableResult static public func checkNonZeroExit(args: String..., environment: [String: String] = env) throws -> String { return try checkNonZeroExit(arguments: args, environment: environment) } public convenience init(args: String..., environment: [String: String] = env, outputRedirection: OutputRedirection = .collect) { self.init(arguments: args, environment: environment, outputRedirection: outputRedirection) } } // MARK: - Private helpers #if os(macOS) private typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t? #else private typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t #endif private func WIFEXITED(_ status: Int32) -> Bool { return _WSTATUS(status) == 0 } private func _WSTATUS(_ status: Int32) -> Int32 { return status & 0x7f } private func WIFSIGNALED(_ status: Int32) -> Bool { return (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f) } private func WEXITSTATUS(_ status: Int32) -> Int32 { return (status >> 8) & 0xff } private func WTERMSIG(_ status: Int32) -> Int32 { return status & 0x7f } /// Open the given pipe. private func open(pipe: inout [Int32]) throws { let rv = SPMLibc.pipe(&pipe) guard rv == 0 else { throw SystemError.pipe(rv) } } /// Close the given fd. private func close(fd: inout Int32) throws { let rv = SPMLibc.close(fd) guard rv == 0 else { throw SystemError.close(rv) } } extension Process.Error: CustomStringConvertible { public var description: String { switch self { case .missingExecutableProgram(let program): return "could not find executable for '\(program)'" } } } extension ProcessResult.Error: CustomStringConvertible { public var description: String { switch self { case .illegalUTF8Sequence: return "illegal UTF8 sequence output" case .nonZeroExit(let result): let stream = BufferedOutputByteStream() switch result.exitStatus { case .terminated(let code): stream <<< "terminated(\(code)): " case .signalled(let signal): stream <<< "signalled(\(signal)): " } // Strip sandbox information from arguments to keep things pretty. var args = result.arguments // This seems a little fragile. if args.first == "sandbox-exec", args.count > 3 { args = args.suffix(from: 3).map({$0}) } stream <<< args.map({ $0.spm_shellEscaped() }).joined(separator: " ") // Include the output, if present. if let output = try? result.utf8Output() + result.utf8stderrOutput() { // We indent the output to keep it visually separated from everything else. let indentation = " " stream <<< " output:\n" <<< indentation <<< output.replacingOccurrences(of: "\n", with: "\n" + indentation) if !output.hasSuffix("\n") { stream <<< "\n" } } return stream.bytes.description } } }
36.872131
132
0.620176
21f47f87d0a0eac8564d341b13f3d6158b08d63d
284
// // Date+isToday.swift // TinkoffMessenger // // Created by Always Strive And Prosper on 01.03.2020. // Copyright © 2020 komarov. All rights reserved. // import Foundation extension Date { func isToday() -> Bool { return Calendar.current.isDateInToday(self) } }
15.777778
55
0.676056
1cb99b69a4182bb45ac83957c5d6ab76fb12d9ce
10,645
// // Armin_OC.swift // Armin // // Created by CavanSu on 2020/8/18. // Copyright © 2020 CavanSu. All rights reserved. // @objc public protocol ArminDelegateOC: NSObjectProtocol { func armin(_ client: ArminOC, requestSuccess event: ArRequestEventOC, startTime: TimeInterval, url: String) func armin(_ client: ArminOC, requestFail error: ArErrorOC, event: ArRequestEventOC, url: String) } @objc public class ArErrorOC: NSError { @objc public var reposeData: Data? } @objc open class ArminOC: Armin { @objc public weak var delegateOC: ArminDelegateOC? @objc public weak var logTubeOC: ArLogTubeOC? @objc public init(delegate: ArminDelegateOC? = nil, logTube: ArLogTubeOC? = nil) { self.delegateOC = delegate super.init(delegate: nil, logTube: nil) self.logTube = self self.delegate = self self.logTubeOC = logTube } @objc public func request(task: ArRequestTaskOC, responseOnMainQueue: Bool = true, successCallbackContent: ArResponseTypeOC, success: ((ArResponseOC) -> Void)? = nil, fail: ArErrorRetryCompletionOC = nil) { let swift_task = ArRequestTask.oc(task) var response: ArResponse switch successCallbackContent { case .json: response = ArResponse.json({ (json) in let response_oc = ArResponseOC(type: successCallbackContent, json: json, data: nil) if let success = success { success(response_oc) } }) case .data: response = ArResponse.data({ (data) in let response_oc = ArResponseOC(type: successCallbackContent, json: nil, data: data) if let success = success { success(response_oc) } }) case .blank: response = ArResponse.blank({ let response_oc = ArResponseOC(type: successCallbackContent, json: nil, data: nil) if let success = success { success(response_oc) } }) } request(task: swift_task, responseOnMainQueue: responseOnMainQueue, success: response) { (error) -> ArRetryOptions in if let fail = fail { let swift_error = error let oc_error = ArErrorOC(domain: swift_error.localizedDescription, code: swift_error.code ?? -1, userInfo: nil) oc_error.reposeData = swift_error.responseData let failRetryInterval = fail(oc_error); if failRetryInterval > 0 { return .retry(after: failRetryInterval) } else { return .resign } } else { return .resign } } } @objc public func upload(task: ArUploadTaskOC, responseOnMainQueue: Bool = true, successCallbackContent: ArResponseTypeOC, success: ((ArResponseOC) -> Void)? = nil, fail: ArErrorRetryCompletionOC = nil) { var response: ArResponse switch successCallbackContent { case .json: response = ArResponse.json({ (json) in let response_oc = ArResponseOC(type: successCallbackContent, json: json, data: nil) if let success = success { success(response_oc) } }) case .data: response = ArResponse.data({ (data) in let response_oc = ArResponseOC(type: successCallbackContent, json: nil, data: data) if let success = success { success(response_oc) } }) case .blank: response = ArResponse.blank({ let response_oc = ArResponseOC(type: successCallbackContent, json: nil, data: nil) if let success = success { success(response_oc) } }) } let swift_task = ArUploadTask.oc(task) upload(task: swift_task, responseOnMainQueue: responseOnMainQueue, success: response) { (error) -> ArRetryOptions in if let fail = fail { let swift_error = error let oc_error = ArErrorOC(domain: swift_error.localizedDescription, code: swift_error.code ?? -1, userInfo: nil) oc_error.reposeData = swift_error.responseData let failRetryInterval = fail(oc_error); if failRetryInterval > 0 { return .retry(after: failRetryInterval) } else { return .resign } } else { return .resign } } } } extension ArminOC: ArminDelegate { public func armin(_ client: Armin, requestSuccess event: ArRequestEvent, startTime: TimeInterval, url: String) { let eventOC = ArRequestEventOC(name: event.name) self.delegateOC?.armin(self, requestSuccess: eventOC, startTime: startTime, url: url) } public func armin(_ client: Armin, requestFail error: ArError, event: ArRequestEvent, url: String) { let eventOC = ArRequestEventOC(name: event.name) let errorOC = ArErrorOC(domain: error.localizedDescription, code: error.code ?? -1, userInfo: nil) self.delegateOC?.armin(self, requestFail: errorOC, event: eventOC, url: url) } } extension ArminOC: ArLogTube { public func log(info: String, extra: String?) { logTubeOC?.log(info: info, extra: extra) } public func log(warning: String, extra: String?) { logTubeOC?.log(warning: warning, extra: extra) } public func log(error: ArError, extra: String?) { let oc_error = ArErrorOC(domain: error.localizedDescription, code: error.code ?? -1, userInfo: nil) oc_error.reposeData = error.responseData logTubeOC?.log(error: oc_error, extra: extra) } } fileprivate extension ArRequestTask { static func oc(_ item: ArRequestTaskOC) -> ArRequestTask { let swift_event = ArRequestEvent(name: item.event.name) let swift_type = ArRequestType.oc(item.requestType) return ArRequestTask(event: swift_event, type: swift_type, timeout: .custom(item.timeout), header: item.header, parameters: item.parameters) } } fileprivate extension ArRequestType { static func oc(_ item: ArRequestTypeObjectOC) -> ArRequestType { switch item.type { case .http: if let http = item as? ArRequestTypeJsonObjectOC { return ArRequestType.http(ArHttpMethod.oc(http.method), url: http.url) } else { fatalError("ArRequestType error") } case .socket: if let socket = item as? ArRequestTypeSocketObjectOC { return ArRequestType.socket(peer: socket.peer) } else { fatalError("ArRequestType error") } } } } fileprivate extension ArHttpMethod { static func oc(_ item: ArHTTPMethodOC) -> ArHttpMethod { switch item { case .options: return .options case .connect: return .connect case .delete: return .delete case .get: return .get case .head: return .head case .patch: return .patch case .post: return .post case .put: return .put case .trace: return .trace } } } fileprivate extension ArFileMIME { static func oc(_ item: ArFileMIMEOC) -> ArFileMIME { switch item { case .png: return .png case .zip: return .zip } } } fileprivate extension ArUploadTask { static func oc(_ item: ArUploadTaskOC) -> ArUploadTask { let siwft_mime = ArFileMIME.oc(item.object.mime) let swift_object = ArUploadObject(fileKeyOnServer: item.object.fileKeyOnServer, fileName: item.object.fileName, fileData: item.object.fileData, mime: siwft_mime) let swift_event = ArRequestEvent(name: item.event.name) let swift_task = ArUploadTask(event: swift_event, timeout: .custom(item.timeout), object: swift_object, url: item.url, header: item.header, parameters: item.header) return swift_task } }
36.084746
87
0.465195
642a12e2c1a7f3225a802d28166042dfed24d137
5,383
// // BBMenuCellsModel.swift // BBSwiftFramework // // Created by Bei Wang on 10/16/15. // Copyright © 2015 BooYah. All rights reserved. // import UIKit class BBMenuCellsModel: NSObject { enum eSectionType: Int { case Section_0 case Section_1 case Section_2 case Section_3 case Section_4 } enum eCellType: Int { case Cell_0 case Cell_1 case Cell_2 case Cell_3 case Cell_4 } var sectionArray: NSMutableArray = NSMutableArray() // MARK: - --------------------System-------------------- // MARK: - --------------------功能函数-------------------- // MARK: 初始化 private func addCellsToSection(sectionType: eSectionType) -> NSDictionary { let dictionary: NSMutableDictionary = NSMutableDictionary() let cells: NSMutableArray = NSMutableArray() switch sectionType { case .Section_0: cells.addObject(eCellType.Cell_0.rawValue) case .Section_1: cells.addObject(eCellType.Cell_1.rawValue) case .Section_2: cells.addObject(eCellType.Cell_2.rawValue) case .Section_3: cells.addObject(eCellType.Cell_3.rawValue) case .Section_4: cells.addObject(eCellType.Cell_4.rawValue) } dictionary.setObject(cells, forKey: sectionType.rawValue) return dictionary } private func getCellType(indexPath: NSIndexPath) -> eCellType { let dictionary = self.sectionArray.objectAtIndex(indexPath.section) as! NSDictionary let key = dictionary.allKeys as NSArray let cells = dictionary.objectForKey(key.firstObject!) as! NSArray // let cellType = cells.objectAtIndex(indexPath.row) as! eCellType // WARNING: cellType var cellType: eCellType = .Cell_0 switch(cells.objectAtIndex(indexPath.row).unsignedIntegerValue) { case 0: cellType = .Cell_0 case 1: cellType = .Cell_1 case 2: cellType = .Cell_2 case 3: cellType = .Cell_3 case 4: cellType = .Cell_4 default: break } return cellType } private func getIdentifierWithType(type: eCellType) -> String { var identifier: String switch (type) { case .Cell_0: identifier = "BBMenuButtonCell" case .Cell_1: identifier = "BBMenuButtonCell" case .Cell_2: identifier = "BBMenuButtonCell" case .Cell_3: identifier = "BBMenuButtonCell" case .Cell_4: identifier = "BBMenuButtonCell" } return identifier } private func getCellWithType(type: eCellType) -> BBTableViewCell { let cell: BBMenuButtonCell = BBTableViewCell.cellFromXib("BBMenuButtonCell") as! BBMenuButtonCell switch (type) { case .Cell_0:break case .Cell_1:break case .Cell_2:break case .Cell_3:break case .Cell_4:break } return cell } // MARK: - --------------------手势事件-------------------- // MARK: 各种手势处理函数注释 // MARK: - --------------------按钮事件-------------------- // MARK: 按钮点击函数注释 // MARK: - --------------------代理方法-------------------- // MARK: - 代理种类注释 // MARK: 代理函数注释 // MARK: - --------------------属性相关-------------------- // MARK: 属性操作函数注释 // MARK: - --------------------接口API-------------------- // MARK: 分块内接口函数注释 func createTableData() { self.sectionArray.addObject(self.addCellsToSection(eSectionType.Section_0)) self.sectionArray.addObject(self.addCellsToSection(eSectionType.Section_1)) self.sectionArray.addObject(self.addCellsToSection(eSectionType.Section_2)) self.sectionArray.addObject(self.addCellsToSection(eSectionType.Section_3)) self.sectionArray.addObject(self.addCellsToSection(eSectionType.Section_4)) } func getIdentifierByCellIndex(indexPath: NSIndexPath) -> String { return self.getIdentifierWithType(self.getCellType(indexPath)) } func configCell(cell: BBTableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let customCell: BBMenuButtonCell = cell as! BBMenuButtonCell let cellType: eCellType = self.getCellType(indexPath) switch (cellType) { case .Cell_0: customCell.menuImageView.image = UIImage(named: "icon-1") case .Cell_1: customCell.menuImageView.image = UIImage(named: "icon-2") case .Cell_2: customCell.menuImageView.image = UIImage(named: "icon-3") case .Cell_3: customCell.menuImageView.image = UIImage(named: "icon-4") case .Cell_4: customCell.menuImageView.image = UIImage(named: "icon-5") } } func cellForRowAtIndexPath(indexPath: NSIndexPath) -> BBTableViewCell { return self.getCellWithType(self.getCellType(indexPath)) } func heightForRowAtIndexPath(indexPath: NSIndexPath) -> CGFloat { return 70; } }
33.02454
105
0.561583
03b5b1f9bce39130fe678b32fe49309c0abd74c7
838
// // AppDelegate.swift // Example // // Created by Robert Edwards on 8/6/15. // Copyright © 2015 Big Nerd Ranch. All rights reserved. // import UIKit import CoreDataStack @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private var coreDataStack: CoreDataStack? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { CoreDataStack.constructSQLiteStack(withModelName: "TestModel") { result in switch result { case .Success(let stack): self.coreDataStack = stack print("Success") case .Failure(let error): print(error) assertionFailure() } } return true } }
23.277778
127
0.627685
e4cddd6ebd441599901bcbce56caef1528bfaf46
4,405
// // CelebrityView.swift // NetflexTestApp // // Created by 김광준 on 2020/09/11. // Copyright © 2020 VincentGeranium. All rights reserved. // import UIKit class CelebrityView: UIView { lazy var celebrityLabel: UILabel = { let celebrityLabel: UILabel = UILabel() celebrityLabel.backgroundColor = .white celebrityLabel.clipsToBounds = true celebrityLabel.layer.cornerRadius = 12 celebrityLabel.textAlignment = .center celebrityLabel.text = "당신과 같은 취향을 가진 배우는" celebrityLabel.font = UIFont.boldSystemFont(ofSize: 19) return celebrityLabel }() lazy var leftCelebrityNameLabel: UILabel = { let leftCelebrityNameLabel: UILabel = UILabel() leftCelebrityNameLabel.backgroundColor = .white leftCelebrityNameLabel.clipsToBounds = true leftCelebrityNameLabel.layer.cornerRadius = 12 leftCelebrityNameLabel.textAlignment = .center leftCelebrityNameLabel.text = "배두나" leftCelebrityNameLabel.font = UIFont.boldSystemFont(ofSize: 19) return leftCelebrityNameLabel }() lazy var rightCelebrityNameLabel: UILabel = { let rightCelebrityNameLabel: UILabel = UILabel() rightCelebrityNameLabel.backgroundColor = .white rightCelebrityNameLabel.clipsToBounds = true rightCelebrityNameLabel.layer.cornerRadius = 12 rightCelebrityNameLabel.textAlignment = .center rightCelebrityNameLabel.text = "주지훈" rightCelebrityNameLabel.font = UIFont.boldSystemFont(ofSize: 19) return rightCelebrityNameLabel }() override init(frame: CGRect) { super .init(frame: frame) addViews() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addViews() { setupCelebrityLabel() setupLeftCelebrityNameLabel() setupRightCelebrityNameLabel() } private func setupCelebrityLabel() { let guide = self.safeAreaLayoutGuide celebrityLabel.translatesAutoresizingMaskIntoConstraints = false self.addSubview(celebrityLabel) NSLayoutConstraint.activate([ celebrityLabel.topAnchor.constraint(equalTo: guide.topAnchor, constant: 10), celebrityLabel.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 10), celebrityLabel.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -10), celebrityLabel.heightAnchor.constraint(equalTo: guide.heightAnchor, multiplier: 1/4) ]) } private func setupLeftCelebrityNameLabel() { let guide = self.safeAreaLayoutGuide leftCelebrityNameLabel.translatesAutoresizingMaskIntoConstraints = false self.addSubview(leftCelebrityNameLabel) NSLayoutConstraint.activate([ leftCelebrityNameLabel.topAnchor.constraint(equalTo: celebrityLabel.bottomAnchor, constant: 10), leftCelebrityNameLabel.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 10), leftCelebrityNameLabel.widthAnchor.constraint(equalTo: guide.widthAnchor, multiplier: 1/2, constant: -10), leftCelebrityNameLabel.heightAnchor.constraint(equalTo: guide.heightAnchor, multiplier: 1/2), leftCelebrityNameLabel.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -10), ]) } private func setupRightCelebrityNameLabel() { let guide = self.safeAreaLayoutGuide rightCelebrityNameLabel.translatesAutoresizingMaskIntoConstraints = false self.addSubview(rightCelebrityNameLabel) NSLayoutConstraint.activate([ rightCelebrityNameLabel.topAnchor.constraint(equalTo: celebrityLabel.bottomAnchor, constant: 10), rightCelebrityNameLabel.leadingAnchor.constraint(equalTo: leftCelebrityNameLabel.trailingAnchor, constant: 5), rightCelebrityNameLabel.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -10), rightCelebrityNameLabel.heightAnchor.constraint(equalTo: guide.heightAnchor, multiplier: 1/2), rightCelebrityNameLabel.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -10), ]) } }
39.330357
122
0.687628
382c65393acefb7f7405ff3561330fa315f08154
1,416
// // readers.swift // Stats // // Created by Serhiy Mytrovtsiy on 17/06/2020. // Using Swift 5.0. // Running on macOS 10.15. // // Copyright © 2020 Serhiy Mytrovtsiy. All rights reserved. // import Cocoa import ModuleKit import StatsKit internal class SensorsReader: Reader<[Sensor_t]> { internal var list: [Sensor_t] = [] private var smc: UnsafePointer<SMCService> init(_ smc: UnsafePointer<SMCService>) { self.smc = smc var available: [String] = self.smc.pointee.getAllKeys() var list: [Sensor_t] = [] available = available.filter({ (key: String) -> Bool in switch key.prefix(1) { case "T", "V", "P": return SensorsDict[key] != nil default: return false } }) available.forEach { (key: String) in if var sensor = SensorsDict[key] { sensor.value = smc.pointee.getValue(key) if sensor.value != nil { sensor.key = key list.append(sensor) } } } self.list = list } public override func read() { for i in 0..<self.list.count { if let newValue = self.smc.pointee.getValue(self.list[i].key) { self.list[i].value = newValue } } self.callback(self.list) } }
25.745455
75
0.521893
e4e36ded849f62c472a8b30a8c9a7fb321ebf2fa
2,947
// // InputTests.swift // SwiftCLITests // // Created by Jake Heiser on 3/15/18. // import XCTest @testable import SwiftCLI class InputTests: XCTestCase { private var input: [String] = [] override func setUp() { super.setUp() Term.read = { return self.input.removeFirst() } } func testInt() { input = ["asdf", "3.4", "5"] let (out, err) = CLI.capture { let int = Input.readInt() XCTAssertEqual(int, 5) } XCTAssertEqual(out, "") XCTAssertEqual(err, """ Invalid value; expected Int Invalid value; expected Int """) } func testDouble() { input = ["asdf", "3.4", "5"] let (out, err) = CLI.capture { let double = Input.readDouble() XCTAssertEqual(double, 3.4) } XCTAssertEqual(out, "") XCTAssertEqual(err, """ Invalid value; expected Double """) } func testBool() { input = ["asdf", "5", "false"] let (out, err) = CLI.capture { let bool = Input.readBool() XCTAssertEqual(bool, false) } XCTAssertEqual(out, "") XCTAssertEqual(err, """ Invalid value; expected Bool Invalid value; expected Bool """) input = ["asdf", "5", "T"] let (out2, err2) = CLI.capture { let bool = Input.readBool() XCTAssertEqual(bool, true) } XCTAssertEqual(out2, "") XCTAssertEqual(err2, """ Invalid value; expected Bool Invalid value; expected Bool """) input = ["asdf", "yeppp", "YES"] let (out3, err3) = CLI.capture { let bool = Input.readBool() XCTAssertEqual(bool, true) } XCTAssertEqual(out3, "") XCTAssertEqual(err3, """ Invalid value; expected Bool Invalid value; expected Bool """) } func testValidation() { input = ["asdf", "3.4", "5", "9", "11"] let (out, err) = CLI.capture { let int = Input.readInt(validation: [.greaterThan(10)]) XCTAssertEqual(int, 11) } XCTAssertEqual(out, "") XCTAssertEqual(err, """ Invalid value; expected Int Invalid value; expected Int Invalid value; must be greater than 10 Invalid value; must be greater than 10 """) input = ["asdf", "5", "false", "SwiftCLI"] let (out2, err2) = CLI.capture { let str = Input.readLine(validation: [.contains("ift")]) XCTAssertEqual(str, "SwiftCLI") } XCTAssertEqual(out2, "") XCTAssertEqual(err2, """ Invalid value; must contain 'ift' Invalid value; must contain 'ift' Invalid value; must contain 'ift' """) } }
24.974576
68
0.50017
2191f3838d96dcdcbb71ef2f9158a6518422d614
1,014
// // iOSStringSizeCalculator.swift // JABSwiftCore // // Created by Jeremy Bannister on 6/8/18. // Copyright © 2018 Jeremy Bannister. All rights reserved. // import UIKit public class iOSStringSizeCalculator: StringSizeCalculator { public func size (of string: String, constrainedToWidth width: Double?, usingFont font: Font) -> Size { var attributes: [NSAttributedStringKey: Any] = [.font: UIFont(font) as Any] attributes[.kern] = font.characterSpacing let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = CGFloat(font.lineHeightMultiple) attributes[.paragraphStyle] = paragraphStyle return (string as NSString).boundingRect(with: CGSize(width: width ?? 0, height: Double.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil).size.asSize } }
40.56
117
0.658777
08fd7b9818cace459cc20ff97d9bafafe504ca6e
646
// // Button+Modifier.swift // Footnote // // Created by Raj Raval on 05/10/20. // Copyright © 2020 Cameron Bardell. All rights reserved. // import SwiftUI struct RoundedButton: ViewModifier { func body(content: Content) -> some View { content .frame(maxWidth: .infinity, maxHeight: 48) .background(Color.blue) .cornerRadius(10) .font(.body) .multilineTextAlignment(.center) .foregroundColor(.white) .padding(.horizontal, 36) } } extension View { func roundedButtonStyle() -> some View { self.modifier(RoundedButton()) } }
22.275862
58
0.595975
76da1e83027e681fff65d11a5b645ee1c428e06a
84,070
// This file was generated from JSON Schema using quicktype, do not modify it directly. // To parse the JSON, add this file to your project and do: // // let feed = try Feed(json) import Foundation // MARK: - Feed struct Feed: Codable { let statusCode, minCursor, maxCursor, hasMore: Int? let awemeList: [AwemeList]? let homeModel, refreshClear: Int? let extra: Extra? let logPb: LogPb? let preloadAds: [JSONAny]? enum CodingKeys: String, CodingKey { case statusCode = "status_code" case minCursor = "min_cursor" case maxCursor = "max_cursor" case hasMore = "has_more" case awemeList = "aweme_list" case homeModel = "home_model" case refreshClear = "refresh_clear" case extra case logPb = "log_pb" case preloadAds = "preload_ads" } } // MARK: Feed convenience initializers and mutators extension Feed { init(data: Data) throws { self = try newJSONDecoder().decode(Feed.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( statusCode: Int?? = nil, minCursor: Int?? = nil, maxCursor: Int?? = nil, hasMore: Int?? = nil, awemeList: [AwemeList]?? = nil, homeModel: Int?? = nil, refreshClear: Int?? = nil, extra: Extra?? = nil, logPb: LogPb?? = nil, preloadAds: [JSONAny]?? = nil ) -> Feed { return Feed( statusCode: statusCode ?? self.statusCode, minCursor: minCursor ?? self.minCursor, maxCursor: maxCursor ?? self.maxCursor, hasMore: hasMore ?? self.hasMore, awemeList: awemeList ?? self.awemeList, homeModel: homeModel ?? self.homeModel, refreshClear: refreshClear ?? self.refreshClear, extra: extra ?? self.extra, logPb: logPb ?? self.logPb, preloadAds: preloadAds ?? self.preloadAds ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - AwemeList struct AwemeList: Codable { let awemeID, desc: String? let createTime: Int? let author: AwemeListAuthor? let music: Music? let chaList: [ChaList]? let video: Video? let shareURL: String? let userDigged: Int? let statistics: Statistics? let status: Status? let rate: Int? let textExtra: [JSONAny]? let isTop: Int? let labelTop: ArakGroundhog? let shareInfo: ChaListShareInfo? let distance: String? let videoLabels: [JSONAny]? let isVR, isAds: Bool? let duration, awemeType: Int? let isFantasy, cmtSWT: Bool? let imageInfos: JSONNull? let riskInfos: RiskInfos? let isRelieve: Bool? let sortLabel: String? let position, uniqidPosition, commentList: JSONNull? let authorUserID, bodydanceScore: Int? let geofencing: [JSONAny]? let isHashTag: Int? let isPgcshow: Bool? let region: String? let videoText: [JSONAny]? let vrType, collectStat: Int? let labelTopText: JSONNull? let promotions: [JSONAny]? let groupID: String? let preventDownload: Bool? let nicknamePosition, challengePosition: JSONNull? let itemCommentSettings: Int? let descendants: Descendants? let withPromotionalMusic: Bool? let xiguaTask: XiguaTask? let longVideo: JSONNull? let itemDuet, itemReact: Int? let descLanguage: String? let interactionStickers: JSONNull? let adLinkType: Int? let originCommentIDS, commerceConfigData: JSONNull? let enableTopView: Bool? let distributeType: Int? let videoControl: VideoControl? let awemeControl: AwemeControl? enum CodingKeys: String, CodingKey { case awemeID = "aweme_id" case desc case createTime = "create_time" case author, music case chaList = "cha_list" case video case shareURL = "share_url" case userDigged = "user_digged" case statistics, status, rate case textExtra = "text_extra" case isTop = "is_top" case labelTop = "label_top" case shareInfo = "share_info" case distance case videoLabels = "video_labels" case isVR = "is_vr" case isAds = "is_ads" case duration case awemeType = "aweme_type" case isFantasy = "is_fantasy" case cmtSWT = "cmt_swt" case imageInfos = "image_infos" case riskInfos = "risk_infos" case isRelieve = "is_relieve" case sortLabel = "sort_label" case position case uniqidPosition = "uniqid_position" case commentList = "comment_list" case authorUserID = "author_user_id" case bodydanceScore = "bodydance_score" case geofencing case isHashTag = "is_hash_tag" case isPgcshow = "is_pgcshow" case region case videoText = "video_text" case vrType = "vr_type" case collectStat = "collect_stat" case labelTopText = "label_top_text" case promotions case groupID = "group_id" case preventDownload = "prevent_download" case nicknamePosition = "nickname_position" case challengePosition = "challenge_position" case itemCommentSettings = "item_comment_settings" case descendants case withPromotionalMusic = "with_promotional_music" case xiguaTask = "xigua_task" case longVideo = "long_video" case itemDuet = "item_duet" case itemReact = "item_react" case descLanguage = "desc_language" case interactionStickers = "interaction_stickers" case adLinkType = "ad_link_type" case originCommentIDS = "origin_comment_ids" case commerceConfigData = "commerce_config_data" case enableTopView = "enable_top_view" case distributeType = "distribute_type" case videoControl = "video_control" case awemeControl = "aweme_control" } } // MARK: AwemeList convenience initializers and mutators extension AwemeList { init(data: Data) throws { self = try newJSONDecoder().decode(AwemeList.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( awemeID: String?? = nil, desc: String?? = nil, createTime: Int?? = nil, author: AwemeListAuthor?? = nil, music: Music?? = nil, chaList: [ChaList]?? = nil, video: Video?? = nil, shareURL: String?? = nil, userDigged: Int?? = nil, statistics: Statistics?? = nil, status: Status?? = nil, rate: Int?? = nil, textExtra: [JSONAny]?? = nil, isTop: Int?? = nil, labelTop: ArakGroundhog?? = nil, shareInfo: ChaListShareInfo?? = nil, distance: String?? = nil, videoLabels: [JSONAny]?? = nil, isVR: Bool?? = nil, isAds: Bool?? = nil, duration: Int?? = nil, awemeType: Int?? = nil, isFantasy: Bool?? = nil, cmtSWT: Bool?? = nil, imageInfos: JSONNull?? = nil, riskInfos: RiskInfos?? = nil, isRelieve: Bool?? = nil, sortLabel: String?? = nil, position: JSONNull?? = nil, uniqidPosition: JSONNull?? = nil, commentList: JSONNull?? = nil, authorUserID: Int?? = nil, bodydanceScore: Int?? = nil, geofencing: [JSONAny]?? = nil, isHashTag: Int?? = nil, isPgcshow: Bool?? = nil, region: String?? = nil, videoText: [JSONAny]?? = nil, vrType: Int?? = nil, collectStat: Int?? = nil, labelTopText: JSONNull?? = nil, promotions: [JSONAny]?? = nil, groupID: String?? = nil, preventDownload: Bool?? = nil, nicknamePosition: JSONNull?? = nil, challengePosition: JSONNull?? = nil, itemCommentSettings: Int?? = nil, descendants: Descendants?? = nil, withPromotionalMusic: Bool?? = nil, xiguaTask: XiguaTask?? = nil, longVideo: JSONNull?? = nil, itemDuet: Int?? = nil, itemReact: Int?? = nil, descLanguage: String?? = nil, interactionStickers: JSONNull?? = nil, adLinkType: Int?? = nil, originCommentIDS: JSONNull?? = nil, commerceConfigData: JSONNull?? = nil, enableTopView: Bool?? = nil, distributeType: Int?? = nil, videoControl: VideoControl?? = nil, awemeControl: AwemeControl?? = nil ) -> AwemeList { return AwemeList( awemeID: awemeID ?? self.awemeID, desc: desc ?? self.desc, createTime: createTime ?? self.createTime, author: author ?? self.author, music: music ?? self.music, chaList: chaList ?? self.chaList, video: video ?? self.video, shareURL: shareURL ?? self.shareURL, userDigged: userDigged ?? self.userDigged, statistics: statistics ?? self.statistics, status: status ?? self.status, rate: rate ?? self.rate, textExtra: textExtra ?? self.textExtra, isTop: isTop ?? self.isTop, labelTop: labelTop ?? self.labelTop, shareInfo: shareInfo ?? self.shareInfo, distance: distance ?? self.distance, videoLabels: videoLabels ?? self.videoLabels, isVR: isVR ?? self.isVR, isAds: isAds ?? self.isAds, duration: duration ?? self.duration, awemeType: awemeType ?? self.awemeType, isFantasy: isFantasy ?? self.isFantasy, cmtSWT: cmtSWT ?? self.cmtSWT, imageInfos: imageInfos ?? self.imageInfos, riskInfos: riskInfos ?? self.riskInfos, isRelieve: isRelieve ?? self.isRelieve, sortLabel: sortLabel ?? self.sortLabel, position: position ?? self.position, uniqidPosition: uniqidPosition ?? self.uniqidPosition, commentList: commentList ?? self.commentList, authorUserID: authorUserID ?? self.authorUserID, bodydanceScore: bodydanceScore ?? self.bodydanceScore, geofencing: geofencing ?? self.geofencing, isHashTag: isHashTag ?? self.isHashTag, isPgcshow: isPgcshow ?? self.isPgcshow, region: region ?? self.region, videoText: videoText ?? self.videoText, vrType: vrType ?? self.vrType, collectStat: collectStat ?? self.collectStat, labelTopText: labelTopText ?? self.labelTopText, promotions: promotions ?? self.promotions, groupID: groupID ?? self.groupID, preventDownload: preventDownload ?? self.preventDownload, nicknamePosition: nicknamePosition ?? self.nicknamePosition, challengePosition: challengePosition ?? self.challengePosition, itemCommentSettings: itemCommentSettings ?? self.itemCommentSettings, descendants: descendants ?? self.descendants, withPromotionalMusic: withPromotionalMusic ?? self.withPromotionalMusic, xiguaTask: xiguaTask ?? self.xiguaTask, longVideo: longVideo ?? self.longVideo, itemDuet: itemDuet ?? self.itemDuet, itemReact: itemReact ?? self.itemReact, descLanguage: descLanguage ?? self.descLanguage, interactionStickers: interactionStickers ?? self.interactionStickers, adLinkType: adLinkType ?? self.adLinkType, originCommentIDS: originCommentIDS ?? self.originCommentIDS, commerceConfigData: commerceConfigData ?? self.commerceConfigData, enableTopView: enableTopView ?? self.enableTopView, distributeType: distributeType ?? self.distributeType, videoControl: videoControl ?? self.videoControl, awemeControl: awemeControl ?? self.awemeControl ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - AwemeListAuthor struct AwemeListAuthor: Codable { let uid, shortID, nickname: String? let gender: Int? let signature: String? let avatarLarger, avatarThumb, avatarMedium: ArakGroundhog? let birthday: String? let isVerified: Bool? let followStatus, awemeCount, followingCount, followerCount: Int? let favoritingCount, totalFavorited: Int? let isBlock, hideSearch: Bool? let constellation: Int? let location: String? let hideLocation: Bool? let weiboVerify, customVerify, uniqueID, bindPhone: String? let specialLock, needRecommend: Int? let isBindedWeibo: Bool? let weiboName, weiboSchema, weiboURL: String? let storyOpen: Bool? let storyCount: Int? let hasFacebookToken, hasTwitterToken: Bool? let fbExpireTime, twExpireTime: Int? let hasYoutubeToken: Bool? let youtubeExpireTime: Int? let roomID: Double? let liveVerify, authorityStatus: Int? let verifyInfo: String? let shieldFollowNotice, shieldDiggNotice, shieldCommentNotice: Int? let schoolName, schoolPoiID: String? let schoolType: Int? let shareInfo: AuthorShareInfo? let withCommerceEntry: Bool? let verificationType: Int? let enterpriseVerifyReason: String? let isAdFake: Bool? let followersDetail: JSONNull? let region, accountRegion: String? let syncToToutiao, commerceUserLevel, liveAgreement: Int? let platformSyncInfo: JSONNull? let withShopEntry, isDisciplineMember: Bool? let secret: Int? let hasOrders, preventDownload, showImageBubble: Bool? let geofencing: [JSONAny]? let uniqueIDModifyTime: Int? let videoIcon: ArakGroundhog? let insID, googleAccount, youtubeChannelID, youtubeChannelTitle: String? let appleAccount: Int? let withDouEntry, withFusionShopEntry, isPhoneBinded, acceptPrivatePolicy: Bool? let twitterID, twitterName: String? let userCanceled, hasEmail, isGovMediaVip: Bool? let liveAgreementTime, status, createTime: Int? let avatarURI: String? let followerStatus, neiguangShield, commentSetting, duetSetting: Int? let reflowPageGid, reflowPageUid, userRate, downloadSetting: Int? let downloadPromptTs, reactSetting: Int? let liveCommerce: Bool? let coverURL: [ArakGroundhog]? let language: String? let hasInsights: Bool? let shareQrcodeURI: String? let itemList: JSONNull? let userMode, userPeriod: Int? let hasUnreadStory: Bool? let newStoryCover: JSONNull? let isStar: Bool? let cvLevel: String? let typeLabel, adCoverURL: JSONNull? let commentFilterStatus: Int? let avatar168X168, avatar300X300: ArakGroundhog? let relativeUsers, chaList: JSONNull? let secUid: String? enum CodingKeys: String, CodingKey { case uid case shortID = "short_id" case nickname, gender, signature case avatarLarger = "avatar_larger" case avatarThumb = "avatar_thumb" case avatarMedium = "avatar_medium" case birthday case isVerified = "is_verified" case followStatus = "follow_status" case awemeCount = "aweme_count" case followingCount = "following_count" case followerCount = "follower_count" case favoritingCount = "favoriting_count" case totalFavorited = "total_favorited" case isBlock = "is_block" case hideSearch = "hide_search" case constellation, location case hideLocation = "hide_location" case weiboVerify = "weibo_verify" case customVerify = "custom_verify" case uniqueID = "unique_id" case bindPhone = "bind_phone" case specialLock = "special_lock" case needRecommend = "need_recommend" case isBindedWeibo = "is_binded_weibo" case weiboName = "weibo_name" case weiboSchema = "weibo_schema" case weiboURL = "weibo_url" case storyOpen = "story_open" case storyCount = "story_count" case hasFacebookToken = "has_facebook_token" case hasTwitterToken = "has_twitter_token" case fbExpireTime = "fb_expire_time" case twExpireTime = "tw_expire_time" case hasYoutubeToken = "has_youtube_token" case youtubeExpireTime = "youtube_expire_time" case roomID = "room_id" case liveVerify = "live_verify" case authorityStatus = "authority_status" case verifyInfo = "verify_info" case shieldFollowNotice = "shield_follow_notice" case shieldDiggNotice = "shield_digg_notice" case shieldCommentNotice = "shield_comment_notice" case schoolName = "school_name" case schoolPoiID = "school_poi_id" case schoolType = "school_type" case shareInfo = "share_info" case withCommerceEntry = "with_commerce_entry" case verificationType = "verification_type" case enterpriseVerifyReason = "enterprise_verify_reason" case isAdFake = "is_ad_fake" case followersDetail = "followers_detail" case region case accountRegion = "account_region" case syncToToutiao = "sync_to_toutiao" case commerceUserLevel = "commerce_user_level" case liveAgreement = "live_agreement" case platformSyncInfo = "platform_sync_info" case withShopEntry = "with_shop_entry" case isDisciplineMember = "is_discipline_member" case secret case hasOrders = "has_orders" case preventDownload = "prevent_download" case showImageBubble = "show_image_bubble" case geofencing case uniqueIDModifyTime = "unique_id_modify_time" case videoIcon = "video_icon" case insID = "ins_id" case googleAccount = "google_account" case youtubeChannelID = "youtube_channel_id" case youtubeChannelTitle = "youtube_channel_title" case appleAccount = "apple_account" case withDouEntry = "with_dou_entry" case withFusionShopEntry = "with_fusion_shop_entry" case isPhoneBinded = "is_phone_binded" case acceptPrivatePolicy = "accept_private_policy" case twitterID = "twitter_id" case twitterName = "twitter_name" case userCanceled = "user_canceled" case hasEmail = "has_email" case isGovMediaVip = "is_gov_media_vip" case liveAgreementTime = "live_agreement_time" case status case createTime = "create_time" case avatarURI = "avatar_uri" case followerStatus = "follower_status" case neiguangShield = "neiguang_shield" case commentSetting = "comment_setting" case duetSetting = "duet_setting" case reflowPageGid = "reflow_page_gid" case reflowPageUid = "reflow_page_uid" case userRate = "user_rate" case downloadSetting = "download_setting" case downloadPromptTs = "download_prompt_ts" case reactSetting = "react_setting" case liveCommerce = "live_commerce" case coverURL = "cover_url" case language case hasInsights = "has_insights" case shareQrcodeURI = "share_qrcode_uri" case itemList = "item_list" case userMode = "user_mode" case userPeriod = "user_period" case hasUnreadStory = "has_unread_story" case newStoryCover = "new_story_cover" case isStar = "is_star" case cvLevel = "cv_level" case typeLabel = "type_label" case adCoverURL = "ad_cover_url" case commentFilterStatus = "comment_filter_status" case avatar168X168 = "avatar_168x168" case avatar300X300 = "avatar_300x300" case relativeUsers = "relative_users" case chaList = "cha_list" case secUid = "sec_uid" } } // MARK: AwemeListAuthor convenience initializers and mutators extension AwemeListAuthor { init(data: Data) throws { self = try newJSONDecoder().decode(AwemeListAuthor.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( uid: String?? = nil, shortID: String?? = nil, nickname: String?? = nil, gender: Int?? = nil, signature: String?? = nil, avatarLarger: ArakGroundhog?? = nil, avatarThumb: ArakGroundhog?? = nil, avatarMedium: ArakGroundhog?? = nil, birthday: String?? = nil, isVerified: Bool?? = nil, followStatus: Int?? = nil, awemeCount: Int?? = nil, followingCount: Int?? = nil, followerCount: Int?? = nil, favoritingCount: Int?? = nil, totalFavorited: Int?? = nil, isBlock: Bool?? = nil, hideSearch: Bool?? = nil, constellation: Int?? = nil, location: String?? = nil, hideLocation: Bool?? = nil, weiboVerify: String?? = nil, customVerify: String?? = nil, uniqueID: String?? = nil, bindPhone: String?? = nil, specialLock: Int?? = nil, needRecommend: Int?? = nil, isBindedWeibo: Bool?? = nil, weiboName: String?? = nil, weiboSchema: String?? = nil, weiboURL: String?? = nil, storyOpen: Bool?? = nil, storyCount: Int?? = nil, hasFacebookToken: Bool?? = nil, hasTwitterToken: Bool?? = nil, fbExpireTime: Int?? = nil, twExpireTime: Int?? = nil, hasYoutubeToken: Bool?? = nil, youtubeExpireTime: Int?? = nil, roomID: Double?? = nil, liveVerify: Int?? = nil, authorityStatus: Int?? = nil, verifyInfo: String?? = nil, shieldFollowNotice: Int?? = nil, shieldDiggNotice: Int?? = nil, shieldCommentNotice: Int?? = nil, schoolName: String?? = nil, schoolPoiID: String?? = nil, schoolType: Int?? = nil, shareInfo: AuthorShareInfo?? = nil, withCommerceEntry: Bool?? = nil, verificationType: Int?? = nil, enterpriseVerifyReason: String?? = nil, isAdFake: Bool?? = nil, followersDetail: JSONNull?? = nil, region: String?? = nil, accountRegion: String?? = nil, syncToToutiao: Int?? = nil, commerceUserLevel: Int?? = nil, liveAgreement: Int?? = nil, platformSyncInfo: JSONNull?? = nil, withShopEntry: Bool?? = nil, isDisciplineMember: Bool?? = nil, secret: Int?? = nil, hasOrders: Bool?? = nil, preventDownload: Bool?? = nil, showImageBubble: Bool?? = nil, geofencing: [JSONAny]?? = nil, uniqueIDModifyTime: Int?? = nil, videoIcon: ArakGroundhog?? = nil, insID: String?? = nil, googleAccount: String?? = nil, youtubeChannelID: String?? = nil, youtubeChannelTitle: String?? = nil, appleAccount: Int?? = nil, withDouEntry: Bool?? = nil, withFusionShopEntry: Bool?? = nil, isPhoneBinded: Bool?? = nil, acceptPrivatePolicy: Bool?? = nil, twitterID: String?? = nil, twitterName: String?? = nil, userCanceled: Bool?? = nil, hasEmail: Bool?? = nil, isGovMediaVip: Bool?? = nil, liveAgreementTime: Int?? = nil, status: Int?? = nil, createTime: Int?? = nil, avatarURI: String?? = nil, followerStatus: Int?? = nil, neiguangShield: Int?? = nil, commentSetting: Int?? = nil, duetSetting: Int?? = nil, reflowPageGid: Int?? = nil, reflowPageUid: Int?? = nil, userRate: Int?? = nil, downloadSetting: Int?? = nil, downloadPromptTs: Int?? = nil, reactSetting: Int?? = nil, liveCommerce: Bool?? = nil, coverURL: [ArakGroundhog]?? = nil, language: String?? = nil, hasInsights: Bool?? = nil, shareQrcodeURI: String?? = nil, itemList: JSONNull?? = nil, userMode: Int?? = nil, userPeriod: Int?? = nil, hasUnreadStory: Bool?? = nil, newStoryCover: JSONNull?? = nil, isStar: Bool?? = nil, cvLevel: String?? = nil, typeLabel: JSONNull?? = nil, adCoverURL: JSONNull?? = nil, commentFilterStatus: Int?? = nil, avatar168X168: ArakGroundhog?? = nil, avatar300X300: ArakGroundhog?? = nil, relativeUsers: JSONNull?? = nil, chaList: JSONNull?? = nil, secUid: String?? = nil ) -> AwemeListAuthor { return AwemeListAuthor( uid: uid ?? self.uid, shortID: shortID ?? self.shortID, nickname: nickname ?? self.nickname, gender: gender ?? self.gender, signature: signature ?? self.signature, avatarLarger: avatarLarger ?? self.avatarLarger, avatarThumb: avatarThumb ?? self.avatarThumb, avatarMedium: avatarMedium ?? self.avatarMedium, birthday: birthday ?? self.birthday, isVerified: isVerified ?? self.isVerified, followStatus: followStatus ?? self.followStatus, awemeCount: awemeCount ?? self.awemeCount, followingCount: followingCount ?? self.followingCount, followerCount: followerCount ?? self.followerCount, favoritingCount: favoritingCount ?? self.favoritingCount, totalFavorited: totalFavorited ?? self.totalFavorited, isBlock: isBlock ?? self.isBlock, hideSearch: hideSearch ?? self.hideSearch, constellation: constellation ?? self.constellation, location: location ?? self.location, hideLocation: hideLocation ?? self.hideLocation, weiboVerify: weiboVerify ?? self.weiboVerify, customVerify: customVerify ?? self.customVerify, uniqueID: uniqueID ?? self.uniqueID, bindPhone: bindPhone ?? self.bindPhone, specialLock: specialLock ?? self.specialLock, needRecommend: needRecommend ?? self.needRecommend, isBindedWeibo: isBindedWeibo ?? self.isBindedWeibo, weiboName: weiboName ?? self.weiboName, weiboSchema: weiboSchema ?? self.weiboSchema, weiboURL: weiboURL ?? self.weiboURL, storyOpen: storyOpen ?? self.storyOpen, storyCount: storyCount ?? self.storyCount, hasFacebookToken: hasFacebookToken ?? self.hasFacebookToken, hasTwitterToken: hasTwitterToken ?? self.hasTwitterToken, fbExpireTime: fbExpireTime ?? self.fbExpireTime, twExpireTime: twExpireTime ?? self.twExpireTime, hasYoutubeToken: hasYoutubeToken ?? self.hasYoutubeToken, youtubeExpireTime: youtubeExpireTime ?? self.youtubeExpireTime, roomID: roomID ?? self.roomID, liveVerify: liveVerify ?? self.liveVerify, authorityStatus: authorityStatus ?? self.authorityStatus, verifyInfo: verifyInfo ?? self.verifyInfo, shieldFollowNotice: shieldFollowNotice ?? self.shieldFollowNotice, shieldDiggNotice: shieldDiggNotice ?? self.shieldDiggNotice, shieldCommentNotice: shieldCommentNotice ?? self.shieldCommentNotice, schoolName: schoolName ?? self.schoolName, schoolPoiID: schoolPoiID ?? self.schoolPoiID, schoolType: schoolType ?? self.schoolType, shareInfo: shareInfo ?? self.shareInfo, withCommerceEntry: withCommerceEntry ?? self.withCommerceEntry, verificationType: verificationType ?? self.verificationType, enterpriseVerifyReason: enterpriseVerifyReason ?? self.enterpriseVerifyReason, isAdFake: isAdFake ?? self.isAdFake, followersDetail: followersDetail ?? self.followersDetail, region: region ?? self.region, accountRegion: accountRegion ?? self.accountRegion, syncToToutiao: syncToToutiao ?? self.syncToToutiao, commerceUserLevel: commerceUserLevel ?? self.commerceUserLevel, liveAgreement: liveAgreement ?? self.liveAgreement, platformSyncInfo: platformSyncInfo ?? self.platformSyncInfo, withShopEntry: withShopEntry ?? self.withShopEntry, isDisciplineMember: isDisciplineMember ?? self.isDisciplineMember, secret: secret ?? self.secret, hasOrders: hasOrders ?? self.hasOrders, preventDownload: preventDownload ?? self.preventDownload, showImageBubble: showImageBubble ?? self.showImageBubble, geofencing: geofencing ?? self.geofencing, uniqueIDModifyTime: uniqueIDModifyTime ?? self.uniqueIDModifyTime, videoIcon: videoIcon ?? self.videoIcon, insID: insID ?? self.insID, googleAccount: googleAccount ?? self.googleAccount, youtubeChannelID: youtubeChannelID ?? self.youtubeChannelID, youtubeChannelTitle: youtubeChannelTitle ?? self.youtubeChannelTitle, appleAccount: appleAccount ?? self.appleAccount, withDouEntry: withDouEntry ?? self.withDouEntry, withFusionShopEntry: withFusionShopEntry ?? self.withFusionShopEntry, isPhoneBinded: isPhoneBinded ?? self.isPhoneBinded, acceptPrivatePolicy: acceptPrivatePolicy ?? self.acceptPrivatePolicy, twitterID: twitterID ?? self.twitterID, twitterName: twitterName ?? self.twitterName, userCanceled: userCanceled ?? self.userCanceled, hasEmail: hasEmail ?? self.hasEmail, isGovMediaVip: isGovMediaVip ?? self.isGovMediaVip, liveAgreementTime: liveAgreementTime ?? self.liveAgreementTime, status: status ?? self.status, createTime: createTime ?? self.createTime, avatarURI: avatarURI ?? self.avatarURI, followerStatus: followerStatus ?? self.followerStatus, neiguangShield: neiguangShield ?? self.neiguangShield, commentSetting: commentSetting ?? self.commentSetting, duetSetting: duetSetting ?? self.duetSetting, reflowPageGid: reflowPageGid ?? self.reflowPageGid, reflowPageUid: reflowPageUid ?? self.reflowPageUid, userRate: userRate ?? self.userRate, downloadSetting: downloadSetting ?? self.downloadSetting, downloadPromptTs: downloadPromptTs ?? self.downloadPromptTs, reactSetting: reactSetting ?? self.reactSetting, liveCommerce: liveCommerce ?? self.liveCommerce, coverURL: coverURL ?? self.coverURL, language: language ?? self.language, hasInsights: hasInsights ?? self.hasInsights, shareQrcodeURI: shareQrcodeURI ?? self.shareQrcodeURI, itemList: itemList ?? self.itemList, userMode: userMode ?? self.userMode, userPeriod: userPeriod ?? self.userPeriod, hasUnreadStory: hasUnreadStory ?? self.hasUnreadStory, newStoryCover: newStoryCover ?? self.newStoryCover, isStar: isStar ?? self.isStar, cvLevel: cvLevel ?? self.cvLevel, typeLabel: typeLabel ?? self.typeLabel, adCoverURL: adCoverURL ?? self.adCoverURL, commentFilterStatus: commentFilterStatus ?? self.commentFilterStatus, avatar168X168: avatar168X168 ?? self.avatar168X168, avatar300X300: avatar300X300 ?? self.avatar300X300, relativeUsers: relativeUsers ?? self.relativeUsers, chaList: chaList ?? self.chaList, secUid: secUid ?? self.secUid ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - ArakGroundhog struct ArakGroundhog: Codable { let uri: String? let urlList: [String]? let width, height: Int? let urlKey: String? enum CodingKeys: String, CodingKey { case uri case urlList = "url_list" case width, height case urlKey = "url_key" } } // MARK: ArakGroundhog convenience initializers and mutators extension ArakGroundhog { init(data: Data) throws { self = try newJSONDecoder().decode(ArakGroundhog.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( uri: String?? = nil, urlList: [String]?? = nil, width: Int?? = nil, height: Int?? = nil, urlKey: String?? = nil ) -> ArakGroundhog { return ArakGroundhog( uri: uri ?? self.uri, urlList: urlList ?? self.urlList, width: width ?? self.width, height: height ?? self.height, urlKey: urlKey ?? self.urlKey ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - AuthorShareInfo struct AuthorShareInfo: Codable { let shareURL, shareWeiboDesc, shareDesc, shareTitle: String? let shareQrcodeURL: ArakGroundhog? let shareTitleMyself, shareTitleOther: String? enum CodingKeys: String, CodingKey { case shareURL = "share_url" case shareWeiboDesc = "share_weibo_desc" case shareDesc = "share_desc" case shareTitle = "share_title" case shareQrcodeURL = "share_qrcode_url" case shareTitleMyself = "share_title_myself" case shareTitleOther = "share_title_other" } } // MARK: AuthorShareInfo convenience initializers and mutators extension AuthorShareInfo { init(data: Data) throws { self = try newJSONDecoder().decode(AuthorShareInfo.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( shareURL: String?? = nil, shareWeiboDesc: String?? = nil, shareDesc: String?? = nil, shareTitle: String?? = nil, shareQrcodeURL: ArakGroundhog?? = nil, shareTitleMyself: String?? = nil, shareTitleOther: String?? = nil ) -> AuthorShareInfo { return AuthorShareInfo( shareURL: shareURL ?? self.shareURL, shareWeiboDesc: shareWeiboDesc ?? self.shareWeiboDesc, shareDesc: shareDesc ?? self.shareDesc, shareTitle: shareTitle ?? self.shareTitle, shareQrcodeURL: shareQrcodeURL ?? self.shareQrcodeURL, shareTitleMyself: shareTitleMyself ?? self.shareTitleMyself, shareTitleOther: shareTitleOther ?? self.shareTitleOther ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - AwemeControl struct AwemeControl: Codable { let canForward, canShare, canComment, canShowComment: Bool? enum CodingKeys: String, CodingKey { case canForward = "can_forward" case canShare = "can_share" case canComment = "can_comment" case canShowComment = "can_show_comment" } } // MARK: AwemeControl convenience initializers and mutators extension AwemeControl { init(data: Data) throws { self = try newJSONDecoder().decode(AwemeControl.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( canForward: Bool?? = nil, canShare: Bool?? = nil, canComment: Bool?? = nil, canShowComment: Bool?? = nil ) -> AwemeControl { return AwemeControl( canForward: canForward ?? self.canForward, canShare: canShare ?? self.canShare, canComment: canComment ?? self.canComment, canShowComment: canShowComment ?? self.canShowComment ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - ChaList struct ChaList: Codable { let cid, chaName, desc, schema: String? let author: ChaListAuthor? let userCount: Int? let shareInfo: ChaListShareInfo? let connectMusic: [JSONAny]? let type, subType: Int? let isPgcshow: Bool? let collectStat, isChallenge, viewCount: Int? let isCommerce: Bool? let hashtagProfile: String? let chaAttrs: JSONNull? enum CodingKeys: String, CodingKey { case cid case chaName = "cha_name" case desc, schema, author case userCount = "user_count" case shareInfo = "share_info" case connectMusic = "connect_music" case type case subType = "sub_type" case isPgcshow = "is_pgcshow" case collectStat = "collect_stat" case isChallenge = "is_challenge" case viewCount = "view_count" case isCommerce = "is_commerce" case hashtagProfile = "hashtag_profile" case chaAttrs = "cha_attrs" } } // MARK: ChaList convenience initializers and mutators extension ChaList { init(data: Data) throws { self = try newJSONDecoder().decode(ChaList.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( cid: String?? = nil, chaName: String?? = nil, desc: String?? = nil, schema: String?? = nil, author: ChaListAuthor?? = nil, userCount: Int?? = nil, shareInfo: ChaListShareInfo?? = nil, connectMusic: [JSONAny]?? = nil, type: Int?? = nil, subType: Int?? = nil, isPgcshow: Bool?? = nil, collectStat: Int?? = nil, isChallenge: Int?? = nil, viewCount: Int?? = nil, isCommerce: Bool?? = nil, hashtagProfile: String?? = nil, chaAttrs: JSONNull?? = nil ) -> ChaList { return ChaList( cid: cid ?? self.cid, chaName: chaName ?? self.chaName, desc: desc ?? self.desc, schema: schema ?? self.schema, author: author ?? self.author, userCount: userCount ?? self.userCount, shareInfo: shareInfo ?? self.shareInfo, connectMusic: connectMusic ?? self.connectMusic, type: type ?? self.type, subType: subType ?? self.subType, isPgcshow: isPgcshow ?? self.isPgcshow, collectStat: collectStat ?? self.collectStat, isChallenge: isChallenge ?? self.isChallenge, viewCount: viewCount ?? self.viewCount, isCommerce: isCommerce ?? self.isCommerce, hashtagProfile: hashtagProfile ?? self.hashtagProfile, chaAttrs: chaAttrs ?? self.chaAttrs ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - ChaListAuthor struct ChaListAuthor: Codable { let followersDetail, platformSyncInfo, geofencing, coverURL: JSONNull? let itemList, newStoryCover, typeLabel, adCoverURL: JSONNull? let relativeUsers, chaList: JSONNull? enum CodingKeys: String, CodingKey { case followersDetail = "followers_detail" case platformSyncInfo = "platform_sync_info" case geofencing case coverURL = "cover_url" case itemList = "item_list" case newStoryCover = "new_story_cover" case typeLabel = "type_label" case adCoverURL = "ad_cover_url" case relativeUsers = "relative_users" case chaList = "cha_list" } } // MARK: ChaListAuthor convenience initializers and mutators extension ChaListAuthor { init(data: Data) throws { self = try newJSONDecoder().decode(ChaListAuthor.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( followersDetail: JSONNull?? = nil, platformSyncInfo: JSONNull?? = nil, geofencing: JSONNull?? = nil, coverURL: JSONNull?? = nil, itemList: JSONNull?? = nil, newStoryCover: JSONNull?? = nil, typeLabel: JSONNull?? = nil, adCoverURL: JSONNull?? = nil, relativeUsers: JSONNull?? = nil, chaList: JSONNull?? = nil ) -> ChaListAuthor { return ChaListAuthor( followersDetail: followersDetail ?? self.followersDetail, platformSyncInfo: platformSyncInfo ?? self.platformSyncInfo, geofencing: geofencing ?? self.geofencing, coverURL: coverURL ?? self.coverURL, itemList: itemList ?? self.itemList, newStoryCover: newStoryCover ?? self.newStoryCover, typeLabel: typeLabel ?? self.typeLabel, adCoverURL: adCoverURL ?? self.adCoverURL, relativeUsers: relativeUsers ?? self.relativeUsers, chaList: chaList ?? self.chaList ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - ChaListShareInfo struct ChaListShareInfo: Codable { let shareURL: String? let shareWeiboDesc, shareDesc, shareTitle: String? let boolPersist: Int? let shareTitleMyself, shareTitleOther: String? let shareSignatureURL: String? let shareSignatureDesc, shareQuote, shareLinkDesc: String? enum CodingKeys: String, CodingKey { case shareURL = "share_url" case shareWeiboDesc = "share_weibo_desc" case shareDesc = "share_desc" case shareTitle = "share_title" case boolPersist = "bool_persist" case shareTitleMyself = "share_title_myself" case shareTitleOther = "share_title_other" case shareSignatureURL = "share_signature_url" case shareSignatureDesc = "share_signature_desc" case shareQuote = "share_quote" case shareLinkDesc = "share_link_desc" } } // MARK: ChaListShareInfo convenience initializers and mutators extension ChaListShareInfo { init(data: Data) throws { self = try newJSONDecoder().decode(ChaListShareInfo.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( shareURL: String?? = nil, shareWeiboDesc: String?? = nil, shareDesc: String?? = nil, shareTitle: String?? = nil, boolPersist: Int?? = nil, shareTitleMyself: String?? = nil, shareTitleOther: String?? = nil, shareSignatureURL: String?? = nil, shareSignatureDesc: String?? = nil, shareQuote: String?? = nil, shareLinkDesc: String?? = nil ) -> ChaListShareInfo { return ChaListShareInfo( shareURL: shareURL ?? self.shareURL, shareWeiboDesc: shareWeiboDesc ?? self.shareWeiboDesc, shareDesc: shareDesc ?? self.shareDesc, shareTitle: shareTitle ?? self.shareTitle, boolPersist: boolPersist ?? self.boolPersist, shareTitleMyself: shareTitleMyself ?? self.shareTitleMyself, shareTitleOther: shareTitleOther ?? self.shareTitleOther, shareSignatureURL: shareSignatureURL ?? self.shareSignatureURL, shareSignatureDesc: shareSignatureDesc ?? self.shareSignatureDesc, shareQuote: shareQuote ?? self.shareQuote, shareLinkDesc: shareLinkDesc ?? self.shareLinkDesc ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - Descendants struct Descendants: Codable { let platforms: [String]? let notifyMsg: String? enum CodingKeys: String, CodingKey { case platforms case notifyMsg = "notify_msg" } } // MARK: Descendants convenience initializers and mutators extension Descendants { init(data: Data) throws { self = try newJSONDecoder().decode(Descendants.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( platforms: [String]?? = nil, notifyMsg: String?? = nil ) -> Descendants { return Descendants( platforms: platforms ?? self.platforms, notifyMsg: notifyMsg ?? self.notifyMsg ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - Music struct Music: Codable { let id: Double? let idStr, title, author, album: String? let coverHD, coverLarge, coverMedium, coverThumb: ArakGroundhog? let playURL: ArakGroundhog? let schemaURL: String? let sourcePlatform, startTime, endTime, duration: Int? let extra: String? let userCount: Int? let position: JSONNull? let collectStat, status: Int? let offlineDesc, ownerID, ownerNickname: String? let isOriginal: Bool? let mid: String? let bindedChallengeID: Int? let redirect, isRestricted, authorDeleted, isDelVideo: Bool? let isVideoSelfSee: Bool? let ownerHandle: String? let authorPosition: JSONNull? let preventDownload: Bool? let strongBeatURL: ArakGroundhog? let unshelveCountries: JSONNull? let preventItemDownloadStatus: Int? let externalSongInfo: [JSONAny]? let secUid: String? let avatarThumb, avatarMedium, avatarLarge: ArakGroundhog? let previewStartTime, previewEndTime: Int? let isCommerceMusic, isOriginalSound: Bool? enum CodingKeys: String, CodingKey { case id case idStr = "id_str" case title, author, album case coverHD = "cover_hd" case coverLarge = "cover_large" case coverMedium = "cover_medium" case coverThumb = "cover_thumb" case playURL = "play_url" case schemaURL = "schema_url" case sourcePlatform = "source_platform" case startTime = "start_time" case endTime = "end_time" case duration, extra case userCount = "user_count" case position case collectStat = "collect_stat" case status case offlineDesc = "offline_desc" case ownerID = "owner_id" case ownerNickname = "owner_nickname" case isOriginal = "is_original" case mid case bindedChallengeID = "binded_challenge_id" case redirect case isRestricted = "is_restricted" case authorDeleted = "author_deleted" case isDelVideo = "is_del_video" case isVideoSelfSee = "is_video_self_see" case ownerHandle = "owner_handle" case authorPosition = "author_position" case preventDownload = "prevent_download" case strongBeatURL = "strong_beat_url" case unshelveCountries = "unshelve_countries" case preventItemDownloadStatus = "prevent_item_download_status" case externalSongInfo = "external_song_info" case secUid = "sec_uid" case avatarThumb = "avatar_thumb" case avatarMedium = "avatar_medium" case avatarLarge = "avatar_large" case previewStartTime = "preview_start_time" case previewEndTime = "preview_end_time" case isCommerceMusic = "is_commerce_music" case isOriginalSound = "is_original_sound" } } // MARK: Music convenience initializers and mutators extension Music { init(data: Data) throws { self = try newJSONDecoder().decode(Music.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( id: Double?? = nil, idStr: String?? = nil, title: String?? = nil, author: String?? = nil, album: String?? = nil, coverHD: ArakGroundhog?? = nil, coverLarge: ArakGroundhog?? = nil, coverMedium: ArakGroundhog?? = nil, coverThumb: ArakGroundhog?? = nil, playURL: ArakGroundhog?? = nil, schemaURL: String?? = nil, sourcePlatform: Int?? = nil, startTime: Int?? = nil, endTime: Int?? = nil, duration: Int?? = nil, extra: String?? = nil, userCount: Int?? = nil, position: JSONNull?? = nil, collectStat: Int?? = nil, status: Int?? = nil, offlineDesc: String?? = nil, ownerID: String?? = nil, ownerNickname: String?? = nil, isOriginal: Bool?? = nil, mid: String?? = nil, bindedChallengeID: Int?? = nil, redirect: Bool?? = nil, isRestricted: Bool?? = nil, authorDeleted: Bool?? = nil, isDelVideo: Bool?? = nil, isVideoSelfSee: Bool?? = nil, ownerHandle: String?? = nil, authorPosition: JSONNull?? = nil, preventDownload: Bool?? = nil, strongBeatURL: ArakGroundhog?? = nil, unshelveCountries: JSONNull?? = nil, preventItemDownloadStatus: Int?? = nil, externalSongInfo: [JSONAny]?? = nil, secUid: String?? = nil, avatarThumb: ArakGroundhog?? = nil, avatarMedium: ArakGroundhog?? = nil, avatarLarge: ArakGroundhog?? = nil, previewStartTime: Int?? = nil, previewEndTime: Int?? = nil, isCommerceMusic: Bool?? = nil, isOriginalSound: Bool?? = nil ) -> Music { return Music( id: id ?? self.id, idStr: idStr ?? self.idStr, title: title ?? self.title, author: author ?? self.author, album: album ?? self.album, coverHD: coverHD ?? self.coverHD, coverLarge: coverLarge ?? self.coverLarge, coverMedium: coverMedium ?? self.coverMedium, coverThumb: coverThumb ?? self.coverThumb, playURL: playURL ?? self.playURL, schemaURL: schemaURL ?? self.schemaURL, sourcePlatform: sourcePlatform ?? self.sourcePlatform, startTime: startTime ?? self.startTime, endTime: endTime ?? self.endTime, duration: duration ?? self.duration, extra: extra ?? self.extra, userCount: userCount ?? self.userCount, position: position ?? self.position, collectStat: collectStat ?? self.collectStat, status: status ?? self.status, offlineDesc: offlineDesc ?? self.offlineDesc, ownerID: ownerID ?? self.ownerID, ownerNickname: ownerNickname ?? self.ownerNickname, isOriginal: isOriginal ?? self.isOriginal, mid: mid ?? self.mid, bindedChallengeID: bindedChallengeID ?? self.bindedChallengeID, redirect: redirect ?? self.redirect, isRestricted: isRestricted ?? self.isRestricted, authorDeleted: authorDeleted ?? self.authorDeleted, isDelVideo: isDelVideo ?? self.isDelVideo, isVideoSelfSee: isVideoSelfSee ?? self.isVideoSelfSee, ownerHandle: ownerHandle ?? self.ownerHandle, authorPosition: authorPosition ?? self.authorPosition, preventDownload: preventDownload ?? self.preventDownload, strongBeatURL: strongBeatURL ?? self.strongBeatURL, unshelveCountries: unshelveCountries ?? self.unshelveCountries, preventItemDownloadStatus: preventItemDownloadStatus ?? self.preventItemDownloadStatus, externalSongInfo: externalSongInfo ?? self.externalSongInfo, secUid: secUid ?? self.secUid, avatarThumb: avatarThumb ?? self.avatarThumb, avatarMedium: avatarMedium ?? self.avatarMedium, avatarLarge: avatarLarge ?? self.avatarLarge, previewStartTime: previewStartTime ?? self.previewStartTime, previewEndTime: previewEndTime ?? self.previewEndTime, isCommerceMusic: isCommerceMusic ?? self.isCommerceMusic, isOriginalSound: isOriginalSound ?? self.isOriginalSound ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - RiskInfos struct RiskInfos: Codable { let vote, warn, riskSink: Bool? let type: Int? let content: String? enum CodingKeys: String, CodingKey { case vote, warn case riskSink = "risk_sink" case type, content } } // MARK: RiskInfos convenience initializers and mutators extension RiskInfos { init(data: Data) throws { self = try newJSONDecoder().decode(RiskInfos.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( vote: Bool?? = nil, warn: Bool?? = nil, riskSink: Bool?? = nil, type: Int?? = nil, content: String?? = nil ) -> RiskInfos { return RiskInfos( vote: vote ?? self.vote, warn: warn ?? self.warn, riskSink: riskSink ?? self.riskSink, type: type ?? self.type, content: content ?? self.content ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - Statistics struct Statistics: Codable { let awemeID: String? let commentCount, diggCount, downloadCount, playCount: Int? let shareCount, forwardCount, loseCount, loseCommentCount: Int? enum CodingKeys: String, CodingKey { case awemeID = "aweme_id" case commentCount = "comment_count" case diggCount = "digg_count" case downloadCount = "download_count" case playCount = "play_count" case shareCount = "share_count" case forwardCount = "forward_count" case loseCount = "lose_count" case loseCommentCount = "lose_comment_count" } } // MARK: Statistics convenience initializers and mutators extension Statistics { init(data: Data) throws { self = try newJSONDecoder().decode(Statistics.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( awemeID: String?? = nil, commentCount: Int?? = nil, diggCount: Int?? = nil, downloadCount: Int?? = nil, playCount: Int?? = nil, shareCount: Int?? = nil, forwardCount: Int?? = nil, loseCount: Int?? = nil, loseCommentCount: Int?? = nil ) -> Statistics { return Statistics( awemeID: awemeID ?? self.awemeID, commentCount: commentCount ?? self.commentCount, diggCount: diggCount ?? self.diggCount, downloadCount: downloadCount ?? self.downloadCount, playCount: playCount ?? self.playCount, shareCount: shareCount ?? self.shareCount, forwardCount: forwardCount ?? self.forwardCount, loseCount: loseCount ?? self.loseCount, loseCommentCount: loseCommentCount ?? self.loseCommentCount ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - Status struct Status: Codable { let awemeID: String? let isDelete, allowShare, allowComment, isPrivate: Bool? let withGoods: Bool? let privateStatus: Int? let withFusionGoods, inReviewing: Bool? let reviewed: Int? let selfSee, isProhibited: Bool? let downloadStatus: Int? enum CodingKeys: String, CodingKey { case awemeID = "aweme_id" case isDelete = "is_delete" case allowShare = "allow_share" case allowComment = "allow_comment" case isPrivate = "is_private" case withGoods = "with_goods" case privateStatus = "private_status" case withFusionGoods = "with_fusion_goods" case inReviewing = "in_reviewing" case reviewed case selfSee = "self_see" case isProhibited = "is_prohibited" case downloadStatus = "download_status" } } // MARK: Status convenience initializers and mutators extension Status { init(data: Data) throws { self = try newJSONDecoder().decode(Status.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( awemeID: String?? = nil, isDelete: Bool?? = nil, allowShare: Bool?? = nil, allowComment: Bool?? = nil, isPrivate: Bool?? = nil, withGoods: Bool?? = nil, privateStatus: Int?? = nil, withFusionGoods: Bool?? = nil, inReviewing: Bool?? = nil, reviewed: Int?? = nil, selfSee: Bool?? = nil, isProhibited: Bool?? = nil, downloadStatus: Int?? = nil ) -> Status { return Status( awemeID: awemeID ?? self.awemeID, isDelete: isDelete ?? self.isDelete, allowShare: allowShare ?? self.allowShare, allowComment: allowComment ?? self.allowComment, isPrivate: isPrivate ?? self.isPrivate, withGoods: withGoods ?? self.withGoods, privateStatus: privateStatus ?? self.privateStatus, withFusionGoods: withFusionGoods ?? self.withFusionGoods, inReviewing: inReviewing ?? self.inReviewing, reviewed: reviewed ?? self.reviewed, selfSee: selfSee ?? self.selfSee, isProhibited: isProhibited ?? self.isProhibited, downloadStatus: downloadStatus ?? self.downloadStatus ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - Video struct Video: Codable { let playAddr, cover: ArakGroundhog? let height, width: Int? let dynamicCover, originCover: ArakGroundhog? let ratio: String? let downloadAddr: ArakGroundhog? let hasWatermark: Bool? let playAddrLowbr: ArakGroundhog? let bitRate: [BitRate]? let duration: Int? let downloadSuffixLogoAddr: ArakGroundhog? let hasDownloadSuffixLogoAddr: Bool? let isH265, cdnURLExpired: Int? let uiAlikeDownloadAddr: ArakGroundhog? enum CodingKeys: String, CodingKey { case playAddr = "play_addr" case cover, height, width case dynamicCover = "dynamic_cover" case originCover = "origin_cover" case ratio case downloadAddr = "download_addr" case hasWatermark = "has_watermark" case playAddrLowbr = "play_addr_lowbr" case bitRate = "bit_rate" case duration case downloadSuffixLogoAddr = "download_suffix_logo_addr" case hasDownloadSuffixLogoAddr = "has_download_suffix_logo_addr" case isH265 = "is_h265" case cdnURLExpired = "cdn_url_expired" case uiAlikeDownloadAddr = "ui_alike_download_addr" } } // MARK: Video convenience initializers and mutators extension Video { init(data: Data) throws { self = try newJSONDecoder().decode(Video.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( playAddr: ArakGroundhog?? = nil, cover: ArakGroundhog?? = nil, height: Int?? = nil, width: Int?? = nil, dynamicCover: ArakGroundhog?? = nil, originCover: ArakGroundhog?? = nil, ratio: String?? = nil, downloadAddr: ArakGroundhog?? = nil, hasWatermark: Bool?? = nil, playAddrLowbr: ArakGroundhog?? = nil, bitRate: [BitRate]?? = nil, duration: Int?? = nil, downloadSuffixLogoAddr: ArakGroundhog?? = nil, hasDownloadSuffixLogoAddr: Bool?? = nil, isH265: Int?? = nil, cdnURLExpired: Int?? = nil, uiAlikeDownloadAddr: ArakGroundhog?? = nil ) -> Video { return Video( playAddr: playAddr ?? self.playAddr, cover: cover ?? self.cover, height: height ?? self.height, width: width ?? self.width, dynamicCover: dynamicCover ?? self.dynamicCover, originCover: originCover ?? self.originCover, ratio: ratio ?? self.ratio, downloadAddr: downloadAddr ?? self.downloadAddr, hasWatermark: hasWatermark ?? self.hasWatermark, playAddrLowbr: playAddrLowbr ?? self.playAddrLowbr, bitRate: bitRate ?? self.bitRate, duration: duration ?? self.duration, downloadSuffixLogoAddr: downloadSuffixLogoAddr ?? self.downloadSuffixLogoAddr, hasDownloadSuffixLogoAddr: hasDownloadSuffixLogoAddr ?? self.hasDownloadSuffixLogoAddr, isH265: isH265 ?? self.isH265, cdnURLExpired: cdnURLExpired ?? self.cdnURLExpired, uiAlikeDownloadAddr: uiAlikeDownloadAddr ?? self.uiAlikeDownloadAddr ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - BitRate struct BitRate: Codable { let gearName: String? let qualityType, bitRate: Int? let playAddr: ArakGroundhog? let isH265: Int? enum CodingKeys: String, CodingKey { case gearName = "gear_name" case qualityType = "quality_type" case bitRate = "bit_rate" case playAddr = "play_addr" case isH265 = "is_h265" } } // MARK: BitRate convenience initializers and mutators extension BitRate { init(data: Data) throws { self = try newJSONDecoder().decode(BitRate.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( gearName: String?? = nil, qualityType: Int?? = nil, bitRate: Int?? = nil, playAddr: ArakGroundhog?? = nil, isH265: Int?? = nil ) -> BitRate { return BitRate( gearName: gearName ?? self.gearName, qualityType: qualityType ?? self.qualityType, bitRate: bitRate ?? self.bitRate, playAddr: playAddr ?? self.playAddr, isH265: isH265 ?? self.isH265 ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - VideoControl struct VideoControl: Codable { let allowDownload: Bool? let shareType, showProgressBar, draftProgressBar: Int? let allowDuet, allowReact: Bool? let preventDownloadType: Int? let allowDynamicWallpaper: Bool? let timerStatus: Int? enum CodingKeys: String, CodingKey { case allowDownload = "allow_download" case shareType = "share_type" case showProgressBar = "show_progress_bar" case draftProgressBar = "draft_progress_bar" case allowDuet = "allow_duet" case allowReact = "allow_react" case preventDownloadType = "prevent_download_type" case allowDynamicWallpaper = "allow_dynamic_wallpaper" case timerStatus = "timer_status" } } // MARK: VideoControl convenience initializers and mutators extension VideoControl { init(data: Data) throws { self = try newJSONDecoder().decode(VideoControl.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( allowDownload: Bool?? = nil, shareType: Int?? = nil, showProgressBar: Int?? = nil, draftProgressBar: Int?? = nil, allowDuet: Bool?? = nil, allowReact: Bool?? = nil, preventDownloadType: Int?? = nil, allowDynamicWallpaper: Bool?? = nil, timerStatus: Int?? = nil ) -> VideoControl { return VideoControl( allowDownload: allowDownload ?? self.allowDownload, shareType: shareType ?? self.shareType, showProgressBar: showProgressBar ?? self.showProgressBar, draftProgressBar: draftProgressBar ?? self.draftProgressBar, allowDuet: allowDuet ?? self.allowDuet, allowReact: allowReact ?? self.allowReact, preventDownloadType: preventDownloadType ?? self.preventDownloadType, allowDynamicWallpaper: allowDynamicWallpaper ?? self.allowDynamicWallpaper, timerStatus: timerStatus ?? self.timerStatus ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - XiguaTask struct XiguaTask: Codable { let isXiguaTask: Bool? enum CodingKeys: String, CodingKey { case isXiguaTask = "is_xigua_task" } } // MARK: XiguaTask convenience initializers and mutators extension XiguaTask { init(data: Data) throws { self = try newJSONDecoder().decode(XiguaTask.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( isXiguaTask: Bool?? = nil ) -> XiguaTask { return XiguaTask( isXiguaTask: isXiguaTask ?? self.isXiguaTask ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - Extra struct Extra: Codable { let now: Int? let fatalItemIDS: JSONNull? enum CodingKeys: String, CodingKey { case now case fatalItemIDS = "fatal_item_ids" } } // MARK: Extra convenience initializers and mutators extension Extra { init(data: Data) throws { self = try newJSONDecoder().decode(Extra.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( now: Int?? = nil, fatalItemIDS: JSONNull?? = nil ) -> Extra { return Extra( now: now ?? self.now, fatalItemIDS: fatalItemIDS ?? self.fatalItemIDS ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - LogPb struct LogPb: Codable { let imprID: String? enum CodingKeys: String, CodingKey { case imprID = "impr_id" } } // MARK: LogPb convenience initializers and mutators extension LogPb { init(data: Data) throws { self = try newJSONDecoder().decode(LogPb.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( imprID: String?? = nil ) -> LogPb { return LogPb( imprID: imprID ?? self.imprID ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } } // MARK: - Helper functions for creating encoders and decoders func newJSONDecoder() -> JSONDecoder { let decoder = JSONDecoder() if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { decoder.dateDecodingStrategy = .iso8601 } return decoder } func newJSONEncoder() -> JSONEncoder { let encoder = JSONEncoder() if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { encoder.dateEncodingStrategy = .iso8601 } return encoder } // MARK: - Encode/decode helpers class JSONNull: Codable, Hashable { public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool { return true } public var hashValue: Int { return 0 } public init() {} public required init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if !container.decodeNil() { throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull")) } } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encodeNil() } } class JSONCodingKey: CodingKey { let key: String required init?(intValue: Int) { return nil } required init?(stringValue: String) { key = stringValue } var intValue: Int? { return nil } var stringValue: String { return key } } class JSONAny: Codable { let value: Any static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError { let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny") return DecodingError.typeMismatch(JSONAny.self, context) } static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError { let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny") return EncodingError.invalidValue(value, context) } static func decode(from container: SingleValueDecodingContainer) throws -> Any { if let value = try? container.decode(Bool.self) { return value } if let value = try? container.decode(Int64.self) { return value } if let value = try? container.decode(Double.self) { return value } if let value = try? container.decode(String.self) { return value } if container.decodeNil() { return JSONNull() } throw decodingError(forCodingPath: container.codingPath) } static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any { if let value = try? container.decode(Bool.self) { return value } if let value = try? container.decode(Int64.self) { return value } if let value = try? container.decode(Double.self) { return value } if let value = try? container.decode(String.self) { return value } if let value = try? container.decodeNil() { if value { return JSONNull() } } if var container = try? container.nestedUnkeyedContainer() { return try decodeArray(from: &container) } if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) { return try decodeDictionary(from: &container) } throw decodingError(forCodingPath: container.codingPath) } static func decode(from container: inout KeyedDecodingContainer<JSONCodingKey>, forKey key: JSONCodingKey) throws -> Any { if let value = try? container.decode(Bool.self, forKey: key) { return value } if let value = try? container.decode(Int64.self, forKey: key) { return value } if let value = try? container.decode(Double.self, forKey: key) { return value } if let value = try? container.decode(String.self, forKey: key) { return value } if let value = try? container.decodeNil(forKey: key) { if value { return JSONNull() } } if var container = try? container.nestedUnkeyedContainer(forKey: key) { return try decodeArray(from: &container) } if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) { return try decodeDictionary(from: &container) } throw decodingError(forCodingPath: container.codingPath) } static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] { var arr: [Any] = [] while !container.isAtEnd { let value = try decode(from: &container) arr.append(value) } return arr } static func decodeDictionary(from container: inout KeyedDecodingContainer<JSONCodingKey>) throws -> [String: Any] { var dict = [String: Any]() for key in container.allKeys { let value = try decode(from: &container, forKey: key) dict[key.stringValue] = value } return dict } static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws { for value in array { if let value = value as? Bool { try container.encode(value) } else if let value = value as? Int64 { try container.encode(value) } else if let value = value as? Double { try container.encode(value) } else if let value = value as? String { try container.encode(value) } else if value is JSONNull { try container.encodeNil() } else if let value = value as? [Any] { var container = container.nestedUnkeyedContainer() try encode(to: &container, array: value) } else if let value = value as? [String: Any] { var container = container.nestedContainer(keyedBy: JSONCodingKey.self) try encode(to: &container, dictionary: value) } else { throw encodingError(forValue: value, codingPath: container.codingPath) } } } static func encode(to container: inout KeyedEncodingContainer<JSONCodingKey>, dictionary: [String: Any]) throws { for (key, value) in dictionary { let key = JSONCodingKey(stringValue: key)! if let value = value as? Bool { try container.encode(value, forKey: key) } else if let value = value as? Int64 { try container.encode(value, forKey: key) } else if let value = value as? Double { try container.encode(value, forKey: key) } else if let value = value as? String { try container.encode(value, forKey: key) } else if value is JSONNull { try container.encodeNil(forKey: key) } else if let value = value as? [Any] { var container = container.nestedUnkeyedContainer(forKey: key) try encode(to: &container, array: value) } else if let value = value as? [String: Any] { var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) try encode(to: &container, dictionary: value) } else { throw encodingError(forValue: value, codingPath: container.codingPath) } } } static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws { if let value = value as? Bool { try container.encode(value) } else if let value = value as? Int64 { try container.encode(value) } else if let value = value as? Double { try container.encode(value) } else if let value = value as? String { try container.encode(value) } else if value is JSONNull { try container.encodeNil() } else { throw encodingError(forValue: value, codingPath: container.codingPath) } } public required init(from decoder: Decoder) throws { if var arrayContainer = try? decoder.unkeyedContainer() { self.value = try JSONAny.decodeArray(from: &arrayContainer) } else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) { self.value = try JSONAny.decodeDictionary(from: &container) } else { let container = try decoder.singleValueContainer() self.value = try JSONAny.decode(from: container) } } public func encode(to encoder: Encoder) throws { if let arr = self.value as? [Any] { var container = encoder.unkeyedContainer() try JSONAny.encode(to: &container, array: arr) } else if let dict = self.value as? [String: Any] { var container = encoder.container(keyedBy: JSONCodingKey.self) try JSONAny.encode(to: &container, dictionary: dict) } else { var container = encoder.singleValueContainer() try JSONAny.encode(to: &container, value: self.value) } } }
35.958084
159
0.618627
d7d3504a10c509bd9562dcb1a90f9581a15081b8
1,500
//---------------------------------------------------- // // Generated by www.easywsdl.com // Version: 5.7.0.0 // // Created by Quasar Development // //--------------------------------------------------- import Foundation /** * abstDomain: A19670 (C-0-T10878-A19670-cpt) */ public enum EPA_FdV_AUTHZ_x_DeterminerInstanceKind:Int,CustomStringConvertible { case KIND case QUANTIFIED_KIND case INSTANCE static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_x_DeterminerInstanceKind? { return createWithString(value: node.stringValue!) } static func createWithString(value:String) -> EPA_FdV_AUTHZ_x_DeterminerInstanceKind? { var i = 0 while let item = EPA_FdV_AUTHZ_x_DeterminerInstanceKind(rawValue: i) { if String(describing: item) == value { return item } i += 1 } return nil } public var stringValue : String { return description } public var description : String { switch self { case .KIND: return "KIND" case .QUANTIFIED_KIND: return "QUANTIFIED_KIND" case .INSTANCE: return "INSTANCE" } } public func getValue() -> Int { return rawValue } func serialize(__parent:DDXMLNode) { __parent.stringValue = stringValue } }
21.428571
90
0.523333
238869e909d6fe35384ca7224e0ed856bc3a043c
766
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation public struct ASCTerritoryResponse: AppStoreConnectBaseModel { public var data: ASCTerritory public var links: ASCDocumentLinks public init(data: ASCTerritory, links: ASCDocumentLinks) { self.data = data self.links = links } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) data = try container.decode("data") links = try container.decode("links") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(data, forKey: "data") try container.encode(links, forKey: "links") } }
22.529412
72
0.719321
89f49d01efb3ad9d313b71d4960711f4a2335393
1,503
// // FolderListView.swift // VIPERDemo // // Created by macmini on 2021/04/11. // import SwiftUI struct FolderListView: View { @ObservedObject var presenter: FolderListPresenter var body: some View { NavigationView { List { self.presenter.linkBuilder(ViewBuilder: { FolderRowView() }) self.presenter.linkBuilder(ViewBuilder: { FolderRowView() }) // Image(systemName: "person.crop.circle.fill.badge.plus") // .renderingMode(.original) // .foregroundColor(.blue) // .font(.largeTitle) // } .listStyle(PlainListStyle()) .navigationBarTitle("Folders", displayMode: .inline) .navigationBarItems( // leading: // Button(action: { // }) { // Image(systemName: "magnifyingglass") // }, trailing: HStack { Button(action: { }) { Image(systemName: "folder.badge.plus") } } ) } } } struct FolderListView_Previews: PreviewProvider { static var previews: some View { let presenter = FolderListPresenter() FolderListView(presenter: presenter) } }
27.327273
73
0.454424
f9bf3464f84c38bc248a88af47c6728d89bf07e1
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 var : String { return " ( " } struct c { protocol A { typealias d: d func a
20.416667
87
0.726531
db3af989c2541cf2f4a48b114becabf12722bb78
10,264
// // RouterExtension.swift // ZRouter // // Created by zuik on 2018/1/20. // Copyright © 2017 zuik. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import ZIKRouter public extension ViewRouteConfig { func configurePath(_ path: ViewRoutePath) { if let source = path.source { self.source = source } self.routeType = path.routeType } } // MARK: View Router Extension /// Add Swift methods for ZIKViewRouter. Unavailable for any other classes. public protocol ViewRouterExtension: class { static func register<Protocol>(_ routableView: RoutableView<Protocol>) static func register<Protocol>(_ routableViewModule: RoutableViewModule<Protocol>) static func register<Protocol>(_ routableView: RoutableView<Protocol>, forMakingView viewClass: AnyClass) static func register<Protocol>(_ routableView: RoutableView<Protocol>, forMakingView viewClass: AnyClass, making factory: @escaping (ViewRouteConfig) -> Protocol?) static func register<Protocol>(_ routableViewModule: RoutableViewModule<Protocol>, forMakingView viewClass: AnyClass, making factory: @escaping () -> Protocol) } public extension ViewRouterExtension { /// Register a view protocol that all views registered with the router conforming to. /// /// - Parameter routableView: A routabe entry carrying a protocol conformed by the destination of the router. static func register<Protocol>(_ routableView: RoutableView<Protocol>) { Registry.register(routableView, forRouter: self) } /// Register a module config protocol conformed by the router's default route configuration. /// /// - Parameter routableViewModule: A routabe entry carrying a module config protocol conformed by the custom configuration of the router. static func register<Protocol>(_ routableViewModule: RoutableViewModule<Protocol>) { Registry.register(routableViewModule, forRouter: self) } /// Register view class with protocol without using any router subclass. The view will be created with `[[viewClass alloc] init]` when used. Use this if your view is very easy and don't need a router subclass. /// /// - Parameters: /// - routableView: A routabe entry carrying a protocol conformed by the destination. /// - viewClass: The view class. static func register<Protocol>(_ routableView: RoutableView<Protocol>, forMakingView viewClass: AnyClass) { Registry.register(routableView, forMakingView: viewClass) } /// Register view class with protocol without using any router subclass. The view will be created with the `making` block when used. Use this if your view is very easy and don't need a router subclass. /// /// - Parameters: /// - routableView: A routabe entry carrying a protocol conformed by the destination. /// - viewClass: The view class. /// - making: Block creating the view. static func register<Protocol>(_ routableView: RoutableView<Protocol>, forMakingView viewClass: AnyClass, making factory: @escaping (ViewRouteConfig) -> Protocol?) { Registry.register(routableView, forMakingView: viewClass, making: factory) } /** Register view class with module config protocol without using any router subclass. The view will be created with the `makeDestination` block in the configuration. Use this if your view is very easy and don't need a router subclass. If a module need a few required parameters when creating destination, you can declare makeDestiantionWith in module config protocol: ``` protocol LoginViewModuleInput { // Pass required parameter and return destination with LoginViewInput type. var makeDestinationWith: (_ account: String) -> LoginViewInput? { get } } // Declare routable protocol extension RoutableViewModule where Protocol == LoginViewModuleInput { init() { self.init(declaredProtocol: Protocol.self) } } ``` Then register module with module config factory block: ``` // Let ViewMakeableConfiguration conform to LoginViewModuleInput extension ViewMakeableConfiguration: LoginViewModuleInput where Destination == LoginViewInput, Constructor == (String) -> LoginViewInput? { } // Register in some +registerRoutableDestination ZIKAnyViewRouter.register(RoutableViewModule<LoginViewModuleInput>(), forMakingView: LoginViewController.self) { () -> LoginViewModuleInput in let config = ViewMakeableConfiguration<LoginViewInput, (String) -> Void>({_,_ in }) config.__prepareDestination = { destination in // Prepare the destination } // User is responsible for calling makeDestinationWith and giving parameters config.makeDestinationWith = { [unowned config] (account) in // Capture parameters in makeDestination, so we don't need configuration subclass to hold the parameters // MakeDestination will be used for creating destination instance config.makeDestination = { () -> LoginViewInput? let destination = LoginViewController(account: account) return destination } if let destination = config.makeDestination?() { config.makedDestination = destination return destination } return nil } return config } ``` You can use this module with LoginViewModuleInput: ``` Router.makeDestination(to: RoutableViewModule<LoginViewModuleInput>()) { (config) in let destination: LoginViewInput = config.makeDestinationWith("account") } ``` - Parameters: - routableViewModule: A routabe entry carrying a module config protocol conformed by the custom configuration of the router. - viewClass: The view class. - making: Block creating the configuration. The configuration must be a ZIKViewRouteConfiguration conforming to ZIKConfigurationMakeable with makeDestination or constructDestiantion property. */ static func register<Protocol>(_ routableViewModule: RoutableViewModule<Protocol>, forMakingView viewClass: AnyClass, making factory: @escaping () -> Protocol) { Registry.register(routableViewModule, forMakingView: viewClass, making: factory) } } extension ZIKViewRouter: ViewRouterExtension { } // MARK: Adapter Extension public extension ZIKViewRouteAdapter { /// Register adapter and adaptee protocols conformed by the destination. Then if you try to find router with the adapter, there will return the adaptee's router. /// /// - Parameter adapter: The required protocol used in the user. The protocol should not be directly registered with any router yet. /// - Parameter adaptee: The provided protocol. static func register<Adapter, Adaptee>(adapter: RoutableView<Adapter>, forAdaptee adaptee: RoutableView<Adaptee>) { Registry.register(adapter: adapter, forAdaptee: adaptee) } /// Register adapter and adaptee protocols conformed by the default configuration of the adaptee's router. Then if you try to find router with the adapter, there will return the adaptee's router. /// /// - Parameter adapter: The required protocol used in the user. The protocol should not be directly registered with any router yet. /// - Parameter adaptee: The provided protocol. static func register<Adapter, Adaptee>(adapter: RoutableViewModule<Adapter>, forAdaptee adaptee: RoutableViewModule<Adaptee>) { Registry.register(adapter: adapter, forAdaptee: adaptee) } } // MARK: View Route Extension /// Add Swift methods for ZIKViewRoute. Unavailable for any other classes. public protocol ViewRouteExtension: class { #if swift(>=4.1) @discardableResult func register<Protocol>(_ routableView: RoutableView<Protocol>) -> Self @discardableResult func register<Protocol>(_ routableViewModule: RoutableViewModule<Protocol>) -> Self #else func register<Protocol>(_ routableView: RoutableView<Protocol>) func register<Protocol>(_ routableViewModule: RoutableViewModule<Protocol>) #endif } public extension ViewRouteExtension { #if swift(>=4.1) /// Register pure Swift protocol or objc protocol for your view with this ZIKViewRoute. /// /// - Parameter routableView: A routabe entry carrying a protocol conformed by the destination of the router. /// - Returns: Self @discardableResult func register<Protocol>(_ routableView: RoutableView<Protocol>) -> Self { Registry.register(routableView, forRoute: self) return self } /// Register pure Swift protocol or objc protocol for your custom configuration with a ZIKViewRoute. You must add `makeDefaultConfiguration` for this route, and router will check whether the registered config protocol is conformed by the defaultRouteConfiguration. /// /// - Parameter routableViewModule: A routabe entry carrying a module config protocol conformed by the custom configuration of the router. /// - Returns: Self @discardableResult func register<Protocol>(_ routableViewModule: RoutableViewModule<Protocol>) -> Self { Registry.register(routableViewModule, forRoute: self) return self } #else func register<Protocol>(_ routableView: RoutableView<Protocol>) { Registry.register(routableView, forRoute: self) } /// Register pure Swift protocol or objc protocol for your custom configuration with a ZIKViewRoute. You must add `makeDefaultConfiguration` for this route, and router will check whether the registered config protocol is conformed by the defaultRouteConfiguration. /// /// - Parameter routableViewModule: A routabe entry carrying a module config protocol conformed by the custom configuration of the router. /// - Returns: Self func register<Protocol>(_ routableViewModule: RoutableViewModule<Protocol>) { Registry.register(routableViewModule, forRoute: self) } #endif } extension ZIKViewRoute: ViewRouteExtension { }
49.110048
268
0.719797
1a7368a28da9d0612585544e68caa8c6cc9df3f2
2,987
//: Playground - noun: a place where people can play import UIKit import PlaygroundSupport class Ball : UIView{ var color: UIColor!{ didSet{ self.setNeedsDisplay() } } var elasticity: CGFloat! lazy var mass:CGFloat = { return 2*CGFloat(M_PI)*(self.frame.size.width/2.0)*(self.frame.size.width/2.0) //return self.frame.size.width }() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = UIColor.clear } init( frame: CGRect , color: UIColor , elasticity: CGFloat = 1.0 ) { super.init(frame: frame) self.color = color self.elasticity = elasticity self.backgroundColor = UIColor.clear } override var collisionBoundsType: UIDynamicItemCollisionBoundsType { return .ellipse } // Swift3中,drawRect变为draw override func draw(_ rect: CGRect) { if let ctx = UIGraphicsGetCurrentContext(){ // Swift3中,CGContext式的C函数全面面向对象化 // 原先UIColor中的CGColor,修改为了cgColor ctx.setFillColor(color.cgColor) ctx.fillEllipse(in: rect) ctx.fillPath() } } // Swift3中,函数生明方式产生了变化,每个函数都应该默认具有第一个参数 static func randomBall(in rect: CGRect ) -> Ball{ let radius = CGFloat(arc4random_uniform(40)) + 10 let centerx = radius + CGFloat( arc4random_uniform(UInt32(rect.width-2*radius) )) let centery = radius + CGFloat( arc4random_uniform(UInt32(rect.height-2*radius) )) let randomColor = UIColor( red: CGFloat(arc4random_uniform(256))/255, green: CGFloat(arc4random_uniform(256))/255, blue: CGFloat(arc4random_uniform(256))/255, alpha: 1.0) let randomElasticity = 10000.0 + CGFloat( arc4random_uniform(2) )/10.0 // CGRect也全面面向对象化,以前的CGRectMake函数被弃用 return Ball(frame: CGRect(x: centerx-radius, y: centery-radius, width: 2*radius, height: 2*radius), color: randomColor , elasticity: randomElasticity ) } } let view = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 600)) view.backgroundColor = UIColor.white let animator = UIDynamicAnimator(referenceView: view) var gravity = UIGravityBehavior() var collision = UICollisionBehavior() var balls:[Ball] = [] let ballCount = 10 for _ in 0..<ballCount{ let aBall = Ball.randomBall(in: view.bounds) gravity.addItem(aBall) collision.addItem(aBall) view.addSubview(aBall) } for ball in balls{ let bounce = UIDynamicItemBehavior(items: [ball]) bounce.elasticity = ball.elasticity bounce.density = ball.mass animator.addBehavior(bounce) } animator.addBehavior(gravity) collision.translatesReferenceBoundsIntoBoundary = true animator.addBehavior(collision) PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = view
27.657407
159
0.648812
ed5b8532c65c7e07716698f5b1176ec9b096a35f
307
// // FivePointedStarShape.swift // Crane // // Created by captain on 2020/8/13. // Copyright © 2020 captain. All rights reserved. // import SwiftUI struct FivePointedStarShape: Shape { func path(in rect: CGRect) -> Path { var path = Path() return path } }
14.619048
50
0.589577
67365863e398b1269f7d733477330a37b39f919b
24,403
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// The core implementation of a highly-optimizable String that /// can store both ASCII and UTF-16, and can wrap native Swift /// _StringBuffer or NSString instances. /// /// Usage note: when elements are 8 bits wide, this code may /// dereference one past the end of the byte array that it owns, so /// make sure that storage is allocated! You want a null terminator /// anyway, so it shouldn't be a burden. // // Implementation note: We try hard to avoid branches in this code, so // for example we use integer math to avoid switching on the element // size with the ternary operator. This is also the cause of the // extra element requirement for 8 bit elements. See the // implementation of subscript(Int) -> UTF16.CodeUnit below for details. @_fixed_layout public struct _StringCore { //===--------------------------------------------------------------------===// // Internals public var _baseAddress: UnsafeMutableRawPointer? var _countAndFlags: UInt public var _owner: AnyObject? /// (private) create the implementation of a string from its component parts. init( baseAddress: UnsafeMutableRawPointer?, _countAndFlags: UInt, owner: AnyObject? ) { self._baseAddress = baseAddress self._countAndFlags = _countAndFlags self._owner = owner _invariantCheck() } func _invariantCheck() { // Note: this code is intentionally #if'ed out. It unconditionally // accesses lazily initialized globals, and thus it is a performance burden // in non-checked builds. #if INTERNAL_CHECKS_ENABLED _sanityCheck(count >= 0) if _baseAddress == nil { #if _runtime(_ObjC) _sanityCheck(hasCocoaBuffer, "Only opaque cocoa strings may have a null base pointer") #endif _sanityCheck(elementWidth == 2, "Opaque cocoa strings should have an elementWidth of 2") } else if _baseAddress == _emptyStringBase { _sanityCheck(!hasCocoaBuffer) _sanityCheck(count == 0, "Empty string storage with non-zero count") _sanityCheck(_owner == nil, "String pointing at empty storage has owner") } else if let buffer = nativeBuffer { _sanityCheck(!hasCocoaBuffer) _sanityCheck(elementWidth == buffer.elementWidth, "_StringCore elementWidth doesn't match its buffer's") _sanityCheck(_baseAddress! >= buffer.start) _sanityCheck(_baseAddress! <= buffer.usedEnd) _sanityCheck(_pointer(toElementAt: count) <= buffer.usedEnd) } #endif } /// Bitmask for the count part of `_countAndFlags`. var _countMask: UInt { return UInt.max &>> 2 } /// Bitmask for the flags part of `_countAndFlags`. var _flagMask: UInt { return ~_countMask } /// Value by which to multiply a 2nd byte fetched in order to /// assemble a UTF-16 code unit from our contiguous storage. If we /// store ASCII, this will be zero. Otherwise, it will be 0x100. var _highByteMultiplier: UTF16.CodeUnit { return UTF16.CodeUnit(elementShift) &<< 8 } /// Returns a pointer to the Nth element of contiguous /// storage. Caveats: The string must have contiguous storage; the /// element may be 1 or 2 bytes wide, depending on elementWidth; the /// result may be null if the string is empty. func _pointer(toElementAt n: Int) -> UnsafeMutableRawPointer { _sanityCheck(hasContiguousStorage && n >= 0 && n <= count) return _baseAddress! + (n &<< elementShift) } static func _copyElements( _ srcStart: UnsafeMutableRawPointer, srcElementWidth: Int, dstStart: UnsafeMutableRawPointer, dstElementWidth: Int, count: Int ) { // Copy the old stuff into the new storage if _fastPath(srcElementWidth == dstElementWidth) { // No change in storage width; we can use memcpy _memcpy( dest: dstStart, src: srcStart, size: UInt(count &<< (srcElementWidth - 1))) } else if srcElementWidth < dstElementWidth { // Widening ASCII to UTF-16; we need to copy the bytes manually var dest = dstStart.assumingMemoryBound(to: UTF16.CodeUnit.self) var src = srcStart.assumingMemoryBound(to: UTF8.CodeUnit.self) let srcEnd = src + count while src != srcEnd { dest.pointee = UTF16.CodeUnit(src.pointee) dest += 1 src += 1 } } else { // Narrowing UTF-16 to ASCII; we need to copy the bytes manually var dest = dstStart.assumingMemoryBound(to: UTF8.CodeUnit.self) var src = srcStart.assumingMemoryBound(to: UTF16.CodeUnit.self) let srcEnd = src + count while src != srcEnd { dest.pointee = UTF8.CodeUnit(src.pointee) dest += 1 src += 1 } } } //===--------------------------------------------------------------------===// // Initialization public init( baseAddress: UnsafeMutableRawPointer?, count: Int, elementShift: Int, hasCocoaBuffer: Bool, owner: AnyObject? ) { _sanityCheck(elementShift == 0 || elementShift == 1) self._baseAddress = baseAddress self._countAndFlags = (UInt(extendingOrTruncating: elementShift) &<< (UInt.bitWidth - 1)) | ((hasCocoaBuffer ? 1 : 0) &<< (UInt.bitWidth - 2)) | UInt(extendingOrTruncating: count) self._owner = owner _sanityCheck(UInt(count) & _flagMask == (0 as UInt), "String too long to represent") _invariantCheck() } /// Create a _StringCore that covers the entire length of the _StringBuffer. init(_ buffer: _StringBuffer) { self = _StringCore( baseAddress: buffer.start, count: buffer.usedCount, elementShift: buffer.elementShift, hasCocoaBuffer: false, owner: buffer._anyObject ) } /// Create the implementation of an empty string. /// /// - Note: There is no null terminator in an empty string. public init() { self._baseAddress = _emptyStringBase self._countAndFlags = 0 self._owner = nil _invariantCheck() } //===--------------------------------------------------------------------===// // Properties /// The number of elements stored /// - Complexity: O(1). public var count: Int { get { return Int(_countAndFlags & _countMask) } set(newValue) { _sanityCheck(UInt(newValue) & _flagMask == 0) _countAndFlags = (_countAndFlags & _flagMask) | UInt(newValue) } } /// Left shift amount to apply to an offset N so that when /// added to a UnsafeMutableRawPointer, it traverses N elements. var elementShift: Int { return Int(_countAndFlags &>> (UInt.bitWidth - 1)) } /// The number of bytes per element. /// /// If the string does not have an ASCII buffer available (including the case /// when we don't have a utf16 buffer) then it equals 2. public var elementWidth: Int { return elementShift &+ 1 } public var hasContiguousStorage: Bool { #if _runtime(_ObjC) return _fastPath(_baseAddress != nil) #else return true #endif } /// Are we using an `NSString` for storage? public var hasCocoaBuffer: Bool { return Int((_countAndFlags &<< 1)._value) < 0 } public var startASCII: UnsafeMutablePointer<UTF8.CodeUnit> { _sanityCheck(elementWidth == 1, "String does not contain contiguous ASCII") return _baseAddress!.assumingMemoryBound(to: UTF8.CodeUnit.self) } /// True iff a contiguous ASCII buffer available. public var isASCII: Bool { return elementWidth == 1 } public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> { _sanityCheck( count == 0 || elementWidth == 2, "String does not contain contiguous UTF-16") return _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self) } public var asciiBuffer: UnsafeMutableBufferPointer<UTF8.CodeUnit>? { if elementWidth != 1 { return nil } return UnsafeMutableBufferPointer(start: startASCII, count: count) } /// the native _StringBuffer, if any, or `nil`. public var nativeBuffer: _StringBuffer? { if !hasCocoaBuffer { return _owner.map { unsafeBitCast($0, to: _StringBuffer.self) } } return nil } #if _runtime(_ObjC) /// the Cocoa String buffer, if any, or `nil`. public var cocoaBuffer: _CocoaString? { if hasCocoaBuffer { return _owner } return nil } #endif //===--------------------------------------------------------------------===// // slicing /// Returns the given sub-`_StringCore`. public subscript(bounds: Range<Int>) -> _StringCore { _precondition( bounds.lowerBound >= 0, "subscript: subrange start precedes String start") _precondition( bounds.upperBound <= count, "subscript: subrange extends past String end") let newCount = bounds.upperBound - bounds.lowerBound _sanityCheck(UInt(newCount) & _flagMask == 0) if hasContiguousStorage { return _StringCore( baseAddress: _pointer(toElementAt: bounds.lowerBound), _countAndFlags: (_countAndFlags & _flagMask) | UInt(newCount), owner: _owner) } #if _runtime(_ObjC) return _cocoaStringSlice(self, bounds) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } /// Get the Nth UTF-16 Code Unit stored. @_versioned func _nthContiguous(_ position: Int) -> UTF16.CodeUnit { let p = UnsafeMutablePointer<UInt8>(_pointer(toElementAt: position)._rawValue) // Always dereference two bytes, but when elements are 8 bits we // multiply the high byte by 0. // FIXME(performance): use masking instead of multiplication. #if _endian(little) return UTF16.CodeUnit(p.pointee) + UTF16.CodeUnit((p + 1).pointee) * _highByteMultiplier #else return _highByteMultiplier == 0 ? UTF16.CodeUnit(p.pointee) : UTF16.CodeUnit((p + 1).pointee) + UTF16.CodeUnit(p.pointee) * _highByteMultiplier #endif } /// Get the Nth UTF-16 Code Unit stored. public subscript(position: Int) -> UTF16.CodeUnit { @inline(__always) get { _precondition( position >= 0, "subscript: index precedes String start") _precondition( position <= count, "subscript: index points past String end") if _fastPath(_baseAddress != nil) { return _nthContiguous(position) } #if _runtime(_ObjC) return _cocoaStringSubscript(self, position) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } } var _unmanagedASCII : UnsafeBufferPointer<Unicode.ASCII.CodeUnit>? { @inline(__always) get { guard _fastPath(_baseAddress != nil && elementWidth == 1) else { return nil } return UnsafeBufferPointer( start: _baseAddress!.assumingMemoryBound( to: Unicode.ASCII.CodeUnit.self), count: count ) } } var _unmanagedUTF16 : UnsafeBufferPointer<UTF16.CodeUnit>? { @inline(__always) get { guard _fastPath(_baseAddress != nil && elementWidth != 1) else { return nil } return UnsafeBufferPointer( start: _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self), count: count ) } } /// Write the string, in the given encoding, to output. func encode<Encoding: Unicode.Encoding>( _ encoding: Encoding.Type, into processCodeUnit: (Encoding.CodeUnit) -> Void) { defer { _fixLifetime(self) } if let bytes = _unmanagedASCII { if encoding == Unicode.ASCII.self || encoding == Unicode.UTF8.self || encoding == Unicode.UTF16.self || encoding == Unicode.UTF32.self { bytes.forEach { processCodeUnit(Encoding.CodeUnit(extendingOrTruncating: $0)) } } else { // TODO: be sure tests exercise this code path. for b in bytes { Encoding._encode( Unicode.Scalar(_unchecked: UInt32(b))).forEach(processCodeUnit) } } } else if let content = _unmanagedUTF16 { var i = content.makeIterator() Unicode.UTF16.ForwardParser._parse(&i) { Encoding._transcode($0, from: UTF16.self).forEach(processCodeUnit) } } else if hasCocoaBuffer { #if _runtime(_ObjC) _StringCore( _cocoaStringToContiguous( source: cocoaBuffer!, range: 0..<count, minimumCapacity: 0) ).encode(encoding, into: processCodeUnit) #else _sanityCheckFailure("encode: non-native string without objc runtime") #endif } } /// Attempt to claim unused capacity in the String's existing /// native buffer, if any. Return zero and a pointer to the claimed /// storage if successful. Otherwise, returns a suggested new /// capacity and a null pointer. /// /// - Note: If successful, effectively appends garbage to the String /// until it has newSize UTF-16 code units; you must immediately copy /// valid UTF-16 into that storage. /// /// - Note: If unsuccessful because of insufficient space in an /// existing buffer, the suggested new capacity will at least double /// the existing buffer's storage. mutating func _claimCapacity( _ newSize: Int, minElementWidth: Int) -> (Int, UnsafeMutableRawPointer?) { if _fastPath((nativeBuffer != nil) && elementWidth >= minElementWidth) { var buffer = nativeBuffer! // In order to grow the substring in place, this _StringCore should point // at the substring at the end of a _StringBuffer. Otherwise, some other // String is using parts of the buffer beyond our last byte. let usedStart = _pointer(toElementAt:0) let usedEnd = _pointer(toElementAt:count) // Attempt to claim unused capacity in the buffer if _fastPath( buffer.grow( oldBounds: UnsafeRawPointer(usedStart)..<UnsafeRawPointer(usedEnd), newUsedCount: newSize) ) { count = newSize return (0, usedEnd) } else if newSize > buffer.capacity { // Growth failed because of insufficient storage; double the size return (Swift.max(_growArrayCapacity(buffer.capacity), newSize), nil) } } return (newSize, nil) } /// Ensure that this String references a _StringBuffer having /// a capacity of at least newSize elements of at least the given width. /// Effectively appends garbage to the String until it has newSize /// UTF-16 code units. Returns a pointer to the garbage code units; /// you must immediately copy valid data into that storage. mutating func _growBuffer( _ newSize: Int, minElementWidth: Int ) -> UnsafeMutableRawPointer { let (newCapacity, existingStorage) = _claimCapacity(newSize, minElementWidth: minElementWidth) if _fastPath(existingStorage != nil) { return existingStorage! } let oldCount = count _copyInPlace( newSize: newSize, newCapacity: newCapacity, minElementWidth: minElementWidth) return _pointer(toElementAt:oldCount) } /// Replace the storage of self with a native _StringBuffer having a /// capacity of at least newCapacity elements of at least the given /// width. Effectively appends garbage to the String until it has /// newSize UTF-16 code units. mutating func _copyInPlace( newSize: Int, newCapacity: Int, minElementWidth: Int ) { _sanityCheck(newCapacity >= newSize) let oldCount = count // Allocate storage. let newElementWidth = minElementWidth >= elementWidth ? minElementWidth : isRepresentableAsASCII() ? 1 : 2 let newStorage = _StringBuffer(capacity: newCapacity, initialSize: newSize, elementWidth: newElementWidth) if hasContiguousStorage { _StringCore._copyElements( _baseAddress!, srcElementWidth: elementWidth, dstStart: UnsafeMutableRawPointer(newStorage.start), dstElementWidth: newElementWidth, count: oldCount) } else { #if _runtime(_ObjC) // Opaque cocoa buffers might not store ASCII, so assert that // we've allocated for 2-byte elements. // FIXME: can we get Cocoa to tell us quickly that an opaque // string is ASCII? Do we care much about that edge case? _sanityCheck(newStorage.elementShift == 1) _cocoaStringReadAll(cocoaBuffer!, newStorage.start.assumingMemoryBound(to: UTF16.CodeUnit.self)) #else _sanityCheckFailure("_copyInPlace: non-native string without objc runtime") #endif } self = _StringCore(newStorage) } /// Append `c` to `self`. /// /// - Complexity: O(1) when amortized over repeated appends of equal /// character values. mutating func append(_ c: Unicode.Scalar) { let width = UTF16.width(c) append( width == 2 ? UTF16.leadSurrogate(c) : UTF16.CodeUnit(c.value), width == 2 ? UTF16.trailSurrogate(c) : nil ) } /// Append `u` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(_ u: UTF16.CodeUnit) { append(u, nil) } mutating func append(_ u0: UTF16.CodeUnit, _ u1: UTF16.CodeUnit?) { _invariantCheck() let minBytesPerCodeUnit = u0 <= 0x7f ? 1 : 2 let utf16Width = u1 == nil ? 1 : 2 let destination = _growBuffer( count + utf16Width, minElementWidth: minBytesPerCodeUnit) if _fastPath(elementWidth == 1) { _sanityCheck(_pointer(toElementAt:count) == destination + 1) destination.assumingMemoryBound(to: UTF8.CodeUnit.self)[0] = UTF8.CodeUnit(u0) } else { let destination16 = destination.assumingMemoryBound(to: UTF16.CodeUnit.self) destination16[0] = u0 if u1 != nil { destination16[1] = u1! } } _invariantCheck() } @inline(never) mutating func append(_ rhs: _StringCore) { _invariantCheck() let minElementWidth = elementWidth >= rhs.elementWidth ? elementWidth : rhs.isRepresentableAsASCII() ? 1 : 2 let destination = _growBuffer( count + rhs.count, minElementWidth: minElementWidth) if _fastPath(rhs.hasContiguousStorage) { _StringCore._copyElements( rhs._baseAddress!, srcElementWidth: rhs.elementWidth, dstStart: destination, dstElementWidth:elementWidth, count: rhs.count) } else { #if _runtime(_ObjC) _sanityCheck(elementWidth == 2) _cocoaStringReadAll(rhs.cocoaBuffer!, destination.assumingMemoryBound(to: UTF16.CodeUnit.self)) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } _invariantCheck() } /// Returns `true` iff the contents of this string can be /// represented as pure ASCII. /// /// - Complexity: O(*n*) in the worst case. func isRepresentableAsASCII() -> Bool { if _slowPath(!hasContiguousStorage) { return false } if _fastPath(elementWidth == 1) { return true } let unsafeBuffer = UnsafeBufferPointer( start: _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self), count: count) return !unsafeBuffer.contains { $0 > 0x7f } } } extension _StringCore : RandomAccessCollection { public typealias Indices = CountableRange<Int> public // @testable var startIndex: Int { return 0 } public // @testable var endIndex: Int { return count } } extension _StringCore : RangeReplaceableCollection { /// Replace the elements within `bounds` with `newElements`. /// /// - Complexity: O(`bounds.count`) if `bounds.upperBound /// == self.endIndex` and `newElements.isEmpty`, O(*n*) otherwise. public mutating func replaceSubrange<C>( _ bounds: Range<Int>, with newElements: C ) where C : Collection, C.Element == UTF16.CodeUnit { _precondition( bounds.lowerBound >= 0, "replaceSubrange: subrange start precedes String start") _precondition( bounds.upperBound <= count, "replaceSubrange: subrange extends past String end") let width = elementWidth == 2 || newElements.contains { $0 > 0x7f } ? 2 : 1 let replacementCount = numericCast(newElements.count) as Int let replacedCount = bounds.count let tailCount = count - bounds.upperBound let growth = replacementCount - replacedCount let newCount = count + growth // Successfully claiming capacity only ensures that we can modify // the newly-claimed storage without observably mutating other // strings, i.e., when we're appending. Already-used characters // can only be mutated when we have a unique reference to the // buffer. let appending = bounds.lowerBound == endIndex let existingStorage = !hasCocoaBuffer && ( appending || isKnownUniquelyReferenced(&_owner) ) ? _claimCapacity(newCount, minElementWidth: width).1 : nil if _fastPath(existingStorage != nil) { let rangeStart = _pointer(toElementAt:bounds.lowerBound) let tailStart = rangeStart + (replacedCount &<< elementShift) if growth > 0 { (tailStart + (growth &<< elementShift)).copyBytes( from: tailStart, count: tailCount &<< elementShift) } if _fastPath(elementWidth == 1) { var dst = rangeStart.assumingMemoryBound(to: UTF8.CodeUnit.self) for u in newElements { dst.pointee = UInt8(extendingOrTruncating: u) dst += 1 } } else { var dst = rangeStart.assumingMemoryBound(to: UTF16.CodeUnit.self) for u in newElements { dst.pointee = u dst += 1 } } if growth < 0 { (tailStart + (growth &<< elementShift)).copyBytes( from: tailStart, count: tailCount &<< elementShift) } } else { var r = _StringCore( _StringBuffer( capacity: newCount, initialSize: 0, elementWidth: width == 1 ? 1 : isRepresentableAsASCII() && !newElements.contains { $0 > 0x7f } ? 1 : 2 )) r.append(contentsOf: self[0..<bounds.lowerBound]) r.append(contentsOf: newElements) r.append(contentsOf: self[bounds.upperBound..<count]) self = r } } public mutating func reserveCapacity(_ n: Int) { if _fastPath(!hasCocoaBuffer) { if _fastPath(isKnownUniquelyReferenced(&_owner)) { let bounds: Range<UnsafeRawPointer> = UnsafeRawPointer(_pointer(toElementAt:0)) ..< UnsafeRawPointer(_pointer(toElementAt:count)) if _fastPath(nativeBuffer!.hasCapacity(n, forSubRange: bounds)) { return } } } _copyInPlace( newSize: count, newCapacity: Swift.max(count, n), minElementWidth: 1) } public mutating func append<S : Sequence>(contentsOf s: S) where S.Element == UTF16.CodeUnit { var width = elementWidth if width == 1 { if let hasNonAscii = s._preprocessingPass({ s.contains { $0 > 0x7f } }) { width = hasNonAscii ? 2 : 1 } } let growth = s.underestimatedCount var iter = s.makeIterator() if _fastPath(growth > 0) { let newSize = count + growth let destination = _growBuffer(newSize, minElementWidth: width) if elementWidth == 1 { let destination8 = destination.assumingMemoryBound(to: UTF8.CodeUnit.self) for i in 0..<growth { destination8[i] = UTF8.CodeUnit(iter.next()!) } } else { let destination16 = destination.assumingMemoryBound(to: UTF16.CodeUnit.self) for i in 0..<growth { destination16[i] = iter.next()! } } } // Append any remaining elements for u in IteratorSequence(iter) { self.append(u) } } } // Used to support a tighter invariant: all strings with contiguous // storage have a non-NULL base address. var _emptyStringStorage: UInt32 = 0 var _emptyStringBase: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(Builtin.addressof(&_emptyStringStorage)) }
31.77474
147
0.64906
5657b4899e9192c711cafe135f512bb3ab3f52a6
3,255
import XCTest import Cuckoo import BigInt @testable import BitcoinCoreKit class DifficultyEncoderTests: XCTestCase { private var difficultyEncoder: DifficultyEncoder! override func setUp() { super.setUp() difficultyEncoder = DifficultyEncoder() } override func tearDown() { difficultyEncoder = nil super.tearDown() } func testCompactFromMaxHash() { let hash = Data(hex: "123456789012345678901234567890FFFF12345678901234567890123456FFFF")! let representation: Int = 0x2100ffff XCTAssertEqual(difficultyEncoder.compactFrom(hash: hash), representation) } func testCompactFromHashWithoutShift() { let hash = Data(hex: "123456789012345678901234567890FFFF12345678901234567890123456FF7F")! let representation: Int = 0x207fff56 XCTAssertEqual(difficultyEncoder.compactFrom(hash: hash), representation) } func testCompactFromHashStandartWithoutShift() { let hash = Data(hex: "123456789012345678901234567890FFFF123456789012345678000000000000")! let representation: Int = 0x1a785634 XCTAssertEqual(difficultyEncoder.compactFrom(hash: hash), representation) } func testCompactFromHashStandartWithShift() { let hash = Data(hex: "123456789012345678901234567890FFFF123456789012345681000000000000")! let representation: Int = 0x1b008156 XCTAssertEqual(difficultyEncoder.compactFrom(hash: hash), representation) } func testCompactFromHashBiggest() { let hash = Data(hex: "0100000000000000000000000000000000000000000000000000000000000000")! let representation: Int = 0x03000001 XCTAssertEqual(difficultyEncoder.compactFrom(hash: hash), representation) } func testEncodeCompact() { let difficulty: BigInt = BigInt("1234560000", radix: 16)! let representation: Int = 0x05123456 XCTAssertEqual(difficultyEncoder.encodeCompact(from: difficulty), representation) } func testEncodeCompact_firstZero() { let difficulty: BigInt = BigInt("c0de000000", radix: 16)! let representation: Int = 0x0600c0de XCTAssertEqual(difficultyEncoder.encodeCompact(from: difficulty), representation) } func testEncodeCompact_negativeSign() { let difficulty: BigInt = BigInt("-40de000000", radix: 16)! let representation: Int = 0x05c0de00 XCTAssertEqual(difficultyEncoder.encodeCompact(from: difficulty), representation) } func testDecodeCompact() { let difficulty: BigInt = BigInt("1234560000", radix: 16)! let representation: Int = 0x05123456 XCTAssertEqual(difficultyEncoder.decodeCompact(bits: representation), difficulty) } func testDecodeCompact_firstZero() { let difficulty: BigInt = BigInt("c0de000000", radix: 16)! let representation: Int = 0x0600c0de XCTAssertEqual(difficultyEncoder.decodeCompact(bits: representation), difficulty) } func testDecodeCompact_negativeSign() { let difficulty: BigInt = BigInt("-40de000000", radix: 16)! let representation: Int = 0x05c0de00 XCTAssertEqual(difficultyEncoder.decodeCompact(bits: representation), difficulty) } }
32.55
97
0.715515
de30c6fd4e2d3c10e34aa525b60637a191e1201b
845
// // ListLocalAssetsCommand.swift // // // Created by Kenneth Endfinger on 10/23/21. // import ArgumentParser import Foundation struct ListLocalAssetsCommand: ParsableCommand { static var configuration = CommandConfiguration( commandName: "list-local-assets", abstract: "List assets inside the local cache." ) @Flag(name: [.customShort("j"), .customLong("json")], help: "Enables JSON output.") var json: Bool = false func run() throws { for asset in try AssetCacheToolCommand.cache.listAllAssets() { if json { print(String(data: try JSONEncoder().encode(asset), encoding: .utf8)!) } else { print("\(asset.guid) namespace=\(asset.namespace ?? "default") index=\(asset.index ?? "unknown") uri=\(asset.uri)") } } } }
28.166667
131
0.614201
ccc17763abce89cf5b434da385df3325bf9cd816
9,390
// // WaveformView.swift // PlayerDemo // // Created by Ryan Francesconi on 7/26/20. // Copyright © 2020 AudioKit. All rights reserved. // import AudioKit import AudioKitUI import AVFoundation import Cocoa /// A basic Waveform editor interface class WaveformView: NSView { public struct Selection { var startTime: TimeInterval = 0 var endTime: TimeInterval = 0 } private let maroon = NSColor(calibratedRed: 0.79, green: 0.372, blue: 0.191, alpha: 1) public weak var delegate: WaveformViewDelegate? public var pixelsPerSample: Int = 1024 public private(set) var waveform: AKWaveform? internal var fadeInLayer = ActionCAShapeLayer() internal var fadeOutLayer = ActionCAShapeLayer() internal var fadeColor = NSColor.black.withAlphaComponent(0.4).cgColor public private(set) lazy var timelineBar = TimelineBar(color: NSColor.white.cgColor) internal var inOutLayer = ActionCAShapeLayer() private var visualScaleFactor: Double = 30 var mouseDownTime: TimeInterval = 0 public var time: TimeInterval = 0 { didSet { timelineBar.frame.origin.x = CGFloat(time * visualScaleFactor) } } var timelineDuration: TimeInterval { startOffset + duration } public private(set) var duration: TimeInterval = 0 { didSet { outPoint = duration } } public private(set) var selection = Selection() public var inPoint: TimeInterval = 0 { didSet { updateSelectionLayer() } } public var outPoint: TimeInterval = 0 { didSet { updateSelectionLayer() } } public var startOffset: TimeInterval = 0 { didSet { updateLayers() } } public var fadeInOffset: TimeInterval = 0 { didSet { updateFadeIn() } } public var fadeOutOffset: TimeInterval = 0 { didSet { updateFadeOut() } } public var fadeInTime: TimeInterval = 0 { didSet { updateFadeIn() } } public var fadeOutTime: TimeInterval = 0 { didSet { updateFadeOut() } } override public init(frame frameRect: NSRect) { super.init(frame: frameRect) initialize() } required init?(coder: NSCoder) { super.init(coder: coder) initialize() } // MARK: - Private Functions private func initialize() { wantsLayer = true fadeInLayer.fillColor = fadeColor fadeOutLayer.fillColor = fadeColor inOutLayer.backgroundColor = NSColor.white.withAlphaComponent(0.3).cgColor layer?.insertSublayer(inOutLayer, at: 0) // waveform to be inserted at: 1 layer?.insertSublayer(fadeInLayer, at: 3) layer?.insertSublayer(fadeOutLayer, at: 4) layer?.insertSublayer(timelineBar, at: 5) } private func updateLayers() { guard duration > 0 else { return } let x: CGFloat = CGFloat(startOffset * visualScaleFactor) let virtualWidth = frame.width - x visualScaleFactor = Double(virtualWidth) / duration fadeInOffset = startOffset updateFadeOut() waveform?.frame = CGRect(x: x, y: 0, width: virtualWidth, height: frame.height) waveform?.updateLayer() timelineBar.setHeight(frame.height) } private func updateSelectionLayer() { let start = CGFloat(inPoint * visualScaleFactor) let end = CGFloat(outPoint * visualScaleFactor) inOutLayer.frame = CGRect(x: start, y: 0, width: end - start, height: frame.height) inOutLayer.setNeedsDisplay() updateSelection() } private func updateSelection() { selection.startTime = min(outPoint, inPoint) selection.endTime = max(inPoint, outPoint) } private func updateFadeIn() { guard fadeInTime > 0 else { fadeInLayer.path = nil return } let fh = frame.height - 1 let fadePath = NSBezierPath() var fw = CGFloat(fadeInTime * visualScaleFactor) if fw < 3.0 { fw = 3.0 } let startX = CGFloat(fadeInOffset * visualScaleFactor) fadeInLayer.frame = CGRect(x: startX, y: 0, width: fw, height: fh) fadePath.move(to: NSPoint(x: 0, y: 0)) fadePath.line(to: NSPoint(x: fw, y: fh)) fadePath.line(to: NSPoint(x: fw, y: 0)) fadePath.line(to: NSPoint(x: 0, y: 0)) fadeInLayer.path = fadePath.cgPath } private func updateFadeOut() { guard fadeOutTime > 0 else { fadeOutLayer.path = nil return } let fh = frame.height - 1 let fadePath = NSBezierPath() let startX = CGFloat(fadeOutOffset * visualScaleFactor) var fw = CGFloat(fadeOutTime * visualScaleFactor) if fw < 3.0 { fw = 3.0 } let x = fw fadeOutLayer.frame = CGRect(x: frame.width - startX - fw, y: 0, width: fw, height: fh) fadePath.move(to: NSPoint(x: fw, y: 0)) fadePath.line(to: NSPoint(x: x - fw, y: 0)) fadePath.line(to: NSPoint(x: x - fw, y: fh)) fadePath.line(to: NSPoint(x: x, y: 0)) fadeOutLayer.path = fadePath.cgPath } private func convertToTime(with event: NSEvent) -> Double { let loc = convert(event.locationInWindow, from: nil) var mouseTime = Double(loc.x / frame.width) * timelineDuration mouseTime = max(0, mouseTime) mouseTime = min(timelineDuration, mouseTime) return mouseTime } // MARK: - Public Functions public func open(url: URL) { if waveform != nil { close() } // it's good to reopen this file as using the same file object in multiple // places can be problematic guard let audioFile = try? AVAudioFile(forReading: url) else { AKLog("Failed to open file for reading...") return } if waveform == nil { duration = audioFile.duration waveform = AKWaveform(channels: Int(audioFile.fileFormat.channelCount), size: frame.size, waveformColor: maroon.cgColor, backgroundColor: nil) waveform?.isMirrored = true waveform?.allowActions = false if let waveform = waveform { layer?.insertSublayer(waveform, at: 1) updateLayers() } } // fetch the waveform data AKWaveformDataRequest(audioFile: audioFile) .getDataAsync(with: pixelsPerSample, completionHandler: { data in guard let floatData = data else { AKLog("Error getting waveform data", type: .error) return } self.waveform?.fill(with: floatData) }) } public func close() { waveform?.dispose() waveform?.removeFromSuperlayer() waveform = nil } } // MARK: - Mouse Handlers extension WaveformView { override public func mouseDown(with event: NSEvent) { super.mouseDown(with: event) inPoint = convertToTime(with: event) outPoint = inPoint delegate?.waveformSelected(source: self, at: inPoint) } override public func mouseUp(with event: NSEvent) { super.mouseUp(with: event) let time = convertToTime(with: event) delegate?.waveformScrubComplete(source: self, at: time) } override public func mouseDragged(with event: NSEvent) { outPoint = convertToTime(with: event) updateSelectionLayer() delegate?.waveformScrubbed(source: self, at: outPoint) } } protocol WaveformViewDelegate: class { func waveformSelected(source: WaveformView, at time: Double) func waveformScrubbed(source: WaveformView, at time: Double) func waveformScrubComplete(source: WaveformView, at time: Double) } // MARK: - Misc class TimelineBar: ActionCAShapeLayer { public init(color: CGColor) { super.init() strokeColor = color } required init?(coder: NSCoder) { super.init(coder: coder) strokeColor = NSColor.white.cgColor } public func setHeight(_ height: CGFloat = 200) { lineWidth = 1 let path = CGMutablePath() path.move(to: NSPoint(x: 0, y: 0)) path.addLine(to: NSPoint(x: 0, y: height)) self.path = path } } public extension NSBezierPath { var cgPath: CGPath { let path = CGMutablePath() var points = [CGPoint](repeating: .zero, count: 3) for i in 0 ..< elementCount { let type = element(at: i, associatedPoints: &points) switch type { case .moveTo: path.move(to: points[0]) case .lineTo: path.addLine(to: points[0]) case .curveTo: path.addCurve(to: points[2], control1: points[0], control2: points[1]) case .closePath: path.closeSubpath() @unknown default: break } } return path } }
27.946429
94
0.582961
2060b3d1ca4e6012b8a34296dab5a8a794fbd981
2,602
// // AppDelegate.swift // uprm1 // // Created by Javier Bustillo on 8/17/17. // Copyright © 2017 Javier Bustillo. All rights reserved. // import UIKit import Parse @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let configuration = ParseClientConfiguration { $0.applicationId = "X8762GRFgHMp2v31GlAhZEOB2MeKtVYk5wyAnggg" $0.clientKey = "H4oCGVkDkTw31dTeQXbCDnjthdj69PGS9wHQwRZl" $0.server = "https://parseapi.back4app.com" } Parse.initialize(with: configuration) PFUser.enableAutomaticUser() PFUser.current()?.saveInBackground() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
44.101695
285
0.736357
202b52597546845650733d442ec0c3ee812d35db
133
// // IInterstitialAd.swift // ee-x-366f64ba // // Created by eps on 6/24/20. // protocol IFullScreenAd: IAd { func show() }
12.090909
30
0.616541
222226ac32ff2693656c9ce880a04108bb43b63b
20,490
// // RestaurantBookmarkViewController.swift // GoOut Restauracje // // Created by Michal Szymaniak on 20/08/16. // Copyright © 2016 Codelabs. All rights reserved. // import UIKit import PKHUD import MapKit class RestaurantBookmarkViewController: RootViewController, CollectionViewControllerDelegate { @IBOutlet weak var RestaurantNameLabel: UILabel! @IBOutlet weak var apiKontentView: UIView! @IBOutlet weak var downView: UIView! @IBOutlet weak var generateButton: UIButton! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var districtLabel: UILabel! @IBOutlet weak var kitchenLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var mailLabel: UILabel! @IBOutlet weak var textView: UITextView! @IBOutlet weak var kitchenLeftView: UIView! @IBOutlet weak var kitchenLeftViewHeightConstr: NSLayoutConstraint! @IBOutlet weak var star1K: UIImageView! @IBOutlet weak var star2K: UIImageView! @IBOutlet weak var star3K: UIImageView! @IBOutlet weak var star4K: UIImageView! @IBOutlet weak var star5K: UIImageView! @IBOutlet weak var wystrojMiddleView: UIView! @IBOutlet weak var wystrojMiddleViewHeightC: NSLayoutConstraint! @IBOutlet weak var star1W: UIImageView! @IBOutlet weak var star2W: UIImageView! @IBOutlet weak var star3W: UIImageView! @IBOutlet weak var star4W: UIImageView! @IBOutlet weak var star5W: UIImageView! @IBOutlet weak var mapsImageView: UIImageView! @IBOutlet weak var obslugaRightView: UIView! @IBOutlet weak var obslugaViewHeightC: NSLayoutConstraint! @IBOutlet weak var star1O: UIImageView! @IBOutlet weak var star2O: UIImageView! @IBOutlet weak var star3O: UIImageView! @IBOutlet weak var star4O: UIImageView! @IBOutlet weak var star5O: UIImageView! @IBOutlet weak var imageNumberDot1: UIImageView! @IBOutlet weak var imageNumberDot2: UIImageView! @IBOutlet weak var imageNumberDot3: UIImageView! @IBOutlet weak var imageNumberDot4: UIImageView! @IBOutlet weak var imageNumberDot5: UIImageView! @IBOutlet weak var imgDotWidth1: NSLayoutConstraint! @IBOutlet weak var imgDotWidth2: NSLayoutConstraint! @IBOutlet weak var imgDotWidth3: NSLayoutConstraint! @IBOutlet weak var imgDotWidth4: NSLayoutConstraint! @IBOutlet weak var imgDotWidth5: NSLayoutConstraint! @IBOutlet weak var mapView: UIView! let animationDuration = 0.5 var kitchenStarsArray = NSArray() var wystroStarsArray = NSArray() var obslugaStarsArray = NSArray() var selectedRestaurantId:NSNumber? var restaurantData:RestaurantDescription = RestaurantDescription() var kuponCount = 0 let controllerCollection = CollectionViewController() var collectionImagesCountArray:NSArray = NSArray() var collectionImagesCountWidthArray:NSArray = NSArray() let controllerMap = MapController() override func viewDidLoad() { super.viewDidLoad() addressLabel.numberOfLines = 1 addressLabel.adjustsFontSizeToFitWidth = true addressLabel.minimumScaleFactor = 0.1 // RestaurantNameLabel.numberOfLines = 1 // RestaurantNameLabel.adjustsFontSizeToFitWidth = true // RestaurantNameLabel.minimumScaleFactor = 0.1 setGenerateButtonTittle() setupButtonViewLabels() shouldAddBackButton = true controllerCollection.collectionDelegate = self fillStarsArray() HUD.show(.progress) if selectedRestaurantId != nil { RestClient.sharedInstance.getRestaurantsDescription(selectedRestaurantId!) { (restaurantDesc, succes) in DispatchQueue.main.async { if succes { HUD.hide() self.restaurantData = restaurantDesc! self.setupCollectionView() self.setViewData() if self.controllerMap.mapView == nil { self.controllerMap.setupMap(self.mapView) self.controllerMap.setRestaurantTomap(restaurantDesc!) } } else { HUD.show(.labeledError(title: "Błąd", subtitle: "Brak połącznia z siecią")) HUD.hide(afterDelay: 2.0) } } } } else { HUD.show(.labeledError(title: "Błąd", subtitle: "Błąd aplikacji")) HUD.hide(afterDelay: 2.0) } } func fillStarsArray() { kitchenStarsArray = [star1K, star2K, star3K, star4K, star5K] obslugaStarsArray = [star1O, star2O, star3O, star4O, star5O] wystroStarsArray = [star1W, star2W, star3W, star4W, star5W] } func setupCollectionView() { controllerCollection.parentViewController = self controllerCollection.parentCollectionView = collectionView controllerCollection.dataArray = restaurantData.photosArray controllerCollection.setupCollectionView() setupCollectionImagesCountArray() DispatchQueue.main.async { self.setupImagesCountForSelection() self.controllerCollection.reloadCollectionView() } } func setViewData() { DispatchQueue.main.async { ViewConfigurator.setTextFont(forLabel: self.RestaurantNameLabel, textForSet: self.restaurantData.name!) //self.RestaurantNameLabel.text = self.restaurantData.name self.addressLabel.text = self.restaurantData.address self.districtLabel.text = self.restaurantData.district self.kitchenLabel.text = self.getAllKitchenString() self.phoneLabel.text = self.restaurantData.phone1 self.mailLabel.text = self.restaurantData.link self.textView.text = self.restaurantData.about_pl self.setupStars() self.view.layoutIfNeeded() self.setupKuponCountButton() } } func setupImagesCountForSelection() { if restaurantData.photosArray.count > 0 { (collectionImagesCountArray[0] as! UIImageView).image = UIImage(named: ConstantsStruct.Buttons.dotFiled) } for (index, imageView) in collectionImagesCountArray.enumerated() { if index < restaurantData.photosArray.count { (imageView as! UIImageView).isHidden = false (collectionImagesCountWidthArray[index] as! NSLayoutConstraint).constant = 20 } else { (imageView as! UIImageView).isHidden = true (collectionImagesCountWidthArray[index] as! NSLayoutConstraint).constant = 0 } } } func setupCollectionImagesCountArray() { collectionImagesCountArray = [imageNumberDot1, imageNumberDot2, imageNumberDot3, imageNumberDot4, imageNumberDot5] collectionImagesCountWidthArray = [imgDotWidth1, imgDotWidth2, imgDotWidth3, imgDotWidth4, imgDotWidth5] } func setupStars() { if restaurantData.kitchenScore != nil { if restaurantData.kitchenScore != 0 { for object in kitchenStarsArray { let imageView = (object as! UIImageView) if imageView.tag <= (restaurantData.kitchenScore?.intValue)! { imageView.image = UIImage(named:ConstantsStruct.Buttons.smallStarSelected) } else { imageView.image = UIImage(named:ConstantsStruct.Buttons.smallStarNOTSelected) } } } else { kitchenLeftView.isHidden = true } } else { kitchenLeftView.isHidden = true } if restaurantData.wystrojScore != nil { if restaurantData.wystrojScore != 0 { for object in wystroStarsArray { let imageView = (object as! UIImageView) if imageView.tag <= (restaurantData.wystrojScore?.intValue)! { imageView.image = UIImage(named:ConstantsStruct.Buttons.smallStarSelected) } else { imageView.image = UIImage(named:ConstantsStruct.Buttons.smallStarNOTSelected) } } } else { wystrojMiddleView.isHidden = true } } else { wystrojMiddleView.isHidden = true } if restaurantData.obslugaScore != nil { if restaurantData.obslugaScore != 0 { for object in obslugaStarsArray { let imageView = (object as! UIImageView) if imageView.tag <= (restaurantData.obslugaScore?.intValue)! { imageView.image = UIImage(named:ConstantsStruct.Buttons.smallStarSelected) } else { imageView.image = UIImage(named:ConstantsStruct.Buttons.smallStarNOTSelected) } } } else { obslugaRightView.isHidden = true } } else { obslugaRightView.isHidden = true } if kitchenLeftView.isHidden == true && wystrojMiddleView.isHidden == true && obslugaRightView.isHidden == true { kitchenLeftViewHeightConstr.constant = 0 wystrojMiddleViewHeightC.constant = 0 obslugaViewHeightC.constant = 0 } } func getAllKitchenString() -> String { var kitchenString = "" if restaurantData.cuisineArray.count > 1 { kitchenString = "Kuchnia: \(((restaurantData.cuisineArray.firstObject as! CuisinesObject).cuisineName?.capitalized)!)" for i in 1..<restaurantData.cuisineArray.count { kitchenString = kitchenString + ", \((restaurantData.cuisineArray[i] as! CuisinesObject).cuisineName!)" } } else if restaurantData.cuisineArray.count == 1 { kitchenString = "Kuchnia: "+((restaurantData.cuisineArray.firstObject as! CuisinesObject).cuisineName!) } return kitchenString } func setGenerateButtonTittle() { if kuponCount == 0 { generateButton.setTitle("Kup dostęp", for: UIControlState()) } else {//Masz 3 kupony użyj if kuponCount % 10 == 1 { generateButton.setTitle("Masz \(kuponCount) kupony, użyj", for: UIControlState()) return } if kuponCount % 10 == 5 || kuponCount % 10 == 6 || kuponCount % 10 == 7 || kuponCount % 10 == 8 || kuponCount % 10 == 9 { generateButton.setTitle("Masz \(kuponCount) kuponów, użyj", for: UIControlState()) return } } } func setupButtonViewLabels() { ViewConfigurator.createRoundedCornersAndBorderWidth(viewObject: generateButton, setRoundedCorners: true, shouldHaveBorder: true); } func setupKuponCountButton() { if restaurantData.kuponAvailable != nil { kuponCount = restaurantData.kuponAvailable!.intValue if kuponCount == 0 { generateButton.setTitle("Nie masz? Kup!", for: UIControlState()) return } if kuponCount == 1 || kuponCount % 10 == 1 { generateButton.setTitle("Masz 1 kupon użyj", for: UIControlState()) return } if kuponCount == 2 || kuponCount == 3 || kuponCount == 4 || kuponCount % 10 == 2 || kuponCount % 10 == 3 || kuponCount % 10 == 4 { generateButton.setTitle("Masz \(kuponCount) kupony użyj", for: UIControlState()) return } else { generateButton.setTitle("Masz \(kuponCount) kuponów użyj", for: UIControlState()) } } } @IBAction func buyKuponButtonClicked(_ sender: AnyObject) { if kuponCount == 0 { let storyboard = UIStoryboard(name: "Main", bundle: nil) let inAppViewController = storyboard.instantiateViewController(withIdentifier: "InnAppPurchaseViewController") as! InnAppPurchaseViewController self.navigationController?.show(inAppViewController, sender: nil) } else { let storyboard = UIStoryboard(name: "Main", bundle: nil) let kuponViewController = storyboard.instantiateViewController(withIdentifier: "KuponViewController") as! KuponViewController kuponViewController.restaurantData.restaurantName = restaurantData.name! kuponViewController.restaurantData.restaurantId = (restaurantData.id! as NSString).integerValue kuponViewController.restaurantData.availableKupons = restaurantData.kuponAvailable?.intValue kuponViewController.restaurantData.totalKupons = restaurantData.kuponTotal?.intValue kuponViewController.restaurantData.address = restaurantData.address self.navigationController?.show(kuponViewController, sender: nil) } } @IBAction func openRestaurantLink(_ sender: AnyObject) { if (mailLabel.text?.characters.count)! > 0 { let linkText = mailLabel.text! as String let callAllertController = UIAlertController(title:"" , message: "Otworzyć w przeglądarce?", preferredStyle: .alert) let cancellAction = UIAlertAction(title: "Nie", style: .cancel, handler: nil) let callAction = UIAlertAction(title: "Tak", style: .default, handler: { (self) in UIApplication.shared.openURL(URL(string: linkText)!) }) callAllertController.addAction(callAction) callAllertController.addAction(cancellAction) DispatchQueue.main.async { self.present(callAllertController, animated: true, completion: nil) } } } @IBAction func callToRestaurant(_ sender: AnyObject) { if (phoneLabel.text?.characters.count)! > 0 { var finalPhoneString = phoneLabel.text?.replacingOccurrences(of: " ", with: "", options: NSString.CompareOptions.literal, range: nil) if phoneLabel.text!.hasPrefix("+48") { let index1 = finalPhoneString?.characters.index((finalPhoneString?.startIndex)!, offsetBy: 3) finalPhoneString = finalPhoneString?.substring(from: index1!) } let callAllertController = UIAlertController(title:"" , message: "Czy chcesz zadzwonić do restauracji?", preferredStyle: .alert) let cancellAction = UIAlertAction(title: "Nie", style: .cancel, handler: nil) let callAction = UIAlertAction(title: "Tak", style: .default, handler: { (self) in UIApplication.shared.openURL(URL(string: "tel://\(finalPhoneString!)")!) }) callAllertController.addAction(callAction) callAllertController.addAction(cancellAction) DispatchQueue.main.async { self.present(callAllertController, animated: true, completion: nil) } // present(callAllertController, animated: true, completion: nil) } } @IBAction func showOnMap(_ sender: AnyObject) { let lat1 : NSString = restaurantData.lat! as NSString let lng1 : NSString = restaurantData.lng! as NSString let latitude:CLLocationDegrees = lat1.doubleValue let longitude:CLLocationDegrees = lng1.doubleValue let regionDistance:CLLocationDistance = 10000 let coordinates = CLLocationCoordinate2DMake(latitude, longitude) let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance) let options = [ MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center), MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span) ] let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil) let mapItem = MKMapItem(placemark: placemark) mapItem.name = "\(restaurantData.name!)" let callAllertController = UIAlertController(title:"" , message: "Pokazać na mapie?", preferredStyle: .alert) let cancellAction = UIAlertAction(title: "Nie", style: .cancel, handler: nil) let callAction = UIAlertAction(title: "Tak", style: .default, handler: { (self) in mapItem.openInMaps(launchOptions: options) }) callAllertController.addAction(callAction) callAllertController.addAction(cancellAction) DispatchQueue.main.async { self.present(callAllertController, animated: true, completion: nil) } } //MARK: - Collection controller delegate methods func collectionController(_ collectionController:CollectionViewController, scrolledToCellAtIndexPath indexPath:IndexPath) { setupSelectedImagesCount(at: (indexPath as NSIndexPath).row) } func setupSelectedImagesCount(at indexImage:Int) { for (index, image) in collectionImagesCountArray.enumerated() { if index == indexImage { (image as! UIImageView).image = UIImage(named: ConstantsStruct.Buttons.dotFiled) } else { (image as! UIImageView).image = UIImage(named: ConstantsStruct.Buttons.dotEmpty) } } } @IBAction func showHideMapView(_ sender: AnyObject) { controllerMap.setCameraOnMarker((restaurantData.lng! as NSString).doubleValue, lat: (restaurantData.lat! as NSString).doubleValue) DispatchQueue.main.async { if self.mapView.isHidden == true { self.mapsImageView.image = UIImage(named: ConstantsStruct.Buttons.showCollectionView) UITableView.transition(with: self.collectionView, duration: self.animationDuration, options: .transitionFlipFromRight, animations: { self.collectionView.isHidden = true }, completion: { (Bool) in UITableView.transition(with: self.mapView, duration: self.animationDuration, options: .transitionFlipFromRight, animations: { self.mapView.isHidden = false }, completion: { (Bool) in }) }) } else { self.mapsImageView.image = UIImage(named: ConstantsStruct.Buttons.showMapButton) UIView.transition(with: self.mapView, duration: self.animationDuration, options: .transitionFlipFromLeft, animations: { self.mapView.isHidden = true },completion: { (Bool) in UITableView.transition(with: self.collectionView, duration: self.animationDuration, options: .transitionFlipFromLeft, animations: { self.collectionView.isHidden = false }, completion: { (Bool) in }) }) } } } }
39.403846
156
0.592191
5038b6cbc772fd06cc1028b8b9c949d7327de373
6,304
// Copyright 2022 Pera Wallet, LDA // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // WCTransactionDappMessageView.swift import UIKit import MacaroonUIKit import MacaroonURLImage class WCTransactionDappMessageView: BaseView { private let layout = Layout<LayoutConstants>() weak var delegate: WCTransactionDappMessageViewDelegate? private lazy var dappImageView: URLImageView = { let imageView = URLImageView() imageView.layer.cornerRadius = layout.current.imageSize.width / 2 return imageView }() private lazy var stackView: VStackView = { let stackView = VStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.distribution = .equalSpacing stackView.spacing = layout.current.spacing stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight] stackView.isUserInteractionEnabled = false return stackView }() private lazy var subtitleStackView: HStackView = { let stackView = HStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.distribution = .fill stackView.spacing = layout.current.spacing stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight] stackView.isUserInteractionEnabled = false return stackView }() private lazy var subtitleContainerView = UIView() private lazy var nameLabel: UILabel = { UILabel() .withAlignment(.left) .withLine(.single) .withTextColor(AppColors.Shared.Global.white.uiColor) .withFont(Fonts.DMSans.medium.make(19).uiFont) }() private lazy var messageLabel: UILabel = { UILabel() .withAlignment(.left) .withLine(.single) .withTextColor(AppColors.Shared.Global.gray400.uiColor) .withFont(Fonts.DMSans.regular.make(13).uiFont) }() private lazy var readMoreLabel: UILabel = { UILabel() .withAlignment(.left) .withLine(.single) .withTextColor(AppColors.Shared.Helpers.positive.uiColor) .withFont(Fonts.DMSans.medium.make(13).uiFont) .withText("wallet-connect-transaction-dapp-show-more".localized) }() private lazy var tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTap)) override func configureAppearance() { backgroundColor = .clear layer.cornerRadius = 12.0 } override func prepareLayout() { setupDappImageViewLayout() setupStackViewLayout() } override func linkInteractors() { super.linkInteractors() readMoreLabel.addGestureRecognizer(tapGestureRecognizer) stackView.isUserInteractionEnabled = true subtitleContainerView.isUserInteractionEnabled = true subtitleStackView.isUserInteractionEnabled = true readMoreLabel.isUserInteractionEnabled = true } } extension WCTransactionDappMessageView { private func setupDappImageViewLayout() { dappImageView.build(URLImageViewNoStyleLayoutSheet()) addSubview(dappImageView) dappImageView.snp.makeConstraints { make in make.leading.equalToSuperview() make.centerY.equalToSuperview() make.size.equalTo(layout.current.imageSize) make.top.equalToSuperview().inset(layout.current.defaultInset) make.bottom.equalToSuperview().inset(layout.current.defaultInset) } } private func setupStackViewLayout() { addSubview(stackView) stackView.snp.makeConstraints { make in make.leading.equalTo(dappImageView.snp.trailing).offset(layout.current.nameLabelLeadingInset) make.trailing.equalToSuperview() make.centerY.equalToSuperview() } stackView.addArrangedSubview(nameLabel) stackView.addArrangedSubview(subtitleStackView) subtitleStackView.addArrangedSubview(subtitleContainerView) subtitleContainerView.addSubview(messageLabel) messageLabel.snp.makeConstraints { make in make.leading.equalToSuperview() make.top.bottom.equalToSuperview() } subtitleContainerView.addSubview(readMoreLabel) readMoreLabel.snp.makeConstraints { make in make.leading.equalTo(messageLabel.snp.trailing).offset(layout.current.spacing) make.trailing.lessThanOrEqualToSuperview() make.top.bottom.equalToSuperview() } readMoreLabel.setContentCompressionResistancePriority(.required, for: .horizontal) } @objc private func didTap() { self.delegate?.wcTransactionDappMessageViewDidTapped(self) } } extension WCTransactionDappMessageView { func bind(_ viewModel: WCTransactionDappMessageViewModel) { dappImageView.load(from: viewModel.image) nameLabel.text = viewModel.name messageLabel.text = viewModel.message readMoreLabel.isHidden = viewModel.isReadMoreHidden if viewModel.message.isNilOrEmpty { self.subtitleStackView.hideViewInStack() } else { self.subtitleStackView.showViewInStack() } } } extension WCTransactionDappMessageView { private struct LayoutConstants: AdaptiveLayoutConstants { let defaultInset: CGFloat = 20.0 let nameLabelLeadingInset: CGFloat = 16.0 let spacing: CGFloat = 4.0 let messageLabelVerticalInset: CGFloat = 4.0 let imageSize = CGSize(width: 48.0, height: 48.0) } } protocol WCTransactionDappMessageViewDelegate: AnyObject { func wcTransactionDappMessageViewDidTapped(_ WCTransactionDappMessageView: WCTransactionDappMessageView) }
34.26087
108
0.693211
dd6f0409cfe2c1a28a90e2ce9812e416fa7b982c
2,500
// // LegalityTable.swift // Scryfall // // Created by Alexander on 13.08.2021. // import SwiftUI import ScryfallModel struct LegalityTable: View { let legalities: LegalityList var columns: [GridItem] = [ GridItem(.flexible(maximum: 100)), GridItem(.flexible(minimum: 40), spacing: 2, alignment: .leading), GridItem(.flexible(maximum: 100)), GridItem(.flexible(minimum: 40), spacing: 2, alignment: .leading) ] var body: some View { LazyVGrid( columns: columns, alignment: .center, spacing: 4 ) { ForEach(cells, id: \.id) { cell in switch cell { case let .value(_, legality): Text(legality.title) .font(Style.Fonts.smallFixed) .foregroundColor(Color("BrightText")) .frame(maxWidth: .infinity) .padding(.vertical, 4) .padding(.horizontal, 4) .background(legality.color) .cornerRadius(2) case let .name(name): Text(name).font(Style.Fonts.small) } } } } enum Cell: Identifiable { case value(String, LegalityList.Legality) case name(String) var id: String { switch self { case let .value(name, _): return "\(name)_value" case let .name(name): return name } } } var cells: [Cell] { [ .value("Standard", legalities.standard), .name("Standard"), .value("Brawl", legalities.brawl), .name("Brawl"), .value("Pioneer", legalities.pioneer), .name("Pioneer"), .value("Historic", legalities.historic), .name("Historic"), .value("Modern", legalities.modern), .name("Modern"), .value("Pauper", legalities.pauper), .name("Pauper"), .value("Legacy", legalities.legacy), .name("Legacy"), .value("Penny", legalities.penny), .name("Penny"), .value("Vintage", legalities.vintage), .name("Vintage"), .value("Commander", legalities.commander), .name("Commander"), ] } } struct LegalityTable_Previews: PreviewProvider { static var previews: some View { LegalityTable(legalities: ModelStubs.abominationOfGudul.legalities!) } }
30.864198
76
0.52
90e3c6bb259e0932cf6d278e78007e88ce6bcd0d
1,591
// // Created by Alexander Gorbovets on 11.04.16. // Copyright (c) 2016 robinclough. All rights reserved. // import Foundation import QuartzCore enum TimingFunction { case Linear case EaseIn case EaseOut case EaseInEaseOut case Default var value: String { switch self { case Linear: return kCAMediaTimingFunctionLinear case EaseIn: return kCAMediaTimingFunctionEaseIn case EaseOut: return kCAMediaTimingFunctionEaseOut case EaseInEaseOut: return kCAMediaTimingFunctionEaseInEaseOut case Default: return kCAMediaTimingFunctionDefault } } } extension CABasicAnimation { convenience init(moveLayer layer: CALayer, horizontallyToCurrentPositionByOffset offset: CGFloat, duration: Double, timing: TimingFunction) { self.init(keyPath: "position.x") // position is a position of center of layer. not view.frame.origin self.fromValue = layer.position.x - offset self.toValue = layer.position.x // to value should be equal to layer.position value. otherwise at end of animation it will be returned to original layer.position self.duration = duration self.timingFunction = CAMediaTimingFunction(name: timing.value) } convenience init(fadeLayer layer: CALayer, inWithDuration: Double, timing: TimingFunction) { self.init(keyPath: "opacity") self.fromValue = 0 self.toValue = 1 self.duration = duration self.timingFunction = CAMediaTimingFunction(name: timing.value) } }
33.851064
169
0.693275
87516f027e11ab6358c7725a3f389bedb2220ae0
1,732
import SpriteKit // MARK: - Static public extension SKAction { /// Returns an empty action. static var empty: SKAction { SKAction() } /** Returns an action that removes the node from its parent after specified delay. - parameter delay: The amount of time to wait (in seconds). */ static func removeFromParentAfterDelay( _ delay: TimeInterval ) -> SKAction { .sequence([ .wait(forDuration: delay), .removeFromParent() ]) } } // MARK: - Instance public extension SKAction { /// Returns the receiver with specified timing mode 'easeInEaseOut'. var easeInEaseOut: SKAction { timingMode = .easeInEaseOut return self } /// Returns the receiver with specified timing mode 'easeIn'. var easeIn: SKAction { timingMode = .easeIn return self } /// Returns the receiver with specified timing mode 'easeOut'. var easeOut: SKAction { timingMode = .easeOut return self } /// Returns the sequence consisting of the receiver and its reverse action. var pulse: SKAction { .sequence([self, reversed()]) } /// Returns an endless repetition of the receiver. var infinite: SKAction { .repeatForever(self) } /// Returns an endless repetition of the sequence consisting of the receiver and its reverse action. var infinitePulse: SKAction { .repeatForever(pulse) } /** Creates a rectangle with the given center and dimensions. - parameter duration: The duration of one revolution (in seconds) - parameter isClockwise: The direction of rotation */ static func rotateInfinite( turnover duration: TimeInterval, isClockwise: Bool = false ) -> SKAction { SKAction.rotate( byAngle: 360.radians * (isClockwise ? -1 : 1), duration: duration ).infinite } }
21.382716
101
0.707852
e6a9648aaed6fad6fd4a4ec49d6f216e7df37e5d
1,092
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "ParallaxView", platforms: [.tvOS(.v9)], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "ParallaxView", targets: ["ParallaxView"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "ParallaxView", dependencies: [], path: "Sources" ), .testTarget( name: "ParallaxViewTests", dependencies: ["ParallaxView"]), ] )
34.125
122
0.622711
48d645078b52a41f00c2891fe7bd6b642368beb8
1,328
import Flutter import Foundation import Appodeal internal final class AppodealBanner { internal let adChannel: FlutterMethodChannel internal let adListener: Listener init(registrar: FlutterPluginRegistrar) { adChannel = FlutterMethodChannel(name: "appodeal_flutter/banner", binaryMessenger: registrar.messenger()) adListener = Listener(adChannel: adChannel) } internal final class Listener: NSObject, AppodealBannerDelegate { private let adChannel: FlutterMethodChannel fileprivate init(adChannel: FlutterMethodChannel) { self.adChannel = adChannel } func bannerDidLoadAdIsPrecache(_ precache: Bool) { adChannel.invokeMethod("onBannerLoaded", arguments: ["isPrecache": precache]) } func bannerDidShow() { adChannel.invokeMethod("onBannerShown", arguments: nil) } func bannerDidFailToLoadAd() { adChannel.invokeMethod("onBannerFailedToLoad", arguments: nil) } func bannerDidClick() { adChannel.invokeMethod("onBannerClicked", arguments: nil) } func bannerDidExpired() { adChannel.invokeMethod("onBannerExpired", arguments: nil) } } }
30.181818
113
0.634789
395a38ac6ec6c3298c31019461dfd4b94395578d
8,934
// Copyright (c) 2021 Dmitry Meduho // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, // distribute, sublicense, create a derivative work, and/or sell copies of the // Software in any work that is designed, intended, or marketed for pedagogical or // instructional purposes related to programming, coding, application development, // or information technology. Permission for such use, copying, modification, // merger, publication, distribution, sublicensing, creation of derivative works, // or sale is expressly withheld. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import AppKit // MARK: - Enums, Structs extension TypeView { public typealias Action = (Int) -> Void public struct Style { let headerStyle: StyledLabel.Style let descriptionStyle: StyledLabel.Style let lineStyle: LineView.Style let itemStyle: TypeItemView.Style public init( headerStyle: StyledLabel.Style, descriptionStyle: StyledLabel.Style, lineStyle: LineView.Style, itemStyle: TypeItemView.Style ) { self.headerStyle = headerStyle self.descriptionStyle = descriptionStyle self.lineStyle = lineStyle self.itemStyle = itemStyle } } private enum KeyCode: UInt16 { case down = 125 case up = 126 case enter = 36 } private enum Constants { static let stackViewSpacing: CGFloat = 0 static let headerLabelLeadingOffset: CGFloat = 16 static let headerLabelTopOffset: CGFloat = 16 static let descriptionLabelLeadingOffset: CGFloat = 16 static let descriptionLabelTopOffset: CGFloat = 2 static let lineHeight: CGFloat = 1 static let lineTopOffset: CGFloat = 14 static let stackViewOffset: CGFloat = 10 } } // MARK: - Class public final class TypeView: View { private lazy var stackView: StackView = { let stackView = StackView() stackView.orientation = .vertical stackView.alignment = .left stackView.distribution = .fill stackView.spacing = Constants.stackViewSpacing return stackView }() private lazy var headerLabel = StyledLabel() private lazy var descriptionLabel = StyledLabel() private lazy var lineView = LineView() public override init() { super.init() setup() } // MARK: - Setup private func setup() { setupView() setupConstraints() } private func setupView() { addSubview(stackView) addSubview(headerLabel) addSubview(descriptionLabel) addSubview(lineView) } private func setupConstraints() { stackView.translatesAutoresizingMaskIntoConstraints = false headerLabel.translatesAutoresizingMaskIntoConstraints = false descriptionLabel.translatesAutoresizingMaskIntoConstraints = false lineView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ headerLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Constants.headerLabelLeadingOffset), headerLabel.topAnchor.constraint(equalTo: topAnchor, constant: Constants.headerLabelTopOffset), descriptionLabel.topAnchor.constraint(equalTo: headerLabel.bottomAnchor, constant: Constants.descriptionLabelTopOffset), descriptionLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Constants.descriptionLabelLeadingOffset), lineView.heightAnchor.constraint(equalToConstant: Constants.lineHeight), lineView.leadingAnchor.constraint(equalTo: leadingAnchor), lineView.trailingAnchor.constraint(equalTo: trailingAnchor), lineView.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: Constants.lineTopOffset), stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Constants.stackViewOffset), stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Constants.stackViewOffset), stackView.topAnchor.constraint(equalTo: lineView.bottomAnchor, constant: Constants.stackViewOffset) ]) } // MARK: - Public public var style: Style? { didSet { runWithEffectiveAppearance { stylize() } } } public var items: [TypeItemView.Item] = [] { didSet { clearSubviews() addItems() } } public var action: Action? public var selectedIndex: Int? { didSet { stackView.arrangedSubviews .compactMap { $0 as? TypeItemView } .forEach { $0.isSelected = $0.index == selectedIndex } } } public var headerText: String? { didSet { headerLabel.stringValue = headerText ?? String() } } public var descriptionText: String? { didSet { descriptionLabel.stringValue = descriptionText ?? String() } } // MARK: - Private private func addItems() { for (index, item) in items.enumerated() { let itemView = TypeItemView() itemView.item = item itemView.index = index itemView.style = style?.itemStyle itemView.selectionAction = { [weak self] item in self?.selectedIndex = item.index } itemView.action = { [weak self] item in guard let selectedIndex = item.index else { return } self?.action?(selectedIndex) } stackView.addArrangedSubview(itemView) itemView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ itemView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor), itemView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor) ]) } } public override var acceptsFirstResponder: Bool { return true } public override func keyDown(with event: NSEvent) { let keyCode = KeyCode(rawValue: event.keyCode) switch keyCode { case .down: selectDown() case .up: selectUp() case .enter: guard let selectedIndex = selectedIndex else { return } action?(selectedIndex) default: break } } private func selectUp() { guard let selectedIndex = selectedIndex else { return } let upperbound = 0 let nextIndex = selectedIndex - 1 self.selectedIndex = nextIndex == upperbound - 1 ? items.count - 1 : nextIndex } private func selectDown() { guard let selectedIndex = selectedIndex else { return } let upperbound = items.count let nextIndex = selectedIndex + 1 self.selectedIndex = nextIndex == upperbound ? 0 : nextIndex } private func clearSubviews() { stackView.arrangedSubviews.forEach { stackView.removeArrangedSubview($0) } } private func stylize() { headerLabel.style = style?.headerStyle descriptionLabel.style = style?.descriptionStyle lineView.style = style?.lineStyle stackView.arrangedSubviews .compactMap { $0 as? TypeItemView } .forEach { $0.style = style?.itemStyle } } }
33.713208
132
0.624133
c18e4208ea315c3cdb1f8dfdddb980603376dc43
6,435
/* Copyright 2016 chaoyang805 [email protected] * * 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 let CYSnackbarShouldShowNotification = Notification.Name("show snackbar") let CYSnackbarShouldDismissNotification = Notification.Name("dismiss snackbar") let CYSnackbarUserInfoKey = "targetSnackbar" @objc protocol CYSnackbarDelegate: NSObjectProtocol { @objc optional func snackbarWillAppear(_ snackbar: CYSnackbar) @objc optional func snackbarDidAppear(_ snackbar: CYSnackbar) @objc optional func snackbarWillDisappear(_ snackbar: CYSnackbar) @objc optional func snackbarDidDisappear(_ snackbar: CYSnackbar) } public enum CYSnackbarDuration: TimeInterval { case short = 1.5 case long = 3 } public class CYSnackbar: NSObject { private(set) lazy var view: CYSnackbarView = { let _barView = CYSnackbarView() // 为了Snackbar不被销毁 _barView.snackbar = self return _barView }() private var showing: Bool = false private var dismissHandler: (() -> Void)? var duration: TimeInterval! private weak var delegate: CYSnackbarDelegate? public class func make(text: String, duration: CYSnackbarDuration) -> CYSnackbar { return make(text, duration: duration.rawValue) } private class func make(_ text: String, duration: TimeInterval) -> CYSnackbar { let snackbar = CYSnackbar() snackbar.setSnackbarText(text: text) snackbar.duration = duration snackbar.registerNotification() snackbar.delegate = CYSnackbarManager.default() return snackbar } public func show() { let record = CYSnackbarRecord(duration: duration, identifier: hash) CYSnackbarManager.default().show(record) } private func dispatchDismiss() { let record = CYSnackbarRecord(duration: duration, identifier: hash) CYSnackbarManager.default().dismiss(record) } // MARK: - Notification private func registerNotification() { let manager = CYSnackbarManager.default() NotificationCenter.default.addObserver(self, selector: #selector(CYSnackbar.handleNotification(_:)), name: CYSnackbarShouldShowNotification, object: manager) NotificationCenter.default.addObserver(self, selector: #selector(CYSnackbar.handleNotification(_:)), name: CYSnackbarShouldDismissNotification, object: manager) } private func unregisterNotification() { NotificationCenter.default.removeObserver(self) } @objc private func handleNotification(_ notification: NSNotification) { guard let identifier = notification.userInfo?[CYSnackbarUserInfoKey] as? Int else { NSLog("not found snackbar in notification's userInfo") return } guard identifier == self.hash else { NSLog("not found specified snackbar:\(identifier)") return } switch notification.name { case CYSnackbarShouldShowNotification: handleShowNotification() case CYSnackbarShouldDismissNotification: handleDismissNotification() default: break } } private func handleShowNotification() { self.showView() } private func handleDismissNotification() { self.dismissView() } // MARK: - Configure Snackbar public func setSnackbarText(text: String) { view.messageView.text = text view.messageView.sizeToFit() } public func action(with title: String, action: @escaping ((_ sender: Any) -> Void)) -> CYSnackbar { view.setAction(with: title, block: { action($0) self.dispatchDismiss() }) return self } public func dismissHandler(block: @escaping (() -> Void)) -> CYSnackbar { self.dismissHandler = block return self } // MARK: - Snackbar View show & dismiss private func showView() { guard let window = UIApplication.shared.keyWindow else { return } self.delegate?.snackbarWillAppear?(self) window.addSubview(view) UIView.animate( withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: { [weak self] in guard let `self` = self else { return } self.view.frame = self.view.frame.offsetBy(dx: 0, dy: -snackbarHeight) }, completion: { (done ) in self.delegate?.snackbarDidAppear?(self) self.showing = true }) } private func dismissView() { guard self.showing else { return } self.delegate?.snackbarWillDisappear?(self) UIView.animate( withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: { [weak self] in guard let `self` = self else { return } self.view.frame = self.view.frame.offsetBy(dx: 0, dy: snackbarHeight) }, completion: { (done) in self.showing = false self.view.snackbar = nil self.view.removeFromSuperview() self.dismissHandler?() self.delegate?.snackbarDidDisappear?(self) self.delegate = nil self.unregisterNotification() } ) } }
31.390244
168
0.592385
7a546b288ba3bee22a6a1bbde52666d0473d2c29
2,435
// // SysExEvent.swift // Swimi // // Created by Kainosuke OBATA on 2020/08/03. // import Foundation /// This represent `F0` style SysEx event. There is another `F7` style SysEx event. public struct F0SysExEvent: Parsing, Equatable { /// Data of this SysEx Event. /// /// This data contains `F0` (SysEx start byte) at first element (data[0]). /// Depending on original data, the terminal `F7` may or may not exists. This struct /// does not care about its correctness because there is another SysEx format /// beginning with `F7`. With `F7` style message, SysEx message can be split into /// multiple messages. public var data: [UInt8] { willSet { Self.checkFirstByteIsF0(newValue) } } public init(dataIncludingFirstF0 firstF0Data: [UInt8]) { Self.checkFirstByteIsF0(firstF0Data) self.data = firstF0Data } public init(dataWithoutFirstF0: [UInt8]) { self.data = [0xF0] + dataWithoutFirstF0 } public static func parse(_ smfBytes: ArraySlice<UInt8>) -> ParseResult<F0SysExEvent> { guard smfBytes.prefix(prefix.count) == prefix[...] else { return .failure(.length(0)) } var bytes = smfBytes.dropFirst(prefix.count) switch VInt.parse(bytes) { case .failure(let failure): return .failure(.length(prefix.count + failure.length)) case .success(let success): bytes = bytes.dropFirst(success.length) let dataLength = success.component.value let data = bytes.prefix(dataLength) guard data.count == dataLength else { return .failure(.length(smfBytes.count)) } return .success( ParseSucceeded( length: prefix.count + success.length + data.count, component: F0SysExEvent(dataWithoutFirstF0: Array(data)) ) ) } } public var smfBytes: [UInt8] { let body = data.dropFirst() return Self.prefix + VInt(body.count).smfBytes + body } private static let prefix: [UInt8] = [0xF0] private static func checkFirstByteIsF0(_ bytes: [UInt8]) { if let first = bytes.first { if first != 0xF0 { fatalError("first byte must be F0") } } } }
31.623377
90
0.579877
d50c33fda352da15b109886c3032f4052c9e2109
3,572
// // AppDelegate.swift // Marvel Heroes // // Created by Marc Humet on 10/4/16. // Copyright © 2016 SPM. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate/*, UISplitViewControllerDelegate */{ var window: UIWindow? private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { BuddyBuildSDK.setup() // Override point for customization after application launch. // let splitViewController = self.window!.rootViewController as! UISplitViewController // let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController // navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() // splitViewController.delegate = self UINavigationBar.appearance().titleTextAttributes = [ NSAttributedStringKey.font.rawValue: UIFont(name: "GothamLight", size: 15)! ] return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view // func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { // guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } // guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } // if topAsDetailController.detailItem == nil { // // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. // return true // } // return false // } }
53.313433
285
0.74916
7af0e615322ee5072c6bd3c453a621efe830c1f5
2,856
// // AppDelegate.swift // MRT // // Created by evan3rd on 2015/5/13. // Copyright (c) 2015年 evan3rd. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. DepartureManager.sharedInstance.syncStationData(completionBlock: { () -> Void in DepartureManager.sharedInstance.syncMRTDepartureTime(completionBlock: { () -> Void in println("==========") for var i = 0; i < DepartureManager.sharedInstance.stations.count; ++i { var st = DepartureManager.sharedInstance.stations[i] println("\(st.cname) \(st.code)") for p:Platform in st.redLine { println("\(p.destination) \(p.arrivalTime) \(p.nextArrivalTime)") } for p:Platform in st.orangeLine { println("\(p.destination) \(p.arrivalTime) \(p.nextArrivalTime)") } println("==========") } }, errorBlock: nil) }, errorBlock: nil) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
42.626866
281
0.715686
f970b07b4932a5d9e2917904e6a1cfa6a839f39c
4,634
// // Invoice.swift // tapcrate-api // // Created by Hakon Hanesand on 1/18/17. // // import Node import Foundation public final class Invoice: NodeConvertible { static let type = "invoice" public let id: String public let amount_due: Int public let application_fee: Int? public let attempt_count: Int public let attempted: Bool public let charge: String public let closed: Bool public let currency: Currency public let customer: String public let date: Date public let description: String? public let discount: Discount public let ending_balance: Int? public let forgiven: Bool public let lines: [LineItem] public let livemode: Bool public let metadata: Node public let next_payment_attempt: Date public let paid: Bool public let period_end: Date public let period_start: Date public let receipt_number: String? public let starting_balance: Int? public let statement_descriptor: String? public let subscription: String public let subtotal: Int public let tax: Int? public let tax_percent: Double? public let total: Int public let webhooks_delivered_at: Date public init(node: Node) throws { guard try node.extract("object") == Invoice.type else { throw NodeError.unableToConvert(input: node, expectation: Invoice.type, path: ["object"]) } id = try node.extract("id") amount_due = try node.extract("amount_due") application_fee = try node.extract("application_fee") attempt_count = try node.extract("attempt_count") attempted = try node.extract("attempted") charge = try node.extract("charge") closed = try node.extract("closed") currency = try node.extract("currency") customer = try node.extract("customer") date = try node.extract("date") description = try node.extract("description") discount = try node.extract("discount") ending_balance = try node.extract("ending_balance") forgiven = try node.extract("forgiven") lines = try node.extract("lines") livemode = try node.extract("livemode") metadata = try node.extract("metadata") next_payment_attempt = try node.extract("next_payment_attempt") paid = try node.extract("paid") period_end = try node.extract("period_end") period_start = try node.extract("period_start") receipt_number = try node.extract("receipt_number") starting_balance = try node.extract("starting_balance") statement_descriptor = try node.extract("statement_descriptor") subscription = try node.extract("subscription") subtotal = try node.extract("subtotal") tax = try node.extract("tax") tax_percent = try node.extract("tax_percent") total = try node.extract("total") webhooks_delivered_at = try node.extract("webhooks_delivered_at") } public func makeNode(in context: Context?) throws -> Node { return try Node(node: [ "id" : .string(id), "amount_due" : .number(.int(amount_due)), "attempt_count" : .number(.int(attempt_count)), "attempted" : .bool(attempted), "charge" : .string(charge), "closed" : .bool(closed), "currency" : try currency.makeNode(in: context), "customer" : .string(customer), "date" : try date.makeNode(in: context), "discount" : try discount.makeNode(in: context), "forgiven" : .bool(forgiven), "lines" : try .array(lines.map { try $0.makeNode(in: context) }), "livemode" : .bool(livemode), "metadata" : metadata, "next_payment_attempt" : try next_payment_attempt.makeNode(in: context), "paid" : .bool(paid), "period_end" : try period_end.makeNode(in: context), "period_start" : try period_start.makeNode(in: context), "subscription" : .string(subscription), "subtotal" : .number(.int(subtotal)), "total" : .number(.int(total)), "webhooks_delivered_at" : try webhooks_delivered_at.makeNode(in: context) ] as [String: Node]).add(objects: [ "application_fee" : application_fee, "description" : description, "receipt_number" : receipt_number, "starting_balance" : starting_balance, "statement_descriptor" : statement_descriptor, "tax" : tax, "tax_percent" : tax_percent ]) } }
38.941176
101
0.626241
fee7a25638b58a715711a523652df3ed5617ea78
1,487
// // AppDelegate.swift // QRCodeView Demo // // Created by Darren Ford on 9/11/21. // import Cocoa import QRCode @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application generateQRCodeImage() } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { return true } } extension AppDelegate { func generateQRCodeImage() { let gr = DSFGradient(pins: [ DSFGradient.Pin(CGColor(red: 1, green: 0, blue: 0, alpha: 1), 0), DSFGradient.Pin(CGColor(red: 0, green: 1, blue: 0, alpha: 1), 0.5), DSFGradient.Pin(CGColor(red: 0, green: 0, blue: 1, alpha: 1), 1), ])! let design = QRCode.Design() let style = QRCode.Style() style.data = QRCode.FillStyle.LinearGradient(gr, startPoint: CGPoint(x: 0, y: 0.5), endPoint: CGPoint(x: 1, y: 0.5)) design.style = style let contentShape = QRCode.Shape() contentShape.data = QRCode.DataShape.RoundedRect(inset: 1, cornerRadiusFraction: 0.8) contentShape.eye = QRCode.EyeShape.RoundedRect() design.shape = contentShape let c = QRCode() c.update(message: QRCode.Message.Link(string: "https://www.apple.com.au")!, errorCorrection: .high) let iii = c.nsImage(CGSize(width: 400, height: 400), scale: 3, design: design)! Swift.print(iii) } }
27.537037
118
0.710827
032819fc94ba6eee6b847491e550afdcfc991ec7
8,413
// // UIImageView+Extension.swift // Hugo // // Created by Ali Gutierrez on 3/29/21. // Copyright © 2021 Clever Mobile Apps. All rights reserved. // import Foundation import UIKit let kFontResizingProportion: CGFloat = 0.4 let kColorMinComponent: Int = 30 let kColorMaxComponent: Int = 214 public typealias GradientColors = (top: UIColor, bottom: UIColor) typealias HSVOffset = (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) let kGradientTopOffset: HSVOffset = (hue: -0.025, saturation: 0.05, brightness: 0, alpha: 0) let kGradientBotomOffset: HSVOffset = (hue: 0.025, saturation: -0.05, brightness: 0, alpha: 0) extension UIImageView { public func setImageForName(_ string: String, backgroundColor: UIColor? = nil, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?, gradient: Bool = false) { setImageForName(string, backgroundColor: backgroundColor, circular: circular, textAttributes: textAttributes, gradient: gradient, gradientColors: nil) } public func setImageForName(_ string: String, gradientColors: GradientColors, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?) { setImageForName(string, backgroundColor: nil, circular: circular, textAttributes: textAttributes, gradient: true, gradientColors: gradientColors) } private func setImageForName(_ string: String, backgroundColor: UIColor?, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?, gradient: Bool = false, gradientColors: GradientColors?) { let initials: String = initialsFromString(string: string) let color: UIColor = (backgroundColor != nil) ? backgroundColor! : randomColor(for: string) let gradientColors = gradientColors ?? topAndBottomColors(for: color) let attributes: [NSAttributedString.Key: AnyObject] = (textAttributes != nil) ? textAttributes! : [ NSAttributedString.Key.font: self.fontForFontName(name: nil), NSAttributedString.Key.foregroundColor: UIColor.white ] self.image = imageSnapshot(text: initials, backgroundColor: color, circular: circular, textAttributes: attributes, gradient: gradient, gradientColors: gradientColors) } private func fontForFontName(name: String?) -> UIFont { let fontSize = self.bounds.width * kFontResizingProportion guard let name = name else { return .systemFont(ofSize: fontSize) } guard let customFont = UIFont(name: name, size: fontSize) else { return .systemFont(ofSize: fontSize) } return customFont } private func imageSnapshot(text imageText: String, backgroundColor: UIColor, circular: Bool, textAttributes: [NSAttributedString.Key : AnyObject], gradient: Bool, gradientColors: GradientColors) -> UIImage { let scale: CGFloat = UIScreen.main.scale var size: CGSize = self.bounds.size if (self.contentMode == .scaleToFill || self.contentMode == .scaleAspectFill || self.contentMode == .scaleAspectFit || self.contentMode == .redraw) { size.width = (size.width * scale) / scale size.height = (size.height * scale) / scale } UIGraphicsBeginImageContextWithOptions(size, false, scale) guard let context: CGContext = UIGraphicsGetCurrentContext() else { return UIImage() } if circular { let path: CGPath = CGPath(ellipseIn: self.bounds, transform: nil) context.addPath(path) context.clip() } if gradient { let baseSpace = CGColorSpaceCreateDeviceRGB() let colors = [gradientColors.top.cgColor, gradientColors.bottom.cgColor] if let gradient = CGGradient(colorsSpace: baseSpace, colors: colors as CFArray, locations: nil) { let startPoint = CGPoint(x: self.bounds.midX, y: self.bounds.minY) let endPoint = CGPoint(x: self.bounds.midX, y: self.bounds.maxY) context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0)) } } else { context.setFillColor(backgroundColor.cgColor) context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) } let textSize: CGSize = imageText.size(withAttributes: textAttributes) let bounds: CGRect = self.bounds imageText.draw(in: CGRect(x: bounds.midX - textSize.width / 2, y: bounds.midY - textSize.height / 2, width: textSize.width, height: textSize.height), withAttributes: textAttributes) guard let snapshot: UIImage = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() } UIGraphicsEndImageContext() return snapshot } } private func initialsFromString(string: String) -> String { var nameComponents = string.uppercased().components(separatedBy: CharacterSet.letters.inverted) nameComponents.removeAll(where: {$0.isEmpty}) let firstInitial = nameComponents.first?.first let lastInitial = nameComponents.count > 1 ? nameComponents.last?.first : nil return (firstInitial != nil ? "\(firstInitial!)" : "") + (lastInitial != nil ? "\(lastInitial!)" : "") } private func randomColorComponent() -> Int { let limit = kColorMaxComponent - kColorMinComponent return kColorMinComponent + Int(drand48() * Double(limit)) } private func randomColor(for string: String) -> UIColor { srand48(string.hashValue) let red = CGFloat(randomColorComponent()) / 255.0 let green = CGFloat(randomColorComponent()) / 255.0 let blue = CGFloat(randomColorComponent()) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } private func clampColorComponent(_ value: CGFloat) -> CGFloat { return min(max(value, 0), 1) } private func correctColorComponents(of color: UIColor, withHSVOffset offset: HSVOffset) -> UIColor { var hue = CGFloat(0) var saturation = CGFloat(0) var brightness = CGFloat(0) var alpha = CGFloat(0) if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { hue = clampColorComponent(hue + offset.hue) saturation = clampColorComponent(saturation + offset.saturation) brightness = clampColorComponent(brightness + offset.brightness) alpha = clampColorComponent(alpha + offset.alpha) return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) } return color } private func topAndBottomColors(for color: UIColor, withTopHSVOffset topHSVOffset: HSVOffset = kGradientTopOffset, withBottomHSVOffset bottomHSVOffset: HSVOffset = kGradientBotomOffset) -> GradientColors { let topColor = correctColorComponents(of: color, withHSVOffset: topHSVOffset) let bottomColor = correctColorComponents(of: color, withHSVOffset: bottomHSVOffset) return (top: topColor, bottom: bottomColor) }
42.705584
122
0.579698
2f4f041901ed14e3db0b1992b9114bc3039e8c28
2,694
// // AppDelegate.swift // Mooskine // // Created by Josh Svatek on 2017-05-29. // Copyright © 2017 Udacity. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let dataController = DataController(modelName: "Mooskine") func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. dataController.load() let navigationController = window?.rootViewController as! UINavigationController let notebooksListViewController = navigationController.topViewController as! NotebooksListViewController notebooksListViewController.dataController = dataController return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. saveViewContext() } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. saveViewContext() } func saveViewContext() { try? dataController.viewContext.save() } }
44.9
285
0.74536
6258480c665b9adb964dc26b3f2b89ae3d0445e6
7,900
// // KVLoading.swift // // Created by Vu Van Khac on 2/22/17. // import UIKit public class KVLoading: UIView { class var shared: KVLoading { struct Static { static let shared = KVLoading() } return Static.shared } public private(set) var isShowing: Bool { get { guard let contentView = self.contentView else { return false } if contentView.alpha > 0 { return true } else { return false } } set { self.isShowing = newValue } } lazy var keyView: UIView = { if let view = UIApplication.shared.keyWindow { return view } return UIView() }() var backgroundView: UIView? var contentView: UIView? override init(frame: CGRect) { super.init(frame: UIScreen.main.bounds) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func didChangeStatusBarOrientation(notifitation: Notification) { guard let contentView = self.contentView else { return } contentView.center = keyView.center } public static func show(_ customView: UIView? = nil, animated: Bool = true) { self.shared.show(customView, animated: animated) } func show(_ customView: UIView? = nil, animated: Bool = true) { if isShowing { return } backgroundView = UIView() if let backgroundView = backgroundView { backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundView.frame = keyView.bounds backgroundView.isUserInteractionEnabled = true backgroundView.backgroundColor = .black keyView.addSubview(backgroundView) backgroundView.alpha = 0 UIView.animate(withDuration: 0.3, animations: { backgroundView.alpha = 0.2 }) } NotificationCenter.default.addObserver(self, selector: #selector(self.didChangeStatusBarOrientation(notifitation:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil) if let customView = customView { customView.translatesAutoresizingMaskIntoConstraints = false contentView = customView } else { contentView = KVLoadingView() } guard let contentView = self.contentView else { return } contentView.alpha = 0 contentView.center = keyView.center keyView.addSubview(contentView) if let customView = customView { let horizontalConstraint = NSLayoutConstraint(item: customView, attribute: .centerX, relatedBy: .equal, toItem: keyView, attribute: .centerX, multiplier: 1, constant: 0) let verticalConstraint = NSLayoutConstraint(item: customView, attribute: .centerY, relatedBy: .equal, toItem: keyView, attribute: .centerY, multiplier: 1, constant: 0) keyView.addConstraint(horizontalConstraint) keyView.addConstraint(verticalConstraint) } if animated { UIView.animate(withDuration: 0.3, animations: { contentView.alpha = 1 }) } else { contentView.alpha = 1 } } public static func showInView(view: UIView, customView: UIView? = nil, animated: Bool = true) { self.shared.showInView(view: view, customView, animated: animated) } func showInView(view: UIView, _ customView: UIView? = nil, animated: Bool = true) { if isShowing { return } backgroundView = UIView() if let backgroundView = backgroundView { backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight] backgroundView.frame = view.bounds backgroundView.isUserInteractionEnabled = true backgroundView.backgroundColor = .black view.addSubview(backgroundView) backgroundView.alpha = 0 UIView.animate(withDuration: 0.3, animations: { backgroundView.alpha = 0.2 }) } NotificationCenter.default.addObserver(self, selector: #selector(self.didChangeStatusBarOrientation(notifitation:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil) if let customView = customView { customView.translatesAutoresizingMaskIntoConstraints = false contentView = customView } else { contentView = KVLoadingView() } guard let contentView = self.contentView else { return } contentView.alpha = 0 contentView.center = view.center view.addSubview(contentView) if let customView = customView { let horizontalConstraint = NSLayoutConstraint(item: customView, attribute: .centerX, relatedBy: .equal, toItem: keyView, attribute: .centerX, multiplier: 1, constant: 0) let verticalConstraint = NSLayoutConstraint(item: customView, attribute: .centerY, relatedBy: .equal, toItem: keyView, attribute: .centerY, multiplier: 1, constant: 0) keyView.addConstraint(horizontalConstraint) keyView.addConstraint(verticalConstraint) } if animated { UIView.animate(withDuration: 0.3, animations: { contentView.alpha = 1 }) } else { contentView.alpha = 1 } } public static func hide(animated: Bool = true) { self.shared.hide(animated: animated) } func hide(animated: Bool = true) { if !isShowing { return } if animated { UIView.animate(withDuration: 0.3, animations: { self.backgroundView?.alpha = 0 self.contentView?.alpha = 0 }, completion: { _ in self.backgroundView?.removeFromSuperview() self.contentView?.removeFromSuperview() self.backgroundView = nil self.contentView = nil NotificationCenter.default.removeObserver(self) }) } else { backgroundView?.removeFromSuperview() contentView?.removeFromSuperview() backgroundView = nil contentView = nil NotificationCenter.default.removeObserver(self) } } } class KVLoadingView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.contentView()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func contentView() -> UIView { let contentView: UIView = UIView() contentView.frame.size.width = 77 contentView.frame.size.height = 77 contentView.center = self.center contentView.backgroundColor = UIColor.black.withAlphaComponent(0.7) contentView.layer.cornerRadius = 5 let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView() activityIndicator.frame.size.width = 37 activityIndicator.frame.size.height = 37 activityIndicator.center = CGPoint(x: contentView.frame.width / 2, y: contentView.frame.height / 2) activityIndicator.activityIndicatorViewStyle = .whiteLarge activityIndicator.startAnimating() contentView.addSubview(activityIndicator) return contentView } }
33.760684
207
0.593418
160ec00bd2b09f80a9476d07307281d2ed054d8f
900
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "BLECombineKit", platforms: [ .macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6) ], products: [ .library(name: "BLECombineKit", targets: ["BLECombineKit"]) ], dependencies: [], targets: [ .target( name: "BLECombineKit", dependencies: [], path: ".", exclude: [ "Source/BLECombineKit.h", "Source/Info.plist", "BLECombineExplorer", "Products", "Frameworks", "Tests" ], sources: [ "Source" ] ) ] )
26.470588
96
0.447778
18ae51480c16def265aa14f21dcaf1bc175be71e
5,824
import XCTest @testable import Earnings_Meter class MeterReaderTests: XCTestCase { func testMeterReading_weekday_beforeWork() throws { // Given var environment = AppEnvironment.unitTest environment.date = { Date.weekday_0800_London } let nineToFiveMeter = MeterSettings.fake(ofType: .day_worker_0900_to_1700) // When let meterReader = MeterReader(environment: environment, meterSettings: nineToFiveMeter) meterReader.inputs.start.send() // Then XCTAssertEqual(0, meterReader.currentReading.amountEarned) XCTAssertEqual(0, meterReader.currentReading.progress) XCTAssertEqual(.free, meterReader.currentReading.status) } func testMeterReading_weekday_atWork() throws { // Given var environment = AppEnvironment.unitTest environment.date = { Date.weekday_1300_London } let nineToFiveMeter = MeterSettings.fake(ofType: .day_worker_0900_to_1700) // When let meterReader = MeterReader(environment: environment, meterSettings: nineToFiveMeter) meterReader.inputs.start.send() // Then XCTAssertEqual(200, meterReader.currentReading.amountEarned) XCTAssertEqual(0.5, meterReader.currentReading.progress) XCTAssertEqual(.atWork, meterReader.currentReading.status) } func testMeterReading_weekday_afterWork() throws { // Given var environment = AppEnvironment.unitTest environment.date = { Date.weekday_1900_London } let nineToFiveMeter = MeterSettings.fake(ofType: .day_worker_0900_to_1700) // When let meterReader = MeterReader(environment: environment, meterSettings: nineToFiveMeter) meterReader.inputs.start.send() // Then XCTAssertEqual(400, meterReader.currentReading.amountEarned) XCTAssertEqual(1, meterReader.currentReading.progress) XCTAssertEqual(.free, meterReader.currentReading.status) } func testMeterReading_atWeekend_forWeekendWorker_showsReadingValue() throws { // Given var environment = AppEnvironment.unitTest environment.date = { Date.weekend_1300_London } let nineToFiveMeter = MeterSettings.fake(ofType: .day_worker_0900_to_1700, rate: .init(amount: 400, type: .daily), runAtWeekends: true) // When let meterReader = MeterReader(environment: environment, meterSettings: nineToFiveMeter) meterReader.inputs.start.send() // Then XCTAssertEqual(200, meterReader.currentReading.amountEarned) XCTAssertEqual(0.5, meterReader.currentReading.progress) XCTAssertEqual(.atWork, meterReader.currentReading.status) } func testMeterReading_atWeekend_forNonWeekendWorker_showsZeroReading() throws { // Given var environment = AppEnvironment.unitTest environment.date = { Date.weekend_1300_London } let nineToFiveMeter = MeterSettings.fake(ofType: .day_worker_0900_to_1700, runAtWeekends: false) // When let meterReader = MeterReader(environment: environment, meterSettings: nineToFiveMeter) meterReader.inputs.start.send() // Then XCTAssertEqual(0, meterReader.currentReading.amountEarned) XCTAssertEqual(0, meterReader.currentReading.progress) XCTAssertEqual(.free, meterReader.currentReading.status) } func testMeterReading_overnightWorker_beforeWork() throws { // Given var environment = AppEnvironment.unitTest environment.date = { Date.weekday_1900_London } let overnightMeter = MeterSettings.fake(ofType: .overnight_worker_2200_to_0600, runAtWeekends: false) // When let meterReader = MeterReader(environment: environment, meterSettings: overnightMeter) meterReader.inputs.start.send() // Then XCTAssertEqual(0, meterReader.currentReading.amountEarned) XCTAssertEqual(0, meterReader.currentReading.progress) XCTAssertEqual(.free, meterReader.currentReading.status) } func testMeterReading_overnightWorker_atWork() throws { // Given var environment = AppEnvironment.unitTest environment.date = { Date.weekday_0200_London } let overnightMeter = MeterSettings.fake(ofType: .overnight_worker_2200_to_0600, runAtWeekends: false) // When let meterReader = MeterReader(environment: environment, meterSettings: overnightMeter) meterReader.inputs.start.send() // Then XCTAssertEqual(200, meterReader.currentReading.amountEarned) XCTAssertEqual(0.5, meterReader.currentReading.progress) XCTAssertEqual(.atWork, meterReader.currentReading.status) } func testMeterReading_overnightWorker_afterWork() throws { // Given var environment = AppEnvironment.unitTest environment.date = { Date.weekday_0800_London } let overnightMeter = MeterSettings.fake(ofType: .overnight_worker_2200_to_0600, runAtWeekends: false) // When let meterReader = MeterReader(environment: environment, meterSettings: overnightMeter) meterReader.inputs.start.send() // Then XCTAssertEqual(400, meterReader.currentReading.amountEarned) XCTAssertEqual(1, meterReader.currentReading.progress) XCTAssertEqual(.free, meterReader.currentReading.status) } }
36.4
95
0.661573
8fbee479d3f91e23b356c6a90f12f37c14231002
808
// // MagiCrashModel.swift // MagiCrash // // Created by anran on 2019/3/11. // Copyright © 2019 anran. All rights reserved. // import Foundation // MARK: - CrashModelType public enum MagiCrashModelType: Int { case signal = 1 case exception = 2 } // MARK: - CrashModel open class MagiCrashModel: NSObject { open var type: MagiCrashModelType! open var name: String! open var reason: String! open var appinfo: String! open var callStack: String! init(type: MagiCrashModelType, name: String, reason: String, appinfo: String, callStack: String) { super.init() self.type = type self.name = name self.reason = reason self.appinfo = appinfo self.callStack = callStack } }
19.707317
48
0.610149
23ba15b85236457e9d7a83883f14a53c47996f04
19,156
// Copyright 2018-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // A copy of the License is located at // // http://www.apache.org/licenses/LICENSE-2.0 // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. // // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment // swiftlint:disable type_body_length function_body_length generic_type_name cyclomatic_complexity // -- Generated Code; do not edit -- // // ECROperationsClientOutput.swift // ECRClient // import Foundation import SmokeHTTPClient import ECRModel /** Type to handle the output from the BatchCheckLayerAvailability operation in a HTTP client. */ extension BatchCheckLayerAvailabilityResponse: HTTPResponseOutputProtocol { public typealias BodyType = BatchCheckLayerAvailabilityResponse public typealias HeadersType = BatchCheckLayerAvailabilityResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> BatchCheckLayerAvailabilityResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the BatchDeleteImage operation in a HTTP client. */ extension BatchDeleteImageResponse: HTTPResponseOutputProtocol { public typealias BodyType = BatchDeleteImageResponse public typealias HeadersType = BatchDeleteImageResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> BatchDeleteImageResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the BatchGetImage operation in a HTTP client. */ extension BatchGetImageResponse: HTTPResponseOutputProtocol { public typealias BodyType = BatchGetImageResponse public typealias HeadersType = BatchGetImageResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> BatchGetImageResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the CompleteLayerUpload operation in a HTTP client. */ extension CompleteLayerUploadResponse: HTTPResponseOutputProtocol { public typealias BodyType = CompleteLayerUploadResponse public typealias HeadersType = CompleteLayerUploadResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> CompleteLayerUploadResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the CreateRepository operation in a HTTP client. */ extension CreateRepositoryResponse: HTTPResponseOutputProtocol { public typealias BodyType = CreateRepositoryResponse public typealias HeadersType = CreateRepositoryResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> CreateRepositoryResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the DeleteLifecyclePolicy operation in a HTTP client. */ extension DeleteLifecyclePolicyResponse: HTTPResponseOutputProtocol { public typealias BodyType = DeleteLifecyclePolicyResponse public typealias HeadersType = DeleteLifecyclePolicyResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> DeleteLifecyclePolicyResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the DeleteRegistryPolicy operation in a HTTP client. */ extension DeleteRegistryPolicyResponse: HTTPResponseOutputProtocol { public typealias BodyType = DeleteRegistryPolicyResponse public typealias HeadersType = DeleteRegistryPolicyResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> DeleteRegistryPolicyResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the DeleteRepository operation in a HTTP client. */ extension DeleteRepositoryResponse: HTTPResponseOutputProtocol { public typealias BodyType = DeleteRepositoryResponse public typealias HeadersType = DeleteRepositoryResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> DeleteRepositoryResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the DeleteRepositoryPolicy operation in a HTTP client. */ extension DeleteRepositoryPolicyResponse: HTTPResponseOutputProtocol { public typealias BodyType = DeleteRepositoryPolicyResponse public typealias HeadersType = DeleteRepositoryPolicyResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> DeleteRepositoryPolicyResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the DescribeImageScanFindings operation in a HTTP client. */ extension DescribeImageScanFindingsResponse: HTTPResponseOutputProtocol { public typealias BodyType = DescribeImageScanFindingsResponse public typealias HeadersType = DescribeImageScanFindingsResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> DescribeImageScanFindingsResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the DescribeImages operation in a HTTP client. */ extension DescribeImagesResponse: HTTPResponseOutputProtocol { public typealias BodyType = DescribeImagesResponse public typealias HeadersType = DescribeImagesResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> DescribeImagesResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the DescribeRegistry operation in a HTTP client. */ extension DescribeRegistryResponse: HTTPResponseOutputProtocol { public typealias BodyType = DescribeRegistryResponse public typealias HeadersType = DescribeRegistryResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> DescribeRegistryResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the DescribeRepositories operation in a HTTP client. */ extension DescribeRepositoriesResponse: HTTPResponseOutputProtocol { public typealias BodyType = DescribeRepositoriesResponse public typealias HeadersType = DescribeRepositoriesResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> DescribeRepositoriesResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the GetAuthorizationToken operation in a HTTP client. */ extension GetAuthorizationTokenResponse: HTTPResponseOutputProtocol { public typealias BodyType = GetAuthorizationTokenResponse public typealias HeadersType = GetAuthorizationTokenResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> GetAuthorizationTokenResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the GetDownloadUrlForLayer operation in a HTTP client. */ extension GetDownloadUrlForLayerResponse: HTTPResponseOutputProtocol { public typealias BodyType = GetDownloadUrlForLayerResponse public typealias HeadersType = GetDownloadUrlForLayerResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> GetDownloadUrlForLayerResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the GetLifecyclePolicy operation in a HTTP client. */ extension GetLifecyclePolicyResponse: HTTPResponseOutputProtocol { public typealias BodyType = GetLifecyclePolicyResponse public typealias HeadersType = GetLifecyclePolicyResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> GetLifecyclePolicyResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the GetLifecyclePolicyPreview operation in a HTTP client. */ extension GetLifecyclePolicyPreviewResponse: HTTPResponseOutputProtocol { public typealias BodyType = GetLifecyclePolicyPreviewResponse public typealias HeadersType = GetLifecyclePolicyPreviewResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> GetLifecyclePolicyPreviewResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the GetRegistryPolicy operation in a HTTP client. */ extension GetRegistryPolicyResponse: HTTPResponseOutputProtocol { public typealias BodyType = GetRegistryPolicyResponse public typealias HeadersType = GetRegistryPolicyResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> GetRegistryPolicyResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the GetRepositoryPolicy operation in a HTTP client. */ extension GetRepositoryPolicyResponse: HTTPResponseOutputProtocol { public typealias BodyType = GetRepositoryPolicyResponse public typealias HeadersType = GetRepositoryPolicyResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> GetRepositoryPolicyResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the InitiateLayerUpload operation in a HTTP client. */ extension InitiateLayerUploadResponse: HTTPResponseOutputProtocol { public typealias BodyType = InitiateLayerUploadResponse public typealias HeadersType = InitiateLayerUploadResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> InitiateLayerUploadResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the ListImages operation in a HTTP client. */ extension ListImagesResponse: HTTPResponseOutputProtocol { public typealias BodyType = ListImagesResponse public typealias HeadersType = ListImagesResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> ListImagesResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the ListTagsForResource operation in a HTTP client. */ extension ListTagsForResourceResponse: HTTPResponseOutputProtocol { public typealias BodyType = ListTagsForResourceResponse public typealias HeadersType = ListTagsForResourceResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> ListTagsForResourceResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the PutImage operation in a HTTP client. */ extension PutImageResponse: HTTPResponseOutputProtocol { public typealias BodyType = PutImageResponse public typealias HeadersType = PutImageResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> PutImageResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the PutImageScanningConfiguration operation in a HTTP client. */ extension PutImageScanningConfigurationResponse: HTTPResponseOutputProtocol { public typealias BodyType = PutImageScanningConfigurationResponse public typealias HeadersType = PutImageScanningConfigurationResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> PutImageScanningConfigurationResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the PutImageTagMutability operation in a HTTP client. */ extension PutImageTagMutabilityResponse: HTTPResponseOutputProtocol { public typealias BodyType = PutImageTagMutabilityResponse public typealias HeadersType = PutImageTagMutabilityResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> PutImageTagMutabilityResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the PutLifecyclePolicy operation in a HTTP client. */ extension PutLifecyclePolicyResponse: HTTPResponseOutputProtocol { public typealias BodyType = PutLifecyclePolicyResponse public typealias HeadersType = PutLifecyclePolicyResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> PutLifecyclePolicyResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the PutRegistryPolicy operation in a HTTP client. */ extension PutRegistryPolicyResponse: HTTPResponseOutputProtocol { public typealias BodyType = PutRegistryPolicyResponse public typealias HeadersType = PutRegistryPolicyResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> PutRegistryPolicyResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the PutReplicationConfiguration operation in a HTTP client. */ extension PutReplicationConfigurationResponse: HTTPResponseOutputProtocol { public typealias BodyType = PutReplicationConfigurationResponse public typealias HeadersType = PutReplicationConfigurationResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> PutReplicationConfigurationResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the SetRepositoryPolicy operation in a HTTP client. */ extension SetRepositoryPolicyResponse: HTTPResponseOutputProtocol { public typealias BodyType = SetRepositoryPolicyResponse public typealias HeadersType = SetRepositoryPolicyResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> SetRepositoryPolicyResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the StartImageScan operation in a HTTP client. */ extension StartImageScanResponse: HTTPResponseOutputProtocol { public typealias BodyType = StartImageScanResponse public typealias HeadersType = StartImageScanResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> StartImageScanResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the StartLifecyclePolicyPreview operation in a HTTP client. */ extension StartLifecyclePolicyPreviewResponse: HTTPResponseOutputProtocol { public typealias BodyType = StartLifecyclePolicyPreviewResponse public typealias HeadersType = StartLifecyclePolicyPreviewResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> StartLifecyclePolicyPreviewResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the TagResource operation in a HTTP client. */ extension TagResourceResponse: HTTPResponseOutputProtocol { public typealias BodyType = TagResourceResponse public typealias HeadersType = TagResourceResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> TagResourceResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the UntagResource operation in a HTTP client. */ extension UntagResourceResponse: HTTPResponseOutputProtocol { public typealias BodyType = UntagResourceResponse public typealias HeadersType = UntagResourceResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> UntagResourceResponse { return try bodyDecodableProvider() } } /** Type to handle the output from the UploadLayerPart operation in a HTTP client. */ extension UploadLayerPartResponse: HTTPResponseOutputProtocol { public typealias BodyType = UploadLayerPartResponse public typealias HeadersType = UploadLayerPartResponse public static func compose(bodyDecodableProvider: () throws -> BodyType, headersDecodableProvider: () throws -> HeadersType) throws -> UploadLayerPartResponse { return try bodyDecodableProvider() } }
40.931624
132
0.740081
72f971dbddfb9e747318ad3c2a06e7a56cb9edac
1,454
// // Icinga2URLProvider.swift // NagBar // // Created by Volen Davidov on 02.07.16. // Copyright © 2016 Volen Davidov. All rights reserved. // import Foundation class Icinga2URLProvider : MonitoringProcessorBase, URLProvider { func create() -> Array<MonitoringURL> { var urls: Array<MonitoringURL> = [] urls.append(MonitoringURL.init(urlType: MonitoringURLType.hosts, priority: 1, url: self.monitoringInstance!.url + "/objects/hosts?attrs=name&attrs=address&attrs=last_state_change&attrs=check_attempt&attrs=last_check_result&attrs=state&attrs=acknowledgement&attrs=downtime_depth&filter=" + Icinga2Settings().getHostStatusTypes() + Icinga2Settings().getHostProperties())) urls.append(MonitoringURL.init(urlType: MonitoringURLType.services, priority: 2, url: self.monitoringInstance!.url + "/objects/services?attrs=name&attrs=last_state_change&attrs=check_attempt&attrs=max_check_attempts&attrs=last_check_result&attrs=state&attrs=host_name&attrs=acknowledgement&attrs=downtime_depth&filter=" + Icinga2Settings().getServiceStatusTypes() + Icinga2Settings().getServiceProperties())) if Settings().boolForKey("skipServicesOfHostsWithScD") { urls.append(MonitoringURL.init(urlType: MonitoringURLType.hostScheduledDowntime, priority: 3, url: self.monitoringInstance!.url + "/objects/hosts?attrs=name&filter=host.last_in_downtime==true")) } return urls } }
58.16
416
0.753095
4a170902606b9851aa498de77c15aa7018ee43c7
1,916
// // AppDelegate.swift // architectureTeamA // // Created by basalaev on 10.07.2018. // Copyright © 2018 Heads and Hands. All rights reserved. // import UIKit import HHModule #if HHNetwork || HHPaginationDemo import HHNetwork #endif @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { typealias LaunchOptions = [UIApplication.LaunchOptionsKey: Any] var window: UIWindow? = UIWindow() var authBufferedController: UIViewController? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: LaunchOptions? ) -> Bool { launchOn(window: window) return true } private func launchOn(window: UIWindow?) { ModulesUserStory.main.displayOn(window: window, animated: false) } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } } #if HHNetwork || HHPaginationDemo extension AppDelegate: ARCHAuthObserverMoyaPluginDelegate { func didExpiredAuthToken() { print("[AppDelegate] >> didExpiredAuthToken") authBufferedController = window?.rootViewController // Делаем переход на экран авторизации } } extension AppDelegate: ARCHSignMoyaPluginDelegate { var signHeaderFields: [String: String] { if let token = Dependency.shared.userStorage.token?.value { return ["X-Auth-Token": token] } else { return [:] } } } extension AppDelegate: ARCHUserStorageDelegate { func didUpdateUser(from: ARCHUser?, to: ARCHUser?) { // TODO: Обновляем стек } } #endif
23.365854
72
0.695198
1116c2fbf911b02116fb666b240a1bbd5164f892
584
// // Runtime.swift // // // Created by Yehor Popovych on 1/11/21. // import Foundation import ScaleCodec import SubstratePrimitives public protocol Runtime: System, ModuleBase, DynamicTypeId { var supportedSpecVersions: Range<UInt32> { get } var modules: [ModuleBase] { get } } extension Runtime { public static var NAME: String { Self.id } public func registerEventsCallsAndTypes<R: TypeRegistryProtocol>(in registry: R) throws { for module in modules { try module.registerEventsCallsAndTypes(in: registry) } } }
21.62963
93
0.67637
eb3c951944b0c690f1d11bb8a716506468c53da3
2,302
import Quick import Nimble import CoreData import SwinjectStoryboard @testable import WeightTracker class DataModelSpec: QuickSpec { override func spec() { describe("Core Data Model") { let container = SwinjectStoryboard.defaultContainer var moc: NSManagedObjectContext! beforeEach { moc = container.resolve(NSManagedObjectContext.self) } afterEach { moc.rollback() } context("Entities") { it("should have weight entry") { let names = moc.persistentStoreCoordinator?.managedObjectModel.entitiesByName.keys.map {$0} expect(names).to(contain(["WeightEntry"])) } } context("WeightEntry") { var entry: WeightEntry! beforeEach { entry = WeightEntry(context: moc) } context("email") { it("should allow valid weight") { entry.weight = 139.0 entry.date = Date() try! moc.save() expect(entry.weight) == 139.0 expect(moc.hasChanges) == false } it("should raise validation errors when there are missing fields") { let expected = CocoaError.error(.validationMissingMandatoryProperty) as NSError entry.weight = 130.0 expect { try entry.managedObjectContext?.save() }.to(throwError { (error: NSError) in expect(error.domain) == expected.domain expect(error.code) == expected.code }) } } context("fetchRequest") { it("should load all entries") { let request: NSFetchRequest<WeightEntry> = WeightEntry.fetchRequest() let entries = try! moc.fetch(request) expect(entries.count) >= 1 } } } } } }
34.878788
111
0.453953
5b309561592b8106f002164b8f3f2f01043769cd
2,180
/* The MIT License * * Copyright © 2020 NBCO YooMoney LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit // MARK: - Styles extension UITextView { enum Styles { // MARK: - Main styles /// Linked style /// /// Text: secondary color. static let linked = InternalStyle(name: "linked") { (textView: UITextView) in textView.setStyles(UITextView.ColorStyle.secondary) textView.isEditable = false textView.isScrollEnabled = false textView.textContainerInset = .zero textView.textContainer.lineFragmentPadding = 0 textView.linkTextAttributes = [ NSAttributedString.Key.foregroundColor: textView.tintColor ?? .blueRibbon, ] } } // MARK: - Dynamic Fonts enum ColorStyle { static let secondary = InternalStyle(name: "textview.color.doveGray") { (textView: UITextView) in if #available(iOS 13.0, *) { textView.textColor = .secondaryLabel } else { textView.textColor = .doveGray } } } }
35.737705
105
0.668807
e55656e6105f2e7c4129ee0e82f2cf52b0d53d1e
1,479
// // ErrorView.swift // NationStatesClient // // Created by Bart Kneepkens on 06/12/2020. // import SwiftUI struct ErrorView: View { let error: APIError var onPress: (() -> Void)? private var text: String { switch error { case .notConnected: return "There appears to be no internet connection. Are you connected?" case .unauthorized: return "There appears to be an authentication problem. Tap here to sign in." case .rateExceeded: fallthrough case .timedOut: return "There appear to be some connection issues. Retrying.." case .nationNotFound: return "Nation not found" #if DEBUG case .conflict: return "conflict" case .notFound: return "notFound" case .unknown(let errorCode): return "unknown error with response code: \(errorCode)" #endif default: return "Unknown error" } } var body: some View { Button(action: { self.onPress?() }, label: { HStack { Image(systemName: "exclamationmark.triangle") Text(text) } }).buttonStyle(PlainButtonStyle()) } } extension ErrorView { public mutating func onPress(onPress: @escaping () -> Void) { self.onPress = onPress } } struct ErrorView_Previews: PreviewProvider { static var previews: some View { ErrorView(error: .unauthorized) } }
27.388889
104
0.59432
64a8c6c0cdfa7121ee7c6d65f7c0c2ac0a83cbba
1,591
// // ViewController.swift // FaveButtonDemo // // Created by Jansel Valentin on 6/12/16. // Copyright © 2016 Jansel Valentin. All rights reserved. // import UIKit import FaveButton func color(_ rgbColor: Int) -> UIColor { return UIColor( red: CGFloat((rgbColor & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbColor & 0x00FF00) >> 8 ) / 255.0, blue: CGFloat((rgbColor & 0x0000FF) >> 0 ) / 255.0, alpha: CGFloat(1.0) ) } class ViewController: UIViewController, FaveButtonDelegate { @IBOutlet var heartButton: FaveButton? @IBOutlet var loveButton : FaveButton? override func viewDidLoad() { super.viewDidLoad() self.heartButton?.setSelected(selected: true, animated: false) self.loveButton?.setSelected(selected: true, animated: false) self.loveButton?.setSelected(selected: false, animated: false) } let colors = [ DotColors(first: color(0x7DC2F4), second: color(0xE2264D)), DotColors(first: color(0xF8CC61), second: color(0x9BDFBA)), DotColors(first: color(0xAF90F4), second: color(0x90D1F9)), DotColors(first: color(0xE9A966), second: color(0xF8C852)), DotColors(first: color(0xF68FA7), second: color(0xF6A2B8)) ] func faveButton(_ faveButton: FaveButton, didSelected selected: Bool) { } func faveButtonDotColors(_ faveButton: FaveButton) -> [DotColors]? { if (faveButton === heartButton || faveButton === loveButton) { return colors } return nil } }
30.596154
75
0.632935
c14616013fcc60b312acf5465c7c55c826040fa7
1,612
// // IssueLabeledSectionController.swift // Freetime // // Created by Ryan Nystrom on 6/6/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit final class IssueLabeledSectionController: ListGenericSectionController<IssueLabeledModel>, MarkdownStyledTextViewDelegate { private let issueModel: IssueDetailsModel private weak var tapDelegate: IssueLabelTapSectionControllerDelegate? init(issueModel: IssueDetailsModel, tapDelegate: IssueLabelTapSectionControllerDelegate) { self.issueModel = issueModel self.tapDelegate = tapDelegate super.init() } override func sizeForItem(at index: Int) -> CGSize { return collectionContext.cellSize( with: object?.string.viewSize(in: collectionContext.safeContentWidth()).height ?? 0 ) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: IssueLabeledCell.self, for: self, at: index) as? IssueLabeledCell, let object = self.object else { fatalError("Missing collection context, cell incorrect type, or object missing") } cell.configure(object) cell.delegate = self return cell } func didTap(cell: MarkdownStyledTextView, attribute: DetectedMarkdownAttribute) { if case .label(let label) = attribute { tapDelegate?.didTapIssueLabel(owner: label.owner, repo: label.repo, label: label.label) } else { viewController?.handle(attribute: attribute) } } }
34.297872
134
0.699752
fbc2a61507036aff45fa04d347040e125c763db0
2,214
// // TableViewCellStyle.swift // BasicTableView // // Created by 이봉원 on 10/04/2019. // Copyright © 2019 giftbot. All rights reserved. // import UIKit final class TableViewCellStyle: UIViewController { /*************************************************** 셀 스타일 4가지 (default, subtitle, value1, value2) ***************************************************/ override var description: String { return "TableView - CellStyle" } override func viewDidLoad() { super.viewDidLoad() let tableView = UITableView(frame: view.frame) tableView.rowHeight = 70 tableView.dataSource = self view.addSubview(tableView) } } // MARK: - UITableViewDataSource extension TableViewCellStyle: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // -------------------------- 재사용부분 let cell: UITableViewCell if let defaultCell = tableView.dequeueReusableCell(withIdentifier: "Default"){ cell = defaultCell }else if let subtitleCell = tableView.dequeueReusableCell(withIdentifier: "Subtitle") { cell = subtitleCell }else if let value1Cell = tableView.dequeueReusableCell(withIdentifier: "Value1") { cell = value1Cell }else if let value2Cell = tableView.dequeueReusableCell(withIdentifier: "Value2") { cell = value2Cell } // -------------------------- 없는 상태면 새로 만드는 부분. else if indexPath.row % 4 == 0 { cell = UITableViewCell(style: .default, reuseIdentifier: "Default") } else if indexPath.row % 4 == 1 { cell = UITableViewCell(style: .value1, reuseIdentifier: "Value1") } else if indexPath.row % 4 == 2 { cell = UITableViewCell(style: .value2, reuseIdentifier: "Value2") } else { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Subtitle") } // 공통 속성 세팅 cell.textLabel?.text = "\(indexPath.row * 1000)" cell.detailTextLabel?.text = "Test" cell.imageView?.image = UIImage(named: "bear") cell.accessoryType = .detailButton return cell } }
30.75
98
0.62692
72feda8551927bb4c05bea275d17531290330605
1,185
// // UIButton+Extension.swift // swift-test // // Created by cleven on 2016/10/15. // Copyright © 2016年 itcast. All rights reserved. // import UIKit extension UIButton { /// UIButton /// /// - parameter setBackgroundImage: backgroundImage 默认为nil /// - parameter title: 文字 /// - parameter titleColor: 文字颜色 /// - parameter fontSize: 字体大小 /// - parameter setImage: image /// /// - returns: UIButton convenience init(setBackgroundImage:String? = nil,title:String?,titleColor:UIColor?,fontSize:CGFloat? = 17,setImage:String? = nil){ self.init() if let setBackgroundImage = setBackgroundImage{ self.setBackgroundImage(UIImage(named:setBackgroundImage), for: .normal) } if let setImage = setImage{ self.setImage(UIImage(named:setImage), for: .normal) } self.setTitle(title, for: .normal) self.setTitleColor(titleColor, for: .normal) self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize!) sizeToFit() } }
26.333333
135
0.564557
03dfa55b3ccabeecac540bcd5e0854456c8e7c0a
599
// Created by Isaac Halvorson on 12/12/18 import UIKit enum ThemeFont: String, CaseIterable { case hack = "Hack" case iAWriterDuospace = "iA Writer Duospace" case lcd = "LCD" } extension ThemeFont { /// The fully specified name of the font var fontName: String { switch self { case .hack: return "Hack-Regular" case .iAWriterDuospace: return "iAWriterDuospace-Regular" case .lcd: return "LCD14" } } var uiFont: UIFont { return UIFont(name: fontName, size: UIFont.systemFontSize) ?? UIFont.monospacedDigitSystemFont(ofSize: UIFont.systemFontSize, weight: .regular) } }
21.392857
84
0.719533
ab3aa3757acc14544fa343a1d91927ddd33d6600
1,472
// // MoveRightState.swift // LiquidMetal2D-Demo // // Created by Matt Casanova on 3/22/20. // Copyright © 2020 Matt Casanova. All rights reserved. // import MetalMath import LiquidMetal2D class MoveRightState: State { private unowned let obj: BehavoirObj private let textures: [Int] private let getBounds: (_ zOrder: Float) -> WorldBounds private var bounds = WorldBounds(maxX: 0, minX: 0, maxY: 0, minY: 0) init(obj: BehavoirObj, getBounds: @escaping (_ zOrder: Float) -> WorldBounds, textures: [Int]) { self.obj = obj self.textures = textures self.getBounds = getBounds } func enter() { randomize() } func exit() { } func update(dt: Float) { obj.position += obj.velocity * dt if !isInRange(value: obj.position.x, low: bounds.minX, high: bounds.maxX) || !isInRange(value: obj.position.y, low: bounds.minY, high: bounds.maxY) { randomize() } } private func randomize() { obj.zOrder = Float.random(in: 0...60) bounds = getBounds(obj.zOrder) obj.position.x = bounds.minX obj.position.y = Float.random(in: bounds.minY/2...bounds.maxY/2) obj.scale.set(1, 1) obj.rotation = 0 obj.velocity.set(Float.random(in: 2...10), 0) obj.textureID = textures[Int.random(in: 0...2)] } }
25.37931
100
0.568614
235bd4e1246d15057277d7f788750f9711656949
238
// // Ranking+CoreDataClass.swift // H-Bazaar // // Created by Pallav Trivedi on 03/04/20. // Copyright © 2020 Pallav Trivedi. All rights reserved. // // import Foundation import CoreData public class Ranking: NSManagedObject { }
14
57
0.705882
62021a8a1c3d3f529f9329b1b3be701829388b1e
2,733
// // CancelTrackerPopupViewController.swift // i2app // // Created by Arcus Team on 3/10/17. /* * Copyright 2019 Arcus Project * * 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 CancelTrackerPopupViewController: PopupSelectionBaseContainer, UITextViewDelegate { @IBOutlet var titleLabel: ArcusLabel! @IBOutlet var descriptionTextView: UITextView! @IBOutlet var descriptionTextHeight: NSLayoutConstraint! override func getHeight() -> CGFloat { return descriptionTextHeight.constant - 141.0 + 265.0 } private var closeHandler: () -> Void = { _ in } static func create() -> CancelTrackerPopupViewController? { let storyboard = UIStoryboard(name: "AlarmTracker", bundle: nil) if let viewController = storyboard .instantiateViewController(withIdentifier: "CancelTrackerPopupViewController") as? CancelTrackerPopupViewController { viewController.view.frame = CGRect(x: viewController.view.frame.origin.x, y: viewController.view.frame.origin.y, width: viewController.view.frame.size.width, height: 255) return viewController } return nil } // MARK: UI Configuration func configureCancelPopup(title: String, message: String, closeBlock: @escaping () -> Void) { view.layoutIfNeeded() titleLabel.text = title descriptionTextView.text = message textViewDidChange(descriptionTextView) closeHandler = closeBlock } // MARK: IBAction @IBAction func closeButtonPressed(_ sender: AnyObject) { closeHandler() } // MARK: UITextViewDelegate func textViewDidChange(_ textView: UITextView) { let insets: UIEdgeInsets = textView.textContainerInset let size: CGSize = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat(MAXFLOAT))) let height = size.height + insets.top + insets.bottom + 16 // + 16 for clickable phone number UIView.animate(withDuration: 0.0, animations: { self.descriptionTextHeight.constant = height self.view.layoutIfNeeded() }, completion: nil) } }
32.927711
97
0.687157
ab0a7cc6e98485dd962361edf8f80909c1548368
807
// // ExampleBasicContentView.swift // ESTabBarControllerExample // // Created by lihao on 2017/2/9. // Copyright © 2017年 Vincent Li. All rights reserved. // import UIKit import ESTabBarController class ExampleBasicContentView: ESTabBarItemContentView { override init(frame: CGRect) { super.init(frame: frame) textColor = UIColor.init(white: 175.0 / 255.0, alpha: 1.0) highlightTextColor = UIColor.init(red: 254/255.0, green: 73/255.0, blue: 42/255.0, alpha: 1.0) iconColor = UIColor.init(white: 175.0 / 255.0, alpha: 1.0) highlightIconColor = UIColor.init(red: 254/255.0, green: 73/255.0, blue: 42/255.0, alpha: 1.0) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
28.821429
102
0.662949
d661ba1f82aa5d1f745ef816bc44cb467caf406f
2,086
// // CultivationFoodCell.swift // twelve-months // // Created by Anton Quietzsch on 24.11.20. // Copyright © 2020 Anton Quietzsch. All rights reserved. // import UIKit class CultivationFoodCell: FoodCell { var cultivationLabel: UILabel! var cultivationImageView = UIImageView() /// Only add subviews that are specific to section `.cultivated`. override init(_ item: Food, in month: Month) { super.init(item, in: month) setupCultivationImageView() setupCultivationLabel() } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setupCultivationImageView() { let index = Month.index(of: month) let availability = item.cultivationByMonth[index].rawValue cultivationImageView.image = UIImage(named: "plant-\(availability)") addSubview(cultivationImageView) cultivationImageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ cultivationImageView.centerYAnchor.constraint(equalTo: centerYAnchor), cultivationImageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -40), cultivationImageView.widthAnchor.constraint(equalToConstant: 30), cultivationImageView.heightAnchor.constraint(equalToConstant: 30) ]) } fileprivate func setupCultivationLabel() { let index = Month.index(of: month) guard let ratio = item.ratio?[index] else { fatalError("No cultivation found for \(item.name)") } cultivationLabel = UILabel(text: "\(ratio)%") cultivationLabel.textColor = .systemGray addSubview(cultivationLabel) cultivationLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ cultivationLabel.trailingAnchor.constraint(equalTo: cultivationImageView.leadingAnchor, constant: -15), cultivationLabel.centerYAnchor.constraint(equalTo: centerYAnchor) ]) } }
38.62963
115
0.697028
5646d3a3d118b095b05c39f915e2a3d741aa3ae9
2,096
// // Reachability.swift // Fokoyo // // Created by Frezy Mboumba on 12/20/16. // Copyright © 2016 MaranathApp. All rights reserved. // import UIKit import SystemConfiguration protocol Utilities { } extension NSObject:Utilities{ enum ReachabilityStatus { case notReachable case reachableViaWWAN case reachableViaWiFi } var currentReachabilityStatus: ReachabilityStatus { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return .notReachable } var flags: SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return .notReachable } if flags.contains(.reachable) == false { // The target host is not reachable. return .notReachable } else if flags.contains(.isWWAN) == true { // WWAN connections are OK if the calling application is using the CFNetwork APIs. return .reachableViaWWAN } else if flags.contains(.connectionRequired) == false { // If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi... return .reachableViaWiFi } else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false { // The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed return .reachableViaWiFi } else { return .notReachable } } }
32.246154
165
0.622615
9c355f84af74aa59cc73bac73659bd9792f7e1d2
10,207
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import MDFTextAccessibility import MaterialComponents.MaterialIcons_ic_check import MaterialComponents.MaterialPalettes import MaterialComponents.MaterialThemes import UIKit private func createSchemeWithPalette(_ palette: MDCPalette) -> MDCSemanticColorScheme { let scheme = MDCSemanticColorScheme() scheme.primaryColor = palette.tint500 scheme.primaryColorVariant = palette.tint900 scheme.secondaryColor = scheme.primaryColor if let onPrimaryColor = MDFTextAccessibility.textColor(fromChoices: [MDCPalette.grey.tint100, MDCPalette.grey.tint900, UIColor.black, UIColor.white], onBackgroundColor: scheme.primaryColor, options: .preferLighter) { scheme.onPrimaryColor = onPrimaryColor } if let onSecondaryColor = MDFTextAccessibility.textColor(fromChoices: [MDCPalette.grey.tint100, MDCPalette.grey.tint900, UIColor.black, UIColor.white], onBackgroundColor: scheme.secondaryColor, options: .preferLighter) { scheme.onSecondaryColor = onSecondaryColor } return scheme } private struct MDCColorThemeCellConfiguration { let name: String let mainColor: UIColor let colorScheme: () -> MDCColorScheming init(name: String, mainColor: UIColor, colorScheme: @escaping () -> MDCColorScheming) { self.name = name self.mainColor = mainColor self.colorScheme = colorScheme } } class MDCThemePickerViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { let palettesCollectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) private var collectionViewLayout: UICollectionViewFlowLayout { return palettesCollectionView.collectionViewLayout as! UICollectionViewFlowLayout } let titleColor = AppTheme.globalTheme.colorScheme.onSurfaceColor.withAlphaComponent(0.5) let titleFont = AppTheme.globalTheme.typographyScheme.button private let cellReuseIdentifier = "cell" private let colorSchemeConfigurations = [ MDCColorThemeCellConfiguration(name: "Default", mainColor: AppTheme.defaultTheme.colorScheme.primaryColor, colorScheme: { return AppTheme.defaultTheme.colorScheme }), MDCColorThemeCellConfiguration(name: "Blue", mainColor: MDCPalette.blue.tint500, colorScheme: { return createSchemeWithPalette(MDCPalette.blue) }), MDCColorThemeCellConfiguration(name: "Red", mainColor: MDCPalette.red.tint500, colorScheme: { return createSchemeWithPalette(MDCPalette.red) }), MDCColorThemeCellConfiguration(name: "Green", mainColor: MDCPalette.green.tint500, colorScheme: { return createSchemeWithPalette(MDCPalette.green) }), MDCColorThemeCellConfiguration(name: "Amber", mainColor: MDCPalette.amber.tint500, colorScheme: { return createSchemeWithPalette(MDCPalette.amber) }), MDCColorThemeCellConfiguration(name: "Pink", mainColor: MDCPalette.pink.tint500, colorScheme: { return createSchemeWithPalette(MDCPalette.pink) }), MDCColorThemeCellConfiguration(name: "Orange", mainColor: MDCPalette.orange.tint500, colorScheme: { return createSchemeWithPalette(MDCPalette.orange) }) ] private let cellSize : CGFloat = 48.0 // minimum touch target private let cellSpacing : CGFloat = 8.0 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "Material Palette-based themes" view.backgroundColor = .white setUpCollectionView() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() positionCollectionView() } func setUpCollectionView() { palettesCollectionView.register(PaletteCell.self, forCellWithReuseIdentifier: cellReuseIdentifier) palettesCollectionView.translatesAutoresizingMaskIntoConstraints = false palettesCollectionView.delegate = self palettesCollectionView.dataSource = self palettesCollectionView.backgroundColor = .white view.addSubview(palettesCollectionView) } func positionCollectionView() { var originX = view.bounds.origin.x var width = view.bounds.size.width var height = view.bounds.size.height if #available(iOS 11.0, *) { originX += view.safeAreaInsets.left; width -= (view.safeAreaInsets.left + view.safeAreaInsets.right); height -= (view.safeAreaInsets.top + view.safeAreaInsets.bottom); } let frame = CGRect(x: originX, y: view.bounds.origin.y, width: width, height: height) palettesCollectionView.frame = frame palettesCollectionView.collectionViewLayout.invalidateLayout() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as! PaletteCell cell.contentView.backgroundColor = colorSchemeConfigurations[indexPath.item].mainColor cell.contentView.layer.cornerRadius = cellSize / 2 cell.contentView.layer.borderWidth = 1 cell.contentView.layer.borderColor = AppTheme.globalTheme.colorScheme.onSurfaceColor.withAlphaComponent(0.05).cgColor if AppTheme.globalTheme.colorScheme.primaryColor == colorSchemeConfigurations[indexPath.item].mainColor { cell.imageView.isHidden = false cell.isSelected = true } else { cell.imageView.isHidden = true cell.isSelected = false } cell.isAccessibilityElement = true cell.accessibilityLabel = colorSchemeConfigurations[indexPath.row].name cell.accessibilityHint = "Changes the catalog color theme." return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: cellSize, height: cellSize) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: cellSpacing, left: cellSpacing, bottom: cellSpacing, right: cellSpacing) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return cellSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return cellSpacing } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return colorSchemeConfigurations.count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let colorScheme = colorSchemeConfigurations[indexPath.item].colorScheme() navigationController?.popViewController(animated: true) AppTheme.globalTheme = AppTheme(colorScheme: colorScheme, typographyScheme: AppTheme.globalTheme.typographyScheme) } } class PaletteCell : UICollectionViewCell { let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) imageView.image = MDCIcons.imageFor_ic_check()?.withRenderingMode(.alwaysTemplate) imageView.tintColor = .white imageView.contentMode = .center self.contentView.addSubview(imageView) } override func layoutSubviews() { imageView.frame = self.contentView.frame } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
42.004115
100
0.638287
8f44b84022ac02291bed86892d34f3fc3e07e72e
14,242
// // YSEKEventTool.swift // ShiJianYun // // Created by Mr.Yang on 2021/10/21. // import Foundation import EventKit public class YSEKEventTool: NSObject {} // MARK:- 一、日历基本的使用 public extension YSEKEventTool { // MARK: 1.1、根据时间段获取日历事件 /// 根据时间段获取日历事件 /// - Parameters: /// - startDate: 开始时间 /// - endDate: 结束时间 /// - eventsClosure: 事件闭包 static func selectCalendarsEvents(startDate: Date, endDate: Date, eventsClosure: @escaping (([EKEvent]) -> Void)) { let eventStore = EKEventStore() // 请求日历事件 eventStore.requestAccess(to: .event, completion: { granted, error in if (granted) && (error == nil) { // 获取本地日历(剔除节假日,生日等其他系统日历) let calendars = eventStore.calendars(for: .event).filter({ (calender) -> Bool in return calender.type == .local || calender.type == .calDAV }) let predicate = eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: calendars) let eV = eventStore.events(matching: predicate) resultMain(parameter: eV, eventsClosure: eventsClosure) } else { resultMain(parameter: [], eventsClosure: eventsClosure) } }) } // MARK: 1.2、添加日历事件 /// 添加日历事件 /// - Parameters: /// - title: 提醒的标题 /// - startDate: 开始时间 /// - endDate: 结束时间 /// - notes: 备注 /// - eventsClosure: 事件闭包 static func addCalendarsEvents(title: String, startDate: Date, endDate: Date, notes: String, eventsClosure: @escaping ((Bool, String?) -> Void)) { let eventStore = EKEventStore() eventStore.requestAccess(to: .event, completion: { granted, error in if (granted) && (error == nil) { let event: EKEvent = EKEvent(eventStore: eventStore) event.title = title event.startDate = startDate event.endDate = endDate event.notes = notes event.calendar = eventStore.defaultCalendarForNewEvents do { try eventStore.save(event, span: .thisEvent) resultMain(parameter: (true, event.calendarItemIdentifier), eventsClosure: eventsClosure) } catch { resultMain(parameter: (false, nil), eventsClosure: eventsClosure) } } else { resultMain(parameter: (false, nil), eventsClosure: eventsClosure) } }) } // MARK: 1.3、修改日历事件 /// 修改日历事件 /// - Parameters: /// - eventIdentifier: 唯一标识符区分某个事件 /// - title: 提醒的标题 /// - startDate: 开始时间 /// - endDate: 结束时间 /// - notes: 备注 /// - eventsClosure: 事件闭包 static func updateCalendarsEvents(eventIdentifier: String, title: String, startDate: Date, endDate: Date, notes: String, eventsClosure: @escaping ((Bool) -> Void)) { let eventStore = EKEventStore() // 请求日历事件 eventStore.requestAccess(to: .event, completion: { granted, error in if (granted) && (error == nil) { // 获取本地日历(剔除节假日,生日等其他系统日历) let calendars = eventStore.calendars(for: .event).filter({ (calender) -> Bool in return calender.type == .local || calender.type == .calDAV }) let predicate = eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: calendars) let events = eventStore.events(matching: predicate) let eventArray = events.filter { $0.calendarItemIdentifier == eventIdentifier } guard eventArray.count > 0 else { resultMain(parameter: false, eventsClosure: eventsClosure) return } let event = eventArray[0] event.title = title event.startDate = startDate event.endDate = endDate event.notes = notes event.calendar = eventStore.defaultCalendarForNewEvents do { try eventStore.save(event, span: .thisEvent) resultMain(parameter: true, eventsClosure: eventsClosure) } catch { resultMain(parameter: false, eventsClosure: eventsClosure) } } else { resultMain(parameter: false, eventsClosure: eventsClosure) } }) } // MARK: 1.4、删除日历事件 /// 删除日历事件 /// - Parameters: /// - eventIdentifier: 唯一标识符区分某个事件 /// - eventsClosure: 事件闭包 static func removeCalendarsEvent(eventIdentifier: String, eventsClosure: @escaping ((Bool) -> Void)) { let eventStore = EKEventStore() // 请求日历事件 eventStore.requestAccess(to: .event, completion: { granted, error in if (granted) && (error == nil) { // 获取本地日历(剔除节假日,生日等其他系统日历) let calendars = eventStore.calendars(for: .event).filter({ (calender) -> Bool in return calender.type == .local || calender.type == .calDAV }) // 获取当前年 let com = Calendar.current.dateComponents([.year], from: Date()) let currentYear = com.year! var events: [EKEvent] = [] // 获取所有的事件(前后20年) for i in -20...20 { let startDate = startOfMonth(year: currentYear + i, month:1) let endDate = endOfMonth(year: currentYear + i, month: 12, returnEndTime: true) let predicate = eventStore.predicateForEvents( withStart: startDate, end: endDate, calendars: calendars) let eV = eventStore.events(matching: predicate) events.append(eV) } let event = events.filter { return $0.calendarItemIdentifier == eventIdentifier } guard event.count > 0 else { resultMain(parameter: false, eventsClosure: eventsClosure) return } do { try eventStore.remove(event[0], span: .thisEvent, commit: true) resultMain(parameter: true, eventsClosure: eventsClosure) } catch { resultMain(parameter: false, eventsClosure: eventsClosure) } } else { resultMain(parameter: false, eventsClosure: eventsClosure) } }) } } // MARK:- 二、提醒事件的基本的使用 public extension YSEKEventTool { // MARK: 2.1、查询出所有提醒事件 static func selectReminder(remindersClosure: @escaping (([EKReminder]?) -> Void)) { // 在取得提醒之前,需要先获取授权 let eventStore = EKEventStore() eventStore.requestAccess(to: .reminder) { (granted: Bool, error: Error?) in if (granted) && (error == nil) { // 获取授权后,我们可以得到所有的提醒事项 let predicate = eventStore.predicateForReminders(in: nil) eventStore.fetchReminders(matching: predicate, completion: { (reminders: [EKReminder]?) -> Void in resultMain(parameter: reminders, eventsClosure: remindersClosure) }) } else { resultMain(parameter: nil, eventsClosure: remindersClosure) } } } // MARK: 2.2、添加提醒事件 /// 添加提醒事件 /// - Parameters: /// - title: 提醒的标题 /// - startDate: 开始时间 /// - endDate: 结束时间 /// - notes: 备注 /// - eventsClosure: 事件闭包 static func addReminder(title: String, startDate: Date, endDate: Date, notes: String, eventsClosure: @escaping ((Bool, String?) -> Void)) { let eventStore = EKEventStore() // 获取"提醒"的访问授权 eventStore.requestAccess(to: .reminder) {(granted, error) in if (granted) && (error == nil) { // 创建提醒条目 let reminder = EKReminder(eventStore: eventStore) reminder.title = title reminder.notes = notes reminder.startDateComponents = dateComponentFrom(date: startDate) reminder.dueDateComponents = dateComponentFrom(date: endDate) reminder.calendar = eventStore.defaultCalendarForNewReminders() // 保存提醒事项 do { try eventStore.save(reminder, commit: true) resultMain(parameter: (true, reminder.calendarItemIdentifier), eventsClosure: eventsClosure) } catch { resultMain(parameter: (false, nil), eventsClosure: eventsClosure) } } else { resultMain(parameter: (false, nil), eventsClosure: eventsClosure) } } } // MARK: 2.3、修改提醒事件 /// 修改提醒事件 /// - Parameters: /// - eventIdentifier: 唯一标识符区分某个事件 /// - title: 提醒的标题 /// - startDate: 开始时间 /// - endDate: 结束时间 /// - notes: 备注 /// - eventsClosure: 事件闭包 static func updateEvent(eventIdentifier: String, title: String, startDate: Date, endDate: Date, notes: String, eventsClosure: @escaping ((Bool) -> Void)) { let eventStore = EKEventStore() // 获取"提醒"的访问授权 eventStore.requestAccess(to: .reminder) {(granted, error) in if (granted) && (error == nil) { // 获取授权后,我们可以得到所有的提醒事项 let predicate = eventStore.predicateForReminders(in: nil) eventStore.fetchReminders(matching: predicate, completion: { (reminders: [EKReminder]?) -> Void in guard let weakReminders = reminders else { resultMain(parameter: false, eventsClosure: eventsClosure) return } let weakReminder = weakReminders.filter { $0.calendarItemIdentifier == eventIdentifier } guard weakReminder.count > 0 else { resultMain(parameter: false, eventsClosure: eventsClosure) return } let reminder = weakReminder[0] reminder.title = title reminder.notes = notes reminder.startDateComponents = dateComponentFrom(date: startDate) reminder.dueDateComponents = dateComponentFrom(date: endDate) reminder.calendar = eventStore.defaultCalendarForNewReminders() // 修改提醒事项 do { try eventStore.save(reminder, commit: true) resultMain(parameter: true, eventsClosure: eventsClosure) } catch { resultMain(parameter: false, eventsClosure: eventsClosure) } }) } } } // MARK: 2.4、移除提醒事件 /// 移除提醒事件 /// - Parameters: /// - eventIdentifier: 唯一标识符区分某个事件 /// - title: 提醒的标题 /// - startDate: 开始时间 /// - endDate: 结束时间 /// - notes: 备注 /// - eventsClosure: 事件闭包 static func removeEvent(eventIdentifier: String, eventsClosure: @escaping ((Bool) -> Void)) { let eventStore = EKEventStore() // 获取"提醒"的访问授权 eventStore.requestAccess(to: .reminder) {(granted, error) in if (granted) && (error == nil) { // 获取授权后,我们可以得到所有的提醒事项 let predicate = eventStore.predicateForReminders(in: nil) eventStore.fetchReminders(matching: predicate, completion: { (reminders: [EKReminder]?) -> Void in guard let weakReminders = reminders else { resultMain(parameter: false, eventsClosure: eventsClosure) return } let reminderArray = weakReminders.filter { $0.calendarItemIdentifier == eventIdentifier } guard reminderArray.count > 0 else { resultMain(parameter: false, eventsClosure: eventsClosure) return } // 移除提醒事项 do { try eventStore.remove(reminderArray[0], commit: true) resultMain(parameter: true, eventsClosure: eventsClosure) } catch { resultMain(parameter: false, eventsClosure: eventsClosure) } }) } } } } // MARK:- private private extension YSEKEventTool { /// 根据NSDate获取对应的DateComponents对象 static func dateComponentFrom(date: Date) -> DateComponents { let cal = Calendar.current let dateComponents = cal.dateComponents([.minute, .hour, .day, .month, .year], from: date) return dateComponents } /// 指定年月的开始日期 static func startOfMonth(year: Int, month: Int) -> Date { let calendar = Calendar.current var startComps = DateComponents() startComps.day = 1 startComps.month = month startComps.year = year let startDate = calendar.date(from: startComps)! return startDate } /// 指定年月的结束日期 static func endOfMonth(year: Int, month: Int, returnEndTime: Bool = false) -> Date { let calendar = Calendar.current var components = DateComponents() components.month = 1 if returnEndTime { components.second = -1 } else { components.day = -1 } let tem = startOfMonth(year: year, month: month) let endOfYear = calendar.date(byAdding: components, to: tem)! return endOfYear } /// 事件主线程 /// - Parameters: /// - parameter: 返回的参数 /// - eventsClosure: 闭包 private static func resultMain<T>(parameter: T, eventsClosure: @escaping ((T) -> Void)) { DispatchQueue.main.async { eventsClosure(parameter) } } }
40.575499
169
0.53581
289895e8e7bd02a78d952c4e2ee466c73729fee5
325
// // Constants.swift // JWTSampleApp // // Created by Martina Stremenova on 28/06/2019. // Copyright © 2019 Box. All rights reserved. // import Foundation struct Constants { static let clientID: String = "YOUR JWT APPLICATION CLIENT ID" static let clientSecret: String = "YOUR JWT APPLICATION CLIENT SECRET" }
21.666667
74
0.713846
899fa2fe6ed9d21171fc5beb677373d01dac7a30
521
// // ViewController.swift // TabbarControllerTransition // // Created by guomin on 16/4/6. // Copyright © 2016年 iBinaryOrg. All rights reserved. // import UIKit class FirstViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.038462
80
0.681382
9c9e1f5830ba17668f2d98408854eee1524ae636
4,836
import Quick import Nimble import RxSwift import RxTest import RxNimbleRxTest class RxNimbleRxTestTests: QuickSpec { override func spec() { describe("Events") { let initialClock = 0 var scheduler: TestScheduler! var disposeBag: DisposeBag! beforeEach { disposeBag = DisposeBag() scheduler = TestScheduler(initialClock: initialClock, simulateProcessingDelay: false) } it("works with uncompleted streams") { let subject = scheduler.createHotObservable([ next(5, "Hello"), next(10, "World"), ]) expect(subject).events(scheduler: scheduler, disposeBag: disposeBag) .to(equal([ Recorded.next(5, "Hello"), Recorded.next(10, "World") ])) } it("works with completed streams") { let subject = scheduler.createHotObservable([ next(5, "Hello"), next(10, "World"), completed(100) ]) expect(subject).events(scheduler: scheduler, disposeBag: disposeBag) .to(equal([ Recorded.next(5, "Hello"), Recorded.next(10, "World"), Recorded.completed(100) ])) } it("works with errored streams") { let subject: TestableObservable<String> = scheduler.createHotObservable([ error(5, AnyError.any) ]) expect(subject).events(scheduler: scheduler, disposeBag: disposeBag) .to(equal([ Recorded.error(5, AnyError.any) ])) } it("throws error if any event is error") { let subject = scheduler.createHotObservable([ Recorded.next(5, "Hello"), Recorded.next(10, "World"), error(15, AnyError.any) ]) expect(subject).events(scheduler: scheduler, disposeBag: disposeBag) .to(throwError()) } it("does not throw error if no errors") { let subject = scheduler.createHotObservable([ Recorded.next(5, "Hello"), Recorded.next(10, "World") ]) expect(subject).events(scheduler: scheduler, disposeBag: disposeBag) .toNot(throwError()) } it("throws assertion if any event is assertion") { let subject = scheduler.createHotObservable([ Recorded.next(5, "Hello"), Recorded.next(10, "World"), error(15, AnyError.any) ]) let observer = PublishSubject<String>() observer.map({ _ in fatalError() }).subscribe().disposed(by: disposeBag) subject.subscribe(observer).disposed(by: disposeBag) expect(subject).events(scheduler: scheduler, disposeBag: disposeBag) .to(throwAssertion()) } it("does not throw assertion if no assertion") { let subject = scheduler.createHotObservable([ Recorded.next(5, "Hello"), Recorded.next(10, "World") ]) expect(subject).events(scheduler: scheduler, disposeBag: disposeBag) .toNot(throwAssertion()) } it("subscribes at specified initial time") { let initialTime = 50 let eventTime = 100 let subject = scheduler.createColdObservable([ next(eventTime, "Hi") ]) expect(subject).events(scheduler: scheduler, disposeBag: disposeBag, startAt: initialTime) .to(equal([ Recorded.next(initialTime + eventTime, "Hi") ])) } it("ignores hot stream events before initial time") { let subject = scheduler.createHotObservable([ next(5, "Hello"), next(10, "World"), completed(100) ]) expect(subject).events(scheduler: scheduler, disposeBag: disposeBag, startAt: 15) .to(equal([ Recorded.completed(100) ])) } } } }
36.636364
106
0.460505
22856ab439a17d57cc3e4ec354801002261e5173
1,514
// @copyright Trollwerks Inc. import XCTest final class AppStoreSnapshotTests: XCTestCase { // to reset all simulators: // xcrun simctl shutdown all // xcrun simctl erase all override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testAppStoreSnapshots() { launch(arguments: [ .disableAnimations, .disableWaitIdle, .takingScreenshots, ], settings: [.loggedIn(true)]) UIMain.locations.assert(.selected) snapshot("01Locations") UILocations.nearby.tap() snapshot("02Nearby") let gaggan = 3 UINearby.place(gaggan).tap() snapshot("03Callout") UILocations.nearby.tap() let thailand = 0 UINearby.place(thailand).doubleTap() snapshot("04Info") UIMain.rankings.tap() UIMain.rankings.wait(for: .selected) snapshot("05Rankings") let charles = 2 UIRankingsPage.profile(.locations, charles).tap() wait(for: 5) snapshot("06UserProfile") UIUserProfile.close.tap() UIRankings.filter.tap() snapshot("07Filter") UIMain.myProfile.tap() UIProfilePaging.counts.tap() snapshot("08MyCounts") UIProfilePaging.photos.tap() wait(for: 8) snapshot("09MyPhotos") UIProfilePaging.posts.tap() snapshot("10MyPosts") } }
19.662338
57
0.570674
ac4f59858ba937529df53c1120b794ff6d5bfbe6
5,699
// RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s // RUN: %target-swift-emit-silgen -enable-astscope-lookup -parse-as-library %s | %FileCheck %s // CHECK-LABEL: sil hidden @$s15local_recursionAA_1yySi_SitF : $@convention(thin) (Int, Int) -> () { // CHECK: bb0([[X:%0]] : $Int, [[Y:%1]] : $Int): func local_recursion(_ x: Int, y: Int) { func self_recursive(_ a: Int) { self_recursive(x + a) } // Invoke local functions by passing all their captures. // CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE:@\$s15local_recursionAA_1yySi_SitF14self_recursiveL_yySiF]] // CHECK: apply [[SELF_RECURSIVE_REF]]([[X]], [[X]]) self_recursive(x) // CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE]] // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[SELF_RECURSIVE_REF]]([[X]]) // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] let sr = self_recursive // CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]] // CHECK: apply [[B]]([[Y]]) // CHECK: end_borrow [[B]] // CHECK: destroy_value [[CLOSURE_COPY]] // CHECK: end_borrow [[BORROWED_CLOSURE]] sr(y) func mutually_recursive_1(_ a: Int) { mutually_recursive_2(x + a) } func mutually_recursive_2(_ b: Int) { mutually_recursive_1(y + b) } // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1:@\$s15local_recursionAA_1yySi_SitF20mutually_recursive_1L_yySiF]] // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]([[X]], [[Y]], [[X]]) mutually_recursive_1(x) // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]] _ = mutually_recursive_1 func transitive_capture_1(_ a: Int) -> Int { return x + a } func transitive_capture_2(_ b: Int) -> Int { return transitive_capture_1(y + b) } // CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE:@\$s15local_recursionAA_1yySi_SitF20transitive_capture_2L_yS2iF]] // CHECK: apply [[TRANS_CAPTURE_REF]]([[X]], [[X]], [[Y]]) transitive_capture_2(x) // CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE]] // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[TRANS_CAPTURE_REF]]([[X]], [[Y]]) // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] let tc = transitive_capture_2 // CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]] // CHECK: apply [[B]]([[X]]) // CHECK: end_borrow [[B]] // CHECK: destroy_value [[CLOSURE_COPY]] // CHECK: end_borrow [[BORROWED_CLOSURE]] tc(x) // CHECK: [[CLOSURE_REF:%.*]] = function_ref @$s15local_recursionAA_1yySi_SitFySiXEfU_ // CHECK: apply [[CLOSURE_REF]]([[X]], [[X]], [[Y]]) let _: Void = { self_recursive($0) transitive_capture_2($0) }(x) // CHECK: [[CLOSURE_REF:%.*]] = function_ref @$s15local_recursionAA_1yySi_SitFySicfU0_ // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[CLOSURE_REF]]([[X]], [[Y]]) // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] // CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]] // CHECK: apply [[B]]([[X]]) // CHECK: end_borrow [[B]] // CHECK: destroy_value [[CLOSURE_COPY]] // CHECK: end_borrow [[BORROWED_CLOSURE]] let f: (Int) -> () = { self_recursive($0) transitive_capture_2($0) } f(x) } // CHECK: sil private [[SELF_RECURSIVE]] // CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int): // CHECK: [[SELF_REF:%.*]] = function_ref [[SELF_RECURSIVE]] // CHECK: apply [[SELF_REF]]({{.*}}, [[X]]) // CHECK: sil private [[MUTUALLY_RECURSIVE_1]] // CHECK: bb0([[A:%0]] : $Int, [[Y:%1]] : $Int, [[X:%2]] : $Int): // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_2:@\$s15local_recursionAA_1yySi_SitF20mutually_recursive_2L_yySiF]] // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[X]], [[Y]]) // CHECK: sil private [[MUTUALLY_RECURSIVE_2]] // CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int): // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]] // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[Y]], [[X]]) // CHECK: sil private [[TRANS_CAPTURE_1:@\$s15local_recursionAA_1yySi_SitF20transitive_capture_1L_yS2iF]] // CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int): // CHECK: sil private [[TRANS_CAPTURE]] // CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int): // CHECK: [[TRANS_CAPTURE_1_REF:%.*]] = function_ref [[TRANS_CAPTURE_1]] // CHECK: apply [[TRANS_CAPTURE_1_REF]]({{.*}}, [[X]]) func plus<T>(_ x: T, _ y: T) -> T { return x } func toggle<T, U>(_ x: T, _ y: U) -> U { return y } func generic_local_recursion<T, U>(_ x: T, y: U) { func self_recursive(_ a: T) { self_recursive(plus(x, a)) } self_recursive(x) _ = self_recursive func transitive_capture_1(_ a: T) -> U { return toggle(a, y) } func transitive_capture_2(_ b: U) -> U { return transitive_capture_1(toggle(b, x)) } transitive_capture_2(y) _ = transitive_capture_2 func no_captures() {} no_captures() _ = no_captures func transitive_no_captures() { no_captures() } transitive_no_captures() _ = transitive_no_captures } func local_properties(_ x: Int, y: Int) -> Int { var self_recursive: Int { return x + self_recursive } var transitive_capture_1: Int { return x } var transitive_capture_2: Int { return transitive_capture_1 + y } func transitive_capture_fn() -> Int { return transitive_capture_2 } return self_recursive + transitive_capture_fn() }
34.96319
146
0.638533
9cdb1571d1f9c8203fb358b1b8f136949cf04b5e
1,692
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct DestinationData : DestinationProtocol { public var name: String? public var properties: DestinationPropertiesProtocol? enum CodingKeys: String, CodingKey {case name = "name" case properties = "properties" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.name) { self.name = try container.decode(String?.self, forKey: .name) } if container.contains(.properties) { self.properties = try container.decode(DestinationPropertiesData?.self, forKey: .properties) } if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if self.name != nil {try container.encode(self.name, forKey: .name)} if self.properties != nil {try container.encode(self.properties as! DestinationPropertiesData?, forKey: .properties)} } } extension DataFactory { public static func createDestinationProtocol() -> DestinationProtocol { return DestinationData() } }
36.782609
122
0.698582
b996914ffd3777ca8b2e194a4958d6895c2314ff
1,235
// // PullRequestCommentsViewController.swift // SwiftHub // // Created by Sygnoos9 on 5/12/19. // Copyright © 2019 Khoren Markosyan. All rights reserved. // import UIKit import RxSwift import RxCocoa import MessageKit class PullRequestCommentsViewController: ChatViewController { var viewModel: PullRequestCommentsViewModel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func bindViewModel() { super.bindViewModel() let refresh = Observable.of(Observable.just(()), themeService.typeStream.mapToVoid()).merge() let input = PullRequestCommentsViewModel.Input(headerRefresh: refresh, sendSelected: sendPressed) let output = viewModel.transform(input: input) output.items.subscribe(onNext: { [weak self] (comments) in self?.messages = comments }).disposed(by: rx.disposeBag) viewModel.error.asDriver().drive(onNext: { [weak self] (error) in self?.showAlert(title: R.string.localizable.commonError.key.localized(), message: error.localizedDescription) }).disposed(by: rx.disposeBag) } }
30.121951
121
0.668016
9c644ea1bf5dd8a59e77f432ee89f525cb523038
3,415
import AEXML import Foundation extension XCScheme { public final class TestableReference: Equatable { // MARK: - Attributes public var skipped: Bool public var parallelizable: Bool public var randomExecutionOrdering: Bool public var useTestSelectionWhitelist: Bool? public var buildableReference: BuildableReference public var skippedTests: [SkippedTest] // MARK: - Init public init(skipped: Bool, parallelizable: Bool = false, randomExecutionOrdering: Bool = false, buildableReference: BuildableReference, skippedTests: [SkippedTest] = [], useTestSelectionWhitelist: Bool? = nil) { self.skipped = skipped self.parallelizable = parallelizable self.randomExecutionOrdering = randomExecutionOrdering self.buildableReference = buildableReference self.skippedTests = skippedTests self.useTestSelectionWhitelist = useTestSelectionWhitelist } init(element: AEXMLElement) throws { skipped = element.attributes["skipped"] == "YES" parallelizable = element.attributes["parallelizable"] == "YES" useTestSelectionWhitelist = element.attributes["useTestSelectionWhitelist"] == "YES" randomExecutionOrdering = element.attributes["testExecutionOrdering"] == "random" buildableReference = try BuildableReference(element: element["BuildableReference"]) if let skippedTests = element["SkippedTests"]["Test"].all, !skippedTests.isEmpty { self.skippedTests = try skippedTests.map(SkippedTest.init) } else { skippedTests = [] } } // MARK: - XML func xmlElement() -> AEXMLElement { var attributes: [String: String] = ["skipped": skipped.xmlString] attributes["parallelizable"] = parallelizable ? parallelizable.xmlString : nil if let useTestSelectionWhitelist = useTestSelectionWhitelist { attributes["useTestSelectionWhitelist"] = useTestSelectionWhitelist.xmlString } attributes["testExecutionOrdering"] = randomExecutionOrdering ? "random" : nil let element = AEXMLElement(name: "TestableReference", value: nil, attributes: attributes) element.addChild(buildableReference.xmlElement()) if !skippedTests.isEmpty { let skippedTestsElement = element.addChild(name: "SkippedTests") skippedTests.forEach { skippedTest in skippedTestsElement.addChild(skippedTest.xmlElement()) } } return element } // MARK: - Equatable public static func == (lhs: TestableReference, rhs: TestableReference) -> Bool { return lhs.skipped == rhs.skipped && lhs.parallelizable == rhs.parallelizable && lhs.randomExecutionOrdering == rhs.randomExecutionOrdering && lhs.buildableReference == rhs.buildableReference && lhs.useTestSelectionWhitelist == rhs.useTestSelectionWhitelist && lhs.skippedTests == rhs.skippedTests } } }
43.782051
96
0.605271
e0c49545e3b060a13f392ed2a174c3c3d4de4255
2,221
import SourceKittenFramework public struct FunctionBodyLengthRule: ASTRule, ConfigurationProviderRule { public var configuration = SeverityLevelsConfiguration(warning: 40, error: 100) public init() {} public static let description = RuleDescription( identifier: "function_body_length", name: "Function Body Length", description: "函数主体最好不要太长了.", kind: .metrics ) public func validate(file: SwiftLintFile, kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) -> [StyleViolation] { guard let input = RuleInput(file: file, kind: kind, dictionary: dictionary) else { return [] } for parameter in configuration.params { let (exceeds, lineCount) = file.exceedsLineCountExcludingCommentsAndWhitespace( input.startLine, input.endLine, parameter.value ) guard exceeds else { continue } return [ StyleViolation( ruleDescription: Self.description, severity: parameter.severity, location: Location(file: file, byteOffset: input.offset), reason: """ 函数主题最好不要超过 \(configuration.warning) 行,不包括空白和换行,当前:\(lineCount) 行,要不要考虑拆分方法 """ ) ] } return [] } } private struct RuleInput { let offset: ByteCount let startLine: Int let endLine: Int init?(file: SwiftLintFile, kind: SwiftDeclarationKind, dictionary: SourceKittenDictionary) { guard SwiftDeclarationKind.functionKinds.contains(kind), let offset = dictionary.offset, let bodyOffset = dictionary.bodyOffset, let bodyLength = dictionary.bodyLength, case let contentsNSString = file.stringView, let startLine = contentsNSString.lineAndCharacter(forByteOffset: bodyOffset)?.line, let endLine = contentsNSString.lineAndCharacter(forByteOffset: bodyOffset + bodyLength)?.line else { return nil } self.offset = offset self.startLine = startLine self.endLine = endLine } }
35.253968
105
0.615939
6a1ceba91b31576aa45c13fd8983f827fd902113
539
// // PhoneContact+CoreDataClass.swift // FanapPodChatSDK // // Created by Mahyar Zhiani on 11/23/1397 AP. // Copyright © 1397 Mahyar Zhiani. All rights reserved. // // import Foundation import CoreData public class PhoneContact: NSManagedObject { func updateObject(with contact: AddContactRequest) { self.cellphoneNumber = contact.cellphoneNumber self.email = contact.email self.firstName = contact.firstName self.lastName = contact.lastName } }
22.458333
57
0.649351
18b7b4f7151232a42d730cd4129c34f7791f2035
837
// // TYPEPersistenceStrategy.swift // import AmberBase import Foundation public class Dictionary_C_IndexPath_InflectionRule_D_PersistenceStrategy: PersistenceStrategy { public var types: Types { return Types.generic("Dictionary", [Types.type("IndexPath"), Types.type("InflectionRule")]) } public func save(_ object: Any) throws -> Data { guard let typedObject = object as? Dictionary<IndexPath, InflectionRule> else { throw AmberError.wrongTypes(self.types, AmberBase.types(of: object)) } let encoder = JSONEncoder() return try encoder.encode(typedObject) } public func load(_ data: Data) throws -> Any { let decoder = JSONDecoder() return try decoder.decode(Dictionary<IndexPath, InflectionRule>.self, from: data) } }
27
99
0.673835
b9e9c1642de117c1ef9f1eeadc07280832e1fb3e
8,453
// ButtonBarView.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public enum PagerScroll { case no case yes case scrollOnlyIfOutOfScreen } public enum SelectedBarAlignment { case left case center case right case progressive } public enum SelectedBarVerticalAlignment { case top case middle case bottom } open class ButtonBarView: UICollectionView { open lazy var selectedBar: UIView = { [unowned self] in let bar = UIView(frame: CGRect(x: self.frame.size.width / 2.0, y: self.frame.size.height - CGFloat(self.selectedBarHeight), width: 0, height: CGFloat(self.selectedBarHeight))) bar.layer.zPosition = 9999 return bar }() internal var selectedBarHeight: CGFloat = 4 { didSet { updateSelectedBarYPosition() } } var selectedBarVerticalAlignment: SelectedBarVerticalAlignment = .bottom var selectedBarAlignment: SelectedBarAlignment = .center open var selectedIndex = 0 open var barWidth: CGFloat = 42.0 required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubview(selectedBar) } public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) addSubview(selectedBar) } open func moveTo(index: Int, animated: Bool, swipeDirection: SwipeDirection, pagerScroll: PagerScroll) { selectedIndex = index updateSelectedBarPosition(animated, swipeDirection: swipeDirection, pagerScroll: pagerScroll) } open func move(fromIndex: Int, toIndex: Int, progressPercentage: CGFloat, pagerScroll: PagerScroll) { selectedIndex = progressPercentage > 0.5 ? toIndex : fromIndex let fromFrame = layoutAttributesForItem(at: IndexPath(item: fromIndex, section: 0))!.frame let numberOfItems = dataSource!.collectionView(self, numberOfItemsInSection: 0) var toFrame: CGRect if toIndex < 0 || toIndex > numberOfItems - 1 { if toIndex < 0 { let cellAtts = layoutAttributesForItem(at: IndexPath(item: 0, section: 0)) toFrame = cellAtts!.frame.offsetBy(dx: -cellAtts!.frame.size.width, dy: 0) } else { let cellAtts = layoutAttributesForItem(at: IndexPath(item: (numberOfItems - 1), section: 0)) toFrame = cellAtts!.frame.offsetBy(dx: cellAtts!.frame.size.width, dy: 0) } } else { toFrame = layoutAttributesForItem(at: IndexPath(item: toIndex, section: 0))!.frame } var targetFrame = fromFrame targetFrame.size.height = selectedBar.frame.size.height targetFrame.size.width = barWidth let toX = toFrame.origin.x + (toFrame.width - barWidth) / 2.0 let fromX = fromFrame.origin.x + (fromFrame.width - barWidth) / 2.0 targetFrame.origin.x = fromFrame.origin.x + (fromFrame.width - barWidth) / 2.0 targetFrame.origin.x += (toX - fromX) * progressPercentage selectedBar.frame = CGRect(x: targetFrame.origin.x, y: selectedBar.frame.origin.y, width: targetFrame.size.width, height: selectedBar.frame.size.height) var targetContentOffset: CGFloat = 0.0 if contentSize.width > frame.size.width { let toContentOffset = contentOffsetForCell(withFrame: toFrame, andIndex: toIndex) let fromContentOffset = contentOffsetForCell(withFrame: fromFrame, andIndex: fromIndex) targetContentOffset = fromContentOffset + ((toContentOffset - fromContentOffset) * progressPercentage) } setContentOffset(CGPoint(x: targetContentOffset, y: 0), animated: false) } func updateSelectedBarPosition(_ animated: Bool, swipeDirection: SwipeDirection, pagerScroll: PagerScroll) { var selectedBarFrame = selectedBar.frame let selectedCellIndexPath = IndexPath(item: selectedIndex, section: 0) let attributes = layoutAttributesForItem(at: selectedCellIndexPath) let selectedCellFrame = attributes!.frame updateContentOffset(animated: animated, pagerScroll: pagerScroll, toFrame: selectedCellFrame, toIndex: (selectedCellIndexPath as NSIndexPath).row) selectedBarFrame.size.width = barWidth selectedBarFrame.origin.x = selectedCellFrame.origin.x + (selectedCellFrame.size.width - barWidth) / 2.0 if animated { UIView.animate(withDuration: 0.3, animations: { [weak self] in self?.selectedBar.frame = selectedBarFrame }) } else { selectedBar.frame = selectedBarFrame } } // MARK: - Helpers private func updateContentOffset(animated: Bool, pagerScroll: PagerScroll, toFrame: CGRect, toIndex: Int) { guard pagerScroll != .no || (pagerScroll != .scrollOnlyIfOutOfScreen && (toFrame.origin.x < contentOffset.x || toFrame.origin.x >= (contentOffset.x + frame.size.width - contentInset.left))) else { return } let targetContentOffset = contentSize.width > frame.size.width ? contentOffsetForCell(withFrame: toFrame, andIndex: toIndex) : 0 setContentOffset(CGPoint(x: targetContentOffset, y: 0), animated: animated) } private func contentOffsetForCell(withFrame cellFrame: CGRect, andIndex index: Int) -> CGFloat { let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset // swiftlint:disable:this force_cast var alignmentOffset: CGFloat = 0.0 switch selectedBarAlignment { case .left: alignmentOffset = sectionInset.left case .right: alignmentOffset = frame.size.width - sectionInset.right - cellFrame.size.width case .center: alignmentOffset = (frame.size.width - cellFrame.size.width) * 0.5 case .progressive: let cellHalfWidth = cellFrame.size.width * 0.5 let leftAlignmentOffset = sectionInset.left + cellHalfWidth let rightAlignmentOffset = frame.size.width - sectionInset.right - cellHalfWidth let numberOfItems = dataSource!.collectionView(self, numberOfItemsInSection: 0) let progress = index / (numberOfItems - 1) alignmentOffset = leftAlignmentOffset + (rightAlignmentOffset - leftAlignmentOffset) * CGFloat(progress) - cellHalfWidth } var contentOffset = cellFrame.origin.x - alignmentOffset contentOffset = max(0, contentOffset) contentOffset = min(contentSize.width - frame.size.width, contentOffset) return contentOffset } private func updateSelectedBarYPosition() { var selectedBarFrame = selectedBar.frame switch selectedBarVerticalAlignment { case .top: selectedBarFrame.origin.y = 0 case .middle: selectedBarFrame.origin.y = (frame.size.height - selectedBarHeight) / 2 case .bottom: selectedBarFrame.origin.y = frame.size.height - selectedBarHeight + 6 } selectedBarFrame.size.height = selectedBarHeight selectedBar.frame = selectedBarFrame } override open func layoutSubviews() { super.layoutSubviews() updateSelectedBarYPosition() } }
43.127551
213
0.689933
ac04eee3e251bee7608cbda2a5c7d19e1b7a13c4
1,898
// // LogInViewController.swift // ChatMe // // Created by Pann Cherry on 9/27/18. // Copyright © 2018 Pann Cherry. All rights reserved. // import UIKit import Parse class LogInViewController: UIViewController { // MARK: IBOutlets @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() } // MARK: - IBActions /*: # Log In * Check user credits * Display error alert if user credis are incorrect */ @IBAction func onLogIn(_ sender: Any) { PFUser.logInWithUsername(inBackground: userNameTextField.text!, password: passwordTextField.text!) { (user: PFUser?, error: Error?) in if user == nil { print("Username/email is required.") self.loginErrorAlert() } if user != nil { print("You are logged in.") self.userNameTextField.text = "" self.passwordTextField.text = "" self.performSegue(withIdentifier: "logInSegue", sender: nil) } } } /*: # Dismiss Keyboard * On tap, dismiss keyboard */ @IBAction func onTappedDismissKeyboard(_ sender: Any) { view.endEditing(true) } //MARK: - Helper Functions /*: # Log In Error Alert */ func loginErrorAlert(){ let alert = UIAlertController(title: "Login Error", message: "Hmm..something went wrong. or Username/Email is missing.", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(defaultAction) self.present(alert, animated: true, completion: nil) userNameTextField.text = "" passwordTextField.text = "" } }
28.328358
152
0.596417
eb5219a8a6d1a894e804ef8e82ec91c463ff5670
124,625
// swiftlint:disable all // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen import Foundation // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length // MARK: - Strings // swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length // swiftlint:disable nesting type_body_length type_name internal enum L10n { /// Add internal static let addButtonLabel = L10n.tr("Localizable", "addButtonLabel") /// Cancel internal static let cancelLabel = L10n.tr("Localizable", "cancel_label") /// Delete internal static let delete = L10n.tr("Localizable", "delete") /// Error internal static let errorLabel = L10n.tr("Localizable", "error_label") /// No internal static let noLabel = L10n.tr("Localizable", "no_label") /// OK internal static let okLabel = L10n.tr("Localizable", "ok_label") /// Preview Output internal static let previewOutput = L10n.tr("Localizable", "preview_output") /// Success internal static let successLabel = L10n.tr("Localizable", "success_label") /// Username internal static let usernameLabel = L10n.tr("Localizable", "username_label") /// Yes internal static let yesLabel = L10n.tr("Localizable", "yes_label") internal enum About { /// About internal static let title = L10n.tr("Localizable", "about.title") internal enum Acknowledgements { /// Acknowledgements internal static let title = L10n.tr("Localizable", "about.acknowledgements.title") } internal enum Beta { /// Join Beta internal static let title = L10n.tr("Localizable", "about.beta.title") } internal enum Chat { /// Chat internal static let title = L10n.tr("Localizable", "about.chat.title") } internal enum Documentation { /// Documentation internal static let title = L10n.tr("Localizable", "about.documentation.title") } internal enum EasterEgg { /// i love you internal static let message = L10n.tr("Localizable", "about.easter_egg.message") /// You found me! internal static let title = L10n.tr("Localizable", "about.easter_egg.title") } internal enum Forums { /// Forums internal static let title = L10n.tr("Localizable", "about.forums.title") } internal enum Github { /// GitHub internal static let title = L10n.tr("Localizable", "about.github.title") } internal enum GithubIssueTracker { /// GitHub Issue Tracker internal static let title = L10n.tr("Localizable", "about.github_issue_tracker.title") } internal enum HelpLocalize { /// Help localize the app! internal static let title = L10n.tr("Localizable", "about.help_localize.title") } internal enum HomeAssistantOnFacebook { /// Home Assistant on Facebook internal static let title = L10n.tr("Localizable", "about.home_assistant_on_facebook.title") } internal enum HomeAssistantOnTwitter { /// Home Assistant on Twitter internal static let title = L10n.tr("Localizable", "about.home_assistant_on_twitter.title") } internal enum Logo { /// Home Assistant Companion internal static let appTitle = L10n.tr("Localizable", "about.logo.app_title") /// Awaken Your Home internal static let tagline = L10n.tr("Localizable", "about.logo.tagline") } internal enum Review { /// Leave a review internal static let title = L10n.tr("Localizable", "about.review.title") } internal enum Website { /// Website internal static let title = L10n.tr("Localizable", "about.website.title") } } internal enum ActionsConfigurator { /// New Action internal static let title = L10n.tr("Localizable", "actions_configurator.title") internal enum Rows { internal enum BackgroundColor { /// Background Color internal static let title = L10n.tr("Localizable", "actions_configurator.rows.background_color.title") } internal enum Icon { /// Icon internal static let title = L10n.tr("Localizable", "actions_configurator.rows.icon.title") } internal enum IconColor { /// Icon Color internal static let title = L10n.tr("Localizable", "actions_configurator.rows.icon_color.title") } internal enum Name { /// Name internal static let title = L10n.tr("Localizable", "actions_configurator.rows.name.title") } internal enum Text { /// Text internal static let title = L10n.tr("Localizable", "actions_configurator.rows.text.title") } internal enum TextColor { /// Text Color internal static let title = L10n.tr("Localizable", "actions_configurator.rows.text_color.title") } } } internal enum Alerts { internal enum Alert { /// OK internal static let ok = L10n.tr("Localizable", "alerts.alert.ok") } internal enum AuthRequired { /// The server has rejected your credentials, and you must sign in again to continue. internal static let message = L10n.tr("Localizable", "alerts.auth_required.message") /// You must sign in to continue internal static let title = L10n.tr("Localizable", "alerts.auth_required.title") } internal enum Confirm { /// Cancel internal static let cancel = L10n.tr("Localizable", "alerts.confirm.cancel") /// OK internal static let ok = L10n.tr("Localizable", "alerts.confirm.ok") } internal enum OpenUrlFromNotification { /// Open URL (%@) found in notification? internal static func message(_ p1: String) -> String { return L10n.tr("Localizable", "alerts.open_url_from_notification.message", p1) } /// Open URL? internal static let title = L10n.tr("Localizable", "alerts.open_url_from_notification.title") } internal enum Prompt { /// Cancel internal static let cancel = L10n.tr("Localizable", "alerts.prompt.cancel") /// OK internal static let ok = L10n.tr("Localizable", "alerts.prompt.ok") } } internal enum ClError { internal enum Description { /// Deferred mode is not supported for the requested accuracy. internal static let deferredAccuracyTooLow = L10n.tr("Localizable", "cl_error.description.deferred_accuracy_too_low") /// The request for deferred updates was canceled by your app or by the location manager. internal static let deferredCanceled = L10n.tr("Localizable", "cl_error.description.deferred_canceled") /// Deferred mode does not support distance filters. internal static let deferredDistanceFiltered = L10n.tr("Localizable", "cl_error.description.deferred_distance_filtered") /// The location manager did not enter deferred mode for an unknown reason. internal static let deferredFailed = L10n.tr("Localizable", "cl_error.description.deferred_failed") /// The manager did not enter deferred mode since updates were already disabled/paused. internal static let deferredNotUpdatingLocation = L10n.tr("Localizable", "cl_error.description.deferred_not_updating_location") /// Access to the location service was denied by the user. internal static let denied = L10n.tr("Localizable", "cl_error.description.denied") /// The geocode request was canceled. internal static let geocodeCanceled = L10n.tr("Localizable", "cl_error.description.geocode_canceled") /// The geocode request yielded no result. internal static let geocodeFoundNoResult = L10n.tr("Localizable", "cl_error.description.geocode_found_no_result") /// The geocode request yielded a partial result. internal static let geocodeFoundPartialResult = L10n.tr("Localizable", "cl_error.description.geocode_found_partial_result") /// The heading could not be determined. internal static let headingFailure = L10n.tr("Localizable", "cl_error.description.heading_failure") /// The location manager was unable to obtain a location value right now. internal static let locationUnknown = L10n.tr("Localizable", "cl_error.description.location_unknown") /// The network was unavailable or a network error occurred. internal static let network = L10n.tr("Localizable", "cl_error.description.network") /// A general ranging error occurred. internal static let rangingFailure = L10n.tr("Localizable", "cl_error.description.ranging_failure") /// Ranging is disabled. internal static let rangingUnavailable = L10n.tr("Localizable", "cl_error.description.ranging_unavailable") /// Access to the region monitoring service was denied by the user. internal static let regionMonitoringDenied = L10n.tr("Localizable", "cl_error.description.region_monitoring_denied") /// A registered region cannot be monitored. internal static let regionMonitoringFailure = L10n.tr("Localizable", "cl_error.description.region_monitoring_failure") /// Core Location will deliver events but they may be delayed. internal static let regionMonitoringResponseDelayed = L10n.tr("Localizable", "cl_error.description.region_monitoring_response_delayed") /// Core Location could not initialize the region monitoring feature immediately. internal static let regionMonitoringSetupDelayed = L10n.tr("Localizable", "cl_error.description.region_monitoring_setup_delayed") /// Unknown Core Location error internal static let unknown = L10n.tr("Localizable", "cl_error.description.unknown") } } internal enum ClientEvents { internal enum EventType { /// Location Update internal static let locationUpdate = L10n.tr("Localizable", "client_events.event_type.location_update") /// Network Request internal static let networkRequest = L10n.tr("Localizable", "client_events.event_type.networkRequest") /// Notification internal static let notification = L10n.tr("Localizable", "client_events.event_type.notification") /// Service Call internal static let serviceCall = L10n.tr("Localizable", "client_events.event_type.service_call") /// Unknown internal static let unknown = L10n.tr("Localizable", "client_events.event_type.unknown") internal enum Notification { /// Received a Push Notification: %@ internal static func title(_ p1: String) -> String { return L10n.tr("Localizable", "client_events.event_type.notification.title", p1) } } internal enum Request { /// Request(SSID: %@ - %@) internal static func log(_ p1: String, _ p2: String) -> String { return L10n.tr("Localizable", "client_events.event_type.request.log", p1, p2) } } } internal enum View { /// Clear internal static let clear = L10n.tr("Localizable", "client_events.view.clear") } } internal enum DevicesMap { /// Battery internal static let batteryLabel = L10n.tr("Localizable", "devices_map.battery_label") /// Devices & Zones internal static let title = L10n.tr("Localizable", "devices_map.title") internal enum MapTypes { /// Hybrid internal static let hybrid = L10n.tr("Localizable", "devices_map.map_types.hybrid") /// Satellite internal static let satellite = L10n.tr("Localizable", "devices_map.map_types.satellite") /// Standard internal static let standard = L10n.tr("Localizable", "devices_map.map_types.standard") } } internal enum Errors { /// The app will automatically detect your Nabu Casa Remote UI, you can not manually enter it. internal static let noRemoteUiUrl = L10n.tr("Localizable", "errors.no_remote_ui_url") } internal enum Extensions { internal enum Map { internal enum Location { /// New Location internal static let new = L10n.tr("Localizable", "extensions.map.location.new") /// Original Location internal static let original = L10n.tr("Localizable", "extensions.map.location.original") } internal enum PayloadMissingHomeassistant { /// Payload didn't contain a homeassistant dictionary! internal static let message = L10n.tr("Localizable", "extensions.map.payload_missing_homeassistant.message") } internal enum ValueMissingOrUncastable { internal enum Latitude { /// Latitude wasn't found or couldn't be casted to string! internal static let message = L10n.tr("Localizable", "extensions.map.value_missing_or_uncastable.latitude.message") } internal enum Longitude { /// Longitude wasn't found or couldn't be casted to string! internal static let message = L10n.tr("Localizable", "extensions.map.value_missing_or_uncastable.longitude.message") } } } internal enum NotificationContent { internal enum Error { /// No entity_id found in payload! internal static let noEntityId = L10n.tr("Localizable", "extensions.notification_content.error.no_entity_id") internal enum Request { /// Authentication failed! internal static let authFailed = L10n.tr("Localizable", "extensions.notification_content.error.request.auth_failed") /// Entity '%@' not found! internal static func entityNotFound(_ p1: String) -> String { return L10n.tr("Localizable", "extensions.notification_content.error.request.entity_not_found", p1) } /// Got non-200 status code (%d) internal static func other(_ p1: Int) -> String { return L10n.tr("Localizable", "extensions.notification_content.error.request.other", p1) } /// Unknown error! internal static let unknown = L10n.tr("Localizable", "extensions.notification_content.error.request.unknown") } } internal enum Hud { /// Loading %@... internal static func loading(_ p1: String) -> String { return L10n.tr("Localizable", "extensions.notification_content.hud.loading", p1) } } } } internal enum HaApi { internal enum ApiError { /// Cant build API URL internal static let cantBuildUrl = L10n.tr("Localizable", "ha_api.api_error.cant_build_url") /// Received invalid response from Home Assistant internal static let invalidResponse = L10n.tr("Localizable", "ha_api.api_error.invalid_response") /// HA API Manager is unavailable internal static let managerNotAvailable = L10n.tr("Localizable", "ha_api.api_error.manager_not_available") /// The mobile_app component is not loaded. Please add it to your configuration, restart Home Assistant, and try again. internal static let mobileAppComponentNotLoaded = L10n.tr("Localizable", "ha_api.api_error.mobile_app_component_not_loaded") /// Your Home Assistant version (%@) is too old, you must upgrade to at least version %@ to use the app. internal static func mustUpgradeHomeAssistant(_ p1: String, _ p2: String) -> String { return L10n.tr("Localizable", "ha_api.api_error.must_upgrade_home_assistant", p1, p2) } /// HA API not configured internal static let notConfigured = L10n.tr("Localizable", "ha_api.api_error.not_configured") /// An unknown error occurred. internal static let unknown = L10n.tr("Localizable", "ha_api.api_error.unknown") /// mobile_app integration has been deleted, you must reconfigure the app. internal static let webhookGone = L10n.tr("Localizable", "ha_api.api_error.webhook_gone") } } internal enum LocationChangeNotification { /// Location change internal static let title = L10n.tr("Localizable", "location_change_notification.title") internal enum AppShortcut { /// Location updated via App Shortcut internal static let body = L10n.tr("Localizable", "location_change_notification.app_shortcut.body") } internal enum BackgroundFetch { /// Current location delivery triggered via background fetch internal static let body = L10n.tr("Localizable", "location_change_notification.background_fetch.body") } internal enum BeaconRegionEnter { /// %@ entered via iBeacon internal static func body(_ p1: String) -> String { return L10n.tr("Localizable", "location_change_notification.beacon_region_enter.body", p1) } } internal enum BeaconRegionExit { /// %@ exited via iBeacon internal static func body(_ p1: String) -> String { return L10n.tr("Localizable", "location_change_notification.beacon_region_exit.body", p1) } } internal enum Manual { /// Location update triggered by user internal static let body = L10n.tr("Localizable", "location_change_notification.manual.body") } internal enum PushNotification { /// Location updated via push notification internal static let body = L10n.tr("Localizable", "location_change_notification.push_notification.body") } internal enum RegionEnter { /// %@ entered internal static func body(_ p1: String) -> String { return L10n.tr("Localizable", "location_change_notification.region_enter.body", p1) } } internal enum RegionExit { /// %@ exited internal static func body(_ p1: String) -> String { return L10n.tr("Localizable", "location_change_notification.region_exit.body", p1) } } internal enum SignificantLocationUpdate { /// Significant location change detected internal static let body = L10n.tr("Localizable", "location_change_notification.significant_location_update.body") } internal enum Siri { /// Location update triggered by Siri internal static let body = L10n.tr("Localizable", "location_change_notification.siri.body") } internal enum Unknown { /// Location updated via unknown method internal static let body = L10n.tr("Localizable", "location_change_notification.unknown.body") } internal enum UrlScheme { /// Location updated via URL Scheme internal static let body = L10n.tr("Localizable", "location_change_notification.url_scheme.body") } internal enum Visit { /// Location updated via Visit internal static let body = L10n.tr("Localizable", "location_change_notification.visit.body") } internal enum XCallbackUrl { /// Location updated via X-Callback-URL internal static let body = L10n.tr("Localizable", "location_change_notification.x_callback_url.body") } } internal enum ManualLocationUpdateFailedNotification { /// Failed to send current location to server. The error was %@ internal static func message(_ p1: String) -> String { return L10n.tr("Localizable", "manual_location_update_failed_notification.message", p1) } /// Location failed to update internal static let title = L10n.tr("Localizable", "manual_location_update_failed_notification.title") } internal enum ManualLocationUpdateNotification { /// Successfully sent a one shot location to the server internal static let message = L10n.tr("Localizable", "manual_location_update_notification.message") /// Location updated internal static let title = L10n.tr("Localizable", "manual_location_update_notification.title") } internal enum NotificationsConfigurator { /// Identifier internal static let identifier = L10n.tr("Localizable", "notifications_configurator.identifier") internal enum Action { internal enum Rows { internal enum AuthenticationRequired { /// When the user selects an action with this option, the system prompts the user to unlock the device. After unlocking, Home Assistant will be notified of the selected action. internal static let footer = L10n.tr("Localizable", "notifications_configurator.action.rows.authentication_required.footer") /// Authentication Required internal static let title = L10n.tr("Localizable", "notifications_configurator.action.rows.authentication_required.title") } internal enum Destructive { /// When enabled, the action button is displayed with special highlighting to indicate that it performs a destructive task. internal static let footer = L10n.tr("Localizable", "notifications_configurator.action.rows.destructive.footer") /// Destructive internal static let title = L10n.tr("Localizable", "notifications_configurator.action.rows.destructive.title") } internal enum Foreground { /// Enabling this will cause the app to launch if it's in the background when tapping a notification internal static let footer = L10n.tr("Localizable", "notifications_configurator.action.rows.foreground.footer") /// Launch app internal static let title = L10n.tr("Localizable", "notifications_configurator.action.rows.foreground.title") } internal enum TextInputButtonTitle { /// Button Title internal static let title = L10n.tr("Localizable", "notifications_configurator.action.rows.text_input_button_title.title") } internal enum TextInputPlaceholder { /// Placeholder internal static let title = L10n.tr("Localizable", "notifications_configurator.action.rows.text_input_placeholder.title") } internal enum Title { /// Title internal static let title = L10n.tr("Localizable", "notifications_configurator.action.rows.title.title") } } internal enum TextInput { /// Text Input internal static let title = L10n.tr("Localizable", "notifications_configurator.action.text_input.title") } } internal enum Category { internal enum NavigationBar { /// Category Configurator internal static let title = L10n.tr("Localizable", "notifications_configurator.category.navigation_bar.title") } internal enum PreviewNotification { /// This is a test notification for the %@ notification category internal static func body(_ p1: String) -> String { return L10n.tr("Localizable", "notifications_configurator.category.preview_notification.body", p1) } /// Test notification internal static let title = L10n.tr("Localizable", "notifications_configurator.category.preview_notification.title") } internal enum Rows { internal enum Actions { /// Categories can have a maximum of 10 actions. internal static let footer = L10n.tr("Localizable", "notifications_configurator.category.rows.actions.footer") /// Actions internal static let header = L10n.tr("Localizable", "notifications_configurator.category.rows.actions.header") } internal enum CategorySummary { /// %%u notifications in %%@ internal static let `default` = L10n.tr("Localizable", "notifications_configurator.category.rows.category_summary.default") /// A format string for the summary description used when the system groups the category’s notifications. You can optionally uses '%%u' to show the number of notifications in the group and '%%@' to show the summary argument provided in the push payload. internal static let footer = L10n.tr("Localizable", "notifications_configurator.category.rows.category_summary.footer") /// Category Summary internal static let header = L10n.tr("Localizable", "notifications_configurator.category.rows.category_summary.header") } internal enum HiddenPreviewPlaceholder { /// %%u notifications internal static let `default` = L10n.tr("Localizable", "notifications_configurator.category.rows.hidden_preview_placeholder.default") /// This text is only displayed if you have notification previews hidden. Use '%%u' for the number of messages with the same thread identifier. internal static let footer = L10n.tr("Localizable", "notifications_configurator.category.rows.hidden_preview_placeholder.footer") /// Hidden Preview Placeholder internal static let header = L10n.tr("Localizable", "notifications_configurator.category.rows.hidden_preview_placeholder.header") } internal enum Name { /// Name internal static let title = L10n.tr("Localizable", "notifications_configurator.category.rows.name.title") } } } internal enum NewAction { /// New Action internal static let title = L10n.tr("Localizable", "notifications_configurator.new_action.title") } internal enum Settings { /// Identifier must contain only letters and underscores. It must be globally unique to the app. internal static let footer = L10n.tr("Localizable", "notifications_configurator.settings.footer") /// Settings internal static let header = L10n.tr("Localizable", "notifications_configurator.settings.header") internal enum Footer { /// Identifier can not be changed after creation. You must delete and recreate the action to change the identifier. internal static let idSet = L10n.tr("Localizable", "notifications_configurator.settings.footer.id_set") } } } internal enum Onboarding { internal enum Connect { /// Connecting to %@ internal static func title(_ p1: String) -> String { return L10n.tr("Localizable", "onboarding.connect.title", p1) } } internal enum ConnectionTestResult { internal enum AuthenticationUnsupported { /// Authentication type is unsupported%@. internal static func description(_ p1: String) -> String { return L10n.tr("Localizable", "onboarding.connection_test_result.authentication_unsupported.description", p1) } } internal enum BasicAuth { /// HTTP Basic Authentication is unsupported. internal static let description = L10n.tr("Localizable", "onboarding.connection_test_result.basic_auth.description") } internal enum ClientCertificate { /// Client Certificate Authentication is not supported. internal static let description = L10n.tr("Localizable", "onboarding.connection_test_result.client_certificate.description") } internal enum ConnectionError { /// General connection error%@. internal static func description(_ p1: String) -> String { return L10n.tr("Localizable", "onboarding.connection_test_result.connection_error.description", p1) } } internal enum NoBaseUrlDiscovered { /// No http.base_url was found in the discovery information. Please add a valid http.base_url to your configuration.yaml and restart Home Assistant to continue with automatic setup or setup manually. internal static let description = L10n.tr("Localizable", "onboarding.connection_test_result.no_base_url_discovered.description") } internal enum ServerError { /// Server error: %@ internal static func description(_ p1: String) -> String { return L10n.tr("Localizable", "onboarding.connection_test_result.server_error.description", p1) } } internal enum SslContainer { /// We encountered an error while connecting to your instance. %@ Due to iOS limitations, you will not be able to continue with setup until a valid SSL certificate is installed. We recommend Lets Encrypt or Nabu Casa Remote UI. internal static func description(_ p1: String) -> String { return L10n.tr("Localizable", "onboarding.connection_test_result.ssl_container.description", p1) } } internal enum SslExpired { /// Your SSL certificate is expired. internal static let description = L10n.tr("Localizable", "onboarding.connection_test_result.ssl_expired.description") } internal enum SslUntrusted { /// Your SSL certificate is untrusted. %@. internal static func description(_ p1: String) -> String { return L10n.tr("Localizable", "onboarding.connection_test_result.ssl_untrusted.description", p1) } } internal enum TooOld { /// You must upgrade your Home Assistant version. internal static let description = L10n.tr("Localizable", "onboarding.connection_test_result.too_old.description") } internal enum UnknownError { /// Unknown error: %@ internal static func description(_ p1: String) -> String { return L10n.tr("Localizable", "onboarding.connection_test_result.unknown_error.description", p1) } } } internal enum Discovery { internal enum ResultsLabel { /// We found %d Home Assistants on your network. internal static func plural(_ p1: Int) -> String { return L10n.tr("Localizable", "onboarding.discovery.results_label.plural", p1) } /// We found %d Home Assistant on your network. internal static func singular(_ p1: Int) -> String { return L10n.tr("Localizable", "onboarding.discovery.results_label.singular", p1) } } } } internal enum Permissions { internal enum Location { /// We use this to inform\rHome Assistant of your device location and state. internal static let message = L10n.tr("Localizable", "permissions.location.message") internal enum Initial { /// We need permission to allow informing\rHome Assistant of your device location and state. internal static let message = L10n.tr("Localizable", "permissions.location.initial.message") /// Allow Location Access? internal static let title = L10n.tr("Localizable", "permissions.location.initial.title") internal enum Button { /// Allow internal static let allow = L10n.tr("Localizable", "permissions.location.initial.button.allow") /// Deny internal static let deny = L10n.tr("Localizable", "permissions.location.initial.button.deny") } } internal enum Reenable { /// You previously had location access enabled but it now appears disabled. Do you wish to re-enable it? internal static let message = L10n.tr("Localizable", "permissions.location.reenable.message") /// Re-enable Location Access? internal static let title = L10n.tr("Localizable", "permissions.location.reenable.title") internal enum Button { /// Re-enable internal static let allow = L10n.tr("Localizable", "permissions.location.reenable.button.allow") /// Leave disabled internal static let deny = L10n.tr("Localizable", "permissions.location.reenable.button.deny") } } } internal enum Motion { internal enum Initial { /// We can use motion data to enhance location updates but need permission to do so. internal static let message = L10n.tr("Localizable", "permissions.motion.initial.message") /// Allow Motion? internal static let title = L10n.tr("Localizable", "permissions.motion.initial.title") internal enum Button { /// Allow internal static let allow = L10n.tr("Localizable", "permissions.motion.initial.button.allow") /// Deny internal static let deny = L10n.tr("Localizable", "permissions.motion.initial.button.deny") } } internal enum Reenable { /// You previously had allowed use of motion data but it now appears to be disabled. Do you wish to re-enable motion data to enhance location updates? internal static let message = L10n.tr("Localizable", "permissions.motion.reenable.message") /// Re-enable Motion? internal static let title = L10n.tr("Localizable", "permissions.motion.reenable.title") internal enum Button { /// Re-enable internal static let allow = L10n.tr("Localizable", "permissions.motion.reenable.button.allow") /// Leave disabled internal static let deny = L10n.tr("Localizable", "permissions.motion.reenable.button.deny") } } } internal enum Notification { /// We use this to let you\rsend notifications to your device. internal static let message = L10n.tr("Localizable", "permissions.notification.message") internal enum Initial { /// We need permission to allow you\rsend notifications to your device. internal static let message = L10n.tr("Localizable", "permissions.notification.initial.message") /// Allow Notifications? internal static let title = L10n.tr("Localizable", "permissions.notification.initial.title") internal enum Button { /// Allow internal static let allow = L10n.tr("Localizable", "permissions.notification.initial.button.allow") /// Deny internal static let deny = L10n.tr("Localizable", "permissions.notification.initial.button.deny") } } internal enum Reenable { /// You previously had notifications enabled but they now appears disabled. Do you wish to re-enable notifications? internal static let message = L10n.tr("Localizable", "permissions.notification.reenable.message") /// Re-enable Notifications? internal static let title = L10n.tr("Localizable", "permissions.notification.reenable.title") internal enum Button { /// Re-enable internal static let allow = L10n.tr("Localizable", "permissions.notification.reenable.button.allow") /// Leave disabled internal static let deny = L10n.tr("Localizable", "permissions.notification.reenable.button.deny") } } } } internal enum RateLimitNotification { /// You have now sent more than %@ notifications today. You will not receive new notifications until midnight UTC. internal static func body(_ p1: String) -> String { return L10n.tr("Localizable", "rate_limit_notification.body", p1) } /// Notifications Rate Limited internal static let title = L10n.tr("Localizable", "rate_limit_notification.title") } internal enum Sensors { /// N/A internal static let notAvailableState = L10n.tr("Localizable", "sensors.not_available_state") /// Unknown internal static let unknownState = L10n.tr("Localizable", "sensors.unknown_state") internal enum Activity { /// Activity internal static let name = L10n.tr("Localizable", "sensors.activity.name") internal enum Attributes { /// Confidence internal static let confidence = L10n.tr("Localizable", "sensors.activity.attributes.confidence") /// Types internal static let types = L10n.tr("Localizable", "sensors.activity.attributes.types") } } internal enum Battery { internal enum Attributes { /// Level internal static let level = L10n.tr("Localizable", "sensors.battery.attributes.level") /// State internal static let state = L10n.tr("Localizable", "sensors.battery.attributes.state") } internal enum State { /// Charging internal static let charging = L10n.tr("Localizable", "sensors.battery.state.charging") /// Full internal static let full = L10n.tr("Localizable", "sensors.battery.state.full") /// Not Charging internal static let notCharging = L10n.tr("Localizable", "sensors.battery.state.not_charging") } } internal enum BatteryLevel { /// Battery Level internal static let name = L10n.tr("Localizable", "sensors.battery_level.name") } internal enum BatteryState { /// Battery State internal static let name = L10n.tr("Localizable", "sensors.battery_state.name") } internal enum Bssid { /// BSSID internal static let name = L10n.tr("Localizable", "sensors.bssid.name") } internal enum CellularProvider { /// Cellular Provider%@ internal static func name(_ p1: String) -> String { return L10n.tr("Localizable", "sensors.cellular_provider.name", p1) } internal enum Attributes { /// Allows VoIP internal static let allowsVoip = L10n.tr("Localizable", "sensors.cellular_provider.attributes.allows_voip") /// Carrier ID internal static let carrierId = L10n.tr("Localizable", "sensors.cellular_provider.attributes.carrier_id") /// Carrier Name internal static let carrierName = L10n.tr("Localizable", "sensors.cellular_provider.attributes.carrier_name") /// ISO Country Code internal static let isoCountryCode = L10n.tr("Localizable", "sensors.cellular_provider.attributes.iso_country_code") /// Mobile Country Code internal static let mobileCountryCode = L10n.tr("Localizable", "sensors.cellular_provider.attributes.mobile_country_code") /// Mobile Network Code internal static let mobileNetworkCode = L10n.tr("Localizable", "sensors.cellular_provider.attributes.mobile_network_code") /// Current Radio Technology internal static let radioTech = L10n.tr("Localizable", "sensors.cellular_provider.attributes.radio_tech") } internal enum RadioTech { /// Code Division Multiple Access (CDMA 1X) internal static let cdma1x = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.cdma_1x") /// Code Division Multiple Access Evolution-Data Optimized Revision 0 (CDMA EV-DO Rev. 0) internal static let cdmaEvdoRev0 = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.cdma_evdo_rev_0") /// Code Division Multiple Access Evolution-Data Optimized Revision A (CDMA EV-DO Rev. A) internal static let cdmaEvdoRevA = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.cdma_evdo_rev_a") /// Code Division Multiple Access Evolution-Data Optimized Revision B (CDMA EV-DO Rev. B) internal static let cdmaEvdoRevB = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.cdma_evdo_rev_b") /// Enhanced Data rates for GSM Evolution (EDGE) internal static let edge = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.edge") /// High Rate Packet Data (HRPD) internal static let ehrpd = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.ehrpd") /// General Packet Radio Service (GPRS) internal static let gprs = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.gprs") /// High Speed Downlink Packet Access (HSDPA) internal static let hsdpa = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.hsdpa") /// High Speed Uplink Packet Access (HSUPA) internal static let hsupa = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.hsupa") /// Long-Term Evolution (LTE) internal static let lte = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.lte") /// Wideband Code Division Multiple Access (WCDMA) internal static let wcdma = L10n.tr("Localizable", "sensors.cellular_provider.radio_tech.wcdma") } } internal enum ConnectionType { /// Connection Type internal static let name = L10n.tr("Localizable", "sensors.connection_type.name") internal enum Attributes { /// Cellular Technology internal static let cellTechType = L10n.tr("Localizable", "sensors.connection_type.attributes.cell_tech_type") } } internal enum Connectivity { /// Not Connected internal static let notConnected = L10n.tr("Localizable", "sensors.connectivity.not_connected") } internal enum GeocodedLocation { /// Geocoded Location internal static let name = L10n.tr("Localizable", "sensors.geocoded_location.name") internal enum Attributes { /// AdministrativeArea internal static let administrativeArea = L10n.tr("Localizable", "sensors.geocoded_location.attributes.administrative_area") /// AreasOfInterest internal static let areasOfInterest = L10n.tr("Localizable", "sensors.geocoded_location.attributes.areas_of_interest") /// Country internal static let country = L10n.tr("Localizable", "sensors.geocoded_location.attributes.country") /// InlandWater internal static let inlandWater = L10n.tr("Localizable", "sensors.geocoded_location.attributes.inland_water") /// ISOCountryCode internal static let isoCountryCode = L10n.tr("Localizable", "sensors.geocoded_location.attributes.iso_country_code") /// Locality internal static let locality = L10n.tr("Localizable", "sensors.geocoded_location.attributes.locality") /// Location internal static let location = L10n.tr("Localizable", "sensors.geocoded_location.attributes.location") /// Name internal static let name = L10n.tr("Localizable", "sensors.geocoded_location.attributes.name") /// Ocean internal static let ocean = L10n.tr("Localizable", "sensors.geocoded_location.attributes.ocean") /// PostalCode internal static let postalCode = L10n.tr("Localizable", "sensors.geocoded_location.attributes.postal_code") /// SubAdministrativeArea internal static let subAdministrativeArea = L10n.tr("Localizable", "sensors.geocoded_location.attributes.sub_administrative_area") /// SubLocality internal static let subLocality = L10n.tr("Localizable", "sensors.geocoded_location.attributes.sub_locality") /// SubThoroughfare internal static let subThoroughfare = L10n.tr("Localizable", "sensors.geocoded_location.attributes.sub_thoroughfare") /// Thoroughfare internal static let thoroughfare = L10n.tr("Localizable", "sensors.geocoded_location.attributes.thoroughfare") /// TimeZone internal static let timeZone = L10n.tr("Localizable", "sensors.geocoded_location.attributes.time_zone") } } internal enum Pedometer { internal enum AverageActivePace { /// Average Active Pace internal static let name = L10n.tr("Localizable", "sensors.pedometer.average_active_pace.name") } internal enum CurrentCadence { /// Current Cadence internal static let name = L10n.tr("Localizable", "sensors.pedometer.current_cadence.name") } internal enum CurrentPace { /// Current Pace internal static let name = L10n.tr("Localizable", "sensors.pedometer.current_pace.name") } internal enum Distance { /// Distance internal static let name = L10n.tr("Localizable", "sensors.pedometer.distance.name") } internal enum FloorsAscended { /// Floors Ascended internal static let name = L10n.tr("Localizable", "sensors.pedometer.floors_ascended.name") } internal enum FloorsDescended { /// Floors Descended internal static let name = L10n.tr("Localizable", "sensors.pedometer.floors_descended.name") } internal enum Steps { /// Steps internal static let name = L10n.tr("Localizable", "sensors.pedometer.steps.name") } internal enum Unit { /// m/s internal static let metersPerSecond = L10n.tr("Localizable", "sensors.pedometer.unit.meters_per_second") /// steps/s internal static let stepsPerSecond = L10n.tr("Localizable", "sensors.pedometer.unit.steps_per_second") } } internal enum Ssid { /// SSID internal static let name = L10n.tr("Localizable", "sensors.ssid.name") } } internal enum Settings { internal enum AdvancedConnectionSettingsSection { /// Advanced Connection Settings internal static let title = L10n.tr("Localizable", "settings.advanced_connection_settings_section.title") } internal enum CertificateErrorNotification { /// A self-signed or invalid SSL certificate has been detected. Certificates of this kind are not supported by Home Assistant Companion. Please tap the More Info button for further information. internal static let message = L10n.tr("Localizable", "settings.certificate_error_notification.message") /// Self-signed or invalid certificate detected internal static let title = L10n.tr("Localizable", "settings.certificate_error_notification.title") } internal enum ConnectionError { internal enum Forbidden { /// The authentication was incorrect. internal static let message = L10n.tr("Localizable", "settings.connection_error.forbidden.message") } internal enum InvalidUrl { /// Looks like your URL is invalid. Please check the format and try again. internal static let message = L10n.tr("Localizable", "settings.connection_error.invalid_url.message") /// Error parsing URL internal static let title = L10n.tr("Localizable", "settings.connection_error.invalid_url.title") } } internal enum ConnectionErrorNotification { /// There was an error connecting to Home Assistant. Please confirm the settings are correct and save to attempt to reconnect. The error was: %@ internal static func message(_ p1: String) -> String { return L10n.tr("Localizable", "settings.connection_error_notification.message", p1) } /// Connection Error internal static let title = L10n.tr("Localizable", "settings.connection_error_notification.title") } internal enum ConnectionSection { /// Cloud Available internal static let cloudAvailable = L10n.tr("Localizable", "settings.connection_section.cloud_available") /// Cloudhook Available internal static let cloudhookAvailable = L10n.tr("Localizable", "settings.connection_section.cloudhook_available") /// Connected via internal static let connectingVia = L10n.tr("Localizable", "settings.connection_section.connecting_via") /// Details internal static let details = L10n.tr("Localizable", "settings.connection_section.details") /// Connection internal static let header = L10n.tr("Localizable", "settings.connection_section.header") /// Log out internal static let logOut = L10n.tr("Localizable", "settings.connection_section.log_out") /// Logged in as internal static let loggedInAs = L10n.tr("Localizable", "settings.connection_section.logged_in_as") /// Nabu Casa Cloud internal static let nabuCasaCloud = L10n.tr("Localizable", "settings.connection_section.nabu_casa_cloud") /// Remote UI Available internal static let remoteUiAvailable = L10n.tr("Localizable", "settings.connection_section.remote_ui_available") internal enum ApiPasswordRow { /// password internal static let placeholder = L10n.tr("Localizable", "settings.connection_section.api_password_row.placeholder") /// Password internal static let title = L10n.tr("Localizable", "settings.connection_section.api_password_row.title") } internal enum BaseUrl { /// https://homeassistant.myhouse.com internal static let placeholder = L10n.tr("Localizable", "settings.connection_section.base_url.placeholder") /// URL internal static let title = L10n.tr("Localizable", "settings.connection_section.base_url.title") } internal enum BasicAuth { /// HTTP Basic Authentication internal static let title = L10n.tr("Localizable", "settings.connection_section.basic_auth.title") internal enum Password { /// verysecure internal static let placeholder = L10n.tr("Localizable", "settings.connection_section.basic_auth.password.placeholder") /// Password internal static let title = L10n.tr("Localizable", "settings.connection_section.basic_auth.password.title") } internal enum Username { /// iam internal static let placeholder = L10n.tr("Localizable", "settings.connection_section.basic_auth.username.placeholder") /// Username internal static let title = L10n.tr("Localizable", "settings.connection_section.basic_auth.username.title") } } internal enum CloudhookUrl { /// Cloudhook URL internal static let title = L10n.tr("Localizable", "settings.connection_section.cloudhook_url.title") } internal enum ConnectRow { /// Connect internal static let title = L10n.tr("Localizable", "settings.connection_section.connect_row.title") } internal enum ErrorEnablingNotifications { /// There was an error enabling notifications. Please try again. internal static let message = L10n.tr("Localizable", "settings.connection_section.error_enabling_notifications.message") /// Error enabling notifications internal static let title = L10n.tr("Localizable", "settings.connection_section.error_enabling_notifications.title") } internal enum ExternalBaseUrl { /// https://homeassistant.myhouse.com internal static let placeholder = L10n.tr("Localizable", "settings.connection_section.external_base_url.placeholder") /// External URL internal static let title = L10n.tr("Localizable", "settings.connection_section.external_base_url.title") } internal enum InternalBaseUrl { /// http://hassio.local:8123/ internal static let placeholder = L10n.tr("Localizable", "settings.connection_section.internal_base_url.placeholder") /// Internal URL internal static let title = L10n.tr("Localizable", "settings.connection_section.internal_base_url.title") } internal enum InternalUrlSsids { /// Add current SSID %@ internal static func addCurrentSsid(_ p1: String) -> String { return L10n.tr("Localizable", "settings.connection_section.internal_url_ssids.add_current_ssid", p1) } /// Add new SSID internal static let addNewSsid = L10n.tr("Localizable", "settings.connection_section.internal_url_ssids.add_new_ssid") /// Internal URL will be used when connected to listed SSIDs internal static let footer = L10n.tr("Localizable", "settings.connection_section.internal_url_ssids.footer") /// SSIDs internal static let header = L10n.tr("Localizable", "settings.connection_section.internal_url_ssids.header") /// MyFunnyNetworkName internal static let placeholder = L10n.tr("Localizable", "settings.connection_section.internal_url_ssids.placeholder") } internal enum InvalidUrlSchemeNotification { /// The URL must begin with either http:// or https://. internal static let message = L10n.tr("Localizable", "settings.connection_section.invalid_url_scheme_notification.message") /// Invalid URL internal static let title = L10n.tr("Localizable", "settings.connection_section.invalid_url_scheme_notification.title") } internal enum NetworkName { /// Current Network Name internal static let title = L10n.tr("Localizable", "settings.connection_section.network_name.title") } internal enum RemoteUi { /// Home Assistant Cloud internal static let title = L10n.tr("Localizable", "settings.connection_section.remote_ui.title") } internal enum RemoteUiUrl { /// Remote UI URL internal static let title = L10n.tr("Localizable", "settings.connection_section.remote_ui_url.title") } internal enum SaveButton { /// Validate and Save Connection Settings internal static let title = L10n.tr("Localizable", "settings.connection_section.save_button.title") } internal enum ShowAdvancedSettingsRow { /// Show advanced settings internal static let title = L10n.tr("Localizable", "settings.connection_section.show_advanced_settings_row.title") } internal enum UseInternalUrl { /// Use internal URL internal static let title = L10n.tr("Localizable", "settings.connection_section.use_internal_url.title") } internal enum UseLegacyAuth { /// Use legacy authentication internal static let title = L10n.tr("Localizable", "settings.connection_section.use_legacy_auth.title") } } internal enum DetailsSection { internal enum EnableLocationRow { /// Enable location tracking internal static let title = L10n.tr("Localizable", "settings.details_section.enable_location_row.title") } internal enum EnableNotificationRow { /// Enable notifications internal static let title = L10n.tr("Localizable", "settings.details_section.enable_notification_row.title") } internal enum Integrations { /// Integrations internal static let header = L10n.tr("Localizable", "settings.details_section.integrations.header") } internal enum LocationSettingsRow { /// Location internal static let title = L10n.tr("Localizable", "settings.details_section.location_settings_row.title") } internal enum NotificationSettingsRow { /// Notifications internal static let title = L10n.tr("Localizable", "settings.details_section.notification_settings_row.title") } internal enum SiriShortcutsRow { /// Siri Shortcuts internal static let title = L10n.tr("Localizable", "settings.details_section.siri_shortcuts_row.title") } internal enum WatchRow { /// Apple Watch internal static let title = L10n.tr("Localizable", "settings.details_section.watch_row.title") } } internal enum Developer { /// Don't use these if you don't know what you are doing! internal static let footer = L10n.tr("Localizable", "settings.developer.footer") /// Developer internal static let header = L10n.tr("Localizable", "settings.developer.header") internal enum CameraNotification { /// Show camera notification content extension internal static let title = L10n.tr("Localizable", "settings.developer.camera_notification.title") internal enum Notification { /// Expand this to show the camera content extension internal static let body = L10n.tr("Localizable", "settings.developer.camera_notification.notification.body") } } internal enum CopyRealm { /// Copy Realm from app group to Documents internal static let title = L10n.tr("Localizable", "settings.developer.copy_realm.title") internal enum Alert { /// Copied Realm from %@ to %@ internal static func message(_ p1: String, _ p2: String) -> String { return L10n.tr("Localizable", "settings.developer.copy_realm.alert.message", p1, p2) } /// Copied Realm internal static let title = L10n.tr("Localizable", "settings.developer.copy_realm.alert.title") } } internal enum DebugStrings { /// Debug strings internal static let title = L10n.tr("Localizable", "settings.developer.debug_strings.title") } internal enum ExportLogFiles { /// Export log files internal static let title = L10n.tr("Localizable", "settings.developer.export_log_files.title") } internal enum Lokalise { /// Update translations from Lokalise! internal static let title = L10n.tr("Localizable", "settings.developer.lokalise.title") internal enum Alert { internal enum NotUpdated { /// No updates internal static let message = L10n.tr("Localizable", "settings.developer.lokalise.alert.not_updated.message") /// No localization updates were available internal static let title = L10n.tr("Localizable", "settings.developer.lokalise.alert.not_updated.title") } internal enum Updated { /// Localizations were updated internal static let message = L10n.tr("Localizable", "settings.developer.lokalise.alert.updated.message") /// Updated internal static let title = L10n.tr("Localizable", "settings.developer.lokalise.alert.updated.title") } } } internal enum MapNotification { /// Show map notification content extension internal static let title = L10n.tr("Localizable", "settings.developer.map_notification.title") internal enum Notification { /// Expand this to show the map content extension internal static let body = L10n.tr("Localizable", "settings.developer.map_notification.notification.body") } } internal enum SyncWatchContext { /// Sync Watch Context internal static let title = L10n.tr("Localizable", "settings.developer.sync_watch_context.title") } } internal enum DeviceIdSection { /// Device ID is the identifier used when sending location updates to Home Assistant, as well as the target to send push notifications to. internal static let footer = L10n.tr("Localizable", "settings.device_id_section.footer") internal enum DeviceIdRow { /// Device ID internal static let title = L10n.tr("Localizable", "settings.device_id_section.device_id_row.title") } } internal enum DiscoverySection { /// Discovered Home Assistants internal static let header = L10n.tr("Localizable", "settings.discovery_section.header") /// Requires password internal static let requiresPassword = L10n.tr("Localizable", "settings.discovery_section.requiresPassword") } internal enum EventLog { /// Event Log internal static let title = L10n.tr("Localizable", "settings.event_log.title") } internal enum GeneralSettingsButton { /// General internal static let title = L10n.tr("Localizable", "settings.general_settings_button.title") } internal enum NavigationBar { /// Settings internal static let title = L10n.tr("Localizable", "settings.navigation_bar.title") internal enum AboutButton { /// About internal static let title = L10n.tr("Localizable", "settings.navigation_bar.about_button.title") } } internal enum ResetSection { internal enum ResetAlert { /// Your settings will be reset and this device will be unregistered from push notifications as well as removed from your Home Assistant configuration. internal static let message = L10n.tr("Localizable", "settings.reset_section.reset_alert.message") /// Reset internal static let title = L10n.tr("Localizable", "settings.reset_section.reset_alert.title") } internal enum ResetRow { /// Reset internal static let title = L10n.tr("Localizable", "settings.reset_section.reset_row.title") } } internal enum StatusSection { /// Status internal static let header = L10n.tr("Localizable", "settings.status_section.header") internal enum ConnectedToSseRow { /// Connected internal static let title = L10n.tr("Localizable", "settings.status_section.connected_to_sse_row.title") } internal enum DeviceTrackerComponentLoadedRow { /// Device Tracker Component Loaded internal static let title = L10n.tr("Localizable", "settings.status_section.device_tracker_component_loaded_row.title") } internal enum IosComponentLoadedRow { /// iOS Component Loaded internal static let title = L10n.tr("Localizable", "settings.status_section.ios_component_loaded_row.title") } internal enum LocationNameRow { /// My Home Assistant internal static let placeholder = L10n.tr("Localizable", "settings.status_section.location_name_row.placeholder") /// Name internal static let title = L10n.tr("Localizable", "settings.status_section.location_name_row.title") } internal enum MobileAppComponentLoadedRow { /// Mobile App Component Loaded internal static let title = L10n.tr("Localizable", "settings.status_section.mobile_app_component_loaded_row.title") } internal enum NotifyPlatformLoadedRow { /// iOS Notify Platform Loaded internal static let title = L10n.tr("Localizable", "settings.status_section.notify_platform_loaded_row.title") } internal enum VersionRow { /// 0.92.0 internal static let placeholder = L10n.tr("Localizable", "settings.status_section.version_row.placeholder") /// Version internal static let title = L10n.tr("Localizable", "settings.status_section.version_row.title") } } } internal enum SettingsDetails { internal enum Actions { /// Actions are used in the Apple Watch app, App Icon Actions and the Today widget internal static let footer = L10n.tr("Localizable", "settings_details.actions.footer") /// Actions internal static let title = L10n.tr("Localizable", "settings_details.actions.title") } internal enum General { /// General internal static let title = L10n.tr("Localizable", "settings_details.general.title") internal enum AppIcon { /// App Icon internal static let title = L10n.tr("Localizable", "settings_details.general.app_icon.title") internal enum Enum { /// Beta internal static let beta = L10n.tr("Localizable", "settings_details.general.app_icon.enum.beta") /// Black internal static let black = L10n.tr("Localizable", "settings_details.general.app_icon.enum.black") /// Blue internal static let blue = L10n.tr("Localizable", "settings_details.general.app_icon.enum.blue") /// Dev internal static let dev = L10n.tr("Localizable", "settings_details.general.app_icon.enum.dev") /// Green internal static let green = L10n.tr("Localizable", "settings_details.general.app_icon.enum.green") /// Old Beta internal static let oldBeta = L10n.tr("Localizable", "settings_details.general.app_icon.enum.old_beta") /// Old Dev internal static let oldDev = L10n.tr("Localizable", "settings_details.general.app_icon.enum.old_dev") /// Old Release internal static let oldRelease = L10n.tr("Localizable", "settings_details.general.app_icon.enum.old_release") /// Orange internal static let orange = L10n.tr("Localizable", "settings_details.general.app_icon.enum.orange") /// Purple internal static let purple = L10n.tr("Localizable", "settings_details.general.app_icon.enum.purple") /// Red internal static let red = L10n.tr("Localizable", "settings_details.general.app_icon.enum.red") /// Release internal static let release = L10n.tr("Localizable", "settings_details.general.app_icon.enum.release") /// White internal static let white = L10n.tr("Localizable", "settings_details.general.app_icon.enum.white") } } internal enum AutohideToolbar { /// Automatically hide toolbar internal static let title = L10n.tr("Localizable", "settings_details.general.autohide_toolbar.title") } internal enum Chrome { /// Open links in Chrome internal static let title = L10n.tr("Localizable", "settings_details.general.chrome.title") } } internal enum Location { /// Location internal static let title = L10n.tr("Localizable", "settings_details.location.title") internal enum Notifications { /// Location Notifications internal static let header = L10n.tr("Localizable", "settings_details.location.notifications.header") internal enum BackgroundFetch { /// Background Fetch Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.background_fetch.title") } internal enum BeaconEnter { /// Enter Zone via iBeacon Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.beacon_enter.title") } internal enum BeaconExit { /// Exit Zone via iBeacon Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.beacon_exit.title") } internal enum Enter { /// Enter Zone Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.enter.title") } internal enum Exit { /// Exit Zone Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.exit.title") } internal enum LocationChange { /// Significant Location Change Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.location_change.title") } internal enum PushNotification { /// Pushed Location Request Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.push_notification.title") } internal enum UrlScheme { /// URL Scheme Location Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.url_scheme.title") } internal enum Visit { /// Visit Location Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.visit.title") } internal enum XCallbackUrl { /// X-Callback-URL Location Notifications internal static let title = L10n.tr("Localizable", "settings_details.location.notifications.x_callback_url.title") } } internal enum Updates { /// Manual location updates can always be triggered internal static let footer = L10n.tr("Localizable", "settings_details.location.updates.footer") /// Update sources internal static let header = L10n.tr("Localizable", "settings_details.location.updates.header") internal enum Background { /// Background fetch internal static let title = L10n.tr("Localizable", "settings_details.location.updates.background.title") } internal enum Notification { /// Push notification request internal static let title = L10n.tr("Localizable", "settings_details.location.updates.notification.title") } internal enum Significant { /// Significant location change internal static let title = L10n.tr("Localizable", "settings_details.location.updates.significant.title") } internal enum Zone { /// Zone enter/exit internal static let title = L10n.tr("Localizable", "settings_details.location.updates.zone.title") } } internal enum Zones { /// To disable location tracking add track_ios: false to each zones settings or under customize. internal static let footer = L10n.tr("Localizable", "settings_details.location.zones.footer") internal enum Beacon { internal enum PropNotSet { /// Not set internal static let value = L10n.tr("Localizable", "settings_details.location.zones.beacon.prop_not_set.value") } } internal enum BeaconMajor { /// iBeacon Major internal static let title = L10n.tr("Localizable", "settings_details.location.zones.beacon_major.title") } internal enum BeaconMinor { /// iBeacon Minor internal static let title = L10n.tr("Localizable", "settings_details.location.zones.beacon_minor.title") } internal enum BeaconUuid { /// iBeacon UUID internal static let title = L10n.tr("Localizable", "settings_details.location.zones.beacon_uuid.title") } internal enum EnterExitTracked { /// Enter/exit tracked internal static let title = L10n.tr("Localizable", "settings_details.location.zones.enter_exit_tracked.title") } internal enum Location { /// Location internal static let title = L10n.tr("Localizable", "settings_details.location.zones.location.title") } internal enum Radius { /// %d m internal static func label(_ p1: Int) -> String { return L10n.tr("Localizable", "settings_details.location.zones.radius.label", p1) } /// Radius internal static let title = L10n.tr("Localizable", "settings_details.location.zones.radius.title") } } } internal enum Notifications { /// Notification internal static let title = L10n.tr("Localizable", "settings_details.notifications.title") internal enum BadgeSection { internal enum Button { /// Reset badge to 0 internal static let title = L10n.tr("Localizable", "settings_details.notifications.badge_section.button.title") } internal enum ResetAlert { /// The badge has been reset to 0. internal static let message = L10n.tr("Localizable", "settings_details.notifications.badge_section.reset_alert.message") /// Badge reset internal static let title = L10n.tr("Localizable", "settings_details.notifications.badge_section.reset_alert.title") } } internal enum Categories { /// Categories internal static let header = L10n.tr("Localizable", "settings_details.notifications.categories.header") } internal enum ImportLegacySettings { internal enum Alert { /// The push notification categories and actions have been imported from the server. internal static let message = L10n.tr("Localizable", "settings_details.notifications.import_legacy_settings.alert.message") /// Server push configuration imported internal static let title = L10n.tr("Localizable", "settings_details.notifications.import_legacy_settings.alert.title") } internal enum Button { /// Import push configuration from server internal static let title = L10n.tr("Localizable", "settings_details.notifications.import_legacy_settings.button.title") } } internal enum NewCategory { /// New Category internal static let title = L10n.tr("Localizable", "settings_details.notifications.new_category.title") } internal enum PromptToOpenUrls { /// Confirm before opening URL internal static let title = L10n.tr("Localizable", "settings_details.notifications.prompt_to_open_urls.title") } internal enum PushIdSection { /// This is the target to use in your Home Assistant configuration. Tap to copy or share. internal static let footer = L10n.tr("Localizable", "settings_details.notifications.push_id_section.footer") /// Push ID internal static let header = L10n.tr("Localizable", "settings_details.notifications.push_id_section.header") /// Not registered for remote notifications internal static let notRegistered = L10n.tr("Localizable", "settings_details.notifications.push_id_section.not_registered") /// Push ID internal static let placeholder = L10n.tr("Localizable", "settings_details.notifications.push_id_section.placeholder") } internal enum Sounds { /// Bundled internal static let bundled = L10n.tr("Localizable", "settings_details.notifications.sounds.bundled") /// Import custom sound internal static let importCustom = L10n.tr("Localizable", "settings_details.notifications.sounds.import_custom") /// Import sounds from iTunes File Sharing internal static let importFileSharing = L10n.tr("Localizable", "settings_details.notifications.sounds.import_file_sharing") /// Import system sounds internal static let importSystem = L10n.tr("Localizable", "settings_details.notifications.sounds.import_system") /// Imported internal static let imported = L10n.tr("Localizable", "settings_details.notifications.sounds.imported") /// System internal static let system = L10n.tr("Localizable", "settings_details.notifications.sounds.system") /// Sounds internal static let title = L10n.tr("Localizable", "settings_details.notifications.sounds.title") internal enum Error { /// Can't build ~/Library/Sounds path: %@ internal static func cantBuildLibrarySoundsPath(_ p1: String) -> String { return L10n.tr("Localizable", "settings_details.notifications.sounds.error.cant_build_library_sounds_path", p1) } /// Can't list directory contents: %@ internal static func cantGetDirectoryContents(_ p1: String) -> String { return L10n.tr("Localizable", "settings_details.notifications.sounds.error.cant_get_directory_contents", p1) } /// Can't access file sharing sounds directory: %@ internal static func cantGetFileSharingPath(_ p1: String) -> String { return L10n.tr("Localizable", "settings_details.notifications.sounds.error.cant_get_file_sharing_path", p1) } /// Failed to convert audio to PCM 32 bit 48khz: %@ internal static func conversionFailed(_ p1: String) -> String { return L10n.tr("Localizable", "settings_details.notifications.sounds.error.conversion_failed", p1) } /// Failed to copy file: %@ internal static func copyError(_ p1: String) -> String { return L10n.tr("Localizable", "settings_details.notifications.sounds.error.copy_error", p1) } /// Failed to delete file: %@ internal static func deleteError(_ p1: String) -> String { return L10n.tr("Localizable", "settings_details.notifications.sounds.error.delete_error", p1) } } internal enum ImportedAlert { /// %d sounds were imported. Please restart your phone to complete the import. internal static func message(_ p1: Int) -> String { return L10n.tr("Localizable", "settings_details.notifications.sounds.imported_alert.message", p1) } /// Sounds Imported internal static let title = L10n.tr("Localizable", "settings_details.notifications.sounds.imported_alert.title") } } internal enum SoundsSection { /// Custom push notification sounds can be added via iTunes. internal static let footer = L10n.tr("Localizable", "settings_details.notifications.sounds_section.footer") internal enum Button { /// Import Sounds internal static let title = L10n.tr("Localizable", "settings_details.notifications.sounds_section.button.title") } internal enum ImportedAlert { /// %d sounds were imported. Please restart your phone to complete the import. internal static func message(_ p1: Int) -> String { return L10n.tr("Localizable", "settings_details.notifications.sounds_section.imported_alert.message", p1) } /// Sounds Imported internal static let title = L10n.tr("Localizable", "settings_details.notifications.sounds_section.imported_alert.title") } } internal enum UpdateSection { /// Updating push settings will request the latest push actions and categories from Home Assistant. internal static let footer = L10n.tr("Localizable", "settings_details.notifications.update_section.footer") internal enum Button { /// Update push settings internal static let title = L10n.tr("Localizable", "settings_details.notifications.update_section.button.title") } internal enum UpdatedAlert { /// Push settings imported from Home Assistant. internal static let message = L10n.tr("Localizable", "settings_details.notifications.update_section.updated_alert.message") /// Settings Imported internal static let title = L10n.tr("Localizable", "settings_details.notifications.update_section.updated_alert.title") } } } internal enum Privacy { /// Privacy internal static let title = L10n.tr("Localizable", "settings_details.privacy.title") internal enum Analytics { /// Allows collection of basic information about your device and interactions with the app. No user identifiable data is shared with Google, including your Home Assistant URLs and tokens. You must restart the app for changes to this setting to take effect. internal static let description = L10n.tr("Localizable", "settings_details.privacy.analytics.description") /// Google Analytics internal static let title = L10n.tr("Localizable", "settings_details.privacy.analytics.title") } internal enum Crashlytics { /// Crashlytics allows for deeper tracking of crashes and other errors in the app, leading to faster fixes being published. No user identifiable information is sent, other than basic device information. You must restart the app for changes to this setting to take effect. internal static let description = L10n.tr("Localizable", "settings_details.privacy.crashlytics.description") /// Firebase Crashlytics internal static let title = L10n.tr("Localizable", "settings_details.privacy.crashlytics.title") } internal enum Messaging { /// Firebase Cloud Messaging must be enabled for push notifications to function. internal static let description = L10n.tr("Localizable", "settings_details.privacy.messaging.description") /// Firebase Cloud Messaging internal static let title = L10n.tr("Localizable", "settings_details.privacy.messaging.title") } internal enum PerformanceMonitoring { /// Firebase Performance Monitoring allows for remote monitoring of overall application performance, allowing for speed improvements to be made more easily. You must restart the app for changes to this setting to take effect. internal static let description = L10n.tr("Localizable", "settings_details.privacy.performance_monitoring.description") /// Firebase Performance Monitoring internal static let title = L10n.tr("Localizable", "settings_details.privacy.performance_monitoring.title") } } internal enum Siri { /// Siri Shortcuts internal static let title = L10n.tr("Localizable", "settings_details.siri.title") internal enum Section { /// Generic Shortcuts internal static let title = L10n.tr("Localizable", "settings_details.siri.section.title") internal enum Existing { /// Existing Shortcuts internal static let title = L10n.tr("Localizable", "settings_details.siri.section.existing.title") } internal enum Generic { /// Generic Shortcuts internal static let title = L10n.tr("Localizable", "settings_details.siri.section.generic.title") } internal enum Services { /// Services internal static let title = L10n.tr("Localizable", "settings_details.siri.section.services.title") } } } internal enum Watch { /// Apple Watch internal static let title = L10n.tr("Localizable", "settings_details.watch.title") internal enum RemainingSends { /// Remaining sends internal static let title = L10n.tr("Localizable", "settings_details.watch.remaining_sends.title") } internal enum SendNow { /// Send now internal static let title = L10n.tr("Localizable", "settings_details.watch.send_now.title") } } } internal enum SiriShortcuts { internal enum Configurator { internal enum Fields { /// Use default value internal static let useDefaultValue = L10n.tr("Localizable", "siri_shortcuts.configurator.fields.use_default_value") /// Use suggested value internal static let useSuggestedValue = L10n.tr("Localizable", "siri_shortcuts.configurator.fields.use_suggested_value") internal enum Section { /// Suggested: %@ internal static func footer(_ p1: String) -> String { return L10n.tr("Localizable", "siri_shortcuts.configurator.fields.section.footer", p1) } /// Fields internal static let header = L10n.tr("Localizable", "siri_shortcuts.configurator.fields.section.header") } } internal enum FireEvent { internal enum Configuration { /// Configuration internal static let header = L10n.tr("Localizable", "siri_shortcuts.configurator.fire_event.configuration.header") } internal enum Rows { internal enum Name { /// Event Name internal static let title = L10n.tr("Localizable", "siri_shortcuts.configurator.fire_event.rows.name.title") } internal enum Payload { /// Must be valid JSON. If no payload is provided, clipboard contents will be used. internal static let placeholder = L10n.tr("Localizable", "siri_shortcuts.configurator.fire_event.rows.payload.placeholder") /// Event Payload internal static let title = L10n.tr("Localizable", "siri_shortcuts.configurator.fire_event.rows.payload.title") } } } internal enum Settings { /// Settings internal static let header = L10n.tr("Localizable", "siri_shortcuts.configurator.settings.header") internal enum Name { /// Shortcut name internal static let title = L10n.tr("Localizable", "siri_shortcuts.configurator.settings.name.title") } internal enum NotifyOnRun { /// Send notification when run internal static let title = L10n.tr("Localizable", "siri_shortcuts.configurator.settings.notify_on_run.title") } } } internal enum Intents { internal enum FireEvent { /// Fire Event internal static let title = L10n.tr("Localizable", "siri_shortcuts.intents.fire_event.title") } internal enum GetCameraImage { /// Get Camera Image internal static let title = L10n.tr("Localizable", "siri_shortcuts.intents.get_camera_image.title") } internal enum RenderTemplate { /// Render Template internal static let title = L10n.tr("Localizable", "siri_shortcuts.intents.render_template.title") } internal enum SendLocation { /// Send Location internal static let title = L10n.tr("Localizable", "siri_shortcuts.intents.send_location.title") } } } internal enum TokenError { /// Connection failed. internal static let connectionFailed = L10n.tr("Localizable", "token_error.connection_failed") /// Token is expired. internal static let expired = L10n.tr("Localizable", "token_error.expired") /// Token is unavailable. internal static let tokenUnavailable = L10n.tr("Localizable", "token_error.token_unavailable") } internal enum UrlHandler { internal enum CallService { internal enum Error { /// An error occurred while attempting to call service %@: %@ internal static func message(_ p1: String, _ p2: String) -> String { return L10n.tr("Localizable", "url_handler.call_service.error.message", p1, p2) } } internal enum Success { /// Successfully called %@ internal static func message(_ p1: String) -> String { return L10n.tr("Localizable", "url_handler.call_service.success.message", p1) } /// Called service internal static let title = L10n.tr("Localizable", "url_handler.call_service.success.title") } } internal enum Error { /// Error internal static let title = L10n.tr("Localizable", "url_handler.error.title") } internal enum FireEvent { internal enum Error { /// An error occurred while attempting to fire event %@: %@ internal static func message(_ p1: String, _ p2: String) -> String { return L10n.tr("Localizable", "url_handler.fire_event.error.message", p1, p2) } } internal enum Success { /// Successfully fired event %@ internal static func message(_ p1: String) -> String { return L10n.tr("Localizable", "url_handler.fire_event.success.message", p1) } /// Fired event internal static let title = L10n.tr("Localizable", "url_handler.fire_event.success.title") } } internal enum NoService { /// %@ is not a valid route internal static func message(_ p1: String) -> String { return L10n.tr("Localizable", "url_handler.no_service.message", p1) } } internal enum SendLocation { internal enum Error { /// An unknown error occurred while attempting to send location: %@ internal static func message(_ p1: String) -> String { return L10n.tr("Localizable", "url_handler.send_location.error.message", p1) } } internal enum Success { /// Sent a one shot location internal static let message = L10n.tr("Localizable", "url_handler.send_location.success.message") /// Sent location internal static let title = L10n.tr("Localizable", "url_handler.send_location.success.title") } } internal enum XCallbackUrl { internal enum Error { /// eventName must be defined internal static let eventNameMissing = L10n.tr("Localizable", "url_handler.x_callback_url.error.eventNameMissing") /// A general error occurred internal static let general = L10n.tr("Localizable", "url_handler.x_callback_url.error.general") /// service (e.g. homeassistant.turn_on) must be defined internal static let serviceMissing = L10n.tr("Localizable", "url_handler.x_callback_url.error.serviceMissing") /// A renderable template must be defined internal static let templateMissing = L10n.tr("Localizable", "url_handler.x_callback_url.error.templateMissing") } } } internal enum Watch { internal enum Configurator { internal enum Rows { internal enum Color { /// Color internal static let title = L10n.tr("Localizable", "watch.configurator.rows.color.title") } internal enum FractionalValue { /// Fractional value internal static let title = L10n.tr("Localizable", "watch.configurator.rows.fractional_value.title") } internal enum Gauge { /// Gauge internal static let title = L10n.tr("Localizable", "watch.configurator.rows.gauge.title") internal enum Color { /// Color internal static let title = L10n.tr("Localizable", "watch.configurator.rows.gauge.color.title") } internal enum GaugeType { /// Type internal static let title = L10n.tr("Localizable", "watch.configurator.rows.gauge.gauge_type.title") internal enum Options { /// Closed internal static let closed = L10n.tr("Localizable", "watch.configurator.rows.gauge.gauge_type.options.closed") /// Open internal static let `open` = L10n.tr("Localizable", "watch.configurator.rows.gauge.gauge_type.options.open") } } internal enum Style { /// Style internal static let title = L10n.tr("Localizable", "watch.configurator.rows.gauge.style.title") internal enum Options { /// Fill internal static let fill = L10n.tr("Localizable", "watch.configurator.rows.gauge.style.options.fill") /// Ring internal static let ring = L10n.tr("Localizable", "watch.configurator.rows.gauge.style.options.ring") } } } internal enum Icon { internal enum Choose { /// Choose an icon internal static let title = L10n.tr("Localizable", "watch.configurator.rows.icon.choose.title") } internal enum Color { /// Color internal static let title = L10n.tr("Localizable", "watch.configurator.rows.icon.color.title") } } internal enum Ring { /// Ring internal static let title = L10n.tr("Localizable", "watch.configurator.rows.ring.title") internal enum Color { /// Color internal static let title = L10n.tr("Localizable", "watch.configurator.rows.ring.color.title") } internal enum RingType { /// Type internal static let title = L10n.tr("Localizable", "watch.configurator.rows.ring.ring_type.title") internal enum Options { /// Closed internal static let closed = L10n.tr("Localizable", "watch.configurator.rows.ring.ring_type.options.closed") /// Open internal static let `open` = L10n.tr("Localizable", "watch.configurator.rows.ring.ring_type.options.open") } } internal enum Value { /// Fractional value internal static let title = L10n.tr("Localizable", "watch.configurator.rows.ring.value.title") } } internal enum Row2Alignment { /// Row 2 Alignment internal static let title = L10n.tr("Localizable", "watch.configurator.rows.row_2_alignment.title") internal enum Options { /// Leading internal static let leading = L10n.tr("Localizable", "watch.configurator.rows.row_2_alignment.options.leading") /// Trailing internal static let trailing = L10n.tr("Localizable", "watch.configurator.rows.row_2_alignment.options.trailing") } } internal enum Style { /// Style internal static let title = L10n.tr("Localizable", "watch.configurator.rows.style.title") } internal enum Template { /// Choose a template internal static let selectorTitle = L10n.tr("Localizable", "watch.configurator.rows.template.selector_title") /// Template internal static let title = L10n.tr("Localizable", "watch.configurator.rows.template.title") } } internal enum Sections { internal enum Gauge { /// The gauge to display in the complication. internal static let footer = L10n.tr("Localizable", "watch.configurator.sections.gauge.footer") /// Gauge internal static let header = L10n.tr("Localizable", "watch.configurator.sections.gauge.header") } internal enum Icon { /// The image to display in the complication. internal static let footer = L10n.tr("Localizable", "watch.configurator.sections.icon.footer") /// Icon internal static let header = L10n.tr("Localizable", "watch.configurator.sections.icon.header") } internal enum Ring { /// The ring showing progress surrounding the text. internal static let footer = L10n.tr("Localizable", "watch.configurator.sections.ring.footer") /// Ring internal static let header = L10n.tr("Localizable", "watch.configurator.sections.ring.header") } } } internal enum Labels { /// No actions configured. Configure actions on your phone to dismiss this message. internal static let noAction = L10n.tr("Localizable", "watch.labels.no_action") internal enum ComplicationGroup { internal enum CircularSmall { /// Use circular small complications to display content in the corners of the Color watch face. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group.circular_small.description") /// Circular Small internal static let name = L10n.tr("Localizable", "watch.labels.complication_group.circular_small.name") } internal enum ExtraLarge { /// Use the extra large complications to display content on the X-Large watch faces. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group.extra_large.description") /// Extra Large internal static let name = L10n.tr("Localizable", "watch.labels.complication_group.extra_large.name") } internal enum Graphic { /// Use graphic complications to display visually rich content in the Infograph and Infograph Modular clock faces. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group.graphic.description") /// Graphic internal static let name = L10n.tr("Localizable", "watch.labels.complication_group.graphic.name") } internal enum Modular { /// Use modular small complications to display content in the Modular watch face. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group.modular.description") /// Modular internal static let name = L10n.tr("Localizable", "watch.labels.complication_group.modular.name") } internal enum Utilitarian { /// Use the utilitarian complications to display content in the Utility, Motion, Mickey Mouse, and Minnie Mouse watch faces. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group.utilitarian.description") /// Utilitarian internal static let name = L10n.tr("Localizable", "watch.labels.complication_group.utilitarian.name") } } internal enum ComplicationGroupMember { internal enum CircularSmall { /// A small circular area used in the Color clock face. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.circular_small.description") /// Circular Small internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.circular_small.name") /// Circular Small internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.circular_small.short_name") } internal enum ExtraLarge { /// A large square area used in the X-Large clock face. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.extra_large.description") /// Extra Large internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.extra_large.name") /// Extra Large internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.extra_large.short_name") } internal enum GraphicBezel { /// A small square area used in the Modular clock face. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_bezel.description") /// Graphic Bezel internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_bezel.name") /// Bezel internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_bezel.short_name") } internal enum GraphicCircular { /// A large rectangular area used in the Modular clock face. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_circular.description") /// Graphic Circular internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_circular.name") /// Circular internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_circular.short_name") } internal enum GraphicCorner { /// A small square or rectangular area used in the Utility, Mickey, Chronograph, and Simple clock faces. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_corner.description") /// Graphic Corner internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_corner.name") /// Corner internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_corner.short_name") } internal enum GraphicRectangular { /// A small rectangular area used in the in the Photos, Motion, and Timelapse clock faces. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_rectangular.description") /// Graphic Rectangular internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_rectangular.name") /// Rectangular internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.graphic_rectangular.short_name") } internal enum ModularLarge { /// A large rectangular area that spans the width of the screen in the Utility and Mickey clock faces. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.modular_large.description") /// Modular Large internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.modular_large.name") /// Large internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.modular_large.short_name") } internal enum ModularSmall { /// A curved area that fills the corners in the Infograph clock face. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.modular_small.description") /// Modular Small internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.modular_small.name") /// Small internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.modular_small.short_name") } internal enum UtilitarianLarge { /// A circular area used in the Infograph and Infograph Modular clock faces. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.utilitarian_large.description") /// Utilitarian Large internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.utilitarian_large.name") /// Large internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.utilitarian_large.short_name") } internal enum UtilitarianSmall { /// A circular area with optional curved text placed along the bezel of the Infograph clock face. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.utilitarian_small.description") /// Utilitarian Small internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.utilitarian_small.name") /// Small internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.utilitarian_small.short_name") } internal enum UtilitarianSmallFlat { /// A large rectangular area used in the Infograph Modular clock face. internal static let description = L10n.tr("Localizable", "watch.labels.complication_group_member.utilitarian_small_flat.description") /// Utilitarian Small Flat internal static let name = L10n.tr("Localizable", "watch.labels.complication_group_member.utilitarian_small_flat.name") /// Small Flat internal static let shortName = L10n.tr("Localizable", "watch.labels.complication_group_member.utilitarian_small_flat.short_name") } } internal enum ComplicationTemplate { internal enum CircularSmallRingImage { /// A template for displaying a single image surrounded by a configurable progress ring. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.circular_small_ring_image.description") } internal enum CircularSmallRingText { /// A template for displaying a short text string encircled by a configurable progress ring. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.circular_small_ring_text.description") } internal enum CircularSmallSimpleImage { /// A template for displaying a single image. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.circular_small_simple_image.description") } internal enum CircularSmallSimpleText { /// A template for displaying a short text string. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.circular_small_simple_text.description") } internal enum CircularSmallStackImage { /// A template for displaying an image with a line of text below it. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.circular_small_stack_image.description") } internal enum CircularSmallStackText { /// A template for displaying two text strings stacked on top of each other. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.circular_small_stack_text.description") } internal enum ExtraLargeColumnsText { /// A template for displaying two rows and two columns of text. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.extra_large_columns_text.description") } internal enum ExtraLargeRingImage { /// A template for displaying an image encircled by a configurable progress ring. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.extra_large_ring_image.description") } internal enum ExtraLargeRingText { /// A template for displaying text encircled by a configurable progress ring. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.extra_large_ring_text.description") } internal enum ExtraLargeSimpleImage { /// A template for displaying an image. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.extra_large_simple_image.description") } internal enum ExtraLargeSimpleText { /// A template for displaying a small amount of text internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.extra_large_simple_text.description") } internal enum ExtraLargeStackImage { /// A template for displaying a single image with a short line of text below it. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.extra_large_stack_image.description") } internal enum ExtraLargeStackText { /// A template for displaying two strings stacked one on top of the other. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.extra_large_stack_text.description") } internal enum GraphicBezelCircularText { /// A template for displaying a circular complication with text along the bezel. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_bezel_circular_text.description") } internal enum GraphicCircularClosedGaugeImage { /// A template for displaying a full-color circular image and a closed circular gauge. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_circular_closed_gauge_image.description") } internal enum GraphicCircularClosedGaugeText { /// A template for displaying text inside a closed circular gauge. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_circular_closed_gauge_text.description") } internal enum GraphicCircularImage { /// A template for displaying a full-color circular image. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_circular_image.description") } internal enum GraphicCircularOpenGaugeImage { /// A template for displaying a full-color circular image, an open gauge, and text. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_circular_open_gauge_image.description") } internal enum GraphicCircularOpenGaugeRangeText { /// A template for displaying text inside an open gauge, with leading and trailing text for the gauge. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_circular_open_gauge_range_text.description") } internal enum GraphicCircularOpenGaugeSimpleText { /// A template for displaying text inside an open gauge, with a single piece of text for the gauge. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_circular_open_gauge_simple_text.description") } internal enum GraphicCornerCircularImage { /// A template for displaying an image in the clock face’s corner. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_corner_circular_image.description") } internal enum GraphicCornerGaugeImage { /// A template for displaying an image and a gauge in the clock face’s corner. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_corner_gauge_image.description") } internal enum GraphicCornerGaugeText { /// A template for displaying text and a gauge in the clock face’s corner. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_corner_gauge_text.description") } internal enum GraphicCornerStackText { /// A template for displaying stacked text in the clock face’s corner. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_corner_stack_text.description") } internal enum GraphicCornerTextImage { /// A template for displaying an image and text in the clock face’s corner. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_corner_text_image.description") } internal enum GraphicRectangularLargeImage { /// A template for displaying a large rectangle containing header text and an image. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_rectangular_large_image.description") } internal enum GraphicRectangularStandardBody { /// A template for displaying a large rectangle containing text. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_rectangular_standard_body.description") } internal enum GraphicRectangularTextGauge { /// A template for displaying a large rectangle containing text and a gauge. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.graphic_rectangular_text_gauge.description") } internal enum ModularLargeColumns { /// A template for displaying multiple columns of data. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_large_columns.description") } internal enum ModularLargeStandardBody { /// A template for displaying a header row and two lines of text internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_large_standard_body.description") } internal enum ModularLargeTable { /// A template for displaying a header row and columns internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_large_table.description") } internal enum ModularLargeTallBody { /// A template for displaying a header row and a tall row of body text. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_large_tall_body.description") } internal enum ModularSmallColumnsText { /// A template for displaying two rows and two columns of text internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_small_columns_text.description") } internal enum ModularSmallRingImage { /// A template for displaying an image encircled by a configurable progress ring internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_small_ring_image.description") } internal enum ModularSmallRingText { /// A template for displaying text encircled by a configurable progress ring internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_small_ring_text.description") } internal enum ModularSmallSimpleImage { /// A template for displaying an image. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_small_simple_image.description") } internal enum ModularSmallSimpleText { /// A template for displaying a small amount of text. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_small_simple_text.description") } internal enum ModularSmallStackImage { /// A template for displaying a single image with a short line of text below it. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_small_stack_image.description") } internal enum ModularSmallStackText { /// A template for displaying two strings stacked one on top of the other. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.modular_small_stack_text.description") } internal enum Style { /// Circular Image internal static let circularImage = L10n.tr("Localizable", "watch.labels.complication_template.style.circular_image") /// Circular Text internal static let circularText = L10n.tr("Localizable", "watch.labels.complication_template.style.circular_text") /// Closed Gauge Image internal static let closedGaugeImage = L10n.tr("Localizable", "watch.labels.complication_template.style.closed_gauge_image") /// Closed Gauge Text internal static let closedGaugeText = L10n.tr("Localizable", "watch.labels.complication_template.style.closed_gauge_text") /// Columns internal static let columns = L10n.tr("Localizable", "watch.labels.complication_template.style.columns") /// Columns Text internal static let columnsText = L10n.tr("Localizable", "watch.labels.complication_template.style.columns_text") /// Flat internal static let flat = L10n.tr("Localizable", "watch.labels.complication_template.style.flat") /// Gauge Image internal static let gaugeImage = L10n.tr("Localizable", "watch.labels.complication_template.style.gauge_image") /// Gauge Text internal static let gaugeText = L10n.tr("Localizable", "watch.labels.complication_template.style.gauge_text") /// Large Image internal static let largeImage = L10n.tr("Localizable", "watch.labels.complication_template.style.large_image") /// Open Gauge Image internal static let openGaugeImage = L10n.tr("Localizable", "watch.labels.complication_template.style.open_gauge_image") /// Open Gauge Range Text internal static let openGaugeRangeText = L10n.tr("Localizable", "watch.labels.complication_template.style.open_gauge_range_text") /// Open Gauge Simple Text internal static let openGaugeSimpleText = L10n.tr("Localizable", "watch.labels.complication_template.style.open_gauge_simple_text") /// Ring Image internal static let ringImage = L10n.tr("Localizable", "watch.labels.complication_template.style.ring_image") /// Ring Text internal static let ringText = L10n.tr("Localizable", "watch.labels.complication_template.style.ring_text") /// Simple Image internal static let simpleImage = L10n.tr("Localizable", "watch.labels.complication_template.style.simple_image") /// Simple Text internal static let simpleText = L10n.tr("Localizable", "watch.labels.complication_template.style.simple_text") /// Square internal static let square = L10n.tr("Localizable", "watch.labels.complication_template.style.square") /// Stack Image internal static let stackImage = L10n.tr("Localizable", "watch.labels.complication_template.style.stack_image") /// Stack Text internal static let stackText = L10n.tr("Localizable", "watch.labels.complication_template.style.stack_text") /// Standard Body internal static let standardBody = L10n.tr("Localizable", "watch.labels.complication_template.style.standard_body") /// Table internal static let table = L10n.tr("Localizable", "watch.labels.complication_template.style.table") /// Tall Body internal static let tallBody = L10n.tr("Localizable", "watch.labels.complication_template.style.tall_body") /// Text Gauge internal static let textGauge = L10n.tr("Localizable", "watch.labels.complication_template.style.text_gauge") /// Text Image internal static let textImage = L10n.tr("Localizable", "watch.labels.complication_template.style.text_image") } internal enum UtilitarianLargeFlat { /// A template for displaying an image and string in a single long line. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.utilitarian_large_flat.description") } internal enum UtilitarianSmallFlat { /// A template for displaying an image and text in a single line. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.utilitarian_small_flat.description") } internal enum UtilitarianSmallRingImage { /// A template for displaying an image encircled by a configurable progress ring internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.utilitarian_small_ring_image.description") } internal enum UtilitarianSmallRingText { /// A template for displaying text encircled by a configurable progress ring. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.utilitarian_small_ring_text.description") } internal enum UtilitarianSmallSquare { /// A template for displaying a single square image. internal static let description = L10n.tr("Localizable", "watch.labels.complication_template.utilitarian_small_square.description") } } internal enum ComplicationTextAreas { internal enum Body1 { /// The main body text to display in the complication. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.body1.description") /// Body 1 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.body1.label") } internal enum Body2 { /// The secondary body text to display in the complication. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.body2.description") /// Body 2 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.body2.label") } internal enum Bottom { /// The text to display at the bottom of the gauge. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.bottom.description") /// Bottom internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.bottom.label") } internal enum Center { /// The text to display in the complication. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.center.description") /// Center internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.center.label") } internal enum Header { /// The header text to display in the complication. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.header.description") /// Header internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.header.label") } internal enum Inner { /// The inner text to display in the complication. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.inner.description") /// Inner internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.inner.label") } internal enum InsideRing { /// The text to display in the ring of the complication. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.inside_ring.description") /// Inside Ring internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.inside_ring.label") } internal enum Leading { /// The text to display on the leading edge of the gauge. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.leading.description") /// Leading internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.leading.label") } internal enum Line1 { /// The text to display on the top line of the complication. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.line1.description") /// Line 1 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.line1.label") } internal enum Line2 { /// The text to display on the bottom line of the complication. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.line2.description") /// Line 2 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.line2.label") } internal enum Outer { /// The outer text to display in the complication. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.outer.description") /// Outer internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.outer.label") } internal enum Row1Column1 { /// The text to display in the first column of the first row. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.row1_column1.description") /// Row 1, Column 1 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.row1_column1.label") } internal enum Row1Column2 { /// The text to display in the second column of the first row. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.row1_column2.description") /// Row 1, Column 2 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.row1_column2.label") } internal enum Row2Column1 { /// The text to display in the first column of the second row. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.row2_column1.description") /// Row 2, Column 1 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.row2_column1.label") } internal enum Row2Column2 { /// The text to display in the second column of the second row. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.row2_column2.description") /// Row 2, Column 2 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.row2_column2.label") } internal enum Row3Column1 { /// The text to display in the first column of the third row. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.row3_column1.description") /// Row 3, Column 1 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.row3_column1.label") } internal enum Row3Column2 { /// The text to display in the second column of the third row. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.row3_column2.description") /// Row 3, Column 2 internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.row3_column2.label") } internal enum Trailing { /// The text to display on the trailing edge of the gauge. internal static let description = L10n.tr("Localizable", "watch.labels.complication_text_areas.trailing.description") /// Trailing internal static let label = L10n.tr("Localizable", "watch.labels.complication_text_areas.trailing.label") } } } } } // swiftlint:enable explicit_type_interface function_parameter_count identifier_name line_length // swiftlint:enable nesting type_body_length type_name // MARK: - Implementation Details extension L10n { private static func tr(_ table: String, _ key: String, _ args: CVarArg...) -> String { // swiftlint:disable:next nslocalizedstring_key let format = NSLocalizedString(key, tableName: table, bundle: Bundle(for: BundleToken.self), comment: "") return String(format: format, locale: Locale.current, arguments: args) } } private final class BundleToken {}
54.468969
279
0.681902
f7d8746d4a942d891c9d89c867bb0e2ada281b79
2,251
import XCTest @testable import DispatchTimer final class DispatchTimerTests: XCTestCase { func testNonRepeatingTimer() throws { let ex = expectation(description: "Should have fired timer") let timer = DispatchTimer(.milliseconds(50), block: { ex.fulfill() }) wait(for: [ex], timeout: 0.2) timer.invalidate() } func testRepeatingTimer() throws { let ex = expectation(description: "Should have fired timer") ex.expectedFulfillmentCount = 3 ex.assertForOverFulfill = false let timer = DispatchTimer( .milliseconds(50), repeat: true, block: { ex.fulfill() } ) wait(for: [ex], timeout: 0.4) timer.invalidate() } func testFireAtTimer() throws { let ex = expectation(description: "Should have fired timer") let timeToFire = DispatchTime.now() + .milliseconds(50) let timer = DispatchTimer( fireAt: timeToFire, block: { ex.fulfill() } ) XCTAssertEqual(timeToFire, timer.nextDeadline) wait(for: [ex], timeout: 0.2) timer.invalidate() } func testInvalidateCancelsTimer() throws { let ex = expectation(description: "Should not have fired timer") ex.isInverted = true let timer = DispatchTimer(.milliseconds(50), block: { ex.fulfill() }) timer.invalidate() wait(for: [ex], timeout: 0.2) timer.invalidate() } func testFireAtInPastFiresImmediately() throws { let ex = expectation(description: "Should have fired timer") let timeToFire = DispatchTime.now() - .milliseconds(50) let timer = DispatchTimer( fireAt: timeToFire, block: { ex.fulfill() } ) XCTAssertEqual(timeToFire, timer.nextDeadline) wait(for: [ex], timeout: 0.1) timer.invalidate() } static var allTests = [ ("testNonRepeatingTimer", testNonRepeatingTimer), ("testRepeatingTimer", testRepeatingTimer), ("testFireAtTimer", testFireAtTimer), ("testInvalidateCancelsTimer", testInvalidateCancelsTimer), ("testFireAtInPastFiresImmediately", testFireAtInPastFiresImmediately), ] }
34.106061
79
0.618836
90d3c627b683f2877efbd8c344c3e14fe1b861ff
1,333
// // LandmarkList.swift // Drawing-and-Animation // // Created by Willie on 2019/10/11. // import SwiftUI struct LandmarkList: View { @EnvironmentObject private var userData: UserData var body: some View { NavigationView { List { Toggle(isOn: $userData.showFavoritesOnly) { Text("Show Favorites Only") } ForEach(userData.landmarks) { landmark in if !self.userData.showFavoritesOnly || landmark.isFavorite { NavigationLink( destination: LandmarkDetail(landmark: landmark) .environmentObject(self.userData) ) { LandmarkRow(landmark: landmark) } } } } .navigationBarTitle(Text("Landmarks")) } } } struct LandmarksList_Previews: PreviewProvider { static var previews: some View { ForEach(["iPhone SE", "iPhone XS Max"], id: \.self) { deviceName in LandmarkList() .previewDevice(PreviewDevice(rawValue: deviceName)) .previewDisplayName(deviceName) } .environmentObject(UserData()) } }
28.978261
80
0.505626
67c17945d8055d1c7ad4aff3c2ee30132d617e28
2,281
// // NavigationCoordinator.swift // Octotorp // import UIKit final class NavigationCoordinator: ICoordinator { // Dependencies private weak var transitionHandler: IRootContainer? func start(transitionHandler: IRootContainer?) { self.transitionHandler = transitionHandler showSearch() } func start(transitionHandler: IRootContainer?, route: Route?) { guard let route = route else { return start(transitionHandler: transitionHandler) } self.transitionHandler = transitionHandler self.transitionHandler?.hideHub(animated: true) showNavigationAnnouncement(for: route) } // MARK: - Private private func showSearch() { let assembly = SearchAssembly() let controller = assembly.assemble { [weak self] result, controller in self?.transitionHandler?.hideHub(animated: true) controller.dismiss(animated: true) self?.showRoutePicker(for: result) } transitionHandler?.present(controller, animated: true) } private func showRoutePicker(for searchResult: SearchResultItem) { guard let container = transitionHandler else { return } let assembly = RoutePickerAssembly() let controller = assembly.assemble(direction: searchResult, container: container) { [weak self] output in switch output { case .selected(let route): self?.showNavigationAnnouncement(for: route) self?.transitionHandler?.removeWidget(.bottom, animated: true) case .close: self?.transitionHandler?.showHub(animated: true) self?.transitionHandler?.removeWidget(.top, animated: true) self?.transitionHandler?.removeWidget(.bottom, animated: true) case .changeDeparture: break } } transitionHandler?.set(widget: controller, as: .top, animated: true) } private func showNavigationAnnouncement(for route: Route) { let assembly = AnnouncementsAssembly() let controller = assembly.assemble(route: route, output: transitionHandler) transitionHandler?.set(widget: controller, as: .top, animated: true) } }
33.057971
113
0.646646
5022b3fc5ad9e62f6093768a4b0ce5bea30b6db8
1,355
// // RecentOrderCell.swift // DiberCourier // // Created by Alexander Tereshkov on 2/4/18. // Copyright © 2018 Diber. All rights reserved. // import UIKit protocol RecentOrderCellDelegate : class { } class RecentOrderCell: UITableViewCell { @IBOutlet weak var fromLabel: UILabel! @IBOutlet weak var toLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var dateTimeLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var icon: UIImageView! weak var delegate: RecentOrderCellDelegate? //MARK:- Lifecycle override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() icon.image = nil } //MARK:- Public public func bind(with item: OrderView) { fromLabel.text = item.addressFrom.address toLabel.text = item.addressTo.address descriptionLabel.text = item.descr dateTimeLabel.text = item.date.toString() /* switch item.status { case "In progress": icon.image = #imageLiteral(resourceName: "ic_swap") case "New": icon.image = #imageLiteral(resourceName: "ic_new") default: icon.image = nil } */ } }
23.362069
63
0.613284
f43f5f129c28bf80d51e8a0f8f740d406a38b90b
2,808
// // BWMTRefreshView.swift // BTStudioWeiBo // // Created by hadlinks on 2019/4/17. // Copyright © 2019 BTStudio. All rights reserved. // import UIKit /// 美团外卖 下拉刷新控件 class BWMTRefreshView: BWRefreshView { /// 建筑背景图片 @IBOutlet weak var buildingImageView: UIImageView! /// 袋鼠图片 @IBOutlet weak var kangarooImageView: UIImageView! /// 地球图片 @IBOutlet weak var earthImageView: UIImageView! /// 父视图高度 override var parentViewHeight: CGFloat { didSet { // print("父视图高度: \(parentViewHeight)") if parentViewHeight < 23 { return } // 23 -> 126 (比例: 0.2 -> 1.0) var scale: CGFloat = 1.0 if parentViewHeight > 126 { scale = 1 } else { scale = 1.0 - (126 - parentViewHeight) / (126 - 23) } kangarooImageView.transform = CGAffineTransform(scaleX: scale, y: scale) } } override func awakeFromNib() { // 1. 建筑动画 (序列帧) if let building1Image = UIImage(named: "icon_building_loading_1"), let building2Image = UIImage(named: "icon_building_loading_2") { buildingImageView.image = UIImage.animatedImage(with: [building1Image, building2Image], duration: 0.5) } // 2. 袋鼠动画 (序列帧+缩放) if let kangarooImage1 = UIImage(named: "icon_small_kangaroo_loading_1"), let kangarooImage2 = UIImage(named: "icon_small_kangaroo_loading_2") { kangarooImageView.image = UIImage.animatedImage(with: [kangarooImage1, kangarooImage2], duration: 0.4) } // 设置锚点 kangarooImageView.layer.anchorPoint = CGPoint(x: 0.5, y: 1) // 设置frame let x = self.bounds.width * 0.5 let y = self.bounds.height - 36 kangarooImageView.center = CGPoint(x: x, y: y) kangarooImageView.transform = CGAffineTransform(scaleX: 0.2, y: 0.2) // 3. 地球旋转动画 let animation = CABasicAnimation(keyPath: "transform.rotation") animation.toValue = -2 * Double.pi animation.repeatCount = HUGE animation.duration = 1.5 animation.isRemovedOnCompletion = false earthImageView.layer.add(animation, forKey: nil) } override class func refreshView() -> BWMTRefreshView { let nib = UINib(nibName: "BWMTRefreshView", bundle: nil) let view = nib.instantiate(withOwner: nil, options: nil)[0] as! BWMTRefreshView return view } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
31.2
114
0.590812