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
2640a616a14dfd11aba0fa3771735446abf55be2
1,008
// // CodingKeysConverter.swift // CleanJSON // // Created by Pircate([email protected]) on 2020/7/21 // Copyright © 2020 Pircate. All rights reserved. // import Foundation public typealias CodingPath = [String] public extension JSONDecoder.KeyDecodingStrategy { static func mapper(_ container: [CodingPath: String]) -> JSONDecoder.KeyDecodingStrategy { .custom { CodingKeysConverter(container).callAsFunction($0) } } } struct CodingKeysConverter { let container: [CodingPath: String] init(_ container: [CodingPath: String]) { self.container = container } func callAsFunction(_ codingPath: [CodingKey]) -> CodingKey { guard !codingPath.isEmpty else { return CleanJSONKey.super } let stringKeys = codingPath.map { $0.stringValue } guard container.keys.contains(stringKeys) else { return codingPath.last! } return CleanJSONKey(stringValue: container[stringKeys]!, intValue: nil) } }
27.243243
94
0.678571
21157b27520fa0df935620f8d7475b87a6ea16ab
83
// // File.swift // // // Created by kntk on 2022/03/12. // import Foundation
9.222222
34
0.578313
e0d64f1355351966be16967dc86b6b46a4400f6b
1,647
// // WidthSelectionTableViewCell.swift // SwiftEntryKit_Example // // Created by Daniel Huri on 4/25/18. // Copyright (c) 2018 [email protected]. All rights reserved. // import UIKit class WidthSelectionTableViewCell: SelectionTableViewCell { override func configure(attributesWrapper: EntryAttributeWrapper) { super.configure(attributesWrapper: attributesWrapper) titleValue = "Width" descriptionValue = "Describes the entry's width inside the screen. It can be stretched to the margins, it can have an offset, can a constant or have a ratio to the screen" insertSegments(by: ["Stretch", "20pts Offset", "90% Screen"]) selectSegment() } private func selectSegment() { switch attributesWrapper.attributes.positionConstraints.size.width { case .offset(value: let value): if value == 0 { segmentedControl.selectedSegmentIndex = 0 } else { segmentedControl.selectedSegmentIndex = 1 } case .ratio(value: _): segmentedControl.selectedSegmentIndex = 2 default: break } } @objc override func segmentChanged() { switch segmentedControl.selectedSegmentIndex { case 0: attributesWrapper.attributes.positionConstraints.size.width = .offset(value: 0) case 1: attributesWrapper.attributes.positionConstraints.size.width = .offset(value: 20) case 2: attributesWrapper.attributes.positionConstraints.size.width = .ratio(value: 0.9) default: break } } }
34.3125
179
0.643594
21c8181688d913c58ce679f5f9b736d1dbf3e9f0
1,273
// Copyright 2020 Itty Bitty Apps Pty Ltd import AppStoreConnect_Swift_SDK import Combine import Foundation import Model import SwiftyTextTable // MARK: - API conveniences extension Model.BundleId { init(_ attributes: AppStoreConnect_Swift_SDK.BundleId.Attributes) { self.init( identifier: attributes.identifier, name: attributes.name, platform: attributes.platform?.rawValue, seedId: attributes.seedId ) } init(_ apiBundleId: AppStoreConnect_Swift_SDK.BundleId) { self.init(apiBundleId.attributes!) } init(_ response: AppStoreConnect_Swift_SDK.BundleIdResponse) { self.init(response.data) } } // MARK: - TextTable conveniences extension Model.BundleId: ResultRenderable, TableInfoProvider { static func tableColumns() -> [TextTableColumn] { return [ TextTableColumn(header: "Identifier"), TextTableColumn(header: "Name"), TextTableColumn(header: "Platform"), TextTableColumn(header: "Seed ID"), ] } var tableRow: [CustomStringConvertible] { return [ identifier ?? "", name ?? "", platform ?? "", seedId ?? "", ] } }
24.960784
71
0.620581
8726233e5fc2e80959fed1dfcbdd8058f9695a93
3,134
// // DatabaseTests.swift // DropBitTests // // Created by BJ Miller on 3/8/19. // Copyright © 2019 Coin Ninja, LLC. All rights reserved. // import XCTest @testable import DropBit import CoreData class DatabaseTests: XCTestCase { var sut: CKDatabase! let config = CoreDataStackConfig(stackType: .main, storeType: .inMemory) override func setUp() { super.setUp() sut = CKDatabase(stackConfig: config) } override func tearDown() { sut = nil super.tearDown() } func testGroomingTransactionsRemovesTransactionsNotBelongingToWallet() { let context = sut.viewContext context.performAndWait { let goodTx = CKMTransaction(insertInto: context) let goodTxid = "abc123" let goodResponse = TransactionResponse(txid: goodTxid) goodTx.configure(with: goodResponse, in: context, relativeToBlockHeight: 0, fullSync: false) let badTx = CKMTransaction(insertInto: context) let badTxid = "bad_id" let badResopnse = TransactionResponse(txid: badTxid) badTx.configure(with: badResopnse, in: context, relativeToBlockHeight: 0, fullSync: false) XCTAssertEqual(context.insertedObjects.count, 2, "2 objects should initially be inserted") XCTAssertEqual(context.registeredObjects.count, 2, "2 objects should initially be registered") XCTAssertEqual(context.deletedObjects.count, 0, "0 objects should initially be deleted") _ = self.sut.deleteTransactions(notIn: [goodTxid], in: context) XCTAssertEqual(context.deletedObjects.count, 1, "1 object should be deleted after grooming") } } func testGroomingTransactionsDoesNotRemoveAnyTransactionsIfAllAreGood() { let context = sut.viewContext context.performAndWait { let goodTx = CKMTransaction(insertInto: context) let goodTxid = "abc123" let goodResponse = TransactionResponse(txid: goodTxid) goodTx.configure(with: goodResponse, in: context, relativeToBlockHeight: 0, fullSync: false) let goodTx2 = CKMTransaction(insertInto: context) let goodTxid2 = "123abc" let goodResponse2 = TransactionResponse(txid: goodTxid2) goodTx2.configure(with: goodResponse2, in: context, relativeToBlockHeight: 0, fullSync: false) XCTAssertEqual(context.insertedObjects.count, 2, "2 objects should initially be inserted") XCTAssertEqual(context.registeredObjects.count, 2, "2 objects should initially be registered") XCTAssertEqual(context.deletedObjects.count, 0, "0 objects should initially be deleted") _ = self.sut.deleteTransactions(notIn: [goodTxid, goodTxid2], in: context) XCTAssertEqual(context.deletedObjects.count, 0, "0 object should be deleted after grooming") do { try context.saveRecursively() } catch { XCTFail("failed to save context: \(error)") } XCTAssertEqual(context.registeredObjects.count, 2, "remaining objects should still equal 2") XCTAssertEqual(context.deletedObjects.count, 0, "0 objects should still be deleted") XCTAssertEqual(context.insertedObjects.count, 0, "0 objects should eventually be inserted") } } }
37.309524
100
0.725271
dbf467979431cb51bdf130e5af9c2f97fa72bfd7
4,894
// // DetailController.swift // animationtest // // Created by wang chao on 2019/4/11. // Copyright © 2019 bigfish. All rights reserved. // import UIKit class DetailController: BaseViewController, UITableViewDelegate, UITableViewDataSource, ImageTransitionCDelegate { var image: UIImage? @IBOutlet weak var topImageView: UIImageView! lazy var tableView: UITableView = { let tab = UITableView(frame: UIScreen.main.bounds) return tab }() var imageHeight: CGFloat = 0 override func viewDidLoad(){ super.viewDidLoad() guard let image = image else{ return } navigationBar.isHidden = true let tmpHeight: CGFloat = image.size.height * UIScreen.main.bounds.width / image.size.width imageHeight = tmpHeight topImageView.image = image topImageView.frame = CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: tmpHeight)) view.addSubview(tableView) tableView.beginUpdates() tableView.contentInset = UIEdgeInsets(top: tmpHeight, left: 0, bottom: 0, right: 0) tableView.endUpdates() tableView.delegate = self tableView.dataSource = self tableView.rowHeight = 100 tableView.estimatedRowHeight = 100 tableView.backgroundColor = .clear //tableView.nextResponer = topImageView topImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapTopImageView))) //topImageView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(panTopImageView(_:)))) wbInteractivePopMaxAllowedInitialDistanceToLeftEdge = 0 //tableView.wbScrollViewPopGestureRecognizerEnable = true } @objc func tapTopImageView(){ debugPrint("点击顶部图片") } var tmpHeight: CGFloat = 0 @objc func panTopImageView(_ sender: UIPanGestureRecognizer){ debugPrint("pan顶部图片") switch sender.state { case .began: debugPrint("pan顶部图片") // let point = sender.translation(in: topImageView) // if point.x <= 5{ // sender. // } tmpHeight = tableView.contentOffset.y case .changed: debugPrint(sender.translation(in: topImageView)) let point = sender.translation(in: topImageView) var realpanDistance = point.y if tableView.contentOffset.y <= -imageHeight{ let t = 1 - (-imageHeight - tableView.contentOffset.y)/(imageHeight) realpanDistance = point.y*(t > 0 ? t : 0.01) } tableView.contentOffset = CGPoint(x: 0, y: tmpHeight - realpanDistance) case .ended: debugPrint("pan ended") if tableView.contentOffset.y < -imageHeight { tableView.setContentOffset(CGPoint(x: 0, y: -imageHeight), animated: true) } else { tableView.setContentOffset(CGPoint(x: 0, y: tableView.contentOffset.y - sender.velocity(in: topImageView).y*0.3), animated: true) } case .cancelled: debugPrint("pan cancelled") default: debugPrint("pan顶部图片") } } func willTransitionPrepareInfo()->(UIImageView?, String?){ return (topImageView, nil) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: "cell") } cell?.textLabel?.text = "\(indexPath.description) cell" return cell! } func scrollViewDidScroll(_ scrollView: UIScrollView) { debugPrint(scrollView.contentOffset) if scrollView.contentOffset.y < -imageHeight { let tmpWidth = UIScreen.main.bounds.width*(-scrollView.contentOffset.y)/imageHeight topImageView.frame = CGRect(origin: CGPoint(x: -(tmpWidth-UIScreen.main.bounds.width)/2.0, y: 0), size: CGSize(width: tmpWidth, height: -scrollView.contentOffset.y)) } else { topImageView.frame = CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: imageHeight)) } } } class TopTransparentTableView: UITableView { weak var nextResponer: UIView? var tapTopTransparent: (()-> Void)? override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { debugPrint(point) let view = super.hitTest(point, with: event) if point.y <= 0{ } return view } }
34.464789
177
0.622599
ffe6982813af91cec46d656fea88a3e88270fb91
8,691
// // ViewController.swift // CredMockup // // Created by Vandit Jain on 22/01/21. // import UIKit import StackView class ViewController: UIViewController{ private let openStackViewButton = UIButton() //Button to open Stack Views private let closeStackViewButton = UIButton() //Button to close Stack Views private var cardViews = [StackCardView]() //Array of StackCardViews to be assigned private let firstCardPrimaryView = UIView() private let firstCardSecondaryView = UIView() private let secondCardBottomView = UIView() private let secondCardPrimaryView = UIView() private let thirdCardPrimaryView = UIView() private let thirdCardBottomView = UIView() private let stackView = StackView() override func viewDidLoad() { super.viewDidLoad() setupViews() stackView.delegate = self //Ensure that the stackview delegate is set for the callback functions cardViews.append(StackCardView(primaryView: firstCardPrimaryView)) //Initialised first cardView with PrimaryView cardViews.append(StackCardView(primaryView: secondCardPrimaryView)) //Initialised second cardView with PrimaryView cardViews.append(StackCardView(primaryView: thirdCardPrimaryView)) //Initialised third cardView with PrimaryView cardViews[0].setSecondaryView(secondaryView: firstCardSecondaryView) //Setting Secondary View of first Card cardViews[1].setBottomView(bottomView: secondCardBottomView) //Setting BottomView of second Card cardViews[2].setBottomView(bottomView: thirdCardBottomView) //Setting BottomView of third card stackView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height) //Setting StackView Frame to full screen stackView.cardViews = cardViews //Setting CardViews of stack [IMPORTANT!] view.addSubview(stackView) //Adding StackView to View } func setupViews(){ openStackViewButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(openStackViewButton) //Adding Open Views Button //Setting Open Button Constraints openStackViewButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -24).isActive = true openStackViewButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true openStackViewButton.widthAnchor.constraint(equalToConstant: 160).isActive = true openStackViewButton.heightAnchor.constraint(equalToConstant: 40).isActive = true openStackViewButton.setTitle("Open", for: .normal) openStackViewButton.titleLabel?.font = UIFont.systemFont(ofSize: 16) openStackViewButton.backgroundColor = UIColor(red: 251/255, green: 21/255, blue: 83/255, alpha: 1) openStackViewButton.layer.cornerRadius = 8 openStackViewButton.addTarget(self, action: #selector(openButtonClicked), for: .touchUpInside) closeStackViewButton.translatesAutoresizingMaskIntoConstraints = false thirdCardPrimaryView.addSubview(closeStackViewButton) //Adding Close Views Button to third Card //Setting Close Button Constraints closeStackViewButton.topAnchor.constraint(equalTo: thirdCardPrimaryView.topAnchor, constant: 20).isActive = true closeStackViewButton.centerXAnchor.constraint(equalTo: thirdCardPrimaryView.centerXAnchor).isActive = true closeStackViewButton.widthAnchor.constraint(equalToConstant: 160).isActive = true closeStackViewButton.heightAnchor.constraint(equalToConstant: 40).isActive = true closeStackViewButton.setTitle("Close all", for: .normal) closeStackViewButton.titleLabel?.font = UIFont.systemFont(ofSize: 16) closeStackViewButton.backgroundColor = UIColor(red: 251/255, green: 21/255, blue: 83/255, alpha: 1) closeStackViewButton.layer.cornerRadius = 8 closeStackViewButton.addTarget(self, action: #selector(closeStackViewButtonClicked), for: .touchUpInside) //There is no need to set frame of Primary View. Frame should be set of Secondary and Bottom Views firstCardPrimaryView.backgroundColor = UIColor(red: 15/255, green: 15/255, blue: 15/255, alpha: 1) //Setting Background Color of Card 1 Primary View //Setting Frame of First Card Secondary View firstCardSecondaryView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 120) //For Example the following code is to add Image View to the Card 1 secondary view let secondaryImageView = UIImageView() secondaryImageView.translatesAutoresizingMaskIntoConstraints = false firstCardSecondaryView.addSubview(secondaryImageView) secondaryImageView .contentMode = .scaleAspectFit secondaryImageView.widthAnchor.constraint(equalTo: firstCardSecondaryView.widthAnchor, constant: -16).isActive = true secondaryImageView.topAnchor.constraint(equalTo: firstCardSecondaryView.topAnchor, constant: 8).isActive = true secondaryImageView.centerXAnchor.constraint(equalTo: firstCardSecondaryView.centerXAnchor, constant: 0).isActive = true secondaryImageView.heightAnchor.constraint(equalTo: firstCardSecondaryView.heightAnchor, constant: -16).isActive = true ///Uncomment the following line to see the image in the secondary view //secondaryImageView.image = UIImage(named: "secondaryImg1") secondCardPrimaryView.backgroundColor = UIColor(red: 251/255, green: 21/255, blue: 83/255, alpha: 1) //Setting Background Color of Card 2 Primary View //Setting Frame of Second Card Secondary View secondCardBottomView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50) ///Note: The Second Card doesn't have a secondary view and will default to blank view //Adding Label to the Card 2 bottom View let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false secondCardBottomView.addSubview(label) label.text = "Bottom View 2" label.textColor = UIColor.white label.leftAnchor.constraint(equalTo: secondCardBottomView.leftAnchor, constant: 16).isActive = true label.topAnchor.constraint(equalTo: secondCardBottomView.topAnchor, constant: 8).isActive = true thirdCardPrimaryView.backgroundColor = UIColor.green //Setting Background Color of Card 3 Primary View //Setting Frame of Third Card Secondary View thirdCardBottomView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50) //Adding Label to the Card 3 bottom View let label1 = UILabel() label1.translatesAutoresizingMaskIntoConstraints = false thirdCardBottomView.addSubview(label1) label1.text = "Bottom View 3" label1.textColor = UIColor.white label1.leftAnchor.constraint(equalTo: thirdCardBottomView.leftAnchor, constant: 16).isActive = true label1.topAnchor.constraint(equalTo: thirdCardBottomView.topAnchor, constant: 8).isActive = true ///Uncomment the following line to set custom corner radius //stackView.setCardCornerRadius(radius: 2) } //Target for open button @objc func openButtonClicked(){ stackView.openNextCard() //Open Next Card of Stack View } //Target for close button @objc func closeStackViewButtonClicked(){ stackView.closeAllCards() // Close All Cards of Stack View } } ///Implementing Callback functions of Stack View extension ViewController: StackViewDelegate { ///This function is callback for when a new Card is opened func didOpenNewCard(for stackViewState: StackView.StackViewState) { print("I'm here") switch stackViewState { case .first: print("first") break case .second: print("second") break case .third: print("third") break default: print("hello!") } } ///This function is callback for when a card is dismissed func didCombebackToCard(for stackViewState: StackView.StackViewState) { print("I'm here") switch stackViewState { case .first: print("first back") break case .second: print("second back") break case .third: print("third back") break default: print("hello! back") } } }
46.978378
158
0.696237
7531e939e0d9c992a254140f955f4bf47d93d9e0
3,104
// // ParameterEncoding.swift // MemoryChainKit // // Created by Marc Steven on 2020/4/17. // Copyright © 2020 Marc Steven(https://github.com/MarcSteven). All rights reserved. // import Foundation /** ParameterEncoding is an Enum that defines how the parameters will be encoded in the request */ public enum ParameterEncoding { /** url encoding will append the parameter in the url as query parameters. For instance if parameters are ["foo":"bar","test":123] url will look something like https://my-website.com/api/path?foo=bar&test=123 */ case url /** json encoding will serialize the parameters in JSON and put them in the body of the request */ case json /** form encoding will url encode the parameters and put them in the body of the request */ case form } /** URLRequest extension that allows us to encode the parameters directly in the request */ extension URLRequest { /** Mutating function that, with a given set of parameters, will take care of building the request It is a mutating function and has side effects, it will modify the headers, the body and the url of the request. Make sure that this function not called after setting one of the above, or they might be overriden. - parameter parameters: A dictionary that needs to be encoded - parameter encoding: The encoding in which the parameters should be encoded */ mutating func encode(parameters: [String: Any]?, encoding: ParameterEncoding) throws { guard let parameters = parameters else {return} switch encoding { case .url: guard let url = self.url else {return} var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) if urlComponents != nil && !parameters.isEmpty { let paramString = (parameters.map { "\($0)=\($1)" } as [String]).joined(separator: "&") let percentEncodedQuery = (urlComponents!.percentEncodedQuery.map { $0 + "&" } ?? "") + paramString urlComponents!.percentEncodedQuery = percentEncodedQuery self.url = urlComponents!.url } case .json: do { let data = try JSONSerialization.data(withJSONObject: parameters, options: []) self.httpBody = data self.setValue("application/json", forHTTPHeaderField: "Content-Type") } catch { throw NetworkError.parameterEncoding(parameters) } case .form: let paramString = (parameters.map { "\($0)=\($1)" } as [String]).joined(separator: "&") self.httpBody = paramString.data(using: String.Encoding.utf8, allowLossyConversion: false) self.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") } } mutating func encode(form: MultipartForm) throws { self.httpBody = try form.encode() self.setValue("multipart/form-data; boundary=\(form.boundary)", forHTTPHeaderField: "Content-Type") } }
39.794872
138
0.65174
46f153284531c2f0f545982b38e949a996896a82
5,850
import Slang import Foundation import Nimble import Quick // Structure request examples: https://github.com/apple/swift/search?q=req%3Dstructure+path%3A%2Ftest%2FSourceKit&unscoped_q=req%3Dstructure+path%3A%2Ftest%2FSourceKit // Test: https://github.com/apple/swift/blob/master/test/SourceKit/DocumentStructure/structure.swift // Input: https://github.com/apple/swift/blob/master/test/SourceKit/DocumentStructure/Inputs/main.swift // Response: https://github.com/apple/swift/blob/master/test/SourceKit/DocumentStructure/structure.swift.response // Syntax-map request examples: https://github.com/apple/swift/search?q=req%3Dsyntax-map+path%3A%2Ftest%2FSourceKit&unscoped_q=req%3Dsyntax-map+path%3A%2Ftest%2FSourceKit // Test: https://github.com/apple/swift/blob/master/test/SourceKit/SyntaxMapData/syntaxmap.swift // Input: https://github.com/apple/swift/blob/master/test/SourceKit/SyntaxMapData/Inputs/syntaxmap.swift // Response: https://github.com/apple/swift/blob/master/test/SourceKit/SyntaxMapData/syntaxmap.swift.response // Get all "source.lang.swift." identifiers in Xcode 12 and below. // strings /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/Versions/Current/XPCServices/SourceKitService.xpc/Contents/MacOS/SourceKitService | grep source.lang.swift. | sort -u // Get all "source.lang.swift." identifiers in Xcode 13 and below. // strings /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitdInProc.framework/Versions/Current/sourcekitdInProc | grep source.lang.swift. | sort -u internal class SourceKindSpec: Spec { override internal func spec() { it("can initialize deep enums") { expect(SourceKind("source.lang.swift.decl.class")) == .decl(.class) expect(SourceKind("source.lang.swift.decl.enum")) == .decl(.enum) expect(SourceKind("source.lang.swift.decl.enumcase")) == .decl(.enum(.case)) expect(SourceKind("source.lang.swift.decl.function.free")) == .decl(.function(.free)) expect(SourceKind("source.lang.swift.expr")) == .expr expect(SourceKind("source.lang.swift.expr.argument")) == .expr(.arg) expect(SourceKind("source.lang.swift.foreach.sequence")) == .forEachSequence expect(SourceKind("source.lang.swift.range.invalid")) == .range(.invalid) expect(SourceKind("source.lang.swift.stmt.brace")) == .stmt(.brace) expect(SourceKind("source.lang.swift.structure.elem.condition_expr")) == .structureElem(.structureElemCondExpr) expect(SourceKind("source.lang.swift.syntaxtype.attribute.builtin")) == .syntaxType(.attributeBuiltin) expect(SourceKind("source.lang.swift.type")) == .type expect(SourceKind("source.lang.swift.foo.bar")) == .unknown("source.lang.swift.foo.bar") } it("can initialize all known cases") { SourceKind.allCases.forEach({ expect(SourceKind($0.rawValue)) == $0 }) } it("can compare known and unknown values") { expect(SourceKind.decl(.associatedType)) == SourceKind.decl(.associatedType) expect(SourceKind.unknown("foo")) == SourceKind.unknown("foo") expect(SourceKind.unknown(SourceKind.decl(.associatedType).rawValue)) != SourceKind.decl(.associatedType) expect(SourceKind.decl(.associatedType)) != SourceKind.unknown(SourceKind.decl(.associatedType).rawValue) } it("includes all current source identifiers") { let identifiers = try! Slang_Test.identifiers() // Make sure it's valid. expect(identifiers).toNot(beEmpty()) // Confirm all identifiers are known, i.e., none were added. expect(identifiers.filter({ SourceKind($0) == .unknown($0) })).to(beEmpty()) // Confirm all currently known identifiers are in the list, i.e., none were removed. expect(SourceKind.allCases.filter({ !identifiers.contains($0.rawValue) })).to(beEmpty()) // Just to be sure… expect(SourceKind.allCases.count) == identifiers.count } } } /// Returns current SourceKit Swift Language identifiers. fileprivate func identifiers() throws -> [String] { let developerPath = try! shell(line: "xcode-select --print-path") // Todo: Would be good to check the Xcode version and do the right thing. // Xcode 12 and below. // let sourceKitServicePath = "\(developerPath)/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitd.framework/Versions/Current/XPCServices/SourceKitService.xpc/Contents/MacOS/SourceKitService" // Xcode 13 and above. let sourceKitServicePath = "\(developerPath)/Toolchains/XcodeDefault.xctoolchain/usr/lib/sourcekitdInProc.framework/Versions/Current/sourcekitdInProc" var identifiers = try! shell(lines: "strings \(sourceKitServicePath) | grep source.lang.swift. | sort -u") // Remove known "out-of-interest" identifiers. // -req=complete identifiers.removeAll(where: { $0.starts(with: "source.lang.swift.codecomplete.group") }) identifiers.removeAll(where: { $0.starts(with: "source.lang.swift.completion.unresolvedmember") }) identifiers.removeAll(where: { $0.starts(with: "source.lang.swift.keyword") }) identifiers.removeAll(where: { $0.starts(with: "source.lang.swift.literal.") }) identifiers.removeAll(where: { $0.starts(with: "source.lang.swift.pattern") }) // -req=doc-info identifiers.removeAll(where: { $0.starts(with: "source.lang.swift.attribute.availability") }) // -req=index identifiers.removeAll(where: { $0.starts(with: "source.lang.swift.import.module.") }) // -req=complete|doc-info|index|cursor|… identifiers.removeAll(where: { $0.starts(with: "source.lang.swift.ref.") }) return identifiers }
59.090909
236
0.70735
5d0af41d6a63a7c5bd51bf150fef675256d5dd59
2,074
//: [Previous](@previous) import Foundation public protocol AnyTopLevelEncoder { associatedtype Output func encode<T>(_ value: T) throws -> Self.Output where T : Encodable } extension JSONEncoder: AnyTopLevelEncoder {} extension PropertyListEncoder: AnyTopLevelEncoder {} struct JSONStringEncoder: AnyTopLevelEncoder { typealias Output = String let encoder: JSONEncoder = JSONEncoder() func encode<T>(_ value: T) throws -> String where T : Encodable { let data = try encoder.encode(value) return String(decoding: data, as: UTF8.self) } } struct JSONSerializationEncoder: AnyTopLevelEncoder { typealias Output = [AnyHashable: Any] let encoder: JSONEncoder = JSONEncoder() func encode<T>(_ value: T) throws -> [AnyHashable : Any] where T : Encodable { let data = try encoder.encode(value) let serialization = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) guard let output = serialization as? [AnyHashable: Any] else { throw EncodingError.invalidValue(value, .init(codingPath: [], debugDescription: "Can't Turn into Dictionary")) } return output } } public extension Encodable { func encode() throws -> Data { try encode(using: JSONEncoder()) } func encode<Encoder: AnyTopLevelEncoder>(using encoder: Encoder) throws -> Encoder.Output { try encoder.encode(self) } } let xmlPropertyList = PropertyListEncoder() xmlPropertyList.outputFormat = .xml let jsonEncoder = JSONEncoder() jsonEncoder.outputFormatting = [.prettyPrinted, .sortedKeys] jsonEncoder.keyEncodingStrategy = .useDefaultKeys try Article.mock.encode(using: jsonEncoder).toString().print() try Article.mock.encode(using: xmlPropertyList).toString().print() try Article.mock.encode(using: JSONStringEncoder()).print() try Article.mock.encode(using: JSONSerializationEncoder()) //: [Next](@next)
32.40625
106
0.667792
291625078bb7b795927a392a430cb8a6f780f3a0
2,877
// // UIView+Additions.swift // ContentstackPersistenceiOS // // Created by Uttam Ukkoji on 18/09/18. // Copyright © 2018 Contentstack. All rights reserved. // import Foundation import UIKit protocol ReusableView: class { static var defaultReuseIdentifier: String { get } } extension ReusableView where Self: UIView { static var defaultReuseIdentifier: String { return String(describing: self) } } protocol NibLoadableView: class { static var nibName: String { get } static var nib : UINib {get} } extension NibLoadableView where Self: UIView { static var nibName: String { return String(describing: self) } static var nib : UINib { let bundle = Bundle(for: self.self) return UINib(nibName: self.nibName, bundle: bundle) } } extension UIView { func loadNib<T:UIView> () -> T where T : NibLoadableView { guard let nib = Bundle.main.loadNibNamed(T.nibName, owner: self, options: nil)?.first as? T else { fatalError("Could not load nib: \(T.nibName)") } return nib } } extension UITableViewCell : ReusableView, NibLoadableView { } extension UITableViewHeaderFooterView : ReusableView, NibLoadableView { } extension UITableView { func register<T: UITableViewCell>(_: T.Type) { register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier) } func registerNib<T: UITableViewCell>(_: T.Type) { let bundle = Bundle(for: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier) } func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } } extension UICollectionViewCell : ReusableView, NibLoadableView { } extension UICollectionView { func register<T: UICollectionViewCell>(_: T.Type) { register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } func registerNib<T: UICollectionViewCell>(_: T.Type) { let bundle = Bundle(for: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withReuseIdentifier: T.defaultReuseIdentifier, for: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } } extension UIView { }
27.4
120
0.666667
e68f670bfd1043c4cd683d9bafe38c992e0101c1
577
// REQUIRES: plus_one_runtime // RUN: %target-swift-frontend -O -emit-ir -primary-file %s | %FileCheck %s // This is a swift file because the crash doesn't reproduce with SIL. @inline(never) func callFoo<T: X>(_ x: T) { x.foo() } public func a(y: Sub) { callFoo(y) // specialization of callFoo for Sub: // CHECK-LABEL: define linkonce_odr hidden swiftcc void @"$S33devirt_witness_method_conformance7callFooyyxAA1XRzlFAA3SubC_Tg5Tf4d_n"() local_unnamed_addr } protocol X { func foo() } extension X { func foo() {} } public class Base: X {} public class Sub: Base {}
26.227273
153
0.715771
762b6ab8dfe2c0a7aa6a6fc363f880a69af89e41
4,168
precedencegroup PartialApplicationPrecedence {} infix operator |> : PartialApplicationPrecedence /// Applies an argument to a 1-ary function. /// /// - Parameters: /// - a: Argument to apply. /// - fun: Function receiving the argument. /// - Returns: Result of running the function with the argument as input. public func |><A, B>(_ a: A, _ fun: (A) -> B) -> B { fun(a) } /// Applies the first argument to a 2-ary function, returning a 1-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C>(_ a: A, _ fun: @escaping (A, B) -> C) -> (B) -> C { { b in fun(a,b) } } /// Applies the first argument to a 3-ary function, returning a 2-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D>(_ a: A, _ fun: @escaping (A, B, C) -> D) -> (B, C) -> D { { b, c in fun(a, b, c) } } /// Applies the first argument to a 4-ary function, returning a 3-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E>(_ a: A, _ fun: @escaping (A, B, C, D) -> E) -> (B, C, D) -> E { { b, c, d in fun(a, b, c, d) } } /// Applies the first argument to a 5-ary function, returning a 4-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E, F>(_ a: A, _ fun: @escaping (A, B, C, D, E) -> F) -> (B, C, D, E) -> F { { b, c, d, e in fun(a, b, c, d, e) } } /// Applies the first argument to a 6-ary function, returning a 5-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E, F, G>(_ a: A, _ fun: @escaping (A, B, C, D, E, F) -> G) -> (B, C, D, E, F) -> G { { b, c, d, e, f in fun(a, b, c, d, e, f) } } /// Applies the first argument to a 7-ary function, returning a 6-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E, F, G, H>(_ a: A, _ fun: @escaping (A, B, C, D, E, F, G) -> H) -> (B, C, D, E, F, G) -> H { { b, c, d, e, f, g in fun(a, b, c, d, e, f, g) } } /// Applies the first argument to a 8-ary function, returning a 7-ary function with the rest of the arguments of the original function. /// /// - Parameters: /// - a: Input to the first argument of the function /// - fun: Function to be applied. /// - Returns: A function with the same behavior of the input function where the first argument is fixed to the value of the provided argument. public func |><A, B, C, D, E, F, G, H, I>(_ a: A, _ fun: @escaping (A, B, C, D, E, F, G, H) -> I) -> (B, C, D, E, F, G, H) -> I { { b, c, d, e, f, g, h in fun(a, b, c, d, e, f, g, h) } }
49.619048
143
0.636996
29fa35128c62dab407ff4e3a655c1cba6c11bbac
4,314
// // InterfaceController.swift // BitcoinXWatch Extension // // Created by Arpit Agarwal on 09/05/18. // Copyright © 2018 acyooman. All rights reserved. // import WatchKit import Foundation //---------------------- // MARK: View Setup //---------------------- class InterfaceController: WKInterfaceController { @IBOutlet var pricesTable: WKInterfaceTable! @IBOutlet var statusLabel: WKInterfaceLabel! var priceList:HistoricalData? var pricesAPI = CoindeskAPI.init() override func awake(withContext context: Any?) { super.awake(withContext: context) self.pricesAPI.delegate = self self.pricesAPI.loadCachedData() self.pricesAPI.fetchHistoricalData() self.pricesAPI.fetchRealtimeData() statusLabel.setHidden(false) statusLabel.setText("Getting the latest exchange rate...") } } //------------------------ // MARK: View Data Logics //------------------------ extension InterfaceController { func scheduleRealtimePriceUpdate() { //schedule next realtime price update Timer.scheduledTimer(timeInterval: CommonHelpers.getRealtimeUpdateInterval(), target: self, selector: #selector(self.makeRealtimePriceRequest), userInfo: nil, repeats: false) } @objc func makeRealtimePriceRequest() { self.pricesAPI.fetchRealtimeData() } } //--------------------------- // MARK: Table Data Handlers //--------------------------- extension InterfaceController { func tableRefresh(){ var rowCount = self.pricesAPI.getHistoricalDataRowsCount() rowCount += self.pricesAPI.isRealtimeDataAvailable() ? 1 : 0 guard rowCount>0 else { return } pricesTable.setNumberOfRows(rowCount, withRowType: "BitcoinPriceRow") //-------------------- // realtime price row //-------------------- if self.pricesAPI.isRealtimeDataAvailable() { guard let controller = pricesTable.rowController(at: 0) as? PriceRowController else { return } let rate:Double = (self.pricesAPI.realtimeData?.bpi.eur.rateFloat)! controller.dateLabel.setText(self.pricesAPI.realtimeData?.time.updated) controller.priceLabel.setText(rate.formatAsEuro()) controller.priceLabel.setTextColor(UIColor.bxDarkTheme.orange) } //----------------------- // historical price rows //----------------------- guard self.pricesAPI.historicalData != nil else {return} let keysArray = Array((self.pricesAPI.historicalData?.bpi.keys)!).sorted(by: >) var index = self.pricesAPI.isRealtimeDataAvailable() ? 1 : 0 for dateString in keysArray { guard let controller = pricesTable.rowController(at: index) as? PriceRowController else { statusLabel.setHidden(false) self.statusLabel.setText("Something went wrong in displaying latest data.") return } let rate:Double = (self.pricesAPI.historicalData?.bpi[dateString])! controller.dateLabel.setText(dateString) controller.priceLabel.setText(rate.formatAsEuro()) controller.priceLabel.setTextColor(UIColor.white) index += 1; } } } //------------------------ // MARK: API Delegates //------------------------ extension InterfaceController: CoindeskAPIDelegate { func cachedDataLoadedSuccessfully() { self.tableRefresh() } func realtimeDataFetchedSuccessfully() { statusLabel.setHidden(true) self.scheduleRealtimePriceUpdate() tableRefresh() } func realtimeDataFetchFailedWithError(error: Error) { statusLabel.setHidden(false) self.statusLabel.setText(error.localizedDescription) } func historialDataFetchedSuccessfully() { statusLabel.setHidden(true) tableRefresh() } func historialDataFetchFailedWithError(error: Error) { statusLabel.setHidden(false) self.statusLabel.setText(error.localizedDescription) } }
32.43609
106
0.590635
d9ad85414ebd16483c4ee44bdec26c7e0b76d227
747
import XCTest import MiniPlayer class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.758621
111
0.601071
f849b72b64ef72431531c834c6fb38c59f1ffb5f
1,028
// // TrafficStatus.swift // TrafficPolice // // Created by 刘栋 on 2016/11/18. // Copyright © 2016年 anotheren.com. All rights reserved. // import Foundation public struct TrafficStatus { public let speed: TrafficSpeed public let data: TrafficData public let origin: TrafficData private init(speed: TrafficSpeed, data: TrafficData, origin: TrafficData) { self.speed = speed self.data = data self.origin = origin } public init(origin data: TrafficData) { self.speed = .zero self.data = .zero self.origin = data } public func update(by data: TrafficData, time interval: Double) -> TrafficStatus { let speed = TrafficSpeed(old: self.data, new: data - origin, interval: interval) return TrafficStatus(speed: speed, data: data - origin, origin: origin) } } extension TrafficStatus: CustomStringConvertible { public var description: String { return "speed:[\(speed)], data:[\(data)]" } }
25.073171
88
0.640078
5bd3cf84b9ea7abe649852deabf9a41e16442dc0
2,300
// // PrintScreenUtils.swift // Pods // // Created by Gregory Sholl e Santos on 05/06/17. // // import UIKit public class PrintScreenUtil { // MARK: - Get public static func get(of view: UIView?) -> UIImage? { guard let view = view else { return nil } let screenSize = UIScreen.main.bounds.size let colorSpaceRef = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGImageAlphaInfo.none guard let context = CGContext(data: nil, width: Int(screenSize.width), height: Int(screenSize.height), bitsPerComponent: 8, bytesPerRow: 4 * Int(screenSize.width), space: colorSpaceRef, bitmapInfo: bitmapInfo.rawValue) else { return nil } context.translateBy(x: 0.0, y: screenSize.height) context.scaleBy(x: 1.0, y: -1.0) view.layer.render(in: context) guard let cgImage = context.makeImage() else { return nil } let image = UIImage(cgImage: cgImage) return image } // MARK: - Save public static func save(toJpgFile filename: String, of view: UIView?) { guard let image = get(of: view) else { return } var filename = filename if !filename.contains(".jpg") { filename.append(".jpg") } if let data = image.jpegData(compressionQuality: 1.0) { do { try data.write(to: URL(fileURLWithPath: filename), options: .withoutOverwriting) } catch { MochaLogger.log("Could not save printed screen on file \(filename).") } } } public static func save(toPngFile filename: String, of view: UIView?) { guard let image = get(of: view) else { return } var filename = filename if !filename.contains(".png") { filename.append(".png") } if let data = image.pngData() { do { try data.write(to: URL(fileURLWithPath: filename), options: .withoutOverwriting) } catch { MochaLogger.log("Could not save printed screen on file \(filename).") } } } }
28.395062
233
0.540435
fc3b2f99163f0e0694b32b4bf0af8b1af7c018b4
5,323
// // BigUIntegers.swift // // // Created by Yehor Popovych on 1/13/21. // import Foundation import BigInt public protocol ScaleFixedUnsignedInteger: ScaleFixedData, CompactConvertible, CompactCodable, ExpressibleByIntegerLiteral { init(bigUInt int: BigUInt) throws static var bitWidth: Int { get } static var max: BigUInt { get } static var min: BigUInt { get } } extension ScaleFixedUnsignedInteger where UI == BigUInt { public init(_ int: UI) { try! self.init(bigUInt: int) } public init?(exactly value: BigUInt) { do { try self.init(bigUInt: value) } catch { return nil } } public init<T>(_ source: T) where T : BinaryInteger { self.init(BigUInt(source)) } public init(integerLiteral value: UInt64) { self.init(BigUInt(integerLiteral: value)) } public init(uintValue: UI) { self.init(uintValue) } public init<C: CompactCodable>(compact: SCompact<C>) throws { try self.init(bigUInt: BigUInt(compact.value.int)) } public func compact<C: CompactCodable>() throws -> SCompact<C> { guard int <= C.compactMax else { let bitWidth = MemoryLayout<C.UI>.size * 8 throw ScaleFixedIntegerError.overflow( bitWidth: bitWidth, value: BigInt(int), message: "Can't store \(int) in \(bitWidth)bit unsigned integer " ) } return SCompact(C(uintValue: C.UI(int))) } public init(decoding data: Data) throws { var data: Data = data data.reverse() try self.init(bigUInt: BigUInt(data)) } public func encode() throws -> Data { return int.serialize().withUnsafeBytes { bytes in var data = Data(bytes) data.reverse() data += Data(repeating: 0x00, count: Self.fixedBytesCount - data.count) return data } } public static func checkSizeBounds(_ value: BigUInt) throws { guard value <= Self.max else { throw ScaleFixedIntegerError.overflow( bitWidth: Self.bitWidth, value: BigInt(value), message: "Can't store \(value) in \(Self.bitWidth)bit unsigned integer") } } public static var fixedBytesCount: Int { return Self.bitWidth / 8 } public static var compactMax: UI { Self.max } } public struct SUInt128: ScaleFixedUnsignedInteger, Equatable, Hashable { public typealias UI = BigUInt public typealias IntegerLiteralType = UInt64 public let int: BigUInt public init(bigUInt int: BigUInt) throws { try Self.checkSizeBounds(int) self.int = int } public static let bitWidth: Int = 128 public static let max: BigUInt = BigUInt(2).power(128) - 1 public static let min: BigUInt = BigUInt(0) } public struct SUInt256: ScaleFixedUnsignedInteger, Equatable, Hashable { public typealias UI = BigUInt public typealias IntegerLiteralType = UInt64 public let int: BigUInt public init(bigUInt int: BigUInt) throws { try Self.checkSizeBounds(int) self.int = int } public static let bitWidth: Int = 256 public static let max: BigUInt = BigUInt(2).power(256) - 1 public static let min: BigUInt = BigUInt(0) } public struct SUInt512: ScaleFixedUnsignedInteger, Equatable, Hashable { public typealias UI = BigUInt public typealias IntegerLiteralType = UInt64 public let int: BigUInt public init(bigUInt int: BigUInt) throws { try Self.checkSizeBounds(int) self.int = int } public static let bitWidth: Int = 512 public static let max: BigUInt = BigUInt(2).power(512) - 1 public static let min: BigUInt = BigUInt(0) } extension BinaryInteger { public init<I: ScaleFixedUnsignedInteger>(_ source: I) { self.init(source.int) } public init<I: ScaleFixedUnsignedInteger>(truncatingIfNeeded source: I) { self.init(truncatingIfNeeded: source.int) } public init<I: ScaleFixedUnsignedInteger>(clamping source: I) { self.init(clamping: source.int) } public init?<I: ScaleFixedUnsignedInteger>(exactly source: I) { self.init(exactly: source.int) } } extension ScaleCustomEncoderFactory where T == BigUInt { public static var b128: ScaleCustomEncoderFactory { ScaleCustomEncoderFactory { try $0.encode(SUInt128(bigUInt: $1)) } } public static var b256: ScaleCustomEncoderFactory { ScaleCustomEncoderFactory { try $0.encode(SUInt256(bigUInt: $1)) } } public static var b512: ScaleCustomEncoderFactory { ScaleCustomEncoderFactory { try $0.encode(SUInt512(bigUInt: $1)) } } } extension ScaleCustomDecoderFactory where T == BigUInt { public static var b128: ScaleCustomDecoderFactory { ScaleCustomDecoderFactory { try $0.decode(SUInt128.self).int } } public static var b256: ScaleCustomDecoderFactory { ScaleCustomDecoderFactory { try $0.decode(SUInt256.self).int } } public static var b512: ScaleCustomDecoderFactory { ScaleCustomDecoderFactory { try $0.decode(SUInt512.self).int } } }
29.73743
88
0.637235
1170a01c7df39d35b1a993f1771ddaf35d969ce3
8,380
// // VirtualTimeScheduler.swift // RxSwift // // Created by Krunoslav Zaher on 2/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /// Base class for virtual time schedulers using a priority queue for scheduled items. open class VirtualTimeScheduler<Converter: VirtualTimeConverterType> : SchedulerType { public typealias VirtualTime = Converter.VirtualTimeUnit public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit private var _running : Bool private var _clock: VirtualTime private var _schedulerQueue : PriorityQueue<VirtualSchedulerItem<VirtualTime>> private var _converter: Converter private var _nextId = 0 /// - returns: Current time. public var now: RxTime { return self._converter.convertFromVirtualTime(self.clock) } /// - returns: Scheduler's absolute time clock value. public var clock: VirtualTime { return self._clock } /// Creates a new virtual time scheduler. /// /// - parameter initialClock: Initial value for the clock. public init(initialClock: VirtualTime, converter: Converter) { self._clock = initialClock self._running = false self._converter = converter self._schedulerQueue = PriorityQueue(hasHigherPriority: { switch converter.compareVirtualTime($0.time, $1.time) { case .lessThan: return true case .equal: return $0.id < $1.id case .greaterThan: return false } }, isEqual: { $0 === $1 }) #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } /** Schedules an action to be executed immediately. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { return self.scheduleRelative(state, dueTime: .microseconds(0)) { a in return action(a) } } /** Schedules an action to be executed. - parameter state: State passed to the action to be executed. - parameter dueTime: Relative time after which to execute the action. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func scheduleRelative<StateType>(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { let time = self.now.addingDispatchInterval(dueTime) let absoluteTime = self._converter.convertToVirtualTime(time) let adjustedTime = self.adjustScheduledTime(absoluteTime) return self.scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) } /** Schedules an action to be executed after relative time has passed. - parameter state: State passed to the action to be executed. - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func scheduleRelativeVirtual<StateType>(_ state: StateType, dueTime: VirtualTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { let time = self._converter.offsetVirtualTime(self.clock, offset: dueTime) return self.scheduleAbsoluteVirtual(state, time: time, action: action) } /** Schedules an action to be executed at absolute virtual time. - parameter state: State passed to the action to be executed. - parameter time: Absolute time when to execute the action. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func scheduleAbsoluteVirtual<StateType>(_ state: StateType, time: VirtualTime, action: @escaping (StateType) -> Disposable) -> Disposable { MainScheduler.ensureExecutingOnScheduler() let compositeDisposable = CompositeDisposable() let item = VirtualSchedulerItem(action: { return action(state) }, time: time, id: self._nextId) self._nextId += 1 self._schedulerQueue.enqueue(item) _ = compositeDisposable.insert(item) return compositeDisposable } /// Adjusts time of scheduling before adding item to schedule queue. open func adjustScheduledTime(_ time: VirtualTime) -> VirtualTime { return time } /// Starts the virtual time scheduler. public func start() { MainScheduler.ensureExecutingOnScheduler() if self._running { return } self._running = true repeat { guard let next = self.findNext() else { break } if self._converter.compareVirtualTime(next.time, self.clock).greaterThan { self._clock = next.time } next.invoke() self._schedulerQueue.remove(next) } while self._running self._running = false } func findNext() -> VirtualSchedulerItem<VirtualTime>? { while let front = self._schedulerQueue.peek() { if front.isDisposed { self._schedulerQueue.remove(front) continue } return front } return nil } /// Advances the scheduler's clock to the specified time, running all work till that point. /// /// - parameter virtualTime: Absolute time to advance the scheduler's clock to. public func advanceTo(_ virtualTime: VirtualTime) { MainScheduler.ensureExecutingOnScheduler() if self._running { fatalError("Scheduler is already running") } self._running = true repeat { guard let next = self.findNext() else { break } if self._converter.compareVirtualTime(next.time, virtualTime).greaterThan { break } if self._converter.compareVirtualTime(next.time, self.clock).greaterThan { self._clock = next.time } next.invoke() self._schedulerQueue.remove(next) } while self._running self._clock = virtualTime self._running = false } /// Advances the scheduler's clock by the specified relative time. public func sleep(_ virtualInterval: VirtualTimeInterval) { MainScheduler.ensureExecutingOnScheduler() let sleepTo = self._converter.offsetVirtualTime(self.clock, offset: virtualInterval) if self._converter.compareVirtualTime(sleepTo, self.clock).lessThen { fatalError("Can't sleep to past.") } self._clock = sleepTo } /// Stops the virtual time scheduler. public func stop() { MainScheduler.ensureExecutingOnScheduler() self._running = false } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } // MARK: description extension VirtualTimeScheduler: CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { return self._schedulerQueue.debugDescription } } final class VirtualSchedulerItem<Time> : Disposable { typealias Action = () -> Disposable let action: Action let time: Time let id: Int var isDisposed: Bool { return self.disposable.isDisposed } var disposable = SingleAssignmentDisposable() init(action: @escaping Action, time: Time, id: Int) { self.action = action self.time = time self.id = id } func invoke() { self.disposable.setDisposable(self.action()) } func dispose() { self.disposable.dispose() } } extension VirtualSchedulerItem : CustomDebugStringConvertible { var debugDescription: String { return "\(self.time)" } }
31.268657
161
0.641169
89aa07648761080100fa6fa5956eb82257b83860
4,049
// // CustomTableViewCell.swift // CafMate // // Created by Andrew Turnblad on 11/8/14. // Copyright (c) 2014 St. Olaf ACM. All rights reserved. // import Foundation import UIKit class CustomTableViewCell: UITableViewCell { var whichMeal = UILabel() var timeRange = UILabel() var mealTime = UILabel() var isMatched = UILabel() func loadItem(theMeal: String, rangeOfTime: String, timeOfMeal: String, matching: String) { println("load item called") println(theMeal) println(timeOfMeal) whichMeal.text = theMeal whichMeal.font = UIFont.systemFontOfSize(22) whichMeal.textAlignment = NSTextAlignment.Center whichMeal.frame = CGRectMake(0, 0, contentView.frame.size.width, 50) timeRange.text = rangeOfTime timeRange.textAlignment = NSTextAlignment.Center timeRange.font = UIFont.systemFontOfSize(20) timeRange.frame = CGRectMake(0, whichMeal.frame.size.height + whichMeal.frame.origin.y + 5, contentView.frame.size.width, 30) mealTime.text = timeOfMeal //mealTime.frame = CGRectMake(15, self.frame.height+100, 100, 15) mealTime.textAlignment = NSTextAlignment.Center mealTime.font = UIFont.systemFontOfSize(20) mealTime.frame = CGRectMake(0, whichMeal.frame.size.height + whichMeal.frame.origin.y + 5, contentView.frame.size.width, 30) isMatched.text = "\(matching)..." isMatched.textAlignment = NSTextAlignment.Center isMatched.font = UIFont(name: "Helvetica-Bold", size: 18) isMatched.frame = CGRectMake(0, timeRange.frame.size.height + timeRange.frame.origin.y + 15, contentView.frame.size.width, 30) contentView.addSubview(whichMeal) contentView.addSubview(timeRange) contentView.addSubview(mealTime) contentView.addSubview(isMatched) } /* override func awakeFromNib() { super.awakeFromNib() whichMeal.setTranslatesAutoresizingMaskIntoConstraints(false) timeRange.setTranslatesAutoresizingMaskIntoConstraints(false) mealTime.setTranslatesAutoresizingMaskIntoConstraints(false) isMatched.setTranslatesAutoresizingMaskIntoConstraints(false) //self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.width, 100.0) self.contentView.addSubview(whichMeal) contentView.addSubview(timeRange) contentView.addSubview(mealTime) contentView.addSubview(isMatched) var viewsDict = ["meal" : whichMeal, "availableTime" : timeRange, "time" : mealTime, "match" : isMatched] whichMeal.frame = CGRectMake(10, self.frame.height-10, 40, 15) timeRange.frame = CGRectMake(10, self.frame.height-30, 40, 15) mealTime.frame = CGRectMake(10, self.frame.height-30, 40, 15) isMatched.frame = CGRectMake(self.frame.width-50, self.frame.height-30, 40, 15) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[match]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[meal]-[availableTime]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[meal]-[time]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[meal]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[availableTime]-[match]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[time]-[match]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewsDict)) }*/ }
49.987654
182
0.699679
22f2953bbd2e6090d00f1ef873ff201a23c69915
1,910
// // LinkTests.swift // Thesi 🧝‍♀️ Tests // // Created by Chris Zielinski on 11/28/18. // Copyright © 2018 Big Z Labs. All rights reserved. // import Foundation import XCTest class LinkTests: ThesiTestCase { override var regexReplaceableClass: RegexReplaceable.Type { return MarkdownLink.self } func testLink() { ThesiTest("Thesi does not convert link.", test: "$[Simple Link](https://google.com)", expected: """ <a href="https://google.com" target="_blank">Simple Link</a> """) } func testNewLineLink() { ThesiTest("Thesi does not convert link.", test: "\n$[Simple Link](https://google.com)", expected: """ <a href="https://google.com" target="_blank">Simple Link</a> """) } func testWeirdLink() { ThesiTest("Thesi does not convert weird link.", test: " $[ Simple Link ] (\"https://google.com\" )", expected: " <a href=\"https://google.com\" target=\"_blank\"> Simple Link </a>") } func testCommonMarkLink() { ThesiTest("Thesi converts CommonMark link.", test: "[Alternate text](http://google.com/images)") } func testLinkInCodeBlock() { ThesiTest("Thesi converts link in (spaced) code block.", test: " $[Alternate text](http://google.com/images)") ThesiTest("Thesi converts link in (tabbed) code block.", test: "\t$[Alternate text](http://google.com/images)") } func testCommonMarkImage() { ThesiTest("Thesi converts CommonMark image to link.", test: "![Alternate text](http://google.com/images)", expected: "![Alternate text](http://google.com/images)") } }
31.833333
98
0.536126
8a129af7e2b6b7ecce839789320c2709e5417ff1
170
// // UICollectionView+Extensions.swift // Tempo // // Created by Dennis Fedorko on 1/13/17. // Copyright © 2017 CUAppDev. All rights reserved. // import Foundation
17
51
0.7
d62b89a5e26cf2ee23f9fe48294bd72c484f559d
443
// // ConcreteStyle.swift // TableViewIndex // // Created by Makarov Yury on 06/06/16. // Copyright © 2016 Makarov Yury. All rights reserved. // import UIKit class ConcreteStyle : Style { @objc let font: UIFont @objc let itemSpacing: CGFloat init(font: UIFont?, itemSpacing: CGFloat?) { self.font = font ?? StyleDefaults.font self.itemSpacing = itemSpacing ?? StyleDefaults.itemSpacing } }
20.136364
67
0.650113
03b503926940aa0f4c4f5dd9c70f2c2754bbd478
2,347
// Differific iOS Playground import UIKit import Differific import PlaygroundSupport final class CollectionViewHandler: NSObject, UICollectionViewDataSource { var values = ["Foo", "Bar"] func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return values.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCollectionViewCell.identifier, for: indexPath) as! MyCollectionViewCell let value = values[indexPath.row] cell.label.text = value return cell } } final class MyCollectionViewCell: UICollectionViewCell { static let identifier = "CellID" let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) label.text = "Foo" label.sizeToFit() label.textAlignment = .center label.textColor = .black addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } final class MyViewController : UIViewController { private let handler = CollectionViewHandler() private let collectionView = UICollectionView(frame: CGRect(origin: .zero, size: .init(width: 379, height: 450)), collectionViewLayout: UICollectionViewFlowLayout()) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: MyCollectionViewCell.identifier) collectionView.backgroundColor = .white collectionView.dataSource = handler view.addSubview(collectionView) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) sleep(2) let new = ["Foo", "Bar", "Baz"] let changes = DiffManager().diff(handler.values, new) collectionView.reload(with: changes, updateDataSource: { handler.values = new }) } } PlaygroundPage.current.liveView = MyViewController()
30.881579
169
0.67533
e27635c79b59681837b324081eb3081f960f4bd9
316
// // WeekSection.swift // uncomplicated-todo // // Created by Vladislav Morozov on 19/05/2019. // Copyright © 2019 misshapes. All rights reserved. // import Foundation struct WeekSection: Equatable { let items: [TodoListItem] let weekStartEnd: String let todoNumber: Int let isOverdue: Bool }
18.588235
52
0.702532
693f63a6d42b1b6be70815d13f15428dc8fc9f55
936
// // HomeViewController.swift // thridDemos // // Created by wlx on 2021/1/4. // import UIKit class HomeViewController: FR_BaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you w ill often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // let vc = UIViewController() let vc = TestViewController() vc.view.backgroundColor = UIColor.randomColor() self.navigationController?.pushViewController(vc, animated: true) } }
25.297297
107
0.662393
e62fec544c5f5c4ba10171f55d0e2911e4914382
26,754
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /** A Realm instance (also referred to as "a realm") represents a Realm database. Realms can either be stored on disk (see `init(path:)`) or in memory (see `Configuration`). Realm instances are cached internally, and constructing equivalent Realm objects (with the same path or identifier) produces limited overhead. If you specifically want to ensure a Realm object is destroyed (for example, if you wish to open a realm, check some property, and then possibly delete the realm file and re-open it), place the code which uses the realm within an `autoreleasepool {}` and ensure you have no other strong references to it. - warning: Realm instances are not thread safe and can not be shared across threads or dispatch queues. You must construct a new instance on each thread you want to interact with the realm on. For dispatch queues, this means that you must call it in each block which is dispatched, as a queue is not guaranteed to run on a consistent thread. */ public final class Realm { // MARK: Properties /// Path to the file where this Realm is persisted. @available(*, deprecated=1, message="Use configuration.fileURL") public var path: String { return configuration.path! } /// Indicates if this Realm was opened in read-only mode. @available(*, deprecated=1, message="Use configuration.readOnly") public var readOnly: Bool { return configuration.readOnly } /// The Schema used by this realm. public var schema: Schema { return Schema(rlmRealm.schema) } /// Returns the `Configuration` that was used to create this `Realm` instance. public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) } /// Indicates if this Realm contains any objects. public var isEmpty: Bool { return rlmRealm.isEmpty } // MARK: Initializers /** Obtains a Realm instance with the default Realm configuration, which can be changed by setting `Realm.Configuration.defaultConfiguration`. - throws: An NSError if the Realm could not be initialized. */ public convenience init() throws { let rlmRealm = try RLMRealm(configuration: RLMRealmConfiguration.defaultConfiguration()) self.init(rlmRealm) } /** Obtains a Realm instance with the given configuration. - parameter configuration: The configuration to use when creating the Realm instance. - throws: An NSError if the Realm could not be initialized. */ public convenience init(configuration: Configuration) throws { let rlmRealm = try RLMRealm(configuration: configuration.rlmConfiguration) self.init(rlmRealm) } /** Obtains a Realm instance persisted at the specified file path. - parameter path: Path to the realm file. - throws: An NSError if the Realm could not be initialized. */ @available(*, deprecated=1, message="Use Realm(fileURL:)") public convenience init(path: String) throws { var configuration = Configuration.defaultConfiguration configuration.fileURL = NSURL(fileURLWithPath: path) try self.init(configuration: configuration) } /** Obtains a Realm instance persisted at the specified file URL. - parameter fileURL: Local URL to the realm file. - throws: An NSError if the Realm could not be initialized. */ public convenience init(fileURL: NSURL) throws { var configuration = Configuration.defaultConfiguration configuration.fileURL = fileURL try self.init(configuration: configuration) } // MARK: Transactions /** Performs actions contained within the given block inside a write transaction. Write transactions cannot be nested, and trying to execute a write transaction on a `Realm` which is already in a write transaction will throw an exception. Calls to `write` from `Realm` instances in other threads will block until the current write transaction completes. Before executing the write transaction, `write` updates the `Realm` to the latest Realm version, as if `refresh()` was called, and generates notifications if applicable. This has no effect if the `Realm` was already up to date. - parameter block: The block to be executed inside a write transaction. - throws: An NSError if the transaction could not be written. */ public func write(@noescape block: (() -> Void)) throws { try rlmRealm.transactionWithBlock(block) } /** Begins a write transaction in a `Realm`. Only one write transaction can be open at a time. Write transactions cannot be nested, and trying to begin a write transaction on a `Realm` which is already in a write transaction will throw an exception. Calls to `beginWrite` from `Realm` instances in other threads will block until the current write transaction completes. Before beginning the write transaction, `beginWrite` updates the `Realm` to the latest Realm version, as if `refresh()` was called, and generates notifications if applicable. This has no effect if the `Realm` was already up to date. It is rarely a good idea to have write transactions span multiple cycles of the run loop, but if you do wish to do so you will need to ensure that the `Realm` in the write transaction is kept alive until the write transaction is committed. */ public func beginWrite() { rlmRealm.beginWriteTransaction() } /** Commits all writes operations in the current write transaction, and ends the transaction. Calling this when not in a write transaction will throw an exception. - throws: An NSError if the transaction could not be written. */ public func commitWrite() throws { try rlmRealm.commitWriteTransaction() } /** Reverts all writes made in the current write transaction and end the transaction. This rolls back all objects in the Realm to the state they were in at the beginning of the write transaction, and then ends the transaction. This restores the data for deleted objects, but does not revive invalidated object instances. Any `Object`s which were added to the Realm will be invalidated rather than switching back to standalone objects. Given the following code: ```swift let oldObject = objects(ObjectType).first! let newObject = ObjectType() realm.beginWrite() realm.add(newObject) realm.delete(oldObject) realm.cancelWrite() ``` Both `oldObject` and `newObject` will return `true` for `invalidated`, but re-running the query which provided `oldObject` will once again return the valid object. Calling this when not in a write transaction will throw an exception. */ public func cancelWrite() { rlmRealm.cancelWriteTransaction() } /** Indicates if this Realm is currently in a write transaction. - warning: Wrapping mutating operations in a write transaction if this property returns `false` may cause a large number of write transactions to be created, which could negatively impact Realm's performance. Always prefer performing multiple mutations in a single transaction when possible. */ public var inWriteTransaction: Bool { return rlmRealm.inWriteTransaction } // MARK: Adding and Creating objects /** Adds or updates an object to be persisted it in this Realm. When 'update' is 'true', the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values. When added, all (child) relationships referenced by this object will also be added to the Realm if they are not already in it. If the object or any related objects already belong to a different Realm an exception will be thrown. Use one of the `create` functions to insert a copy of a persisted object into a different Realm. The object to be added must be valid and cannot have been previously deleted from a Realm (i.e. `invalidated` must be false). - parameter object: Object to be added to this Realm. - parameter update: If true will try to update existing objects with the same primary key. */ public func add(object: Object, update: Bool = false) { if update && object.objectSchema.primaryKeyProperty == nil { throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated") } RLMAddObjectToRealm(object, rlmRealm, update) } /** Adds or updates objects in the given sequence to be persisted it in this Realm. - see: add(_:update:) - warning: This method can only be called during a write transaction. - parameter objects: A sequence which contains objects to be added to this Realm. - parameter update: If true will try to update existing objects with the same primary key. */ public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) { for obj in objects { add(obj, update: update) } } /** Create an `Object` with the given value. Creates or updates an instance of this object and adds it to the `Realm` populating the object with the given value. When 'update' is 'true', the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values. - warning: This method can only be called during a write transaction. - parameter type: The object type to create. - parameter value: The value used to populate the object. This can be any key/value coding compliant object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`, or an `Array` with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. When passing in an `Array`, all properties must be present, valid and in the same order as the properties defined in the model. - parameter update: If true will try to update existing objects with the same primary key. - returns: The created object. */ public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T { let className = (type as Object.Type).className() if update && schema[className]?.primaryKeyProperty == nil { throwRealmException("'\(className)' does not have a primary key and can not be updated") } return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), T.self) } /** This method is useful only in specialized circumstances, for example, when building components that integrate with Realm. If you are simply building an app on Realm, it is recommended to use the typed method `create(_:value:update:)`. Creates or updates an object with the given class name and adds it to the `Realm`, populating the object with the given value. When 'update' is 'true', the object must have a primary key. If no objects exist in the Realm instance with the same primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values. - warning: This method can only be called during a write transaction. - parameter className: The class name of the object to create. - parameter value: The value used to populate the object. This can be any key/value coding compliant object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`, or an `Array` with one object for each persisted property. An exception will be thrown if any required properties are not present and no default is set. When passing in an `Array`, all properties must be present, valid and in the same order as the properties defined in the model. - parameter update: If true will try to update existing objects with the same primary key. - returns: The created object. :nodoc: */ public func dynamicCreate(className: String, value: AnyObject = [:], update: Bool = false) -> DynamicObject { if update && schema[className]?.primaryKeyProperty == nil { throwRealmException("'\(className)' does not have a primary key and can not be updated") } return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), DynamicObject.self) } // MARK: Deleting objects /** Deletes the given object from this Realm. - warning: This method can only be called during a write transaction. - parameter object: The object to be deleted. */ public func delete(object: Object) { RLMDeleteObjectFromRealm(object, rlmRealm) } /** Deletes the given objects from this Realm. - warning: This method can only be called during a write transaction. - parameter objects: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`, or any other enumerable SequenceType which generates Object. */ public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S) { for obj in objects { delete(obj) } } /** Deletes the given objects from this Realm. - warning: This method can only be called during a write transaction. - parameter objects: The objects to be deleted. Must be `List<Object>`. :nodoc: */ public func delete<T: Object>(objects: List<T>) { rlmRealm.deleteObjects(objects._rlmArray) } /** Deletes the given objects from this Realm. - warning: This method can only be called during a write transaction. - parameter objects: The objects to be deleted. Must be `Results<Object>`. :nodoc: */ public func delete<T: Object>(objects: Results<T>) { rlmRealm.deleteObjects(objects.rlmResults) } /** Deletes all objects from this Realm. - warning: This method can only be called during a write transaction. */ public func deleteAll() { RLMDeleteAllObjectsFromRealm(rlmRealm) } // MARK: Object Retrieval /** Returns all objects of the given type in the Realm. - parameter type: The type of the objects to be returned. - returns: All objects of the given type in Realm. */ public func objects<T: Object>(type: T.Type) -> Results<T> { return Results<T>(RLMGetObjects(rlmRealm, (type as Object.Type).className(), nil)) } /** This method is useful only in specialized circumstances, for example, when building components that integrate with Realm. If you are simply building an app on Realm, it is recommended to use the typed method `objects(type:)`. Returns all objects for a given class name in the Realm. - warning: This method is useful only in specialized circumstances. - parameter className: The class name of the objects to be returned. - returns: All objects for the given class name as dynamic objects :nodoc: */ public func dynamicObjects(className: String) -> Results<DynamicObject> { return Results<DynamicObject>(RLMGetObjects(rlmRealm, className, nil)) } /** Get an object with the given primary key. Returns `nil` if no object exists with the given primary key. This method requires that `primaryKey()` be overridden on the given subclass. - see: Object.primaryKey() - parameter type: The type of the objects to be returned. - parameter key: The primary key of the desired object. - returns: An object of type `type` or `nil` if an object with the given primary key does not exist. */ public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T? { return unsafeBitCast(RLMGetObject(rlmRealm, (type as Object.Type).className(), key), Optional<T>.self) } /** This method is useful only in specialized circumstances, for example, when building components that integrate with Realm. If you are simply building an app on Realm, it is recommended to use the typed method `objectForPrimaryKey(_:key:)`. Get a dynamic object with the given class name and primary key. Returns `nil` if no object exists with the given class name and primary key. This method requires that `primaryKey()` be overridden on the given subclass. - see: Object.primaryKey() - warning: This method is useful only in specialized circumstances. - parameter className: The class name of the object to be returned. - parameter key: The primary key of the desired object. - returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist. :nodoc: */ public func dynamicObjectForPrimaryKey(className: String, key: AnyObject) -> DynamicObject? { return unsafeBitCast(RLMGetObject(rlmRealm, className, key), Optional<DynamicObject>.self) } // MARK: Notifications /** Add a notification handler for changes in this Realm. Notification handlers are called after each write transaction is committed, independent from the thread or process. The block is called on the same thread as it was added on, and can only be added on threads which are currently within a run loop. Unless you are specifically creating and running a run loop on a background thread, this normally will only be the main thread. Notifications can't be delivered as long as the runloop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced. You must retain the returned token for as long as you want updates to continue to be sent to the block. To stop receiving updates, call stop() on the token. - parameter block: A block which is called to process Realm notifications. It receives the following parameters: - `Notification`: The incoming notification. - `Realm`: The realm for which this notification occurred. - returns: A token which must be held for as long as you want notifications to be delivered. */ @warn_unused_result(message="You must hold on to the NotificationToken returned from addNotificationBlock") public func addNotificationBlock(block: NotificationBlock) -> NotificationToken { return rlmRealm.addNotificationBlock(rlmNotificationBlockFromNotificationBlock(block)) } /** Remove a previously registered notification handler using the token returned from `addNotificationBlock(_:)` - parameter notificationToken: The token returned from `addNotificationBlock(_:)` corresponding to the notification block to remove. */ @available(*, deprecated=1, message="Use NotificationToken.stop()") public func removeNotification(notificationToken: NotificationToken) { notificationToken.stop() } // MARK: Autorefresh and Refresh /** Whether this Realm automatically updates when changes happen in other threads. If set to `true` (the default), changes made on other threads will be reflected in this Realm on the next cycle of the run loop after the changes are committed. If set to `false`, you must manually call `refresh()` on the Realm to update it to get the latest version. Note that by default, background threads do not have an active run loop and you will need to manually call `refresh()` in order to update to the latest version, even if `autorefresh` is set to `true`. Even with this enabled, you can still call `refresh()` at any time to update the Realm before the automatic refresh would occur. Notifications are sent when a write transaction is committed whether or not this is enabled. Disabling this on a `Realm` without any strong references to it will not have any effect, and it will switch back to YES the next time the `Realm` object is created. This is normally irrelevant as it means that there is nothing to refresh (as persisted `Object`s, `List`s, and `Results` have strong references to the containing `Realm`), but it means that setting `Realm().autorefresh = false` in `application(_:didFinishLaunchingWithOptions:)` and only later storing Realm objects will not work. Defaults to true. */ public var autorefresh: Bool { get { return rlmRealm.autorefresh } set { rlmRealm.autorefresh = newValue } } /** Update a `Realm` and outstanding objects to point to the most recent data for this `Realm`. - returns: Whether the realm had any updates. Note that this may return true even if no data has actually changed. */ public func refresh() -> Bool { return rlmRealm.refresh() } // MARK: Invalidation /** Invalidate all `Object`s and `Results` read from this Realm. A Realm holds a read lock on the version of the data accessed by it, so that changes made to the Realm on different threads do not modify or delete the data seen by this Realm. Calling this method releases the read lock, allowing the space used on disk to be reused by later write transactions rather than growing the file. This method should be called before performing long blocking operations on a background thread on which you previously read data from the Realm which you no longer need. All `Object`, `Results` and `List` instances obtained from this `Realm` on the current thread are invalidated, and can not longer be used. The `Realm` itself remains valid, and a new read transaction is implicitly begun the next time data is read from the Realm. Calling this method multiple times in a row without reading any data from the Realm, or before ever reading any data from the Realm is a no-op. This method cannot be called on a read-only Realm. */ public func invalidate() { rlmRealm.invalidate() } // MARK: Writing a Copy /** Write an encrypted and compacted copy of the Realm to the given path. The destination file cannot already exist. Note that if this is called from within a write transaction it writes the *current* data, and not data when the last write transaction was committed. - parameter path: Path to save the Realm to. - parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with. - throws: An NSError if the copy could not be written. */ @available(*, deprecated=1, message="Use Realm.writeCopyToURL(_:encryptionKey:)") public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) throws { try writeCopyToURL(NSURL(fileURLWithPath: path)) } /** Write an encrypted and compacted copy of the Realm to the given local URL. The destination file cannot already exist. Note that if this is called from within a write transaction it writes the *current* data, and not data when the last write transaction was committed. - parameter fileURL: Local URL to save the Realm to. - parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with. - throws: An NSError if the copy could not be written. */ public func writeCopyToURL(fileURL: NSURL, encryptionKey: NSData? = nil) throws { try rlmRealm.writeCopyToURL(fileURL, encryptionKey: encryptionKey) } // MARK: Internal internal var rlmRealm: RLMRealm internal init(_ rlmRealm: RLMRealm) { self.rlmRealm = rlmRealm } } // MARK: Equatable extension Realm: Equatable { } /// Returns whether the two realms are equal. public func == (lhs: Realm, rhs: Realm) -> Bool { // swiftlint:disable:this valid_docs return lhs.rlmRealm == rhs.rlmRealm } // MARK: Notifications /// A notification due to changes to a realm. public enum Notification: String { /** Posted when the data in a realm has changed. DidChange is posted after a realm has been refreshed to reflect a write transaction, i.e. when an autorefresh occurs, `refresh()` is called, after an implicit refresh from `write(_:)`/`beginWrite()`, and after a local write transaction is committed. */ case DidChange = "RLMRealmDidChangeNotification" /** Posted when a write transaction has been committed to a Realm on a different thread for the same file. This is not posted if `autorefresh` is enabled or if the Realm is refreshed before the notification has a chance to run. Realms with autorefresh disabled should normally have a handler for this notification which calls `refresh()` after doing some work. While not refreshing is allowed, it may lead to large Realm files as Realm has to keep an extra copy of the data for the un-refreshed Realm. */ case RefreshRequired = "RLMRealmRefreshRequiredNotification" } /// Closure to run when the data in a Realm was modified. public typealias NotificationBlock = (notification: Notification, realm: Realm) -> Void internal func rlmNotificationBlockFromNotificationBlock(notificationBlock: NotificationBlock) -> RLMNotificationBlock { return { rlmNotification, rlmRealm in return notificationBlock(notification: Notification(rawValue: rlmNotification)!, realm: Realm(rlmRealm)) } }
39.518464
120
0.699858
1aee20fcb4ba04e3b0e48c6fd8ad0fff9814543f
1,240
// // RunFunUITests.swift // RunFunUITests // // Created by Hannah Teuteberg on 15.01.18. // Copyright © 2018 bughana. All rights reserved. // import XCTest class RunFunUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.513514
182
0.662097
2680e12a423a77f3676d03178154df487c5d3ed6
859
// // BluetoothBase.swift // BluetoothDemo // // Created by Wojciech Kulik on 21/07/2018. // Copyright © 2018 Wojciech Kulik. All rights reserved. // import Foundation import CoreBluetooth protocol FlowController { func bluetoothOn() func bluetoothOff() func scanStarted() func scanStopped() func connected(peripheral: CBPeripheral) func disconnected(failure: Bool) func discoveredPeripheral() func readyToWrite() func received(response: Data) // TODO: add other events if needed } extension FlowController { func bluetoothOn() { } func bluetoothOff() { } func scanStarted() { } func scanStopped() { } func connected(peripheral: CBPeripheral) { } func disconnected(failure: Bool) { } func discoveredPeripheral() { } func readyToWrite() { } func received(response: Data) { } }
23.861111
57
0.682189
eb7f2e82e3d80e471fb3cd2d04d2eec76971e63a
2,479
// // FavouriteManager.swift // BaihuTest // // Created by liudong on 2020/8/9. // Copyright © 2020 liudong. All rights reserved. // import UIKit class FavouriteManager: NSObject { @objc static let shared = FavouriteManager() override private init() { } var favouriteList = [(albumId: String, favouriteId: String)]() @objc func isFavouriteLocalCheck(albumId: String) -> String? { let result = favouriteList.first { (item) -> Bool in item.albumId == albumId } if result == nil { return nil } else { return result!.favouriteId } } // 闭包逃逸。 @objc func addFavourite(albumId: String, callback: ((Bool) -> Void)?) { NetworkManager.getHttpSessionManager().post(UrlConstants.addFavourite(), parameters: ["album_id": albumId], headers: NetworkManager.getCommonHeaders(), progress: nil, success: { _, response in let resObj = FavouriteOperationResponse.yy_model(with: response as! [AnyHashable: Any]) if resObj?.error == nil { callback?(true) FavouriteManager.shared.favouriteList.append((albumId: resObj!.data!.album!.id, favouriteId: resObj!.data!.id)) } }) { _, _ in callback?(false) } } @objc func removeFavourite(favouriteIdParams: String, callback: ((Bool) -> Void)?) { NetworkManager.getHttpSessionManager().delete(UrlConstants.deleteFavourite(favouriteIdParams), parameters: nil, headers: NetworkManager.getCommonHeaders(), success: { _, response in let result = CommonOperationsResponse(fromDictionary: response as! NSDictionary) if result.error == nil { callback?(true) FavouriteManager.shared.favouriteList.removeAll { (item) -> Bool in item.favouriteId == favouriteIdParams } } else { callback?(false) } let value = Test.dictionary2String(response as! [AnyHashable: Any]) print(value) }) { _, _ in callback?(false) } } @objc func pullFavourites() { NetworkManager.getHttpSessionManager().get(UrlConstants.getAllFavourite(), parameters: nil, headers: NetworkManager.getCommonHeaders(), progress: nil, success: { [weak self] _, _ in guard let self = self else { return } }) { _, _ in } } }
35.414286
200
0.598628
20b80cca1b288df737cc99c98626016d37bf00ca
439
import UIKit public class SectionColorHeader: UITableViewHeaderFooterView { public override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) backgroundView = UIView() isUserInteractionEnabled = false } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundView = UIView() isUserInteractionEnabled = false } }
24.388889
62
0.690205
20ef7fb9fcdba23a3bf553c3d57ca612112a03d8
764
// // ArtisanError.swift // Artisan // // Created by Nayanda Haberty (ID) on 27/08/20. // import Foundation #if canImport(UIKit) public struct ArtisanError: LocalizedError { /// Description of error public let errorDescription: String? /// Reason of failure public let failureReason: String? init(errorDescription: String, failureReason: String? = nil) { self.errorDescription = errorDescription self.failureReason = failureReason } } extension ArtisanError { static func whenDiffReloading(failureReason: String? = nil) -> ArtisanError { .init( errorDescription: "Artisan Error: Error when reload by difference", failureReason: failureReason ) } } #endif
22.470588
81
0.660995
5006dc50775ba96ee13743a24808fffc79e9849a
911
// // UIPickerView+Rx.swift // Rx // // Created by Segii Shulga on 5/12/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // #if os(iOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit extension UIPickerView { /** Reactive wrapper for `delegate`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var rx_delegate: DelegateProxy { return RxPickerViewDelegateProxy.proxyForObject(self) } public var rx_itemSelected: ControlEvent<(row: Int, component: Int)> { let source = rx_delegate .observe(#selector(UIPickerViewDelegate.pickerView(_:didSelectRow:inComponent:))) .map { return (try castOrThrow(Int.self, $0[1]), try castOrThrow(Int.self, $0[2])) } return ControlEvent(events: source) } } #endif
24.621622
93
0.644347
01be3301caf26771552fd6506718a39322b62392
3,245
// ITJSONResourceManager.swift // ImitationTown // Created by CodeInventor Group, // Copyright © 2017年 ManoBoo. All rights reserved. // Our site: https://www.codeinventor.club // Function: JSON资源的获取与解析 import UIKit public let SourceBundlePath = Bundle.main.path(forResource: "JSONResources", ofType: "bundle")! public let SourceBundle = Bundle(path: SourceBundlePath)! // JSONResources's filename public let Home_venuebook_filename = "Home_venuebook" public let Home_iconPage_filename = "Home_iconPage" public let Home_freshFabulas_filename = "Home_freshFabulas" public let Home_category_coffee_filename = "Home_category_coffee" public let Home_selectCity_filename = "Home_selectCity" public let Home_venue_coffee1_filename = "Home_venue_coffee1" public let Home_venue_coffee2_filename = "Home_venue_coffee2" public let Home_venue_building_filename = "Home_venue_ building" public let Home_venue_food_filename = "Home_venue_food" public let Home_venue_sanlitun_filename = "Home_venue_sanlitun" public let Home_venue_vintage_file = "Home_venue_vintage" public let Feed_dashboard = "Feed" public let Search_HothashTag_filename = "Search_HothashTag" public let Search_Fabulas_filename = "Search_Fabulas" public let Search_Venuebook_filename = "Search_Venuebook" public let Search_Users_filename = "Search_Users" enum ITJSONResourceManagerError: String, Error { case notFindJSONFile = "未找到json资源文件" case jsonAnalysisFailed = "json -> Dictionary 失败" case dictionaryConvertToJsonFailed = "Dictionary -> Json 失败" } class ITJSONResourceManager: NSObject { static func getJSONResources(from location: String) throws -> Dictionary<String, Any>? { guard let jsonFilePath = SourceBundle.path(forResource: location, ofType: "json") else { throw ITJSONResourceManagerError.notFindJSONFile } let data = try Data(contentsOf: URL(fileURLWithPath: jsonFilePath)) /// json整体转换为字典 guard let dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Dictionary<String, Any> else { throw ITJSONResourceManagerError.jsonAnalysisFailed } return dict } static func getJSONStringWithJsonObject(from object: Any) throws -> String? { /// 字典转换为json guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else { throw ITJSONResourceManagerError.dictionaryConvertToJsonFailed } let jsonString: String = String(data: data, encoding: String.Encoding.utf8)! return jsonString } static func getRowsJSONStringFromFilePath(jsonFilePath: String) throws -> String? { /// 从文件中获取rows的json数据 guard let dict = try getJSONResources(from: jsonFilePath) else { throw ITJSONResourceManagerError.jsonAnalysisFailed } let result = dict["result"] as! Dictionary<String, Any> let rows = result["rows"] as! [Dictionary<String, Any>] guard let jsonString = try getJSONStringWithJsonObject(from: rows) else { throw ITJSONResourceManagerError.dictionaryConvertToJsonFailed } return jsonString } }
39.096386
130
0.727581
e8ab4d6861a6e4a82cae58b8d5619ca1e9d26972
20,577
// // PetAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif open class PetAPI { /** Add a new pet to the store - parameter body: (body) Pet object that needs to be added to the store - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: completion((), nil) case let .failure(error): completion(nil, error) } } } /** Add a new pet to the store - POST /pet - OAuth: - type: oauth2 - name: petstore_auth - parameter body: (body) Pet object that needs to be added to the store - returns: RequestBuilder<Void> */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder<Void> { let path = "/pet" let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Deletes a pet - parameter petId: (path) Pet id to delete - parameter apiKey: (header) (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: completion((), nil) case let .failure(error): completion(nil, error) } } } /** Deletes a pet - DELETE /pet/{petId} - OAuth: - type: oauth2 - name: petstore_auth - parameter petId: (path) Pet id to delete - parameter apiKey: (header) (optional) - returns: RequestBuilder<Void> */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder<Void> { var path = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** * enum for parameter status */ public enum Status_findPetsByStatus: String, CaseIterable { case available = "available" case pending = "pending" case sold = "sold" } /** Finds Pets by status - parameter status: (query) Status values that need to be considered for filter - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** Finds Pets by status - GET /pet/findByStatus - Multiple status values can be provided with comma separated strings - OAuth: - type: oauth2 - name: petstore_auth - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil var urlComponents = URLComponents(string: URLString) urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Finds Pets by tags - parameter tags: (query) Tags to filter by - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTags(tags: Set<String>, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Set<Pet>?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** Finds Pets by tags - GET /pet/findByTags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - OAuth: - type: oauth2 - name: petstore_auth - parameter tags: (query) Tags to filter by - returns: RequestBuilder<Set<Pet>> */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: Set<String>) -> RequestBuilder<Set<Pet>> { let path = "/pet/findByTags" let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil var urlComponents = URLComponents(string: URLString) urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Set<Pet>>.Type = PetstoreClient.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Find pet by ID - parameter petId: (path) ID of pet to return - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** Find pet by ID - GET /pet/{petId} - Returns a single pet - API Key: - type: apiKey api_key - name: api_key - parameter petId: (path) ID of pet to return - returns: RequestBuilder<Pet> */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder<Pet> { var path = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClient.basePath + path let parameters: [String: Any]? = nil let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Pet>.Type = PetstoreClient.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Update an existing pet - parameter body: (body) Pet object that needs to be added to the store - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: completion((), nil) case let .failure(error): completion(nil, error) } } } /** Update an existing pet - PUT /pet - OAuth: - type: oauth2 - name: petstore_auth - parameter body: (body) Pet object that needs to be added to the store - returns: RequestBuilder<Void> */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder<Void> { let path = "/pet" let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** Updates a pet in the store with form data - parameter petId: (path) ID of pet that needs to be updated - parameter name: (form) Updated name of the pet (optional) - parameter status: (form) Updated status of the pet (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: completion((), nil) case let .failure(error): completion(nil, error) } } } /** Updates a pet in the store with form data - POST /pet/{petId} - OAuth: - type: oauth2 - name: petstore_auth - parameter petId: (path) ID of pet that needs to be updated - parameter name: (form) Updated name of the pet (optional) - parameter status: (form) Updated status of the pet (optional) - returns: RequestBuilder<Void> */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> { var path = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Void>.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** uploads an image - parameter petId: (path) ID of pet to update - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter file: (form) file to upload (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** uploads an image - POST /pet/{petId}/uploadImage - OAuth: - type: oauth2 - name: petstore_auth - parameter petId: (path) ID of pet to update - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter file: (form) file to upload (optional) - returns: RequestBuilder<ApiResponse> */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder<ApiResponse> { var path = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<ApiResponse>.Type = PetstoreClient.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } /** uploads an image (required) - parameter petId: (path) ID of pet to update - parameter requiredFile: (form) file to upload - parameter additionalMetadata: (form) Additional data to pass to server (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** uploads an image (required) - POST /fake/{petId}/uploadImageWithRequiredFile - OAuth: - type: oauth2 - name: petstore_auth - parameter petId: (path) ID of pet to update - parameter requiredFile: (form) file to upload - parameter additionalMetadata: (form) Additional data to pass to server (optional) - returns: RequestBuilder<ApiResponse> */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder<ApiResponse> { var path = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) let URLString = PetstoreClient.basePath + path let formParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] let nonNullParameters = APIHelper.rejectNil(formParams) let parameters = APIHelper.convertBoolToString(nonNullParameters) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<ApiResponse>.Type = PetstoreClient.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } }
42.252567
256
0.658551
9ca76e7cd60bd84ddf3d491f251c9192c40d613d
9,356
// // ServiceViewController.swift // BiciBoard // // Created by Adolfo Vera Blasco on 16/5/18. // Copyright © 2018 desappstre {eStudio}. All rights reserved. // import UIKit import WebKit import Foundation import CoreOD import BiciKit import DashboardKit internal class ServiceViewController: UIViewController { /// @IBOutlet private weak var buttonMap: UIBarButtonItem! /// @IBOutlet private weak var scroolViewContainer: UIScrollView! /// @IBOutlet private weak var labelStations: UILabel! /// @IBOutlet private weak var webViewStations: WKWebView! /// @IBOutlet private weak var labelBikes: UILabel! /// @IBOutlet private weak var webViewBikes: WKWebView! /// @IBOutlet private weak var labelOccupation: UILabel! /// @IBOutlet private weak var webViewOccupation: WKWebView! /// @IBOutlet private weak var labelCompare: UILabel! /// @IBOutlet private weak var webViewCompare: WKWebView! /// @IBOutlet private weak var labelStationsList: UILabel! /// @IBOutlet private weak var webViewStationsList: WKWebView! // // MARK: - Life Cycle // /** Cargamos los datos de las estaciones */ override internal func viewDidLoad() -> Void { super.viewDidLoad() self.loadStationsInformation() } /** Aplicamos aspecto visual */ override internal func viewWillAppear(_ animated: Bool) -> Void { super.viewWillAppear(animated) self.navigationItem.largeTitleDisplayMode = .always self.navigationController?.navigationBar.prefersLargeTitles = true self.navigationController?.navigationBar.isTranslucent = false self.applyTheme() self.localizeText() } // // MARK: - Prepare UI // /** El tema UI */ private func applyTheme() -> Void { self.view.backgroundColor = Theme.current.background self.labelStations.textColor = Theme.current.textColor self.labelBikes.textColor = Theme.current.textColor self.labelStationsList.textColor = Theme.current.textColor } /** Texto en base al idioma */ private func localizeText() -> Void { self.title = NSLocalizedString("SERVICE_TITLE", comment: "") self.labelBikes.text = NSLocalizedString("SERVICE_BIKES_GRAPH_TITLE", comment: "") self.labelCompare.text = NSLocalizedString("SERVICE_COMPARATION_GRAPH_TITLE", comment: "") self.labelStations.text = NSLocalizedString("SERVICE_STATIONS_GRAPH_TITLE", comment: "") self.labelOccupation.text = NSLocalizedString("SERVICE_OCCUPATION_GRAPH_TITLE", comment: "") self.labelStationsList.text = NSLocalizedString("SERVICE_STATIONS_LIST_TITLE", comment: "") } // // MARK: - Service Data // /** Solicitamos los datos de todas las estaciones */ private func loadStationsInformation() -> Void { BiciMADClient.shared.stations() { (result: BiciMADResult) -> Void in switch result { case let .success(stations): DispatchQueue.main.async { // Estaciones self.presentStations(active: stations.stationsAvailables, outOfService: stations.stationsUnavailables) // Bicicletas self.presentBikes(inUse: stations.bikesInUse, availablesInStations: stations.freeBikes) // Ocupacion let low_count = stations.stationsCount(by: .low) let middle_count = stations.stationsCount(by: .medium) let high_count = stations.stationsCount(by: .high) let unavailable_count = stations.stationsCount(by: .unavailable) self.presentOccupation(lowLevel: low_count, medium: middle_count, high: high_count, unavailable: unavailable_count) // Listado let stations_data = stations.map({ return (name: $0.name, bikes: $0.bikesDocked, docks: $0.freeBases, occupation: $0.occupationLevel) }) self.presentStations(list: stations_data) // Mes anterior let dataController = BiciMadDataController() if let subscriptions = dataController.subscriptions(by: .april, duringYear: 2018) { self.presentSubscriptions(subscriptions, inMonth: "\(Subscription.Month.april)", duringYear: 2018) } } case let .error(message): print("Algo pasa con el servicio...") } } } // // MARK: - Reports // /** Gráfico de estado de las estaciones - Parameters: - active: Operativas - outOfService: Fuera de servicio */ private func presentStations(active: Int, outOfService: Int) -> Void { guard let htmlCode = ReportEngine.shared.reporForStations(availables: active, outOfService: outOfService) else { return } self.webViewStations.loadHTMLString(htmlCode, baseURL: ReportEngine.shared.baseURL) } /** Gráficos de cantidad de bicicletas - Parameters: - inUse: Circulando por Madrid - availables: Las que se pueden alquilar */ private func presentBikes(inUse: Int, availablesInStations availables: Int) -> Void { guard let htmlCode = ReportEngine.shared.reportForBikes(inUse: inUse, availables: availables) else { return } self.webViewBikes.loadHTMLString(htmlCode, baseURL: ReportEngine.shared.baseURL) } /** Gráfico con los niveles de ocupación de las estaciones - Parameter: - low: Baja ocupación - medium: Nivel medio - high: Alto nivel de ocupación - unavailable: No están disponibles */ private func presentOccupation(lowLevel low: Int, medium: Int, high: Int, unavailable: Int) -> Void { guard let htmlCode = ReportEngine.shared.reportForStations(occupationLow: low, medium: medium, high: high, unavailable: unavailable) else { return } self.webViewOccupation.loadHTMLString(htmlCode, baseURL: ReportEngine.shared.baseURL) } /** Gráfico de subscripciones al servicio BiciMad del mes anterior (abril) Muestra los datos para los abonos anuales y los ocasionales. - Parameters: - subscriptions: Todas las subscripciones - month: De que mes queremos extraer los datos - year: Y de que año. */ private func presentSubscriptions(_ subscriptions: [Subscription], inMonth month: String, duringYear year: Int) -> Void { let anual = subscriptions.map({ $0.anualSubscriptions }) let occasionals = subscriptions.map({ $0.occasionalSubscriptions }) guard let htmlCode = ReportEngine.shared.reportMonth(month, inYear:year, anualSubscriptions: anual, occasionals: occasionals) else { return } self.webViewCompare.loadHTMLString(htmlCode, baseURL: ReportEngine.shared.baseURL) } /** Listado de todas las estaciones del servicio. Los datos están en un array que contiene tuplas con las información que muestro para cada estación * name: Nombre de la estación * bikes: Las bicis disponibles * docks: Los anclajes libres * occupation: El nivel de ocupación - Parameters: list: Los datos de las estaciones */ private func presentStations(list: [(name: String, bikes: Int, docks: Int, occupation: Ocuppation)]) -> Void { let reportParameters = list.map({ (item: (name: String, bikes: Int, docks: Int, occupation: Ocuppation)) -> StationRecord in let reportOccupation = ReportEngine.OcuppationReporting(rawValue: item.occupation.rawValue)! let parameter: StationRecord = (name: item.name, bikes: item.bikes, docks: item.docks, occupation: reportOccupation) return parameter }) guard let htmlCode = ReportEngine.shared.reportToList(reportParameters) else { return } self.webViewStationsList.loadHTMLString(htmlCode, baseURL: ReportEngine.shared.baseURL) } // // MARK: - Actions // /** Mostramos las estaciones sobre un mapa */ @IBAction private func handleMapButtonTap() -> Void { guard let storyboard = self.storyboard, let stationsViewController = storyboard.instantiateViewController(withIdentifier: "StationsViewController") as? StationsViewController else { return } self.navigationController?.pushViewController(stationsViewController, animated: true) } }
32.151203
148
0.605387
08e8a6ede787765942e70bc29b5d7b80739ab55e
3,406
// // ZCheck.swift // ZCheck // // Created by three stone 王 on 2019/8/25. // Copyright © 2019 three stone 王. All rights reserved. // import Foundation import DCTResult import WLToolsKit public func DCTCheckUsernameAndPassword(_ username: String ,password: String) -> DCTResult { if username.isEmpty || username.wl_isEmpty { return DCTResult.failed("请输入手机号") } if !String.validPhone(phone: username) { return DCTResult.failed("请输入11位手机号") } if password.isEmpty || password.wl_isEmpty { return DCTResult.failed("请输入6-18密码") } if password.length < 6 { return DCTResult.failed("请输入6-18密码") } return DCTResult.ok("验证成功") } public func DCTCheckUsernameAndVCode(_ mobile: String ,vcode: String) -> DCTResult { if mobile.isEmpty || mobile.wl_isEmpty { return DCTResult.failed("手机号不能为空") } if !String.validPhone(phone: mobile) { return DCTResult.failed( "请输入正确手机号") } if vcode.isEmpty || vcode.wl_isEmpty { return DCTResult.failed( "请输入6位验证码") } if vcode.length < 6 { return DCTResult.failed( "请输入6位验证码") } return DCTResult.ok( "") } public func DCTCheckUsername(_ mobile: String ) -> DCTResult { if mobile.isEmpty || mobile.wl_isEmpty { return DCTResult.failed("手机号不能为空") } if !String.validPhone(phone: mobile) { return DCTResult.failed( "请输入正确手机号") } return DCTResult.ok("") } public func smsResult(count: Int) -> (Bool ,String) { if count <= 0 { return (true ,"获取验证码") } else { return (false ,"(\(count)s)")} } public func DCTCheckPasswordForget(_ mobile: String ,vcode: String ,password: String) -> DCTResult { if mobile.isEmpty || mobile.wl_isEmpty { return DCTResult.failed("手机号不能为空") } if !String.validPhone(phone: mobile) { return DCTResult.failed( "请输入正确手机号") } if vcode.isEmpty || vcode.wl_isEmpty { return DCTResult.failed( "请输入6位验证码") } if vcode.length < 6 { return DCTResult.failed( "请输入6位验证码") } if password.isEmpty || password.wl_isEmpty { return DCTResult.failed( "请输入6-18位密码") } if password.length < 6 { return DCTResult.failed( "请输入6-18位密码") } return DCTResult.ok( "") } public func DCTCheckPasswordModify(_ oldpassword: String,password: String ,passwordAgain: String) -> DCTResult { if oldpassword.isEmpty || oldpassword.wl_isEmpty { return DCTResult.failed( "请输入6-18位旧密码") } if oldpassword.length < 6 { return DCTResult.failed( "请输入6-18位旧密码") } if password.isEmpty || password.wl_isEmpty { return DCTResult.failed( "请输入6-18位新密码") } if password.length < 6 { return DCTResult.failed( "请输入6-18位新密码") } if passwordAgain.isEmpty || passwordAgain.wl_isEmpty { return DCTResult.failed( "请输入6-18位确认密码") } if passwordAgain.length < 6 { return DCTResult.failed( "请输入6-18位确认密码") } if password != passwordAgain { return DCTResult.failed( "新密码和确认密码不一致") } return DCTResult.ok( "") }
22.556291
112
0.583089
280f66b7bece90e135bbf23d1af18046ccb29193
7,795
// // Sender.swift // breadwallet // // Created by Adrian Corscadden on 2017-01-16. // Copyright © 2017 breadwallet LLC. All rights reserved. // // File Description: // - Verify user, create tx, and publish it import Foundation import UIKit import BRCore enum SendResult { case success case creationError(String) case publishFailure(BRPeerManagerError) } private let protocolPaymentTimeout: TimeInterval = 20.0 class Sender { init(walletManager: WalletManager, kvStore: BRReplicatedKVStore, store: Store) { self.walletManager = walletManager self.kvStore = kvStore self.store = store } private let walletManager: WalletManager private let kvStore: BRReplicatedKVStore private let store: Store var transaction: BRTxRef? var protocolRequest: PaymentProtocolRequest? var rate: Rate? var comment: String? var feePerKb: UInt64? func createTransaction(amount: UInt64, to: String) -> Bool { transaction = walletManager.wallet?.createTransaction(forAmount: amount, toAddress: to) return transaction != nil } func createTransaction(forPaymentProtocol: PaymentProtocolRequest) { protocolRequest = forPaymentProtocol transaction = walletManager.wallet?.createTxForOutputs(forPaymentProtocol.details.outputs) } var fee: UInt64 { guard let tx = transaction else { return 0 } return walletManager.wallet?.feeForTx(tx) ?? 0 } var canUseBiometrics: Bool { guard let tx = transaction else { return false } return walletManager.canUseBiometrics(forTx: tx) } func feeForTx(amount: UInt64) -> UInt64 { return walletManager.wallet?.feeForTx(amount:amount) ?? 0 } //Amount in bits func send(biometricsMessage: String, rate: Rate?, comment: String?, feePerKb: UInt64, verifyPinFunction: @escaping (@escaping(String) -> Bool) -> Void, completion:@escaping (SendResult) -> Void) { guard let tx = transaction else { return completion(.creationError(S.Send.createTransactionError)) } self.rate = rate self.comment = comment self.feePerKb = feePerKb if UserDefaults.isBiometricsEnabled && walletManager.canUseBiometrics(forTx:tx) { DispatchQueue.walletQueue.async { [weak self] in guard let myself = self else { return } myself.walletManager.signTransaction(tx, biometricsPrompt: biometricsMessage, completion: { result in if result == .success { myself.publish(completion: completion) } else { if result == .failure || result == .fallback { myself.verifyPin(tx: tx, withFunction: verifyPinFunction, completion: completion) } } }) } } else { self.verifyPin(tx: tx, withFunction: verifyPinFunction, completion: completion) } } private func verifyPin(tx: BRTxRef, withFunction: (@escaping(String) -> Bool) -> Void, completion:@escaping (SendResult) -> Void) { withFunction({ pin in var success = false let group = DispatchGroup() group.enter() DispatchQueue.walletQueue.async { if self.walletManager.signTransaction(tx, pin: pin) { self.publish(completion: completion) success = true } group.leave() } let result = group.wait(timeout: .now() + 4.0) if result == .timedOut { let alert = UIAlertController(title: "Error", message: "Did not sign tx within timeout", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.topViewController?.present(alert, animated: true, completion: nil) return false } return success }) } //TODO - remove this -- only temporary for testing private var topViewController: UIViewController? { var viewController = UIApplication.shared.keyWindow?.rootViewController while viewController?.presentedViewController != nil { viewController = viewController?.presentedViewController } return viewController } private func publish(completion: @escaping (SendResult) -> Void) { guard let tx = transaction else { assert(false, "publish failure"); return } DispatchQueue.walletQueue.async { [weak self] in guard let myself = self else { assert(false, "myelf didn't exist"); return } myself.walletManager.peerManager?.publishTx(tx, completion: { success, error in DispatchQueue.main.async { if let error = error { completion(.publishFailure(error)) } else { myself.setMetaData() completion(.success) myself.postProtocolPaymentIfNeeded() } } }) } } private func setMetaData() { guard let rate = rate, let tx = transaction, let feePerKb = feePerKb else { print("Incomplete tx metadata"); return } let metaData = TxMetaData(transaction: tx.pointee, exchangeRate: rate.rate, exchangeRateCurrency: rate.code, feeRate: Double(feePerKb), deviceId: UserDefaults.standard.deviceID, comment: comment) do { let _ = try kvStore.set(metaData) } catch let error { print("could not update metadata: \(error)") } store.trigger(name: .txMemoUpdated(tx.pointee.txHash.description)) } private func postProtocolPaymentIfNeeded() { guard let protoReq = protocolRequest else { return } guard let wallet = walletManager.wallet else { return } let amount = protoReq.details.outputs.map { $0.amount }.reduce(0, +) let payment = PaymentProtocolPayment(merchantData: protoReq.details.merchantData, transactions: [transaction], refundTo: [(address: wallet.receiveAddress, amount: amount)]) guard let urlString = protoReq.details.paymentURL else { return } guard let url = URL(string: urlString) else { return } let request = NSMutableURLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: protocolPaymentTimeout) request.setValue("application/bitcoincash-payment", forHTTPHeaderField: "Content-Type") request.addValue("application/bitcoincash-paymentack", forHTTPHeaderField: "Accept") request.httpMethod = "POST" request.httpBody = Data(bytes: payment!.bytes) URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in guard error == nil else { print("payment error: \(error!)"); return } guard let response = response, let data = data else { print("no response or data"); return } if response.mimeType == "application/bitcoincash-paymentack" && data.count <= 50000 { if let ack = PaymentProtocolACK(data: data) { print("received ack: \(ack)") //TODO - show memo to user } else { print("ack failed to deserialize") } } else { print("invalid data") } print("finished!!") }.resume() } }
40.598958
200
0.59628
38f1982a196ef3ecdfbb7460d6b7358a669143f3
749
import XCTest import StringSwitch class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.827586
111
0.602136
0ec5bdade6a8b83ecd12a31c03a253a2d50068a8
286
// // CoinListView.swift // CryptoWidget // // Created by Mario Eguiluz on 25/12/2020. // import SwiftUI struct CoinListView: View { var data: [Coin] var body: some View { VStack { ForEach(data, id: \.symbol){ coin in CoinRow(coin: coin) } } } }
13.619048
43
0.583916
e5ea80396e576f21c2bef1edbc048ad138c6be57
688
import SwiftUI struct AnimateObjectScale: View { @State var rotation = 0.0 @State var scaleXY = 1.0 var body: some View { Rectangle() .fill(Color("orange")) .frame(width: 50, height: 50, alignment: .center) .rotationEffect(.degrees(rotation)) .scaleEffect(CGFloat(scaleXY)) .animation(Animation.easeInOut(duration: 3).repeatForever(autoreverses: true).speed(4)) .onAppear() { rotation += 360 scaleXY += 1.1 } } } struct AnimateObjectScale_Previews: PreviewProvider { static var previews: some View { AnimateObjectScale() } }
26.461538
99
0.572674
9c53fa5b31a35c4f7c140cf2933396eedaedb371
2,826
// // ViewController.swift // CustomURLTextView // // Created by htomcat on 2017/09/29. // Copyright © 2017年 htomcat. All rights reserved. // import UIKit class ViewController: UIViewController { let textView = CustomTextView() private let urlPattern = "(http|ftp|https)://([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?" override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let titleLabel = UILabel(frame: CGRect(x: 0, y: 50, width: UIScreen.main.bounds.width, height: 50)) titleLabel.font = .boldSystemFont(ofSize: 30.0) titleLabel.text = "UITextView" let subTitleLabel = UILabel(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 50)) subTitleLabel.font = .boldSystemFont(ofSize: 25.0) subTitleLabel.text = "Overview" textView.frame = CGRect(x: 0, y: 150, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) detectURLandReplaceHyperlink() view.addSubview(titleLabel) view.addSubview(subTitleLabel) view.addSubview(textView) } private func detectURLandReplaceHyperlink() { guard let text = textView.text else { return } guard let regExp = try? NSRegularExpression(pattern: urlPattern, options: .caseInsensitive) else { return } let attributeText = NSMutableAttributedString(string: text) let matchedText = regExp.matches(in: text, options: .reportProgress, range: NSRange(location: 0, length: text.characters.count)) matchedText.forEach { result in let castText = text as NSString let subText = castText.substring(with: result.range) let attributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.link: URL(string: subText)!, NSAttributedStringKey.foregroundColor: UIColor.blue, NSAttributedStringKey.strikethroughStyle: 1] let attributeSubText = NSAttributedString(string: subText, attributes: attributes) attributeText.replaceCharacters(in: result.range, with: attributeSubText) } textView.attributedText = attributeText } }
44.15625
119
0.518401
eb4a1d67e73eb3cf7fd5bfd5bdb2778dff983bb9
352
// // ImageError.swift // NyrisSDK // // Created by MOSTEFAOUI Anas on 02/02/2018. // Copyright © 2018 nyris. All rights reserved. // import Foundation public enum ImageError : Error { case invalidSize(message:String) case invalidImageData(message:String) case resizingFailed(message:String) case rotatingFailed(message:String) }
20.705882
48
0.724432
28493406229f9fbd91bf92f4458f0a9bf7016098
1,159
// // BroadcastView2.swift // wwdc20_proto2 // // Created by Gabriel C Paula on 11/05/20. // Copyright © 2020 Gabriel C Paula. All rights reserved. // import SwiftUI public struct BroadcastView: View { @ObservedObject var person: Person public var body: some View { VStack(alignment: .center) { FullPersonView(previous: person.pastPseudonyms, encountered: person.encounteredPseudonyms) VStack { HStack { Text("Broadcasting").font(.headline) .fontWeight(.medium) Image(systemName: "antenna.radiowaves.left.and.right") .imageScale(.large) }.padding(.top) PersonBroadcastingView(name: person.broadcasting).id("rataria" + person.broadcasting) } } .padding() .background( RoundedRectangle(cornerRadius: 25, style: .continuous) .fill(Color.tertiarySystemBackground) .shadow(radius: 5) .aspectRatio(1, contentMode: .fill) ) }}
26.953488
102
0.542709
3ae544d2aa3aa7bd0e529a9af47dacca576045a4
1,241
class Solution { // Solution @ Sergey Leschev, Belarusian State University // 598. Range Addition II // You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi. // Count and return the number of maximum integers in the matrix after performing all the operations. // Example 1: // Input: m = 3, n = 3, ops = [[2,2],[3,3]] // Output: 4 // Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4. // Example 2: // Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] // Output: 4 // Example 3: // Input: m = 3, n = 3, ops = [] // Output: 9 // Constraints: // 1 <= m, n <= 4 * 10^4 // 1 <= ops.length <= 10^4 // ops[i].length == 2 // 1 <= ai <= m // 1 <= bi <= n func maxCount(_ m: Int, _ n: Int, _ ops: [[Int]]) -> Int { if ops.isEmpty { return m * n } var m = m var n = n for op in ops { m = min(m, op[0]) n = min(n, op[1]) } return m * n } }
29.547619
199
0.490733
f53050dc6fa533e8a9eaf0ec612536df4f5a86b0
2,457
// // AppDelegate.swift // ActionLoggerExample_1 // // Created by Christian Muth on 13.12.15. // Copyright © 2015 Christian Muth. All rights reserved. // import Cocoa // with referencing ActionLogger class a default ActionLogger is created // with this global constant you can use logger in all other files let logger = ActionLogger.defaultLogger() @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var textViewController: ViewController? func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } /// you will see the messages for each LogLevel in different Colors in Xcode console (if you have installed the XcodeColors PlugIn) /// If you have additional installed the PlugIn MCLogForActionLogger you can try the filterfunctions /// choose different levels of output in the bottom left of the console and watch the output in the console. /// also you can try the filter functions in the search field at the bottom of the console /// if you precede the search with a @ char, the search is interpreted as a regular expression @IBAction func generateLineForEachLevel(_ sender: NSMenuItem) { generateLineForEachLevel() logger.logSetupValues() textViewController?.outputLogLines(linesNumber: 1000, log: logger) } func generateLineForEachLevel() { logger.messageOnly("this is the line for level: MessageOnly") logger.comment("this is the line for level: Comment") logger.verbose("this is the line for level: Verbose") logger.info("this is the line for level: Info") logger.debug("this is the line for level: Debug") logger.warning("this is the line for level: Warning") logger.error("this is the line for level: Error") logger.severe("this is the line for level: Severe") } @IBAction func generateOutputToTextViewInWindow(_ sender: NSMenuItem) { if let _ = textViewController { textViewController!.generateOutputToTextViewInWindow() } } @IBAction func fixAttributesInTextView(_ sender: NSMenuItem) { if let _ = textViewController { textViewController!.fixAttributesInTextView() } } }
37.227273
135
0.70289
1d632faf8fc243f2836534ae406f441a2515a629
55,460
/** * Copyright (c) 2017 Håvard Fossli. * * Licensed under the MIT license, as follows: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import Foundation import Security import LocalAuthentication @available(OSX 10.12.1, iOS 9.0, *) public class EllipticCurveKeyPair : NSObject { // A stateful and opiniated manager for using the secure enclave and keychain // If the private or public key is not found this manager will naively just recreate a new keypair // If the device doesn't have a Secure Enclave it will store the private key in keychain just like the public key // // If you think this manager is "too smart" in that sense you may use this manager as an example // and create your own manager // public final class Manager { public var context: LAContext = LAContext() private let config: Config private var helper: Helper private var cachedPublicKey: PublicKey? = nil private var cachedPrivateKey: PrivateKey? = nil public init(config: Config) { self.config = config self.helper = Helper(config: config) super.init() } deinit { do{ try self.deleteKeyPair() } catch { print(error) } } /* Gevin added: */ public func importPrivateKeyB64(_ privateKeyB64: String ) throws { try self.helper.importPrivateKeyBase64(privateKeyB64, context: self.context ) try cachedPrivateKey = self.helper.fetchPrivateKey(context: self.context) } /* Gevin added: */ public func importPrivateKeyData(_ privateKeyData: Data ) throws { try self.helper.importPrivateKeyData(privateKeyData, context: self.context ) try cachedPrivateKey = self.helper.fetchPrivateKey(context: self.context) } /* Gevin added: */ public func importPublicKeyB64(_ publicKeyB64: String ) throws { try self.helper.importPublicKeyBase64(publicKeyB64 ) try cachedPublicKey = self.helper.fetchPublicKey() } /* Gevin added: */ public func importPublicKeyData(_ publicKeyData: Data ) throws { try self.helper.importPublicKeyData(publicKeyData ) try cachedPublicKey = self.helper.fetchPublicKey() } /* Gevin added: */ public func privateKeyDER() throws -> Data { return try self.helper.exportDER( privateKey: self.privateKey()) } /* Gevin added */ public func privateKeyPEM() throws -> String { let privateKeyPEM = try self.helper.exportPEM(privateKey: self.privateKey()) return privateKeyPEM } /* Gevin added: */ public func privateKeyBase64() throws -> String { let data = try self.helper.exportDER( privateKey: self.privateKey()) let b64key = data.base64EncodedString() return b64key } /* Gevin added: */ public func publicKeyDER() throws -> Data { return try self.helper.exportDER( publicKey: self.publicKey()) } /* Gevin added */ public func publicKeyPEM() throws -> String { let publicKeyPEM = try self.helper.exportPEM( publicKey: self.publicKey()) return publicKeyPEM } /* Gevin added: */ public func publicKeyBase64() throws -> String { let data = try self.helper.exportDER( publicKey: self.publicKey()) let b64key = data.base64EncodedString() return b64key } /* Gevin added: */ public func generateKeyPair() throws{ self.context = LAContext() let keys = try helper.generateKeyPair(context: self.context) cachedPublicKey = keys.public cachedPrivateKey = keys.private } public func deleteKeyPair() throws { clearCache() try helper.delete() } public func publicKey() throws -> PublicKey { do { if let key = cachedPublicKey { return key } let key = try helper.fetchPublicKey() cachedPublicKey = key return key }catch EllipticCurveKeyPair.Error.underlying(_, let underlying) where underlying.code == errSecItemNotFound { let keys = try self.helper.generateKeyPair(context: self.context) cachedPublicKey = keys.public cachedPrivateKey = keys.private return keys.public } catch { throw error } } public func privateKey() throws -> PrivateKey { do { if cachedPrivateKey?.context !== context { cachedPrivateKey = nil } if let key = cachedPrivateKey { return key } let key = try helper.fetchPrivateKey(context: context) cachedPrivateKey = key return key } catch EllipticCurveKeyPair.Error.underlying(_, let underlying) where underlying.code == errSecItemNotFound { if config.publicKeyAccessControl.flags.contains(.privateKeyUsage) == false, (try? helper.fetchPublicKey()) != nil { throw Error.probablyAuthenticationError(underlying: underlying) } let keys = try helper.generateKeyPair(context: nil) cachedPublicKey = keys.public cachedPrivateKey = keys.private return keys.private } catch { throw error } } public func keys() throws -> (`public`: PublicKey, `private`: PrivateKey) { let privateKey = try self.privateKey() let publicKey = try self.publicKey() return (public: publicKey, private: privateKey) } public func clearCache() { cachedPublicKey = nil cachedPrivateKey = nil } @available(iOS 10, *) public func sign(_ digest: Data, hash: Hash) throws -> Data { return try helper.sign(digest, privateKey: privateKey(), hash: hash) } @available(OSX, unavailable) @available(iOS, deprecated: 10.0, message: "This method and extra complexity will be removed when 9.0 is obsolete.") public func signUsingSha256(_ digest: Data) throws -> Data { #if os(iOS) return try helper.signUsingSha256(digest, privateKey: privateKey() ) #else throw Error.inconcistency(message: "Should be unreachable.") #endif } @available(iOS 10, *) public func verify(signature: Data, originalDigest: Data, hash: Hash) throws { try helper.verify(signature: signature, digest: originalDigest, publicKey: publicKey(), hash: hash) } @available(OSX, unavailable) @available(iOS, deprecated: 10.0, message: "This method and extra complexity will be removed when 9.0 is obsolete.") public func verifyUsingSha256(signature: Data, originalDigest: Data) throws { #if os(iOS) try helper.verifyUsingSha256(signature: signature, digest: originalDigest, publicKey: publicKey()) #else throw Error.inconcistency(message: "Should be unreachable.") #endif } @available(iOS 10.3, *) // API available at 10.0, but bugs made it unusable on versions lower than 10.3 public func encrypt(_ digest: Data, hash: Hash = .sha256) throws -> Data { return try helper.encrypt(digest, publicKey: publicKey(), hash: hash) } @available(iOS 10.3, *) // API available at 10.0, but bugs made it unusable on versions lower than 10.3 public func decrypt(_ encrypted: Data, hash: Hash = .sha256) throws -> Data { return try helper.decrypt(encrypted, privateKey: privateKey(), hash: hash) } // } public struct Config { // The label used to identify the public key in keychain public var publicLabel: String // The label used to identify the private key on the secure enclave public var privateLabel: String // The text presented to the user about why we need his/her fingerprint / device pin // If you are passing an LAContext to sign or decrypt this value will be rejected public var operationPrompt: String? // The access control used to manage the access to the public key public var publicKeyAccessControl: AccessControl // The access control used to manage the access to the private key public var privateKeyAccessControl: AccessControl // The access group e.g. "BBDV3R8HVV.no.agens.demo" // Useful for shared keychain items public var publicKeyAccessGroup: String? // The access group e.g. "BBDV3R8HVV.no.agens.demo" // Useful for shared keychain items public var privateKeyAccessGroup: String? // Should it be stored on .secureEnclave or in .keychain ? public var token: Token public init(publicLabel: String, privateLabel: String, operationPrompt: String?, publicKeyAccessControl: AccessControl, privateKeyAccessControl: AccessControl, publicKeyAccessGroup: String? = nil, privateKeyAccessGroup: String? = nil, token: Token) { self.publicLabel = publicLabel self.privateLabel = privateLabel self.operationPrompt = operationPrompt self.publicKeyAccessControl = publicKeyAccessControl self.privateKeyAccessControl = privateKeyAccessControl self.publicKeyAccessGroup = publicKeyAccessGroup self.privateKeyAccessGroup = privateKeyAccessGroup self.token = token } } // Helper is a stateless class for querying the secure enclave and keychain // You may create a small stateful facade around this // `Manager` is an example of such an opiniated facade public class Helper { // The open ssl compatible DER format X.509 // // We take the raw key and prepend an ASN.1 headers to it. The end result is an // ASN.1 SubjectPublicKeyInfo structure, which is what OpenSSL is looking for. // // See the following DevForums post for more details on this. // https://forums.developer.apple.com/message/84684#84684 // // End result looks like this // https://lapo.it/asn1js/#3059301306072A8648CE3D020106082A8648CE3D030107034200041F4E3F6CD8163BCC14505EBEEC9C30971098A7FA9BFD52237A3BCBBC48009162AAAFCFC871AC4579C0A180D5F207316F74088BF01A31F83E9EBDC029A533525B // // Header 的資料 // https://stackoverflow.com/questions/45131935/export-an-elliptic-curve-key-from-ios-to-work-with-openssl // // Gevin note: // java 那 private key 的格式,跟 rfc5915 定義不一樣,但為了讓兩邊相容,這邊的輸出改為像 java 那樣 // openssl 則是按照 rfc5915 定義的格式 // private key format // https://tools.ietf.org/html/rfc5915 // ECPrivateKey ::= // SEQUENCE { // |-> version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), // |-> privateKey OCTET STRING, // |-> parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, // |-> publicKey [1] BIT STRING OPTIONAL // } // // 0 116: SEQUENCE { // 2 1: INTEGER 1 // 5 32: OCTET STRING // : ED 03 E5 18 E6 7A CF FD D4 D6 F7 74 76 3D 77 19 // : 9B 33 B8 15 7F 19 81 DB E3 95 B8 B9 96 31 B1 97 // 39 7: [0] { // 41 5: OBJECT IDENTIFIER secp256k1 (1 3 132 0 10) // : } // 48 68: [1] { // 50 66: BIT STRING // : 04 81 53 44 BA 2A D4 34 21 15 75 FE E7 2D 20 54 // : 81 4D 46 5C BA ED 20 17 A0 94 86 CA E7 8B 3D D4 // : 79 56 28 E2 A3 93 80 A4 27 7F C1 C0 60 1F 71 82 // : 9A F8 38 09 D8 85 10 48 3D 79 2B 54 FF 82 13 3D // : 79 // : } // : } // tag 的規則, [tag id] [value len] [ value content .... ] public let x9_62PrivateECHeader = [UInt8]([ /* sequence */ 0x30, 0x81, 0x87, /* |-> Integer */ 0x02, 0x01, 0x00, /* |-> sequence */ 0x30, 0x13, /* |---> ecPublicKey */ 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, // http://oid-info.com/get/1.2.840.10045.2.1 (ANSI X9.62 public key type) /* |---> prime256v1 */ 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, // http://oid-info.com/get/1.2.840.10045.3.1.7 (ANSI X9.62 named elliptic curve) /* |-> octet string */ 0x04, 0x6D, /* |---> sequence */ 0x30, 0x6B, /* |-----> integer */ 0x02, 0x01, 0x01, /* |-----> oct string */ 0x04, 0x20 ]) public let x9_62PrivateECHeader_Element = [UInt8]([ /* |-----> sub element */ 0xA1, 0x44, /* |-----> bit string */ 0x03, 0x42, 0x00 ]) public let x9_62PublicECHeader = [UInt8]([ /* sequence */ 0x30, 0x59, /* |-> sequence */ 0x30, 0x13, /* |---> ecPublicKey */ 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, // http://oid-info.com/get/1.2.840.10045.2.1 (ANSI X9.62 public key type) /* |---> prime256v1 */ 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, // http://oid-info.com/get/1.2.840.10045.3.1.7 (ANSI X9.62 named elliptic curve) /* |-> bit headers */ 0x03, 0x42, 0x00 ]) var _publicKeyData: Data = Data() var _privateKeyData: Data = Data() // The user visible label in the device's key chain public let config: Config // MARK: - init required init(config: Config) { self.config = config } // MARK: - SecKey Manage /* Gevin added */ public func importPrivateKeyBase64(_ privateKeyB64: String, context: LAContext? ) throws{ guard let decodedData = Data.init(base64Encoded: privateKeyB64) else { throw NSError(domain: "Base64DecodeError", code: -1, userInfo: [NSLocalizedDescriptionKey : "import private key, base64 data decode fail."]) } try self.importPrivateKeyData(decodedData, context: context) } public func importPrivateKeyData(_ privateKeyData: Data, context: LAContext? ) throws{ try self.deletePrivateKey() self._privateKeyData.removeAll() // offset 0 為 30 sequence // 81 or 82 用 1 byte or 2 byte 來表示長度, 81 offset +2, 82 offset +3 // 若不是 81 或 82 那就直接代表長度,offset +1 // x9.62 的 tag, 24 byte // 02 01 00 30 13 06 07 2A 86 48 CE 3D 02 01 // 06 08 2A 86 48 CE 3D 03 01 07 // 所以開始 3 + 24 或是 2 + 24 取到值為 04 // 代表 private key 的開頭 // 再加 1 即為 private key 的長度資料 // 所以偏移 27 或 28 的值非 81 82 的話,即代表長度 // 取得長度後,再往後偏移 5 byte 即為 private key 資料內容的開始 // 轉成 byte array let bytes = privateKeyData.withUnsafeBytes { [UInt8](UnsafeBufferPointer(start: $0, count: privateKeyData.count/MemoryLayout<UInt8>.stride)) } var offset = 0 // Sequence 0X30, if bytes[offset] == 0x30 { offset += 1 if bytes[offset] == 0x81 { offset += 2 // length tag(1) + length value(1) = 2 } else if bytes[offset] == 0x82 { offset += 3 // length tag(1) + length value(2) = 3 } else { offset += 1 // length value(1) = 1 } } // 偏移 24 byte, x9.62 的 tag 長度 offset += 24 // octet string var keyLength: UInt32 = 0 if bytes[offset] == 0x04 { offset += 1 if bytes[offset] == 0x81 { keyLength = UInt32( bytes[offset+1] ) offset += 2 } else if bytes[offset] == 0x82 { keyLength = UInt32( bytes[offset] | bytes[offset+1] << 8 ) offset += 3 } else { keyLength = UInt32( bytes[offset] ) offset += 1 } } // sequence 0x30 if bytes[offset] == 0x30 { offset += 1 if bytes[offset] == 0x81 { offset += 2 } else if bytes[offset] == 0x82 { offset += 3 } else { offset += 1 } } // INTEGER 0x02 if bytes[offset] == 0x02 { offset += 3 // tag, length, data, Integer 只有一個長度1 的資料 1, 所以 tag + length + data = 3 } // octet string if bytes[offset] == 0x04 { offset += 1 if bytes[offset] == 0x81 { offset += 2 } else if bytes[offset] == 0x82 { offset += 3 } else { offset += 1 } } let privateKeyStart = offset let privateKeyEnd = privateKeyStart + 32 //let privateKeyStart = x9_62PrivateECHeader.count //let privateKeyEnd = x9_62PrivateECHeader.count + 32 let private_key_data = privateKeyData.subdata(in:privateKeyStart..<privateKeyEnd) //# Gevin_Note: 通常 ECC private key 會包含 public key // 但有的 sdk 產出,就會不包含 public key let publicKeyStart = privateKeyEnd + 5 let publicKeyEnd = publicKeyStart + 65 if publicKeyEnd <= privateKeyData.count { let public_key_data = privateKeyData.subdata(in:publicKeyStart..<publicKeyEnd) self._privateKeyData.append(public_key_data) } else { self._privateKeyData.append(self._publicKeyData) } self._privateKeyData.append(private_key_data) // On iOS 10+, we can use SecKeyCreateWithData without going through the keychain if #available(iOS 10.0, *), #available(watchOS 3.0, *), #available(tvOS 10.0, *) { let sizeInBits = self._privateKeyData.count * 8 let createParams:[CFString:Any] = [ kSecAttrKeyType: kSecAttrKeyTypeEC, //Constants.attrKeyTypeEllipticCurve, kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrKeySizeInBits: NSNumber(value: sizeInBits), kSecReturnPersistentRef: true ] var error: Unmanaged<CFError>? guard let key = SecKeyCreateWithData(self._privateKeyData as CFData, createParams as CFDictionary, &error) else { let errMsg = "Private key create failed." guard let err = error else { throw Error.inconcistency(message: errMsg) } guard let swifterr = err.takeUnretainedValue() as? Error else { throw Error.inconcistency(message: errMsg) } throw Error.underlying(message: errMsg, error: swifterr as NSError ) } try self.forceSaveKey(key, label: config.privateLabel, isPrivate: true) // On iOS 9 and earlier, add a persistent version of the key to the system keychain } else { let persistKey = UnsafeMutablePointer<AnyObject?>(mutating: nil) let keyAddDict: [CFString: Any] = [ kSecClass: kSecClassKey, kSecAttrApplicationTag: config.privateLabel, kSecAttrKeyType: kSecAttrKeyTypeEC, kSecValueData: self._privateKeyData, kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecReturnPersistentRef: true, kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked ] let addStatus = SecItemAdd(keyAddDict as CFDictionary, persistKey) guard addStatus == errSecSuccess || addStatus == errSecDuplicateItem else { throw Error.osStatus(message: "Private key create failed.", osStatus: addStatus) } let keyCopyDict: [CFString: Any] = [ kSecClass: kSecClassKey, kSecAttrApplicationTag: config.privateLabel, kSecAttrKeyType: kSecAttrKeyTypeEC, //Constants.attrKeyTypeEllipticCurve, kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked, kSecReturnRef: true, ] // Now fetch the SecKeyRef version of the key var keyRef: AnyObject? = nil let copyStatus = SecItemCopyMatching(keyCopyDict as CFDictionary, &keyRef) guard keyRef != nil else { throw Error.osStatus(message: "Private key copy failed", osStatus: copyStatus) } } } /* Gevin added */ public func importPublicKeyBase64(_ publicKeyB64: String ) throws { guard let decodedData = Data.init(base64Encoded: publicKeyB64) else { throw NSError(domain: "Base64DecodeError", code: -1, userInfo: [NSLocalizedDescriptionKey : "import public key, base64 data decode fail."]) } try self.importPublicKeyData(decodedData) } public func importPublicKeyData(_ publicKeyData: Data ) throws { try self.deletePublicKey() self._publicKeyData.removeAll() let publicKeyStart = x9_62PublicECHeader.count let publicKeyEnd = publicKeyData.count let public_key_data = publicKeyData.subdata(in:publicKeyStart..<publicKeyEnd) self._publicKeyData.append(public_key_data) // On iOS 10+, we can use SecKeyCreateWithData without going through the keychain if #available(iOS 10.0, *), #available(watchOS 3.0, *), #available(tvOS 10.0, *) { let sizeInBits = _publicKeyData.count * 8 let createParams:[CFString:Any] = [ kSecAttrKeyType: kSecAttrKeyTypeEC, //QueryParam.ECKeyType(), kSecAttrKeyClass: kSecAttrKeyClassPublic, kSecAttrKeySizeInBits: NSNumber(value: sizeInBits), kSecReturnPersistentRef: true ] var error: Unmanaged<CFError>? guard let key = SecKeyCreateWithData(_publicKeyData as CFData, createParams as CFDictionary, &error) else { let errMsg = "Public key create failed." guard let err = error else { throw Error.inconcistency(message: errMsg) } guard let swifterr = err.takeUnretainedValue() as? Error else { throw Error.inconcistency(message: errMsg) } throw Error.underlying(message: errMsg, error: swifterr as NSError ) } try self.forceSaveKey(key, label: config.publicLabel, isPrivate: false) // On iOS 9 and earlier, add a persistent version of the key to the system keychain } else { let persistKey = UnsafeMutablePointer<AnyObject?>(mutating: nil) let keyAddDict: [CFString: Any] = [ kSecClass: kSecClassKey, kSecAttrApplicationTag: config.publicLabel, kSecAttrKeyType: kSecAttrKeyTypeEC, kSecValueData: _publicKeyData, kSecAttrKeyClass: kSecAttrKeyClassPublic, kSecReturnPersistentRef: true, kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked ] let addStatus = SecItemAdd(keyAddDict as CFDictionary, persistKey) guard addStatus == errSecSuccess || addStatus == errSecDuplicateItem else { throw Error.osStatus(message: "Public key create failed.", osStatus: addStatus) } //let keyCopyDict: [CFString: Any] = QueryParam.publicKeyCopy(publicLabel: config.publicLabel) let keyCopyDict: [CFString: Any] = [ kSecClass: kSecClassKey, kSecAttrApplicationTag: config.publicLabel, kSecAttrKeyType: kSecAttrKeyTypeEC, kSecAttrKeyClass: kSecAttrKeyClassPublic, kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked, kSecReturnRef: true, ] // Now fetch the SecKeyRef version of the key var keyRef: AnyObject? = nil let copyStatus = SecItemCopyMatching(keyCopyDict as CFDictionary, &keyRef) guard keyRef != nil else { throw Error.osStatus(message: "Public key copy failed", osStatus: copyStatus) } } } /* Gevin added */ public func exportDER( privateKey: PrivateKey ) throws -> Data { let rawKeyData = try privateKey.exportData() var result = Data() result.append(Data(x9_62PrivateECHeader)) // raw data contains private key data(32) + public key data(65) = 97 let private_key_data = rawKeyData.subdata(in:65..<rawKeyData.count) let public_key_data = rawKeyData.subdata(in:0..<65) result.append(private_key_data) result.append(Data(x9_62PrivateECHeader_Element)) result.append(public_key_data) return result } /* Gevin added */ public func exportPEM(privateKey: PrivateKey) throws -> String { var lines = String() lines.append("-----BEGIN PRIVATE KEY-----\n") lines.append( try self.exportDER(privateKey: privateKey).base64EncodedString(options: [.lineLength64Characters, .endLineWithCarriageReturn])) lines.append("\n-----END PRIVATE KEY-----") return lines } /* Gevin added */ public func exportDER( publicKey: PublicKey ) throws -> Data { let rawKeyData = try publicKey.exportData() var result = Data() result.append(Data(x9_62PublicECHeader)) result.append(rawKeyData) return result } /* Gevin added */ public func exportPEM(publicKey: PublicKey) throws -> String { var lines = String() lines.append("-----BEGIN PUBLIC KEY-----\n") lines.append( try self.exportDER(publicKey: publicKey).base64EncodedString(options: [.lineLength64Characters, .endLineWithCarriageReturn])) lines.append("\n-----END PUBLIC KEY-----") return lines } public func fetchPublicKey() throws -> PublicKey { var params: [CFString:Any] = [ kSecClass: kSecClassKey, kSecAttrKeyClass: kSecAttrKeyClassPublic, kSecAttrApplicationTag: config.publicLabel, kSecReturnRef: true, ] if let accessGroup = config.publicKeyAccessGroup { params[kSecAttrAccessGroup] = accessGroup } let rawKey: SecKey = try self.fetchSecKey(params) return PublicKey(rawKey) } public func fetchPrivateKey(context: LAContext?) throws -> PrivateKey { var params: [CFString:Any] = [ kSecClass: kSecClassKey, kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrApplicationTag: config.privateLabel, kSecReturnRef: true, ] if let accessGroup = config.privateKeyAccessGroup { params[kSecAttrAccessGroup] = accessGroup } if let prompt = config.operationPrompt { params[kSecUseOperationPrompt] = prompt } if let context = context { params[kSecUseAuthenticationContext] = context } let rawKey: SecKey = try self.fetchSecKey(params) return PrivateKey( rawKey, context: context) } func fetchSecKey(_ query: [CFString: Any]) throws -> SecKey { var raw: CFTypeRef? print("## fetchSecKey:\n\(query)") let status = SecItemCopyMatching(query as CFDictionary, &raw) guard status == errSecSuccess, let result = raw else { throw Error.osStatus(message: "Could not get key for query: \(query)", osStatus: status) } return result as! SecKey } public func fetchSecKeyPairs(context: LAContext?) throws -> (`public`: PublicKey, `private`: PrivateKey) { let privateKey = try fetchPrivateKey(context: context) let publicKey = try fetchPublicKey() return (public: publicKey, private: privateKey) } public func generateKeyPair(context: LAContext?) throws -> (`public`: PublicKey, `private`: PrivateKey) { guard config.privateLabel != config.publicLabel else{ throw Error.inconcistency(message: "Public key and private key can not have same label") } let context = context ?? LAContext() // let query = try QueryParam.generateKeyPairQuery(config: config, token: config.token, context: context) /* ========= private ========= */ var privateKeyParams: [CFString: Any] = [ kSecAttrLabel: config.privateLabel, kSecAttrIsPermanent: true, kSecUseAuthenticationUI: kSecUseAuthenticationUIAllow, ] if let privateKeyAccessGroup = config.privateKeyAccessGroup { privateKeyParams[kSecAttrAccessGroup] = privateKeyAccessGroup } privateKeyParams[kSecUseAuthenticationContext] = context // On iOS 11 and lower: access control with empty flags doesn't work if !config.privateKeyAccessControl.flags.isEmpty { privateKeyParams[kSecAttrAccessControl] = try config.privateKeyAccessControl.underlying() } else { privateKeyParams[kSecAttrAccessible] = config.privateKeyAccessControl.protection } /* ========= public ========= */ var publicKeyParams: [CFString: Any] = [ kSecAttrLabel: config.publicLabel, ] if let publicKeyAccessGroup = config.publicKeyAccessGroup { publicKeyParams[kSecAttrAccessGroup] = publicKeyAccessGroup } // On iOS 11 and lower: access control with empty flags doesn't work if !config.publicKeyAccessControl.flags.isEmpty { publicKeyParams[kSecAttrAccessControl] = try config.publicKeyAccessControl.underlying() } else { publicKeyParams[kSecAttrAccessible] = config.publicKeyAccessControl.protection } /* ========= combined ========= */ var params: [CFString: Any] = [ kSecAttrKeyType: kSecAttrKeyTypeEC, //Constants.attrKeyTypeEllipticCurve, kSecPrivateKeyAttrs: privateKeyParams, kSecPublicKeyAttrs: publicKeyParams, kSecAttrKeySizeInBits: 256, ] if config.token == .secureEnclave { params[kSecAttrTokenID] = kSecAttrTokenIDSecureEnclave } var publicOptional, privateOptional: SecKey? print("## generateKeyPair:\n\(params)") let status = SecKeyGeneratePair(params as CFDictionary, &publicOptional, &privateOptional) guard status == errSecSuccess else { if status == errSecAuthFailed { throw Error.osStatus(message: "Could not generate keypair. Security probably doesn't like the access flags you provided. Specifically if this device doesn't have secure enclave and you pass `.privateKeyUsage`. it will produce this error.", osStatus: status) } else { throw Error.osStatus(message: "Could not generate keypair.", osStatus: status) } } guard let publicSec = publicOptional, let privateSec = privateOptional else { throw Error.inconcistency(message: "Created private public key pair successfully, but weren't able to retreive it.") } let publicKey = PublicKey(publicSec) let privateKey = PrivateKey(privateSec, context: context) try self.forceSaveKey(publicSec, label: config.publicLabel, isPrivate: false) try self.forceSaveKey(privateSec, label: config.privateLabel, isPrivate: true) return (public: publicKey, private: privateKey) } func deletePublicKey() throws { var params: [CFString:Any] = [ kSecClass: kSecClassKey, kSecAttrKeyClass: kSecAttrKeyClassPublic, kSecAttrApplicationTag: config.publicLabel, kSecReturnRef: true, ] if let accessGroup = config.publicKeyAccessGroup { params[kSecAttrAccessGroup] = accessGroup } print("## deletePublicKey:\n\(params)") let status = SecItemDelete(params as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw Error.osStatus(message: "Could not delete public key.", osStatus: status) } } func deletePrivateKey() throws { var params: [CFString:Any] = [ kSecClass: kSecClassKey, kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrApplicationTag: config.privateLabel, kSecReturnRef: true, ] if let accessGroup = config.privateKeyAccessGroup { params[kSecAttrAccessGroup] = accessGroup } if let prompt = config.operationPrompt { params[kSecUseOperationPrompt] = prompt } // if let context = context { // params[kSecUseAuthenticationContext] = context // } print("## deletePrivateKey:\n\(params)") let status = SecItemDelete(params as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw Error.osStatus(message: "Could not delete private key.", osStatus: status) } } public func delete() throws { try self.deletePublicKey() try self.deletePrivateKey() } func forceSaveKey(_ rawKey: SecKey, label: String, isPrivate: Bool ) throws { let query: [CFString:Any] = [ kSecClass: kSecClassKey, kSecAttrKeyType: kSecAttrKeyTypeEC, //Constants.attrKeyTypeEllipticCurve, kSecAttrKeyClass: isPrivate ? kSecAttrKeyClassPrivate : kSecAttrKeyClassPublic, kSecAttrApplicationTag: label, kSecValueRef:rawKey, ] var raw: CFTypeRef? print("## SecItemAdd:\n\(query)") var status = SecItemAdd(query as CFDictionary, &raw) if status == errSecDuplicateItem { print("## errSecDuplicateItem") //print("## SecItemDelete: \(query)") status = SecItemDelete(query as CFDictionary) //print("## SecItemAdd: \(query)") status = SecItemAdd(query as CFDictionary, &raw) } if status == errSecInvalidRecord { throw Error.osStatus(message: "Could not save key \(label). It is possible that the access control you have provided is not supported on this OS and/or hardware.", osStatus: status) } else if status != errSecSuccess { throw Error.osStatus(message: "Could not save key \(label)", osStatus: status) } if status == errSecSuccess { print("## SecItemAdd: \(label) add success") } } // MARK: - Sign & Verify @available(iOS 10.0, *) public func sign(_ digest: Data, privateKey: PrivateKey, hash: Hash) throws -> Data { Helper.logToConsoleIfExecutingOnMainThread() var error : Unmanaged<CFError>? let result = SecKeyCreateSignature(privateKey.rawKey, hash.signatureMessage, digest as CFData, &error) guard let signature = result else { throw Error.fromError(error?.takeRetainedValue(), message: "Could not create signature.") } return signature as Data } @available(OSX, unavailable) @available(iOS, deprecated: 10.0, message: "This method and extra complexity will be removed when 9.0 is obsolete.") public func signUsingSha256(_ digest: Data, privateKey: PrivateKey) throws -> Data { #if os(iOS) Helper.logToConsoleIfExecutingOnMainThread() let digestToSign = digest.sha256() var digestToSignBytes = [UInt8](repeating: 0, count: digestToSign.count) digestToSign.copyBytes(to: &digestToSignBytes, count: digestToSign.count) var signatureBytes = [UInt8](repeating: 0, count: 128) var signatureLength = 128 let signErr = SecKeyRawSign(privateKey.rawKey, .PKCS1, &digestToSignBytes, digestToSignBytes.count, &signatureBytes, &signatureLength) guard signErr == errSecSuccess else { throw Error.osStatus(message: "Could not create signature.", osStatus: signErr) } let signature = Data(bytes: &signatureBytes, count: signatureLength) return signature #else throw Error.inconcistency(message: "Should be unreachable.") #endif } @available(iOS 10.0, *) public func verify(signature: Data, digest: Data, publicKey: PublicKey, hash: Hash) throws { var error : Unmanaged<CFError>? let valid = SecKeyVerifySignature(publicKey.rawKey, hash.signatureMessage, digest as CFData, signature as CFData, &error) if let error = error?.takeRetainedValue() { throw Error.fromError(error, message: "Could not verify signature.") } guard valid == true else { throw Error.inconcistency(message: "Signature yielded no error, but still marks itself as unsuccessful") } } @available(OSX, unavailable) @available(iOS, deprecated: 10.0, message: "This method and extra complexity will be removed when 9.0 is obsolete.") public func verifyUsingSha256(signature: Data, digest: Data, publicKey: PublicKey) throws { #if os(iOS) let sha = digest.sha256() var shaBytes = [UInt8](repeating: 0, count: sha.count) sha.copyBytes(to: &shaBytes, count: sha.count) var signatureBytes = [UInt8](repeating: 0, count: signature.count) signature.copyBytes(to: &signatureBytes, count: signature.count) let status = SecKeyRawVerify(publicKey.rawKey, .PKCS1, &shaBytes, shaBytes.count, &signatureBytes, signatureBytes.count) guard status == errSecSuccess else { throw Error.osStatus(message: "Could not verify signature.", osStatus: status) } #else throw Error.inconcistency(message: "Should be unreachable.") #endif } @available(iOS 10.3, *) public func encrypt(_ digest: Data, publicKey: PublicKey, hash: Hash) throws -> Data { var error : Unmanaged<CFError>? let result = SecKeyCreateEncryptedData(publicKey.rawKey, hash.encryptionEciesEcdh, digest as CFData, &error) guard let data = result else { throw Error.fromError(error?.takeRetainedValue(), message: "Could not encrypt.") } return data as Data } @available(iOS 10.3, *) public func decrypt(_ encrypted: Data, privateKey: PrivateKey, hash: Hash) throws -> Data { Helper.logToConsoleIfExecutingOnMainThread() var error : Unmanaged<CFError>? let result = SecKeyCreateDecryptedData(privateKey.rawKey, hash.encryptionEciesEcdh, encrypted as CFData, &error) guard let data = result else { throw Error.fromError(error?.takeRetainedValue(), message: "Could not decrypt.") } return data as Data } private static var logOnceFlag = false public static func logToConsoleIfExecutingOnMainThread() { if logOnceFlag { return } logOnceFlag = true if Thread.isMainThread { print("[WARNING] \(EllipticCurveKeyPair.self): Decryption and signing should be done off main thread because LocalAuthentication may need the thread to show UI. This message is logged only once.") } } } public class Key { public let rawKey: SecKey public var keyType = kSecAttrKeyClassPrivate internal init(_ underlying: SecKey) { self.rawKey = underlying } private var cachedAttributes: [String:Any]? = nil public func attributes() throws -> [String:Any] { if let attributes = cachedAttributes { return attributes } else { let attributes = try queryAttributes() cachedAttributes = attributes return attributes } } public func label() throws -> String { guard let attribute = try self.attributes()[kSecAttrLabel as String] as? String else { throw Error.inconcistency(message: "We've got a private key, but we are missing its label.") } return attribute } public func accessGroup() throws -> String? { return try self.attributes()[kSecAttrAccessGroup as String] as? String } public func accessControl() throws -> SecAccessControl { guard let attribute = try self.attributes()[kSecAttrAccessControl as String] else { throw Error.inconcistency(message: "We've got a private key, but we are missing its access control.") } return attribute as! SecAccessControl } private func queryAttributes() throws -> [String:Any] { var matchResult: AnyObject? = nil let query: [String:Any] = [ kSecClass as String: kSecClassKey, kSecValueRef as String: rawKey, kSecReturnAttributes as String: true ] //print("## SecItemCopyMatching: \(query)") let status = SecItemCopyMatching(query as CFDictionary, &matchResult) guard status == errSecSuccess else { throw Error.osStatus(message: "Could not read attributes for key", osStatus: status) } guard let attributes = matchResult as? [String:Any] else { throw Error.inconcistency(message: "Tried reading key attributes something went wrong. Expected dictionary, but received \(String(describing: matchResult)).") } return attributes } func exportData() throws -> Data { // if #available(iOS 10.0, *) { // var error : Unmanaged<CFError>? // guard let raw = SecKeyCopyExternalRepresentation(rawKey, &error) else { // throw Error.fromError(error?.takeRetainedValue(), message: "Tried reading public key bytes.") // } // return raw as Data // } // else{ // let attributes = try self.queryAttributes() // print("\t>> attribute\n \(attributes)") var matchResult: AnyObject? = nil let query: [String:Any] = [ // kSecAttrKeyClass as String: self.keyType, // kSecAttrApplicationTag: labeled, // kSecClass as String: kSecClassKey, kSecValueRef as String: rawKey, kSecReturnData as String: true, // kSecReturnPersistentRef as String: true ] //print("## SecItemCopyMatching: \(query)") let status = SecItemCopyMatching(query as CFDictionary, &matchResult) guard status == errSecSuccess else { throw Error.osStatus(message: "Could not generate keypair", osStatus: status) } // if let dict = matchResult as? [String:Any] { // let value = dict["v_PersistentRef"] as? Data // return value! // } guard let keyRaw = matchResult as? Data else { throw Error.inconcistency(message: "Tried reading public key bytes. Expected data, but received \(String(describing: matchResult)).") } return keyRaw // } } } public class PublicKey: Key { internal override init(_ secKey: SecKey) { super.init(secKey) self.keyType = kSecAttrKeyClassPublic } } public class PrivateKey: Key { public private(set) var context: LAContext? internal init(_ secKey: SecKey, context: LAContext?) { super.init(secKey) self.keyType = kSecAttrKeyClassPrivate self.context = context } public func isStoredOnSecureEnclave() throws -> Bool { let attribute = try self.attributes()[kSecAttrTokenID as String] as? String return attribute == (kSecAttrTokenIDSecureEnclave as String) } } public final class AccessControl { // E.g. kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly public let protection: CFTypeRef // E.g. [.userPresence, .privateKeyUsage] public let flags: SecAccessControlCreateFlags public init(protection: CFTypeRef, flags: SecAccessControlCreateFlags) { self.protection = protection self.flags = flags } public func underlying() throws -> SecAccessControl { if flags.contains(.privateKeyUsage) { let flagsWithOnlyPrivateKeyUsage: SecAccessControlCreateFlags = [.privateKeyUsage] guard flags != flagsWithOnlyPrivateKeyUsage else { throw Error.inconcistency(message: "Couldn't create access control flag. Keychain chokes if you try to create access control with only [.privateKeyUsage] on devices older than iOS 11 and macOS 10.13.x") } } var error: Unmanaged<CFError>? let result = SecAccessControlCreateWithFlags(kCFAllocatorDefault, protection, flags, &error) guard let accessControl = result else { throw Error.fromError(error?.takeRetainedValue(), message: "Tried creating access control object with flags \(flags) and protection \(protection)") } return accessControl } } public enum Error: LocalizedError { case underlying(message: String, error: NSError) case inconcistency(message: String) case authentication(error: LAError) public var errorDescription: String? { switch self { case let .underlying(message: message, error: error): return "\(message) \(error.localizedDescription)" case let .authentication(error: error): return "Authentication failed. \(error.localizedDescription)" case let .inconcistency(message: message): return "Inconcistency in setup, configuration or keychain. \(message)" } } internal static func osStatus(message: String, osStatus: OSStatus) -> Error { let error = NSError(domain: NSOSStatusErrorDomain, code: Int(osStatus), userInfo: [ NSLocalizedDescriptionKey: message, NSLocalizedRecoverySuggestionErrorKey: "See https://www.osstatus.com/search/results?platform=all&framework=all&search=\(osStatus)" ]) return .underlying(message: message, error: error) } internal static func probablyAuthenticationError(underlying: NSError) -> Error { return Error.authentication(error: .init(_nsError: NSError(domain: LAErrorDomain, code: LAError.authenticationFailed.rawValue, userInfo: [ NSLocalizedFailureReasonErrorKey: "Found public key, but couldn't find or access private key. The errSecItemNotFound error is sometimes wrongfully reported when LAContext authentication fails", NSUnderlyingErrorKey: underlying ]))) } internal static func fromError(_ error: CFError?, message: String) -> Error { let any = error as Any if let authenticationError = any as? LAError { return .authentication(error: authenticationError) } if let error = error, let domain = CFErrorGetDomain(error) as String? { let code = Int(CFErrorGetCode(error)) var userInfo = (CFErrorCopyUserInfo(error) as? [String:Any]) ?? [String:Any]() if userInfo[NSLocalizedRecoverySuggestionErrorKey] == nil { userInfo[NSLocalizedRecoverySuggestionErrorKey] = "See https://www.osstatus.com/search/results?platform=all&framework=all&search=\(code)" } let underlying = NSError(domain: domain, code: code, userInfo: userInfo) return .underlying(message: message, error: underlying) } return .inconcistency(message: "\(message) Unknown error occured.") } } @available(iOS 10.0, *) public enum Hash: String { case sha1 case sha224 case sha256 case sha384 case sha512 @available(iOS 10.0, *) var signatureMessage: SecKeyAlgorithm { switch self { case .sha1: return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA1 case .sha224: return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA224 case .sha256: return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA256 case .sha384: return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA384 case .sha512: return SecKeyAlgorithm.ecdsaSignatureMessageX962SHA512 } } @available(iOS 10.0, *) var encryptionEciesEcdh: SecKeyAlgorithm { switch self { case .sha1: return SecKeyAlgorithm.eciesEncryptionStandardX963SHA1AESGCM case .sha224: return SecKeyAlgorithm.eciesEncryptionStandardX963SHA224AESGCM case .sha256: return SecKeyAlgorithm.eciesEncryptionStandardX963SHA256AESGCM case .sha384: return SecKeyAlgorithm.eciesEncryptionStandardX963SHA384AESGCM case .sha512: return SecKeyAlgorithm.eciesEncryptionStandardX963SHA512AESGCM } } } public enum Token { case secureEnclave case keychain public static var secureEnclaveIfAvailable: Token { return Device.hasSecureEnclave ? .secureEnclave : .keychain } } public enum Device { public static var hasTouchID: Bool { if #available(OSX 10.12.2, *) { return LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) } else { return false } } public static var isSimulator: Bool { return TARGET_OS_SIMULATOR != 0 } public static var hasSecureEnclave: Bool { return hasTouchID && !isSimulator } } } extension Data { struct HexEncodingOptions: OptionSet { let rawValue: Int static let upperCase = HexEncodingOptions(rawValue: 1 << 0) } func hexEncodedString(options: HexEncodingOptions = []) -> String { let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx" return map { String(format: format, $0) }.joined() } }
44.546185
277
0.572178
de86d1b81fe96d1cde2fcada6557c6f5343e6686
2,321
// // PillTextField.swift // Examples // // Created by Drew Olbrich on 12/24/18. // Copyright 2019 Oath Inc. // // Licensed under the terms of the MIT License. See the file LICENSE for the full terms. // import UIKit /// A text field with rounded ends. class PillTextField: UITextField { private let fillColor = UIColor(white: 1, alpha: 0.1) private let outlineColor = UIColor(white: 1, alpha: 0.15) private let placeholderColor = UIColor(white: 1, alpha: 0.4) override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder decoder: NSCoder) { super.init(coder: decoder) commonInit() } private func commonInit() { borderStyle = .none font = UIFont.systemFont(ofSize: 17, weight: .medium) textColor = .white // The insertion point's color and the color of selected text. tintColor = .white updateAttributedPlaceholder() } override func layoutSubviews() { super.layoutSubviews() if background?.size.height != bounds.height { background = roundedCornersImage(fillColor: fillColor, outlineColor: outlineColor, cornerRadius: bounds.height/2) } } override var placeholder: String? { didSet { updateAttributedPlaceholder() } } private func updateAttributedPlaceholder() { let placeholderAttributes: [NSAttributedString.Key: Any] = [ .foregroundColor: placeholderColor, .font: UIFont.systemFont(ofSize: 17, weight: .medium), ] if let placeholder = placeholder { attributedPlaceholder = NSAttributedString(string: placeholder, attributes: placeholderAttributes) } else { attributedPlaceholder = nil } } override func placeholderRect(forBounds bounds: CGRect) -> CGRect { return textRect(forBounds: bounds) } override func editingRect(forBounds bounds: CGRect) -> CGRect { return textRect(forBounds: bounds) } override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: round(bounds.height*0.45), dy: 0) } override var intrinsicContentSize: CGSize { return CGSize(width: 280, height: 44) } }
27.305882
125
0.638087
5b38c45f05b7e5319183a58a3dfe92c6012f9427
514
import Parsing extension FieldSignature { /// Parses a ``FieldSignature`` from a ``Substring``. /// - Returns: The ``Parser`` static func parser() -> AnyParser<Substring, FieldSignature> { Parse(FieldSignature.init) { ModuleSignature.prefixParser() "." Identifier.parser() Optionally { Skip(oneOrMoreSpaces) Rest().map(FieldType.init) } End() } .eraseToAnyParser() } }
25.7
66
0.523346
fba524fbaa8b9c3f2e9198babdd803f36884124b
214
// // HomePagingViewController.swift // Peekr // // Created by Mounir Ybanez on 9/6/19. // Copyright © 2019 Nir. All rights reserved. // import UIKit class HomePagingViewController: UIPageViewController { }
15.285714
54
0.719626
690c51902ead01a578654922e91cd231513e567d
3,262
// The MIT License (MIT) // // Copyright (c) 2020 Alexander Grebenyuk (github.com/kean). import SwiftUI struct TunnelDetailsView: View { @ObservedObject var model: TunnelViewModel var body: some View { NavigationView { Form { Section(header: Text("Settings")) { TextInputView(title: "Username", text: $model.username) TextInputView(title: "Password", text: $model.password) TextInputView(title: "Server", text: $model.server) Button(action: model.buttonSaveTapped) { Text("Save") } .foregroundColor(Color.blue) } Section(header: Text("Status")) { Toggle(isOn: $model.isEnabled, label: { Text("Enabled") }) if model.isEnabled { Text("Status: ") + Text(model.status).bold() if model.isStarted { Button(action: model.buttonStopTapped) { Text("Stop") } .foregroundColor(Color.orange) } else { Button(action: model.buttonStartTapped) { Text("Start") } .foregroundColor(Color.blue) } } } Section { ButtonRemoveProfile(model: model) } } .disabled(model.isLoading) .alert(isPresented: $model.isShowingError) { Alert( title: Text(self.model.errorTitle), message: Text(self.model.errorMessage), dismissButton: .cancel() ) } .navigationBarItems(trailing: Spinner(isAnimating: $model.isLoading, color: .label, style: .medium) ) .navigationBarTitle("VPN Status") } } } private struct TextInputView: View { let title: String let text: Binding<String> var body: some View { HStack(alignment: .center) { Text(title) .font(.callout) TextField(title, text: text) .multilineTextAlignment(.trailing) .foregroundColor(Color.gray) } } } private struct ButtonRemoveProfile: View { let model: TunnelViewModel @State private var isConfirmationPresented = false var body: some View { Button(action: { self.isConfirmationPresented = true }) { Text("Remove Profile") } .foregroundColor(.red) .alert(isPresented: $isConfirmationPresented) { Alert( title: Text("Are you sure you want to remove the profile?"), primaryButton: .destructive(Text("Remove profile"), action: { self.isConfirmationPresented = false self.model.buttonRemoveProfileTapped() }), secondaryButton: .cancel() ) } } } struct TunnelView_Previews: PreviewProvider { static var previews: some View { TunnelDetailsView(model: .init(tunnel: .init())) } }
33.285714
85
0.504292
08d6b261277a4da07923d837cd9c73149d39ba8f
2,233
// // Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved. // The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.") // // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and limitations under the License. // import XCTest struct UserInfoPage { enum Label { case firstname case lastname case username } private let app: XCUIApplication init(app: XCUIApplication) { self.app = app } func label(_ type: Label, value: String) -> XCUIElement { switch type { case .firstname: return app.cells["givenName"].staticTexts.element(matching: .init(format: "label CONTAINS[c] %@", value)) case .lastname: return app.cells["familyName"].staticTexts.element(matching: .init(format: "label CONTAINS[c] %@", value)) case .username: return app.cells["username"].staticTexts.element(matching: .init(format: "label CONTAINS[c] %@", value)) } } func assert(with credentials: Scenario.Credentials) { test("THEN she is redirected to the Root View") { test("AND the cell for the value of 'email' is shown and contains her email") { XCTAssertTrue(label(.username, value: credentials.username).waitForExistence(timeout: .regular)) } test("AND the cell for the value of 'firstname' is shown and contains her first name") { XCTAssertTrue(label(.firstname, value: credentials.firstName).waitForExistence(timeout: .regular)) } test("AND the cell for the value of 'lastname' is shown and contains her last name") { XCTAssertTrue(label(.lastname, value: credentials.lastName).waitForExistence(timeout: .regular)) } } } }
40.6
120
0.644872
fccd9a12b78ceec14999b2b6c2a90db166c31af5
3,003
@testable import GISTools import XCTest final class RhumbDestinationTests: XCTestCase { func testDistance() { let coordinate1 = Coordinate3D(latitude: 38, longitude: -75) let other1 = coordinate1.rhumbDestination(distance: 100_000.0, bearing: 0.0) let result1 = Coordinate3D(latitude: 38.89932036372454, longitude: -75.0) let coordinate2 = Coordinate3D(latitude: 39, longitude: -75) let other2 = coordinate2.rhumbDestination(distance: 100_000.0, bearing: 180.0) let result2 = Coordinate3D(latitude: 38.10067963627546, longitude: -75.0) let coordinate3 = Coordinate3D(latitude: 39, longitude: -75) let other3 = coordinate3.rhumbDestination(distance: 100_000.0, bearing: 90.0) let result3 = Coordinate3D(latitude: 39.0, longitude: -73.84279091917494) let coordinate4 = Coordinate3D(latitude: 39, longitude: -75) let other4 = coordinate4.rhumbDestination(distance: GISTool.convert(length: 5000, from: .miles, to: .meters)!, bearing: 90.0) let result4 = Coordinate3D(latitude: 39.0, longitude: 18.117374548567227) XCTAssertEqual(other1, result1) XCTAssertEqual(other2, result2) XCTAssertEqual(other3, result3) XCTAssertEqual(other4, result4) } func testMeridian() { let coordinate1 = Coordinate3D(latitude: -16.5, longitude: -539.5) let other1 = coordinate1.rhumbDestination(distance: 100_000.0, bearing: -90.0) let result1 = Coordinate3D(latitude: -16.5, longitude: -540.4379451955566) let coordinate2 = Coordinate3D(latitude: -16.5, longitude: -179.5) let other2 = coordinate2.rhumbDestination(distance: 100_000.0, bearing: -90.0) let result2 = Coordinate3D(latitude: -16.5, longitude: -180.43794519555667) let coordinate3 = Coordinate3D(latitude: -16.5, longitude: 179.5) let other3 = coordinate3.rhumbDestination(distance: 150_000.0, bearing: 120.0) let result3 = Coordinate3D(latitude: -17.174490272793403, longitude: 180.72058412338447) XCTAssertEqual(other1, result1) XCTAssertEqual(other2, result2) XCTAssertEqual(other3, result3) } func testAllowsZeroDistance() { let coordinate = Coordinate3D(latitude: 38, longitude: -75) let other = coordinate.rhumbDestination(distance: 0.0, bearing: 45.0) XCTAssertEqual(other, coordinate) } func testAllowsNegativeDistance() { let coordinate = Coordinate3D(latitude: -54.0, longitude: 12.0) let other = coordinate.rhumbDestination(distance: -100_000.0, bearing: 45.0) let result = Coordinate3D(latitude: -54.63591552764877, longitude: 10.90974456038191) XCTAssertEqual(other, result) } static var allTests = [ ("testDistance", testDistance), ("testMeridian", testMeridian), ("testAllowsZeroDistance", testAllowsZeroDistance), ("testAllowsNegativeDistance", testAllowsNegativeDistance), ] }
42.295775
133
0.690643
ffd8db556993e54e1440e76f3e4061dff708873e
518
// // BaseTableViewCell.swift // KOMvvmSample // // Copyright (c) 2019 Kuba Ostrowski // Licensed under the MIT License. See LICENSE file in the project root for full license information. import UIKit class BaseTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.Theme.baseCellBackground self.contentView.tintColor = UIColor.Theme.baseCellTintColor self.selectedBackgroundView = SelectedBackgroundView() } }
28.777778
102
0.735521
5b4f75b5ebe5afe2683f692e8640660210fffddd
285
// // ViewController.swift // PoleControlPanel // // Created by Steven Knodl on 3/28/17. // Copyright © 2017 Steve Knodl. All rights reserved. // import UIKit class RootViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
15
54
0.670175
eb216191e39ac5fb5838efdc0fc74dd76b3824c0
1,040
// // ChatCellTableViewCell.swift // GroupProject // // Created by SiuChun Kung on 10/19/18. // Copyright © 2018 SiuChun Kung. All rights reserved. // import UIKit import Parse import ParseUI import AlamofireImage class ChatTableViewCell: UITableViewCell { @IBOutlet weak var profilePic: UIImageView! @IBOutlet weak var chat: UITextView! var chatRoom: PFObject!{ didSet{ chat.text = (chatRoom["caption"] as! PFUser).username! as String profilePic.af_setImage(withURL: URL(string: "https://api.tumblr.com/v2/blog/humansofnewyork.tumblr.com/avatar")!) profilePic.clipsToBounds = true profilePic.layer.cornerRadius = 7; } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
23.636364
125
0.6375
1d84ad7c019893662c4f8e369a7defcf8c6a149b
3,288
// // ADOBE CONFIDENTIAL // // Copyright 2020 Adobe // All Rights Reserved. // // NOTICE: All information contained herein is, and remains // the property of Adobe and its suppliers, if any. The intellectual // and technical concepts contained herein are proprietary to Adobe // and its suppliers and are protected by all applicable intellectual // property laws, including trade secret and copyright laws. // Dissemination of this information or reproduction of this material // is strictly forbidden unless prior written permission is obtained // from Adobe. // import AEPAssurance import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? @available(iOS 13.0, *) func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } @available(iOS 13.0, *) func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } @available(iOS 13.0, *) func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } @available(iOS 13.0, *) func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } @available(iOS 13.0, *) func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } @available(iOS 13.0, *) func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } @available(iOS 13.0, *) func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { // to note : this method is not called when an app not in memory (forceclosed) is opened with deeplink if let url = URLContexts.first?.url { Assurance.startSession(url: url) } } }
44.432432
147
0.711375
0a0de60301f1fcb3ff2465124b1b90bb23067b42
3,008
// // Coding.swift // SwiftFHIR // // Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/Coding) on 2016-09-16. // 2016, SMART Health IT. // import Foundation /** * A reference to a code defined by a terminology system. */ public class Coding: Element { override public class var resourceType: String { get { return "Coding" } } /// Symbol in syntax defined by the system. public var code: String? /// Representation defined by the system. public var display: String? /// Identity of the terminology system. public var system: URL? /// If this coding was chosen directly by the user. public var userSelected: Bool? /// Version of the system - if relevant. public var version: String? /** Initialize with a JSON object. */ public required init(json: FHIRJSON?, owner: FHIRAbstractBase? = nil) { super.init(json: json, owner: owner) } public override func populate(from json: FHIRJSON?, presentKeys: inout Set<String>) -> [FHIRJSONError]? { var errors = super.populate(from: json, presentKeys: &presentKeys) ?? [FHIRJSONError]() if let js = json { if let exist = js["code"] { presentKeys.insert("code") if let val = exist as? String { self.code = val } else { errors.append(FHIRJSONError(key: "code", wants: String.self, has: type(of: exist))) } } if let exist = js["display"] { presentKeys.insert("display") if let val = exist as? String { self.display = val } else { errors.append(FHIRJSONError(key: "display", wants: String.self, has: type(of: exist))) } } if let exist = js["system"] { presentKeys.insert("system") if let val = exist as? String { self.system = URL(string: val) } else { errors.append(FHIRJSONError(key: "system", wants: String.self, has: type(of: exist))) } } if let exist = js["userSelected"] { presentKeys.insert("userSelected") if let val = exist as? Bool { self.userSelected = val } else { errors.append(FHIRJSONError(key: "userSelected", wants: Bool.self, has: type(of: exist))) } } if let exist = js["version"] { presentKeys.insert("version") if let val = exist as? String { self.version = val } else { errors.append(FHIRJSONError(key: "version", wants: String.self, has: type(of: exist))) } } } return errors.isEmpty ? nil : errors } override public func asJSON(with options: FHIRJSONOptions) -> FHIRJSON { var json = super.asJSON(with: options) if let code = self.code { json["code"] = code.asJSON(with: options) } if let display = self.display { json["display"] = display.asJSON(with: options) } if let system = self.system { json["system"] = system.asJSON(with: options) } if let userSelected = self.userSelected { json["userSelected"] = userSelected.asJSON(with: options) } if let version = self.version { json["version"] = version.asJSON(with: options) } return json } }
25.931034
106
0.643285
0968a5f058386dcfd05552ae13c7bbec6f6b7bf9
2,928
import Metal internal class MTLTextureDescriptorCodableBox: Codable { let descriptor: MTLTextureDescriptor init(descriptor: MTLTextureDescriptor) { self.descriptor = descriptor } required init(from decoder: Decoder) throws { self.descriptor = try MTLTextureDescriptor(from: decoder) } func encode(to encoder: Encoder) throws { try self.descriptor.encode(to: encoder) } } extension MTLTextureDescriptor: Encodable { internal enum CodingKeys: String, CodingKey { case width case height case depth case arrayLength case storageMode case cpuCacheMode case usage case textureType case sampleCount case mipmapLevelCount case pixelFormat case allowGPUOptimizedContents } public convenience init(from decoder: Decoder) throws { self.init() let container = try decoder.container(keyedBy: CodingKeys.self) self.width = try container.decode(Int.self, forKey: .width) self.height = try container.decode(Int.self, forKey: .height) self.depth = try container.decode(Int.self, forKey: .depth) self.arrayLength = try container.decode(Int.self, forKey: .arrayLength) self.cpuCacheMode = try container.decode(MTLCPUCacheMode.self, forKey: .cpuCacheMode) self.usage = try container.decode(MTLTextureUsage.self, forKey: .usage) self.textureType = try container.decode(MTLTextureType.self, forKey: .textureType) self.sampleCount = try container.decode(Int.self, forKey: .sampleCount) self.mipmapLevelCount = try container.decode(Int.self, forKey: .mipmapLevelCount) self.pixelFormat = try container.decode(MTLPixelFormat.self, forKey: .pixelFormat) if #available(iOS 12, macOS 10.14, *) { self.allowGPUOptimizedContents = (try? container.decode(Bool.self, forKey: .allowGPUOptimizedContents)) ?? true } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.width, forKey: .width) try container.encode(self.height, forKey: .height) try container.encode(self.depth, forKey: .depth) try container.encode(self.arrayLength, forKey: .arrayLength) try container.encode(self.cpuCacheMode, forKey: .cpuCacheMode) try container.encode(self.usage, forKey: .usage) try container.encode(self.textureType, forKey: .textureType) try container.encode(self.sampleCount, forKey: .sampleCount) try container.encode(self.mipmapLevelCount, forKey: .mipmapLevelCount) try container.encode(self.pixelFormat, forKey: .pixelFormat) if #available(iOS 12, macOS 10.14, *) { try container.encode(self.allowGPUOptimizedContents, forKey: .allowGPUOptimizedContents) } } }
39.04
123
0.686475
fbc8dcf9b45c89653fba650cf8c6e5d4f879946e
9,298
// // CURLRequestOptions.swift // PerfectCURL // // Created by Kyle Jessup on 2017-05-17. // Copyright (C) 2017 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2017 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import CCurlyCURL #if canImport(Darwin) import Darwin #elseif canImport(Glibc) import Glibc #endif extension CURLRequest.Option { private func headerAdd(_ curl: CURL, optName: CURLRequest.Header.Name, optValue: String) { if optValue.isEmpty { curl.setOption(CURLOPT_HTTPHEADER, s: "\(optName.standardName);") } else { curl.setOption(CURLOPT_HTTPHEADER, s: "\(optName.standardName): \(optValue)") } } func apply(to request: CURLRequest) { let curl = request.curl switch self { case .url(let optString): curl.setOption(CURLOPT_URL, s: optString) case .port(let optInt): curl.setOption(CURLOPT_PORT, int: optInt) case .failOnError: curl.setOption(CURLOPT_FAILONERROR, int: 1) case .userPwd(let optString): curl.setOption(CURLOPT_USERPWD, s: optString) case .proxy(let optString): curl.setOption(CURLOPT_PROXY, s: optString) case .proxyUserPwd(let optString): curl.setOption(CURLOPT_PROXYUSERPWD, s: optString) case .proxyPort(let optInt): curl.setOption(CURLOPT_PROXYPORT, int: optInt) case .timeout(let optInt): curl.setOption(CURLOPT_TIMEOUT, int: optInt) case .timeoutMs(let optInt): curl.setOption(CURLOPT_TIMEOUT_MS, int: optInt) case .connectTimeout(let optInt): curl.setOption(CURLOPT_CONNECTTIMEOUT, int: optInt) case .connectTimeoutMs(let optInt): curl.setOption(CURLOPT_CONNECTTIMEOUT_MS, int: optInt) case .lowSpeedLimit(let optInt): curl.setOption(CURLOPT_LOW_SPEED_LIMIT, int: optInt) case .lowSpeedTime(let optInt): curl.setOption(CURLOPT_LOW_SPEED_TIME, int: optInt) case .range(let optString): curl.setOption(CURLOPT_RANGE, s: optString) case .resumeFrom(let optInt): curl.setOption(CURLOPT_RESUME_FROM_LARGE, int: Int64(optInt)) case .cookie(let optString): curl.setOption(CURLOPT_COOKIE, s: optString) case .cookieFile(let optString): curl.setOption(CURLOPT_COOKIEFILE, s: optString) case .cookieJar(let optString): curl.setOption(CURLOPT_COOKIEJAR, s: optString) case .followLocation(let optBool): curl.setOption(CURLOPT_FOLLOWLOCATION, int: optBool ? 1 : 0) case .maxRedirects(let optInt): curl.setOption(CURLOPT_MAXREDIRS, int: optInt) case .maxConnects(let optInt): curl.setOption(CURLOPT_MAXCONNECTS, int: optInt) case .autoReferer(let optBool): curl.setOption(CURLOPT_AUTOREFERER, int: optBool ? 1 : 0) case .krbLevel(let optString): curl.setOption(CURLOPT_KRBLEVEL, s: optString.description) case .addHeader(let optName, let optValue): headerAdd(curl, optName: optName, optValue: optValue) case .addHeaders(let optArray): optArray.forEach { self.headerAdd(curl, optName: $0, optValue: $1) } case .replaceHeader(let optName, let optValue): curl.setOption(CURLOPT_HTTPHEADER, s: "\(optName.standardName):") headerAdd(curl, optName: optName, optValue: optValue) case .removeHeader(let optName): curl.setOption(CURLOPT_HTTPHEADER, s: "\(optName.standardName):") case .useSSL: curl.setOption(CURLOPT_USE_SSL, int: Int(CURLUSESSL_ALL.rawValue)) case .sslCert(let optString): curl.setOption(CURLOPT_SSLCERT, s: optString) case .sslCertType(let optString): curl.setOption(CURLOPT_SSLCERTTYPE, s: optString.description) case .sslKey(let optString): curl.setOption(CURLOPT_SSLKEY, s: optString) case .sslKeyPwd(let optString): curl.setOption(CURLOPT_KEYPASSWD, s: optString) case .sslKeyType(let optString): curl.setOption(CURLOPT_SSLKEYTYPE, s: optString.description) case .sslVersion(let optVersion): let value: Int switch optVersion { case .tlsV1: value = CURL_SSLVERSION_TLSv1 case .tlsV1_1: value = CURL_SSLVERSION_TLSv1_1 case .tlsV1_2: value = CURL_SSLVERSION_TLSv1_2 } curl.setOption(CURLOPT_SSLVERSION, int: value) case .sslVerifyPeer(let optBool): curl.setOption(CURLOPT_SSL_VERIFYPEER, int: optBool ? 1 : 0) case .sslVerifyHost(let optBool): curl.setOption(CURLOPT_SSL_VERIFYHOST, int: optBool ? 2 : 0) case .sslCAFilePath(let optString): curl.setOption(CURLOPT_CAINFO, s: optString) case .sslCADirPath(let optString): curl.setOption(CURLOPT_CAPATH, s: optString) case .sslPinnedPublicKey(let optString): curl.setOption(CURLOPT_PINNEDPUBLICKEY, s: optString) case .sslCiphers(let optArray): curl.setOption(CURLOPT_SSL_CIPHER_LIST, s: optArray.joined(separator: ":")) case .ftpPreCommands(let optArray): optArray.forEach { curl.setOption(CURLOPT_PREQUOTE, s: $0) } case .ftpPostCommands(let optArray): optArray.forEach { curl.setOption(CURLOPT_POSTQUOTE, s: $0) } case .ftpPort(let optString): curl.setOption(CURLOPT_FTPPORT, s: optString) case .ftpResponseTimeout(let optInt): curl.setOption(CURLOPT_FTP_RESPONSE_TIMEOUT, int: optInt) case .sshPublicKey(let optString): curl.setOption(CURLOPT_SSH_PUBLIC_KEYFILE, s: optString) case .sshPrivateKey(let optString): curl.setOption(CURLOPT_SSH_PRIVATE_KEYFILE, s: optString) case .httpMethod(let optHTTPMethod): switch optHTTPMethod { case .get: curl.setOption(CURLOPT_HTTPGET, int: 1) case .post: curl.setOption(CURLOPT_POST, int: 1) case .head: curl.setOption(CURLOPT_NOBODY, int: 1) case .patch: curl.setOption(CURLOPT_CUSTOMREQUEST, s: "PATCH") case .delete, .put, .trace, .options, .connect, .custom(_): curl.setOption(CURLOPT_CUSTOMREQUEST, s: optHTTPMethod.description) } case .postField(let optPOSTField): if nil == request.postFields { request.postFields = CURLRequest.POSTFields() } switch optPOSTField.type { case .value: _ = request.postFields?.append(key: optPOSTField.name, value: optPOSTField.value, mimeType: optPOSTField.mimeType ?? "") case .file: _ = request.postFields?.append(key: optPOSTField.name, path: optPOSTField.value, mimeType: optPOSTField.mimeType ?? "") } case .postData(let optBytes): curl.setOption(CURLOPT_POSTFIELDSIZE_LARGE, int: optBytes.count) curl.setOption(CURLOPT_COPYPOSTFIELDS, v: optBytes) case .postString(let optString): let bytes = Array(optString.utf8) curl.setOption(CURLOPT_POSTFIELDSIZE_LARGE, int: bytes.count) curl.setOption(CURLOPT_COPYPOSTFIELDS, v: bytes) case .mailFrom(let optString): curl.setOption(CURLOPT_MAIL_FROM, s: optString) case .mailRcpt(let optString): curl.setOption(CURLOPT_MAIL_RCPT, s: optString) case .verbose: curl.setOption(CURLOPT_VERBOSE, int: 1) case .header: curl.setOption(CURLOPT_HEADER, int: 1) case .upload(let gen): curl.setOption(CURLOPT_UPLOAD, int: 1) request.uploadBodyGen = gen if let len = gen.contentLength { curl.setOption(CURLOPT_INFILESIZE_LARGE, int: len) } let opaqueRequest = Unmanaged<AnyObject>.passRetained(request as AnyObject).toOpaque() let curlFunc: curl_func = { ptr, size, count, opaque -> Int in guard let opaque = opaque, let ptr = ptr else { return 0 } let this = Unmanaged<CURLRequest>.fromOpaque(opaque).takeUnretainedValue() guard let bytes = this.uploadBodyGen?.next(byteCount: size*count) else { return 0 } memcpy(ptr, bytes, bytes.count) return bytes.count } curl.setOption(CURLOPT_READDATA, v: opaqueRequest) curl.setOption(CURLOPT_READFUNCTION, f: curlFunc) case .acceptEncoding(let str): curl.setOption(CURLOPT_ACCEPT_ENCODING, s: str) } } }
45.356098
136
0.614326
236fc14c52c93197058a2aedf09245db84642700
1,713
// // Constants.swift // Domain // // Created by Gilwan Ryu on 2020/03/03. // Copyright © 2020 Gilwan Ryu. All rights reserved. // import Foundation public struct Constants { public struct Key { public static let coinMarketCapKey = "204918f9-4725-4dfb-acc1-26662aa93bff" public static let cryptoCompareKey = "5f8a6d771949191aed7a988ab7dbdc3adb1d569099b2f00da51bb2748c71fc17" } public struct Coin { public struct CoinMarketCap { private static let BaseUrl = "https://pro-api.coinmarketcap.com" public static let imageBaseUrl = "https://chasing-coins.com/api/v1/std/logo/" public static let list = "\(BaseUrl)/v1/cryptocurrency/listings/latest" } public struct CryptoCompare { private static let BaseUrl = "https://min-api.cryptocompare.com" private static let detailBaseUrl = "https://www.cryptocompare.com" public static let list = "\(BaseUrl)/data/all/coinlist" public static let detail = "\(detailBaseUrl)/api/data/coinsnapshotfullbyid" } } public struct General { public struct News { private static let baseUrl = "https://min-api.cryptocompare.com" public static let list = "\(baseUrl)/data/v2/news/?lang=EN" } public struct Mining { private static let baseUrl = "https://min-api.cryptocompare.com" public static let imageBaseUrl = "https://www.cryptocompare.com" public static let list = "\(baseUrl)/data/mining/pools/general?api_key=\(Constants.Key.cryptoCompareKey)" } } public struct About { } }
34.26
117
0.629889
23898b3ad23d319ffa6c14074e5640a40f3cfbbf
517
// // ViewController.swift // GZImageLayoutViewDemo // // Created by Grady Zhuo on 2/19/15. // Copyright (c) 2015 Grady Zhuo. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.884615
80
0.673114
76d8c4f4862b2e8b07fdd1095c981aadd15f2071
882
// // ViewController.swift // myCameraDemoSwift3 // // Created by NowOrNever on 18/07/2017. // Copyright © 2017 Focus. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupUI() } fileprivate func setupUI(){ let button = UIButton.init(type: .contactAdd) button.addTarget(self, action:#selector(buttonFunction), for: .touchUpInside); self.view.addSubview(button) button.center = self.view.center } @objc func buttonFunction() { let vc = AVCaptureVideoPicViewController() present(vc, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
22.615385
86
0.651927
5b886e91e424b4c95f24c5c8e226f4c57b6a1387
2,787
// // CalendarViewModel.swift // TylerCalendarView-iOSTests // // Created by tskim on 13/05/2019. // Copyright © 2019 Tyler. All rights reserved. // import Foundation import UIKit enum CalendarViewModelItemType { case dayOfWeek case date } protocol CalendarViewModelItem { var type: CalendarViewModelItemType { get } var sectionTitle: String { get } var rowCount: Int { get } } struct DayOfWeekViewModel: CalendarViewModelItem { var type: CalendarViewModelItemType = .dayOfWeek var sectionTitle: String var items: [String] var rowCount: Int { return items.count } init() { type = .dayOfWeek items = DayOfWeek.all sectionTitle = "DayOfWeek" } } struct DateViewModel: CalendarViewModelItem { private let titleDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy. MM" return formatter }() var type: CalendarViewModelItemType = .date var sectionTitle: String = "Date" var rowCount: Int { return items.count } var items: [String] var todayTitle: String public init(source: CalendarSource) { todayTitle = titleDateFormatter.string(from: source.startDate) items = source.days() } } class CalendarViewModel: NSObject { var items: [CalendarViewModelItem] = [] init(items: [CalendarViewModelItem]) { self.items = items } } extension CalendarViewModel: UICollectionViewDataSource { public func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int { return items[section].rowCount } public func numberOfSections(in collectionView: UICollectionView) -> Int { return items.count } public func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let item = items[indexPath.section] switch item.type { case .dayOfWeek: if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DayOfWeekCell.swiftIdentifier, for: indexPath) as? DayOfWeekCell, let item = (self.items[indexPath.section] as? DayOfWeekViewModel)?.items[indexPath.row] { cell.configCell(item) return cell } case .date: if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DateCell.swiftIdentifier, for: indexPath) as? DateCell, let item = (self.items[indexPath.section] as? DateViewModel)?.items[indexPath.row] { cell.configCell(item) return cell } } return UICollectionViewCell() } }
27.058252
147
0.651597
5d8858fd34075d21f1729e3d2c13a481625b6f98
25,717
// Copyright © 2018 Stormbird PTE. LTD. import Foundation import UIKit import APIKit import BigInt import JSONRPCKit import Moya import PromiseKit import Result import UserNotifications class SingleChainTransactionEtherscanDataCoordinator: SingleChainTransactionDataCoordinator { private let storage: TransactionsStorage let session: WalletSession private let keystore: Keystore private let tokensStorage: TokensDataStore private let promptBackupCoordinator: PromptBackupCoordinator private let fetchLatestTransactionsQueue: OperationQueue private let queue = DispatchQueue(label: "com.SingleChainTransaction.updateQueue") private var timer: Timer? private var updateTransactionsTimer: Timer? private lazy var transactionsTracker: TransactionsTracker = { return TransactionsTracker(sessionID: session.sessionID) }() private let alphaWalletProvider = AlphaWalletProviderFactory.makeProvider() private var isAutoDetectingERC20Transactions: Bool = false private var isAutoDetectingErc721Transactions: Bool = false private var isFetchingLatestTransactions = false var coordinators: [Coordinator] = [] weak var delegate: SingleChainTransactionDataCoordinatorDelegate? lazy var tokenProvider: TokenProviderType = TokenProvider(account: session.account, server: session.server) required init( session: WalletSession, storage: TransactionsStorage, keystore: Keystore, tokensStorage: TokensDataStore, promptBackupCoordinator: PromptBackupCoordinator, onFetchLatestTransactionsQueue fetchLatestTransactionsQueue: OperationQueue ) { self.session = session self.storage = storage self.keystore = keystore self.tokensStorage = tokensStorage self.promptBackupCoordinator = promptBackupCoordinator self.fetchLatestTransactionsQueue = fetchLatestTransactionsQueue } func start() { runScheduledTimers() if transactionsTracker.fetchingState != .done { fetchOlderTransactions(for: session.account.address) autoDetectERC20Transactions() autoDetectErc721Transactions() } } func stopTimers() { timer?.invalidate() timer = nil updateTransactionsTimer?.invalidate() updateTransactionsTimer = nil } func runScheduledTimers() { guard timer == nil, updateTransactionsTimer == nil else { return } timer = Timer.scheduledTimer(timeInterval: 5, target: BlockOperation { [weak self] in guard let strongSelf = self else { return } strongSelf.queue.async { strongSelf.fetchPendingTransactions() } }, selector: #selector(Operation.main), userInfo: nil, repeats: true) updateTransactionsTimer = Timer.scheduledTimer(timeInterval: 15, target: BlockOperation { [weak self] in guard let strongSelf = self else { return } strongSelf.queue.async { strongSelf.fetchLatestTransactions() strongSelf.autoDetectERC20Transactions() strongSelf.autoDetectErc721Transactions() } }, selector: #selector(Operation.main), userInfo: nil, repeats: true) } //TODO should this be added to the queue? //TODO when blockscout-compatible, this includes ERC721 too. Maybe rename? private func autoDetectERC20Transactions() { guard !isAutoDetectingERC20Transactions else { return } isAutoDetectingERC20Transactions = true let server = session.server let wallet = session.account.address let startBlock = Config.getLastFetchedErc20InteractionBlockNumber(session.server, wallet: wallet).flatMap { $0 + 1 } firstly { GetContractInteractions(queue: queue).getErc20Interactions(address: wallet, server: server, startBlock: startBlock) }.map { result in functional.extractBoundingBlockNumbers(fromTransactions: result) }.then { result, minBlockNumber, maxBlockNumber in functional.backFillTransactionGroup(result, startBlock: minBlockNumber, endBlock: maxBlockNumber, session: self.session, alphaWalletProvider: self.alphaWalletProvider, tokensStorage: self.tokensStorage, tokenProvider: self.tokenProvider, queue: self.queue).map { ($0, maxBlockNumber) } }.done(on: queue) { backFilledTransactions, maxBlockNumber in //Just to be sure, we don't want any kind of strange errors to clear our progress by resetting blockNumber = 0 if maxBlockNumber > 0 { Config.setLastFetchedErc20InteractionBlockNumber(maxBlockNumber, server: server, wallet: wallet) } self.update(items: backFilledTransactions) }.cauterize() .finally { self.isAutoDetectingERC20Transactions = false } } private func autoDetectErc721Transactions() { guard !isAutoDetectingErc721Transactions else { return } isAutoDetectingErc721Transactions = true let server = session.server let wallet = session.account.address let startBlock = Config.getLastFetchedErc721InteractionBlockNumber(session.server, wallet: wallet).flatMap { $0 + 1 } firstly { GetContractInteractions(queue: queue).getErc721Interactions(address: wallet, server: server, startBlock: startBlock) }.map(on: queue, { result in functional.extractBoundingBlockNumbers(fromTransactions: result) }).then(on: queue, { result, minBlockNumber, maxBlockNumber in functional.backFillTransactionGroup(result, startBlock: minBlockNumber, endBlock: maxBlockNumber, session: self.session, alphaWalletProvider: self.alphaWalletProvider, tokensStorage: self.tokensStorage, tokenProvider: self.tokenProvider, queue: self.queue).map { ($0, maxBlockNumber) } }).done(on: queue) { backFilledTransactions, maxBlockNumber in //Just to be sure, we don't want any kind of strange errors to clear our progress by resetting blockNumber = 0 if maxBlockNumber > 0 { Config.setLastFetchedErc721InteractionBlockNumber(maxBlockNumber, server: server, wallet: wallet) } self.update(items: backFilledTransactions) }.cauterize() .finally { self.isAutoDetectingErc721Transactions = false } } func fetch() { queue.async { self.session.refresh(.balance) self.fetchLatestTransactions() self.fetchPendingTransactions() } } private func update(items: [TransactionInstance]) { guard !items.isEmpty else { return } filterTransactionsToPullContractsFrom(items).done(on: .main, { transactionsToPullContractsFrom, contractsAndTokenTypes in //NOTE: Realm write operation! self.storage.add(transactions: items, transactionsToPullContractsFrom: transactionsToPullContractsFrom, contractsAndTokenTypes: contractsAndTokenTypes) self.delegate?.handleUpdateItems(inCoordinator: self, reloadImmediately: false) }).cauterize() } private func detectContractsToAvoid(for tokensStorage: TokensDataStore) -> Promise<[AlphaWallet.Address]> { return Promise { seal in DispatchQueue.main.async { let deletedContracts = tokensStorage.deletedContracts.map { $0.contractAddress } let hiddenContracts = tokensStorage.hiddenContracts.map { $0.contractAddress } let delegateContracts = tokensStorage.delegateContracts.map { $0.contractAddress } let values = tokensStorage.enabledObjectAddresses + deletedContracts + hiddenContracts + delegateContracts seal.fulfill(values) } } } private func filterTransactionsToPullContractsFrom(_ transactions: [TransactionInstance]) -> Promise<(transactions: [TransactionInstance], contractTypes: [AlphaWallet.Address: TokenType])> { return detectContractsToAvoid(for: tokensStorage).then(on: queue, { contractsToAvoid -> Promise<(transactions: [TransactionInstance], contractTypes: [AlphaWallet.Address: TokenType])> in let filteredTransactions = transactions.filter { if let toAddressToCheck = AlphaWallet.Address(string: $0.to), contractsToAvoid.contains(toAddressToCheck) { return false } if let contractAddressToCheck = $0.operation?.contractAddress, contractsToAvoid.contains(contractAddressToCheck) { return false } return true } //The fetch ERC20 transactions endpoint from Etherscan returns only ERC20 token transactions but the Blockscout version also includes ERC721 transactions too (so it's likely other types that it can detect will be returned too); thus we check the token type rather than assume that they are all ERC20 let contracts = Array(Set(filteredTransactions.compactMap { $0.localizedOperations.first?.contractAddress })) let tokenTypePromises = contracts.map { self.tokenProvider.getTokenType(for: $0) } return when(fulfilled: tokenTypePromises).map(on: self.queue, { tokenTypes in let contractsToTokenTypes = Dictionary(uniqueKeysWithValues: zip(contracts, tokenTypes)) return (transactions: filteredTransactions, contractTypes: contractsToTokenTypes) }) }) } private func fetchPendingTransactions() { storage.pendingObjects.done { txs in for each in txs { self.updatePendingTransaction(each ) } }.cauterize() } private func updatePendingTransaction(_ transaction: TransactionInstance) { let request = GetTransactionRequest(hash: transaction.id) firstly { Session.send(EtherServiceRequest(server: session.server, batch: BatchFactory().create(request))) }.done { pendingTransaction in if let blockNumber = Int(pendingTransaction.blockNumber), blockNumber > 0 { //NOTE: We dont want to call function handleUpdateItems: twice because it will be updated in update(items: self.update(state: .completed, for: transaction, withPendingTransaction: pendingTransaction, shouldUpdateItems: false) self.update(items: [transaction]) } }.catch { error in switch error as? SessionTaskError { case .responseError(let error): // TODO: Think about the logic to handle pending transactions. //TODO we need to detect when a transaction is marked as failed by the node? switch error as? JSONRPCError { case .responseError: self.delete(transactions: [transaction]) case .resultObjectParseError: self.storage.hasCompletedTransaction(withNonce: transaction.nonce).done(on: self.queue, { value in if value { self.delete(transactions: [transaction]) } }).cauterize() //The transaction might not be posted to this node yet (ie. it doesn't even think that this transaction is pending). Especially common if we post a transaction to TaiChi and fetch pending status through Etherscan case .responseNotFound, .errorObjectParseError, .unsupportedVersion, .unexpectedTypeObject, .missingBothResultAndError, .nonArrayResponse, .none: break } case .connectionError, .requestError, .none: break } } } private func delete(transactions: [TransactionInstance]) { storage.delete(transactions: transactions).done(on: self.queue, { _ in self.delegate?.handleUpdateItems(inCoordinator: self, reloadImmediately: true) }).cauterize() } private func update(state: TransactionState, for transaction: TransactionInstance, withPendingTransaction pendingTransaction: PendingTransaction?, shouldUpdateItems: Bool = true) { storage.update(state: state, for: transaction.primaryKey, withPendingTransaction: pendingTransaction).done(on: self.queue, { _ in guard shouldUpdateItems else { return } self.delegate?.handleUpdateItems(inCoordinator: self, reloadImmediately: false) }).cauterize() } ///Fetching transactions might take a long time, we use a flag to make sure we only pull the latest transactions 1 "page" at a time, otherwise we'd end up pulling the same "page" multiple times private func fetchLatestTransactions() { guard !isFetchingLatestTransactions else { return } isFetchingLatestTransactions = true storage.transactionObjectsThatDoNotComeFromEventLogs().done(on: self.queue, { value in let startBlock: Int let sortOrder: AlphaWalletService.SortOrder if let newestCachedTransaction = value { startBlock = newestCachedTransaction.blockNumber + 1 sortOrder = .asc } else { startBlock = 1 sortOrder = .desc } let operation = FetchLatestTransactionsOperation(forSession: self.session, coordinator: self, startBlock: startBlock, sortOrder: sortOrder, queue: self.queue) self.fetchLatestTransactionsQueue.addOperation(operation) }).cauterize() } private func handleError(error: Error) { //delegate?.didUpdate(result: .failure(TransactionError.failedToFetch)) // Avoid showing an error on failed request, instead show cached transactions. } //TODO notify user of received tokens too private func notifyUserEtherReceived(inNewTransactions transactions: [TransactionInstance]) { guard !transactions.isEmpty else { return } let wallet = keystore.currentWallet storage.transactions.done(on: queue, { objects in var toNotify: [TransactionInstance] if let newestCached = objects.first { toNotify = transactions.filter { $0.blockNumber > newestCached.blockNumber } } else { toNotify = transactions } //Beyond a certain number, it's too noisy and a performance nightmare. Eg. the first time we fetch transactions for a newly imported wallet, we might get 10,000 of them let maximumNumberOfNotifications = 10 if toNotify.count > maximumNumberOfNotifications { toNotify = Array(toNotify[0..<maximumNumberOfNotifications]) } let toNotifyUnique: [TransactionInstance] = self.filterUniqueTransactions(toNotify) let newIncomingEthTransactions = toNotifyUnique.filter { wallet.address.sameContract(as: $0.to) } let formatter = EtherNumberFormatter.short let thresholdToShowNotification = Date.yesterday for each in newIncomingEthTransactions { let amount = formatter.string(from: BigInt(each.value) ?? BigInt(), decimals: 18) if each.date > thresholdToShowNotification { self.notifyUserEtherReceived(for: each.id, amount: amount) } } let etherReceivedUsedForBackupPrompt = newIncomingEthTransactions .last { wallet.address.sameContract(as: $0.to) } .flatMap { BigInt($0.value) } DispatchQueue.main.async { switch self.session.server { //TODO make this work for other mainnets case .main: etherReceivedUsedForBackupPrompt.flatMap { self.promptBackupCoordinator.showCreateBackupAfterReceiveNativeCryptoCurrencyPrompt(nativeCryptoCurrency: $0) } case .classic, .xDai: break case .kovan, .ropsten, .rinkeby, .poa, .sokol, .callisto, .goerli, .artis_sigma1, .artis_tau1, .binance_smart_chain, .binance_smart_chain_testnet, .custom, .heco, .heco_testnet, .fantom, .fantom_testnet, .avalanche, .avalanche_testnet, .polygon, .mumbai_testnet, .optimistic, .optimisticKovan, .cronosTestnet: break } } }).cauterize() } //Etherscan for Ropsten returns the same transaction twice. Normally Realm will take care of this, but since we are showing user a notification, we don't want to show duplicates private func filterUniqueTransactions(_ transactions: [TransactionInstance]) -> [TransactionInstance] { var results = [TransactionInstance]() for each in transactions { if !results.contains(where: { each.id == $0.id }) { results.append(each) } } return results } private func notifyUserEtherReceived(for transactionId: String, amount: String) { let notificationCenter = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() //TODO support other mainnets too switch session.server { case .main, .xDai: content.body = R.string.localizable.transactionsReceivedEther(amount, session.server.symbol) case .kovan, .ropsten, .rinkeby, .poa, .sokol, .classic, .callisto, .goerli, .artis_sigma1, .artis_tau1, .binance_smart_chain, .binance_smart_chain_testnet, .custom, .heco, .heco_testnet, .fantom, .fantom_testnet, .avalanche, .avalanche_testnet, .polygon, .mumbai_testnet, .optimistic, .optimisticKovan, .cronosTestnet: content.body = R.string.localizable.transactionsReceivedEther("\(amount) (\(session.server.name))", session.server.symbol) } content.sound = .default let identifier = Constants.etherReceivedNotificationIdentifier let request = UNNotificationRequest(identifier: "\(identifier):\(transactionId)", content: content, trigger: nil) DispatchQueue.main.async { notificationCenter.add(request) } } private func fetchOlderTransactions(for address: AlphaWallet.Address) { storage.completedObjects.done(on: self.queue, { txs in guard let oldestCachedTransaction = txs.last else { return } let promise = functional.fetchTransactions(for: address, startBlock: 1, endBlock: oldestCachedTransaction.blockNumber - 1, sortOrder: .desc, session: self.session, alphaWalletProvider: self.alphaWalletProvider, tokensStorage: self.tokensStorage, tokenProvider: self.tokenProvider, queue: self.queue) promise.done(on: self.queue, { [weak self] transactions in guard let strongSelf = self else { return } strongSelf.update(items: transactions) if transactions.isEmpty { strongSelf.transactionsTracker.fetchingState = .done } else { let timeout = DispatchTime.now() + .milliseconds(300) strongSelf.queue.asyncAfter(deadline: timeout) { strongSelf.fetchOlderTransactions(for: address) } } }).catch(on: self.queue) { [weak self] _ in guard let strongSelf = self else { return } strongSelf.transactionsTracker.fetchingState = .failed } }).cauterize() } func stop() { timer?.invalidate() timer = nil updateTransactionsTimer?.invalidate() updateTransactionsTimer = nil } func isServer(_ server: RPCServer) -> Bool { return session.server == server } //This inner class reaches into the internals of its outer coordinator class to call some methods. It exists so we can wrap operations into an Operation class and feed it into a queue, so we don't put much logic into it class FetchLatestTransactionsOperation: Operation { private let session: WalletSession weak private var coordinator: SingleChainTransactionEtherscanDataCoordinator? private let startBlock: Int private let sortOrder: AlphaWalletService.SortOrder override var isExecuting: Bool { return coordinator?.isFetchingLatestTransactions ?? false } override var isFinished: Bool { return !isExecuting } override var isAsynchronous: Bool { return true } private let queue: DispatchQueue init(forSession session: WalletSession, coordinator: SingleChainTransactionEtherscanDataCoordinator, startBlock: Int, sortOrder: AlphaWalletService.SortOrder, queue: DispatchQueue) { self.session = session self.coordinator = coordinator self.startBlock = startBlock self.sortOrder = sortOrder self.queue = queue super.init() self.queuePriority = session.server.networkRequestsQueuePriority } override func main() { guard let coordinator = self.coordinator else { return } firstly { SingleChainTransactionEtherscanDataCoordinator.functional.fetchTransactions(for: session.account.address, startBlock: startBlock, sortOrder: sortOrder, session: coordinator.session, alphaWalletProvider: coordinator.alphaWalletProvider, tokensStorage: coordinator.tokensStorage, tokenProvider: coordinator.tokenProvider, queue: coordinator.queue) }.then(on: queue, { transactions -> Promise<[TransactionInstance]> in //NOTE: we want to perform notification creating on main thread coordinator.notifyUserEtherReceived(inNewTransactions: transactions) return .value(transactions) }).done(on: queue, { transactions in coordinator.update(items: transactions) }).catch { e in coordinator.handleError(error: e) }.finally { [weak self] in guard let strongSelf = self else { return } strongSelf.willChangeValue(forKey: "isExecuting") strongSelf.willChangeValue(forKey: "isFinished") coordinator.isFetchingLatestTransactions = false strongSelf.didChangeValue(forKey: "isExecuting") strongSelf.didChangeValue(forKey: "isFinished") } } } } extension SingleChainTransactionEtherscanDataCoordinator { class functional {} } extension SingleChainTransactionEtherscanDataCoordinator.functional { static func extractBoundingBlockNumbers(fromTransactions transactions: [TransactionInstance]) -> (transactions: [TransactionInstance], min: Int, max: Int) { let blockNumbers = transactions.map(\.blockNumber) if let minBlockNumber = blockNumbers.min(), let maxBlockNumber = blockNumbers.max() { return (transactions: transactions, min: minBlockNumber, max: maxBlockNumber) } else { return (transactions: [], min: 0, max: 0) } } static func fetchTransactions(for address: AlphaWallet.Address, startBlock: Int, endBlock: Int = 999_999_999, sortOrder: AlphaWalletService.SortOrder, session: WalletSession, alphaWalletProvider: MoyaProvider<AlphaWalletService>, tokensStorage: TokensDataStore, tokenProvider: TokenProviderType, queue: DispatchQueue) -> Promise<[TransactionInstance]> { firstly { alphaWalletProvider.request(.getTransactions(config: session.config, server: session.server, address: address, startBlock: startBlock, endBlock: endBlock, sortOrder: sortOrder)) }.map(on: queue) { try $0.map(ArrayResponse<RawTransaction>.self).result.map { TransactionInstance.from(transaction: $0, tokensStorage: tokensStorage, tokenProvider: tokenProvider) } }.then(on: queue) { when(fulfilled: $0).compactMap(on: queue) { $0.compactMap { $0 } } } } static func backFillTransactionGroup(_ transactionsToFill: [TransactionInstance], startBlock: Int, endBlock: Int, session: WalletSession, alphaWalletProvider: MoyaProvider<AlphaWalletService>, tokensStorage: TokensDataStore, tokenProvider: TokenProviderType, queue: DispatchQueue) -> Promise<[TransactionInstance]> { guard !transactionsToFill.isEmpty else { return .value([]) } return firstly { fetchTransactions(for: session.account.address, startBlock: startBlock, endBlock: endBlock, sortOrder: .asc, session: session, alphaWalletProvider: alphaWalletProvider, tokensStorage: tokensStorage, tokenProvider: tokenProvider, queue: queue) }.map(on: queue) { fillerTransactions -> [TransactionInstance] in var results: [TransactionInstance] = .init() for each in transactionsToFill { //ERC20 transactions are expected to have operations because of the API we use to retrieve them from guard !each.localizedOperations.isEmpty else { continue } if var transaction = fillerTransactions.first(where: { $0.blockNumber == each.blockNumber }) { transaction.isERC20Interaction = true transaction.localizedOperations = each.localizedOperations results.append(transaction) } else { results.append(each) } } return results } } }
51.229084
361
0.666913
4b9fb546880f7ea1f3197da3df51e723988836ee
6,648
// The MIT License (MIT) // // Copyright (c) 2018 Alexander Grebenyuk (github.com/kean). import UIKit /** Manages distribution: constraints along the axis. */ class DistributionLayoutArrangement: LayoutArrangement { var type: StackViewDistribution = .fill var spacing: CGFloat = 0 var isBaselineRelative = false var spacer: LayoutSpacer private var gaps = [GapLayoutGuide]() override init(canvas: StackView) { spacer = LayoutSpacer() spacer.accessibilityIdentifier = "ASV-alignment-spanner" super.init(canvas: canvas) } override func updateConstraints() { super.updateConstraints() spacer.removeFromSuperview() gaps.forEach { $0.removeFromSuperview() } gaps.removeAll() if items.count > 0 { updateCanvasConnectingConstraints() updateSpacingConstraints() updateDistributionConstraints() } if hiddenItems.count > 0 { updateHiddenItemsConstraints() } if items.count > 0 && (type == .equalSpacing || type == .equalCentering) { // If spacings are weak addCanvasFitConstraint(attribute: width) } } private func updateCanvasConnectingConstraints() { if visibleItems.count == 0 { canvas.addSubview(spacer) connectToCanvas(spacer, attribute: leading) connectToCanvas(spacer, attribute: trailing) } else { connectToCanvas(visibleItems.first!, attribute: leading) connectToCanvas(visibleItems.last!, attribute: trailing) } } private func updateSpacingConstraints() { switch type { case .fill, .fillEqually, .fillProportionally: addSpacings() case .equalSpacing, .equalCentering: addSpacings(.greaterThanOrEqual) updateGapLayoutGuides() } } private func updateGapLayoutGuides() { visibleItems.forPair { previous, current in let gap = GapLayoutGuide() canvas.addSubview(gap) gaps.append(gap) let toAttr: NSLayoutAttribute = isBaselineRelative ? .firstBaseline : leading let fromAttr: NSLayoutAttribute = isBaselineRelative ? .lastBaseline : trailing connectItem(gap, attribute: toAttr, item: previous, attribute: (type == .equalCentering ? center : fromAttr)) connectItem(gap, attribute: fromAttr, item: current, attribute: (type == .equalCentering ? center : toAttr)) } matchItemsSize(gaps, priority: type == .equalCentering ? UILayoutPriority(rawValue: 149) : nil) } private func updateDistributionConstraints() { switch type { case .fillProportionally: fillItemsProportionally() case .fillEqually: matchItemsSize(visibleItems) default: break } } private func fillItemsProportionally() { func sizeFor(_ item: UIView) -> CGFloat { let intrinsic = item.intrinsicContentSize return axis == .horizontal ? intrinsic.width : intrinsic.height } let itemsWithIntrinsic: [UIView] = visibleItems.filter { let size = sizeFor($0) return size != UIViewNoIntrinsicMetric && size > 0 } guard itemsWithIntrinsic.count > 0 else { matchItemsSize(visibleItems) return } let totalSpacing = spacing * CGFloat(visibleItems.count - 1) let totalSize = itemsWithIntrinsic.reduce(totalSpacing) { total, item in return total + sizeFor(item) } var priority: UILayoutPriority? = (itemsWithIntrinsic.count == 1 && (visibleItems.count == 1 || spacing == 0.0)) ? nil : UILayoutPriority(rawValue: 999) visibleItems.forEach { let size = sizeFor($0) if size != UIViewNoIntrinsicMetric && size > 0 { constraint(item: $0, attribute: width, toItem: canvas, relation: .equal, multiplier: (size / totalSize), priority: priority, identifier: "ASV-fill-proportionally") } else { constraint(item: $0, attribute: width, constant: 0, identifier: "ASV-fill-proportionally") } if let unwrappedPriority = priority { priority = UILayoutPriority(rawValue: unwrappedPriority.rawValue - 1) } } } private func updateHiddenItemsConstraints() { hiddenItems.forEach { constraint(item: $0, attribute: width, constant: 0, identifier: "ASV-hiding") } } // MARK: Managed Attributes private var width: NSLayoutAttribute { return axis == .horizontal ? .width : .height } private var leading: NSLayoutAttribute { return axis == .horizontal ? .leading : .top } private var trailing: NSLayoutAttribute { return axis == .horizontal ? .trailing : .bottom } private var center: NSLayoutAttribute { return axis == .horizontal ? .centerX : .centerY } // MARK: Helpers private func addSpacings(_ relation: NSLayoutRelation = .equal) { func spacingFor(previous: UIView, current: UIView) -> CGFloat { if current === visibleItems.first || previous === visibleItems.last { return 0.0 } else { return spacing - (spacing / 2.0) * CGFloat([previous, current].filter{ isHidden($0) }.count) } } items.forPair { previous, current in let spacing = spacingFor(previous: previous, current: current) let toAttr: NSLayoutAttribute = isBaselineRelative ? .firstBaseline : leading let fromAttr: NSLayoutAttribute = isBaselineRelative ? .lastBaseline : trailing constraint(item: current, attribute: toAttr, toItem: previous, attribute: fromAttr, relation: relation, constant: spacing, identifier: "ASV-spacing") } } private func connectItem(_ item1: UIView, attribute attr1: NSLayoutAttribute, item item2: UIView, attribute attr2: NSLayoutAttribute) { constraint(item: item1, attribute: attr1, toItem: item2, attribute: attr2, identifier: "ASV-distributing-edge") } private func matchItemsSize(_ items: [UIView], priority: UILayoutPriority? = nil) { guard items.count > 0 else { return } let firstItem = items.first! items.dropFirst().forEach { constraint(item: $0, attribute: width, toItem: firstItem, priority: priority, identifier: "ASV-fill-equally") } } }
37.772727
179
0.619134
0e968a301fe489ee10efcae27a5f5830dd3fb9b3
7,067
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import XCTest @testable import JacquardSDK class FragmenterTests: XCTestCase { struct CatchLogger: Logger { func log(level: LogLevel, file: String, line: Int, function: String, message: () -> String) { expectation.fulfill() } var expectation: XCTestExpectation } private let mtu = ProtocolSpec.version2.mtu private var singlePacket: Data { // Max length in single packet. MTU subtracted by 1 byte opcode, 2 bytes att handle, // 1 byte Fragment header 1 byte packet length let packetLength = mtu - 5 // 58 return Data((1...packetLength).map { UInt8($0 % 255) }) } private var invalidFragment: Data { let packetLength = mtu - 3 // 58 var fragment = Data(capacity: 1024) fragment.append(0x40) // First Byte let encodedPacketLength = Varint.encode(value: packetLength) fragment.append(encodedPacketLength) fragment.append(Data((1...packetLength).map { UInt8($0 % 255) })) return fragment } override func setUp() { super.setUp() let logger = PrintLogger( logLevels: [.debug, .info, .warning, .error, .assertion], includeSourceDetails: true ) setGlobalJacquardSDKLogger(logger) } override func tearDown() { // Other tests may run in the same process. Ensure that any fake logger fulfillment doesn't // cause any assertions later. JacquardSDK.setGlobalJacquardSDKLogger(JacquardSDK.createDefaultLogger()) super.tearDown() } func testOversizedPacket() { let oversizePacketExpectation = expectation(description: "oversizePacket") jqLogger = CatchLogger(expectation: oversizePacketExpectation) let packetLength = 1025 let overSizedPacket = Data((1...packetLength).map { UInt8($0 % 255) }) let fragmenter = Fragmenter(mtu: mtu) let fragments = fragmenter.fragments(fromPacket: overSizedPacket) XCTAssertEqual(fragments.count, 0, "Incorrect number of fragments") wait(for: [oversizePacketExpectation], timeout: 1.0) } /// Tests packet assembley from Invalid fragment should always return nil func testInValidPacketAssembling() { let packetLength = mtu - 3 // 58 var fragment = Data(capacity: 1024) fragment.append(0x3F) // First Byte let encodedPacketLength = Varint.encode(value: packetLength) fragment.append(encodedPacketLength) fragment.append(Data((1...packetLength).map { UInt8($0 % 255) })) var fragmenter = Fragmenter(mtu: mtu) let packet = fragmenter.packet(fromAddedFragment: fragment) XCTAssertNil(packet, "Unable to crate packet from garbageFrament") let packet1 = fragmenter.packet(fromAddedFragment: invalidFragment) XCTAssertNil(packet1, "Unable to crate packet from garbageFrament") } /// Create single packet from test fragment func testSingleFragmentAssembling() { var fragmenter = Fragmenter(mtu: mtu) let fragments = fragmenter.fragments(fromPacket: singlePacket) let packet = fragmenter.packet(fromAddedFragment: fragments[0]) XCTAssertNotNil(packet, "Assembled packet should not be nil") XCTAssertEqual(singlePacket, packet, "Invalid packet") } /// Create fragments from single test packet func testSinglePacketFragmenting() { let fragments = Fragmenter(mtu: mtu).fragments(fromPacket: singlePacket) let packetLength = mtu - 5 XCTAssertEqual(fragments.count, 1, "Incorrect number of fragments") XCTAssertLessThan( fragments[0].count, 1024, "Can't send packet of \(singlePacket.count) bytes it's more than the maximum of 1024 bytes") XCTAssertEqual(fragments[0].count, packetLength + 2, "Incorrect length of fragment 0") XCTAssertEqual(fragments[0][0], 0xc0, "Incorrect header of fragment 0") // 192 0xC0 XCTAssertEqual(fragments[0][1], UInt8(packetLength), "Incorrect packet length") XCTAssertEqual(fragments[0][2...], singlePacket[0...], "Incorrect payload of fragment 0") } func testMultiFragmentAssembling(packetLength: Int) { let fragmentSize = mtu - 3 let maxPayloadSize = fragmentSize - 1 XCTAssertGreaterThan(packetLength, maxPayloadSize, "Packet fit in a single fragment") var fragmenter = Fragmenter(mtu: mtu) let packet = Data((1...packetLength).map { UInt8($0 % 256) }) let fragments = fragmenter.fragments(fromPacket: packet) var newPacket: Data? = nil fragments.forEach { if let packet = fragmenter.packet(fromAddedFragment: $0) { newPacket = packet } } XCTAssertEqual(newPacket, packet, "Invalid packet") } func testMultiPacketFragmenting(packetLength: Int) { let fragmentSize = mtu - 3 let maxPayloadSize = fragmentSize - 1 XCTAssertGreaterThan(packetLength, maxPayloadSize, "Packet fit in a single fragment") let fragmenter = Fragmenter(mtu: mtu) let encodedLength = Varint.encode(value: packetLength) let packet = Data((1...packetLength).map { UInt8($0 % 256) }) let encodedPacket = encodedLength + packet let lastIndex = encodedPacket.count / maxPayloadSize - (encodedPacket.count % maxPayloadSize == 0 ? 1 : 0) let fragments = fragmenter.fragments(fromPacket: packet) XCTAssertEqual(fragments.count, lastIndex + 1, "Incorrect number of fragments") XCTAssertEqual(fragments[0][0] & 0x80, 0x80, "Incorrect header of fragment 0") XCTAssertEqual( fragments[lastIndex][0] & 0x40, 0x40, "Incorrect header of fragment \(lastIndex)") fragments.enumerated().forEach { XCTAssertEqual($1[0] & 0x3F, UInt8($0), "Incorrect sequence for fragment \(lastIndex)") } let payloads = fragments.map { $0[1...] } let splitedPackets = stride(from: 0, to: encodedPacket.count, by: maxPayloadSize).map { encodedPacket[$0..<min($0 + maxPayloadSize, encodedPacket.count)] } XCTAssertEqual(payloads, splitedPackets, "Incorrect payload") } func testTwoFragmentPacket() { let packetLength = (mtu - 5) * 2 testMultiPacketFragmenting(packetLength: packetLength) testMultiFragmentAssembling(packetLength: packetLength) } func testWithSmallerPacketSize() { testMultiPacketFragmenting(packetLength: 61) testMultiFragmentAssembling(packetLength: 61) } func testWithMediumPacketSize() { testMultiPacketFragmenting(packetLength: 555) testMultiFragmentAssembling(packetLength: 555) } func testWithMaximumPacketSize() { testMultiPacketFragmenting(packetLength: 1024) testMultiFragmentAssembling(packetLength: 1024) } }
36.056122
98
0.71657
71ccd09d524863e9761bd6bbb285effd67ef3efe
847
import CaptainKit //swiftlint:disable line_length extension InstallerError: CustomStringConvertible { public var description: String { switch self { case .gitDirectoryMissingOrInvalid: return "Git directory missing or invalid" case .failedToCreateGitHooksDirectory: return "Failed to create git hooks directory" case .noConfigAtPath: return "No config file found at specified path" case .failedToParseConfig: return "Failed to parse config file" case .gitHookExists(let hook): return "An existing unmanaged git hook was found (\(hook.rawValue)). Remove this hook manually, or re-run with --force." case .failedToInstallGitHook: return "An unknown error occurred when trying to install git hooks" } } }
38.5
132
0.668241
167255d91976addf48967ca6ef6867a49c18a916
4,503
// // UploadStrategy.swift // VimeoUpload // // Created by Nguyen, Van on 11/13/18. // Copyright © 2018 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import VimeoNetworking /// An error enum related to any problem with an upload link. /// /// - unavailable: Thrown when an upload link is not available. /// - wrongType: Thrown when attempting to get an upload link with a /// wrong upload approach i.e using `StreamingUploadStrategy` to get a /// tus upload link. public enum UploadLinkError: Error { case unavailable case wrongType } /// An interface to assist `UploadDescriptor` in getting an upload task /// and an upload link. public protocol UploadStrategy { /// Returns the appropriate upload request parameters for creating a video on Vimeo's server /// /// - Returns: A dictionary of upload parameters static func createVideoUploadParameters() -> UploadParameters /// Creates an upload request for the upload descriptor. /// /// - Parameters: /// - requestSerializer: A request serializer. /// - fileUrl: A URL to a video file. /// - uploadLink: A destination URL to send the video file to. /// - Returns: An upload request. /// - Throws: An `NSError` that describes why an upload request cannot be /// created. static func uploadRequest(requestSerializer: VimeoRequestSerializer?, fileUrl: URL, uploadLink: String) throws -> URLRequest /// Returns an appropriate upload link. /// /// - Parameter video: A video object returned by `CreateVideoOperation`. /// - Returns: An upload link if it exists in the video object. /// - Throws: One of the values of `UploadLinkError` if there is a problem /// with the upload link. static func uploadLink(from video: VIMVideo) throws -> String /// Determines if an upload task should retry. /// /// - Parameter urlResponse: A HTTP server response. /// - Returns: `true` if the task should retry; `false` otherwise. static func shouldRetry(urlResponse: URLResponse?) -> Bool } /// An upload strategy that supports the streaming upload approach. public struct StreamingUploadStrategy: UploadStrategy { public enum ErrorCode: Error { case requestSerializerUnavailable } public static func createVideoUploadParameters() -> UploadParameters { return [VimeoSessionManager.Constants.ApproachKey : VimeoSessionManager.Constants.StreamingApproachValue] } public static func uploadRequest(requestSerializer: VimeoRequestSerializer?, fileUrl: URL, uploadLink: String) throws -> URLRequest { guard let requestSerializer = requestSerializer else { throw ErrorCode.requestSerializerUnavailable } return try requestSerializer.uploadVideoRequest(with: fileUrl, destination: uploadLink) as URLRequest } public static func uploadLink(from video: VIMVideo) throws -> String { guard let approach = video.upload?.uploadApproach, approach == .Streaming else { throw UploadLinkError.wrongType } guard let uploadLink = video.upload?.uploadLink else { throw UploadLinkError.unavailable } return uploadLink } public static func shouldRetry(urlResponse: URLResponse?) -> Bool { return false } }
37.525
135
0.698867
464444c98dad602561920e0faa812fc9a32e038e
597
// // flare_fill.swift // Flare-Swift // // Created by Umberto Sonnino on 2/26/19. // Copyright © 2019 2Dimensions. All rights reserved. // import Foundation import CoreGraphics protocol FlareFill: class { var _fillRule: FillRule { get set } var _fillColor: CGColor { get set } func initializeGraphics() func paint(fill: ActorFill, context: CGContext, path: CGPath) } extension FlareFill { var cgFillRule: CGPathFillRule { switch _fillRule { case .EvenOdd: return .evenOdd case .NonZero: return .winding } } }
20.586207
65
0.639866
f9dd682c82d3c4ea39f34213df85fae681a470e9
2,342
// MIT License // // Copyright (c) 2020 Igor Tiukavkin. // // 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 class Color: View { let color: UIColor public init(_ color: UIColor) { self.color = color super.init() } override internal var toUIView: UIView { let view = UIView() view.backgroundColor = self.color return view } public func opacity(_ opacity: CGFloat) -> Color { let alpha: CGFloat = max(0.0, min(opacity, 1.0)) return Color(self.color.withAlphaComponent(alpha)) } } public extension Color { static var black: Color { Color(.black) } static var darkGray: Color { Color(.darkGray) } static var lightGray: Color { Color(.lightGray) } static var white: Color { Color(.white) } static var gray: Color { Color(.gray) } static var red: Color { Color(.red) } static var green: Color { Color(.green) } static var blue: Color { Color(.blue) } static var cyan: Color { Color(.cyan) } static var yellow: Color { Color(.yellow) } static var magenta: Color { Color(.magenta) } static var orange: Color { Color(.orange) } static var purple: Color { Color(.purple) } static var brown: Color { Color(.brown) } static var clear: Color { Color(.clear) } }
37.174603
81
0.691716
e9374070d7f9e5b49e58b73b5cff57c6a982c254
903
// // EventLoop.swift // webrtc-asyncio // // Created by sunlubo on 2020/10/22. // Copyright © 2020 sunlubo. All rights reserved. // import CLibuv public final class EventLoop { public static let `default`: EventLoop = { EventLoop(handle: uv_default_loop()) }() internal var handle: UnsafeMutablePointer<uv_loop_t> public init() { self.handle = UnsafeMutablePointer.allocate(capacity: 1) self.handle.initialize(to: uv_loop_t()) precondition(uv_loop_init(handle) >= 0, "uv_loop_init") } internal init(handle: UnsafeMutablePointer<uv_loop_t>) { self.handle = handle } deinit { handle.deallocate() logger.debug("\(self) is deinit") } public func run() throws { try check(uv_run(handle, UV_RUN_DEFAULT)) } public func close() throws { stop() try check(uv_loop_close(handle)) } internal func stop() { uv_stop(handle) } }
19.630435
60
0.672204
f8349714e6c34a59e46e99e36f84e8cb2f88c103
3,860
// // PokemonViewModelTests.swift // Pokedex-MVPTests // // Created by Adriano Souza Costa on 08/02/21. // import XCTest import Nimble @testable import Pokedex_MVP class PokemonViewModelTests: XCTestCase { private let url = URL(string: "https://pokemon.com.br")! func testEnsureOrderFormatterConsistency() throws { let pokemon = Pokemon( name: "charmander", order: 23, weight: 4, types: [], sprites: .init(other: .init(officialArtwork: .init(frontDefault: url))), abilities: [], stats: [] ) let viewModel = PokemonViewModel(pokemon) expect(viewModel.order) == "#023" } func testEnsureImageUrlConsistency() throws { let pokemon = Pokemon( name: "charmander", order: 23, weight: 4, types: [], sprites: .init(other: .init(officialArtwork: .init(frontDefault: url))), abilities: [], stats: [] ) let viewModel = PokemonViewModel(pokemon) expect(viewModel.image) == url } func testEnsureTypesConsistency() throws { let pokemon = Pokemon( name: "charmander", order: 23, weight: 4, types: [ .init(slot: 10, type: .dark), .init(slot: 1, type: .fire), .init(slot: 3, type: .water), ], sprites: .init(other: .init(officialArtwork: .init(frontDefault: url))), abilities: [], stats: [] ) let viewModel = PokemonViewModel(pokemon) expect(viewModel.primaryType) == .fire expect(viewModel.types) == [.fire, .water, .dark] } func testEnsureAbilitiesConsistency() throws { let pokemon = Pokemon( name: "charmander", order: 23, weight: 4, types: [], sprites: .init(other: .init(officialArtwork: .init(frontDefault: url))), abilities: [ .init(name: "Ability 2", slot: 2), .init(name: "Ability 1", slot: 1) ], stats: [] ) let viewModel = PokemonViewModel(pokemon) expect(viewModel.abilities) == ["Ability 1", "Ability 2"] } func testEnsureStatsConsistency() throws { let pokemon = Pokemon( name: "charmander", order: 23, weight: 4, types: [], sprites: .init(other: .init(officialArtwork: .init(frontDefault: url))), abilities: [], stats: [ .init(value: 33, name: "hp"), .init(value: 1, name: "attack"), .init(value: 2, name: "defense"), .init(value: 4, name: "special-attack"), .init(value: 5, name: "special-defense"), .init(value: 6, name: "speed"), ] ) let viewModel = PokemonViewModel(pokemon) expect(viewModel.stats.count) == 6 expect(viewModel.stats[0].name) == "HP" expect(viewModel.stats[0].percentage) == 33 expect(viewModel.stats[1].name) == "Attack" expect(viewModel.stats[1].percentage) == 1 expect(viewModel.stats[2].name) == "Defense" expect(viewModel.stats[2].percentage) == 2 expect(viewModel.stats[3].name) == "Special Attack" expect(viewModel.stats[3].percentage) == 4 expect(viewModel.stats[4].name) == "Special Defense" expect(viewModel.stats[4].percentage) == 5 expect(viewModel.stats[5].name) == "Speed" expect(viewModel.stats[5].percentage) == 6 } }
29.692308
84
0.505699
6a7441d391ec787052393113b82bf3dc00e2ae96
411
// // I18nRegions.swift // YoutubeKit // // Created by Ryo Ishikawa on 12/30/2017 // import Foundation public struct I18nRegionsList: Codable { public let etag: String public let items: [I18nRegion] public let kind: String } public struct I18nRegion: Codable { public let etag: String public let id: String public let kind: String public let snippet: Snippet.I18nRegionsList }
18.681818
47
0.705596
283d3acd450edfedd90f3e4603a58f18de7a6098
6,216
// // RequestViewController.swift // MakerMate // // Created by Jens Van Steen on 31/01/2019. // Copyright © 2019 Jens Van Steen. All rights reserved. // import UIKit class RequestViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate { let ageClass = [1: "kinderen (-12 jaar)", 2: "jongeren (-26 jaar)", 3: "volwassenen (26+ jaar)", 4: "senioren (65+ jaar)"] private var interests = [String]() var request: Request? @IBOutlet weak private var intrestsCollectionView: UICollectionView! @IBOutlet weak private var widthCollectionView: NSLayoutConstraint! @IBOutlet weak private var targetGroupName: UILabel! @IBOutlet weak private var targetGroupNameView: UIView! @IBOutlet weak private var widthLabelTagTargetGroup: NSLayoutConstraint! @IBOutlet weak private var requestShort: UILabel! @IBOutlet weak var requestLong: UILabel! @IBOutlet weak var locationlabel: UILabel! @IBOutlet weak var nameLabel: UILabel! var width: CGFloat = 0 { didSet { widthCollectionView.constant = width } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.intrestsCollectionView.delegate = self self.intrestsCollectionView.dataSource = self let widthContent = intrestsCollectionView.contentSize.width print("this widht of the content is \(widthContent)") setData() setupNavigationBar() } private func setData() { guard let requestToDisplay = request else {return} requestShort.text = "\"\(requestToDisplay.requestShort!)\"" targetGroupName.text = ageClass[requestToDisplay.age!]! locationlabel.text = requestToDisplay.city! nameLabel.text = requestToDisplay.firstNameRequest! interests = requestToDisplay.interests! intrestsCollectionView.reloadData() } private func setupNavigationBar() { self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.2, green: 0.2, blue: 0.1960784314, alpha: 1), NSAttributedString.Key.font: UIFont(name: "AvenirNext-Medium", size: 14)!] self.navigationController?.navigationBar.barTintColor = UIColor.white self.navigationItem.setHidesBackButton(true, animated:false) //your custom view for back image with custom size let view = UIView(frame: CGRect(x: 0, y: 0, width: 32, height: 29)) let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 32, height: 29)) if let imgBackArrow = UIImage(named: "backButton") { imageView.image = imgBackArrow } view.addSubview(imageView) let backTap = UITapGestureRecognizer(target: self, action: #selector(backToMain)) view.addGestureRecognizer(backTap) let leftBarButtonItem = UIBarButtonItem(customView: view) self.navigationItem.leftBarButtonItem = leftBarButtonItem navigationController?.interactivePopGestureRecognizer?.delegate = self } @objc func backToMain() { self.navigationController?.popViewController(animated: true) } @IBAction func backToHome(_ sender: UIButton) { LastProject.shared.showProject = true request!.addToProjectsFromRequest() self.navigationController?.popViewController(animated: true) } @IBAction func displayActionSheet(_ sender: Any) { let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) optionMenu.addAction(UIAlertAction(title: "Aanvraag later herhalen", style: UIAlertAction.Style.default, handler: { _ in self.navigationController?.popViewController(animated: true) })) optionMenu.addAction(UIAlertAction(title: "Aanvraag niet meer laten zien", style: UIAlertAction.Style.destructive, handler: { _ in self.navigationController?.popViewController(animated: true) })) optionMenu.addAction(UIAlertAction(title: "Annuleer", style: UIAlertAction.Style.cancel, handler: { _ in self.dismiss(animated: true, completion: nil) })) // 5 self.present(optionMenu, animated: true, completion: nil) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return interests.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "interestCell", for: indexPath) as! IntrestHomeCollectionViewCell cell.intrestLabel.text = interests[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let size = CGSize(width: 200, height: 23) var estimedSizeText: CGRect? if let font = UIFont(name: "Avenir Next", size: 10) { let attributes = [NSAttributedString.Key.font: font] estimedSizeText = NSString(string: interests[indexPath.row]).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) width += (estimedSizeText!.width + 20 + 10) return CGSize(width: estimedSizeText!.width + 20, height: 23) } return CGSize(width: 40, height: 23) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
38.134969
169
0.670045
9156447b337696bc4fcc97e1e9c73833ae7f5b37
3,510
// // ChatViewControllerTests.swift // WebimClientLibrary_Example // // Created by Nikita Lazarev-Zubov on 15.01.18. // Copyright © 2018 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import XCTest @testable import WebimClientLibrary @testable import WebimClientLibrary_Example class ChatViewControllerTests: XCTestCase { // MARK: - Properties var chatViewController: ChatViewController! // MARK: - Methods override func setUp() { super.setUp() let storyboard = UIStoryboard(name: "Main", bundle: nil) chatViewController = storyboard.instantiateViewController(withIdentifier: "ChatViewController") as! ChatViewController } // MARK: - Tests func testBackgroundViewNotEmpty() { // When: Table view is empty. let tableView = chatViewController.tableView! tableView.reloadData() // Then: Table view background has the message. let label = tableView.backgroundView as! UILabel XCTAssertEqual(label.attributedText?.string, "Send first message to start chat.") } func testBackgroundViewEmpty() { // MARK: Set up var messages = [Message]() for index in 0 ... 2 { let message = MessageImpl(serverURLString: "http://demo.webim.ru/", id: String(index), operatorID: nil, senderAvatarURLString: nil, senderName: "Sender name", type: .VISITOR, data: nil, text: "Text", timeInMicrosecond: Int64(index), attachment: nil, historyMessage: false, internalID: nil, rawText: nil) messages.append(message as Message) } // When: Table view is not empty. chatViewController.set(messages: messages) chatViewController.tableView?.reloadData() // Then: Table view background view is empty. XCTAssertNil(chatViewController.tableView!.backgroundView) } }
39.886364
126
0.595157
0abde7c7d1cfc894db2788501a99e368ef91374d
1,439
// // AVAssetExportSessionExtensionViewController.swift // JKSwiftExtension_Example // // Created by IronMan on 2021/1/20. // Copyright © 2021 CocoaPods. All rights reserved. // import UIKit import AVFoundation class AVAssetExportSessionExtensionViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() headDataArray = ["一、有关视频压缩的扩展"] dataArray = [["本地视频压缩"]] } } // MARK: - 一、有关视频压缩的扩展 extension AVAssetExportSessionExtensionViewController { // MARK: 1.1、本地视频压缩 @objc func test11() { AVAssetExportSession.jk.assetExportSession(inputPath: "是本地视频路径", outputPath: "导出视频的路径", outputFileType: .mp4, completionHandler: { (exportSession, duration, videoSize, localVideoPath) in switch exportSession.status{ case .waiting: print("等待压缩") break case .exporting: print("压缩中:") break case .completed: JKPrint("转码成功") //上传 break case .cancelled: JKPrint("取消") break case .failed: JKPrint("失败...\(String(describing: exportSession.error?.localizedDescription))") break default: JKPrint("..") break } }, shouldOptimizeForNetworkUse: true) } }
28.215686
194
0.566366
dd64984841156ad6d4c5352a2a9147659910e50f
730
import Basic import Foundation import TuistSupport public class CoreDataModel: Equatable { // MARK: - Attributes public let path: AbsolutePath public let versions: [AbsolutePath] public let currentVersion: String // MARK: - Init public init(path: AbsolutePath, versions: [AbsolutePath], currentVersion: String) { self.path = path self.versions = versions self.currentVersion = currentVersion } // MARK: - Equatable public static func == (lhs: CoreDataModel, rhs: CoreDataModel) -> Bool { return lhs.path == rhs.path && lhs.currentVersion == rhs.currentVersion && lhs.versions == rhs.versions } }
24.333333
76
0.621918
eb0022308fec91a64e1b14bd8445a4827e2200af
1,277
class Song { private let lineStart = "This is " private let lineEnd = "." private var phrases = [ "the house that Jack built", "the malt that lay in", "the rat that ate" ] init(songType: String) { if songType == "repeat" { self.phrases = self.phrases.map { phrase -> String in return phrase + " " + phrase } } else if songType == "reverse" { self.phrases = self.phrases.reverse() } } func line(number: Int) -> String { let linePhrases = self.phrases[0...number-1].reverse() let line = " ".join(linePhrases) return self.lineStart + line + self.lineEnd } func recite() -> String { var lines = [String]() for i in 1...self.phrases.count { lines.append(self.line(i)) } return "\n".join(lines) } } let song = Song(songType: "normal") song.line(1) song.line(2) song.line(3) song.recite() let repeatingSong = Song(songType: "repeat") repeatingSong.line(1) repeatingSong.line(2) repeatingSong.line(3) repeatingSong.recite() let reversingSong = Song(songType: "reverse") reversingSong.line(1) reversingSong.line(2) reversingSong.line(3) reversingSong.recite()
24.557692
65
0.582616
033d889a72b84583d88dae4436abc169fa47640b
1,701
// Copyright 2019 Hotspring Ventures Ltd. // // 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 TWUITests final class Configuration: TWUITests.Configuration { var apiConfiguration: APIConfiguration = APIConfiguration( portRange: 9000...9999, apiStubs: [], // Add defaults API stubs here appID: "" // appID is used to specify stubs path ) var dictionary: [String: String] = [ ConfigurationKeys.isUITest: String(Bool(true)), ConfigurationKeys.isFirstTimeUser: String(Bool(false)), ConfigurationKeys.isAnimationsEnabled: String(Bool(false)), ConfigurationKeys.isUser: String(Bool(false)) ] } extension Configuration { func isFirstTimeUser() -> Self { dictionary[ConfigurationKeys.isFirstTimeUser] = String(Bool(true)) return self } func isUser(_ userName: String, password: String) -> Self { dictionary[ConfigurationKeys.isUser] = userName + "::" + password apiConfiguration.apiStubs.append(Stub.Authentication.success) return self } func isLoggedInUser() -> Self { return isUser("[email protected]", password: "password") } }
35.4375
76
0.691946
4a8733368321845d5c825eb3fea7f69a0df117f0
3,963
// // AddNotifViewController.swift // P1 BUSINESS // // Created by Hui Lin on 24/1/18. // Copyright © 2018 Hui Lin. All rights reserved. // import UIKit import FirebaseDatabase import FirebaseAuth class AddNotifViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate { @IBOutlet weak var branchAddNotif: UITextField! @IBOutlet weak var titleAddNotif: UITextField! @IBOutlet weak var descAddNotif: UITextView! @IBOutlet weak var repeatAddNotif: UITextField! @IBOutlet weak var branchPicker: UIPickerView! @IBOutlet weak var repeatPicker: UIPickerView! var branches = ["Jurong East", "Clementi", "Tampines", "Sentosa", "Serangoon"] var repeats = ["No repeat", "Everyday", "Weekdays", "Weekends"] func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { var countRows : Int = branches.count if (pickerView == repeatPicker) { countRows = self.repeats.count } return countRows } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if (pickerView == branchPicker) { let titleRow = branches[row] return titleRow } else if (pickerView == repeatPicker) { let titleRow = repeats[row] return titleRow } return "" } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if (pickerView == branchPicker) { self.branchAddNotif.text = self.branches[row] pickerView.isHidden = true } else if (pickerView == repeatPicker) { self.repeatAddNotif.text = self.repeats[row] pickerView.isHidden = true } } func textFieldDidBeginEditing(_ textField: UITextField) { if (textField == branchAddNotif) { branchPicker.isHidden = false } else if (textField == repeatAddNotif) { repeatPicker.isHidden = false } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. branchAddNotif.layer.borderWidth = 1 titleAddNotif.layer.borderWidth = 1 descAddNotif.layer.borderWidth = 1 repeatAddNotif.layer.borderWidth = 1 branchAddNotif.layer.borderColor = UIColor.lightGray.cgColor titleAddNotif.layer.borderColor = UIColor.lightGray.cgColor descAddNotif.layer.borderColor = UIColor.lightGray.cgColor repeatAddNotif.layer.borderColor = UIColor.lightGray.cgColor } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addNotif(_ sender: UIButton) { let ref = Database.database().reference() let notifRef = ref.child("notifications").child(Auth.auth().currentUser!.uid) let newNotifRef = notifRef.childByAutoId() newNotifRef.setValue([ "branch": self.branchAddNotif.text, "title": self.titleAddNotif.text, "description": self.descAddNotif.text, "repeat": self.repeatAddNotif.text]) branchAddNotif.text = "" titleAddNotif.text = "" descAddNotif.text = "" repeatAddNotif.text = "" } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
33.584746
115
0.640172
3ac5c1576377a5a148d1d529adbb6e246bc32c79
3,272
// // MapAndTabbedViewController.swift // OnTheMap // // Created by bhuvan on 10/04/2020. // Copyright © 2020 Udacity. All rights reserved. // import UIKit protocol MapAndTabbedViewDelegate { func logout() func refreshList() func addLocation() } class MapAndTabbedViewController: UITabBarController { public weak var mapAndTabDelegate: MapAndTabbedViewController? override func viewDidLoad() { super.viewDidLoad() title = "On the Map" // Add left bar button let logoutBarButton = UIBarButtonItem(title: "LOGOUT", style: .done, target: self, action: #selector(logout)) navigationItem.leftBarButtonItem = logoutBarButton // Add right bar button let refreshBarButton = UIBarButtonItem(image: UIImage(named: "icon_refresh"), style: .done, target: self, action: #selector(refreshRecentLocations)) let addLocationButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addLocation)) navigationItem.rightBarButtonItems = [addLocationButton, refreshBarButton] } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } @objc func logout() { UdacityClient.logout { self.navigationController?.popViewController(animated: true) } } @objc func refreshRecentLocations() { UdacityClient.getStudentInformation(completion: handleLocationResponse(response:error:)) } func handleLocationResponse(response: StudentListResponse?, error: Error?) { if let response = response { UserManager.shared.locations = response.results if let listVC = selectedViewController as? ListViewController { listVC.tableView.reloadData() } else if let mapVC = selectedViewController as? MapViewController { mapVC.updateAnnotations(response: response.results) } } else { UIAlertController.showAlert(from: self, title: AlertTitle.error, message: error?.localizedDescription ?? "") } } @objc func addLocation() { func openNextVC() { let informationPostingVC = storyboard?.instantiateViewController(identifier: "InformationPostingNavigation") as! UINavigationController present(informationPostingVC, animated: true, completion: nil) } if UserManager.shared.objectId.isEmpty { openNextVC() } else { let alert = UIAlertController(title: "", message: AlertMessage.overrideLocation, preferredStyle: .alert) let overwriteAction = UIAlertAction(title: "Overwrite", style: .default) { _ in performUIUpdate { openNextVC() } } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(cancelAction) alert.addAction(overwriteAction) present(alert, animated: true, completion: nil) } } }
36.764045
156
0.631418
8959163f8ea428ca9188b7445594908eaf40dae0
2,652
import XCTest @testable import SwiftGraphQLCodegen final class ASTTests: XCTestCase { /* Schema */ func testDecodeSchema() throws { let json = """ { "data": { "__schema": { "queryType": { "name": "Query" }, "mutationType": null, "subscriptionType": null, "types": [ { "kind": "OBJECT", "name": "Human", "description": "A humanoid creature in the Star Wars universe.", "fields": [ { "name": "name", "description": "The name of the character", "args": [], "type": { "kind": "SCALAR", "name": "String", "ofType": null }, "isDeprecated": false, "deprecationReason": null } ], "inputFields": null, "interfaces": [ { "kind": "INTERFACE", "name": "Character", "ofType": null } ], "enumValues": null, "possibleTypes": null } ] } } } """ /* Decode */ let value = try GraphQL.parse(json.data(using: .utf8)!) let expected = GraphQL.Schema( description: nil, types: [ .object(GraphQL.ObjectType( name: "Human", description: "A humanoid creature in the Star Wars universe.", fields: [ GraphQL.Field( name: "name", description: "The name of the character", args: [], type: .named(.scalar("String")), isDeprecated: false, deprecationReason: nil ) ], interfaces: [ .named(.interface("Character")) ] )) ], queryType: GraphQL.Operation(name: "Query"), mutationType: nil, subscriptionType: nil ) /* Tests */ XCTAssertEqual(value, expected) } }
30.136364
82
0.334842
232ff9f280f750c8e98a166c719b3f3d7e2d6268
3,865
// // AVPlayerLayerViewController.swift // LayerPlayer // // Created by Scott Gardner on 12/6/14. // Copyright (c) 2014 Scott Gardner. All rights reserved. // import UIKit import AVFoundation class AVPlayerLayerViewController: UIViewController { @IBOutlet weak var viewForPlayerLayer: UIView! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var rateSegmentedControl: UISegmentedControl! @IBOutlet weak var loopSwitch: UISwitch! @IBOutlet weak var volumeSlider: UISlider! enum Rate: Int { case slowForward, normal, fastForward } let playerLayer = AVPlayerLayer() var player: AVPlayer { return playerLayer.player! } var rateBeforePause: Float? var shouldLoop = true var isPlaying = false // MARK: - Quick reference func setUpPlayerLayer() { playerLayer.frame = viewForPlayerLayer.bounds let url = Bundle.main.url(forResource: "colorfulStreak", withExtension: "m4v")! let player = AVPlayer(url: url) player.actionAtItemEnd = .none playerLayer.player = player } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() setUpPlayerLayer() viewForPlayerLayer.layer.addSublayer(playerLayer) NotificationCenter.default.addObserver(self, selector: #selector(AVPlayerLayerViewController.playerDidReachEndNotificationHandler(_:)), name: NSNotification.Name(rawValue: "AVPlayerItemDidPlayToEndTimeNotification"), object: player.currentItem) } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - IBActions @IBAction func playButtonTapped(_ sender: UIButton) { play() } @IBAction func rateSegmentedControlChanged(_ sender: UISegmentedControl) { var rate: Float! switch sender.selectedSegmentIndex { case Rate.slowForward.rawValue: rate = 0.5 case Rate.fastForward.rawValue: rate = 2.0 default: rate = 1.0 } player.rate = rate isPlaying = true rateBeforePause = rate updatePlayButtonTitle() } @IBAction func loopSwitchChanged(_ sender: UISwitch) { shouldLoop = sender.isOn if shouldLoop { player.actionAtItemEnd = .none } else { player.actionAtItemEnd = .pause } } @IBAction func volumeSliderChanged(_ sender: UISlider) { player.volume = sender.value } // MARK: - Triggered actions func play() { if playButton.titleLabel?.text == "Play" { if let resumeRate = rateBeforePause { player.rate = resumeRate } else { player.play() } isPlaying = true } else { rateBeforePause = player.rate player.pause() isPlaying = false } updatePlayButtonTitle() updateRateSegmentedControl() } @objc func playerDidReachEndNotificationHandler(_ notification: Notification) { guard let playerItem = notification.object as? AVPlayerItem else { return } playerItem.seek(to: CMTime.zero) if shouldLoop == false { player.pause() isPlaying = false updatePlayButtonTitle() updateRateSegmentedControl() } } // MARK: - Helpers func updatePlayButtonTitle() { if isPlaying { playButton.setTitle("Pause", for: UIControl.State()) } else { playButton.setTitle("Play", for: UIControl.State()) } } func updateRateSegmentedControl() { if isPlaying { switch player.rate { case 0.5: rateSegmentedControl.selectedSegmentIndex = Rate.slowForward.rawValue case 1.0: rateSegmentedControl.selectedSegmentIndex = Rate.normal.rawValue case 2.0: rateSegmentedControl.selectedSegmentIndex = Rate.fastForward.rawValue default: break } } else { rateSegmentedControl.selectedSegmentIndex = UISegmentedControl.noSegment } } }
25.097403
248
0.673997
1a03147af0cda464b2a29080cebf0b27769ec8f7
3,109
// Copyright (c) 2015 Rob Rix. All rights reserved. final class ResultTests: XCTestCase { func testMapTransformsSuccesses() { XCTAssertEqual(success.map(count) ?? 0, 7) } func testMapRewrapsFailures() { XCTAssertEqual(failure.map(count) ?? 0, 0) } func testInitOptionalSuccess() { XCTAssert(Result("success" as String?, failWith: error) == success) } func testInitOptionalFailure() { XCTAssert(Result(nil, failWith: error) == failure) } // MARK: Errors func testErrorsIncludeTheSourceFile() { let file = __FILE__ XCTAssertEqual(Result<(), NSError>.error().file ?? "", file) } func testErrorsIncludeTheSourceLine() { let (line, error) = (__LINE__, Result<(), NSError>.error()) XCTAssertEqual(error.line ?? -1, line) } func testErrorsIncludeTheCallingFunction() { let function = __FUNCTION__ XCTAssertEqual(Result<(), NSError>.error().function ?? "", function) } // MARK: Cocoa API idioms func testTryProducesFailuresForBooleanAPIWithErrorReturnedByReference() { let result = try { attempt(true, succeed: false, error: $0) } XCTAssertFalse(result ?? false) XCTAssertNotNil(result.error) } func testTryProducesFailuresForOptionalWithErrorReturnedByReference() { let result = try { attempt(1, succeed: false, error: $0) } XCTAssertEqual(result ?? 0, 0) XCTAssertNotNil(result.error) } func testTryProducesSuccessesForBooleanAPI() { let result = try { attempt(true, succeed: true, error: $0) } XCTAssertTrue(result ?? false) XCTAssertNil(result.error) } func testTryProducesSuccessesForOptionalAPI() { let result = try { attempt(1, succeed: true, error: $0) } XCTAssertEqual(result ?? 0, 1) XCTAssertNil(result.error) } // MARK: Operators func testConjunctionOperator() { let resultSuccess = success &&& success if let (x, y) = resultSuccess.value { XCTAssertTrue(x == "success" && y == "success") } else { XCTFail() } let resultFailureBoth = failure &&& failure2 XCTAssert(resultFailureBoth.error == error) let resultFailureLeft = failure &&& success XCTAssert(resultFailureLeft.error == error) let resultFailureRight = success &&& failure2 XCTAssert(resultFailureRight.error == error2) } } // MARK: - Fixtures let success = Result<String, NSError>.success("success") let error = NSError(domain: "com.antitypical.Result", code: 0xdeadbeef, userInfo: nil) let error2 = NSError(domain: "com.antitypical.Result", code: 0x12345678, userInfo: nil) let failure = Result<String, NSError>.failure(error) let failure2 = Result<String, NSError>.failure(error2) // MARK: - Helpers func attempt<T>(value: T, #succeed: Bool, #error: NSErrorPointer) -> T? { if succeed { return value } else { error.memory = Result<(), NSError>.error() return nil } } extension NSError { var function: String? { return userInfo?[Result<(), NSError>.functionKey as NSString] as? String } var file: String? { return userInfo?[Result<(), NSError>.fileKey as NSString] as? String } var line: Int? { return userInfo?[Result<(), NSError>.lineKey as NSString] as? Int } } import Result import XCTest
25.072581
87
0.707623
1cc13e0d5a7875c7e7f476cbc71c681d2018b1d1
2,103
/* MIT License Copyright (c) 2017-2018 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import class CoreLocation.CLLocation /// An enum representing the kind of message and its underlying data. public enum MessageData { /// A standard text message. /// /// NOTE: The font used for this message will be the value of the /// `messageLabelFont` property in the `MessagesCollectionViewFlowLayout` object. /// /// Tip: Using `MessageData.attributedText(NSAttributedString)` doesn't require you /// to set this property and results in higher performance. case text(String) /// A message with attributed text. case attributedText(NSAttributedString) /// A photo message. case photo(UIImage) /// A video message. case video(file: URL, thumbnail: UIImage) /// A location message. case location(CLLocation) /// An emoji message. case emoji(String) // MARK: - Not supported yet // case audio(Data) // // case system(String) // // case custom(Any) // // case placeholder }
31.863636
87
0.727057
bf92e76f0bb6dc450cb2396408d8ebe920ad9982
3,768
import UIKit #if !COCOAPODS import PromiseKit #endif //TODO tests //TODO NSCoding /** A “promisable” UIAlertController. UIAlertController is not a suitable API for an extension; it has closure handlers on its main API for each button and an extension would have to either replace all these when the controller is presented or force you to use an extended addAction method, which would be easy to forget part of the time. Hence we provide a facade pattern that can be promised. let alert = PMKAlertController("OHAI") let sup = alert.addActionWithTitle("SUP") let bye = alert.addActionWithTitle("BYE") promiseViewController(alert).then { action in switch action { case is sup: //… case is bye: //… } } */ public class PMKAlertController { /// The title of the alert. public var title: String? { return UIAlertController.title } /// Descriptive text that provides more details about the reason for the alert. public var message: String? { return UIAlertController.message } /// The style of the alert controller. public var preferredStyle: UIAlertController.Style { return UIAlertController.preferredStyle } /// The actions that the user can take in response to the alert or action sheet. public var actions: [UIAlertAction] { return UIAlertController.actions } /// The array of text fields displayed by the alert. public var textFields: [UITextField]? { return UIAlertController.textFields } #if !os(tvOS) /// The nearest popover presentation controller that is managing the current view controller. public var popoverPresentationController: UIPopoverPresentationController? { return UIAlertController.popoverPresentationController } #endif /// Creates and returns a view controller for displaying an alert to the user. public required init(title: String?, message: String? = nil, preferredStyle: UIAlertController.Style = .alert) { UIAlertController = UIKit.UIAlertController(title: title, message: message, preferredStyle: preferredStyle) } /// Attaches an action title to the alert or action sheet. public func addActionWithTitle(title: String, style: UIAlertAction.Style = .default) -> UIAlertAction { let action = UIAlertAction(title: title, style: style) { action in if style != .cancel { self.fulfill(action) } else { self.reject(Error.cancelled) } } UIAlertController.addAction(action) return action } /// Adds a text field to an alert. public func addTextFieldWithConfigurationHandler(configurationHandler: ((UITextField) -> Void)?) { UIAlertController.addTextField(configurationHandler: configurationHandler) } fileprivate let UIAlertController: UIKit.UIAlertController fileprivate let (promise, fulfill, reject) = Promise<UIAlertAction>.pending() fileprivate var retainCycle: PMKAlertController? /// Errors that represent PMKAlertController failures public enum Error: CancellableError { /// The user cancelled the PMKAlertController. case cancelled /// - Returns: true public var isCancelled: Bool { return self == .cancelled } } } extension UIViewController { /// Presents the PMKAlertController, resolving with the user action. public func promise(_ vc: PMKAlertController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<UIAlertAction> { vc.retainCycle = vc present(vc.UIAlertController, animated: animated, completion: completion) _ = vc.promise.always { vc.retainCycle = nil } return vc.promise } }
38.845361
137
0.694533
71b4b9eb7f610c76e05ce7a5245dbfc70de57127
4,157
// // ViewController.swift // AFNSwift // // Created by liurihua on 15/12/22. // Copyright © 2015年 刘日华. All rights reserved. // import UIKit final class ViewController: UIViewController{ var table: UITableView? var musics = [Music]() var offset: Int = 0 struct Identifier { static let musicCell = "musicCell" } private struct URL { static var musicsURL = "http://mapi.yinyuetai.com/video/list.json?D-A=0&deviceinfo=%7B%22aid%22%3A%2210201024%22%2C%22os%22%3A%22Android%22%2C%22ov%22%3A%224.2.2%22%2C%22rn%22%3A%22480*800%22%2C%22dn%22%3A%22H30-T00%22%2C%22cr%22%3A%2246002%22%2C%22as%22%3A%22WIFI%22%2C%22uid%22%3A%22c5aa133090bd0d5d9ecd4163bb27f3cb%22%2C%22clid%22%3A110013000%7D" } //MARK: ---- //MARK: ---ViewController life cycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.greenColor() self.title = "Itachi San" table = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain) table?.delegate = self table?.dataSource = self table?.registerNib(UINib(nibName: "MusicCell",bundle: nil), forCellReuseIdentifier: Identifier.musicCell) //fetch musics Block let fetchMusics = {() -> Void in RequestAPI.GET.fetch(URL.musicsURL, body: ["offset" : 0], succeed: { [unowned self] (task: NSURLSessionDataTask?, responseObject: AnyObject?) -> Void in if let response = responseObject as? [String: AnyObject] { if let musicsArray = response["videos"] as? [[String : AnyObject]]{ self.musics.removeAll() if let tempMusics = Music.musicsWithDictArray(musicsArray) { self.musics += tempMusics } self.table?.reloadData() self.table?.mj_header.endRefreshing() } } }) { (task: NSURLSessionDataTask?, error: NSError) -> Void in print("oh shit 失败了 + \(error)") } } table?.mj_header = MJRefreshHeader(refreshingBlock: fetchMusics) view.addSubview(table!) fetchMusics() } } //MARK: ---- //MARK: ----UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return musics.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(Identifier.musicCell, forIndexPath: indexPath) as! MusicCell cell.configCell(withDatasource: musics[indexPath.row], delegate: musics[indexPath.row]) cell.delegateeeee = self return cell } } //MARK: ---- //MARK: ----UITableViewDelegate extension ViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let playerViewController = PlayerViewController() playerViewController.music = musics[indexPath.row] self.navigationController?.pushViewController(playerViewController, animated: true) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 200.0 } } //MARK: ---- //MARK: ----MusicCellDelegate extension ViewController: ToViewController { func returnDataToViewController(data: String?) { let alert = UIAlertController(title: data, message: data, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: { (action) -> Void in // alert.dismissViewControllerAnimated(true, completion: nil) })) self.presentViewController(alert, animated: true, completion: nil) } }
34.07377
357
0.61198
f8e5860b7d75b4f3ef498c69bbf6ce66065b5af5
877
// // MarginLabel.swift // // Created by zhangshumeng on 2018/8/25. // Copyright © 2018年 ZSM. All rights reserved. // import UIKit class MarginLabel: UILabel { var contentInset: UIEdgeInsets = .zero override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { var rect: CGRect = super.textRect(forBounds: UIEdgeInsetsInsetRect(bounds, contentInset), limitedToNumberOfLines: numberOfLines) //根据edgeInsets,修改绘制文字的bounds rect.origin.x -= contentInset.left; rect.origin.y -= contentInset.top; rect.size.width += contentInset.left + contentInset.right; rect.size.height += contentInset.top + contentInset.bottom; return rect } override func drawText(in rect: CGRect) { super.drawText(in: UIEdgeInsetsInsetRect(rect, contentInset)) } }
31.321429
136
0.688712
9c6929cdf2c4e63a8795ce91415bf153ea17192a
11,996
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import UIKit class MSTransmissionTargetsViewController: UITableViewController, AppCenterProtocol { var appCenter: AppCenterDelegate! private class MSTransmissionTargetSection: NSObject { static var defaultTransmissionTargetIsEnabled: Bool? var token: String? var headerText: String? var footerText: String? var isDefault = false func isTransmissionTargetEnabled() -> Bool { if isDefault { return MSTransmissionTargets.shared.defaultTransmissionTargetIsEnabled } else { return getTransmissionTarget()!.enabled } } func setTransmissionTargetEnabled(_ enabledState: Bool) { if !isDefault { getTransmissionTarget()!.enabled = enabledState } } func getTransmissionTarget() -> AnalyticsTransmissionTarget? { if isDefault { return nil } else { return MSTransmissionTargets.shared.transmissionTargets[token!] } } func shouldSendAnalytics() -> Bool { if isDefault { return MSTransmissionTargets.shared.defaultTargetShouldSendAnalyticsEvents() } else { return MSTransmissionTargets.shared.targetShouldSendAnalyticsEvents(targetToken: token!) } } func setShouldSendAnalytics(enabledState: Bool) { if isDefault { MSTransmissionTargets.shared.setShouldDefaultTargetSendAnalyticsEvents(enabledState: enabledState) } else { MSTransmissionTargets.shared.setShouldSendAnalyticsEvents(targetToken: token!, enabledState: enabledState) } } func pause() { getTransmissionTarget()!.pause() } func resume() { getTransmissionTarget()!.resume() } } private var transmissionTargetSections: [MSTransmissionTargetSection]? private let kEnabledSwitchCellId = "enabledswitchcell" private let kAnalyticsSwitchCellId = "analyticsswitchcell" private let kTokenCellId = "tokencell" private let kPauseCellId = "pausecell" private let kEnabledStateIndicatorCellId = "enabledstateindicator" private let kTokenDisplayLabelTag = 1 private let kEnabledCellRowIndex = 0 private let kAnalyticsCellRowIndex = 1 private let kTokenCellRowIndex = 2 private let kPauseCellRowIndex = 3 private var targetPropertiesSection: TargetPropertiesTableSection? private var csPropertiesSection: CommonSchemaPropertiesTableSection? enum Section : Int { case Default = 0 case Runtime case Child1 case Child2 case TargetProperties case CommonSchemaProperties } override func viewDidLoad() { super.viewDidLoad() targetPropertiesSection = TargetPropertiesTableSection(tableSection: Section.TargetProperties.rawValue, tableView: tableView) csPropertiesSection = CommonSchemaPropertiesTableSection(tableSection: Section.CommonSchemaProperties.rawValue, tableView: tableView) let appName = Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String // Test start from library. appCenter.startAnalyticsFromLibrary() // Default target section. let defaultTargetSection = MSTransmissionTargetSection() defaultTargetSection.headerText = "Default Transmission Target" defaultTargetSection.footerText = "You need to change startup mode and restart the app to get update this target's enabled state." defaultTargetSection.isDefault = true defaultTargetSection.token = appName.contains("SasquatchSwift") ? kMSSwiftTargetToken : kMSObjCTargetToken // Runtime target section. let runtimeTargetSection = MSTransmissionTargetSection() runtimeTargetSection.headerText = "Runtime Transmission Target" runtimeTargetSection.footerText = "This transmission target is the parent of the two transmission targets below." runtimeTargetSection.token = appName.contains("SasquatchSwift") ? kMSSwiftRuntimeTargetToken : kMSObjCRuntimeTargetToken // Child 1. let child1TargetSection = MSTransmissionTargetSection() child1TargetSection.headerText = "Child Transmission Target 1" child1TargetSection.token = kMSTargetToken1 // Child 2. let child2TargetSection = MSTransmissionTargetSection() child2TargetSection.headerText = "Child Transmission Target 2" child2TargetSection.token = kMSTargetToken2 // The ordering of these target sections is important so they are displayed in the right order. transmissionTargetSections = [defaultTargetSection, runtimeTargetSection, child1TargetSection, child2TargetSection] tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableView.automaticDimension tableView.setEditing(true, animated: false) // Make sure the UITabBarController does not cut off the last cell. self.edgesForExtendedLayout = [] } override func numberOfSections(in tableView: UITableView) -> Int { return transmissionTargetSections!.count + 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == Section.TargetProperties.rawValue { return targetPropertiesSection!.tableView(tableView, numberOfRowsInSection:section) } else if section == Section.CommonSchemaProperties.rawValue { return csPropertiesSection!.tableView(tableView, numberOfRowsInSection:section) } else if section == Section.Default.rawValue { return 3 } else { return 4 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == Section.TargetProperties.rawValue { return targetPropertiesSection!.tableView(tableView, cellForRowAt:indexPath) } else if indexPath.section == Section.CommonSchemaProperties.rawValue { return csPropertiesSection!.tableView(tableView, cellForRowAt: indexPath) } let section = transmissionTargetSections![indexPath.section] switch indexPath.row { case kEnabledCellRowIndex: let cell = tableView.dequeueReusableCell(withIdentifier: kEnabledSwitchCellId)! let switcher: UISwitch? = cell.getSubview() switcher?.isOn = section.isTransmissionTargetEnabled() switcher?.isEnabled = indexPath.section != Section.Default.rawValue switcher?.addTarget(self, action: #selector(targetEnabledSwitchValueChanged), for: .valueChanged) let label: UILabel? = cell.getSubview() label!.text = "Set Enabled" return cell case kAnalyticsCellRowIndex: let cell = tableView.dequeueReusableCell(withIdentifier: kAnalyticsSwitchCellId)! let switcher: UISwitch? = cell.getSubview() switcher?.isOn = section.shouldSendAnalytics() switcher?.addTarget(self, action: #selector(targetShouldSendAnalyticsSwitchValueChanged), for: .valueChanged) return cell case kTokenCellRowIndex: let cell = tableView.dequeueReusableCell(withIdentifier: kTokenCellId)! let label: UILabel? = cell.getSubview(withTag: kTokenDisplayLabelTag) label?.text = section.token return cell case kPauseCellRowIndex: return tableView.dequeueReusableCell(withIdentifier: kPauseCellId)! default: return super.tableView(tableView, cellForRowAt: indexPath) } } @objc func targetEnabledSwitchValueChanged(sender: UISwitch!) { let sectionIndex = getCellSection(forView: sender) let section = transmissionTargetSections![sectionIndex] if (sectionIndex == Section.Default.rawValue) { section.setTransmissionTargetEnabled(sender!.isOn) } else if sectionIndex == Section.Runtime.rawValue { section.setTransmissionTargetEnabled(sender!.isOn) for childSectionIndex in 2...3 { guard let childCell = tableView.cellForRow(at: IndexPath(row: kEnabledCellRowIndex, section: childSectionIndex)) else { continue } let childSwitch: UISwitch? = childCell.getSubview() let childTarget = transmissionTargetSections![childSectionIndex].getTransmissionTarget() childSwitch!.setOn(childTarget!.enabled, animated: true) childSwitch!.isEnabled = sender!.isOn } } else if sectionIndex == Section.Child1.rawValue || sectionIndex == Section.Child2.rawValue { let switchEnabled = sender!.isOn section.setTransmissionTargetEnabled(switchEnabled) if switchEnabled && !section.isTransmissionTargetEnabled() { // Switch tried to enable the transmission target but it didn't work. sender!.setOn(false, animated: true) section.setTransmissionTargetEnabled(false) sender!.isEnabled = false } } } @objc func targetShouldSendAnalyticsSwitchValueChanged(sender: UISwitch!) { let sectionIndex = getCellSection(forView: sender) let section = transmissionTargetSections![sectionIndex] section.setShouldSendAnalytics(enabledState: sender!.isOn) } @IBAction func pause(_ sender: UIButton) { let sectionIndex = getCellSection(forView: sender) let section = transmissionTargetSections![sectionIndex] section.pause() } @IBAction func resume(_ sender: UIButton) { let sectionIndex = getCellSection(forView: sender) let section = transmissionTargetSections![sectionIndex] section.resume() } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section < transmissionTargetSections!.count { return transmissionTargetSections![section].headerText } else if section == Section.CommonSchemaProperties.rawValue { return "Override Common Schema Properties" } return "Transmission Target Properties" } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section < transmissionTargetSections!.count { return transmissionTargetSections![section].footerText } return nil } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if indexPath.section == Section.TargetProperties.rawValue { targetPropertiesSection?.tableView(tableView, commit: editingStyle, forRowAt: indexPath) } } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { if indexPath.section == Section.TargetProperties.rawValue { return targetPropertiesSection!.tableView(tableView, editingStyleForRowAt: indexPath) } return .none } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == Section.TargetProperties.rawValue && targetPropertiesSection!.isInsertRow(indexPath) { self.tableView(tableView, commit: .insert, forRowAt: indexPath) } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } /* * Without this override, the default implementation will try to get a table cell that is out of bounds * (since they are inserted/removed at a slightly different time than the actual data source is updated). */ override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int { return 0 } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if indexPath.section == Section.TargetProperties.rawValue { return targetPropertiesSection!.tableView(tableView, canEditRowAt:indexPath) } return false } override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return false } private func getCellSection(forView view: UIView) -> Int { let cell = view.superview!.superview as! UITableViewCell let indexPath = tableView.indexPath(for: cell)! return indexPath.section } }
39.986667
137
0.744748
03a4a2604b045f803465dc73bf226eb4eafa1708
2,400
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import Foundation //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// internal extension DecodingError { /// Returns a `.typeMismatch` error describing the expected type. /// /// - parameter path: The path of `CodingKey`s taken to decode a value of this type. /// - parameter expectation: The type expected to be encountered. /// - parameter reality: The value that was encountered instead of the expected type. /// - returns: A `DecodingError` with the appropriate path and debug description. internal static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError { let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead." return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description)) } /// Returns a description of the type of `value` appropriate for an error message. /// /// - parameter value: The value whose type to describe. /// - returns: A string describing `value`. /// - precondition: `value` is one of the types below. fileprivate static func _typeDescription(of value: Any) -> String { if value is NSNull { return "a null value" } else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ { return "a number" } else if value is String { return "a string/data" } else if value is [Any] { return "an array" } else if value is [String : Any] { return "a dictionary" } else { return "\(type(of: value))" } } }
46.153846
175
0.5725
d6a24b0b50032c51b796393794453bc5694ff7a7
1,922
import Cocoa class GridWrapper: NSCollectionViewItem, Wrappable, Cell { public var bounds: CGRect { return coreView.bounds } weak var wrappedView: View? { didSet { wrappableViewChanged() } } public var contentView: View { return coreView } var isFlipped: Bool = true open var coreView: FlippedView = FlippedView() open override func loadView() { view = coreView } override func viewWillLayout() { super.viewWillLayout() self.wrappedView?.frame = coreView.bounds } override func prepareForReuse() { wrappedView?.removeFromSuperview() } override var isSelected: Bool { didSet { (wrappedView as? ViewStateDelegate)?.viewStateDidChange(viewState) } } var isHighlighted: Bool = false { didSet { (wrappedView as? ViewStateDelegate)?.viewStateDidChange(viewState) } } override func mouseDown(with event: NSEvent) { super.mouseDown(with: event) guard let collectionView = collectionView else { return } guard let delegate = collectionView.delegate as? Delegate, let component = delegate.component else { return } guard event.clickCount > 1 && component.model.interaction.mouseClick == .double else { return } for index in collectionView.selectionIndexes { guard let item = component.item(at: index) else { continue } component.delegate?.component(component, itemSelected: item) } } override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) guard !isSelected else { return } (wrappedView as? ViewStateDelegate)?.viewStateDidChange(.hover) } override func mouseExited(with event: NSEvent) { super.mouseExited(with: event) guard !isHighlighted && !isSelected else { return } (wrappedView as? ViewStateDelegate)?.viewStateDidChange(.normal) } }
20.891304
90
0.672216
d545dc9a33c056218f759e2c9e3b23ab3485badb
7,370
import UIKit import SectionsTableView class CoinSettingsViewController: WalletViewController { private let delegate: ICoinSettingsViewDelegate private let mode: CoinSettingsModule.Mode private let tableView = SectionsTableView(style: .grouped) private var coinTitle: String = "" private var restoreUrl: String = "" private var derivation: MnemonicDerivation? private var syncMode: SyncMode? init(delegate: ICoinSettingsViewDelegate, mode: CoinSettingsModule.Mode) { self.delegate = delegate self.mode = mode super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(title: "button.cancel".localized, style: .plain, target: self, action: #selector(onTapCancelButton)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "coin_settings.enable_button".localized, style: .done, target: self, action: #selector(onTapEnableButton)) tableView.registerCell(forClass: CoinSettingCell.self) tableView.registerHeaderFooter(forClass: SubtitleHeaderFooterView.self) tableView.registerHeaderFooter(forClass: BottomDescriptionHeaderFooterView.self) tableView.registerHeaderFooter(forClass: CoinSettingsHeaderFooterView.self) tableView.sectionDataSource = self tableView.backgroundColor = .clear tableView.separatorStyle = .none view.addSubview(tableView) tableView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } delegate.onLoad() tableView.buildSections() } @objc func onTapEnableButton() { delegate.onTapEnableButton() } @objc func onTapCancelButton() { delegate.onTapCancelButton() } private func handleSelect(derivation: MnemonicDerivation) { self.derivation = derivation delegate.onSelect(derivation: derivation) tableView.reload(animated: true) } private func handleSelect(syncMode: SyncMode) { self.syncMode = syncMode delegate.onSelect(syncMode: syncMode) tableView.reload(animated: true) } private func derivationRows(selectedDerivation: MnemonicDerivation) -> [RowProtocol] { let derivations = MnemonicDerivation.allCases return derivations.enumerated().map { (index, derivation) in Row<CoinSettingCell>( id: derivation.rawValue, hash: "\(derivation == selectedDerivation)", height: .heightDoubleLineCell, autoDeselect: true, bind: { cell, _ in cell.bind( title: derivation.title, subtitle: derivation.description, selected: derivation == selectedDerivation, last: index == derivations.count - 1 ) }, action: { [weak self] _ in self?.handleSelect(derivation: derivation) } ) } } private func syncModeRows(selectedSyncMode: SyncMode) -> [RowProtocol] { let syncModes = [SyncMode.fast, SyncMode.slow] let coinTitle = self.coinTitle return syncModes.enumerated().map { (index, syncMode) in Row<CoinSettingCell>( id: syncMode.rawValue, hash: "\(syncMode == selectedSyncMode)", height: .heightDoubleLineCell, autoDeselect: true, bind: { cell, _ in cell.bind( title: syncMode.title(coinTitle: coinTitle), subtitle: "coin_settings.sync_mode.\(syncMode.rawValue).description".localized, selected: syncMode == selectedSyncMode, last: index == syncModes.count - 1 ) }, action: { [weak self] _ in self?.handleSelect(syncMode: syncMode) } ) } } private func header(hash: String, text: String, additionalMargin: CGFloat = 0) -> ViewState<SubtitleHeaderFooterView> { .cellType( hash: hash, binder: { view in view.bind(text: text) }, dynamicHeight: { _ in SubtitleHeaderFooterView.height + additionalMargin } ) } private func footer(hash: String, text: String) -> ViewState<BottomDescriptionHeaderFooterView> { .cellType( hash: hash, binder: { view in view.bind(text: text) }, dynamicHeight: { [unowned self] _ in BottomDescriptionHeaderFooterView.height(containerWidth: self.tableView.bounds.width, text: text) } ) } private func urlFooter(hash: String, text: String, url: String) -> ViewState<CoinSettingsHeaderFooterView> { .cellType( hash: hash, binder: { view in view.bind(text: text, url: url) { [weak self] in self?.delegate.onTapLink() } }, dynamicHeight: { [unowned self] _ in CoinSettingsHeaderFooterView.height(containerWidth: self.tableView.bounds.width, text: text, url: url) } ) } } extension CoinSettingsViewController: SectionsDataSource { func buildSections() -> [SectionProtocol] { var sections = [SectionProtocol]() if let derivation = derivation { sections.append(Section( id: "derivation", headerState: header(hash: "derivation_header", text: "coin_settings.derivation.title".localized, additionalMargin: .margin3x), footerState: footer(hash: "derivation_footer", text: "coin_settings.derivation.description_\(mode)".localized), rows: derivationRows(selectedDerivation: derivation) )) } if let syncMode = syncMode { sections.append(Section( id: "sync_mode", headerState: header(hash: "sync_mode_header", text: "coin_settings.sync_mode.title".localized), footerState: urlFooter(hash: "sync_mode_footer", text: "coin_settings.sync_mode.description".localized(coinTitle), url: restoreUrl), rows: syncModeRows(selectedSyncMode: syncMode) )) } return sections } } extension CoinSettingsViewController: ICoinSettingsView { func set(coinTitle: String) { self.coinTitle = coinTitle title = coinTitle } func set(restoreUrl: String) { self.restoreUrl = restoreUrl } func set(syncMode: SyncMode) { self.syncMode = syncMode } func set(derivation: MnemonicDerivation) { self.derivation = derivation } }
35.432692
173
0.575441
e060e6c7409d9d9d3ad22152770cdb6119e4fbf2
7,493
// // CarsTableViewController.swift // Carangas // // Created by Eric Brito on 21/10/17. // Copyright © 2017 Eric Brito. All rights reserved. // import UIKit import SideMenu class CarsTableViewController: UITableViewController { var cars: [Car] = [] var label: UILabel = { let label = UILabel() label.textAlignment = .center label.textColor = UIColor(named: "main") return label }() override func viewDidLoad() { super.viewDidLoad() tableView.refreshControl = UIRefreshControl() tableView.refreshControl?.addTarget(self, action: #selector(loadCars), for: .valueChanged) // Define the menus SideMenuManager.default.menuLeftNavigationController = storyboard!.instantiateViewController(withIdentifier: "LeftMenuNavigationController") as? UISideMenuNavigationController // Enable gestures. The left and/or right menus must be set up above for these to work. // Note that these continue to work on the Navigation Controller independent of the View Controller it displays! SideMenuManager.default.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar) SideMenuManager.default.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadCars() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // TODO como mostrar sem dados na tela de forma ideal ? return cars.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // Configure the cell... let car = cars[indexPath.row] cell.textLabel?.text = car.name cell.detailTextLabel?.text = car.brand return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let car = cars[indexPath.row] REST.delete(car: car) { (success) in if success { // ATENCAO nao esquecer disso self.cars.remove(at: indexPath.row) DispatchQueue.main.async { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } } } } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "viewSegue" { let vc = segue.destination as! CarViewController vc.car = cars[tableView.indexPathForSelectedRow!.row] } } @objc fileprivate func loadCars() { RESTAlamofire.loadCarsAlamofire(onComplete: { (cars) in self.cars = cars // precisa recarregar a tableview usando a main UI thread DispatchQueue.main.async { self.tableView.refreshControl?.endRefreshing() if cars.count == 0 { // mostrar mensagem padrao self.label.text = "Sem dados" self.tableView.backgroundView = self.label } else { self.label.text = "" } self.tableView.reloadData() } }) { (error) in // algum erro ocorreu no request var response: String = "" switch error { case .invalidJSON: response = "invalidJSON" case .noData: response = "noData" case .noResponse: response = "noResponse" case .url: response = "JSON inválido" case .taskError(let error): response = "\(error.localizedDescription)" case .responseStatusCode(let code): if code != 200 { response = "Algum problema com o servidor. :( \nError:\(code)" } } print(response) DispatchQueue.main.async { self.tableView.refreshControl?.endRefreshing() } } /* REST.loadCars(onComplete: { (cars) in self.cars = cars // precisa recarregar a tableview usando a main UI thread DispatchQueue.main.async { self.tableView.refreshControl?.endRefreshing() if cars.count == 0 { // mostrar mensagem padrao self.label.text = "Sem dados" self.tableView.backgroundView = self.label } else { self.label.text = "" } self.tableView.reloadData() } }) { (error) in // algum erro ocorreu no request var response: String = "" switch error { case .invalidJSON: response = "invalidJSON" case .noData: response = "noData" case .noResponse: response = "noResponse" case .url: response = "JSON inválido" case .taskError(let error): response = "\(error.localizedDescription)" case .responseStatusCode(let code): if code != 200 { response = "Algum problema com o servidor. :( \nError:\(code)" } } print(response) DispatchQueue.main.async { self.tableView.refreshControl?.endRefreshing() } } */ } }
30.709016
183
0.521153
23c848373183812183c5c362c27db385d6ccf168
319
// // UInt16+extensions.swift // CIDR Trainer // // Created by Darrell Root on 2/25/22. // import Foundation extension UInt16 { var hex4: String { var a = String(self,radix: 16) let prepend = 4 - a.count for _ in 0..<prepend { a = "0" + a } return a } }
15.95
39
0.517241
d57a96851f54939abc59cf2b1d48cebdee7adc8a
3,419
// // Utils.swift // AnimatableStackView // // Created by Anton Plebanovich on 7/17/19. // Copyright © 2019 Anton Plebanovich. All rights reserved. // @testable import Example import Nimble import Nimble_Snapshots import Quick import UIKit typealias SimpleClosure = () -> Void enum Utils { /// Default Window size to use for UI checking unit tests static let defaultWindowSize = CGSize(width: 375, height: 667) /// Resizes view using the screen width and checks its layout inside `it` statement using `expect` call. /// - parameter resizeableScreenWidthView: A view with height to be layouted. /// - parameter sideInset: Left and right inset to the screen side. /// - parameter beforeLayout: Actions to execute before layout. They are performed inside `it` closure so additional checks are possible inside it. static func shouldHaveProperLayout(resizeableScreenWidthView: @escaping @autoclosure () -> UIView, sideInset: CGFloat = 0, beforeLayout: SimpleClosure? = nil, file: Quick.FileString = #file, line: UInt = #line) { it("should have proper layout") { let resizeableScreenWidthView = resizeableScreenWidthView() assert(!(resizeableScreenWidthView is UITableViewCell), "Please use shouldHaveProperLayout(resizeableCell:) instead") assert(!(resizeableScreenWidthView is UICollectionViewCell), "Please use shouldHaveProperLayout(resizeableCell:) instead") resizeableScreenWidthView.translatesAutoresizingMaskIntoConstraints = false resizeableScreenWidthView.widthAnchor.constraint(equalToConstant: defaultWindowSize.width - sideInset * 2).isActive = true beforeLayout?() resizeableScreenWidthView.layoutIfNeededInWindow() expect(file: file, line: line, resizeableScreenWidthView).to(haveValidSnapshot()) } } } // ******************************* MARK: - Snapshots Recording /// Set to true to update snapshots private let recordSnapshots = false func haveValidSnapshot(named name: String? = nil, identifier: String? = nil, usesDrawRect: Bool = false, tolerance: CGFloat? = nil) -> Predicate<Snapshotable> { if recordSnapshots { return recordSnapshot(named: name, identifier: identifier, usesDrawRect: usesDrawRect) } else { return Nimble_Snapshots.haveValidSnapshot(named: name, identifier: identifier, usesDrawRect: usesDrawRect, tolerance: tolerance) } } // ******************************* MARK: - Private Extensions private extension UIView { func layoutIfNeededInWindow() { let window = UIWindow(frame: .init(origin: .zero, size: Utils.defaultWindowSize)) AppDelegate.shared.window = window window.addSubview(self) leftAnchor.constraint(equalTo: window.leftAnchor).isActive = true topAnchor.constraint(equalTo: window.topAnchor).isActive = true window.makeKeyAndVisible() window.layoutIfNeeded() window.rootViewController = nil window.isHidden = true // https://stackoverflow.com/a/59988501/4124265 if #available(iOS 13.0, *) { window.windowScene = nil } } }
40.223529
160
0.648143
387af953d23e365f3b89ee3f79d3cd1ee56c4349
2,826
// // MultipartStreamPart.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public struct MultipartStreamPart { public var headers: HTTPHeaders public var body: Body public var contentDisposition: HTTPHeaders.ContentDisposition? { get { return self.headers.contentDisposition } set { self.headers.contentDisposition = newValue } } public var name: String? { get { return self.contentDisposition?.name } set { if var contentDisposition = self.contentDisposition { contentDisposition.name = newValue self.contentDisposition = contentDisposition } else { self.contentDisposition = .init(.formData, name: newValue) } } } public init(headers: HTTPHeaders = .init(), body: HTTPBodyStreamable) { self.headers = headers self.body = .stream(body) } public init(headers: HTTPHeaders = .init(), body: String) { self.init(headers: headers, body: body.utf8) } public init<Bytes: Collection>(headers: HTTPHeaders = .init(), body: Bytes) where Bytes.Element == UInt8 { var buffer = ByteBufferAllocator().buffer(capacity: body.count) buffer.writeBytes(body) self.init(headers: headers, body: buffer) } public init(headers: HTTPHeaders = .init(), body: ByteBuffer) { self.headers = headers self.body = .buffer(body) } } extension MultipartStreamPart { public enum Body { case buffer(ByteBuffer) case stream(HTTPBodyStreamable) } }
34.048193
110
0.657466
3a78f5d2fd4baf22217d16332b90cdcf97fcd6c6
991
// // TestPushNotificationOnSimulatorTests.swift // TestPushNotificationOnSimulatorTests // // Created by Milan Panchal on 30/11/20. // import XCTest @testable import TestPushNotificationOnSimulator class TestPushNotificationOnSimulatorTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
29.147059
111
0.695257
23bede64e2ff7849acd747424e1e8daf54d8ea84
826
// // Token.swift // Firefly // // Created by Zachary lineman on 12/25/20. // import Foundation /// A type that stores the data of tokens /// Tokens represent a range of text, with some extra values /// **Range** - The range of text /// **Type** - The type of the token /// **Is Multiline** - Whether or not the token takes up multiple lines struct Token: Comparable { var range: NSRange var type: String var isMultiline: Bool static func == (lhs: Token, rhs: Token) -> Bool { return (lhs.range == rhs.range) && (lhs.type == rhs.type) && (lhs.isMultiline == rhs.isMultiline) } static func < (lhs: Token, rhs: Token) -> Bool { return (lhs.range.lowerBound < rhs.range.lowerBound) && (lhs.range.upperBound < rhs.range.upperBound) && (lhs.type < rhs.type) } }
29.5
134
0.622276
23edcbc57d1b4a500030b0947596f6968a31ebc5
3,419
//// // 🦠 Corona-Warn-App // import FMDB extension EventStore { convenience init?(url: URL) { guard let databaseQueue = FMDatabaseQueue(path: url.path) else { Log.error("[EventStore] Failed to create FMDatabaseQueue.", log: .localData) return nil } let latestDBVersion = 1 let schema = EventStoreSchemaV1( databaseQueue: databaseQueue ) let migrations: [Migration] = [] let migrator = SerialDatabaseQueueMigrator( queue: databaseQueue, latestVersion: latestDBVersion, migrations: migrations ) self.init( databaseQueue: databaseQueue, schema: schema, key: EventStore.encryptionKey, migrator: migrator ) } static var storeURL: URL { storeDirectoryURL .appendingPathComponent("EventStore") .appendingPathExtension("sqlite") } static var storeDirectoryURL: URL { let fileManager = FileManager.default guard let storeDirectoryURL = try? fileManager .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("EventStore") else { fatalError("[EventStore] Could not create folder.") } if !fileManager.fileExists(atPath: storeDirectoryURL.path) { do { try fileManager.createDirectory(atPath: storeDirectoryURL.path, withIntermediateDirectories: true, attributes: nil) } catch { Log.error("Could not create directory at \(storeDirectoryURL)", log: .localData, error: error) assertionFailure() } } return storeDirectoryURL } static func make(url: URL? = nil) -> EventStore { let storeURL: URL if let url = url { storeURL = url } else { storeURL = EventStore.storeURL } Log.info("[EventStore] Trying to create event store...", log: .localData) if let store = EventStore(url: storeURL) { Log.info("[EventStore] Successfully created event store", log: .localData) return store } Log.info("[EventStore] Failed to create event store. Try to rescue it...", log: .localData) // The database could not be created – To the rescue! // Remove the database file and try to init the store a second time. do { try FileManager.default.removeItem(at: storeURL) } catch { Log.error("Could not remove item at \(EventStore.storeDirectoryURL)", log: .localData, error: error) assertionFailure() } if let secondTryStore = EventStore(url: storeURL) { Log.info("[EventStore] Successfully rescued event store", log: .localData) return secondTryStore } else { Log.info("[EventStore] Failed to rescue event store.", log: .localData) fatalError("[EventStore] Could not create event store after second try.") } } private static var encryptionKey: String { guard let keychain = try? KeychainHelper() else { fatalError("[EventStore] Failed to create KeychainHelper for event store.") } let key: String if let keyData = keychain.loadFromKeychain(key: EventStore.encryptionKeyKey) { key = String(decoding: keyData, as: UTF8.self) } else { do { key = try keychain.generateEventDatabaseKey() } catch { fatalError("[EventStore] Failed to create key for event store.") } } return key } static func resetEncryptionKey() throws -> String { guard let keychain = try? KeychainHelper() else { fatalError("[EventStore] Failed to create KeychainHelper for event store.") } try keychain.clearInKeychain(key: EventStore.encryptionKeyKey) return encryptionKey } }
27.352
119
0.711319