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
4874e9d4a00e9e43e0c68c3b4d0bca1b72910a5c
4,988
// // Created by James Sangalli on 8/11/18. // import Foundation import CryptoSwift import Result import web3swift //https://github.com/ethereum/EIPs/blob/master/EIPS/eip-137.md extension String { var nameHash: String { var node = [UInt8].init(repeating: 0x0, count: 32) if !self.isEmpty { node = self.split(separator: ".") .map { Array($0.utf8).sha3(.keccak256) } .reversed() .reduce(node) { return ($0 + $1).sha3(.keccak256) } } return "0x" + node.toHexString() } } class GetENSAddressCoordinator { private struct ENSLookupKey: Hashable { let name: String let server: RPCServer } private static var resultsCache = [ENSLookupKey: EthereumAddress]() private static let DELAY_AFTER_STOP_TYPING_TO_START_RESOLVING_ENS_NAME = TimeInterval(0.5) private var toStartResolvingEnsNameTimer: Timer? private let server: RPCServer init(server: RPCServer) { self.server = server } func getENSAddressFromResolver( for input: String, completion: @escaping (Result<EthereumAddress, AnyError>) -> Void ) { //if already an address, send back the address if let ethAddress = EthereumAddress(input) { completion(.success(ethAddress)) return } //if it does not contain .eth, then it is not a valid ens name if !input.contains(".") { completion(.failure(AnyError(Web3Error(description: "Invalid ENS Name")))) return } let node = input.lowercased().nameHash if let cachedResult = cachedResult(forNode: node) { completion(.success(cachedResult)) return } let function = GetENSResolverEncode() callSmartContract(withServer: server, contract: server.ensRegistrarContract, functionName: function.name, abiString: function.abi, parameters: [node] as [AnyObject]).done { result in //if null address is returned (as 0) we count it as invalid //this is because it is not assigned to an ENS and puts the user in danger of sending funds to null if let resolver = result["0"] as? EthereumAddress { if Constants.nullAddress.sameContract(as: resolver) { completion(.failure(AnyError(Web3Error(description: "Null address returned")))) } else { let function = GetENSRecordFromResolverEncode() callSmartContract(withServer: self.server, contract: AlphaWallet.Address(address: resolver), functionName: function.name, abiString: function.abi, parameters: [node] as [AnyObject]).done { result in if let ensAddress = result["0"] as? EthereumAddress { if Constants.nullAddress.sameContract(as: ensAddress) { completion(.failure(AnyError(Web3Error(description: "Null address returned")))) } else { //Retain self because it's useful to cache the results even if we don't immediately need it now self.cache(forNode: node, result: ensAddress) completion(.success(ensAddress)) } } else { completion(.failure(AnyError(Web3Error(description: "Incorrect data output from ENS resolver")))) } }.cauterize() } } else { completion(.failure(AnyError(Web3Error(description: "Error extracting result from \(self.server.ensRegistrarContract).\(function.name)()")))) } }.catch { completion(.failure(AnyError($0))) } } func queueGetENSOwner(for input: String, completion: @escaping (Result<EthereumAddress, AnyError>) -> Void) { let node = input.lowercased().nameHash if let cachedResult = cachedResult(forNode: node) { completion(.success(cachedResult)) return } toStartResolvingEnsNameTimer?.invalidate() toStartResolvingEnsNameTimer = Timer.scheduledTimer(withTimeInterval: GetENSAddressCoordinator.DELAY_AFTER_STOP_TYPING_TO_START_RESOLVING_ENS_NAME, repeats: false) { _ in //Retain self because it's useful to cache the results even if we don't immediately need it now self.getENSAddressFromResolver(for: input) { result in completion(result) } } } private func cachedResult(forNode node: String) -> EthereumAddress? { return GetENSAddressCoordinator.resultsCache[ENSLookupKey(name: node, server: server)] } private func cache(forNode node: String, result: EthereumAddress) { GetENSAddressCoordinator.resultsCache[ENSLookupKey(name: node, server: server)] = result } }
42.271186
218
0.609463
0890f45c453f9866dd73ad58e8a01b59c99f2f22
1,289
// // GoodsListTableViewCell.swift // Shoping // // Created by qiang.c.fu on 2020/1/3. // Copyright © 2020 付强. All rights reserved. // import UIKit class GoodsListTableViewCell: UITableViewCell { @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var img: UIImageView! override func awakeFromNib() { super.awakeFromNib() setPrice() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setPrice() { let attributes: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.font: UIFont(name: "Helvetica-Bold", size: 28)!, NSAttributedString.Key.foregroundColor: UIColor.red ] let attributesR: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.foregroundColor: UIColor.red ] let attrName = NSMutableAttributedString(string: "¥200 200人付款") attrName.addAttributes(attributes, range: NSRange.init(location: 1, length: 3)) attrName.addAttributes(attributesR, range: NSRange.init(location: 0, length: 1)) priceLabel.attributedText = attrName } }
30.690476
88
0.660202
1808447aaed0dc85c4920415f38214e93fc602a5
97,105
// swiftlint:disable cyclomatic_complexity // swiftlint:disable file_length // swiftlint:disable force_cast // swiftlint:disable force_try // swiftlint:disable function_body_length // swiftlint:disable type_body_length // swiftlint:disable todo import XCTest import MongoSwift import StitchCore import StitchCoreSDK import StitchCoreAdminClient import StitchDarwinCoreTestUtils @testable import StitchCoreRemoteMongoDBService import StitchCoreLocalMongoDBService @testable import StitchRemoteMongoDBService class XCMongoMobileConfiguration: NSObject, XCTestObservation { // This init is called first thing as the test bundle starts up and before any test // initialization happens override init() { super.init() // We don't need to do any real work, other than register for callbacks // when the test suite progresses. // XCTestObservation keeps a strong reference to observers XCTestObservationCenter.shared.addTestObserver(self) } func testBundleWillStart(_ testBundle: Bundle) { try? CoreLocalMongoDBService.shared.initialize() } func testBundleDidFinish(_ testBundle: Bundle) { CoreLocalMongoDBService.shared.close() } } class RemoteMongoClientIntTests: BaseStitchIntTestCocoaTouch { private let mongodbUriProp = "test.stitch.mongodbURI" private lazy var pList: [String: Any]? = fetchPlist(type(of: self)) private lazy var mongodbUri: String = pList?[mongodbUriProp] as? String ?? "mongodb://localhost:26000" private let dbName = ObjectId().hex private let collName = ObjectId().hex private var mongoClient: RemoteMongoClient! override func setUp() { super.setUp() try! prepareService() let joiner = CallbackJoiner() getTestColl().deleteMany([:], joiner.capture()) _ = joiner.capturedValue } override func tearDown() { let joiner = CallbackJoiner() getTestColl().deleteMany([:], joiner.capture()) XCTAssertNotNil(joiner.capturedValue) getTestColl().sync.proxy.dataSynchronizer.stop() CoreLocalMongoDBService.shared.localInstances.forEach { client in try! client.listDatabases().forEach { try? client.db($0["name"] as! String).drop() } } } private func prepareService() throws { let app = try self.createApp() _ = try self.addProvider(toApp: app.1, withConfig: ProviderConfigs.anon) let svc = try self.addService( toApp: app.1, withType: "mongodb", withName: "mongodb1", withConfig: ServiceConfigs.mongodb( name: "mongodb1", uri: mongodbUri ) ) _ = try self.addRule( toService: svc.1, withConfig: RuleCreator.mongoDb( database: dbName, collection: collName, roles: [RuleCreator.Role( read: true, write: true )], schema: RuleCreator.Schema(properties: Document())) ) let client = try self.appClient(forApp: app.0) let exp = expectation(description: "should login") client.auth.login(withCredential: AnonymousCredential()) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) self.mongoClient = try client.serviceClient(fromFactory: remoteMongoClientFactory, withName: "mongodb1") } private func getTestColl() -> RemoteMongoCollection<Document> { let db = mongoClient.db(dbName.description) XCTAssertEqual(dbName, db.name) let coll = db.collection(collName) XCTAssertEqual(dbName, coll.databaseName) XCTAssertEqual(collName, coll.name) return coll } private func getTestColl<T>(_ type: T.Type) -> RemoteMongoCollection<T> { let db = mongoClient.db(dbName.description) XCTAssertEqual(dbName, db.name) let coll = db.collection(collName, withCollectionType: type) XCTAssertEqual(dbName, coll.databaseName) XCTAssertEqual(collName, coll.name) return coll } func testCount() { let coll = getTestColl() var exp = expectation(description: "should count empty collection") coll.count { result in switch result { case .success(let count): XCTAssertEqual(0, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) let rawDoc: Document = ["hello": "world"] let doc1 = rawDoc let doc2 = rawDoc exp = expectation(description: "document should be inserted") coll.insertOne(doc1) { (_) in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should count collection with one document") coll.count { result in switch result { case .success(let count): XCTAssertEqual(1, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "document should be inserted") coll.insertOne(doc2) { (_) in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should count collection with two document") coll.count { result in switch result { case .success(let count): XCTAssertEqual(2, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should find two documents with original document as filter") coll.count(rawDoc) { result in switch result { case .success(let count): XCTAssertEqual(2, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should not find any documents when filtering for nonexistent document") coll.count(["hello": "Friend"]) { result in switch result { case .success(let count): XCTAssertEqual(0, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should find one document when limiting result") coll.count(rawDoc, options: RemoteCountOptions.init(limit: 1)) { result in switch result { case .success(let count): XCTAssertEqual(1, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should error with invalid filter") coll.count(["$who": 1]) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } private func withoutId(_ document: Document) -> Document { var newDoc = Document() document.filter { $0.0 != "_id" }.forEach { (key, value) in newDoc[key] = value } return newDoc } private func withoutIds(_ documents: [Document]) -> [Document] { var list: [Document] = [] documents.forEach { (doc) in list.append(withoutId(doc)) } return list } func testFindOne() { let coll = getTestColl() var exp = expectation(description: "should not find any documents in empty collection") coll.findOne { result in switch result { case .success(let doc): XCTAssertNil(doc) case .failure(let err): XCTFail("unexpected failure in findOne \(err)") } exp.fulfill() } wait(for: [exp], timeout: 5.0) let doc1: Document = ["hello": "world"] let doc2: Document = ["hello": "friend", "proj": "field"] exp = expectation(description: "should insert one document") coll.insertOne(doc1) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should find the inserted documents") coll.findOne { result in switch result { case .success(let resultDoc): XCTAssertNotNil(resultDoc) XCTAssertEqual(self.withoutId(doc1), self.withoutId(resultDoc!)) case .failure(let err): XCTFail("unexpected failure in findOne \(err)") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should insert one document") coll.insertOne(doc2) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should find the inserted documents when applying filter") coll.findOne(doc2, options: RemoteFindOptions.init(projection: ["proj": 1])) { result in switch result { case .success(let resultDoc): XCTAssertNotNil(resultDoc) XCTAssertEqual(["proj": "field"], self.withoutId(resultDoc!)) case .failure(let err): XCTFail("unexpected failure in findOne \(err)") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "find with filter should return nil if no documents match") coll.findOne(["noAField": 1]) {result in switch result { case .success(let resultDoc): XCTAssertNil(resultDoc) case .failure(let err): XCTFail("unexpected failure in findOne \(err)") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should error with invalid filter") coll.findOne(["$who": 1]) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testFind() { let coll = getTestColl() var exp = expectation(description: "should not find any documents in empty collection") coll.find().toArray { result in switch result { case .success(let docs): XCTAssertEqual([], docs) case .failure: XCTFail("unexpected failure in find") } exp.fulfill() } wait(for: [exp], timeout: 5.0) let doc1: Document = ["hello": "world"] let doc2: Document = ["hello": "friend", "proj": "field"] exp = expectation(description: "should insert two documents") coll.insertMany([doc1, doc2]) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should find the inserted documents") coll.find().toArray { result in switch result { case .success(let resultDocs): XCTAssertEqual(self.withoutId(doc1), self.withoutId(resultDocs[0])) XCTAssertEqual(self.withoutId(doc2), self.withoutId(resultDocs[1])) case .failure: XCTFail("unexpected failure in find") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should find the second document when applying it as a filter") coll.find(doc2).first { result in switch result { case .success(let document): XCTAssertEqual(self.withoutId(doc2), self.withoutId(document!)) case .failure: XCTFail("unexpected failure in find") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should project the result when a projection is specified") coll.find(doc2, options: RemoteFindOptions.init(projection: ["proj": 1])).first { result in switch result { case .success(let document): XCTAssertEqual(["proj": "field"], document!) case .failure: XCTFail("unexpected failure in find") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "async iterator should work") var cursor: RemoteMongoCursor<Document>! coll.find().iterator { result in switch result { case .success(let foundCursor): cursor = foundCursor case .failure: XCTFail("unexpected failure in find") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "iterator should find first document") cursor.next({ result in switch result { case .success(let document): XCTAssertEqual(self.withoutId(doc1), self.withoutId(document!)) case .failure: XCTFail("unexpected failure in cursor next") } exp.fulfill() }) wait(for: [exp], timeout: 5.0) exp = expectation(description: "iterator should find second document") cursor.next({ result in switch result { case .success(let document): XCTAssertEqual(self.withoutId(doc2), self.withoutId(document!)) case .failure: XCTFail("unexpected failure in cursor next") } exp.fulfill() }) wait(for: [exp], timeout: 5.0) exp = expectation(description: "iterator should find no more documents") cursor.next({ result in switch result { case .success(let document): XCTAssertNil(document) case .failure: XCTFail("unexpected failure in cursor next") } exp.fulfill() }) wait(for: [exp], timeout: 5.0) exp = expectation(description: "should error with invalid filter") coll.find(["$who": 1]).first { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testAggregate() { let coll = getTestColl() var exp = expectation(description: "should not find any documents in empty collection") coll.aggregate([]).toArray { result in switch result { case .success(let docs): XCTAssertEqual([], docs) case .failure: XCTFail("unexpected error in aggregate") } exp.fulfill() } wait(for: [exp], timeout: 5.0) let doc1: Document = ["hello": "world"] let doc2: Document = ["hello": "friend"] exp = expectation(description: "should insert two documents") coll.insertMany([doc1, doc2]) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should find the inserted documents") coll.aggregate([]).toArray { result in switch result { case .success(let docs): XCTAssertEqual(self.withoutId(doc1), self.withoutId(docs[0])) XCTAssertEqual(self.withoutId(doc2), self.withoutId(docs[1])) case .failure: XCTFail("unexpected error in aggregate") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation( description: "should find the second document when sorting by descending object id, and limiting to 1" ) coll.aggregate([["$sort": ["_id": -1] as Document], ["$limit": 1]]).toArray { result in switch result { case .success(let docs): XCTAssertEqual(1, docs.count) XCTAssertEqual(self.withoutId(doc2), self.withoutId(docs.first!)) case .failure: XCTFail("unexpected error in aggregate") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should find first document when matching for it") coll.aggregate([["$match": doc1]]).toArray { result in switch result { case .success(let docs): XCTAssertEqual(1, docs.count) XCTAssertEqual(self.withoutId(doc1), self.withoutId(docs.first!)) case .failure: XCTFail("unexpected error in aggregate") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should error with invalid pipeline") coll.aggregate([["$who": 1]]).first { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testInsertOne() { let coll = getTestColl() let doc: Document = ["_id": ObjectId(), "hello": "world"] var exp = expectation(description: "document should be successfully inserted") coll.insertOne(doc) { result in switch result { case .success(let insertResult): XCTAssertEqual(doc["_id"] as! ObjectId, insertResult.insertedId as! ObjectId) case .failure: XCTFail("unexpected error in insert") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "document should not be inserted again because it would be a duplicate") coll.insertOne(doc) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(let message, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) XCTAssertNotNil(message.range(of: "duplicate")) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "document should be successfully inserted with a differento object ID") coll.insertOne(["hello": "world"]) { result in switch result { case .success(let insertResult): XCTAssertNotEqual(doc["_id"] as! ObjectId, insertResult.insertedId as! ObjectId) case .failure: XCTFail("unexpected error in insert") } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testInsertMany() { let coll = getTestColl() let doc1: Document = ["_id": ObjectId(), "hello": "world"] var exp = expectation(description: "single document should be successfully inserted") coll.insertMany([doc1]) { result in switch result { case .success(let insertResult): XCTAssertEqual(doc1["_id"] as! ObjectId, insertResult.insertedIds[0] as! ObjectId) case .failure: XCTFail("unexpected error in insert") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "document should not be inserted again because it would be a duplicate") coll.insertMany([doc1]) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(let message, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) XCTAssertNotNil(message.range(of: "duplicate")) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) let doc2: Document = ["hello": "world"] exp = expectation(description: "document should be successfully inserted with a different object ID") coll.insertMany([doc2]) { result in switch result { case .success(let insertResult): XCTAssertNotEqual(doc1["_id"] as! ObjectId, insertResult.insertedIds[0] as! ObjectId) case .failure: XCTFail("unexpected error in insert") } exp.fulfill() } wait(for: [exp], timeout: 5.0) let doc3: Document = ["one": "two"] let doc4: Document = ["three": 4] exp = expectation(description: "multiple documents should be successfully inserted") coll.insertMany([doc3, doc4]) { result in switch result { case .success(let insertResult): XCTAssertEqual(2, insertResult.insertedIds.count) case .failure: XCTFail("unexpected error in insert") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "all inserted documents should be findable") coll.find().toArray { result in switch result { case .success(let documents): XCTAssertEqual(self.withoutIds([doc1, doc2, doc3, doc4]), self.withoutIds(documents)) case .failure: XCTFail("unexpected error in find") } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testDeleteOne() { let coll = getTestColl() var exp = expectation(description: "delete on an empty collection should result in no deletions") coll.deleteOne([:]) { result in switch result { case .success(let deleteResult): XCTAssertEqual(0, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "delete on an empty collection should result in no deletions") coll.deleteOne(["hello": "world"]) { result in switch result { case .success(let deleteResult): XCTAssertEqual(0, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) let doc1: Document = ["hello": "world"] let doc2: Document = ["hello": "friend"] exp = expectation(description: "multiple documents should be inserted") coll.insertMany([doc1, doc2]) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "deleting in a non-empty collection should work") coll.deleteOne([:]) { result in switch result { case .success(let deleteResult): XCTAssertEqual(1, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "deleting in a non-empty collection should work") coll.deleteOne([:]) { result in switch result { case .success(let deleteResult): XCTAssertEqual(1, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "no more items in collection should result in no deletes") coll.deleteOne([:]) { result in switch result { case .success(let deleteResult): XCTAssertEqual(0, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "multiple documents should be inserted") coll.insertMany([doc1, doc2]) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "deleting an item by filter work") coll.deleteOne(doc1) { result in switch result { case .success(let deleteResult): XCTAssertEqual(1, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation( description: "once the item is deleted, the delete with the filter should no longer delete anything" ) coll.deleteOne(doc1) { result in switch result { case .success(let deleteResult): XCTAssertEqual(0, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "there should be one document left in the collection") coll.count { result in switch result { case .success(let count): XCTAssertEqual(1, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "there should be no documents left matching the filter") coll.count(doc1) { result in switch result { case .success(let count): XCTAssertEqual(0, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should error with invalid filter") coll.deleteOne(["$who": 1]) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testDeleteMany() { let coll = getTestColl() var exp = expectation(description: "delete on an empty collection should result in no deletions") coll.deleteMany([:]) { result in switch result { case .success(let deleteResult): XCTAssertEqual(0, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "delete on an empty collection should result in no deletions") coll.deleteMany(["hello": "world"]) { result in switch result { case .success(let deleteResult): XCTAssertEqual(0, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) let doc1: Document = ["hello": "world"] let doc2: Document = ["hello": "friend"] exp = expectation(description: "multiple documents should be inserted") coll.insertMany([doc1, doc2]) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "deleting in a non-empty collection should work") coll.deleteMany([:]) { result in switch result { case .success(let deleteResult): XCTAssertEqual(2, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "no more items in collection should result in no deletes") coll.deleteMany([:]) { result in switch result { case .success(let deleteResult): XCTAssertEqual(0, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "multiple documents should be inserted") coll.insertMany([doc1, doc2]) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "deleting an item by filter work") coll.deleteMany(doc1) { result in switch result { case .success(let deleteResult): XCTAssertEqual(1, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation( description: "once the item is deleted, the delete with the filter should no longer delete anything" ) coll.deleteMany(doc1) { result in switch result { case .success(let deleteResult): XCTAssertEqual(0, deleteResult.deletedCount) case .failure: XCTFail("unexpected error in delete") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "there should be one document left in the collection") coll.count { result in switch result { case .success(let count): XCTAssertEqual(1, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "there should be no documents left matching the filter") coll.count(doc1) { result in switch result { case .success(let count): XCTAssertEqual(0, count) case .failure: XCTFail("unexpected error in count") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should error with invalid filter") coll.deleteMany(["$who": 1]) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testUpdateOne() { let coll = getTestColl() let doc1: Document = ["hello": "world"] var exp = expectation(description: "updating a document in an empty collection should result in no update") coll.updateOne(filter: [:], update: doc1) { result in switch result { case .success(let updateResult): XCTAssertEqual(0, updateResult.matchedCount) XCTAssertEqual(0, updateResult.modifiedCount) XCTAssertNil(updateResult.upsertedId) case .failure: XCTFail("unexpected error in update") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "upsert should be successful") coll.updateOne(filter: [:], update: doc1, options: RemoteUpdateOptions.init(upsert: true)) { result in switch result { case .success(let updateResult): XCTAssertEqual(0, updateResult.matchedCount) XCTAssertEqual(0, updateResult.modifiedCount) XCTAssertNotNil(updateResult.upsertedId) case .failure: XCTFail("unexpected error in update") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "updating an existing document should work") coll.updateOne(filter: [:], update: ["$set": ["woof": "meow"] as Document]) { result in switch result { case .success(let updateResult): XCTAssertEqual(1, updateResult.matchedCount) XCTAssertEqual(1, updateResult.modifiedCount) XCTAssertNil(updateResult.upsertedId) case .failure: XCTFail("unexpected error in update") } exp.fulfill() } wait(for: [exp], timeout: 5.0) let expectedDoc: Document = ["hello": "world", "woof": "meow"] exp = expectation(description: "should find the updated document in the collection") coll.find().first { result in switch result { case .success(let document): XCTAssertEqual(expectedDoc, self.withoutId(document!)) case .failure: XCTFail("unexpected error in find") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should error with invalid filter") coll.updateOne(filter: ["$who": 1], update: [:]) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testUpdateMany() { let coll = getTestColl() let doc1: Document = ["hello": "world"] var exp = expectation(description: "updating a document in an empty collection should result in no updates") coll.updateMany(filter: [:], update: doc1) { result in switch result { case .success(let updateResult): XCTAssertEqual(0, updateResult.matchedCount) XCTAssertEqual(0, updateResult.modifiedCount) XCTAssertNil(updateResult.upsertedId) case .failure: XCTFail("unexpected error in update") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "upsert should be successful") coll.updateMany(filter: [:], update: doc1, options: RemoteUpdateOptions.init(upsert: true)) { result in switch result { case .success(let updateResult): XCTAssertEqual(0, updateResult.matchedCount) XCTAssertEqual(0, updateResult.modifiedCount) XCTAssertNotNil(updateResult.upsertedId) case .failure: XCTFail("unexpected error in update") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "updating an existing document should work") coll.updateMany(filter: [:], update: ["$set": ["woof": "meow"] as Document]) { result in switch result { case .success(let updateResult): XCTAssertEqual(1, updateResult.matchedCount) XCTAssertEqual(1, updateResult.modifiedCount) XCTAssertNil(updateResult.upsertedId) case .failure: XCTFail("unexpected error in update") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should insert a document") coll.insertOne([:]) { _ in exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "updating multiple existing documents should work") coll.updateMany(filter: [:], update: ["$set": ["woof": "meow"] as Document]) { result in switch result { case .success(let updateResult): XCTAssertEqual(2, updateResult.matchedCount) XCTAssertEqual(2, updateResult.modifiedCount) XCTAssertNil(updateResult.upsertedId) case .failure: XCTFail("unexpected error in update") } exp.fulfill() } wait(for: [exp], timeout: 5.0) let expectedDoc1: Document = ["hello": "world", "woof": "meow"] let expectedDoc2: Document = ["woof": "meow"] exp = expectation(description: "should find the updated documents in the collection") coll.find().toArray { result in switch result { case .success(let documents): XCTAssertEqual([expectedDoc1, expectedDoc2], self.withoutIds(documents)) case .failure: XCTFail("unexpected error in find") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should error with invalid filter") coll.updateMany(filter: ["$who": 1], update: [:]) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testFindOneAndUpdate() { let coll = getTestColl() let joiner = CallbackJoiner() // Collection should start out empty // This also tests the null return format coll.findOneAndUpdate(filter: [:], update: [:], joiner.capture()) if let resErr = joiner.value(asType: Document.self) { XCTFail("Found Document Where It Shouldnt Be \(resErr)") return } // Insert a sample Document coll.insertOne(["hello": "world1", "num": 2], joiner.capture()) _ = joiner.capturedValue coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Sample call to findOneAndUpdate() where we get the previous document back coll.findOneAndUpdate( filter: ["hello": "world1"], update: ["$inc": ["num": 1] as Document, "$set": ["hello": "hellothere"] as Document], joiner.capture()) guard let result1 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world1", "num": 2], withoutId(result1)) coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Make sure the update took place coll.findOne([:], joiner.capture()) guard let result2 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "hellothere", "num": 3], withoutId(result2)) // Call findOneAndUpdate() again but get the new document coll.findOneAndUpdate( filter: ["hello": "hellothere"], update: ["$inc": ["num": 1] as Document], options: RemoteFindOneAndModifyOptions(returnNewDocument: true), joiner.capture()) guard let result3 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "hellothere", "num": 4], withoutId(result3)) coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Make sure that was the new document coll.findOne([:], joiner.capture()) guard let result4 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "hellothere", "num": 4], withoutId(result4)) // Test null behaviour again with a filter that should not match any documents coll.findOneAndUpdate(filter: ["helloa": "thisisnotreal"], update: ["hi": "there"], joiner.capture()) if let resErr = joiner.value(asType: Document.self) { XCTFail("Found Document Where It Shouldnt Be \(resErr)") return } // Test the upsert option where it should not actually be invoked coll.findOneAndUpdate( filter: ["hello": "hellothere"], update: ["$set": ["hello": "world1", "num": 1] as Document], options: RemoteFindOneAndModifyOptions(upsert: true, returnNewDocument: true), joiner.capture()) guard let result5 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world1", "num": 1], withoutId(result5)) // There should still only be one documnt in the collection coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Test the upsert option where the server should perform upsert and return new document coll.findOneAndUpdate( filter: ["hello": "hello"], update: ["$set": ["hello": "world2", "num": 2] as Document], options: RemoteFindOneAndModifyOptions(upsert: true, returnNewDocument: true), joiner.capture()) guard let result6 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world2", "num": 2], withoutId(result6)) // There should now be 2 documents in the collection coll.count([:], joiner.capture()) XCTAssertEqual(2, joiner.value(asType: Int.self)) // Test the upsert option where the server should perform upsert and return old document // The old document should be empty coll.findOneAndUpdate( filter: ["hello": "hello"], update: ["$set": ["hello": "world3", "num": 3] as Document], options: RemoteFindOneAndModifyOptions(upsert: true), joiner.capture()) if let resErr = joiner.value(asType: Document.self) { XCTFail("Found Document Where It Shouldnt Be \(resErr)") return } // There should now be three documents in the collection coll.count([:], joiner.capture()) XCTAssertEqual(3, joiner.value(asType: Int.self)) // Test sort and project coll.findOneAndUpdate( filter: [:], update: ["$inc": ["num": 1] as Document], options: RemoteFindOneAndModifyOptions( projection: ["hello": 1, "_id": 0], sort: ["num": -1] ), joiner.capture()) guard let result7 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world3"], result7) coll.findOneAndUpdate( filter: [:], update: ["$inc": ["num": 1] as Document], options: RemoteFindOneAndModifyOptions( projection: ["hello": 1, "_id": 0], sort: ["num": 1] ), joiner.capture()) guard let result8 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world1"], result8) // Test proper failure let exp = expectation(description: "should error with invalid filter") coll.findOneAndUpdate(filter: [:], update: ["$who": 1]) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.mongoDBError, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testFindOneAndReplace() { let coll = getTestColl() let joiner = CallbackJoiner() // Collection should start out empty // This also tests the null return format coll.findOneAndReplace(filter: [:], replacement: [:], joiner.capture()) if let resErr = joiner.value(asType: Document.self) { XCTFail("Found Document Where It Shouldnt Be \(resErr)") return } // Insert a sample Document coll.insertOne(["hello": "world1", "num": 1], joiner.capture()) _ = joiner.capturedValue coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Sample call to findOneAndReplace() where we get the previous document back coll.findOneAndReplace( filter: ["hello": "world1"], replacement: ["hello": "world2", "num": 2], joiner.capture()) guard let result1 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world1", "num": 1], withoutId(result1)) coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Make sure the update took place coll.findOne([:], joiner.capture()) guard let result2 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world2", "num": 2], withoutId(result2)) // Call findOneAndReplace() again but get the new document coll.findOneAndReplace( filter: [:], replacement: ["hello": "world3", "num": 3], options: RemoteFindOneAndModifyOptions(returnNewDocument: true), joiner.capture()) guard let result3 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world3", "num": 3], withoutId(result3)) coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Make sure that was the new document coll.findOne([:], joiner.capture()) guard let result4 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world3", "num": 3], withoutId(result4)) // Test null behaviour again with a filter that should not match any documents coll.findOneAndReplace(filter: ["helloa": "t"], replacement: ["hi": "there"], joiner.capture()) if let resErr = joiner.value(asType: Document.self) { XCTFail("Found Document Where It Shouldnt Be \(resErr)") return } // Test the upsert option where it should not actually be invoked coll.findOneAndReplace( filter: ["hello": "world3"], replacement: ["hello": "world4", "num": 4], options: RemoteFindOneAndModifyOptions(upsert: true, returnNewDocument: true), joiner.capture()) guard let result5 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world4", "num": 4], withoutId(result5)) // There should still only be one documnt in the collection coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Test the upsert option where the server should perform upsert and return new document coll.findOneAndReplace( filter: ["hello": "world3"], replacement: ["hello": "world5", "num": 5], options: RemoteFindOneAndModifyOptions(upsert: true, returnNewDocument: true), joiner.capture()) guard let result6 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world5", "num": 5], withoutId(result6)) // There should now be 2 documents in the collection coll.count([:], joiner.capture()) XCTAssertEqual(2, joiner.value(asType: Int.self)) // Test the upsert option where the server should perform upsert and return old document // The old document should be empty coll.findOneAndReplace( filter: ["hello": "world3"], replacement: ["hello": "world6", "num": 6], options: RemoteFindOneAndModifyOptions(upsert: true), joiner.capture()) if let resErr = joiner.value(asType: Document.self) { XCTFail("Found Document Where It Shouldnt Be \(resErr)") return } // There should now be three documents in the collection coll.count([:], joiner.capture()) XCTAssertEqual(3, joiner.value(asType: Int.self)) // Test sort and project coll.findOneAndReplace( filter: [:], replacement: ["hello": "blah", "num": 100], options: RemoteFindOneAndModifyOptions( projection: ["hello": 1, "_id": 0], sort: ["num": -1] ), joiner.capture()) guard let result7 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world6"], result7) coll.findOneAndReplace( filter: [:], replacement: ["hello": "blahblah", "num": 200], options: RemoteFindOneAndModifyOptions( projection: ["hello": 1, "_id": 0], sort: ["num": 1] ), joiner.capture()) guard let result8 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world4"], result8) // Test proper failure let exp = expectation(description: "should error with invalid filter") coll.findOneAndReplace(filter: [:], replacement: ["$who": 1]) { result in switch result { case .success: XCTFail("expected an error") case .failure(let error): switch error { case .serviceError(_, let withServiceErrorCode): XCTAssertEqual(StitchServiceErrorCode.invalidParameter, withServiceErrorCode) default: XCTFail("unexpected error code") } } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testFindOneAndDelete() { let coll = getTestColl() let joiner = CallbackJoiner() // Collection should start out empty // This also tests the null return format if case let .success(document) = await(coll.findOneAndDelete, [:], nil), document != nil { XCTFail("Found Document Where It Shouldnt Be: \(String(describing: document))") return } // Insert a sample Document guard case .success(let insertOneResult) = await(coll.insertOne, ["hello": "world1", "num": 1]) else { XCTFail("could not insert sample document") return } guard case .success(1) = await(coll.count, [:], nil) else { XCTFail("too many documents in collection") return } // Simple call to findOneAndDelete() where we delete the only document in the collection guard case .success( ["_id": insertOneResult.insertedId, "hello": "world1", "num": 1]) = await(coll.findOneAndDelete, [:], nil) else { XCTFail("document not found") return } // There should be no documents in the collection guard case .success(0) = await(coll.count, [:], nil) else { XCTFail("too many documents in collection") return } // TODO: Replace `joiner` with new await syntax // Insert a sample Document coll.insertOne(["hello": "world1", "num": 1], joiner.capture()) _ = joiner.capturedValue coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Call findOneAndDelete() again but this time wijth a filter coll.findOneAndDelete( filter: ["hello": "world1"], joiner.capture()) guard let result2 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world1", "num": 1], withoutId(result2)) // There should be no documents in the collection coll.count([:], joiner.capture()) XCTAssertEqual(0, joiner.value(asType: Int.self)) // Insert a sample Document coll.insertOne(["hello": "world1", "num": 1], joiner.capture()) _ = joiner.capturedValue coll.count([:], joiner.capture()) XCTAssertEqual(1, joiner.value(asType: Int.self)) // Call findOneAndDelete() again but give it filter that does not match any documents coll.findOneAndDelete( filter: ["hello": "world10"], joiner.capture()) if let resErr = joiner.value(asType: Document.self) { XCTFail("Found Document Where It Shouldnt Be \(resErr)") return } // Put in more documents let docs: [Document] = [ ["hello": "world2", "num": 2] as Document, ["hello": "world3", "num": 3] as Document ] coll.insertMany(docs, joiner.capture()) _ = joiner.capturedValue // There should be three doc coll.count([:], joiner.capture()) XCTAssertEqual(3, joiner.value(asType: Int.self)) // Test project and sort coll.findOneAndDelete( filter: [:], options: RemoteFindOneAndModifyOptions( projection: ["hello": 1, "_id": 0], sort: ["num": -1]), joiner.capture()) guard let result3 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world3"], withoutId(result3)) coll.findOneAndDelete( filter: [:], options: RemoteFindOneAndModifyOptions( projection: ["hello": 1, "_id": 0], sort: ["num": 1]), joiner.capture()) guard let result4 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual(["hello": "world1"], withoutId(result4)) } class WatchTestDelegate<DocumentT: Codable>: ChangeStreamDelegate, CompactChangeStreamDelegate { public init() { self.previousAssertionCalled = true self.expectedEventType = .streamOpened } // swiftlint:disable nesting enum EventType { case eventReceived case errorReceived case streamOpened case streamClosed } // swiftlint:enable nesting private var expectedEventType: EventType private var previousAssertionCalled: Bool private var assertion: (() -> Void)? private var eventAssertion: ((_ event: ChangeEvent<DocumentT>) -> Void)? private var compactEventAssertion: ((_ event: CompactChangeEvent<DocumentT>) -> Void)? func expect(eventType: EventType, _ testAssertion: @escaping () -> Void) { guard previousAssertionCalled else { fatalError("the previous assertion for the expected event was not called") } self.previousAssertionCalled = false self.expectedEventType = eventType self.assertion = testAssertion self.eventAssertion = nil } func expectEvent(_ assertion: @escaping (_ event: ChangeEvent<DocumentT>) -> Void) { guard previousAssertionCalled else { fatalError("the previous assertion for the expected event was not called") } previousAssertionCalled = false self.expectedEventType = .eventReceived self.assertion = nil self.eventAssertion = assertion } func expectCompactEvent(_ assertion: @escaping (_ event: CompactChangeEvent<DocumentT>) -> Void) { guard previousAssertionCalled else { fatalError("the previous assertion for the expected event was not called") } previousAssertionCalled = false self.expectedEventType = .eventReceived self.assertion = nil self.compactEventAssertion = assertion } func didReceive(event: ChangeEvent<DocumentT>) { print("got public delegate receieve event") switch expectedEventType { case .eventReceived: guard assertion != nil || eventAssertion != nil else { fatalError("test not configured correctly, must have an assertion when expecting an event") } if let assertion = assertion { assertion() previousAssertionCalled = true } else if let eventAssertion = eventAssertion { eventAssertion(event) previousAssertionCalled = true } default: XCTFail("unexpected receive event, expected to get \(expectedEventType)") } } func didReceive(event: CompactChangeEvent<DocumentT>) { print("got public delegate receieve Compact event") switch expectedEventType { case .eventReceived: guard assertion != nil || compactEventAssertion != nil else { fatalError("test not configured correctly, must have an assertion when expecting an event") } if let assertion = assertion { assertion() previousAssertionCalled = true } else if let eventAssertion = compactEventAssertion { eventAssertion(event) previousAssertionCalled = true } default: XCTFail("unexpected receive event, expected to get \(expectedEventType)") } } func didReceive(streamError: Error) { print("got public delegate stream error") switch expectedEventType { case .errorReceived: guard let assertion = assertion else { fatalError("test not configured correctly, must have an assertion when expecting an error") } assertion() previousAssertionCalled = true default: XCTFail("unexpected error event, expected to get \(expectedEventType)") } } func didOpen() { print("got public delegate did open") switch expectedEventType { case .streamOpened: guard let assertion = assertion else { fatalError("test not configured correctly, must have an assertion when expecting stream to open") } assertion() previousAssertionCalled = true default: XCTFail("unexpected stream open event, expected to get \(expectedEventType)") } } func didClose() { print("got public delegate did close") switch expectedEventType { case .streamClosed: guard let assertion = assertion else { fatalError("test not configured correctly, must have an assertion when expecting stream to close") } assertion() previousAssertionCalled = true default: XCTFail("unexpected stream close event, expected to get \(expectedEventType)") } } } func testWatchFullCollection() throws { let coll = getTestColl() let testDelegate = WatchTestDelegate<Document>.init() var doc1: Document = [ "_id": ObjectId.init(), "hello": "world" ] var doc2: Document = [ "_id": ObjectId.init(), "hello": "universe" ] // set up CallbackJoiner to make synchronous calls to callback functions let joiner = CallbackJoiner() // should be notified on stream open var exp = expectation(description: "should be notified on stream open") testDelegate.expect(eventType: .streamOpened) { exp.fulfill() } let stream1 = try coll.watch(delegate: testDelegate) wait(for: [exp], timeout: 5.0) // should receive events for both documents exp = expectation(description: "should receive an event for doc1") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(doc1["_id"]) ?? false) XCTAssertTrue(doc1.bsonEquals(event.fullDocument)) XCTAssertEqual(event.operationType, OperationType.insert) exp.fulfill() } coll.insertOne(doc1, joiner.capture()) wait(for: [exp], timeout: 5.0) exp = expectation(description: "should receive an event for doc2") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(doc2["_id"]) ?? false) XCTAssertTrue(doc2.bsonEquals(event.fullDocument)) XCTAssertEqual(event.operationType, OperationType.insert) exp.fulfill() } coll.insertOne(doc2, joiner.capture()) wait(for: [exp], timeout: 5.0) // should receive more events let updateDoc: Document = [ "$set": ["goodbye": "test"] as Document ] exp = expectation(description: "should receive another event for doc1") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(doc1["_id"]) ?? false) XCTAssertTrue(doc1.bsonEquals(event.fullDocument)) XCTAssertEqual(event.operationType, OperationType.update) exp.fulfill() } doc1["goodbye"] = "test" coll.updateOne(filter: ["_id": doc1["_id"]!], update: updateDoc, joiner.capture()) wait(for: [exp], timeout: 5.0) exp = expectation(description: "should receive another event for doc2") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(doc2["_id"]) ?? false) XCTAssertTrue(doc2.bsonEquals(event.fullDocument)) XCTAssertEqual(event.operationType, OperationType.update) exp.fulfill() } doc2["goodbye"] = "test" coll.updateOne(filter: ["_id": doc2["_id"]!], update: updateDoc, joiner.capture()) wait(for: [exp], timeout: 5.0) // should be notified on stream close exp = expectation(description: "should be notified on stream close") testDelegate.expect(eventType: .streamClosed) { exp.fulfill() } stream1.close() wait(for: [exp], timeout: 5.0) // should receive no more events after stream close coll.updateOne( filter: ["_id": doc1["_id"]!], update: ["$set": ["you": "can't see me"] as Document ] as Document, joiner.capture() ) } func testWatchWithFilter() throws { let coll = getTestColl() let testDelegate = WatchTestDelegate<Document>.init() let doc1: Document = [ "_id": ObjectId.init(), "hello": "world" ] var doc2: Document = [ "_id": ObjectId.init(), "hello": "universe" ] // set up CallbackJoiner to make synchronous calls to callback functions let joiner = CallbackJoiner() // should be notified on stream open var exp = expectation(description: "should be notified on stream open") testDelegate.expect(eventType: .streamOpened) { exp.fulfill() } let stream1 = try coll.watch(matchFilter: ["fullDocument.hello": "universe"] as Document, delegate: testDelegate) wait(for: [exp], timeout: 5.0) // should receive an event for just one document exp = expectation(description: "should receive an event for one document") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(doc2["_id"]) ?? false) XCTAssertTrue(doc2.bsonEquals(event.fullDocument)) XCTAssertEqual(event.operationType, OperationType.insert) exp.fulfill() } coll.insertOne(doc1, joiner.capture()) // should be filtered coll.insertOne(doc2, joiner.capture()) wait(for: [exp], timeout: 5.0) // should receive more events for a single document let updateDoc: Document = [ "$set": ["goodbye": "test"] as Document ] exp = expectation(description: "should receive more events for a single document") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(doc2["_id"]) ?? false) XCTAssertTrue(doc2.bsonEquals(event.fullDocument)) XCTAssertEqual(event.operationType, OperationType.update) exp.fulfill() } coll.updateOne(filter: ["_id": doc1["_id"]!], update: updateDoc, joiner.capture()) // should be filtered doc2["goodbye"] = "test" coll.updateOne(filter: ["_id": doc2["_id"]!], update: updateDoc, joiner.capture()) wait(for: [exp], timeout: 5.0) // should be notified on stream close exp = expectation(description: "should be notified on stream close") testDelegate.expect(eventType: .streamClosed) { exp.fulfill() } stream1.close() wait(for: [exp], timeout: 5.0) // should receive no more events after stream close coll.updateOne( filter: ["_id": doc1["_id"]!], update: ["$set": ["you": "can't see me"] as Document ] as Document, joiner.capture() ) } func testWatchIds() throws { let coll = getTestColl() let testDelegate = WatchTestDelegate<Document>.init() let doc1: Document = [ "_id": ObjectId.init(), "hello": "universe" ] // set up CallbackJoiner to make synchronous calls to callback functions let joiner = CallbackJoiner() // should be notified on stream open var exp = expectation(description: "should be notified on stream open") testDelegate.expect(eventType: .streamOpened) { exp.fulfill() } let stream1 = try coll.watch(ids: [doc1["_id"]!], forStreamType: .fullDocument(withDelegate: testDelegate)) wait(for: [exp], timeout: 5.0) // should receive an event for one document exp = expectation(description: "should receive an event for one document") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(doc1["_id"]) ?? false) XCTAssertTrue(doc1.bsonEquals(event.fullDocument)) XCTAssertEqual(event.operationType, OperationType.insert) exp.fulfill() } coll.insertOne(doc1, joiner.capture()) wait(for: [exp], timeout: 5.0) // should receive more events for a single document let updateDoc: Document = [ "$set": ["hello": "universe"] as Document ] exp = expectation(description: "should receive more events for a single document") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(doc1["_id"]) ?? false) XCTAssertTrue(doc1.bsonEquals(event.fullDocument)) XCTAssertEqual(event.operationType, OperationType.update) exp.fulfill() } coll.updateOne(filter: ["_id": doc1["_id"]!], update: updateDoc, joiner.capture()) wait(for: [exp], timeout: 5.0) // should be notified on stream close exp = expectation(description: "should be notified on stream close") testDelegate.expect(eventType: .streamClosed) { exp.fulfill() } stream1.close() wait(for: [exp], timeout: 5.0) // should receive no more events after stream close coll.updateOne( filter: ["_id": doc1["_id"]!], update: ["$set": ["you": "can't see me"] as Document ] as Document, joiner.capture() ) // should receive events for multiple documents being watched let doc2: Document = [ "_id": 42, "hello": "i am a number doc" ] let doc3: Document = [ "_id": "blah", "hello": "i am a string doc" ] exp = expectation(description: "notify on stream open") testDelegate.expect(eventType: .streamOpened) { exp.fulfill() } let stream2 = try coll.watch(ids: [42, "blah"], forStreamType: .fullDocument(withDelegate: testDelegate)) wait(for: [exp], timeout: 5.0) exp = expectation(description: "doc2 inserted") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(42) ?? false) XCTAssertTrue(event.fullDocument?.bsonEquals(doc2) ?? false) XCTAssertEqual(event.operationType, OperationType.insert) exp.fulfill() } coll.insertOne(doc2, joiner.capture()) wait(for: [exp], timeout: 5.0) exp = expectation(description: "doc3 inserted") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals("blah") ?? false) XCTAssertTrue(event.fullDocument?.bsonEquals(doc3) ?? false) XCTAssertEqual(event.operationType, OperationType.insert) exp.fulfill() } coll.insertOne(doc3, joiner.capture()) wait(for: [exp], timeout: 5.0) exp = expectation(description: "should be notified on stream close") testDelegate.expect(eventType: .streamClosed) { exp.fulfill() } stream2.close() wait(for: [exp], timeout: 5.0) } func testWatchCompact() throws { let coll = getTestColl() let testDelegate = WatchTestDelegate<Document>.init() let doc1: Document = [ "_id": ObjectId.init(), "hello": "universe" ] // set up CallbackJoiner to make synchronous calls to callback functions let joiner = CallbackJoiner() // should be notified on stream open var exp = expectation(description: "should be notified on stream open") testDelegate.expect(eventType: .streamOpened) { exp.fulfill() } let stream1 = try coll.watch(ids: [doc1["_id"]!], forStreamType: .compactDocument(withDelegate: testDelegate)) wait(for: [exp], timeout: 5.0) // should receive an event for one document exp = expectation(description: "should receive an event for one document") testDelegate.expectCompactEvent { event in XCTAssertTrue(event.documentKey["_id"]!.bsonEquals(doc1["_id"])) XCTAssertTrue(doc1.bsonEquals(event.fullDocument)) XCTAssertEqual(event.operationType, OperationType.insert) XCTAssertNotNil(event.stitchDocumentHash) XCTAssertNil(event.stitchDocumentVersion) exp.fulfill() } coll.insertOne(doc1, joiner.capture()) wait(for: [exp], timeout: 5.0) // should receive more events for a single document let updateDoc: Document = [ "$set": ["hello": "universe"] as Document ] exp = expectation(description: "should receive more events for a single document") testDelegate.expectCompactEvent { event in XCTAssertTrue(event.documentKey["_id"]!.bsonEquals(doc1["_id"])) XCTAssertNil(event.fullDocument) XCTAssertEqual(event.operationType, OperationType.update) exp.fulfill() } coll.updateOne(filter: ["_id": doc1["_id"]!], update: updateDoc, joiner.capture()) wait(for: [exp], timeout: 5.0) // should be notified on stream close exp = expectation(description: "should be notified on stream close") testDelegate.expect(eventType: .streamClosed) { exp.fulfill() } stream1.close() wait(for: [exp], timeout: 5.0) // should receive no more events after stream close coll.updateOne( filter: ["_id": doc1["_id"]!], update: ["$set": ["you": "can't see me"] as Document ] as Document, joiner.capture() ) // should receive events for multiple documents being watched let doc2: Document = [ "_id": 42, "hello": "i am a number doc" ] let doc3: Document = [ "_id": "blah", "hello": "i am a string doc" ] exp = expectation(description: "notify on stream open") testDelegate.expect(eventType: .streamOpened) { exp.fulfill() } let stream2 = try coll.watch(ids: [42, "blah"], forStreamType: .compactDocument(withDelegate: testDelegate)) wait(for: [exp], timeout: 5.0) exp = expectation(description: "doc2 inserted") testDelegate.expectCompactEvent { event in XCTAssertTrue(event.documentKey["_id"]!.bsonEquals(42)) XCTAssertTrue(event.fullDocument!.bsonEquals(doc2)) XCTAssertEqual(event.operationType, OperationType.insert) XCTAssertNotNil(event.stitchDocumentHash) XCTAssertNil(event.stitchDocumentVersion) exp.fulfill() } coll.insertOne(doc2, joiner.capture()) wait(for: [exp], timeout: 5.0) exp = expectation(description: "doc3 inserted") testDelegate.expectCompactEvent { event in XCTAssertTrue(event.documentKey["_id"]!.bsonEquals("blah")) XCTAssertTrue(event.fullDocument!.bsonEquals(doc3)) XCTAssertEqual(event.operationType, OperationType.insert) XCTAssertNotNil(event.stitchDocumentHash) exp.fulfill() } coll.insertOne(doc3, joiner.capture()) wait(for: [exp], timeout: 5.0) exp = expectation(description: "should be notified on stream close") testDelegate.expect(eventType: .streamClosed) { exp.fulfill() } stream2.close() wait(for: [exp], timeout: 5.0) } func testWatchWithCustomDocType() throws { let coll = getTestColl().withCollectionType(CustomType.self) let doc1 = CustomType.init(id: "my_string_id", intValue: 42) let testDelegate = WatchTestDelegate<CustomType>.init() let joiner = CallbackJoiner.init() var exp = expectation(description: "notifies on stream open") testDelegate.expect(eventType: .streamOpened) { exp.fulfill() } let stream = try coll.watch(ids: ["my_string_id"], forStreamType: .fullDocument(withDelegate: testDelegate)) wait(for: [exp], timeout: 5.0) // If this code is uncommented, the test should not compile, since you shouldn't be able to use a // Document-based test delegate with a CustomType-based collection. // // let incorrectlyTypedTestDelegate = WatchTestDelegate<Document>.init() // try coll.watch(ids: ["my_string_id"], delegate: incorrectlyTypedTestDelegate) exp = expectation(description: "notifies on document insert") testDelegate.expectEvent { event in XCTAssertTrue(event.documentKey["_id"]?.bsonEquals(doc1.id) ?? false) XCTAssertEqual(event.fullDocument, doc1) XCTAssertEqual(event.operationType, OperationType.insert) exp.fulfill() } coll.insertOne(doc1, joiner.capture()) wait(for: [exp], timeout: 5.0) exp = expectation(description: "notifies on stream close") testDelegate.expect(eventType: .streamClosed) { exp.fulfill() } stream.close() wait(for: [exp], timeout: 5.0) } func testWithCollectionType() { let coll = getTestColl().withCollectionType(CustomType.self) XCTAssertTrue(type(of: coll).CollectionType.self == CustomType.self) let expected = CustomType.init(id: "my_string_id", intValue: 42) var exp = expectation(description: "type should be able to be inserted") coll.insertOne(expected) { result in switch result { case .success(let insertResult): XCTAssertEqual(expected.id, insertResult.insertedId as? String) case .failure(let err): XCTFail("unexpected error in insert: \(err.localizedDescription)") } exp.fulfill() } wait(for: [exp], timeout: 5.0) exp = expectation(description: "should be able to retrieve what was inserted") coll.find().first { result in switch result { case .success(let docResult): XCTAssertEqual(expected, docResult!) case .failure: XCTFail("unexpected error in find") } exp.fulfill() } wait(for: [exp], timeout: 5.0) } func testSync_Count() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) let doc1 = ["hello": "world", "a": "b"] as Document let doc2 = ["hello": "computer", "a": "b"] as Document sync.insertMany(documents: [doc1, doc2], joiner.capture()) sync.count(joiner.capture()) XCTAssertEqual(2, joiner.value()) sync.deleteMany(filter: ["a": "b"], joiner.capture()) sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) } func testSync_Find() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) let doc1 = ["hello": "world", "a": "b"] as Document let doc2 = ["hello": "computer", "a": "b"] as Document sync.insertMany(documents: [doc1, doc2], joiner.capture()) sync.count(joiner.capture()) XCTAssertEqual(2, joiner.value()) sync.find(filter: ["hello": "computer"], options: nil, joiner.capture()) guard let cursor = joiner.value(asType: MongoCursor<Document>.self), let actualDoc = cursor.next() else { XCTFail("documents not found") return } XCTAssertEqual("b", actualDoc["a"] as? String) XCTAssertNotNil(actualDoc["_id"]) XCTAssertEqual("computer", actualDoc["hello"] as? String) XCTAssertNil(cursor.next()) } func testSync_FindOne() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) let doc1 = ["hello": "world", "a": "b"] as Document sync.insertMany(documents: [doc1], joiner.capture()) sync.count(joiner.capture()) XCTAssertEqual(1, joiner.value()) sync.findOne(joiner.capture()) guard let doc = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual("world", doc["hello"] as? String) XCTAssertEqual("b", doc["a"] as? String) sync.findOne(filter: ["hello": "world"], options: nil, joiner.capture()) guard let doc2 = joiner.value(asType: Document.self) else { XCTFail("document not found") return } XCTAssertEqual("world", doc2["hello"] as? String) XCTAssertEqual("b", doc2["a"] as? String) sync.findOne(filter: ["hello": "worldsss"], options: nil, joiner.capture()) let doc3: Document? = joiner.value() XCTAssertNil(doc3) } func testSync_Aggregate() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) let doc1 = ["hello": "world", "a": "b"] as Document let doc2 = ["hello": "computer", "a": "b"] as Document sync.insertMany(documents: [doc1, doc2], joiner.capture()) sync.count(joiner.capture()) XCTAssertEqual(2, joiner.value()) sync.aggregate( pipeline: [ ["$project": ["_id": 0, "a": 0] as Document], ["$match": ["hello": "computer"] as Document] ], options: nil, joiner.capture()) guard let cursor = joiner.value(asType: MongoCursor<Document>.self), let actualDoc = cursor.next() else { XCTFail("docs not inserted") return } XCTAssertNil(actualDoc["a"]) XCTAssertNil(actualDoc["_id"]) XCTAssertEqual("computer", actualDoc["hello"] as? String) XCTAssertNil(cursor.next()) } func testSync_InsertOne() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) let doc1 = ["hello": "world", "a": "b", documentVersionField: "naughty"] as Document sync.insertOne(document: doc1, joiner.capture()) let insertOneResult = joiner.value(asType: SyncInsertOneResult.self) sync.count(joiner.capture()) XCTAssertEqual(1, joiner.value()) sync.find(filter: ["_id": insertOneResult?.insertedId ?? BSONNull()], options: nil, joiner.capture()) guard let cursor = joiner.value(asType: MongoCursor<Document>.self), let actualDoc = cursor.next() else { XCTFail("doc was not inserted") return } XCTAssertEqual("b", actualDoc["a"] as? String) XCTAssert((insertOneResult?.insertedId!.bsonEquals(actualDoc["_id"]))!) XCTAssertEqual("world", actualDoc["hello"] as? String) XCTAssertFalse(actualDoc.hasKey(documentVersionField)) XCTAssertNil(cursor.next()) } func testSync_InsertMany() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) let doc1 = ["hello": "world", "a": "b"] as Document let doc2 = ["hello": "computer", "a": "b"] as Document sync.insertMany(documents: [doc1, doc2], joiner.capture()) let insertManyResult = joiner.value(asType: SyncInsertManyResult.self) sync.count(joiner.capture()) XCTAssertEqual(2, joiner.value()) sync.find(filter: [ "_id": ["$in": insertManyResult?.insertedIds.values.compactMap { $0 } ?? BSONNull() ] as Document], joiner.capture()) guard let cursor = joiner.capturedValue as? MongoCursor<Document>, let actualDoc = cursor.next() else { XCTFail("doc was not inserted") return } XCTAssertEqual("b", actualDoc["a"] as? String) XCTAssert((insertManyResult?.insertedIds[0]!!.bsonEquals(actualDoc["_id"]))!) XCTAssertEqual("world", actualDoc["hello"] as? String) XCTAssertFalse(actualDoc.hasKey(documentVersionField)) XCTAssertNotNil(cursor.next()) } func testSync_UpdateOne() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) let doc1 = ["hello": "world", "a": "b", documentVersionField: "naughty"] as Document sync.updateOne(filter: doc1, update: doc1, options: SyncUpdateOptions(upsert: true), joiner.capture()) guard let insertedId = (joiner.capturedValue as? SyncUpdateResult)?.upsertedId else { XCTFail("doc not upserted") return } sync.updateOne(filter: ["_id": insertedId], update: ["$set": ["hello": "goodbye"] as Document], options: nil, joiner.capture()) guard let updateResult = joiner.capturedValue as? SyncUpdateResult else { XCTFail("failed to update doc") return } XCTAssertEqual(updateResult.matchedCount, 1) XCTAssertEqual(updateResult.modifiedCount, 1) XCTAssertNil(updateResult.upsertedId) sync.count(joiner.capture()) XCTAssertEqual(1, joiner.value()) sync.find(filter: ["_id": insertedId], options: nil, joiner.capture()) guard let cursor = joiner.value(asType: MongoCursor<Document>.self), let actualDoc = cursor.next() else { XCTFail("doc was not inserted") return } XCTAssertEqual("b", actualDoc["a"] as? String) XCTAssertEqual("goodbye", actualDoc["hello"] as? String) XCTAssertFalse(actualDoc.hasKey(documentVersionField)) XCTAssertNil(cursor.next()) } func testSync_UpdateMany() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) let doc1 = ["hello": "world", "a": "b", documentVersionField: "naughty"] as Document let doc2 = ["hello": "computer", "a": "b"] as Document sync.insertMany(documents: [doc1, doc2], joiner.capture()) guard let insertManyResult = (joiner.capturedValue as? SyncInsertManyResult) else { XCTFail("insert failed") return } let insertedIds = insertManyResult.insertedIds.compactMap({ $0.value }) sync.updateMany(filter: ["_id": ["$in": insertedIds] as Document], update: ["$set": ["hello": "goodbye"] as Document], options: nil, joiner.capture()) guard let updateResult = joiner.capturedValue as? SyncUpdateResult else { XCTFail("update failed") return } XCTAssertEqual(updateResult.matchedCount, 2) XCTAssertEqual(updateResult.modifiedCount, 2) XCTAssertNil(updateResult.upsertedId) sync.count(joiner.capture()) XCTAssertEqual(2, joiner.value()) sync.find(filter: ["_id": ["$in": insertedIds] as Document], options: nil, joiner.capture()) guard let cursor = joiner.value(asType: MongoCursor<Document>.self) else { XCTFail("could not find documents") return } cursor.forEach { actualDoc in XCTAssertEqual("b", actualDoc["a"] as? String) XCTAssertEqual("goodbye", actualDoc["hello"] as? String) XCTAssertFalse(actualDoc.hasKey(documentVersionField)) } } func testSync_deleteOne() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() // ensure that the test collection is empty sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) // insert some test documents let doc1 = ["hello": "world", "a": "b"] as Document let doc2 = ["goodbye": "world", "a": "b"] as Document sync.insertMany(documents: [doc1, doc2], joiner.capture()) // ensure that the documents were inserted sync.count(joiner.capture()) XCTAssertEqual(2, joiner.value()) // delete the { hello: "world" } document sync.deleteOne(filter: ["hello": "world"], joiner.capture()) var deleteResult = joiner.value(asType: SyncDeleteResult.self) XCTAssertEqual(1, deleteResult?.deletedCount) // ensure that there is only one document, and that it is the { goodbye: "world" } one sync.count(joiner.capture()) XCTAssertEqual(1, joiner.value()) sync.count(filter: ["hello": "world"], options: nil, joiner.capture()) XCTAssertEqual(0, joiner.value()) // delete the remaining document with empty filter sync.deleteOne(filter: [], joiner.capture()) deleteResult = joiner.value(asType: SyncDeleteResult.self) XCTAssertEqual(1, deleteResult?.deletedCount) // collection should be empty sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) // should not be able to delete any more documents sync.deleteOne(filter: [], joiner.capture()) deleteResult = joiner.value(asType: SyncDeleteResult.self) XCTAssertEqual(0, deleteResult?.deletedCount) } func testSync_deleteMany() throws { let coll = getTestColl() let sync = coll.sync sync.configure(conflictHandler: { _, _, rDoc in rDoc.fullDocument }, changeEventDelegate: { _, _ in }, errorListener: { _, _ in }, { _ in }) let joiner = CallbackJoiner() // ensure that the test collection is empty sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) // insert some test documents let doc1 = ["hello": "world", "a": "b"] as Document let doc2 = ["goodbye": "world", "a": "b"] as Document sync.insertMany(documents: [doc1, doc2], joiner.capture()) // ensure that the documents were inserted sync.count(joiner.capture()) XCTAssertEqual(2, joiner.value()) // delete documents with a filter for which there are no documents sync.deleteMany(filter: ["a": "c"], joiner.capture()) var deleteResult = joiner.value(asType: SyncDeleteResult.self) XCTAssertEqual(0, deleteResult?.deletedCount) // ensure nothing got deleted sync.count(joiner.capture()) XCTAssertEqual(2, joiner.value()) // delete all the documents we inserted sync.deleteMany(filter: ["a": "b"], joiner.capture()) deleteResult = joiner.value(asType: SyncDeleteResult.self) XCTAssertEqual(2, deleteResult?.deletedCount) // collection should be empty sync.count(joiner.capture()) XCTAssertEqual(0, joiner.value()) // should not be able to delete any more documents sync.deleteMany(filter: [], joiner.capture()) deleteResult = joiner.value(asType: SyncDeleteResult.self) XCTAssertEqual(0, deleteResult?.deletedCount) } } public struct CustomType: Codable { public let id: String public let intValue: Int public enum CodingKeys: String, CodingKey { case id = "_id", intValue } } extension CustomType: Equatable { public static func == (lhs: CustomType, rhs: CustomType) -> Bool { return lhs.id == rhs.id && lhs.intValue == rhs.intValue } }
37.739992
118
0.567901
f8775b87351fd74cbc162deb5d6e979dd34b6fbc
12,399
// // TimelineViewCellDelegate.swift // ochamochi // // import Foundation import UIKit import OAuthSwift protocol TimelineViewCellDelegate { func reply(_ tootId: String) func fav(_ tootId: String) func unfav(_ tootId: String) func reblog(_ tootId: String) func unreblog(_ tootId: String) func reloadRow(_ tootId: String) func confirmDelete(_ tootId: String) func accountDetail(_ accountId: String) func attachmentDetail(_ attachment: Attachment) } extension TimelineViewCellDelegate where Self: TimelineViewController { func reply(_ tootId: String) { if let controller = storyboard?.instantiateViewController(withIdentifier: "MakeTootView") { ((controller as! UINavigationController).viewControllers.first as! MakeTootViewController).inReplyToId = tootId present(controller, animated: true, completion: nil) } } func fav(_ tootId: String) { confirmFav(tootId) // favImpl(tootId) } func unfav(_ tootId: String) { confirmUnfav(tootId) // unfavImpl(tootId) } func reblog(_ tootId: String) { confirmReblog(tootId) // reblogImpl(tootId) } func unreblog(_ tootId: String) { confirmUnreblog(tootId) // unreblogImpl(tootId) } func confirmFav(_ tootId: String) { confirm(title: "Favorite", message: "Do you want to favorite toot?", defaultAction: { self.favImpl(tootId) }) } func confirmUnfav(_ tootId: String) { confirm(title: "Unfavorite", message: "Do you want to unfavorite toot?", defaultAction: { self.unfavImpl(tootId) }) } func confirmReblog(_ tootId: String) { confirm(title: "Boost", message: "Do you want to boost toot?", defaultAction: { self.reblogImpl(tootId) }) } func confirmUnreblog(_ tootId: String) { confirm(title: "Unboost", message: "Do you want to unboost toot?", defaultAction: { self.unreblogImpl(tootId) }) } func favImpl(_ tootId: String) { if let currentAccount = MastodonUtil.getCurrentAccount() { favCommon(tootId, url: favoriteUrl(currentAccount.url, tootId: tootId)) for (index, toot) in toots.enumerated() { if toot.id == tootId { toot.favourited = true DispatchQueue.main.async { self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.none) } } } } } func unfavImpl(_ tootId: String) { if let currentAccount = MastodonUtil.getCurrentAccount() { favCommon(tootId, url: unfavoriteUrl(currentAccount.url, tootId: tootId)) for (index, toot) in toots.enumerated() { if toot.id == tootId { toot.favourited = false DispatchQueue.main.async { self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.none) } } } } } func reblogImpl(_ tootId: String) { if let currentAccount = MastodonUtil.getCurrentAccount() { reblogCommon(tootId, url: reblogUrl(currentAccount.url, tootId: tootId)) for (index, toot) in toots.enumerated() { if toot.id == tootId { toot.reblogged = true DispatchQueue.main.async { self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.none) } } } } } func unreblogImpl(_ tootId: String) { if let currentAccount = MastodonUtil.getCurrentAccount() { reblogCommon(tootId, url: unreblogUrl(currentAccount.url, tootId: tootId)) for (index, toot) in toots.enumerated() { if toot.id == tootId { toot.reblogged = false DispatchQueue.main.async { self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.none) } } } } } func reloadRow(_ tootId: String) { } private func favCommon(_ tootId: String, url: String) { if let currentAccount = MastodonUtil.getCurrentAccount() { if let currentInstance = MastodonUtil.getCurrentInstance() { let oauthswift = OAuth2Swift(consumerKey: currentInstance.clientId, consumerSecret: currentInstance.clientSecret, authorizeUrl: "", responseType: "") oauthswift.client.credential.oauthToken = currentAccount.accessToken let _ = oauthswift.client.post(url) { result in switch result { case .success(let response): do { // set acct to Account and save let dataString = response.string let json = try JSONSerialization.jsonObject(with: dataString!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.allowFragments) let status = json as! [String:Any] } catch { print(error) } case .failure(let error): print(error) } } } } } private func reblogCommon(_ tootId: String, url: String) { if let currentAccount = MastodonUtil.getCurrentAccount() { if let currentInstance = MastodonUtil.getCurrentInstance() { let oauthswift = OAuth2Swift(consumerKey: currentInstance.clientId, consumerSecret: currentInstance.clientSecret, authorizeUrl: "", responseType: "") oauthswift.client.credential.oauthToken = currentAccount.accessToken let _ = oauthswift.client.post(url) { result in switch result { case .success(let response): do { // set acct to Account and save let dataString = response.string let json = try JSONSerialization.jsonObject(with: dataString!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.allowFragments) let status = json as! [String:Any] } catch { print(error) } case .failure(let error): print(error) } } } } } func accountDetail(_ accountId: String) { if let controller = storyboard?.instantiateViewController(withIdentifier: "AccountTimelineView") { (controller as! AccountTimelineViewController).accountId = accountId self.navigationController?.pushViewController(controller, animated: true) } } func attachmentDetail(_ attachment: Attachment) { if (attachment.type == "image") { if let _controller = storyboard?.instantiateViewController(withIdentifier: "AttachmentDetailView") { let controller = _controller as! AttachmentDetailViewController controller.modalPresentationStyle = .fullScreen controller.url = attachment.url self.present(controller, animated: true, completion: {}) } } else if (attachment.type == "gifv" || attachment.type == "video"){ if let _controller = storyboard?.instantiateViewController(withIdentifier: "AttachmentVideoView") { let controller = _controller as! AttachmentVideoViewController controller.url = attachment.url self.present(controller, animated: true, completion: {}) } } } func delete(_ tootId: String) { confirmDelete(tootId) // deleteImpl(tootId) } func confirmDelete(_ tootId: String) { let alert: UIAlertController = UIAlertController(title: "Delete toot", message: "Do you really want to delete toot?", preferredStyle: UIAlertControllerStyle.alert) let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{ (action: UIAlertAction!) -> Void in self.deleteImpl(tootId) }) let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler:{ (action: UIAlertAction!) -> Void in }) alert.addAction(cancelAction) alert.addAction(defaultAction) present(alert, animated: true, completion: nil) } func deleteImpl(_ tootId: String) { if let currentAccount = MastodonUtil.getCurrentAccount() { if let currentInstance = MastodonUtil.getCurrentInstance() { let oauthswift = OAuth2Swift(consumerKey: currentInstance.clientId, consumerSecret: currentInstance.clientSecret, authorizeUrl: "", responseType: "") oauthswift.client.credential.oauthToken = currentAccount.accessToken let _ = oauthswift.client.delete(self.deleteTootUrl(currentAccount.url, tootId: tootId)) { result in switch result { case .success(_): for (index, toot) in self.toots.enumerated() { if toot.id == tootId { self.toots.remove(at: index) break } } DispatchQueue.main.async { self.tableView.reloadData() } case .failure(let error): print(error) } } } } } private func confirm(title: String, message: String, defaultAction: @escaping (() -> Void)) { let alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{ (action: UIAlertAction!) -> Void in defaultAction() }) let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler:{ (action: UIAlertAction!) -> Void in }) alert.addAction(cancelAction) alert.addAction(defaultAction) present(alert, animated: true, completion: nil) } private func favoriteUrl(_ url : String, tootId : String) -> String { return "https://\(url)/api/v1/statuses/\(tootId)/favourite".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)! } private func unfavoriteUrl(_ url : String, tootId : String) -> String { return "https://\(url)/api/v1/statuses/\(tootId)/unfavourite".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)! } private func reblogUrl(_ url : String, tootId: String) -> String { return "https://\(url)/api/v1/statuses/\(tootId)/reblog".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)! } private func unreblogUrl(_ url : String, tootId: String) -> String { return "https://\(url)/api/v1/statuses/\(tootId)/unreblog".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)! } private func deleteTootUrl(_ url: String, tootId: String) -> String { return "https://\(url)/api/v1/statuses/\(tootId)".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)! } }
41.607383
183
0.569159
c18f23e9bb48497e3368e4ac9598b56561711e65
1,536
import UIKit import SoraFoundation final class NetworkAvailabilityLayerPresenter { var view: ApplicationStatusPresentable! var unavailbleStyle: ApplicationStatusStyle { return ApplicationStatusStyle(backgroundColor: R.color.colorPink()!, titleColor: UIColor.white, titleFont: UIFont.h6Title) } var availableStyle: ApplicationStatusStyle { return ApplicationStatusStyle(backgroundColor: R.color.colorGreen()!, titleColor: UIColor.white, titleFont: UIFont.h6Title) } } extension NetworkAvailabilityLayerPresenter: NetworkAvailabilityLayerInteractorOutputProtocol { func didDecideUnreachableStatusPresentation() { let languages = localizationManager?.preferredLocalizations view.presentStatus(title: R.string.localizable .networkStatusConnecting(preferredLanguages: languages), style: unavailbleStyle, animated: true) } func didDecideReachableStatusPresentation() { let languages = localizationManager?.preferredLocalizations view.dismissStatus(title: R.string.localizable .networkStatusConnected(preferredLanguages: languages), style: availableStyle, animated: true) } } extension NetworkAvailabilityLayerPresenter: Localizable { func applyLocalization() {} }
37.463415
95
0.642578
d6046e823d0ed51af3a31597975aa6e7f58b2cfc
730
// // MarkdownAutomaticLink.swift // Pods // // Created by Ivan Bruel on 19/07/16. // // import Foundation open class MarkdownAutomaticLink: MarkdownLink { override open func regularExpression() throws -> NSRegularExpression { return try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) } override open func match(_ match: NSTextCheckingResult, attributedString: NSMutableAttributedString) { let linkURLString = attributedString.attributedSubstring(from: match.range).string formatText(attributedString, range: match.range, link: linkURLString) addAttributes(attributedString, range: match.range, link: linkURLString) } }
31.73913
90
0.715068
f4bdc060a90635d6b776436a2114dc8bbc9e6107
2,990
// // UartSelectPeripheralViewController.swift // Bluefruit // // Created by Antonio on 08/02/2017. // Copyright © 2017 Adafruit. All rights reserved. // import UIKit protocol UartSelectPeripheralViewControllerDelegate: class { func onUartSendToChanged(uuid: UUID?, name: String) } class UartSelectPeripheralViewController: UIViewController { weak var delegate: UartSelectPeripheralViewControllerDelegate? var colorForPeripheral: [UUID: Color]? private var connectedPeripherals = [BlePeripheral]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - UITableViewDataSource extension UartSelectPeripheralViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { connectedPeripherals = BleManager.shared.connectedPeripherals() return connectedPeripherals.count + 1 // +1 All } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseIdentifier = "PeripheralCell" var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: reuseIdentifier) } return cell! } } // MARK: - UITableViewDelegate extension UartSelectPeripheralViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == 0 { cell.textLabel?.text = LocalizationManager.shared.localizedString("uart_send_toall_long") cell.textLabel?.textColor = UIColor.black } else { let peripheral = connectedPeripherals[indexPath.row-1] let localizationManager = LocalizationManager.shared cell.textLabel?.text = peripheral.name ?? localizationManager.localizedString("scanner_unnamed") cell.textLabel?.textColor = colorForPeripheral?[peripheral.identifier] ?? UIColor.black } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let localizationManager = LocalizationManager.shared if indexPath.row == 0 { delegate?.onUartSendToChanged(uuid: nil, name: localizationManager.localizedString("uart_send_toall_action")) } else { let peripheral = connectedPeripherals[indexPath.row-1] let name = peripheral.name ?? localizationManager.localizedString("scanner_unnamed") delegate?.onUartSendToChanged(uuid: peripheral.identifier, name: name) } tableView.deselectRow(at: indexPath, animated: true) dismiss(animated: true, completion: nil) } }
35.595238
121
0.707023
dd3ff1ed955b0a725d91a51865b129bcfe0cf6a5
5,182
// // ViewController.swift // neighborhood watch // // Created by Eli Berger on 5/20/17. // // import UIKit import MapKit import CoreLocation import Firebase class ViewController: UIViewController, CLLocationManagerDelegate{ @IBOutlet var mapView: MKMapView! let manager = CLLocationManager() internal var upvoteCount = false var ref: DatabaseReference! var refHandle: UInt! var timer: Timer! var refresher: UIRefreshControl! let categories = ["Blocked Roads", "Crowd", "Infrastructure", "Sanitation", "Suspicious Activity"] func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations[0] let span:MKCoordinateSpan = MKCoordinateSpanMake(0.005, 0.005) let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude) let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span) mapView.setRegion(region, animated:true) self.mapView.showsUserLocation = true } func checkPinStatus(inputTimestamp:TimeInterval, voteCount:Int) -> (Bool){ let date1:Date = Date() let date2:Date = Date(timeIntervalSince1970: inputTimestamp) let calender:Calendar = Calendar.current let components: DateComponents = calender.dateComponents([.minute, .day, .hour], from: date2, to: date1) if (voteCount > 0 && components.day! >= 1){ return false } else if (voteCount == 0 && components.hour! >= 6){ return false } else if (voteCount < 0 && voteCount > -5 && components.minute! >= 30){ return false } else if(voteCount < -5 && voteCount > -10){ return false } return true } func update() { // Get data from the firebase self.mapView.removeAnnotations(self.mapView.annotations) showPin() } func logoutButton(){ if (UserDefaults.standard.value(forKey: "isLoggedIn") as! Bool == true){ navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(self.handleLogout)) } } func showPin(){ logoutButton() ref = Database.database().reference() for items in categories { ref.child(items).observe(.childAdded, with: { (snapshot) in let enumerator = snapshot.children let pinID = snapshot.key var array: [Any] = [pinID] while let rest = enumerator.nextObject() as? DataSnapshot { array.append(rest.value!) } let pinIdInDatabase = array[0] let pinDescription = array[1] let pinLongitude = array[4] let pinLatitude = array[3] let pinTimeStamp = array[5] let pinVote = array[6] let newPin = Location(title: items, locationName: pinDescription as! String, discipline: items, coordinate: CLLocationCoordinate2D(latitude: pinLatitude as! CLLocationDegrees, longitude: pinLongitude as! CLLocationDegrees), pinKey: pinIdInDatabase as! String) if (self.checkPinStatus(inputTimestamp: pinTimeStamp as! TimeInterval, voteCount: pinVote as! Int )){ self.mapView.addAnnotation(newPin) } }, withCancel: nil) } } override func viewDidLoad() { super.viewDidLoad() self.showPin() ref = Database.database().reference() Timer.scheduledTimer(timeInterval: 8, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) mapView.delegate = self manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest manager.requestWhenInUseAuthorization() manager.startUpdatingLocation() } func handleLogout() { UserDefaults.standard.set(false, forKey: "isLoggedIn") let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print ("Error signing out: %@", signOutError) } self.navigationItem.setLeftBarButton(nil, animated: false) } @IBAction func addPinTapped(_ sender: UIButton) { moveToCreatePinVC() } private func moveToCreatePinVC() { if (UserDefaults.standard.value(forKey: "isLoggedIn") as! Bool == true) { let pinVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PinVC") as! CreatePinViewController self.navigationController?.pushViewController(pinVC, animated: true) } else { let loginVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginVC") as! SecondViewController loginVC.navigationController = self.navigationController self.present(loginVC, animated: true, completion: nil) } } }
37.824818
275
0.626785
f5e21eaca61a1dadfbbc5ba9174163f62b190c46
4,640
//___FILEHEADER___ import UIKit protocol ___VARIABLE_controllerName___TableControllerDelegate: AnyObject { } final class ___VARIABLE_controllerName___TableController: NSObject, TableController { weak var delegate: ___VARIABLE_controllerName___TableControllerDelegate? var updatesQueue: DispatchQueue = DispatchQueue(label: "\(NSStringFromClass(___VARIABLE_controllerName___TableController.self)).collection.updates", qos: .userInteractive, attributes: [], autoreleaseFrequency: .workItem, target: nil) var dataSource: [TableViewSectionVM] = [ // NOTE: - Insert some initial models values if needed ] var factory: TableCellsFactory = ___VARIABLE_controllerName___TableCellsFactory() var tableView: UITableView // MARK: - Life cycle init(tableView: UITableView) { self.tableView = tableView factory.registerAllCells(for: tableView) super.init() tableView.delegate = self tableView.dataSource = self if let factory = self.factory as? ___VARIABLE_controllerName___TableCellsFactory { factory.delegate = self } } // MARK: - Public functions func updateDataSource(with newItems: [TableCellModel], animated: Bool) { // NOTE: - Update your data source using internal queue to avoid NSInternalInconsistencyException. Change to diffable data source if needed updatesQueue.async { } } // NOTE: - Insert custom data source update methods here } // MARK: - UITableViewDataSource extension ___VARIABLE_controllerName___TableController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource[section].cells.count } func numberOfSections(in tableView: UITableView) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let model = dataSource[indexPath.section].cells[indexPath.row] return factory.generateCell(for: model, tableView: tableView, at: indexPath) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return false } } // MARK: - UITableViewDelegate extension ___VARIABLE_controllerName___TableController: UITableViewDelegate { func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { guard dataSource.indices.contains(indexPath.section) else { return CGFloat.leastNonzeroMagnitude } guard dataSource[indexPath.section].cells.indices.contains(indexPath.row) else { return CGFloat.leastNonzeroMagnitude } return dataSource[indexPath.section].cells[indexPath.row].rowHeight } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard dataSource.indices.contains(indexPath.section) else { return CGFloat.leastNonzeroMagnitude } guard dataSource[indexPath.section].cells.indices.contains(indexPath.row) else { return CGFloat.leastNonzeroMagnitude } return dataSource[indexPath.section].cells[indexPath.row].rowHeight } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return dataSource[section].header?.rowHeight ?? CGFloat.leastNonzeroMagnitude } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return dataSource[section].footer?.rowHeight ?? CGFloat.leastNonzeroMagnitude } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let model: TableHeaderFooterModel = dataSource[section].header else { return nil } return factory.generateHeader(for: model, tableView: tableView, at: section) } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let model: TableHeaderFooterModel = dataSource[section].footer else { return nil } return factory.generateFooter(for: model, tableView: tableView, at: section) } } // MARK: - Cell factory delegate extension ___VARIABLE_controllerName___TableController: ___VARIABLE_controllerName___TableCellsFactoryDelegate { }
34.887218
237
0.686422
b9e19875dcb0f4bca42e9259830af87fed35b18f
3,387
// // MNTMock.swift // Monet // // Created by Francisco Javier Chacon de Dios on 19/04/21. // Copyright © 2021 Monet. All rights reserved. // import Foundation public struct MNTMock: Equatable { public var body: MNTBodyMock public var error: Error? public var statusCode: Int public var urlConvertible: URLConvertible public var method: HTTPMethod public var headers: Headers public init(body: MNTBodyMock, error: Error?, statusCode: Int, urlConvertible: URLConvertible, method: HTTPMethod, headers: Headers = [:]) { self.body = body self.error = error self.statusCode = statusCode self.urlConvertible = urlConvertible self.method = method self.headers = headers } public init(body: MNTBodyMock, error: Error?, status: RequestStatus, urlConvertible: URLConvertible, method: HTTPMethod, headers: Headers = [:]) { self.body = body self.error = error self.statusCode = status.code self.urlConvertible = urlConvertible self.method = method self.headers = headers } public func httpResponse() throws -> HTTPURLResponse?{ return HTTPURLResponse(url: try urlConvertible.toUrl(), statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: headers) } public static func == (lhs: MNTMock, rhs: MNTMock) -> Bool { lhs.method == rhs.method && lhs.urlConvertible.toString() == rhs.urlConvertible.toString() } } extension MNTMock { public enum RequestStatus { case success case created case accepted case noContent case multipleChoice case movedPermanently case found case temporaryRedirect case permanentRedirect case badRequest case unauthorised case forbidden case notFound case requestTimedOut case unprocessableEntity case internalServerError case notImplemented case serviceTemporaryOverloaded case serviceUnavailable public var code: Int { switch self { case .success: return 200 case .created: return 201 case .accepted: return 202 case .noContent: return 204 case .multipleChoice: return 300 case .movedPermanently: return 301 case .found: return 302 case .temporaryRedirect: return 307 case .permanentRedirect: return 308 case .badRequest: return 400 case .unauthorised: return 401 case .forbidden: return 403 case .notFound: return 404 case .requestTimedOut: return 408 case .unprocessableEntity: return 422 case .internalServerError: return 500 case .notImplemented: return 501 case .serviceTemporaryOverloaded: return 502 case .serviceUnavailable: return 503 } } } }
29.198276
150
0.555359
0a245b691cf1a109c95172ba7542561d4ee5acb2
216
// // Place.swift // BrakhQ // // Created by Kiryl Holubeu on 4/8/19. // Copyright © 2019 brakhmen. All rights reserved. // import Foundation struct Place: Codable { var place: Int var user: User }
12.705882
51
0.634259
dd14caa3471b32b6a3d6590f449611be0c10f03b
1,952
import SwiftUI class ListViewModel: ObservableObject { // MARK: - Public @Published var title: String @Published var folders: [Folder] = [] @Published var places: [Placemark] = [] init(folder: Folder?, dataStore: ListDataStore, notificationCenter: NotificationCenter) { self.folder = folder ?? dataStore.fetchRootFolder() self.dataStore = dataStore self.notificationCenter = notificationCenter title = self.folder?.name ?? "" refreshListItems() notificationCenter.addObserver(self, selector: #selector(dataChanged), name: .dataChanged, object: nil) } /// Style URL to use for the given place. For certain placemarks we don't want to use the style URL. func styleURL(for place: Placemark) -> String? { guard case .point = place.type else { return nil } return place.styleUrl } /// System name of the image to use as a backup icon if we are not using the style icon for the given placemark. func defaultIconName(for place: Placemark) -> String { switch place.type { case .point: return "mappin" case .lineString: return "scribble" case .polygon: return "square.dashed" } } // MARK: - Actions @objc private func dataChanged() { folder = dataStore.fetchRootFolder() title = self.folder?.name ?? "" refreshListItems() } // MARK: - Private private var folder: Folder? private let dataStore: ListDataStore private let notificationCenter: NotificationCenter private func refreshListItems() { folders = folder?.subfoldersArray.sorted(by: { folder1, folder2 in (folder1.name ?? "") < (folder2.name ?? "") }) ?? [] places = folder?.placesArray.sorted(by: { place1, place2 in (place1.name ?? "") < (place2.name ?? "") }) ?? [] } }
30.984127
116
0.610143
0850a2474c3acd78082f84aa0026864c16cc1b90
1,285
// // FadeInImage.swift // Tweetmeister // // Created by Patwardhan, Saurabh on 10/27/16. // Copyright © 2016 Saurabh Patwardhan. All rights reserved. // import Foundation import UIKit import AFNetworking class StaticHelper{ static func fadeInImage(posterImageView : UIImageView, posterImageUrl : URL){ let imageUrlRequest = URLRequest(url: posterImageUrl) posterImageView.setImageWith(imageUrlRequest, placeholderImage: nil, success: { (request : URLRequest, response : HTTPURLResponse?, image : UIImage!) in if image != nil { posterImageView.alpha = 0 posterImageView.image = image UIView.animate(withDuration: 0.5 , animations: {() -> Void in posterImageView.alpha = 1 }) } }, failure: { (request : URLRequest,response : HTTPURLResponse?,error : Error) -> Void in //self.posterImageView.image = }) } }
36.714286
120
0.47393
e9e0335d2c1a6ff1b8936dfa567ce0e90949cfdb
5,743
// // MapToJSON.swift // SwiftyMapper // // Created by huajiahen on 2/20/16. // Copyright © 2016 huajiahen. All rights reserved. // public final class MapToJSON { fileprivate enum ContentType { case json(Any) case mapArray([MapToJSON]) case mapDictionary([String: MapToJSON]) case none } fileprivate var content: ContentType = .none public var JSON: Any? { get { switch content { case .json(let JSONContent): return JSONContent case .mapArray(let mapContent): return mapContent.map({ aMap -> Any in aMap.JSON ?? NSNull() }) case .mapDictionary(let mapContent): var JSONDict: [String: Any] = [:] for (key, value) in mapContent { JSONDict[key] = value.JSON ?? NSNull() } return JSONDict case .none: return nil } } set { if newValue == nil { content = .none } else if newValue is Int || newValue is Float || newValue is Double || newValue is Bool || newValue is String || newValue is [Any] || newValue is [String: Any] || newValue is NSNull { content = .json(newValue!) } } } public func JSONData() throws -> Data? { guard JSON != nil else { return nil } return try JSONSerialization.data(withJSONObject: JSON!, options: JSONSerialization.WritingOptions()) } public func JSONString(_ prettyPrinted: Bool = true) throws -> String? { guard JSON != nil else { return nil } let writingOptions: JSONSerialization.WritingOptions = prettyPrinted ? .prettyPrinted : JSONSerialization.WritingOptions() let JSONData = try JSONSerialization.data(withJSONObject: JSON!, options: writingOptions) return String(data: JSONData, encoding: String.Encoding.utf8) } //MARK: - Init public init() {} //MARK: - Subscript public subscript(key: String) -> MapToJSON { if case .none = content { content = .mapDictionary([:]) } guard case .mapDictionary(var mapTree) = content else { return MapToJSON() } let newMap = MapToJSON() mapTree[key] = newMap content = .mapDictionary(mapTree) return newMap } //MARK: - Map //MARK: Serializable public func map<T: Serializable>(_ object: T?) -> MapToJSON { if object == nil { JSON = nil } else { object!.mapToJSON(self) } return self } public func map<T: Serializable>(_ object: [T]?) -> MapToJSON { if let mapArray = object?.map({ MapToJSON().map($0) }) { content = .mapArray(mapArray) } else { content = .none } return self } public func map<T: Serializable>(_ object: [T?]?) -> MapToJSON { if let mapArray = object?.map({ MapToJSON().map($0) }) { content = .mapArray(mapArray) } else { content = .none } return self } public func map<T: Serializable>(_ object: [String: T]?) -> MapToJSON { if let mapDict = object?.mapValues({ MapToJSON().map($0) }) { content = .mapDictionary(mapDict) } else { content = .none } return self } public func map<T: Serializable>(_ object: [String: T?]?) -> MapToJSON { if let mapDict = object?.mapValues({ MapToJSON().map($0) }) { content = .mapDictionary(mapDict) } else { content = .none } return self } //MARK: Object public func map(_ mapper: ((MapToJSON) -> Void)?) -> MapToJSON { if mapper != nil { mapper!(self) } else { content = .none } return self } public func map<T>(_ object: T?, mapper: (T) -> (MapToJSON) -> Void) -> MapToJSON { if object != nil { mapper(object!)(self) } else { content = .none } return self } public func map<T>(_ object: [T]?, mapper: (T) -> (MapToJSON) -> Void) -> MapToJSON { if let mapArray = object?.map({ MapToJSON().map($0, mapper: mapper) }) { content = .mapArray(mapArray) } else { content = .none } return self } public func map<T>(_ object: [T?]?, mapper: (T) -> (MapToJSON) -> Void) -> MapToJSON { if let mapArray = object?.map({ MapToJSON().map($0, mapper: mapper) }) { content = .mapArray(mapArray) } else { content = .none } return self } public func map<T>(_ object: [String: T]?, mapper: @escaping (T) -> (MapToJSON) -> Void) -> MapToJSON { if let mapDict = object?.mapValues({ MapToJSON().map($0, mapper: mapper) }) { content = .mapDictionary(mapDict) } else { content = .none } return self } public func map<T>(_ object: [String: T?]?, mapper: @escaping (T) -> (MapToJSON) -> Void) -> MapToJSON { if let mapDict = object?.mapValues({ MapToJSON().map($0, mapper: mapper) }) { content = .mapDictionary(mapDict) } else { content = .none } return self } }
28.014634
196
0.496605
f75ece7afe3801b7dff4a4295d561d5829d1b240
1,351
// // RadioCell.swift // FoodAndFitness // // Created by Mylo Ho on 4/5/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit protocol RadioCellDelegate: NSObjectProtocol { func cell(_ cell: RadioCell, didSelectGender gender: Gender) } final class RadioCell: BaseTableViewCell { @IBOutlet fileprivate(set) weak var titleLabel: UILabel! @IBOutlet fileprivate(set) weak var maleButton: UIButton! @IBOutlet fileprivate(set) weak var femaleButton: UIButton! weak var delegate: RadioCellDelegate? enum Action { case male case female } struct Data { var title: String } var data: Data? { didSet { guard let data = data else { return } titleLabel.text = data.title } } private func changeButtonStatus() { maleButton.isSelected = !maleButton.isSelected femaleButton.isSelected = !femaleButton.isSelected } @IBAction fileprivate func maleClicked(_ sender: Any) { delegate?.cell(self, didSelectGender: .male) if maleButton.isSelected { return } changeButtonStatus() } @IBAction fileprivate func femaleClicked(_ sender: Any) { delegate?.cell(self, didSelectGender: .female) if femaleButton.isSelected { return } changeButtonStatus() } }
25.018519
64
0.65433
768da2c128f91c17407af1aff19cafaf5e3a5d53
17,433
//////////////////////////////////////////////////////////////////////////// // // 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 XCTest import RealmSwift class ListTests: TestCase { var str1: SwiftStringObject! var str2: SwiftStringObject! var arrayObject: SwiftArrayPropertyObject! var array: List<SwiftStringObject>! func createArray() -> SwiftArrayPropertyObject { fatalError("abstract") } func createArrayWithLinks() -> SwiftListOfSwiftObject { fatalError("abstract") } override func setUp() { super.setUp() str1 = SwiftStringObject() str1.stringCol = "1" str2 = SwiftStringObject() str2.stringCol = "2" arrayObject = createArray() array = arrayObject.array let realm = realmWithTestPath() realm.write { realm.add(self.str1) realm.add(self.str2) } realm.beginWrite() } override func tearDown() { realmWithTestPath().commitWrite() str1 = nil str2 = nil arrayObject = nil array = nil super.tearDown() } override class func defaultTestSuite() -> XCTestSuite! { // Don't run tests for the base class if isEqual(ListTests) { return nil } return super.defaultTestSuite() } func testDescription() { XCTAssertFalse(array.description.isEmpty) } func testInvalidated() { XCTAssertFalse(array.invalidated) if let realm = arrayObject.realm { realm.delete(arrayObject) XCTAssertTrue(array.invalidated) } } func testCount() { XCTAssertEqual(Int(0), array.count) array.append(str1) XCTAssertEqual(Int(1), array.count) array.append(str2) XCTAssertEqual(Int(2), array.count) } func testIndexOfObject() { XCTAssertNil(array.indexOf(str1)) XCTAssertNil(array.indexOf(str2)) array.append(str1) XCTAssertEqual(Int(0), array.indexOf(str1)!) XCTAssertNil(array.indexOf(str2)) array.append(str2) XCTAssertEqual(Int(0), array.indexOf(str1)!) XCTAssertEqual(Int(1), array.indexOf(str2)!) } func testIndexOfPredicate() { let pred1 = NSPredicate(format: "stringCol = '1'") let pred2 = NSPredicate(format: "stringCol = '2'") XCTAssertNil(array.indexOf(pred1)) XCTAssertNil(array.indexOf(pred2)) array.append(str1) XCTAssertEqual(Int(0), array.indexOf(pred1)!) XCTAssertNil(array.indexOf(pred2)) array.append(str2) XCTAssertEqual(Int(0), array.indexOf(pred1)!) XCTAssertEqual(Int(1), array.indexOf(pred2)!) } func testIndexOfFormat() { XCTAssertNil(array.indexOf("stringCol = %@", "1")) XCTAssertNil(array.indexOf("stringCol = %@", "2")) array.append(str1) XCTAssertEqual(Int(0), array.indexOf("stringCol = %@", "1")!) XCTAssertNil(array.indexOf("stringCol = %@", "2")) array.append(str2) XCTAssertEqual(Int(0), array.indexOf("stringCol = %@", "1")!) XCTAssertEqual(Int(1), array.indexOf("stringCol = %@", "2")!) } func testSubscript() { array.append(str1) XCTAssertEqual(str1, array[0]) array[0] = str2 XCTAssertEqual(str2, array[0]) assertThrows(self.array[-1] = self.str2) array.append(str1) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) assertThrows(self.array[200]) assertThrows(self.array[-200]) } func testFirst() { XCTAssertNil(array.first) array.append(str1) XCTAssertNotNil(array.first) XCTAssertEqual(str1, array.first!) array.append(str2) XCTAssertEqual(str1, array.first!) } func testLast() { XCTAssertNil(array.last) array.append(str1) XCTAssertNotNil(array.last) XCTAssertEqual(str1, array.last!) array.append(str2) XCTAssertEqual(str2, array.last!) } func testValueForKey() { let expected = map(array) { $0.stringCol } let actual = array.valueForKey("stringCol") as! [String]! XCTAssertEqual(expected, actual) XCTAssertEqual(map(array) { $0 }, array.valueForKey("self") as! [SwiftStringObject]) } func testSetValueForKey() { array.setValue("hi there!", forKey: "stringCol") let expected = map(array!) { _ in "hi there!" } let actual = map(array) { $0.stringCol } XCTAssertEqual(expected, actual) } func testFilterFormat() { XCTAssertEqual(Int(0), array.filter("stringCol = '1'").count) XCTAssertEqual(Int(0), array.filter("stringCol = '2'").count) array.append(str1) XCTAssertEqual(Int(1), array.filter("stringCol = '1'").count) XCTAssertEqual(Int(0), array.filter("stringCol = '2'").count) array.append(str2) XCTAssertEqual(Int(1), array.filter("stringCol = '1'").count) XCTAssertEqual(Int(1), array.filter("stringCol = '2'").count) } func testFilterList() { let innerArray = createArrayWithLinks() if let realm = innerArray.realm { realm.beginWrite() innerArray.array.append(SwiftObject()) let outerArray = SwiftDoubleListOfSwiftObject() realm.add(outerArray) outerArray.array.append(innerArray) realm.commitWrite() XCTAssertEqual(Int(1), outerArray.array.filter("ANY array IN %@", innerArray.array).count) } } func testFilterResults() { let arrayObject = createArrayWithLinks() if let realm = arrayObject.realm { realm.beginWrite() arrayObject.array.append(SwiftObject()) let subArray = arrayObject.array realm.commitWrite() XCTAssertEqual(Int(1), realm.objects(SwiftListOfSwiftObject).filter("ANY array IN %@", subArray).count) } } func testFilterPredicate() { let pred1 = NSPredicate(format: "stringCol = '1'") let pred2 = NSPredicate(format: "stringCol = '2'") XCTAssertEqual(Int(0), array.filter(pred1).count) XCTAssertEqual(Int(0), array.filter(pred2).count) array.append(str1) XCTAssertEqual(Int(1), array.filter(pred1).count) XCTAssertEqual(Int(0), array.filter(pred2).count) array.append(str2) XCTAssertEqual(Int(1), array.filter(pred1).count) XCTAssertEqual(Int(1), array.filter(pred2).count) } func testSortWithProperty() { array.extend([str1, str2]) var sorted = array.sorted("stringCol", ascending: true) XCTAssertEqual("1", sorted[0].stringCol) XCTAssertEqual("2", sorted[1].stringCol) sorted = array.sorted("stringCol", ascending: false) XCTAssertEqual("2", sorted[0].stringCol) XCTAssertEqual("1", sorted[1].stringCol) assertThrows(self.array.sorted("noSuchCol"), named: "Invalid sort property") } func testSortWithDescriptors() { let object = realmWithTestPath().create(SwiftAggregateObjectList.self, value: [[]]) let array = object.list let obj1 = SwiftAggregateObject() obj1.intCol = 1 obj1.floatCol = 1.1 obj1.doubleCol = 1.11 obj1.dateCol = NSDate(timeIntervalSince1970: 1) obj1.boolCol = false let obj2 = SwiftAggregateObject() obj2.intCol = 2 obj2.floatCol = 2.2 obj2.doubleCol = 2.22 obj2.dateCol = NSDate(timeIntervalSince1970: 2) obj2.boolCol = false let obj3 = SwiftAggregateObject() obj3.intCol = 3 obj3.floatCol = 2.2 obj3.doubleCol = 2.22 obj3.dateCol = NSDate(timeIntervalSince1970: 2) obj3.boolCol = false realmWithTestPath().add([obj1, obj2, obj3]) array.extend([obj1, obj2, obj3]) var sorted = array.sorted([SortDescriptor(property: "intCol", ascending: true)]) XCTAssertEqual(1, sorted[0].intCol) XCTAssertEqual(2, sorted[1].intCol) sorted = array.sorted([SortDescriptor(property: "doubleCol", ascending: false), SortDescriptor(property: "intCol", ascending: false)]) XCTAssertEqual(2.22, sorted[0].doubleCol) XCTAssertEqual(3, sorted[0].intCol) XCTAssertEqual(2.22, sorted[1].doubleCol) XCTAssertEqual(2, sorted[1].intCol) XCTAssertEqual(1.11, sorted[2].doubleCol) assertThrows(array.sorted([SortDescriptor(property: "noSuchCol", ascending: true)]), named: "Invalid sort property") } func testFastEnumeration() { array.extend([str1, str2, str1]) var str = "" for obj in array { str += obj.stringCol } XCTAssertEqual(str, "121") } func testAppendObject() { for str in [str1, str2, str1] { array.append(str) } XCTAssertEqual(Int(3), array.count) XCTAssertEqual(str1, array[0]) XCTAssertEqual(str2, array[1]) XCTAssertEqual(str1, array[2]) } func testAppendArray() { array.extend([str1, str2, str1]) XCTAssertEqual(Int(3), array.count) XCTAssertEqual(str1, array[0]) XCTAssertEqual(str2, array[1]) XCTAssertEqual(str1, array[2]) } func testAppendResults() { array.extend(realmWithTestPath().objects(SwiftStringObject)) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str1, array[0]) XCTAssertEqual(str2, array[1]) } func testInsert() { XCTAssertEqual(Int(0), array.count) array.insert(str1, atIndex: 0) XCTAssertEqual(Int(1), array.count) XCTAssertEqual(str1, array[0]) array.insert(str2, atIndex: 0) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) assertThrows(self.array.insert(self.str2, atIndex: 200)) assertThrows(self.array.insert(self.str2, atIndex: -200)) } func testRemoveAtIndex() { array.extend([str1, str2, str1]) array.removeAtIndex(1) XCTAssertEqual(str1, array[0]) XCTAssertEqual(str1, array[1]) assertThrows(self.array.removeAtIndex(200)) assertThrows(self.array.removeAtIndex(-200)) } func testRemoveLast() { array.extend([str1, str2]) array.removeLast() XCTAssertEqual(Int(1), array.count) XCTAssertEqual(str1, array[0]) array.removeLast() XCTAssertEqual(Int(0), array.count) array.removeLast() // should be a no-op XCTAssertEqual(Int(0), array.count) } func testRemoveAll() { array.extend([str1, str2]) array.removeAll() XCTAssertEqual(Int(0), array.count) array.removeAll() // should be a no-op XCTAssertEqual(Int(0), array.count) } func testReplace() { array.extend([str1, str1]) array.replace(0, object: str2) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) array.replace(1, object: str2) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str2, array[1]) assertThrows(self.array.replace(200, object: self.str2)) assertThrows(self.array.replace(-200, object: self.str2)) } func testSwap() { array.extend([str1, str2]) array.swap(0, 1) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) array.swap(1, 1) XCTAssertEqual(Int(2), array.count) XCTAssertEqual(str2, array[0]) XCTAssertEqual(str1, array[1]) assertThrows(self.array.swap(-1, 0)) assertThrows(self.array.swap(0, -1)) assertThrows(self.array.swap(1000, 0)) assertThrows(self.array.swap(0, 1000)) } func testChangesArePersisted() { if let realm = array.realm { array.extend([str1, str2]) let otherArray = realm.objects(SwiftArrayPropertyObject).first!.array XCTAssertEqual(Int(2), otherArray.count) } } func testPopulateEmptyArray() { XCTAssertEqual(array.count, 0, "Should start with no array elements.") let obj = SwiftStringObject() obj.stringCol = "a" array.append(obj) array.append(realmWithTestPath().create(SwiftStringObject.self, value: ["b"])) array.append(obj) XCTAssertEqual(array.count, 3) XCTAssertEqual(array[0].stringCol, "a") XCTAssertEqual(array[1].stringCol, "b") XCTAssertEqual(array[2].stringCol, "a") // Make sure we can enumerate for obj in array { XCTAssertTrue(count(obj.description) > 0, "Object should have description") } } func testEnumeratingListWithListProperties() { let arrayObject = createArrayWithLinks() arrayObject.realm?.beginWrite() for _ in 0..<10 { arrayObject.array.append(SwiftObject()) } arrayObject.realm?.commitWrite() XCTAssertEqual(10, arrayObject.array.count) for object in arrayObject.array { XCTAssertEqual(123, object.intCol) XCTAssertEqual(false, object.objectCol.boolCol) XCTAssertEqual(0, object.arrayCol.count) } } } class ListStandaloneTests: ListTests { override func createArray() -> SwiftArrayPropertyObject { let array = SwiftArrayPropertyObject() XCTAssertNil(array.realm) return array } override func createArrayWithLinks() -> SwiftListOfSwiftObject { let array = SwiftListOfSwiftObject() XCTAssertNil(array.realm) return array } // MARK: Things not implemented in standalone override func testSortWithProperty() { assertThrows(self.array.sorted("stringCol", ascending: true)) assertThrows(self.array.sorted("noSuchCol")) } override func testSortWithDescriptors() { assertThrows(self.array.sorted([SortDescriptor(property: "intCol", ascending: true)])) assertThrows(self.array.sorted([SortDescriptor(property: "noSuchCol", ascending: true)])) } override func testFilterFormat() { assertThrows(self.array.filter("stringCol = '1'")) assertThrows(self.array.filter("noSuchCol = '1'")) } override func testFilterPredicate() { let pred1 = NSPredicate(format: "stringCol = '1'") let pred2 = NSPredicate(format: "noSuchCol = '2'") assertThrows(self.array.filter(pred1)) assertThrows(self.array.filter(pred2)) } } class ListNewlyAddedTests: ListTests { override func createArray() -> SwiftArrayPropertyObject { let array = SwiftArrayPropertyObject() array.name = "name" let realm = realmWithTestPath() realm.write { realm.add(array) } XCTAssertNotNil(array.realm) return array } override func createArrayWithLinks() -> SwiftListOfSwiftObject { let array = SwiftListOfSwiftObject() let realm = Realm() realm.write { realm.add(array) } XCTAssertNotNil(array.realm) return array } } class ListNewlyCreatedTests: ListTests { override func createArray() -> SwiftArrayPropertyObject { let realm = realmWithTestPath() realm.beginWrite() let array = realm.create(SwiftArrayPropertyObject.self, value: ["name", [], []]) realm.commitWrite() XCTAssertNotNil(array.realm) return array } override func createArrayWithLinks() -> SwiftListOfSwiftObject { let realm = Realm() realm.beginWrite() let array = realm.create(SwiftListOfSwiftObject) realm.commitWrite() XCTAssertNotNil(array.realm) return array } } class ListRetrievedTests: ListTests { override func createArray() -> SwiftArrayPropertyObject { let realm = realmWithTestPath() realm.beginWrite() realm.create(SwiftArrayPropertyObject.self, value: ["name", [], []]) realm.commitWrite() let array = realm.objects(SwiftArrayPropertyObject).first! XCTAssertNotNil(array.realm) return array } override func createArrayWithLinks() -> SwiftListOfSwiftObject { let realm = Realm() realm.beginWrite() realm.create(SwiftListOfSwiftObject) realm.commitWrite() let array = realm.objects(SwiftListOfSwiftObject).first! XCTAssertNotNil(array.realm) return array } }
30.108808
142
0.614123
9b573a5822b219702e2862ea3720ad0d9454e30f
4,534
// // InfoRequestHandler.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 11/16/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import semver protocol InfoRequestHandlerDelegate: class { var viewControllerToPresentAlerts: UIViewController? { get } func urlNotValid() func serverIsValid() func serverChangedURL(_ newURL: String?) } final class InfoRequestHandler: NSObject { weak var delegate: InfoRequestHandlerDelegate? var url: URL? var version: Version? var validateServerVersion = true func validate(with url: URL, sslCertificatePath: URL?, sslCertificatePassword: String = "") { let api = API(host: url) if let sslCertificatePath = sslCertificatePath { api.sslCertificatePath = sslCertificatePath api.sslCertificatePassword = sslCertificatePassword } api.fetch(InfoRequest()) { [weak self] response in switch response { case .resource(let resource): self?.validateServerResponse(result: resource) case .error(let error): self?.alert(for: error) self?.delegate?.urlNotValid() } } } func alert(for error: APIError) { switch error { case .notSecured: Alert(key: "alert.connection.not_secured").present() case .error(let error): Alert(title: localized("global.error"), message: error.localizedDescription).present() default: alertInvalidURL() } } func alertInvalidURL() { Alert(key: "alert.connection.invalid_url").present() } internal func validateServerResponse(result: InfoResource?) { guard let version = result?.version else { alertInvalidURL() delegate?.urlNotValid() return } self.version = version.version() if validateServerVersion { if let minVersion = Bundle.main.object(forInfoDictionaryKey: "RC_MIN_SERVER_VERSION") as? String { validateServerVersion(minVersion: minVersion, version: version) } } delegate?.serverIsValid() } internal func validateServerVersion(minVersion: String, version: String) { if Semver.lt(version, minVersion) { Alert( title: localized("alert.connection.invalid_version.title"), message: String(format: localized("alert.connection.invalid_version.message"), version, minVersion) ).present() } } } extension InfoRequestHandler: URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { task.suspend() if let location = response.allHeaderFields["Location"] as? String { if let newURL = URL(string: location, scheme: "https") { handleRedirect(newURL) } } completionHandler(nil) } func handleRedirect(_ newURL: URL) { API(host: newURL).fetch(InfoRequest()) { [weak self] response in switch response { case .resource(let resource): self?.handleRedirectInfoResult(resource, for: newURL) case .error: self?.delegate?.urlNotValid() } } } func handleRedirectInfoResult(_ result: InfoResource, for url: URL) { guard result.raw != nil, let controller = self.delegate?.viewControllerToPresentAlerts, let newHost = url.host else { self.delegate?.urlNotValid() return } let alert = UIAlertController( title: localized("connection.server.redirect.alert.title"), message: String(format: localized("connection.server.redirect.alert.message"), newHost), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: localized("global.cancel"), style: .cancel, handler: { _ in self.delegate?.serverChangedURL(nil) })) alert.addAction(UIAlertAction(title: localized("connection.server.redirect.alert.confirm"), style: .default, handler: { _ in self.delegate?.serverChangedURL(newHost) })) DispatchQueue.main.async { controller.present(alert, animated: true, completion: nil) } } }
31.929577
204
0.622629
01c8f4c3fec921a42be882ba6a55900083ebd451
1,474
// // DefaultPeerManager.swift // Clink // // Created by Nick Sweet on 7/13/17. // import Foundation public class DefaultPeerManager: ClinkPeerManager { public func createPeer(withId peerId: String) { let peer = Clink.DefaultPeer(id: peerId) UserDefaults.standard.set(peer.toDict(), forKey: peer.id) var savedPeerIds = UserDefaults.standard.stringArray(forKey: savedPeerIdsDefaultsKey) ?? [] if savedPeerIds.index(of: peer.id) == nil { savedPeerIds.append(peer.id) UserDefaults.standard.set(savedPeerIds, forKey: savedPeerIdsDefaultsKey) } } public func update(value: Any, forKey key: String, ofPeerWithId peerId: String) { guard let peer: Clink.DefaultPeer = self.getPeer(withId: peerId) else { return } peer[key] = value UserDefaults.standard.set(peer.toDict(), forKey: peer.id) } public func getPeer<T: ClinkPeer>(withId peerId: String) -> T? { guard let peerDict = UserDefaults.standard.dictionary(forKey: peerId) else { return nil } return Clink.DefaultPeer(dict: peerDict) as? T } public func getKnownPeerIds() -> [Clink.PeerId] { return UserDefaults.standard.stringArray(forKey: savedPeerIdsDefaultsKey) ?? [] } public func delete(peerWithId peerId: String) { UserDefaults.standard.removeObject(forKey: peerId) } }
31.361702
99
0.63772
bfda794bd8b3443e9129bb4385e75a1cedc03477
1,303
import Vapor import Tau public func configure(_ app: Application) throws { app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory)) /// setup Leaf template engine Renderer.Option.caching = .bypass let detected = TemplateEngine.rootDirectory ?? app.directory.viewsDirectory TemplateEngine.rootDirectory = detected TemplateEngine.sources = .singleSource(FileSource(fileio: app.fileio, limits: .default, sandboxDirectory: detected, viewDirectory: detected, defaultExtension: "html")) app.views.use(.tau) if let hostname = Environment.get("SERVER_HOSTNAME") { app.http.server.configuration.hostname = hostname } app.get() { req in req.tau.render(template: "pages/home") } app.get(.anything) { req -> EventLoopFuture<View> in guard !req.url.path.contains("."), let slug = req.url.path.split(separator: "/").first else { return req.eventLoop.future(error: Abort(.notFound)) } return req.tau.render(template: "pages/" + String(slug).lowercased()) } }
35.216216
101
0.574827
79c91c669e5423d49540e3bdb0c1977665a15102
753
// // MySingletonAnalytics.swift // HardDependencies // // Created by Ben Chatelain on 4/11/20. // Copyright © 2020 Ben Chatelain. All rights reserved. // class MySingletonAnalytics { private static let instance = MySingletonAnalytics() #if DEBUG static var stubbedInstance: MySingletonAnalytics? #endif static var shared: MySingletonAnalytics { #if DEBUG if let stubbedInstance = stubbedInstance { return stubbedInstance } #endif return instance } func track(event: String) { Analytics.shared.track(event: event) if self !== MySingletonAnalytics.instance { print(">> Not the MySingletonAnalytics singleton") } } }
22.147059
62
0.633466
d728481b90133d439d9126dff861b791153fd906
1,836
// Copyright 2018, Oath Inc. // Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms. import XCTest @testable import PlayerCore class AdFinishTrackerComponentTestCase: XCTestCase { func testOnAdRequest() { let url = URL(string: "http://test.com")! let initial = AdFinishTracker.successfullyCompleted var sut = reduce(state: initial, action: VRMCore.AdRequest(url: url, id: UUID(), type: .preroll)) XCTAssertEqual(sut, .unknown) sut = reduce(state: initial, action: VRMCore.AdRequest(url: url, id: UUID(), type: .preroll)) XCTAssertEqual(sut, .unknown) } func testReduceOnShowAd() { let initial = AdFinishTracker.unknown var sut = reduce(state: initial, action: ShowMP4Ad(creative: AdCreative.mp4(with: testUrl), id: UUID())) XCTAssertEqual(sut, .unknown) sut = reduce(state: initial, action: ShowVPAIDAd(creative: AdCreative.vpaid(with: testUrl), id: UUID())) XCTAssertEqual(sut, .unknown) } func testReducerOnMaxShowTime() { let initial = AdFinishTracker.unknown let sut = reduce(state: initial, action: AdMaxShowTimeout()) XCTAssertEqual(sut, .forceFinished) } func testReduceOnShowContent() { let initial = AdFinishTracker.unknown let sut = reduce(state: initial, action: ShowContent()) XCTAssertEqual(sut, .successfullyCompleted) } func testReduceOnSkipAd() { let initial = AdFinishTracker.unknown let sut = reduce(state: initial, action: SkipAd()) XCTAssertEqual(sut, .skipped) } }
34
96
0.596405
fe74eed68be1c516c036a219c677f4d4c9bd7f0a
2,285
// // YBInfinityLocalManager.swift // YouboraLib iOS // // Created by Tiago Pereira on 04/05/2020. // Copyright © 2020 NPAW. All rights reserved. // import Foundation @objcMembers public class YBInfinityLocalManager: NSObject { /** * Saves new session id on <NSUserDefaults> * @param sessionId sessionId to save */ public static func saveSession(sessionId: String) { UserDefaults.standard.set(sessionId, forKey: YBConstants.preferencesSessionIdKey) } /** * Gets saved session id on <NSUserDefaults> * @return session id to save */ public static func getSessionId() -> String? { return UserDefaults.standard.value(forKey: YBConstants.preferencesSessionIdKey) as? String } /** * Saves new context on <NSUserDefaults> * @param context to save */ public static func saveContext(context: String) { UserDefaults.standard.set(context, forKey: YBConstants.preferencesContextKey) } /** * Gets saved context on <NSUserDefaults> * @return context to save */ public static func getContext() -> String? { return UserDefaults.standard.value(forKey: YBConstants.preferencesContextKey) as? String } /** * Saves timestamp of last event sent on <NSUserDefaults> */ public static func saveLastActiveDate() { UserDefaults.standard.set(NSNumber(value: YBChrono().now), forKey: YBConstants.preferencesLastActiveKey) } /** * Gets saved timestamp on <NSUserDefaults> * @return context to save */ public static func getLastActive() -> NSNumber? { return UserDefaults.standard.value(forKey: YBConstants.preferencesLastActiveKey) as? NSNumber } /** * Method that will clean all data in the user defaults realtive with * infinity local manager */ public static func cleanLocalManager() { DispatchQueue.main.async { UserDefaults.standard.removeObject(forKey: YBConstants.preferencesSessionIdKey) UserDefaults.standard.removeObject(forKey: YBConstants.preferencesContextKey) UserDefaults.standard.removeObject(forKey: YBConstants.preferencesLastActiveKey) UserDefaults.standard.synchronize() } } }
31.30137
112
0.677899
fefbe0a744a81ee6306e45b590f2b1368c1e6b00
22,564
// // Client.swift // Contentful // // Created by Boris Bügling on 18/08/15. // Copyright © 2015 Contentful GmbH. All rights reserved. // import Foundation /// The completion callback for an API request with a `Result<T>` containing the requested object of /// type `T` on success, or an error if the request was unsuccessful. public typealias ResultsHandler<T> = (_ result: Result<T, Error>) -> Void /// Client object for performing requests against the Contentful Delivery and Preview APIs. open class Client { /// The configuration for this instance of the client. public let clientConfiguration: ClientConfiguration /// The identifier of the space this Client is set to interface with. public let spaceId: String /// The identifier of the environment within the space that this Client is set to interface with. public let environmentId: String /// Available Locales for this environment public var locales: [Contentful.Locale]? public var isFetchingLocales: Bool = false public var localesCompletionHandlers: [ResultsHandler<Array<Contentful.Locale>>] = [] /// Context for holding information about the fallback chain of locales for the Space. public private(set) var localizationContext: LocalizationContext! { set { jsonDecoderBuilder.localizationContext = newValue } get { jsonDecoderBuilder.localizationContext } } /// The base domain that all URIs have for each request the client makes. public let host: String /** Builder for `JSONDecoder` instance that is used to deserialize JSONs. `Client` will inject information about the locales to the builder and use this information to normalize the fields dictionary of entries and assets. */ private let jsonDecoderBuilder = JSONDecoderBuilder() // Always returns new instance of the decoder. For legacy code support. public var jsonDecoder: JSONDecoder { jsonDecoderBuilder.build() } /// The persistence integration which will receive delegate messages from the `Client` when new /// `Entry` and `Asset` objects are created from data being sent over the network. Currently, these /// messages are only sent during the response hadling for `client.sync` calls. See a CoreData /// persistence integration at <https://github.com/contentful/contentful-persistence.swift>. public var persistenceIntegration: PersistenceIntegration? { didSet { guard var headers = self.urlSession.configuration.httpAdditionalHeaders else { assertionFailure("Headers should have already been set on the current URL Session.") return } assert(headers["Authorization"] != nil) headers["X-Contentful-User-Agent"] = clientConfiguration.userAgentString(with: persistenceIntegration) // There is a bug in foundation with directly setting the headers like so self.urlSession.configuration.header = ... // so we must recreate the URLSession in order to set the headers. let configuration = self.urlSession.configuration configuration.httpAdditionalHeaders = headers self.urlSession = URLSession(configuration: configuration) } } internal var urlSession: URLSession fileprivate(set) internal var space: Space? fileprivate var scheme: String { return clientConfiguration.secure ? "https": "http" } /// Initializes a new Contentful client instance /// /// - Parameters: /// - spaceId: The identifier of the space to perform requests against. /// - environmentId: The identifier of the space environment to perform requests against. Defaults to "master". /// - accessToken: The access token used for authorization. /// - host: The domain host to perform requests against. Defaults to `Host.delivery` i.e. `"cdn.contentful.com"`. /// - clientConfiguration: Custom Configuration of the Client. Uses `ClientConfiguration.default` if omitted. /// - sessionConfiguration: The configuration for the URLSession. Note that HTTP headers will be overwritten /// internally by the SDK so that requests can be authorized correctly. /// - persistenceIntegration: An object conforming to the `PersistenceIntegration` protocol /// which will receive messages about created/deleted Resources when calling `sync` methods. /// - contentTypeClasses: An array of `EntryDecodable` classes to map Contentful entries to when using the relevant fetch methods. public init(spaceId: String, environmentId: String = "master", accessToken: String, host: String = Host.delivery, clientConfiguration: ClientConfiguration = .default, sessionConfiguration: URLSessionConfiguration = .default, persistenceIntegration: PersistenceIntegration? = nil, contentTypeClasses: [EntryDecodable.Type]? = nil) { self.spaceId = spaceId self.environmentId = environmentId self.host = host self.clientConfiguration = clientConfiguration if let dateDecodingStrategy = clientConfiguration.dateDecodingStrategy { // Override default date decoding strategy if present jsonDecoderBuilder.dateDecodingStrategy = dateDecodingStrategy } if let timeZone = clientConfiguration.timeZone { jsonDecoderBuilder.timeZone = timeZone } if let contentTypeClasses = contentTypeClasses { var contentTypes = [ContentTypeId: EntryDecodable.Type]() for type in contentTypeClasses { contentTypes[type.contentTypeId] = type } jsonDecoderBuilder.contentTypes = contentTypes } self.persistenceIntegration = persistenceIntegration let contentfulHTTPHeaders = [ "Authorization": "Bearer \(accessToken)", "X-Contentful-User-Agent": clientConfiguration.userAgentString(with: persistenceIntegration) ] sessionConfiguration.httpAdditionalHeaders = contentfulHTTPHeaders self.urlSession = URLSession(configuration: sessionConfiguration) } deinit { urlSession.invalidateAndCancel() } /// Returns an optional URL for the specified endpoint with its query paramaters. /// /// - Parameters: /// - endpoint: The delivery/preview API endpoint. /// - parameters: A dictionary of query parameters which be appended at the end of the URL in a URL safe format. /// - Returns: A valid URL for the Content Delivery or Preview API, or nil if the URL could not be constructed. public func url(endpoint: Endpoint, parameters: [String: String]? = nil) -> URL { var components: URLComponents switch endpoint { case .spaces: components = URLComponents(string: "\(scheme)://\(host)/spaces/\(spaceId)/\(endpoint.pathComponent)")! case .assets, .contentTypes, .locales, .entries, .sync: components = URLComponents(string: "\(scheme)://\(host)/spaces/\(spaceId)/environments/\(environmentId)/\(endpoint.pathComponent)")! } let queryItems: [URLQueryItem]? = parameters?.map { key, value in return URLQueryItem(name: key, value: value) } // Since Swift 4.2, the order of a dictionary's keys will vary accross executions so we must sort // the parameters so that the URL is consistent accross executions (so that all test recordings are found). components.queryItems = queryItems?.sorted { a, b in return a.name > b.name } let url = components.url! return url } internal func fetchDecodable<DecodableType: Decodable>( url: URL, completion: @escaping ResultsHandler<DecodableType> ) -> URLSessionDataTask { let finishDataFetch: (ResultsHandler<Data>) = { result in switch result { case .success(let mappableData): self.handleJSON(data: mappableData, completion: completion) case .failure(let error): completion(.failure(error)) } } let task = fetchData(url: url) { dataResult in if url.lastPathComponent == "locales" || url.lastPathComponent == self.spaceId { // Now that we have all the locale information, start callback chain. finishDataFetch(dataResult) } else { self.fetchLocalesIfNecessary { localesResult in switch localesResult { case .success: // Trigger chain with data we're currently interested in. finishDataFetch(dataResult) case .failure(let error): // Return the current error. finishDataFetch(.failure(error)) } } } } return task } internal func fetchData(url: URL, completion: @escaping ResultsHandler<Data>) -> URLSessionDataTask { let jsonDecoder = jsonDecoderBuilder.build() let task = urlSession.dataTask(with: url) { data, response, error in if let data = data { if self.didHandleRateLimitError( data: data, response: response, jsonDecoder: jsonDecoder, completion: completion ) == true { return // Exit if there was a RateLimitError. } // Use failable initializer to optional rather than initializer that throws, // because failure to find an error in the JSON should error should not throw an error that JSON is not parseable. if let response = response as? HTTPURLResponse { if response.statusCode != 200 { if let apiError = APIError.error(with: jsonDecoder, data: data, statusCode: response.statusCode) { let errorMessage = """ Errored: 'GET' (\(response.statusCode)) \(url.absoluteString) Message: \(apiError.message!)" """ ContentfulLogger.log(.error, message: errorMessage) completion(.failure(apiError)) } else { // In case there is an error returned by the API that has an unexpected format, return a custom error. let errorMessage = "An API error was returned that the SDK was unable to parse" let logMessage = """ Errored: 'GET' \(url.absoluteString). \(errorMessage) Message: \(errorMessage) """ ContentfulLogger.log(.error, message: logMessage) let error = SDKError.unparseableJSON(data: data, errorMessage: errorMessage) completion(.failure(error)) } return } let successMessage = "Success: 'GET' (\(response.statusCode)) \(url.absoluteString)" ContentfulLogger.log(.info, message: successMessage) } completion(Result.success(data)) return } if let error = error { // An extra check, just in case. let errorMessage = """ Errored: 'GET' \(url.absoluteString) Message: \(error.localizedDescription) """ ContentfulLogger.log(.error, message: errorMessage) completion(.failure(error)) return } let sdkError = SDKError.invalidHTTPResponse(response: response) let errorMessage = """ Errored: 'GET' \(url.absoluteString) Message: Request returned invalid HTTP response: \(sdkError.localizedDescription)" """ ContentfulLogger.log(.error, message: errorMessage) completion(.failure(sdkError)) } let logMessage = "Request: 'GET' \(url.absoluteString)" ContentfulLogger.log(.info, message: logMessage) task.resume() return task } internal func fetchResource<ResourceType>( resourceType: ResourceType.Type, id: String, include includesLevel: UInt? = nil, completion: @escaping ResultsHandler<ResourceType> ) -> URLSessionDataTask where ResourceType: Decodable & EndpointAccessible { // If the resource is not an entry, includes are not supported. if !(resourceType is EntryDecodable.Type) && resourceType != Entry.self { var url = self.url(endpoint: ResourceType.endpoint) url.appendPathComponent(id) return fetchDecodable( url: url, completion: completion ) } // Before `completion` is called, either the first item is extracted, and // sent as `.success`, or an `.error` is sent. let fetchCompletion: (Result<HomogeneousArrayResponse<ResourceType>, Error>) -> Void = { result in switch result { case .success(let response): guard let firstItem = response.items.first else { completion(.failure(SDKError.noResourceFoundFor(id: id))) break } completion(.success(firstItem)) case .failure(let error): completion(.failure(error)) } } var query = ResourceQuery.where(sys: .id, .equals(id)) if let includesLevel = includesLevel { query = query.include(includesLevel) } return fetchDecodable( url: url(endpoint: ResourceType.endpoint, parameters: query.parameters), completion: fetchCompletion ) } /// Fetches the space this client is configured to interface with. /** Fetches the `Space` the client is configured to interface with. If there is a space in the cache, it will be returned and no request will be performed. Otherwise, the space will be fetched and stored. */ @discardableResult internal func fetchCurrentSpace(then completion: @escaping ResultsHandler<Space>) -> URLSessionDataTask? { // Attempt to pull from cache first. if let space = self.space { completion(.success(space)) return nil } return fetchDecodable(url: url(endpoint: .spaces)) { (result: Result<Space, Error>) in switch result { case .success(let space): self.space = space default: break } completion(result) } } /// Fetches all the locales belonging to the space environment that this client is configured to interface with. /// /// - Parameters: /// - completion: A handler being called on completion of the request. /// - Returns: Returns the `URLSessionDataTask` of the request which can be used for request cancellation. @discardableResult internal func fetchCurrentSpaceLocales(then completion: @escaping ResultsHandler<HomogeneousArrayResponse<Contentful.Locale>>) -> URLSessionDataTask { // The robust thing to do would be to fetch all pages of the `/locales` endpoint, however, pagination is not supported // at the moment. We also are not expecting any consumers to have > 1000 locales as Contentful subscriptions do not allow that. let query = ResourceQuery.limit(to: QueryConstants.maxLimit) let url = self.url(endpoint: .locales, parameters: query.parameters) return fetchDecodable(url: url) { (result: Result<HomogeneousArrayResponse<Contentful.Locale>, Error>) in switch result { case .success(let localesArray): let locales = localesArray.items self.locales = locales let localeCodes = locales.map { $0.code } self.persistenceIntegration?.update(localeCodes: localeCodes) self.isFetchingLocales = false guard let localizationContext = LocalizationContext(locales: locales) else { let error = SDKError.localeHandlingError(message: "Locale with default == true not found in Environment!") completion(.failure(error)) return } self.localizationContext = localizationContext completion(result) case .failure(let error): completion(.failure(error)) } } } @discardableResult private func fetchLocalesIfNecessary(then completion: @escaping ResultsHandler<Array<Contentful.Locale>>) -> URLSessionDataTask? { if let locales = self.locales { let localeCodes = locales.map { $0.code } persistenceIntegration?.update(localeCodes: localeCodes) completion(Result.success(locales)) return nil } guard !isFetchingLocales else { localesCompletionHandlers.append(completion) return nil } isFetchingLocales = true return fetchCurrentSpaceLocales { [weak self] result in switch result { case .success(let localesResponse): self?.localesCompletionHandlers.forEach({ $0(.success(localesResponse.items)) }) self?.localesCompletionHandlers.removeAll() completion(Result.success(localesResponse.items)) case .failure(let error): completion(.failure(error)) } } } // Returns the rate limit reset. fileprivate func readRateLimitHeaderIfPresent(response: URLResponse?) -> Int? { if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode == 429 { let rateLimitResetPair = httpResponse.allHeaderFields.filter { arg in let (key, _) = arg return (key as? String)?.lowercased() == "x-contentful-ratelimit-reset" } if let rateLimitResetString = rateLimitResetPair.first?.value as? String { return Int(rateLimitResetString) } } } return nil } // Returns true if a rate limit error was returned by the API. fileprivate func didHandleRateLimitError( data: Data, response: URLResponse?, jsonDecoder: JSONDecoder, completion: ResultsHandler<Data> ) -> Bool { guard let timeUntilLimitReset = self.readRateLimitHeaderIfPresent(response: response) else { return false } // At this point, We know for sure that the type returned by the API can be mapped to an `APIError` instance. // Directly handle JSON and exit. let statusCode = (response as! HTTPURLResponse).statusCode self.handleRateLimitJSON( data: data, timeUntilLimitReset: timeUntilLimitReset, statusCode: statusCode, jsonDecoder: jsonDecoder ) { (_ result: Result<RateLimitError, Error>) in switch result { case .success(let rateLimitError): completion(.failure(rateLimitError)) case .failure(let auxillaryError): // We should never get here, but we'll bubble up what should be a `SDKError.unparseableJSON` error just in case. completion(.failure(auxillaryError)) } } return true } private func handleRateLimitJSON( data: Data, timeUntilLimitReset: Int, statusCode: Int, jsonDecoder: JSONDecoder, completion: ResultsHandler<RateLimitError> ) { guard let rateLimitError = try? jsonDecoder.decode(RateLimitError.self, from: data) else { completion(.failure(SDKError.unparseableJSON(data: data, errorMessage: "SDK unable to parse RateLimitError payload"))) return } rateLimitError.statusCode = statusCode rateLimitError.timeBeforeLimitReset = timeUntilLimitReset let errorMessage = """ Errored: Rate Limit Error Message: \(rateLimitError)" """ ContentfulLogger.log(.error, message: errorMessage) // In this case, .success means that a RateLimitError was successfully initialized. completion(Result.success(rateLimitError)) } private func handleJSON<DecodableType: Decodable>( data: Data, completion: @escaping ResultsHandler<DecodableType> ) { let jsonDecoder = jsonDecoderBuilder.build() var decodedObject: DecodableType? do { decodedObject = try jsonDecoder.decode(DecodableType.self, from: data) } catch let error { let sdkError = SDKError.unparseableJSON(data: data, errorMessage: "\(error)") ContentfulLogger.log(.error, message: sdkError.message) completion(.failure(sdkError)) } guard let linkResolver = jsonDecoder.userInfo[.linkResolverContextKey] as? LinkResolver else { let error = SDKError.unparseableJSON( data: data, errorMessage: "Couldn't find link resolver instance." ) ContentfulLogger.log(.error, message: error.message) completion(.failure(error)) return } linkResolver.churnLinks() // Make sure decoded object is not nil before calling success completion block. if let decodedObject = decodedObject { completion(.success(decodedObject)) } else { let error = SDKError.unparseableJSON( data: data, errorMessage: "Unknown error occured during decoding." ) ContentfulLogger.log(.error, message: error.message) completion(.failure(error)) } } }
43.559846
154
0.611771
e890ca1663b427f161ab2a05df967307e0bee954
1,328
// // Copyright (c) 2016 Keun young Kim <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit for i in 0..<3 { for j in 0...10 { if j > 2 { break } print("inner \(j)") } print("OUTER \(i)") }
36.888889
81
0.696536
8fd9be2bed7a52db0f47c3935da816d4e3c221a9
2,570
// // GuruResult.swift // // Create by xijinfa on 4/2/2017 // Copyright © 2017. All rights reserved. // Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation import ObjectMapper public class GurusResult: NSObject, NSCoding, Mappable { public var currentPage: Int? public var data: [GuruData]? public var from: Int? public var lastPage: Int? public var nextPageUrl: AnyObject? public var perPage: Int? public var prevPageUrl: AnyObject? public var to: Int? public var total: Int? class func newInstance(map: Map) -> Mappable? { return GurusResult() } required public init?(map: Map) {} private override init() {} public func mapping(map: Map) { currentPage <- map["current_page"] data <- map["data"] from <- map["from"] lastPage <- map["last_page"] nextPageUrl <- map["next_page_url"] perPage <- map["per_page"] prevPageUrl <- map["prev_page_url"] to <- map["to"] total <- map["total"] } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required public init(coder aDecoder: NSCoder) { currentPage = aDecoder.decodeObject(forKey: "current_page") as? Int data = aDecoder.decodeObject(forKey: "data") as? [GuruData] from = aDecoder.decodeObject(forKey: "from") as? Int lastPage = aDecoder.decodeObject(forKey: "last_page") as? Int nextPageUrl = aDecoder.decodeObject(forKey: "next_page_url") as? AnyObject perPage = aDecoder.decodeObject(forKey: "per_page") as? Int prevPageUrl = aDecoder.decodeObject(forKey: "prev_page_url") as? AnyObject to = aDecoder.decodeObject(forKey: "to") as? Int total = aDecoder.decodeObject(forKey: "total") as? Int } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc public func encode(with aCoder: NSCoder) { if currentPage != nil { aCoder.encode(currentPage, forKey: "current_page") } if data != nil { aCoder.encode(data, forKey: "data") } if from != nil { aCoder.encode(from, forKey: "from") } if lastPage != nil { aCoder.encode(lastPage, forKey: "last_page") } if nextPageUrl != nil { aCoder.encode(nextPageUrl, forKey: "next_page_url") } if perPage != nil { aCoder.encode(perPage, forKey: "per_page") } if prevPageUrl != nil { aCoder.encode(prevPageUrl, forKey: "prev_page_url") } if to != nil { aCoder.encode(to, forKey: "to") } if total != nil { aCoder.encode(total, forKey: "total") } } }
27.052632
83
0.663424
b9e8c5a75bc37fc1992a99ab18d48f25bdea86d2
180
// // BaseURL.swift // Network // // Created by apple on 2021/06/18. // import Foundation enum BaseURL: String { case base = "https://d2bab9i9pr8lds.cloudfront.net/api" }
13.846154
59
0.661111
4618542df79b49dfe97c5c818cb181dfc4428e52
1,071
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Base58String", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "Base58String", targets: ["Base58String"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/attaswift/BigInt.git", from: "5.0.0") ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "Base58String", dependencies: ["BigInt"]), .testTarget( name: "Base58StringTests", dependencies: ["Base58String"]), ] )
36.931034
122
0.636788
e8bed6bc169dcc37827a7f640e6bf865cd23a052
888
// // BBAnchorable.swift // AutoLayoutProxy // // Created by Bibin Jacob Pulickal on 14/08/19. // Copyright © 2019 Bibin Jacob Pulickal. All rights reserved. // #if canImport(UIKit) import UIKit.NSLayoutAnchor #elseif canImport(AppKit) import AppKit.NSLayoutAnchor #endif public protocol BBAnchorable { var leadingAnchor: NSLayoutXAxisAnchor { get } var trailingAnchor: NSLayoutXAxisAnchor { get } var leftAnchor: NSLayoutXAxisAnchor { get } var rightAnchor: NSLayoutXAxisAnchor { get } var topAnchor: NSLayoutYAxisAnchor { get } var bottomAnchor: NSLayoutYAxisAnchor { get } var widthAnchor: NSLayoutDimension { get } var heightAnchor: NSLayoutDimension { get } var centerXAnchor: NSLayoutXAxisAnchor { get } var centerYAnchor: NSLayoutYAxisAnchor { get } } #if canImport(UIKit) extension UILayoutGuide: BBAnchorable { } #endif
20.651163
63
0.73536
f99594faf36f50f745c640f4ec54d750f769259b
346
// // TZStackViewAlignment.swift // TZStackView // // Created by Tom van Zummeren on 15/06/15. // Copyright © 2015 Tom van Zummeren. All rights reserved. // import Foundation @objc public enum TZStackViewAlignment: Int { case Fill case Center case Leading case Top case Trailing case Bottom case FirstBaseline }
17.3
59
0.690751
2333d41852804cb0dbbfe18601908714b9f3463f
797
// // PreworkUITestsLaunchTests.swift // PreworkUITests // // Created by PHUONG NHI on 21/12/2021. // import XCTest class PreworkUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
24.151515
88
0.672522
0817486d80c9006b0b5f7bdf179528954d71ed20
11,184
// // Buffer.swift // PublisherKit // // Created by Raghav Ahuja on 29/03/20. // extension Publisher { /// Buffers elements received from an upstream publisher. /// - Parameter size: The maximum number of elements to store. /// - Parameter prefetch: The strategy for initially populating the buffer. /// - Parameter whenFull: The action to take when the buffer becomes full. public func buffer(size: Int, prefetch: Publishers.PrefetchStrategy, whenFull: Publishers.BufferingStrategy<Failure>) -> Publishers.Buffer<Self> { Publishers.Buffer(upstream: self, size: size, prefetch: prefetch, whenFull: whenFull) } } extension Publishers { /// A strategy for filling a buffer. /// /// * keepFull: A strategy to fill the buffer at subscription time, and keep it full thereafter. /// * byRequest: A strategy that avoids prefetching and instead performs requests on demand. public enum PrefetchStrategy { /// A strategy to fill the buffer at subscription time, and keep it full thereafter. /// /// This strategy starts by making a demand equal to the buffer’s size from the upstream when the subscriber first connects. Afterwards, it continues to demand elements from the upstream to try to keep the buffer full. case keepFull /// A strategy that avoids prefetching and instead performs requests on demand. /// /// This strategy just forwards the downstream’s requests to the upstream publisher. case byRequest } /// A strategy for handling exhaustion of a buffer’s capacity. /// /// * dropNewest: When full, discard the newly-received element without buffering it. /// * dropOldest: When full, remove the least recently-received element from the buffer. /// * customError: When full, execute the closure to provide a custom error. public enum BufferingStrategy<Failure> where Failure: Error { /// When full, discard the newly-received element without buffering it. case dropNewest /// When full, remove the least recently-received element from the buffer. case dropOldest /// When full, execute the closure to provide a custom error. case customError(() -> Failure) } /// A publisher that buffers elements received from an upstream publisher. public struct Buffer<Upstream: Publisher>: Publisher { public typealias Output = Upstream.Output public typealias Failure = Upstream.Failure /// The publisher from which this publisher receives elements. public let upstream: Upstream /// The maximum number of elements to store. public let size: Int /// The strategy for initially populating the buffer. public let prefetch: Publishers.PrefetchStrategy /// The action to take when the buffer becomes full. public let whenFull: Publishers.BufferingStrategy<Upstream.Failure> /// Creates a publisher that buffers elements received from an upstream publisher. /// - Parameter upstream: The publisher from which this publisher receives elements. /// - Parameter size: The maximum number of elements to store. /// - Parameter prefetch: The strategy for initially populating the buffer. /// - Parameter whenFull: The action to take when the buffer becomes full. public init(upstream: Upstream, size: Int, prefetch: Publishers.PrefetchStrategy, whenFull: Publishers.BufferingStrategy<Failure>) { self.upstream = upstream self.size = size self.prefetch = prefetch self.whenFull = whenFull } public func receive<S: Subscriber>(subscriber: S) where Output == S.Input, Failure == S.Failure { upstream.subscribe(Inner(downstream: subscriber, parent: self)) } } } extension Publishers.PrefetchStrategy: Equatable { } extension Publishers.PrefetchStrategy: Hashable { } extension Publishers.Buffer { // MARK: BUFFER SINK private final class Inner<Downstream: Subscriber>: Subscriber, Subscription, CustomStringConvertible, CustomPlaygroundDisplayConvertible, CustomReflectable where Output == Downstream.Input, Failure == Downstream.Failure { typealias Input = Upstream.Output typealias Failure = Upstream.Failure private var terminal: Subscribers.Completion<Failure>? private let lock = Lock() private var values: [Input] = [] private var downstreamDemand: Subscribers.Demand = .none private var isActive = false fileprivate typealias Buffer = Publishers.Buffer<Upstream> private enum State { case awaiting(Buffer, Downstream) case subscribed(Buffer, Downstream, Subscription) case terminated } private var state: State init(downstream: Downstream, parent: Buffer) { state = .awaiting(parent, downstream) } func receive(subscription: Subscription) { lock.lock() guard case .awaiting(let parent, let downstream) = state else { lock.unlock() subscription.cancel() return } state = .subscribed(parent, downstream, subscription) lock.unlock() let demand: Subscribers.Demand switch parent.prefetch { case .keepFull: demand = .max(parent.size) case .byRequest: demand = .unlimited } subscription.request(demand) downstream.receive(subscription: self) } func receive(_ input: Input) -> Subscribers.Demand { lock.lock() guard case .subscribed(let parent, _, let subscription) = state else { lock.unlock(); return .none } switch terminal { case .none, .finished: guard values.count >= parent.size else { values.append(input) lock.unlock() return drain() } switch parent.whenFull { case .dropNewest: lock.unlock() return drain() case .dropOldest: values.removeFirst() values.append(input) lock.unlock() return drain() case .customError(let createError): terminal = .failure(createError()) lock.unlock() subscription.cancel() return .none } case .failure: lock.unlock() return .none } } func receive(completion: Subscribers.Completion<Failure>) { lock.lock() guard case .subscribed = state, terminal == nil else { lock.unlock(); return } terminal = completion lock.unlock() _ = drain() } func request(_ demand: Subscribers.Demand) { lock.lock() guard case .subscribed(_, _, let subscription) = state else { lock.unlock(); return } downstreamDemand += demand let isActive = self.isActive lock.unlock() guard !isActive else { return } subscription.request(drain() + demand) } func cancel() { lock.lock() guard case .subscribed(_, _, let subscription) = state else { lock.unlock(); return } state = .terminated values = [] lock.unlock() subscription.cancel() } private func drain() -> Subscribers.Demand { var demand: Subscribers.Demand = .none lock.lock() while true { guard case .subscribed(let parent, let downstream, _) = state else { lock.unlock(); return demand } guard downstreamDemand > .none else { guard let terminal = terminal, case .failure(let error) = terminal else { lock.unlock(); return demand } state = .terminated lock.unlock() downstream.receive(completion: .failure(error)) return demand } if values.isEmpty { guard let terminal = terminal else { lock.unlock(); return demand } state = .terminated lock.unlock() downstream.receive(completion: terminal) return demand } let poppedValues = locked_pop(downstreamDemand) downstreamDemand -= poppedValues.count isActive = true lock.unlock() var additionalDemand: Subscribers.Demand = .none var additionalUpstreamDemand = 0 poppedValues.forEach { (value) in additionalDemand += downstream.receive(value) additionalUpstreamDemand += 1 } if parent.prefetch == .keepFull { demand += additionalUpstreamDemand } lock.lock() isActive = false downstreamDemand += additionalDemand lock.unlock() } } private func locked_pop(_ demand: Subscribers.Demand) -> [Input] { assert(demand > .none) guard let max = demand.max else { let values = self.values self.values = [] return values } let values = Array(self.values.prefix(max)) self.values.removeFirst(values.count) return values } var description: String { "Buffer" } var playgroundDescription: Any { description } var customMirror: Mirror { let children: [Mirror.Child] = [ ("values", values), ("state", state), ("downstreamDemand", downstreamDemand), ("terminal", terminal as Any) ] return Mirror(self, children: children) } } }
35.961415
226
0.534603
08d7f7dcf8c20d33386b0d0c3355953175db1df6
3,758
// // LXFChatTextCell.swift // LXFWeChat // // Created by 林洵锋 on 2017/1/3. // Copyright © 2017年 林洵锋. All rights reserved. // // GitHub: https://github.com/LinXunFeng // 简书: http://www.jianshu.com/users/31e85e7a22a2 import UIKit class LXFChatTextCell: LXFChatBaseCell { // MARK:- 模型 override var model: LXFChatMsgModel? { didSet { setModel() } } // MARK:- 懒加载 lazy var contentLabel: UILabel = { let contentL = UILabel() contentL.numberOfLines = 0 contentL.textAlignment = .left contentL.font = UIFont.systemFont(ofSize: 16.0) return contentL }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) bubbleView.addSubview(self.contentLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 模型数据 extension LXFChatTextCell { fileprivate func setModel() { contentLabel.attributedText = LXFChatFindEmotion.shared.findAttrStr(text: model?.text, font: contentLabel.font) // 设置泡泡 let img = self.model?.userType == .me ? #imageLiteral(resourceName: "message_sender_background_normal") : #imageLiteral(resourceName: "message_receiver_background_normal") let normalImg = img.resizableImage(withCapInsets: UIEdgeInsetsMake(30, 28, 85, 28), resizingMode: .stretch) bubbleView.image = normalImg let contentSize = contentLabel.sizeThatFits(CGSize(width: 220.0, height: CGFloat(FLT_MAX))) // 重新布局 avatar.snp.remakeConstraints { (make) in make.width.height.equalTo(40) make.top.equalTo(self.snp.top) } bubbleView.snp.remakeConstraints { (make) in make.top.equalTo(self.snp.top).offset(-2) make.bottom.equalTo(contentLabel.snp.bottom).offset(16) } contentLabel.snp.remakeConstraints { (make) in make.height.equalTo(contentSize.height) make.width.equalTo(contentSize.width) } tipView.snp.remakeConstraints { (make) in make.centerY.equalTo(avatar.snp.centerY) make.width.height.equalTo(30) } if model?.userType == .me { avatar.snp.makeConstraints { (make) in make.right.equalTo(self.snp.right).offset(-10) } bubbleView.snp.makeConstraints { (make) in make.right.equalTo(avatar.snp.left).offset(-2) make.left.equalTo(contentLabel.snp.left).offset(-20) } contentLabel.snp.makeConstraints { (make) in make.top.equalTo(bubbleView.snp.top).offset(12) make.right.equalTo(bubbleView.snp.right).offset(-17) } tipView.snp.makeConstraints { (make) in make.right.equalTo(bubbleView.snp.left) } } else { avatar.snp.makeConstraints { (make) in make.left.equalTo(self.snp.left).offset(10) } bubbleView.snp.makeConstraints { (make) in make.left.equalTo(avatar.snp.right).offset(2) make.right.equalTo(contentLabel.snp.right).offset(20) } contentLabel.snp.makeConstraints { (make) in make.top.equalTo(bubbleView.snp.top).offset(12) make.left.equalTo(bubbleView.snp.left).offset(17) } tipView.snp.makeConstraints { (make) in make.left.equalTo(bubbleView.snp.right) } } model?.cellHeight = getCellHeight() } }
35.45283
179
0.595796
01507328f3b89e18d2e81055d177fc804f90bdd4
2,306
// // GitHubServiceTests.swift // GPM // // Created by mtgto on 2016/09/18. // Copyright © 2016 mtgto. All rights reserved. // import Foundation import XCTest @testable import GPM class GitHubServiceTests: XCTestCase, GitHubTestsSupport { let service = GitHubService() func testParseProjectsResponse() { let data = self.dataFromResourceFile("response_repos_owner_repo_projects.json") let json = try! JSONSerialization.jsonObject(with: data, options: []) let projects = service.parseProjectsResponse(json) XCTAssertEqual(projects.map({ $0.count }), Optional(1)) } func testParseProjectColumnsResponse() { let data = self.dataFromResourceFile("response_repos_owner_repo_projects_project_number_columns.json") let json = try! JSONSerialization.jsonObject(with: data, options: []) let columns = service.parseProjectColumnsResponse(json) XCTAssertEqual(columns.map({ $0.count }), Optional(1)) } func testParseProjectCardsResponse() { let data = self.dataFromResourceFile("response_repos_owner_repo_projects_columns_column_id_cards.json") let json = try! JSONSerialization.jsonObject(with: data, options: []) let cards = service.parseProjectCardsResponse(json) XCTAssertEqual(cards.map({ $0.count }), Optional(2)) } func testParseProjectCardResponse() { let data = self.dataFromResourceFile("response_repos_owner_repo_projects_columns_column_id_card.json") let json = try! JSONSerialization.jsonObject(with: data, options: []) let card = service.parseProjectCardResponse(json) XCTAssertNotNil(card) } func testParseIssueResponse() { let data = self.dataFromResourceFile("response_repos_owner_repo_issues_number.json") let json = try! JSONSerialization.jsonObject(with: data, options: []) let issue = service.parseIssueResponse(json, owner: "octocat", repo: "Hello-World") XCTAssertNotNil(issue) } func testParseUserResponse() { let data = self.dataFromResourceFile("response_user.json") let json = try! JSONSerialization.jsonObject(with: data, options: []) let user = service.parseUser(json) XCTAssertEqual(user.map({ $0.login }), Optional("octocat")) } }
39.758621
111
0.705984
edf9f3da426d1c4da1ec9333f83ee23575aea9ee
3,269
// // SACookieManager.swift // Saralin // // Created by zhang on 4/3/17. // Copyright © 2017 zaczh. All rights reserved. // import Foundation import WebKit class SACookieManager { private var logoutNotificationObject: NSObjectProtocol? private var loginNotificationObject: NSObjectProtocol? private var lastTimeRefreshCookie: Date? private var lastTimeRefreshCookieLock = NSLock() init() { let center = NotificationCenter.default logoutNotificationObject = center.addObserver(forName: Notification.Name.SAUserLoggedOutNotification, object: nil, queue: nil, using: { [weak self] (notification) in guard let self = self else { return } self.lastTimeRefreshCookieLock.lock() self.lastTimeRefreshCookie = nil self.lastTimeRefreshCookieLock.unlock() }) loginNotificationObject = center.addObserver(forName: Notification.Name.SAUserLoggedInNotification, object: nil, queue: nil, using: { [weak self] (notification) in guard let self = self else { return } self.lastTimeRefreshCookieLock.lock() self.lastTimeRefreshCookie = Date() self.lastTimeRefreshCookieLock.unlock() }) } func syncWKCookiesToNSCookieStorage(completion:(() -> Void)?) { let cookieStorage = HTTPCookieStorage.shared WKWebsiteDataStore.default().httpCookieStore.getAllCookies { (cookies) in for cookie in cookies { if !(cookieStorage.cookies?.contains(cookie) ?? false) { cookieStorage.setCookie(cookie) } } completion?() } } deinit { let center = NotificationCenter.default if let object = logoutNotificationObject { center.removeObserver(object) } if let object = loginNotificationObject { center.removeObserver(object) } } // on iPad, App will stay in memory for a very long time. If we do not refresh cookies periodically, // then when we open a forum page after some days, we are logged out. func renewCookiesIfNeeded() { let account = Account() guard !account.uid.isEmpty else { return } lastTimeRefreshCookieLock.lock() if let lastTimeRefreshCookie = lastTimeRefreshCookie as NSDate?, lastTimeRefreshCookie.timeIntervalSinceNow > -8 * 3600 { lastTimeRefreshCookieLock.unlock() return } lastTimeRefreshCookieLock.unlock() os_log("refresh cookie", log: .cookie, type: .info) var request = URLRequest(url: URL(string: SAGlobalConfig().forum_url)!) request.setValue(SAGlobalConfig().pc_useragent_string, forHTTPHeaderField: "User-Agent"); let task = URLSession.saCustomized.downloadTask(with: request) { (url, response, error) in guard error == nil else { return } self.lastTimeRefreshCookieLock.lock() self.lastTimeRefreshCookie = Date() self.lastTimeRefreshCookieLock.unlock() } task.resume() } }
35.923077
173
0.620067
eb54661304098cf81629c0e49251d2926459516b
611
import Combine import Foundation let runLoop = RunLoop.main let cancelable = runLoop .schedule(after: runLoop.now, interval: .seconds(1), tolerance: .milliseconds(100), options: nil) { print("Schedule fired") // it fires every interval the action block } DispatchQueue.main.asyncAfter(deadline: .now() + 5) { cancelable.cancel() } let oneSecInTheFuture = Date().addingTimeInterval(TimeInterval(1)) let after = RunLoop.SchedulerTimeType(oneSecInTheFuture) print(Date()) runLoop.schedule(after: after) { print("Schedule \(Date())") //fires only once after the specified time, not cancelable }
29.095238
103
0.739771
f465f30e7b5f763304d6f4ae71c99f383fb8d340
4,329
// // SliderConfig.swift // MobilePlayer // // Created by Baris Sencan on 9/15/15. // Copyright (c) 2015 MovieLaLa. All rights reserved. // import UIKit /// Holds slider configuration values. public class SliderConfig: ElementConfig { /// Height of the slider track. public let trackHeight: CGFloat /// Corner radius of the slider track. public let trackCornerRadius: CGFloat /// Color of the track to the left of slider thumb. public let minimumTrackTintColor: UIColor /// Color of the parts of the track which fall to the right side of slider thumb and represent available value /// (e.g. buffered duration of a video). public let availableTrackTintColor: UIColor /// Color of the track to the right of slider thumb. public let maximumTrackTintColor: UIColor /// Color of the slider thumb. public let thumbTintColor: UIColor /// Width of the slider thumb. public let thumbWidth: CGFloat /// Height of the slider thumb. public let thumbHeight: CGFloat /// Corner radius of the slider thumb. public let thumbCornerRadius: CGFloat /// Border width of the slider thumb. public let thumbBorderWidth: CGFloat /// Border color of the slider thumb. public let thumbBorderColor: CGColor /// Initializes using default values. public convenience init() { self.init(dictionary: [String: Any]()) } /// Initializes using a dictionary. /// /// * Key for `trackHeight` is `"trackHeight"` and its value should be a number. /// * Key for `trackCornerRadius` is `"trackCornerRadius"` and its value should be a number. /// * Key for `minimumTrackTintColor` is `"minimumTrackTintColor"` and its value should be a color hex string. /// * Key for `availableTrackTintColor` is `"availableTrackTintColor"` and its value should be a color hex string. /// * Key for `maximumTrackTintColor` is `"maximumTrackTintColor"` and its value should be a color hex string. /// * Key for `thumbTintColor` is `"thumbTintColor"` and its value should be a color hex string. /// * Key for `thumbWidth` is `"thumbWidth"` and its value should be a number. /// * Key for `thumbHeight` is `"thumbHeight"` and its value should be a number. /// * Key for `thumbCornerRadius` is `"thumbCornerRadius"` and its value should be a number. /// * Key for `thumbBorderWidth` is `"thumbBorderWidth"` and its value should be a number. /// * Key for `thumbBorderColor` is `"thumbBorderColor"` and its value should be a color hex string. /// /// - parameters: /// - dictionary: Toggle button configuration dictionary. public override init(dictionary: [String: Any]) { // Values need to be AnyObject for type conversions to work correctly. let dictionary = dictionary as [String: AnyObject] trackHeight = (dictionary["trackHeight"] as? CGFloat) ?? 6 trackCornerRadius = (dictionary["trackCornerRadius"] as? CGFloat) ?? 3 if let minimumTrackTintColorHex = dictionary["minimumTrackTintColor"] as? String { minimumTrackTintColor = UIColor(hex: minimumTrackTintColorHex) } else { minimumTrackTintColor = UIColor(white: 0.9, alpha: 1) } if let availableTrackTintColorHex = dictionary["availableTrackTintColor"] as? String { availableTrackTintColor = UIColor(hex: availableTrackTintColorHex) } else { availableTrackTintColor = UIColor(white: 0.6, alpha: 1) } if let maximumTrackTintColorHex = dictionary["maximumTrackTintColor"] as? String { maximumTrackTintColor = UIColor(hex: maximumTrackTintColorHex) } else { maximumTrackTintColor = UIColor(white: 0.3, alpha: 1) } if let thumbTintColorHex = dictionary["thumbTintColor"] as? String { thumbTintColor = UIColor(hex: thumbTintColorHex) } else { thumbTintColor = UIColor.white } thumbWidth = (dictionary["thumbWidth"] as? CGFloat) ?? 16 thumbHeight = (dictionary["thumbHeight"] as? CGFloat) ?? 16 thumbCornerRadius = (dictionary["thumbCornerRadius"] as? CGFloat) ?? 8 thumbBorderWidth = (dictionary["thumbBorderWidth"] as? CGFloat) ?? 0 if let thumbBorderColorHex = dictionary["thumbBorderColor"] as? String { thumbBorderColor = UIColor(hex: thumbBorderColorHex).cgColor } else { thumbBorderColor = UIColor.clear.cgColor } super.init(dictionary: dictionary) } }
37.973684
116
0.709864
eb07a60d7931bcb4dea2be2230aa44ec068288af
5,522
@testable import Swindler import AXSwift class TestObserver: ObserverType { typealias UIElement = TestUIElement typealias Context = TestObserver //typealias Callback = (Context, TestUIElement, AXNotification) -> () required init(processID: pid_t, callback: @escaping Callback) throws {} init() {} func addNotification(_ notification: AXNotification, forElement: TestUIElement) throws {} func removeNotification(_ notification: AXNotification, forElement: TestUIElement) throws {} } // MARK: - Adversaries /// Allows defining adversarial actions when a property is observed. final class AdversaryObserver: FakeObserver { static var onNotification: AXNotification? static var handler: Optional<(AdversaryObserver) -> Void> = nil /// Call this in beforeEach for any tests that use this class. static func reset() { onNotification = nil handler = nil } /// Defines code that runs on the main thread before returning from addNotification. static func onAddNotification(_ notification: AXNotification, handler: @escaping (AdversaryObserver) -> Void) { onNotification = notification self.handler = handler } override func addNotification( _ notification: AXNotification, forElement element: TestUIElement) throws { try super.addNotification(notification, forElement: element) if notification == AdversaryObserver.onNotification { performOnMainThread { AdversaryObserver.handler!(self) } } } } /// Allows defining adversarial actions when an attribute is read. final class AdversaryApplicationElement: TestApplicationElementBase, ApplicationElementType { static var allApps: [AdversaryApplicationElement] = [] static func all() -> [AdversaryApplicationElement] { return AdversaryApplicationElement.allApps } var onRead: Optional < (AdversaryApplicationElement) -> Void> = nil var watchAttribute: Attribute? var alreadyCalled = false var onMainThread = true init() { super.init(processID: 0) } init?(forProcessID processID: pid_t) { return nil } /// Defines code that runs on the main thread before returning the value of the attribute. func onFirstAttributeRead(_ attribute: Attribute, onMainThread: Bool = true, handler: @escaping (AdversaryApplicationElement) -> Void) { watchAttribute = attribute onRead = handler alreadyCalled = false self.onMainThread = onMainThread } var lock = NSLock() fileprivate func handleAttributeRead() { lock.lock() defer { lock.unlock() } if !self.alreadyCalled { if self.onMainThread { performOnMainThread { self.onRead?(self) } } else { self.onRead?(self) } self.alreadyCalled = true } } override func attribute<T>(_ attribute: Attribute) throws -> T? { let result: T? = try super.attribute(attribute) if attribute == watchAttribute { handleAttributeRead() } return result } override func arrayAttribute<T>(_ attribute: Attribute) throws -> [T]? { let result: [T]? = try super.arrayAttribute(attribute) if attribute == watchAttribute { handleAttributeRead() } return result } override func getMultipleAttributes(_ attributes: [AXSwift.Attribute]) throws -> [Attribute: Any] { let result: [Attribute: Any] = try super.getMultipleAttributes(attributes) if let watchAttribute = watchAttribute, attributes.contains(watchAttribute) { handleAttributeRead() } return result } } /// Allows defining adversarial actions when an attribute is read. class AdversaryWindowElement: TestWindowElement { var onRead: Optional<() -> Void> = nil var watchAttribute: Attribute? var alreadyCalled = false /// Defines code that runs on the main thread before returning the value of the attribute. func onAttributeFirstRead(_ attribute: Attribute, handler: @escaping () -> Void) { watchAttribute = attribute onRead = handler alreadyCalled = false } override func attribute<T>(_ attribute: Attribute) throws -> T? { let result: T? = try super.attribute(attribute) if attribute == watchAttribute { performOnMainThread { if !self.alreadyCalled { self.onRead?() self.alreadyCalled = true } } } return result } override func getMultipleAttributes(_ attributes: [AXSwift.Attribute]) throws -> [Attribute: Any] { let result: [Attribute: Any] = try super.getMultipleAttributes(attributes) if let watchAttribute = watchAttribute, attributes.contains(watchAttribute) { performOnMainThread { if !self.alreadyCalled { self.onRead?() self.alreadyCalled = true } } } return result } } /// Performs the given action on the main thread, synchronously, regardless of the current thread. func performOnMainThread(_ action: () -> Void) { if Thread.current.isMainThread { action() } else { DispatchQueue.main.sync { action() } } }
34.5125
98
0.636726
acf5331b3d0735d09d402d9857404000f042ad16
1,277
// Copyright © 2015 Abhishek Banthia import Cocoa import os import os.log import os.signpost public class Logger: NSObject { let logObjc = OSLog(subsystem: "com.abhishek.Clocker", category: "app") public class func log(object annotations: [String: Any]?, for event: NSString) { if #available(OSX 10.14, *) { os_log(.default, "[%@] - [%@]", event, annotations ?? [:]) } } public class func info(_ message: String) { if #available(OSX 10.14, *) { os_log(.info, "%@", message) } } } @available(OSX 10.14, *) public class PerfLogger: NSObject { static var panelLog = OSLog(subsystem: "com.abhishek.Clocker", category: "Open Panel") static let signpostID = OSSignpostID(log: panelLog) public class func disable() { panelLog = .disabled } public class func startMarker(_ name: StaticString) { os_signpost(.begin, log: panelLog, name: name, signpostID: signpostID) } public class func endMarker(_ name: StaticString) { os_signpost(.end, log: panelLog, name: name, signpostID: signpostID) } }
26.604167
84
0.555991
e93e561099f17f473e0fce4254f75790ee1dc130
555
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "LocalPackage", platforms: [ .iOS(.v14) ], products: [ .library( name: "MyFramework", targets: ["MyFramework"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. ], targets: [ .target(name: "LocalPackage"), .binaryTarget( name: "MyFramework", path: "MyFramework/prebuilt/MyFramework.xcframework" ) ] )
22.2
76
0.554955
c16bde10d40f43f98ae38fab9516f041130facd7
1,702
import Foundation import SourceKittenFramework struct BasicPipeline: Pipeline { let extractor: Extractor let parser: Parser let validator: Validator let resolver: Resolver let cleaner: Cleaner let assembler: Assembler let preparator: Preparator let generator: Generator func extract(from file: WithTargets<File>) throws -> [Struct<Stage.Extracted>] { return try extractor.extract(from: file) } func parse(extracted: Struct<Stage.Extracted>) throws -> Struct<Stage.Parsed> { return try parser.parse(extracted: extracted) } func validate(parsed: Struct<Stage.Parsed>, using apis: [API]) throws -> Struct<Stage.Validated> { return try validator.validate(parsed: parsed, using: apis) } func resolve(validated: [Struct<Stage.Validated>]) throws -> [Struct<Stage.Resolved>] { return try resolver.resolve(validated: validated) } func clean(resolved: [Struct<Stage.Resolved>]) throws -> [Struct<Stage.Cleaned>] { return try cleaner.clean(resolved: resolved) } func assemble(cleaned: Project.State<Stage.Cleaned>) throws -> Project.State<Stage.Assembled> { return try assembler.assemble(cleaned: cleaned) } func prepare(assembled: Project.State<Stage.Assembled>, using apollo: ApolloReference) throws -> Project.State<Stage.Prepared> { return try preparator.prepare(assembled: assembled, using: apollo) } func generate(prepared: Project.State<Stage.Prepared>, useFormatting: Bool) throws -> String { return try generator.generate(prepared: prepared, useFormatting: useFormatting) } }
35.458333
102
0.680964
756177afde2f357deb01bf0100489590cc258508
794
// // AppDelegate.swift // SwiftUITouchHandling // // Created by Peter Steinberger on 26.10.20. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } }
34.521739
179
0.753149
e5f263f120ffa56f0c00d889205a4317acd34ef3
899
// // Copyright © 2020 NHSX. All rights reserved. // import Foundation final class AuthenticatedRequestGenerator: RequestGenerator { private let baseURLComponents: URLComponents private let makeBearerToken: () -> String init(host: String, path: String, makeBearerToken: @escaping () -> String) { self.makeBearerToken = makeBearerToken baseURLComponents = mutating(URLComponents()) { $0.scheme = "https" $0.host = host $0.path = path } } func request(for path: String) -> URLRequest { let urlComponents = mutating(baseURLComponents) { $0.path += path } let token = makeBearerToken() return mutating(URLRequest(url: urlComponents.url!)) { $0.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } } }
26.441176
79
0.591769
e20c4f7112c784baec52477189c013a590c81316
41,845
// // KeymanWebViewController.swift // KeymanEngine // // Created by Gabriel Wong on 2017-10-31. // Copyright © 2017 SIL International. All rights reserved. // import UIKit import WebKit import AudioToolbox private let keyboardChangeHelpText = NSLocalizedString("keyboard-help-change", bundle: engineBundle, comment: "") private let subKeyColor = Colors.popupKey private let subKeyColorHighlighted = Colors.popupKeyHighlighted // We subclass for one critical reason - by default, WebViews may become first responder... // a detail that is really, REALLY bad for a WebView in a keyboard. // // Minor reference here: https://stackoverflow.com/questions/39829863/can-a-uiwebview-handle-user-interaction-without-becoming-first-responder // // Confirmed issue existed within app during workaround for https://github.com/keymanapp/keyman/issues/2716 class KeymanWebView: WKWebView { override public var canBecomeFirstResponder: Bool { return false; } override public func becomeFirstResponder() -> Bool { return false; } } // MARK: - UIViewController class KeymanWebViewController: UIViewController { let storage: Storage weak var delegate: KeymanWebDelegate? private var useSpecialFont = false // Views var webView: KeymanWebView? var activeModel: Bool = false private var helpBubbleView: PopoverView? private var keyPreviewView: KeyPreviewView? private var subKeysView: SubKeysView? private var keyboardMenuView: KeyboardMenuView? // Arrays private var subKeyIDs: [String] = [] private var subKeyTexts: [String] = [] private var subKeys: [UIButton] = [] private var subKeyAnchor = CGRect.zero /// Stores the keyboard view's current size. private var kbSize: CGSize = CGSize.zero /// Stores the current image for use by the Banner /// when predictive text is not active private var bannerImgPath: String = "" var isLoading: Bool = false private var currentText: String = "" private var currentCursorRange: NSRange? = nil init(storage: Storage) { self.storage = storage super.init(nibName: nil, bundle: nil) _ = view } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func fixLayout() { view.setNeedsLayout() view.layoutIfNeeded() } override func viewWillLayoutSubviews() { // This method is called automatically during layout correction by iOS. // It also has access to correct `view.bounds.size` values, unlike viewDidAppear. // As a result, it's the correct place to perform OSK size adjustments. // // Problem - this is ALSO called automatically upon any touch-based interaction with the OSK! (Why!?) // The `keyboardSize` property will filter out any such redundant size-change requests to prevent issues // that would otherwise arise. (Important event handlers can trigger for the original OSK instance // after it has been replaced by KMW's OSK resizing operation.) keyboardSize = view.bounds.size } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) if Manager.shared.isKeymanHelpOn { showHelpBubble(afterDelay: 1.5) } coordinator.animateAlongsideTransition(in: nil, animation: { _ in self.fixLayout() }, completion: { _ in // When going from landscape to portrait, the value is often not properly set until the end of the call chain. // A simple, ultra-short timer allows us to quickly rectify the value in these cases to correct the keyboard. Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.fixLayout), userInfo: nil, repeats: false) }) } override func loadView() { let config = WKWebViewConfiguration() let prefs = WKPreferences() prefs.javaScriptEnabled = true config.preferences = prefs config.suppressesIncrementalRendering = false let userContentController = WKUserContentController() userContentController.add(self, name: "keyman") config.userContentController = userContentController webView = KeymanWebView(frame: CGRect(origin: .zero, size: keyboardSize), configuration: config) webView!.isOpaque = false webView!.translatesAutoresizingMaskIntoConstraints = false webView!.backgroundColor = UIColor.clear webView!.navigationDelegate = self webView!.scrollView.isScrollEnabled = false view = webView // Set UILongPressGestureRecognizer to show sub keys // let hold = UILongPressGestureRecognizer(target: self, action: #selector(self.holdAction)) // hold.minimumPressDuration = 0.5 // hold.delegate = self // view.addGestureRecognizer(hold) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) reloadKeyboard() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } // Very useful for immediately adjusting the WebView's properties upon loading. override func viewDidAppear(_ animated: Bool) { fixLayout() // Initialize the keyboard's size/scale. In iOS 13 (at least), the system // keyboard's width will be set at this stage, but not in viewWillAppear. keyboardSize = view.bounds.size } } // MARK: - JavaScript functions extension KeymanWebViewController { func languageMenuPosition(_ completion: @escaping (CGRect) -> Void) { webView!.evaluateJavaScript("langMenuPos();") { result, _ in guard let result = result as? String, !result.isEmpty else { return } let components = result.components(separatedBy: ",") let x = CGFloat(Float(components[0])!) let y = CGFloat(Float(components[1])!) let w = CGFloat(Float(components[2])!) let h = CGFloat(Float(components[3])!) completion(KeymanWebViewController.keyFrame(x: x, y: y, w: w, h: h)) } } // FIXME: text is unused in the JS func executePopupKey(id: String, text: String) { // Text must be checked for ', ", and \ characters; they must be escaped properly! do { let encodingArray = [ text ]; let jsonString = try String(data: JSONSerialization.data(withJSONObject: encodingArray), encoding: .utf8)! let start = jsonString.index(jsonString.startIndex, offsetBy: 2) let end = jsonString.index(jsonString.endIndex, offsetBy: -2) let escapedText = jsonString[start..<end] let cmd = "executePopupKey(\"\(id)\",\"\(escapedText)\");" webView!.evaluateJavaScript(cmd, completionHandler: nil) } catch { log.error(error) return } } func setOskWidth(_ width: Int) { webView?.evaluateJavaScript("setOskWidth(\(width));", completionHandler: nil) } func setOskHeight(_ height: Int) { webView?.evaluateJavaScript("setOskHeight(\(height));", completionHandler: nil) } func setPopupVisible(_ visible: Bool) { webView!.evaluateJavaScript("popupVisible(\(visible));", completionHandler: nil) } func setCursorRange(_ range: NSRange) { if range.location != NSNotFound { webView!.evaluateJavaScript("setCursorRange(\(range.location),\(range.length));", completionHandler: nil) self.currentCursorRange = range } } func setText(_ text: String?) { var text = text ?? "" // Remove any system-added LTR/RTL marks. text = text.replacingOccurrences(of: "\u{200e}", with: "") // Unicode's LTR codepoint text = text.replacingOccurrences(of: "\u{200f}", with: "") // Unicode's RTL codepoint (v1) text = text.replacingOccurrences(of: "\u{202e}", with: "") // Unicode's RTL codepoint (v2) // JavaScript escape-sequence encodings. text = text.replacingOccurrences(of: "\\", with: "\\\\") text = text.replacingOccurrences(of: "'", with: "\\'") text = text.replacingOccurrences(of: "\n", with: "\\n") self.currentText = text webView!.evaluateJavaScript("setKeymanVal('\(text)');", completionHandler: nil) } func resetContext() { webView!.evaluateJavaScript("keyman.core.resetContext();", completionHandler: nil) } func setDeviceType(_ idiom: UIUserInterfaceIdiom) { let type: String switch idiom { case .phone: type = "AppleMobile" case .pad: type = "AppleTablet" default: log.error("Unexpected interface idiom: \(idiom)") return } webView!.evaluateJavaScript("setDeviceType('\(type)');", completionHandler: nil) } private func fontObject(from font: Font?, keyboard: InstallableKeyboard, isOsk: Bool) -> [String: Any]? { guard let font = font else { return nil } // family does not have to match the name in the font file. It only has to be unique. return [ "family": "\(keyboard.id)__\(isOsk ? "osk" : "display")", "files": font.source.map { storage.fontURL(forResource: keyboard, filename: $0)!.absoluteString } ] } func setKeyboard(_ keyboard: InstallableKeyboard) { var stub: [String: Any] = [ "KI": "Keyboard_\(keyboard.id)", "KN": keyboard.name, "KLC": keyboard.languageID, "KL": keyboard.languageName, "KF": storage.keyboardURL(for: keyboard).absoluteString ] if let packageID = keyboard.packageID { stub["KP"] = packageID } let displayFont = fontObject(from: keyboard.font, keyboard: keyboard, isOsk: false) let oskFont = fontObject(from: keyboard.oskFont, keyboard: keyboard, isOsk: true) ?? displayFont if let displayFont = displayFont { stub["KFont"] = displayFont } if let oskFont = oskFont { stub["KOskFont"] = oskFont } let data: Data do { data = try JSONSerialization.data(withJSONObject: stub, options: []) } catch { log.error("Failed to serialize keyboard stub: \(error)") return } guard let stubString = String(data: data, encoding: .utf8) else { log.error("Failed to create stub string") return } log.debug("Keyboard stub: \(stubString)") webView!.evaluateJavaScript("setKeymanLanguage(\(stubString));", completionHandler: nil) } func deregisterLexicalModel(_ lexicalModel: InstallableLexicalModel) { webView!.evaluateJavaScript("keyman.modelManager.deregister(\"\(lexicalModel.id)\")") } func registerLexicalModel(_ lexicalModel: InstallableLexicalModel) { let stub: [String: Any] = [ "id": lexicalModel.id, "languages": [lexicalModel.languageID], // Change when InstallableLexicalModel is updated to store an array "path": storage.lexicalModelURL(for: lexicalModel).absoluteString ] let data: Data do { data = try JSONSerialization.data(withJSONObject: stub, options: []) } catch { log.error("Failed to serialize lexical model stub: \(error)") return } guard let stubString = String(data: data, encoding: .utf8) else { log.error("Failed to create stub string") return } log.debug("LexicalModel stub: \(stubString)") if lexicalModel.languageID == Manager.shared.currentKeyboardID?.languageID { // We're registering a lexical model for the now-current keyboard. // Enact any appropriate language-modeling settings! let userDefaults = Storage.active.userDefaults let predict = userDefaults.predictSettingForLanguage(languageID: lexicalModel.languageID) let correct = userDefaults.correctSettingForLanguage(languageID: lexicalModel.languageID) // Pass these off to KMW! // We do these first so that they're automatically set for the to-be-registered model in advance. webView!.evaluateJavaScript("enableSuggestions(\(stubString), \(predict), \(correct))") self.activeModel = predict } else { // We're registering a model in the background - don't change settings. webView!.evaluateJavaScript("keyman.registerModel(\(stubString));", completionHandler: nil) } setBannerHeight(to: Int(InputViewController.topBarHeight)) } func showBanner(_ display: Bool) { log.debug("Changing banner's alwaysShow property to \(display).") webView?.evaluateJavaScript("showBanner(\(display ? "true" : "false"))", completionHandler: nil) } func setBannerImage(to path: String) { bannerImgPath = path // Save the path in case delayed initializaiton is needed. var logString: String if path.contains("base64") || path.count > 256 { logString = "<base64 image>" } else { logString = path } log.debug("Banner image path: '\(logString).'") webView?.evaluateJavaScript("setBannerImage(\"\(path)\");", completionHandler: nil) } func setBannerHeight(to height: Int) { webView?.evaluateJavaScript("setBannerHeight(\(height));", completionHandler: nil) } /** * Ensures that the embedded KMW instance uses the app's current error-report toggle setting. * This is always called during keyboard page initialization and may also be called any time * thereafter for settings updates. */ func setSentryState(enabled: Bool = SentryManager.enabled) { // This may be called before the page - and thus the `sentryManager` variable - // is ready. It's a known limitation, so why log error reports for it? webView?.evaluateJavaScript("try { sentryManager.enabled = \(enabled ? "true" : "false") } catch(err) { }") } } // MARK: - WKScriptMessageHandler extension KeymanWebViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { guard let fragment = message.body as? String, !fragment.isEmpty else { return } if fragment.hasPrefix("#insertText-") { let dnRange = fragment.range(of: "+dn=")! let sRange = fragment.range(of: "+s=")! let drRange = fragment.range(of: "+dr=")! let dn = Int(fragment[dnRange.upperBound..<sRange.lowerBound])! let s = fragment[sRange.upperBound..<drRange.lowerBound] // This computes the number of requested right-deletion characters. // Use it when we're ready to implement that. // Our .insertText will need to be adjusted accordingly. _ = Int(fragment[drRange.upperBound...])! // KMW uses dn == -1 to perform special processing of deadkeys. // This is handled outside of Swift so we don't delete any characters. let numCharsToDelete = max(0, dn) let newText = String(s).stringFromUTF16CodeUnits() ?? "" insertText(self, numCharsToDelete: numCharsToDelete, newText: newText) delegate?.insertText(self, numCharsToDelete: numCharsToDelete, newText: newText) } else if fragment.hasPrefix("#showKeyPreview-") { let xKey = fragment.range(of: "+x=")! let yKey = fragment.range(of: "+y=")! let wKey = fragment.range(of: "+w=")! let hKey = fragment.range(of: "+h=")! let tKey = fragment.range(of: "+t=")! let x = CGFloat(Float(fragment[xKey.upperBound..<yKey.lowerBound])!) let y = CGFloat(Float(fragment[yKey.upperBound..<wKey.lowerBound])!) let w = CGFloat(Float(fragment[wKey.upperBound..<hKey.lowerBound])!) let h = CGFloat(Float(fragment[hKey.upperBound..<tKey.lowerBound])!) let t = String(fragment[tKey.upperBound...]) let frame = KeymanWebViewController.keyFrame(x: x, y: y, w: w, h: h) let preview = t.stringFromUTF16CodeUnits() ?? "" showKeyPreview(self, keyFrame: frame, preview: preview) delegate?.showKeyPreview(self, keyFrame: frame, preview: preview) } else if fragment.hasPrefix("#dismissKeyPreview-") { dismissKeyPreview(self) delegate?.dismissKeyPreview(self) } else if fragment.hasPrefix("#showMore-") { let baseFrameKey = fragment.range(of: "+baseFrame=")! let keysKey = fragment.range(of: "+keys=")! let fontKey = fragment.range(of: "+font=") let baseFrame = fragment[baseFrameKey.upperBound..<keysKey.lowerBound] let keys = fragment[keysKey.upperBound..<(fontKey?.lowerBound ?? fragment.endIndex)] let useSpecialFont = fontKey != nil let frameComponents = baseFrame.components(separatedBy: ",") let x = CGFloat(Float(frameComponents[0])!) let y = CGFloat(Float(frameComponents[1])!) let w = CGFloat(Float(frameComponents[2])!) let h = CGFloat(Float(frameComponents[3])!) let frame = KeymanWebViewController.keyFrame(x: x, y: y, w: w, h: h) let keyArray = keys.components(separatedBy: ";") var subkeyIDs: [String] = [] var subkeyTexts: [String] = [] for key in keyArray { let values = key.components(separatedBy: ":") switch values.count { case 1: let id = values[0] subkeyIDs.append(id) // id is in the form layer-keyID. We only process keyIDs with prefix U_. if let index = id.range(of: "-U_", options: .backwards)?.upperBound, let codepoint = UInt32(id[index...], radix: 16), let scalar = Unicode.Scalar(codepoint) { subkeyTexts.append(String(Character(scalar))) } else { subkeyTexts.append("") } case 2: subkeyIDs.append(values[0]) subkeyTexts.append(values[1].stringFromUTF16CodeUnits() ?? "") default: log.warning("Unexpected subkey key: \(key)") } } showSubkeys(self, keyFrame: frame, subkeyIDs: subkeyIDs, subkeyTexts: subkeyTexts, useSpecialFont: useSpecialFont) delegate?.showSubkeys(self, keyFrame: frame, subkeyIDs: subkeyIDs, subkeyTexts: subkeyTexts, useSpecialFont: useSpecialFont) self.touchHoldBegan() } else if fragment.hasPrefix("#menuKeyDown-") { perform(#selector(self.menuKeyHeld), with: self, afterDelay: 0.5) menuKeyDown(self) delegate?.menuKeyDown(self) } else if fragment.hasPrefix("#menuKeyUp-") { // Blocks summoning the globe-key menu for quick taps. (Hence the 0.5 delay.) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.menuKeyHeld), object: self) menuKeyUp(self) delegate?.menuKeyUp(self) } else if fragment.hasPrefix("#hideKeyboard-") { hideKeyboard(self) Manager.shared.hideKeyboard() } else if fragment.hasPrefix("ios-log:#iOS#") { let message = fragment.dropFirst(13) log.info("KMW Log: \(message)") } else if fragment.hasPrefix("#beep-") { beep(self) delegate?.beep(self) } else if fragment.hasPrefix("#suggestPopup"){ let cmdKey = fragment.range(of: "+cmd=")! let cmdStr = fragment[cmdKey.upperBound..<fragment.endIndex] let cmdData = cmdStr.data(using: .utf16) let decoder = JSONDecoder() do { let cmd = try decoder.decode(SuggestionPopup.self, from: cmdData!) log.verbose("Longpress detected on suggestion: \"\(cmd.suggestion.displayAs)\".") } catch { log.error("Unexpected JSON parse error: \(error).") } // Will need processing upon extraction from the resulting object. // let frameComponents = baseFrame.components(separatedBy: ",") // let x = CGFloat(Float(frameComponents[0])!) // let y = CGFloat(Float(frameComponents[1])!) // let w = CGFloat(Float(frameComponents[2])!) // let h = CGFloat(Float(frameComponents[3])!) // let frame = KeymanWebViewController.keyFrame(x: x, y: y, w: w, h: h) } else { log.error("Unexpected KMW event: \(fragment)") } } private static func keyFrame(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) -> CGRect { return CGRect(x: x - (w/2), y: y, width: w, height: h) } public func beep(_ keymanWeb: KeymanWebViewController) { let vibrationSupport = Manager.shared.vibrationSupportLevel let kSystemSoundID_MediumVibrate: SystemSoundID = 1520 if vibrationSupport == .none { // TODO: Find something we can do visually and/or audibly to provide feedback. } else if vibrationSupport == .basic { // The publicly-suggested kSystemSoundID_Vibrate lasts for 0.4 seconds. // Better than nothing, though it's easily too long for a proper beep. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } else if vibrationSupport == .basic_plus { // Code 1519 is near-undocumented, but should result in a 'weaker'/shorter vibration. // Corresponds directly to UIImpactFeedbackGenerator below, but on select phones that // don't support that part of the API. // // Ref: https://stackoverflow.com/questions/10570553/how-to-set-iphone-vibrate-length/44495798#44495798 // Not usable by older iPhone models. AudioServicesPlaySystemSound(kSystemSoundID_MediumVibrate) } else { // if vibrationSupport == .taptic if #available(iOSApplicationExtension 10.0, *) { // Available with iPhone 7 and beyond, we can now produce nicely customized haptic feedback. // We use this style b/c it's short, and in essence it is a minor UI element collision - // a single key with blocked (erroneous) output. // Oddly, is a closer match to SystemSoundID 1520 than 1521. let vibrator = UIImpactFeedbackGenerator(style: UIImpactFeedbackGenerator.FeedbackStyle.heavy) vibrator.impactOccurred() } else { // Fallback on earlier feedback style AudioServicesPlaySystemSound(kSystemSoundID_MediumVibrate) } } } } // MARK: - WKNavigationDelegate extension KeymanWebViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { guard let url = webView.url else { return } guard url.lastPathComponent == Resources.kmwFilename && (url.fragment?.isEmpty ?? true) else { return } keyboardLoaded(self) delegate?.keyboardLoaded(self) } } // MARK: - KeymanWebDelegate extension KeymanWebViewController: KeymanWebDelegate { func keyboardLoaded(_ keymanWeb: KeymanWebViewController) { delegate?.keyboardLoaded(keymanWeb) isLoading = false log.info("Loaded keyboard.") self.setSentryState() resizeKeyboard() // There may have been attempts to set these values before the keyboard loaded! self.setText(self.currentText) if let cursorRange = self.currentCursorRange { self.setCursorRange(cursorRange) } setDeviceType(UIDevice.current.userInterfaceIdiom) let shouldReloadKeyboard = Manager.shared.shouldReloadKeyboard var newKb = Manager.shared.currentKeyboard if !shouldReloadKeyboard { // otherwise, we automatically reload anyway. let userData = Manager.shared.isSystemKeyboard ? UserDefaults.standard : Storage.active.userDefaults if newKb == nil { if let id = userData.currentKeyboardID { if let kb = Storage.active.userDefaults.userKeyboard(withFullID: id) { newKb = kb } } // Failsafe in case the previous lookup fails - at least load A keyboard. if newKb == nil, let userKbs = Storage.active.userDefaults.userKeyboards, !userKbs.isEmpty { newKb = userKbs[0] } } log.info("Setting initial keyboard.") _ = Manager.shared.setKeyboard(newKb!) } // in case `shouldReloadKeyboard == true`. Is set otherwise above. if(newKb == nil) { newKb = Defaults.keyboard } updateShowBannerSetting() setBannerImage(to: bannerImgPath) // Reset the keyboard's size. keyboardSize = kbSize fixLayout() NotificationCenter.default.post(name: Notifications.keyboardLoaded, object: self, value: newKb!) if shouldReloadKeyboard { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.resetKeyboard), object: nil) perform(#selector(self.resetKeyboard), with: nil, afterDelay: 0.25) Manager.shared.shouldReloadKeyboard = false } } func updateShowBannerSetting() { let userData = Storage.active.userDefaults let alwaysShow = userData.bool(forKey: Key.optShouldShowBanner) if !Manager.shared.isSystemKeyboard { showBanner(false) } else { showBanner(alwaysShow) } } func insertText(_ view: KeymanWebViewController, numCharsToDelete: Int, newText: String) { dismissHelpBubble() Manager.shared.isKeymanHelpOn = false } func showKeyPreview(_ view: KeymanWebViewController, keyFrame: CGRect, preview: String) { if UIDevice.current.userInterfaceIdiom == .pad || isSubKeysMenuVisible { return } dismissKeyPreview() clearSubKeyArrays() keyPreviewView = KeyPreviewView(frame: keyFrame) keyPreviewView!.setLabelText(preview) let oskFontName = Manager.shared.oskFontNameForKeyboard(withFullID: Manager.shared.currentKeyboardID!) ?? Manager.shared.fontNameForKeyboard(withFullID: Manager.shared.currentKeyboardID!) keyPreviewView!.setLabelFont(oskFontName) self.view.addSubview(keyPreviewView!) } func dismissKeyPreview(_ view: KeymanWebViewController) { if UIDevice.current.userInterfaceIdiom == .pad || keyPreviewView == nil { return } let dismissKeyPreview = #selector(self.dismissKeyPreview as () -> Void) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: dismissKeyPreview, object: nil) perform(dismissKeyPreview, with: nil, afterDelay: 0.1) clearSubKeyArrays() } func showSubkeys(_ view: KeymanWebViewController, keyFrame: CGRect, subkeyIDs: [String], subkeyTexts: [String], useSpecialFont: Bool) { dismissHelpBubble() Manager.shared.isKeymanHelpOn = false dismissSubKeys() dismissKeyboardMenu() subKeyAnchor = keyFrame subKeyIDs = subkeyIDs subKeyTexts = subkeyTexts self.useSpecialFont = useSpecialFont } func menuKeyUp(_ view: KeymanWebViewController) { dismissHelpBubble() Manager.shared.isKeymanHelpOn = false if Util.isSystemKeyboard { let userData = UserDefaults.standard userData.set(true, forKey: Key.keyboardPickerDisplayed) userData.synchronize() } } func hideKeyboard(_ view: KeymanWebViewController) { dismissHelpBubble() dismissSubKeys() dismissKeyboardMenu() } } // MARK: - UIGestureRecognizerDelegate extension KeymanWebViewController: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } // An adaptation of holdAction, just for direct taps. @objc func tapAction(_ sender: UITapGestureRecognizer) { switch sender.state { case .ended: // Touch Ended guard let subKeysView = subKeysView else { return } let touchPoint = sender.location(in: subKeysView.containerView) var buttonClicked = false for button in subKeys { if button.frame.contains(touchPoint) { button.isEnabled = true button.isHighlighted = true button.backgroundColor = subKeyColorHighlighted button.sendActions(for: .touchUpInside) buttonClicked = true } else { button.isHighlighted = false button.isEnabled = false button.backgroundColor = subKeyColor } } if !buttonClicked { clearSubKeyArrays() } default: return } } @objc func holdAction(_ sender: UILongPressGestureRecognizer) { switch sender.state { case .ended: // Touch Ended if let subKeysView = subKeysView { subKeysView.removeFromSuperview() subKeysView.subviews.forEach { $0.removeFromSuperview() } self.subKeysView = nil setPopupVisible(false) } var buttonClicked = false for button in subKeys where button.isHighlighted { button.isHighlighted = false button.backgroundColor = subKeyColor button.isEnabled = false button.sendActions(for: .touchUpInside) buttonClicked = true break } if !buttonClicked { clearSubKeyArrays() } case .began: // // Touch & Hold Began // let touchPoint = sender.location(in: sender.view) // // Check if touch was for language menu button // languageMenuPosition { keyFrame in // if keyFrame.contains(touchPoint) { // self.delegate?.menuKeyHeld(self) // return // } // self.touchHoldBegan() // } return default: // Hold & Move guard let subKeysView = subKeysView else { return } let touchPoint = sender.location(in: subKeysView.containerView) for button in subKeys { if button.frame.contains(touchPoint) { button.isEnabled = true button.isHighlighted = true button.backgroundColor = subKeyColorHighlighted } else { button.isHighlighted = false button.isEnabled = false button.backgroundColor = subKeyColor } } } } private func touchHoldBegan() { // Is also called for banner longpresses. Will need a way to properly differentiate. let isPad = UIDevice.current.userInterfaceIdiom == .pad let fontSize = isPad ? UIFont.buttonFontSize * 2 : UIFont.buttonFontSize let oskFontName = Manager.shared.oskFontNameForKeyboard(withFullID: Manager.shared.currentKeyboardID!) ?? Manager.shared.fontNameForKeyboard(withFullID: Manager.shared.currentKeyboardID!) if subKeyIDs.isEmpty { subKeys = [] return } subKeys = subKeyTexts.enumerated().map { i, subKeyText in let button = UIButton(type: .custom) button.tag = i button.backgroundColor = subKeyColor button.setRoundedBorder(withRadius: 4.0, borderWidth: 1.0, color: .gray) button.setTitleColor(Colors.keyText, for: .disabled) button.setTitleColor(Colors.keyText, for: .highlighted) button.setTitleColor(Colors.keyText, for: .normal) if let oskFontName = oskFontName { button.titleLabel?.font = UIFont(name: oskFontName, size: fontSize) } else { button.titleLabel?.font = UIFont.systemFont(ofSize: fontSize) } if useSpecialFont{ if FontManager.shared.registerFont(at: Storage.active.specialOSKFontURL), let fontName = FontManager.shared.fontName(at: Storage.active.specialOSKFontURL) { button.titleLabel?.font = UIFont(name: fontName, size: fontSize) } button.setTitleColor(.gray, for: .disabled) } button.addTarget(self, action: #selector(subKeyButtonClick), for: .touchUpInside) // Detect the text width for subkeys. The 'as Any' silences an inappropriate warning from Swift. let textSize = subKeyText.size(withAttributes: [NSAttributedString.Key.font: button.titleLabel?.font! as Any]) var displayText = subKeyText if textSize.width <= 0 && subKeyText.count > 0 { // It's probably a diacritic in need of a combining character! // Also check if the language is RTL! if Manager.shared.currentKeyboard?.isRTL ?? false { displayText = "\u{200f}\u{25cc}" + subKeyText } else { displayText = "\u{25cc}" + subKeyText } } button.setTitle(displayText, for: .normal) button.tintColor = Colors.popupKeyTint button.isEnabled = false return button } dismissKeyPreview() subKeysView = SubKeysView(keyFrame: subKeyAnchor, subKeys: subKeys) view.addSubview(subKeysView!) let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapAction)) subKeysView!.addGestureRecognizer(tap) let hold = UILongPressGestureRecognizer(target: self, action: #selector(self.holdAction)) hold.minimumPressDuration = 0.01 hold.delegate = self subKeysView!.addGestureRecognizer(hold) setPopupVisible(true) } @objc func menuKeyHeld(_ keymanWeb: KeymanWebViewController) { self.delegate?.menuKeyHeld(self) } @objc func subKeyButtonClick(_ sender: UIButton) { let keyIndex = sender.tag if keyIndex < subKeyIDs.count && keyIndex < subKeyTexts.count { let subKeyID = subKeyIDs[keyIndex] let subKeyText = subKeyTexts[keyIndex] executePopupKey(id: subKeyID, text: subKeyText) } subKeys.removeAll() subKeyIDs.removeAll() subKeyTexts.removeAll() } } // MARK: - Manage views extension KeymanWebViewController { // MARK: - Sizing public var keyboardHeight: CGFloat { return keyboardSize.height } func constraintTargetHeight(isPortrait: Bool) -> CGFloat { return KeyboardScaleMap.getDeviceDefaultKeyboardScale(forPortrait: isPortrait)?.keyboardHeight ?? 216 // default for ancient devices } var keyboardWidth: CGFloat { return keyboardSize.width } func initKeyboardSize() { var width: CGFloat var height: CGFloat width = UIScreen.main.bounds.width if Util.isSystemKeyboard { height = constraintTargetHeight(isPortrait: InputViewController.isPortrait) } else { height = constraintTargetHeight(isPortrait: UIDevice.current.orientation.isPortrait) } keyboardSize = CGSize(width: width, height: height) } var keyboardSize: CGSize { get { if kbSize.equalTo(CGSize.zero) { initKeyboardSize() } return kbSize } set(size) { // Only perform set management code if the size values has actually changed. // We tend to get a lot of noise on this, so filtering like this also helps increase // stability and performance. // // Note that since viewWillLayoutSubviews is triggered by touch events (for some reason) as // well as view transitions, this helps to prevent issues that arise from replacing the OSK // on touch events that would otherwise occur - at present, a resize operation in KMW // automatically replaces the OSK. if kbSize != size { kbSize = size setOskWidth(Int(size.width)) setOskHeight(Int(size.height)) } } } @objc func resizeDelay() { // + 1000 to work around iOS bug with resizing on landscape orientation. Technically we only // need this for landscape but it doesn't hurt to do it with both. 1000 is a big number that // should hopefully work on all devices. let kbWidth = keyboardWidth let kbHeight = keyboardHeight view.frame = CGRect(x: 0.0, y: 0.0, width: kbWidth, height: kbHeight + 1000) } // Keyman interaction func resizeKeyboard() { fixLayout() // Ensures the width and height are properly updated. // Note: System Keyboard init currently requires this for the keyboard to display properly // the first time. setOskWidth(Int(kbSize.width)) setOskHeight(Int(kbSize.height)) } func resetKeyboardState() { dismissSubKeys() dismissKeyPreview() dismissKeyboardMenu() resizeKeyboard() } // Used for a selector; keep @objc! @objc func resetKeyboard() { let keyboard = Manager.shared.currentKeyboard Manager.shared.currentKeyboardID = nil if let keyboard = keyboard { log.info("Current keyboard is set.") _ = Manager.shared.setKeyboard(keyboard) } else if let keyboard = Storage.active.userDefaults.userKeyboards?[safe: 0] { log.info("Using user's default keyboard.") _ = Manager.shared.setKeyboard(keyboard) } else { log.info("Using app-default keyboard.") _ = Manager.shared.setKeyboard(Defaults.keyboard) } } // MARK: - Show/hide views func reloadKeyboard() { webView!.loadFileURL(Storage.active.kmwURL, allowingReadAccessTo: Storage.active.baseDir) isLoading = true // Check for a change of "always show banner" state updateShowBannerSetting() } /* * Implemented as a workaround for a weird bug (likely within iOS) in which the * InputViewController and KeymanWebViewController constructors (and thus, `loadView`) * are sometimes completely bypassed during system-keyboard use. * See https://github.com/keymanapp/keyman/issues/3985 */ func verifyLoaded() { // Test: are we currently loading? If so, don't worry 'bout a thing. if !isLoading { webView!.evaluateJavaScript("verifyLoaded()", completionHandler: nil) } } @objc func showHelpBubble() { // Help bubble is always disabled for system-wide keyboard if Util.isSystemKeyboard || keyboardMenuView != nil { return } languageMenuPosition { keyFrame in // We should calculate the center point between the origin and the right-hand coordinate of the key. // keyFrame.origin seems to use the left-hand (minX) edge, which looks ugly. Y coord's good, though. let tipRootPoint = CGPoint(x: keyFrame.midX, y: keyFrame.origin.y) self.showHelpBubble(at: tipRootPoint) } } // TODO: The bulk of this should be moved to PopoverView private func showHelpBubble(at point: CGPoint) { self.helpBubbleView?.removeFromSuperview() let helpBubbleView = PopoverView(frame: CGRect.zero) self.helpBubbleView = helpBubbleView helpBubbleView.backgroundColor = Colors.helpBubbleGradient1 helpBubbleView.backgroundColor2 = Colors.helpBubbleGradient2 helpBubbleView.borderColor = Colors.popupBorder let isPad = UIDevice.current.userInterfaceIdiom == .pad let sizeMultiplier = CGFloat(isPad ? 1.5 : 1.0) let frameWidth = 90.0 * sizeMultiplier let frameHeight = (40.0 + helpBubbleView.arrowHeight) * sizeMultiplier let fontSize = 10.0 * sizeMultiplier let inputViewFrame = view.frame let screenWidth = inputViewFrame.size.width // TODO: Refactor this out let isPortrait = UIDevice.current.orientation.isPortrait let adjY: CGFloat if isPortrait { adjY = Util.isSystemKeyboard ? 9.0 : 4.0 } else { adjY = Util.isSystemKeyboard ? 3.0 : 4.0 } let px = point.x let py = point.y + adjY + (isPad ? 2.0 : 1.0) var x = px - frameWidth / 2 let y = py - frameHeight if x < 0 { x = 0 } else if x + frameWidth > screenWidth { x = screenWidth - frameWidth } helpBubbleView.frame = CGRect(x: x, y: y, width: frameWidth, height: frameHeight) if x == 0 { helpBubbleView.arrowPosX = px } else if x == screenWidth - frameWidth { helpBubbleView.arrowPosX = (px - x) } else { helpBubbleView.arrowPosX = frameWidth / 2 } let helpText = UILabel(frame: CGRect(x: 5, y: 0, width: frameWidth - 10, height: frameHeight - helpBubbleView.arrowHeight)) helpText.backgroundColor = UIColor.clear helpText.font = helpText.font.withSize(fontSize) helpText.textAlignment = .center //helpText.textColor = UIColor.darkText helpText.lineBreakMode = .byWordWrapping helpText.numberOfLines = 0 helpText.text = keyboardChangeHelpText helpBubbleView.addSubview(helpText) view.addSubview(helpBubbleView) } func dismissHelpBubble() { helpBubbleView?.removeFromSuperview() helpBubbleView = nil } @objc func dismissKeyPreview() { keyPreviewView?.removeFromSuperview() keyPreviewView = nil } var isSubKeysMenuVisible: Bool { return subKeysView != nil } func dismissSubKeys() { if let subKeysView = subKeysView { subKeysView.removeFromSuperview() subKeysView.subviews.forEach { $0.removeFromSuperview() } self.subKeysView = nil setPopupVisible(false) } clearSubKeyArrays() } func clearSubKeyArrays() { if subKeysView == nil { subKeys.removeAll() subKeyIDs.removeAll() subKeyTexts.removeAll() } } func showHelpBubble(afterDelay delay: TimeInterval) { helpBubbleView?.removeFromSuperview() let showHelpBubble = #selector(self.showHelpBubble as () -> Void) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: showHelpBubble, object: nil) perform(showHelpBubble, with: nil, afterDelay: delay) } func showKeyboardMenu(_ ic: InputViewController, closeButtonTitle: String?) { let parentView = ic.view ?? view languageMenuPosition { keyFrame in if keyFrame != .zero { self.keyboardMenuView?.removeFromSuperview() self.keyboardMenuView = KeyboardMenuView(keyFrame: keyFrame, inputViewController: ic, closeButtonTitle: closeButtonTitle) parentView?.addSubview(self.keyboardMenuView!) self.keyboardMenuView!.flashScrollIndicators() } } } func dismissKeyboardMenu() { keyboardMenuView?.removeFromSuperview() keyboardMenuView = nil } var isKeyboardMenuVisible: Bool { return keyboardMenuView != nil } } // MARK: - Keyboard Notifications extension KeymanWebViewController { @objc func keyboardWillShow(_ notification: Notification) { dismissSubKeys() dismissKeyPreview() resizeKeyboard() if Manager.shared.isKeymanHelpOn { showHelpBubble(afterDelay: 1.5) } } @objc func keyboardWillHide(_ notification: Notification) { dismissHelpBubble() dismissSubKeys() dismissKeyPreview() } }
35.918455
142
0.676114
915568eb2ec34e1d012be0bfe97b86e23bf56a19
297
// // UIApplication+RootViewController.swift // // // Created by MohammadReza Ansary on 2/28/21. // import XCTest import UIKit @testable import ExtensionKit final class UIApplication_RootViewControllerTests: XCTestCase { } // Unfortunately i found no way to test UIApplication extensions.
18.5625
65
0.771044
ab746c48b10a079455fc0ab95fbcb77c05d896ff
669
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "TagsView", platforms: [ .macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), ], products: [ .library( name: "TagsView", targets: ["TagsView"] ), ], dependencies: [ ], targets: [ .target( name: "TagsView", dependencies: [] ), .testTarget( name: "TagsViewTests", dependencies: ["TagsView"] ), ] )
20.272727
96
0.493274
e4e744a3bacfdae6e83f60633c276575d689f8f0
943
// Copyright 2017 Esri. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS open class MapViewController: UIViewController { public let mapView = AGSMapView(frame: CGRect.zero) override open func viewDidLoad() { super.viewDidLoad() mapView.frame = view.bounds mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(mapView) } }
30.419355
75
0.715801
291777fab8ab9b737a8950b368413c6d469f3c5e
26,907
// // JTACMonthLayout.swift // // Copyright (c) 2016-2020 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar) // // 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 UIKit /// Methods in this class are meant to be overridden and will be called by its collection view to gather layout information. class JTACMonthLayout: UICollectionViewLayout, JTACMonthLayoutProtocol { var allowsDateCellStretching = true var firstContentOffsetWasSet = false var lastSetCollectionViewSize: CGRect = .zero var cellSize: CGSize = CGSize.zero var shouldUseUserItemSizeInsteadOfDefault: Bool { return delegate.cellSize == 0 ? false: true } var scrollDirection: UICollectionView.ScrollDirection = .horizontal var maxMissCount: Int = 0 var cellCache: [Int: [(item: Int, section: Int, xOffset: CGFloat, yOffset: CGFloat, width: CGFloat, height: CGFloat)]] = [:] var headerCache: [Int: (item: Int, section: Int, xOffset: CGFloat, yOffset: CGFloat, width: CGFloat, height: CGFloat)] = [:] var decorationCache: [IndexPath:UICollectionViewLayoutAttributes] = [:] var endOfSectionOffsets: [CGFloat] = [] var lastWrittenCellAttribute: (Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)! var xStride: CGFloat = 0 var minimumInteritemSpacing: CGFloat = 0 var minimumLineSpacing: CGFloat = 0 var sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) var headerSizes: [AnyHashable:CGFloat] = [:] var focusIndexPath: IndexPath? var isCalendarLayoutLoaded: Bool { return !cellCache.isEmpty } var layoutIsReadyToBePrepared: Bool { return !(!cellCache.isEmpty || delegate.calendarDataSource == nil) } var monthMap: [Int: Int] = [:] var numberOfRows: Int = 0 var strictBoundaryRulesShouldApply: Bool = false var thereAreHeaders: Bool { return !headerSizes.isEmpty } var thereAreDecorationViews = false weak var delegate: JTACMonthDelegateProtocol! var currentHeader: (section: Int, size: CGSize)? // Tracks the current header size var currentCell: (section: Int, width: CGFloat, height: CGFloat)? // Tracks the current cell size var contentHeight: CGFloat = 0 // Content height of calendarView var contentWidth: CGFloat = 0 // Content wifth of calendarView var xCellOffset: CGFloat = 0 var yCellOffset: CGFloat = 0 var endSeparator: CGFloat = 0 override var flipsHorizontallyInOppositeLayoutDirection: Bool { return true } var delayedExecutionClosure: [(() -> Void)] = [] func executeDelayedTasks() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { let tasksToExecute = self.delayedExecutionClosure self.delayedExecutionClosure.removeAll() for aTaskToExecute in tasksToExecute { aTaskToExecute() } } } var daysInSection: [Int: Int] = [:] // temporary caching var monthInfo: [Month] = [] var reloadWasTriggered = false var isDirty: Bool { return updatedLayoutCellSize != cellSize } var updatedLayoutCellSize: CGSize { guard let cachedConfiguration = delegate._cachedConfiguration else { return .zero } // Default Item height and width var height: CGFloat = collectionView!.bounds.size.height / CGFloat(cachedConfiguration.numberOfRows) var width: CGFloat = collectionView!.bounds.size.width / CGFloat(maxNumberOfDaysInWeek) if shouldUseUserItemSizeInsteadOfDefault { // If delegate item size was set if scrollDirection == .horizontal { width = delegate.cellSize } else { height = delegate.cellSize } } return CGSize(width: width, height: height) } open override func register(_ nib: UINib?, forDecorationViewOfKind elementKind: String) { super.register(nib, forDecorationViewOfKind: elementKind) thereAreDecorationViews = true } open override func register(_ viewClass: AnyClass?, forDecorationViewOfKind elementKind: String) { super.register(viewClass, forDecorationViewOfKind: elementKind) thereAreDecorationViews = true } init(withDelegate delegate: JTACMonthDelegateProtocol) { super.init() self.delegate = delegate } /// Tells the layout object to update the current layout. open override func prepare() { // set the last content size before the if statement which can possible return if layout is not yet ready to be prepared. Avoids inf loop // with layout subviews lastSetCollectionViewSize = collectionView!.frame if !layoutIsReadyToBePrepared { // Layoout may not be ready, but user might have reloaded with an anchor date let requestedOffset = delegate.requestedContentOffset if requestedOffset != .zero { collectionView!.setContentOffset(requestedOffset, animated: false) } // execute any other delayed tasks executeDelayedTasks() return } setupDataFromDelegate() if scrollDirection == .vertical { configureVerticalLayout() } else { configureHorizontalLayout() } // Get rid of header data if dev didnt register headers. // They were used for calculation but are not needed to be displayed if !thereAreHeaders { headerCache.removeAll() } // Set the first content offset only once. This will prevent scrolling animation on viewDidload. if !firstContentOffsetWasSet { firstContentOffsetWasSet = true let firstContentOffset = delegate.requestedContentOffset collectionView!.setContentOffset(firstContentOffset, animated: false) } daysInSection.removeAll() // Clear chache reloadWasTriggered = false executeDelayedTasks() } func setupDataFromDelegate() { // get information from the delegate headerSizes = delegate.sizesForMonthSection() // update first. Other variables below depend on it strictBoundaryRulesShouldApply = thereAreHeaders || delegate._cachedConfiguration.hasStrictBoundaries numberOfRows = delegate._cachedConfiguration.numberOfRows monthMap = delegate.monthMap allowsDateCellStretching = delegate.allowsDateCellStretching monthInfo = delegate.monthInfo scrollDirection = delegate.scrollDirection maxMissCount = scrollDirection == .horizontal ? maxNumberOfRowsPerMonth : maxNumberOfDaysInWeek minimumInteritemSpacing = delegate.minimumInteritemSpacing minimumLineSpacing = delegate.minimumLineSpacing sectionInset = delegate.sectionInset cellSize = updatedLayoutCellSize } func indexPath(direction: SegmentDestination, of section:Int, item: Int) -> IndexPath? { var retval: IndexPath? switch direction { case .next: if let data = cellCache[section], !data.isEmpty, 0..<data.count ~= item + 1 { retval = IndexPath(item: item + 1, section: section) } else if let data = cellCache[section + 1], !data.isEmpty { retval = IndexPath(item: 0, section: section + 1) } case .previous: if let data = cellCache[section], !data.isEmpty, 0..<data.count ~= item - 1 { retval = IndexPath(item: item - 1, section: section) } else if let data = cellCache[section - 1], !data.isEmpty { retval = IndexPath(item: data.count - 1, section: section - 1) } default: break } return retval } /// Returns the width and height of the collection view’s contents. /// The width and height of the collection view’s contents. open override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: contentHeight) } override func invalidateLayout() { super.invalidateLayout() if isDirty && reloadWasTriggered { clearCache() } } /// Returns the layout attributes for all of the cells /// and views in the specified rectangle. override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let startSectionIndex = startIndexFrom(rectOrigin: rect.origin) // keep looping until there were no interception rects var attributes: [UICollectionViewLayoutAttributes] = [] var beganIntercepting = false var missCount = 0 outterLoop: for sectionIndex in startSectionIndex..<cellCache.count { if let validSection = cellCache[sectionIndex], !validSection.isEmpty { if thereAreDecorationViews { let attrib = layoutAttributesForDecorationView(ofKind: decorationViewID, at: IndexPath(item: 0, section: sectionIndex))! attributes.append(attrib) } // Add header view attributes if thereAreHeaders { let data = headerCache[sectionIndex]! if CGRect(x: data.xOffset, y: data.yOffset, width: data.width, height: data.height).intersects(rect) { let attrib = layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: IndexPath(item: data.item, section: data.section)) attributes.append(attrib!) } } for val in validSection { if CGRect(x: val.xOffset, y: val.yOffset, width: val.width, height: val.height).intersects(rect) { missCount = 0 beganIntercepting = true let attrib = layoutAttributesForItem(at: IndexPath(item: val.item, section: val.section)) attributes.append(attrib!) } else { missCount += 1 // If there are at least 8 misses in a row // since intercepting began, then this // section has no more interceptions. // So break if missCount > maxMissCount && beganIntercepting { break outterLoop } } } } } return attributes } /// Returns the layout attributes for the item at the specified index /// path. A layout attributes object containing the information to apply /// to the item’s cell. override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { // If this index is already cached, then return it else, // apply a new layout attribut to it if let alreadyCachedCellAttrib = cellAttributeFor(indexPath.item, section: indexPath.section) { return alreadyCachedCellAttrib } return nil } func supplementaryAttributeFor(item: Int, section: Int, elementKind: String) -> UICollectionViewLayoutAttributes? { var retval: UICollectionViewLayoutAttributes? if let cachedData = headerCache[section] { let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: IndexPath(item: item, section: section)) attributes.frame = CGRect(x: cachedData.xOffset, y: cachedData.yOffset, width: cachedData.width, height: cachedData.height) retval = attributes } return retval } func cachedValue(for item: Int, section: Int) -> (item: Int, section: Int, xOffset: CGFloat, yOffset: CGFloat, width: CGFloat, height: CGFloat)? { if let alreadyCachedCellAttrib = cellCache[section], item < alreadyCachedCellAttrib.count, item >= 0 { return alreadyCachedCellAttrib[item] } return nil } func sizeOfSection(_ section: Int) -> CGFloat { guard let cellOfSection = cellCache[section]?.first else { return 0 } var offSet: CGFloat if scrollDirection == .horizontal { offSet = cellOfSection.width * 7 } else { offSet = cellOfSection.height * CGFloat(numberOfDaysInSection(section)) if thereAreHeaders, let headerHeight = headerCache[section]?.height { offSet += headerHeight } } let startOfSection = endOfSectionOffsets[section] let endOfSection = endOfSectionOffsets[section + 1] return endOfSection - startOfSection } func frameOfVerticalSection(_ section: Int) -> CGRect { let endOfSection = endOfSectionOffsets[section].rounded() let sectionSize = trueSizeOfContentForSection(section) return CGRect(x: sectionInset.left, y: endOfSection - sectionSize.height, width: sectionSize.width, height: sectionSize.height) } func cellAttributeFor(_ item: Int, section: Int) -> UICollectionViewLayoutAttributes? { guard let cachedValue = cachedValue(for: item, section: section) else { return nil } let attrib = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: item, section: section)) attrib.frame = CGRect(x: cachedValue.xOffset, y: cachedValue.yOffset, width: cachedValue.width, height: cachedValue.height) if minimumInteritemSpacing > -1, minimumLineSpacing > -1 { var frame = attrib.frame.insetBy(dx: minimumInteritemSpacing, dy: minimumLineSpacing) if frame == .null { frame = attrib.frame.insetBy(dx: 0, dy: 0) } attrib.frame = frame } return attrib } func determineToApplyAttribs(_ item: Int, section: Int) -> (item: Int, section: Int, xOffset: CGFloat, yOffset: CGFloat, width: CGFloat, height: CGFloat)? { let monthIndex = monthMap[section]! let numberOfDays = numberOfDaysInSection(monthIndex) // return nil on invalid range if !(0...monthMap.count ~= section) || !(0...numberOfDays ~= item) { return nil } let size = sizeForitemAtIndexPath(item, section: section) let y = scrollDirection == .horizontal ? yCellOffset + sectionInset.top : yCellOffset return (item, section, xCellOffset + xStride, y, size.width, size.height) } func determineToApplySupplementaryAttribs(_ item: Int, section: Int) -> (item: Int, section: Int, xOffset: CGFloat, yOffset: CGFloat, width: CGFloat, height: CGFloat)? { var retval: (item: Int, section: Int, xOffset: CGFloat, yOffset: CGFloat, width: CGFloat, height: CGFloat)? let headerHeight = cachedHeaderHeightForSection(section) switch scrollDirection { case .horizontal: let modifiedSize = sizeForitemAtIndexPath(item, section: section) let width = (modifiedSize.width * 7) retval = (item, section, contentWidth + sectionInset.left, sectionInset.top, width , headerHeight) case .vertical: // Use the calculaed header size and force the width // of the header to take up 7 columns // We cache the header here so we dont call the // delegate so much fallthrough default: let modifiedSize = (width: collectionView!.frame.width, height: headerHeight) retval = (item, section, sectionInset.left, yCellOffset , modifiedSize.width - (sectionInset.left + sectionInset.right), modifiedSize.height) } if retval?.width == 0, retval?.height == 0 { return nil } return retval } open override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let alreadyCachedVal = decorationCache[indexPath] { return alreadyCachedVal } let retval = UICollectionViewLayoutAttributes(forDecorationViewOfKind: decorationViewID, with: indexPath) decorationCache[indexPath] = retval retval.frame = delegate.sizeOfDecorationView(indexPath: indexPath) retval.zIndex = -1 return retval } /// Returns the layout attributes for the specified supplementary view. open override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let alreadyCachedHeaderAttrib = supplementaryAttributeFor(item: indexPath.item, section: indexPath.section, elementKind: elementKind) { return alreadyCachedHeaderAttrib } return nil } func numberOfDaysInSection(_ index: Int) -> Int { if let days = daysInSection[index] { return days } let days = monthInfo[index].numberOfDaysInMonthGrid daysInSection[index] = days return days } func numberOfRowsInSection(_ index: Int) -> Int { let numberOfDays = CGFloat(numberOfDaysInSection(index)) return Int(ceil(numberOfDays / CGFloat(numberOfRows))) } func cachedHeaderHeightForSection(_ section: Int) -> CGFloat { var retval: CGFloat = 0 // We look for most specific to less specific // Section = specific dates // Months = generic months // Default = final resort if let height = headerSizes[section] { retval = height } else { let monthIndex = monthMap[section]! let monthName = monthInfo[monthIndex].name if let height = headerSizes[monthName] { retval = height } else if let height = headerSizes["default"] { retval = height } } return retval } func sizeForitemAtIndexPath(_ item: Int, section: Int) -> (width: CGFloat, height: CGFloat) { if let cachedCell = currentCell, cachedCell.section == section { if !strictBoundaryRulesShouldApply, scrollDirection == .horizontal, !cellCache.isEmpty { if let x = cellCache[0]?[0] { return (x.width, x.height) } else { return (0, 0) } } else { return (cachedCell.width, cachedCell.height) } } let width = cellSize.width - ((sectionInset.left / 7) + (sectionInset.right / 7)) var size: (width: CGFloat, height: CGFloat) = (width, cellSize.height) if shouldUseUserItemSizeInsteadOfDefault { if scrollDirection == .vertical { size.height = cellSize.height } else { size.width = cellSize.width let headerHeight = strictBoundaryRulesShouldApply ? cachedHeaderHeightForSection(section) : 0 let currentMonth = monthInfo[monthMap[section]!] let recalculatedNumOfRows = allowsDateCellStretching ? CGFloat(currentMonth.maxNumberOfRowsForFull(developerSetRows: numberOfRows)) : CGFloat(maxNumberOfRowsPerMonth) size.height = (collectionView!.frame.height - headerHeight - sectionInset.top - sectionInset.bottom) / recalculatedNumOfRows currentCell = (section: section, width: size.width, height: size.height) } } else { // Get header size if it already cached let headerHeight = strictBoundaryRulesShouldApply ? cachedHeaderHeightForSection(section) : 0 var height: CGFloat = 0 let currentMonth = monthInfo[monthMap[section]!] let numberOfRowsForSection: Int if allowsDateCellStretching { numberOfRowsForSection = strictBoundaryRulesShouldApply ? currentMonth.maxNumberOfRowsForFull(developerSetRows: numberOfRows) : numberOfRows } else { numberOfRowsForSection = maxNumberOfRowsPerMonth } height = (collectionView!.frame.height - headerHeight - sectionInset.top - sectionInset.bottom) / CGFloat(numberOfRowsForSection) size.height = height > 0 ? height : 0 currentCell = (section: section, width: size.width, height: size.height) } return size } func numberOfRowsForMonth(_ index: Int) -> Int { let monthIndex = monthMap[index]! return monthInfo[monthIndex].rows } func startIndexFrom(rectOrigin offset: CGPoint) -> Int { let key = scrollDirection == .horizontal ? offset.x : offset.y return startIndexBinarySearch(endOfSectionOffsets, offset: key) } func sizeOfContentForSection(_ section: Int) -> CGFloat { switch scrollDirection { case .horizontal: return cellCache[section]![0].width * CGFloat(maxNumberOfDaysInWeek) + sectionInset.left + sectionInset.right case .vertical: fallthrough default: let headerSizeOfSection = !headerCache.isEmpty ? headerCache[section]!.height : 0 return cellCache[section]![0].height * CGFloat(numberOfRowsForMonth(section)) + headerSizeOfSection } } func trueSizeOfContentForSection(_ section: Int) -> CGSize { let headerSizeOfSection = !headerCache.isEmpty ? headerCache[section]!.height : 0 return CGSize(width: cellCache[section]![0].width * CGFloat(maxNumberOfDaysInWeek), height: cellCache[section]![0].height * CGFloat(numberOfRowsForMonth(section)) + headerSizeOfSection) } func sectionFromOffset(_ theOffSet: CGFloat) -> Int { var val: Int = 0 for (index, sectionSizeValue) in endOfSectionOffsets.enumerated() { if abs(theOffSet - sectionSizeValue) < errorDelta { continue } if theOffSet < sectionSizeValue { val = index break } } return val } func startIndexBinarySearch<T: Comparable>(_ val: [T], offset: T) -> Int { if val.count < 3 { return 0 } // If the range is less than 2 just break here. var midIndex: Int = 0 var startIndex = 0 var endIndex = val.count - 1 while startIndex < endIndex { midIndex = startIndex + (endIndex - startIndex) / 2 if midIndex + 1 >= val.count || offset >= val[midIndex] && offset < val[midIndex + 1] || val[midIndex] == offset { break } else if val[midIndex] < offset { startIndex = midIndex + 1 } else { endIndex = midIndex } } return midIndex } /// Returns an object initialized from data in a given unarchiver. /// self, initialized using the data in decoder. required public init?(coder aDecoder: NSCoder) { delegate = (aDecoder.value(forKey: "delegate") as! JTACMonthDelegateProtocol) cellCache = aDecoder.value(forKey: "delegate") as! [Int : [(Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)]] headerCache = aDecoder.value(forKey: "delegate") as! [Int : (Int, Int, CGFloat, CGFloat, CGFloat, CGFloat)] headerSizes = aDecoder.value(forKey: "delegate") as! [AnyHashable:CGFloat] super.init(coder: aDecoder) } // This function ignores decoration views //JT101 for setting proposal func minimumVisibleIndexPaths() -> (cellIndex: IndexPath?, headerIndex: IndexPath?) { let visibleItems: [UICollectionViewLayoutAttributes] if scrollDirection == .horizontal { visibleItems = elementsAtRect(excludeHeaders: true) } else { visibleItems = elementsAtRect() } var cells: [IndexPath] = [] var headers: [IndexPath] = [] for item in visibleItems { switch item.representedElementCategory { case .cell: cells.append(item.indexPath) case .supplementaryView: headers.append(item.indexPath) case .decorationView: fallthrough default: break } } return (cells.min(), headers.min()) } func elementsAtRect(excludeHeaders: Bool? = false, from rect: CGRect? = nil) -> [UICollectionViewLayoutAttributes] { let aRect = rect ?? CGRect(x: collectionView!.contentOffset.x + 1, y: collectionView!.contentOffset.y + 1, width: collectionView!.frame.width - 2, height: collectionView!.frame.height - 2) guard let attributes = layoutAttributesForElements(in: aRect), !attributes.isEmpty else { return [] } if excludeHeaders == true { return attributes.filter { $0.representedElementKind != UICollectionView.elementKindSectionHeader } } return attributes } func clearCache() { headerCache.removeAll() cellCache.removeAll() endOfSectionOffsets.removeAll() decorationCache.removeAll() currentHeader = nil currentCell = nil lastWrittenCellAttribute = nil xCellOffset = 0 yCellOffset = 0 contentHeight = 0 contentWidth = 0 xStride = 0 firstContentOffsetWasSet = false } }
44.548013
196
0.629576
bbd9411c5ef1be91b5415710067160490afb1089
4,687
// // AppDelegate.swift // BlockChain_Logic // // Created by Petar Lemajic on 1/2/19. // Copyright © 2019 Petar Lemajic. All rights reserved. // import UIKit import CoreData import IQKeyboardManagerSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { IQKeyboardManager.shared.enable = true // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "BlockChain_Logic") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
48.822917
285
0.68978
2831d6ba5e2a9a311a73214d5b51bad2b7bdd746
1,031
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import func libc.chdir import var libc.errno /** Causes the named directory to become the current working directory. */ public func chdir(_ path: String) throws { if memo == nil { let argv0 = try realpath(CommandLine.arguments.first!) let cwd = try realpath(getcwd()) memo = (argv0: argv0, wd: cwd) } guard libc.chdir(path) == 0 else { throw SystemError.chdir(errno, path) } } private var memo: (argv0: String, wd: String)? /** The initial working directory before any calls to POSIX.chdir. */ public func getiwd() -> String { return memo?.wd ?? getcwd() } public var argv0: String { return memo?.argv0 ?? CommandLine.arguments.first! }
24.547619
68
0.692532
79bab3c0f03aa957f4fc554a8ab50070ab23e0aa
1,373
// Copyright © 2019 Pedro Daniel Prieto Martínez. All rights reserved. import DataSourceController struct MockCellDataController: CellDataController { let reuseIdentifier = "MockCellDataController" let populateFunctionHasBeenCalled: Bool let title: String init(_ populateFunctionHasBeenCalled: Bool, title: String = .init()) { self.populateFunctionHasBeenCalled = populateFunctionHasBeenCalled self.title = title } static func populate(with model: Any) -> CellDataController { if let product = model as? Product { return MockCellDataController(true, title: product.name) } else if let sectionData = model as? SectionDataModel { return MockCellDataController(true, title: sectionData.header ?? "") } return MockCellDataController(false) } } struct SecondaryMockCellDataController: CellDataController { let reuseIdentifier = "SecondaryCellDataController" let populateFunctionHasBeenCalled: Bool init(_ populateFunctionHasBeenCalled: Bool) { self.populateFunctionHasBeenCalled = populateFunctionHasBeenCalled } static func populate(with model: Any) -> CellDataController { guard model is Product else { return SecondaryMockCellDataController(false) } return SecondaryMockCellDataController(true) } }
34.325
80
0.719592
e4f0ea7de153cd6ac50dd453bf98814152366542
1,014
fileprivate struct AssociatedKeys { static var styleName: UInt8 = 0 static var isStyleApplied: UInt8 = 1 } @objc extension UINavigationItem { @objc var styleName: String { get { isStyleApplied = false guard let value = objc_getAssociatedObject(self, &AssociatedKeys.styleName) as? String else { return "" } return value } set(newValue) { objc_setAssociatedObject(self, &AssociatedKeys.styleName, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @objc var isStyleApplied: Bool { get { guard let value = objc_getAssociatedObject(self, &AssociatedKeys.isStyleApplied) as? Bool else { return false } return value } set(newValue) { objc_setAssociatedObject(self, &AssociatedKeys.isStyleApplied, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @objc func setStyleAndApply(_ styleName: String) { self.styleName = styleName self.applyTheme() } }
27.405405
136
0.700197
717ed3d104d262be81cf3f5d87ff55e44fb1ae17
2,673
// // ViewController.swift // Jisho // // Created by Florent on 01/05/2018. // Copyright © 2018 Florent. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! @IBOutlet weak var segmentedControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func searchData(_ sender: UIButton) { if let inputString = textField.text, inputString != "" { if segmentedControl.selectedSegmentIndex == 0 { searchTheMeaningOfTheWord(word: inputString) } else if segmentedControl.selectedSegmentIndex == 1 { searchKanji(kanji: inputString) } else { searchAllKindOfSentencesWith(word: inputString) } } else { Toast.shared.long(self.view, message: "Please! tap a search 🙇‍♂️") } } // Search functions func searchTheMeaningOfTheWord(word: String) { Api.init().fetchWordsFromApi(parameter: word){ if let result = words, result.data.count > 0 { histories?.append(History(inputSearched: word, type: "word")) self.performSegue(withIdentifier: "showWords", sender: self) } else { Toast.shared.long(self.view, message: "Sumimasen! We have no results 🙇‍♂️") } } } func searchAllKindOfSentencesWith(word: String) { Api.init().fetchSentencesFromApi(parameter: word){ if let result = arrayOfSentences, result.count > 0 { histories?.append(History(inputSearched: word, type: "sentence")) self.performSegue(withIdentifier: "showSentences", sender: self) } else { Toast.shared.long(self.view, message: "Sumimasen! We have no results 🙇‍♂️") } } } func searchKanji(kanji: String) { Api.init().fetchKanjiFromApi(parameter: kanji){ if let result = kanjiFetched, result.found == true { histories?.append(History(inputSearched: kanji, type: "kanji")) self.performSegue(withIdentifier: "showKanjiDetail", sender: self) } else { Toast.shared.long(self.view, message: "Sumimasen! We have no results 🙇‍♂️") } } } }
31.081395
91
0.563412
dee000f691e324ea2f96f245391877050bfa0e48
2,182
// // AppDelegate.swift // ios-uikit-uifont-demo // // Created by k_motoyama on 2017/02/27. // Copyright © 2017年 k_moto. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.425532
285
0.755729
1899531ac9ec0d097e81c8d5c7535d74e30b3422
12,130
// // SliderAdv.swift // Timetochill // // Created by Yestay Muratov on 3/29/16. // Copyright © 2016 Yestay Muratov. All rights reserved. // import Foundation import UIKit public protocol SliderViewHorizontalPandaDelegate: class { func ytmSliderView(sliderView: SliderViewHorizontalPanda, didSelectItemAt index: Int, withView: UIView) func ytmSliderViewNumberOfItems(sliderView: SliderViewHorizontalPanda)->Int func ytmSliderView(sliderView: SliderViewHorizontalPanda, viewForRowAt index: Int)-> UIView func ytmSliderView(sliderView: SliderViewHorizontalPanda, didMoveTo index: Int) } public class SliderViewHorizontalPanda: UIView, UIScrollViewDelegate { public var delegate: SliderViewHorizontalPandaDelegate? var pageViews:[UIView?] = [] var scrollView: UIScrollView! public var selectedPage: Int? var timerToMoveToTheNextPage: Timer? public var isRandomPages = false var pageNumber: UIPageControl = UIPageControl(frame: .zero) public var isToSetPageNumber = false { didSet{ setConstraintPageController() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initViewsAndSetSlider() } public init(){ super.init(frame: .zero) initViewsAndSetSlider() } func getNumberOfItems()-> Int { return delegate?.ytmSliderViewNumberOfItems(sliderView: self) ?? 0 } func cleanArrayOfElementsInVM(){ self.pageViews = [] } func initViewsAndSetSlider(){ // creating scroll view slider self.scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) self.addSubview(self.scrollView) self.scrollView.delegate = self self.scrollView.isPagingEnabled = true self.scrollView.showsHorizontalScrollIndicator = false self.scrollView.backgroundColor = .black } func initGestureRecognizer(){ let tapgesture = UITapGestureRecognizer(target: self, action: #selector(self.goLinkOfAd(_:))) tapgesture.numberOfTapsRequired = 1 self.isUserInteractionEnabled = true self.addGestureRecognizer(tapgesture) } @objc func goLinkOfAd(_ gesture: UITapGestureRecognizer){ print("did tap slidet at view: \(self.selectedPage!)") } deinit{ switch UIDevice.current.systemVersion.compare("9.0.0", options: NSString.CompareOptions.numeric) { case .orderedSame, .orderedDescending: print("iOS >= 9.0") case .orderedAscending: print("iOS < 9.0") self.scrollView.delegate = nil } } override public func draw(_ rect: CGRect) { super.draw(rect) didSetView() } func didSetView(){ self.setscrollViewConst() self.setConstraintPageController() self.setScrollAdvAndLoadPages() self.initGestureRecognizer() } func setConstraintPageController(){ if self.isToSetPageNumber == false { return // not setting page number } pageNumber.tintColor = .white pageNumber.currentPage = 0 pageNumber.numberOfPages = self.getNumberOfItems() pageNumber.layer.zPosition = 2 self.addSubview(pageNumber) pageNumber.translatesAutoresizingMaskIntoConstraints = false pageNumber.heightAnchor.constraint(equalToConstant: 30).isActive = true pageNumber.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true pageNumber.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true } func setscrollViewConst(){ self.scrollView.translatesAutoresizingMaskIntoConstraints = false // set constraint to scrollview let topconst = NSLayoutConstraint(item: self.scrollView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0) self.addConstraint(topconst) let leftcons = NSLayoutConstraint(item: self.scrollView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 0.0) self.addConstraint(leftcons) let rightconst = NSLayoutConstraint(item: self.scrollView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: 0.0) self.addConstraint(rightconst) let bottonconst = NSLayoutConstraint(item: self.scrollView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0) self.addConstraint(bottonconst) self.updateConstraints() self.layoutIfNeeded() self.scrollView.backgroundColor = .black } func setScrollAdvAndLoadPages(){ // update page controller values let pageCount = self.getNumberOfItems() // 3 for _ in 0..<pageCount { self.pageViews.append(nil) } // 4 let pagesScrollViewSize = self.frame.size self.scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageCount), height: pagesScrollViewSize.height) // for some reason when scroll view loads it the content offset is not 0 , so we are setting content offset to 0 here // set random page number to slider if pageCount > 0 { let pageWidth = self.scrollView.frame.size.width var pageToStart: Int! if self.isRandomPages == true { let limit : UInt32 = UInt32(pageCount) let random = arc4random_uniform(limit) pageToStart = Int(random) }else { pageToStart = 0 } self.scrollView.contentOffset.x = pageWidth * CGFloat(pageToStart) } self.scrollView.setContentOffset(CGPoint(x: self.scrollView.contentOffset.x, y: 0), animated: false) // 5 loadVisiblePages() } func loadVisiblePages() { // First, determine which page is currently visible let pageCount = self.getNumberOfItems() if pageCount == 0 { return } let pageWidth = self.scrollView.frame.size.width if pageWidth == 0 { // happends when view is not set yet and we dont need to load views return } let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0))) // getting page by x coordinate of focus self.selectedPage = page pageNumber.currentPage = page self.delegate?.ytmSliderView(sliderView: self, didMoveTo: page) // Work out which pages you want to load var firstPage = page - 1 let lastPage = page + 1 if firstPage < 0 { firstPage = 0 } if firstPage >= 0 { // Purge anything before the first page for index in 0 ..< firstPage{ purgePage(index) } } // Load pages in our range for index in firstPage...lastPage { loadPage(index) } let newLastPage = lastPage + 1 if newLastPage < pageCount { // Purge anything after the last page for index in newLastPage..<pageCount{ purgePage(index) } } } func loadPage(_ page: Int) { if page < 0 || page >= self.getNumberOfItems() { // If it's outside the range of what you have to display, then do nothing return } guard let _delegate = self.delegate else { return } if let _ = pageViews[page] { // Do nothing. The view is already loaded. // do refresh image print("we have view , dont do anything") } else { // going to create customimage view var frame = scrollView.bounds frame.origin.x = frame.size.width * CGFloat(page) frame.origin.y = 0.0 let newPageView = _delegate.ytmSliderView(sliderView: self, viewForRowAt: page) newPageView.frame = frame self.pageViews[page] = newPageView self.scrollView.addSubview(newPageView) self.scrollView.bringSubviewToFront(newPageView) } } func purgePage(_ page: Int) { if page < 0 || page >= getNumberOfItems() { // If it's outside the range of what you have to display, then do nothing return } // Remove a page from the scroll view and reset the container array if let pageView = pageViews[page] { pageView.removeFromSuperview() pageViews[page] = nil } } public func jumpToNextPage() { let pageCount = self.getNumberOfItems() if pageCount == 0 { return } let pageWidth = self.scrollView.frame.size.width var value = (selectedPage ?? 0) * Int(pageWidth) var firstPage = (selectedPage ?? 0) - 1 let lastPage = (selectedPage ?? 0) + 1 if firstPage < 0 { value = 0 selectedPage = 0 firstPage = 0 } if (selectedPage ?? 0) >= pageCount { value -= Int(pageWidth) selectedPage = pageCount - 1 } if firstPage >= 0 { // Purge anything before the first page for index in 0 ..< firstPage{ purgePage(index) } } // Load pages in our range for index in firstPage...lastPage { loadPage(index) } let newLastPage = lastPage + 1 if newLastPage < pageCount { // Purge anything after the last page for index in newLastPage..<pageCount{ purgePage(index) } } scrollView.contentOffset.x = CGFloat(value) } // MARK: uiscroll delegate public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.timerToMoveToTheNextPage?.invalidate() } public func scrollViewDidScroll(_ scrollView: UIScrollView) { // loadVisiblePages() } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { print("did end decelerating") loadVisiblePages() } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { print("did end scrollign animation") } func startTimerLoop(){ //setting time interval that will change the background image if self.getNumberOfItems() > 1 { // else there is no image to scroll self.timerToMoveToTheNextPage = Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(self.changeBackgroundView), userInfo: nil, repeats: true) } } func stopTimerLoop(){ if timerToMoveToTheNextPage != nil { timerToMoveToTheNextPage!.invalidate() timerToMoveToTheNextPage = nil } } @objc func changeBackgroundView(){ print("ns timer is wokring good and it is not turned off") if self.getNumberOfItems() != 0 { let newContentOffsetX = scrollView.contentOffset.x + self.frame.width if newContentOffsetX >= scrollView.contentSize.width { self.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true) }else { self.scrollView.setContentOffset(CGPoint(x: newContentOffsetX, y: 0), animated: true) } loadVisiblePages() } } }
33.324176
175
0.593487
8a10d55383f9244f80e2e06f6e66cb616d71afa6
5,935
// // RadioCoordinatorTests.swift // Spotify TuneIn Tests // // Created by Jonathan Berglind on 2018-12-21. // Copyright © 2018 Jonathan Berglind. All rights reserved. // import XCTest import RxSwift import RxBlocking class RadioCoordinatorTests: XCTestCase { var socket: MockSocketProvider! var remote: MockMusicRemote! var coordinator: RadioCoordinator! var disposeBag = DisposeBag() override func setUp() { socket = MockSocketProvider() let api = RadioAPIClient(socket: socket) remote = MockMusicRemote() coordinator = RadioCoordinator(api: api, remote: remote) } var examplePlayerState = PlayerState(timestamp: 0, isPaused: true, trackName: nil, trackArtist: nil, trackURI: "", playbackPosition: 1) func startBroadcast() throws { _ = try coordinator.startBroadcast(station: RadioStation(name: "station", coordinate: nil)) .toBlocking(timeout: 1.0) .last() } func endBroadcast() throws { _ = try coordinator.endBroadcast() .toBlocking(timeout: 1.0) .last() } func joinBroadcast() throws { socket.mockAckResponderData( for: RadioAPIClient.OutgoingEvent.joinBroadcast.rawValue, data: examplePlayerState.socketRepresentation() ) _ = try coordinator.joinBroadcast(stationName: "station") .toBlocking(timeout: 1.0) .last() } func leaveBroadcast() throws { _ = try coordinator.leaveBroadcast() .toBlocking(timeout: 1.0) .last() } func failOnError() { coordinator.errors.emit(onNext: { _ in XCTFail() }).disposed(by: disposeBag) } func testBroadcastHappyPath() throws { failOnError() try startBroadcast() remote.mockPlayerUpdateEvent(playerState: examplePlayerState) remote.mockPlayerUpdateEvent(playerState: examplePlayerState) try endBroadcast() XCTAssertEqual( socket.emittedEvents, [RadioAPIClient.OutgoingEvent.startBroadcast, RadioAPIClient.OutgoingEvent.updatePlayerState, RadioAPIClient.OutgoingEvent.updatePlayerState, RadioAPIClient.OutgoingEvent.endBroadcast].map({ $0.rawValue }) ) } func testTuneInHappyPath() throws { failOnError() try joinBroadcast() socket.mockIncomingEvent(RadioAPIClient.IncomingEvent.playerStateUpdated.rawValue, data: examplePlayerState.socketRepresentation()) socket.mockIncomingEvent(RadioAPIClient.IncomingEvent.playerStateUpdated.rawValue, data: examplePlayerState.socketRepresentation()) try leaveBroadcast() XCTAssertEqual( socket.emittedEvents, [RadioAPIClient.OutgoingEvent.joinBroadcast, RadioAPIClient.OutgoingEvent.leaveBroadcast].map({ $0.rawValue }) ) XCTAssertEqual( remote.playerStateUpdates, [examplePlayerState, examplePlayerState, examplePlayerState] ) } func testBroadcastWhenBroadcasting() throws { failOnError() try startBroadcast() try startBroadcast() } func testTuneInWhenTunedIn() throws { failOnError() try joinBroadcast() try joinBroadcast() } func testTuneInWhenBroadcasting() throws { failOnError() try startBroadcast() try joinBroadcast() XCTAssertEqual( socket.emittedEvents, [RadioAPIClient.OutgoingEvent.startBroadcast, RadioAPIClient.OutgoingEvent.joinBroadcast].map({ $0.rawValue }) ) } func testBroadcastWhenTunedIn() throws { failOnError() try joinBroadcast() try startBroadcast() XCTAssertEqual( socket.emittedEvents, [RadioAPIClient.OutgoingEvent.joinBroadcast, RadioAPIClient.OutgoingEvent.startBroadcast, RadioAPIClient.OutgoingEvent.updatePlayerState].map({ $0.rawValue }) ) } func testBroadcastWhenDisconnectedFromApi () { socket.disconnectWithError() XCTAssertThrowsError(try startBroadcast()) } func testBroadcastWhenDisconnectedFromRemote () { failOnError() remote.allowConnect = false XCTAssertThrowsError(try startBroadcast()) } func testTuneInWhenDisconnectedFromApi () { socket.disconnectWithError() XCTAssertThrowsError(try joinBroadcast()) } func testTuneInWhenDisconnectedFromRemote () { failOnError() remote.allowConnect = false XCTAssertThrowsError(try joinBroadcast()) } func testApiDisconnectWhileBroadcasting() throws { try startBroadcast() let async = XCTestExpectation() coordinator.errors.emit(onNext: { error in if case .apiDisconnected = error {} else { XCTFail() } async.fulfill() }).disposed(by: disposeBag) socket.disconnectWithError() wait(for: [async], timeout: 1.0) } func testRemoteDisconnectWhileBroadcasting() throws { try startBroadcast() let async = XCTestExpectation() coordinator.errors.emit(onNext: { error in if case .remoteDisconnected = error {} else { XCTFail() } async.fulfill() }).disposed(by: disposeBag) remote.mockDisconnect() wait(for: [async], timeout: 1.0) } func testApiDisconnectWhileTunedIn() throws { try joinBroadcast() let async = XCTestExpectation() coordinator.errors.emit(onNext: { error in if case .apiDisconnected = error {} else { XCTFail() } async.fulfill() }).disposed(by: disposeBag) socket.disconnectWithError() wait(for: [async], timeout: 1.0) } func testRemoteDisconnectWhileTunedIn() throws { try joinBroadcast() let async = XCTestExpectation() coordinator.errors.emit(onNext: { error in if case .remoteDisconnected = error {} else { XCTFail() } async.fulfill() }).disposed(by: disposeBag) remote.mockDisconnect() wait(for: [async], timeout: 1.0) } }
28.533654
95
0.672789
f895d030ffa074a141965bab5721256906703e27
15,982
/** * Publish * Copyright (c) John Sundell 2019 * MIT license, see LICENSE file for details */ import Foundation import Files import Plot /// Type used to implement a publishing pipeline step. /// Each Publish website is generated and deployed using steps, which can also /// be combined into groups, and conditionally executed. Publish ships with many /// built-in steps, and new ones can easily be defined using `step(named:body:)`. /// Steps are added when calling `Website.publish`. public struct PublishingStep<Site: Website> { /// Closure type used to define the main body of a publishing step. public typealias Closure = (inout PublishingContext<Site>) throws -> Void internal let kind: Kind internal let body: Body } // MARK: - Core public extension PublishingStep { /// An empty step that does nothing. Can be used as a conditional fallback. static var empty: Self { PublishingStep(kind: .system, body: .empty) } /// Group an array of steps into one. /// - parameter steps: The steps to use to form a group. static func group(_ steps: [Self]) -> Self { PublishingStep(kind: .system, body: .group(steps)) } /// Conditionally run a step if an expression evaluates to `true`. /// - parameter condition: The condition that determines whether the /// step should be run or not. /// - parameter step: The step to run if the condition is `true`. static func `if`(_ condition: Bool, _ step: Self) -> Self { condition ? step : .empty } /// Conditionally run a step if an optional isn't `nil`. /// - parameter optional: The optional to unwrap. /// - parameter transform: A closure that transforms any unwrapped /// value into a `PublishingStep` instance. static func unwrap<T>(_ optional: T?, _ transform: (T) -> Self) -> Self { optional.map(transform) ?? .empty } /// Convert a step into an optional one, making it silently fail in /// case it encountered an error. /// - parameter step: The step to turn into an optional one. static func optional(_ step: Self) -> Self { switch step.body { case .empty, .group: return step case .operation(let name, let closure): return .step(named: name, kind: step.kind) { context in do { try closure(&context) } catch {} } } } /// Install a plugin into this publishing process. /// - parameter plugin: The plugin to install. static func installPlugin(_ plugin: Plugin<Site>) -> Self { step( named: "Install plugin '\(plugin.name)'", kind: .generation, body: plugin.installer ) } /// Create a custom step. /// - parameter name: A human-readable name for the step. /// - parameter body: The step's closure body, which is used to /// to mutate the current `PublishingContext`. static func step(named name: String, body: @escaping Closure) -> Self { step(named: name, kind: .generation, body: body) } } // MARK: - Content public extension PublishingStep { /// Add an item to website programmatically. /// - parameter item: The item to add. static func addItem(_ item: Item<Site>) -> Self { step(named: "Add item '\(item.path)'") { context in context.addItem(item) } } /// Add a sequence of items to website programmatically. /// - parameter sequence: The items to add. static func addItems<S: Sequence>( in sequence: S ) -> Self where S.Element == Item<Site> { step(named: "Add items in sequence") { context in sequence.forEach { context.addItem($0) } } } /// Add a page to website programmatically. /// - parameter page: The page to add. static func addPage(_ page: Page) -> Self { step(named: "Add page '\(page.path)'") { context in context.addPage(page) } } /// Add a sequence of pages to website programmatically. /// - parameter sequence: The pages to add. static func addPages<S: Sequence>( in sequence: S ) -> Self where S.Element == Page { step(named: "Add pages in sequence") { context in sequence.forEach { context.addPage($0) } } } /// Parse a folder of Markdown files and use them to add content to /// the website. The root folders will be parsed as sections, and the /// files within them as items, while root files will be parsed as pages. /// - parameter path: The path of the Markdown folder to add (default: `Content`). static func addMarkdownFiles(at path: Path = "Content") -> Self { step(named: "Add Markdown files from '\(path)' folder") { context in let folder = try context.folder(at: path) try MarkdownFileHandler().addMarkdownFiles(in: folder, to: &context) } } /// Mutate all items matching a predicate, optionally within a specific section. /// - parameter section: Any specific section to mutate all items within. /// - parameter predicate: Any predicate to filter the items using. /// - parameter mutations: The mutations to apply to each item. static func mutateAllItems( in section: Site.SectionID? = nil, matching predicate: Predicate<Item<Site>> = .any, using mutations: @escaping Mutations<Item<Site>> ) -> Self { let nameSuffix = section.map { " in '\($0)'" } ?? "" return step(named: "Mutate items" + nameSuffix) { context in if let section = section { try context.sections[section].mutateItems( matching: predicate, using: mutations ) } else { for section in context.sections.ids { try context.sections[section].mutateItems( matching: predicate, using: mutations ) } } } } /// Mutate an item at a given path within a section. /// - parameter path: The relative path of the item to mutate. /// - parameter section: The section that the item belongs to. /// - parameter mutations: The mutations to apply to the item. static func mutateItem( at path: Path, in section: Site.SectionID, using mutations: @escaping Mutations<Item<Site>> ) -> Self { step(named: "Mutate item at '\(path)' in \(section)") { context in try context.sections[section].mutateItem(at: path, using: mutations) } } /// Mutate a page at a given path. /// - parameter path: The path of the page to mutate. /// - parameter mutations: The mutations to apply to the page. static func mutatePage( at path: Path, using mutations: @escaping Mutations<Page> ) -> Self { step(named: "Mutate page at '\(path)'") { context in try context.mutatePage(at: path, using: mutations) } } /// Mutate all pages, optionally matching a given predicate. /// - parameter predicate: Any predicate to filter the items using. /// - parameter mutations: The mutations to apply to the page. static func mutateAllPages( matching predicate: Predicate<Page> = .any, using mutations: @escaping Mutations<Page> ) -> Self { step(named: "Mutate all pages") { context in for path in context.pages.keys { try context.mutatePage( at: path, matching: predicate, using: mutations ) } } } /// Sort all items, optionally within a specific section, using a key path. /// - parameter section: Any specific section to sort all items within. /// - parameter keyPath: The key path to use when sorting. /// - parameter order: The order to use when sorting. static func sortItems<T: Comparable>( in section: Site.SectionID? = nil, by keyPath: KeyPath<Item<Site>, T>, order: SortOrder = .ascending ) -> Self { let nameSuffix = section.map { " in '\($0)'" } ?? "" return step(named: "Sort items" + nameSuffix) { context in let sorter = order.makeSorter(forKeyPath: keyPath) if let section = section { context.sections[section].sortItems(by: sorter) } else { for section in context.sections { context.sections[section.id].sortItems(by: sorter) } } } } } // MARK: - Files and folders public extension PublishingStep { /// Copy the website's main resources into its output folder /// - parameter originPath: The path that the resource folder is located at. /// - parameter targetFolderPath: Any specific path to copy the resources to. /// If `nil`, then the resources will be copied to the output folder itself. /// - parameter includeFolder: Whether the resource folder itself, or just its /// contents, should be copied. Default: `false`. static func copyResources( at originPath: Path = "Resources", to targetFolderPath: Path? = nil, includingFolder includeFolder: Bool = false ) -> Self { copyFiles(at: originPath, to: targetFolderPath, includingFolder: includeFolder) } /// Copy a file at a given path into the website's output folder. /// - parameter originPath: The path of the file to copy. /// - parameter targetFolderPath: Any specific folder path to copy the file to. /// If `nil`, then the file will be copied to the output folder itself. static func copyFile(at originPath: Path, to targetFolderPath: Path? = nil) -> Self { step(named: "Copy file '\(originPath)'") { context in try context.copyFileToOutput( from: originPath, to: targetFolderPath ) } } /// Copy a folder at a given path into the website's output folder. /// - parameter originPath: The path of the folder to copy. /// - parameter targetFolderPath: Any specific path to copy the folder to. /// If `nil`, then the folder will be copied to the output folder itself. /// - parameter includeFolder: Whether the origin folder itself, or just its /// contents, should be copied. Default: `false`. static func copyFiles( at originPath: Path, to targetFolderPath: Path? = nil, includingFolder includeFolder: Bool = false ) -> Self { step(named: "Copy '\(originPath)' files") { context in let folder = try context.folder(at: originPath) if includeFolder { try context.copyFolderToOutput( folder, targetFolderPath: targetFolderPath ) } else { for subfolder in folder.subfolders { try context.copyFolderToOutput( subfolder, targetFolderPath: targetFolderPath ) } for file in folder.files { try context.copyFileToOutput( file, targetFolderPath: targetFolderPath ) } } } } } // MARK: - Generation public extension PublishingStep { /// Generate the website's HTML using a given theme. /// - parameter theme: The theme to use to generate the website's HTML. /// - parameter indentation: How each HTML file should be indented. /// - parameter fileMode: The mode to use when generating each HTML file. static func generateHTML( withTheme theme: Theme<Site>, indentation: Indentation.Kind? = nil, fileMode: HTMLFileMode = .foldersAndIndexFiles ) -> Self { step(named: "Generate HTML") { context in let generator = HTMLGenerator( theme: theme, indentation: indentation, fileMode: fileMode, context: context ) try generator.generate() } } /// Generate an RSS feed for the website. /// - parameter includedSectionIDs: The IDs of the sections which items /// to include when generating the feed. /// - parameter config: The configuration to use when generating the feed. static func generateRSSFeed( including includedSectionIDs: Set<Site.SectionID>, config: RSSFeedConfiguration = .default ) -> Self { guard !includedSectionIDs.isEmpty else { return .empty } return step(named: "Generate RSS feed") { context in let generator = RSSFeedGenerator( includedSectionIDs: includedSectionIDs, config: config, context: context ) try generator.generate() } } /// Generate a site map for the website, which is an XML file used /// for search engine indexing. /// - parameter excludedPaths: Any paths to exclude from the site map. /// Adding a section's path to the list removes the entire section, including all its items. /// - parameter indentation: How the site map should be indented. static func generateSiteMap(excluding excludedPaths: Set<Path> = [], indentedBy indentation: Indentation.Kind? = nil) -> Self { step(named: "Generate site map") { context in let generator = SiteMapGenerator( excludedPaths: excludedPaths, indentation: indentation, context: context ) try generator.generate() } } } public extension PublishingStep where Site.ItemMetadata: PodcastCompatibleWebsiteItemMetadata { /// Generate a podcast feed for one of the website's sections. /// Note that all of the items within the given section must define `podcast` /// and `audio` metadata, or an error will be thrown. /// - parameter section: The section to generate a podcast feed for. /// - parameter config: The configuration to use when generating the feed. static func generatePodcastFeed( for section: Site.SectionID, config: PodcastFeedConfiguration<Site> ) -> Self { step(named: "Generate podcast feed") { context in let generator = PodcastFeedGenerator( sectionID: section, config: config, context: context ) try generator.generate() } } } // MARK: - Deployment public extension PublishingStep { /// Deploy the website using a given method. /// This step will only run in case either the `-d` or `--deploy /// flag was passed on the command line, for example by using the /// `publish deploy` command. /// - parameter method: The method to use when deploying the website. static func deploy(using method: DeploymentMethod<Site>) -> Self { step(named: "Deploy using \(method.name)", kind: .deployment) { context in try method.body(context) } } } // MARK: - Implementation details internal extension PublishingStep { enum Kind { case system case generation case deployment } enum Body { case empty case operation(name: String, closure: Closure) case group([PublishingStep]) } } private extension PublishingStep { static func step(named name: String, kind: Kind, body: @escaping Closure) -> Self { PublishingStep( kind: kind, body: .operation(name: name, closure: body) ) } }
36.909931
98
0.597234
fedee0b5a23b638606d89f97189e29683fe5be04
2,126
// // AudioRecorder.swift // TestChatApp // // Created by Alexander Vinogradov on 01.11.2021. // import Foundation import AVFoundation class AudioRecorder: NSObject { var recordingSession: AVAudioSession! var audioRecorder: AVAudioRecorder! var isAudioRecordingGranded: Bool = false static let shared = AudioRecorder() private override init() { super.init() checkPermissions() } func checkPermissions() { switch AVAudioSession.sharedInstance().recordPermission { case .granted: isAudioRecordingGranded = true case .denied: isAudioRecordingGranded = false case .undetermined: AVAudioSession.sharedInstance().requestRecordPermission { isGranded in self.isAudioRecordingGranded = isGranded } @unknown default: break } } func setupRecorder() { guard isAudioRecordingGranded else { return } recordingSession = AVAudioSession.sharedInstance() do { try recordingSession.setCategory(.playAndRecord, mode: .default) try recordingSession.setActive(true) } catch { assert(false, error.localizedDescription) } } func startRecording(fileName: String) { let filePath = FileStorage.documentsURL.appendingPathComponent(fileName + ".m4a", isDirectory: false) let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] do { audioRecorder = try AVAudioRecorder(url: filePath, settings: settings) audioRecorder.delegate = self audioRecorder.record() } catch { assert(false, error.localizedDescription) finishRecording() } } func finishRecording() { audioRecorder?.stop() audioRecorder = nil } } // MARK: - AVAudioRecorderDelegate extension AudioRecorder: AVAudioRecorderDelegate {}
27.973684
109
0.631703
569ee14dae9e33909e7586c78f097648ee5a0014
2,410
// // FeedbackGeneratorView.swift // FeedbackGenerator // // Created by Michael Kao on 02.11.20. // import ComposableArchitecture import SwiftUI struct FeedbackGeneratorView: View { let store: Store<AppState, AppAction> var body: some View { WithViewStore(self.store) { viewStore in Form { Section(header: Text("Impact Feedback Generator")) { WithViewStore(self.store.scope(state: { $0.impactStyle }, action: AppAction.impactStylePicked)) { impactViewStore in VStack { Picker( "Impact", selection: impactViewStore.binding(send: { $0 }) ) { ForEach(ImpactStyle.allCases, id: \.self) { style in Text(style.rawValue).tag(style) } } .pickerStyle(SegmentedPickerStyle()) Button("Run") { viewStore.send(.tappedImpactButton) } .padding() } } } Section(header: Text("Notification Feedback Generator")) { WithViewStore(self.store.scope(state: { $0.notificationType }, action: AppAction.notificationTypePicked)) { impactViewStore in VStack { Picker( "Notification", selection: impactViewStore.binding(send: { $0 }) ) { ForEach(NotificationType.allCases, id: \.self) { type in Text(type.rawValue).tag(type) } } .pickerStyle(SegmentedPickerStyle()) Button("Run") { viewStore.send(.tappedNotificationButton) } .padding() } } } Section(header: Text("Selection Feedback Generator")) { WithViewStore(self.store) { viewStore in HStack { Spacer() Button("Run") { viewStore.send(.tappedSelectionButton) } .padding() Spacer() } } } } } } } struct FeedbackGeneratorView_Previews: PreviewProvider { static var previews: some View { FeedbackGeneratorView( store: Store( initialState: AppState(), reducer: .empty, environment: AppEnvironment( feedbackGenerator: .unimplemented() ) ) ) } }
28.690476
136
0.518672
4833f72b250f099a44dc431a1a4af199b62ce84e
8,458
// // AlamofireClient.swift // // Created by Alexander Ignatev on 12/02/2019. // Copyright © 2019 RedMadRobot. All rights reserved. // import Apexy import Foundation import Alamofire /// API Client. open class AlamofireClient: Client { /// A closure used to observe result of every response from the server. public typealias ResponseObserver = (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Void /// Session network manager. private let sessionManager: Alamofire.Session /// The queue on which the network response handler is dispatched. private let responseQueue = DispatchQueue( label: "Apexy.responseQueue", qos: .utility) /// The queue on which the completion handler is dispatched. private let completionQueue: DispatchQueue /// This closure to be called after each response from the server for the request. private let responseObserver: ResponseObserver? /// Look more at Alamofire.RequestInterceptor. public let requestInterceptor: RequestInterceptor /// Creates new 'AlamofireClient' instance. /// /// - Parameters: /// - requestInterceptor: Alamofire Request Interceptor. /// - configuration: The configuration used to construct the managed session. /// - completionQueue: The serial operation queue used to dispatch all completion handlers. `.main` by default. /// - publicKeys: Dictionary with 1..n public keys used for SSL-pinning: ["example1.com": [PK1], "example2": [PK2, PK3]]. /// - responseObserver: The closure to be called after each response. /// - eventMonitors: Alamofire `EventMonitor`s used by the instance. `[]` by default. public init( requestInterceptor: RequestInterceptor, configuration: URLSessionConfiguration, completionQueue: DispatchQueue = .main, publicKeys: [String: [SecKey]] = [:], responseObserver: ResponseObserver? = nil, eventMonitors: [EventMonitor] = []) { var securityManager: ServerTrustManager? /// All requests will cancelled if `ServerTrustManager` will initialized with empty evaluators if !publicKeys.isEmpty { let evaluators = publicKeys.mapValues { keys in return PublicKeysTrustEvaluator(keys: keys, performDefaultValidation: true, validateHost: true) } securityManager = ServerTrustManager(evaluators: evaluators) } self.completionQueue = completionQueue self.requestInterceptor = requestInterceptor self.sessionManager = Session( configuration: configuration, interceptor: requestInterceptor, serverTrustManager: securityManager, eventMonitors: eventMonitors) self.responseObserver = responseObserver } /// Creates new 'AlamofireClient' instance. /// /// - Parameters: /// - baseURL: Base `URL`. /// - configuration: The configuration used to construct the managed session. /// - completionQueue: The serial operation queue used to dispatch all completion handlers. `.main` by default. /// - publicKeys: Dictionary with 1..n public keys used for SSL-pinning: ["example1.com": [PK1], "example2": [PK2, PK3]]. /// - responseObserver: The closure to be called after each response. /// - eventMonitors: Alamofire `EventMonitor`s used by the instance. `[]` by default. public convenience init( baseURL: URL, configuration: URLSessionConfiguration, completionQueue: DispatchQueue = .main, publicKeys: [String: [SecKey]] = [:], responseObserver: ResponseObserver? = nil, eventMonitors: [EventMonitor] = []) { self.init( requestInterceptor: BaseRequestInterceptor(baseURL: baseURL), configuration: configuration, completionQueue: completionQueue, publicKeys: publicKeys, responseObserver: responseObserver, eventMonitors: eventMonitors) } /// Send request to specified endpoint. /// /// - Parameters: /// - endpoint: endpoint of remote content. /// - completionHandler: The completion closure to be executed when request is completed. /// - Returns: The progress of fetching the response data from the server for the request. open func request<T>( _ endpoint: T, completionHandler: @escaping (APIResult<T.Content>) -> Void ) -> Progress where T: Endpoint { let anyRequest = AnyRequest(create: endpoint.makeRequest) let request = sessionManager.request(anyRequest) .validate { request, response, data in Result(catching: { try endpoint.validate(request, response: response, data: data) }) }.responseData( queue: responseQueue, completionHandler: { (response: DataResponse<Data, AFError>) in let result = APIResult<T.Content>(catching: { () throws -> T.Content in do { let data = try response.result.get() return try endpoint.content(from: response.response, with: data) } catch { throw error.unwrapAlamofireValidationError() } }) self.completionQueue.async { self.responseObserver?(response.request, response.response, response.data, result.error) completionHandler(result) } }) let progress = request.downloadProgress progress.cancellationHandler = { [weak request] in request?.cancel() } return progress } /// Upload data to specified endpoint. /// /// - Parameters: /// - endpoint: The remote endpoint and data to upload. /// - completionHandler: The completion closure to be executed when request is completed. /// - Returns: The progress of uploading data to the server. open func upload<T>( _ endpoint: T, completionHandler: @escaping (APIResult<T.Content>) -> Void ) -> Progress where T: UploadEndpoint { let urlRequest: URLRequest let body: UploadEndpointBody do { (urlRequest, body) = try endpoint.makeRequest() } catch { completionHandler(.failure(error)) return Progress() } let request: UploadRequest switch body { case .data(let data): request = sessionManager.upload(data, with: urlRequest) case .file(let url): request = sessionManager.upload(url, with: urlRequest) case .stream(let stream): request = sessionManager.upload(stream, with: urlRequest) } request.responseData( queue: responseQueue, completionHandler: { (response: DataResponse<Data, AFError>) in let result = APIResult<T.Content>(catching: { () throws -> T.Content in let data = try response.result.get() return try endpoint.content(from: response.response, with: data) }) self.completionQueue.async { self.responseObserver?(response.request, response.response, response.data, result.error) completionHandler(result) } }) let progress = request.uploadProgress progress.cancellationHandler = { [weak request] in request?.cancel() } return progress } } // MARK: - Helper /// Wrapper for `URLRequestConvertible` from `Alamofire`. private struct AnyRequest: Alamofire.URLRequestConvertible { let create: () throws -> URLRequest func asURLRequest() throws -> URLRequest { return try create() } } private extension APIResult { var error: Error? { switch self { case .failure(let error): return error default: return nil } } } public extension Error { func unwrapAlamofireValidationError() -> Error { guard let afError = asAFError else { return self } if case .responseValidationFailed(let reason) = afError, case .customValidationFailed(let underlyingError) = reason { return underlyingError } return self } }
38.621005
128
0.621305
210256e7b63dccde1dd118ec4ee4e1ce210b0f95
544
// // DatasourceCell.swift // Pods // // Created by Brian Voong on 11/21/16. // // import UIKit open class DatasourceCell: UICollectionViewCell { open var datasourceItem: Any? open var controller: DatasourceController? public override init(frame: CGRect) { super.init(frame: frame) setupViews() } open func setupViews() { clipsToBounds = true } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
18.133333
59
0.617647
33b87862a113f38d6a187e2a0639a44f9a24df38
689
import Foundation @available(iOS 15.2, macOS 12.1, tvOS 15.2, watchOS 8.3, *) public extension SFSymbol { static var allSymbols15P2: [SFSymbol] { return [ .airpodGen3Left, .airpodGen3Right, .airpodsGen3, .airpodsGen3ChargingcaseWireless, .airpodsGen3ChargingcaseWirelessFill, .beatsFitPro, .beatsFitProChargingcase, .beatsFitProChargingcaseFill, .beatsFitProLeft, .beatsFitProRight, .rectangleLeadinghalfFilled, .rectangleTrailinghalfFilled, .square3Layers3DDownLeftSlash, .square3Layers3DDownRightSlash, .square3Stack3DSlash ] } }
27.56
59
0.641509
d96a25521984d3a76b8910fd90df751884fe5df2
1,030
// // WLMixtape+CoreDataProperties.swift // Pods // // Created by Alexander Givens on 8/6/17. // // import Foundation import CoreData extension WLMixtape { @nonobjc public class func fetchRequest() -> NSFetchRequest<WLMixtape> { return NSFetchRequest<WLMixtape>(entityName: "WLMixtape") } @NSManaged public var artworkCredit: String? @NSManaged public var artworkCreditURL: String? @NSManaged public var artworkURL: String? @NSManaged public var created: NSDate? @NSManaged public var descriptionText: String? @NSManaged public var id: Int32 @NSManaged public var modified: NSDate? @NSManaged public var product: String? @NSManaged public var productURL: String? @NSManaged public var released: NSDate? @NSManaged public var slug: String? @NSManaged public var sponsor: String? @NSManaged public var sponsorURL: String? @NSManaged public var title: String? @NSManaged public var trackCount: Int32 @NSManaged public var collectionID: Int32 }
27.837838
76
0.72233
0ed234d2e389112d35d26b3d1b6f9a6296449673
499
// // PairResponse.swift // Pods-TSRTLS_Example // // Created by Steeven Sylveus on 1/30/22. // import Foundation struct PairResponse: Codable { enum PairCode: String, Codable { case noChange = "no_change" case trackerNotFound = "tracker_not_found" case trackerInUse = "tracker_in_use" } var code: PairCode? var message: String? var overwritable: Bool? var vehicleId: String? var success: Bool? var previousVehicleId: String? }
19.96
50
0.653307
bb608bb31a0d7e8116599a288965cabc3d8e93e4
1,397
// // EzsigndocumentGetActionableElementsV1Response.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif /** Response for GET /1/object/ezsigndocument/{pkiEzsigndocumentID}/getActionableElements */ public struct EzsigndocumentGetActionableElementsV1Response: Codable, JSONEncodable, Hashable { public var mPayload: EzsigndocumentGetActionableElementsV1ResponseMPayload public var objDebugPayload: CommonResponseObjDebugPayload? public var objDebug: CommonResponseObjDebug? public init(mPayload: EzsigndocumentGetActionableElementsV1ResponseMPayload, objDebugPayload: CommonResponseObjDebugPayload? = nil, objDebug: CommonResponseObjDebug? = nil) { self.mPayload = mPayload self.objDebugPayload = objDebugPayload self.objDebug = objDebug } public enum CodingKeys: String, CodingKey, CaseIterable { case mPayload case objDebugPayload case objDebug } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(mPayload, forKey: .mPayload) try container.encodeIfPresent(objDebugPayload, forKey: .objDebugPayload) try container.encodeIfPresent(objDebug, forKey: .objDebug) } }
33.261905
178
0.758769
26834116cda3b65d09a0ec832a014a8e881aa4e2
3,654
// // MoreLoginViewController.swift // News // // Created by 杨蒙 on 2017/9/27. // Copyright © 2017年 hrscy. All rights reserved. // import UIKit import IBAnimatable class MoreLoginViewController: AnimatableModalViewController, StoryboardLoadable { @IBOutlet weak var loginCloseButton: UIButton! /// 顶部标题 @IBOutlet weak var topLabel: UILabel! /// 手机号 view @IBOutlet weak var mobileView: AnimatableView! /// 验证码 view @IBOutlet weak var passwrodView: AnimatableView! /// 发送验证码 view @IBOutlet weak var sendVerifyView: UIView! /// 找回密码 view @IBOutlet weak var findPasswordView: UIView! /// 发送验证码按钮 @IBOutlet weak var sendVerifyButton: UIButton! /// 手机号 输入框 @IBOutlet weak var mobileTextField: UITextField! /// 找回密码 按钮 @IBOutlet weak var findPasswordButton: UIButton! /// 密码输入框 @IBOutlet weak var passwordtextField: UITextField! /// 未注册 @IBOutlet weak var middleTipLabel: UILabel! /// 进入头条 @IBOutlet weak var enterTouTiaoButton: AnimatableButton! /// 阅读条款 @IBOutlet weak var readLabel: UILabel! /// 阅读按钮 @IBOutlet weak var readButton: UIButton! /// 帐号密码登录 @IBOutlet weak var loginModeButton: UIButton! @IBOutlet weak var wechatLoginButton: UIButton! @IBOutlet weak var qqLoginButton: UIButton! @IBOutlet weak var tianyiLoginButton: UIButton! @IBOutlet weak var mailLoginButton: UIButton! /// 帐号密码登录 点击 @IBAction func loginModeButtonCicked(_ sender: UIButton) { loginModeButton.isSelected = !sender.isSelected sendVerifyView.isHidden = sender.isSelected findPasswordView.isHidden = !sender.isSelected middleTipLabel.isHidden = sender.isSelected passwordtextField.placeholder = sender.isSelected ? "密码" : "请输入验证码" topLabel.text = sender.isSelected ? "帐号密码登录" : "登录你的头条,精彩永不消失" } override func viewDidLoad() { super.viewDidLoad() loginModeButton.setTitle("免密码登录", for: .selected) view.theme_backgroundColor = "colors.cellBackgroundColor" topLabel.theme_textColor = "colors.black" middleTipLabel.theme_textColor = "colors.cellRightTextColor" readLabel.theme_textColor = "colors.black" enterTouTiaoButton.theme_backgroundColor = "colors.enterToutiaoBackgroundColor" enterTouTiaoButton.theme_setTitleColor("colors.enterToutiaoTextColor", forState: .normal) readButton.theme_setImage("images.loginReadButton", forState: .selected) readButton.theme_setImage("images.loginReadButtonSelected", forState: .normal) mobileView.theme_backgroundColor = "colors.loginMobileViewBackgroundColor" passwrodView.theme_backgroundColor = "colors.loginMobileViewBackgroundColor" loginCloseButton.theme_setImage("images.loginCloseButtonImage", forState: .normal) wechatLoginButton.theme_setImage("images.moreLoginWechatButton", forState: .normal) qqLoginButton.theme_setImage("images.moreLoginQQButton", forState: .normal) tianyiLoginButton.theme_setImage("images.moreLoginTianyiButton", forState: .normal) mailLoginButton.theme_setImage("images.moreLoginMailButton", forState: .normal) } @IBAction func readButton(_ sender: UIButton) { sender.isSelected = !sender.isSelected } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// 关闭按钮点击 @IBAction func moreLoginColseButtonClicked(_ sender: UIButton) { dismiss(animated: true, completion: nil) } }
37.670103
97
0.706897
2365de39a097b507bab11d92f8914ebb1f47b83b
3,767
// // Future+Signal.swift // Flow // // Created by Måns Bernhardt on 2016-03-22. // Copyright © 2016 iZettle. All rights reserved. // import Foundation public extension SignalProvider { /// Returns a future that will succeed for when `self` signals its first value, or fail if `self` is terminated. /// - Note: If the signal is terminated without an error, the return future will fail with `FutureError.aborted` var future: Future<Value> { let signal = providedSignal return Future<Value> { completion in signal.onEventType { eventType in switch eventType { case .initial: break case .event(.value(let value)): completion(.success(value)) case .event(.end(let error)): completion(.failure(error ?? FutureError.aborted)) } } } } } public extension SignalProvider { /// Returns a new signal forwarding the value from the future returned from `transform` unless the future fails, where the returned signal terminates with the future's error. /// - Note: If `self` signals a value, any previous future returned from `transform` will be cancelled. func mapLatestToFuture<T>(on scheduler: Scheduler = .current, _ transform: @escaping (Value) -> Future<T>) -> FiniteSignal<T> { return FiniteSignal(self).flatMapLatest(on: scheduler) { value in transform(value).valueSignal } } } public extension Future { /// Returns a `Disposable` the will cancel `self` when being disposed. /// - Note: The disposable will hold a weak reference to `self` to not delay the deallocation of `self`. var disposable: Disposable { // A future have at least one strong referene until it's completed or cancelled. // By holding a weak reference to self we make sure we won't delay the deallocation of the future when it's done. // And canceling a completed future has no effect anyway. return Disposer { [weak self] in self?.cancel() } } /// Returns a signal that at the completion of `self` will signal the result. var resultSignal: Signal<Result<Value>> { return Signal { callback in self.onResult(callback).disposable } } /// Returns a signal that at the completion of `self` will signal the success value, unless a failure where the signal will be terminated with that failure error. var valueSignal: FiniteSignal<Value> { return resultSignal.map { try $0.getValue() } } /// Returns a signal that at the completion of `self` will signal the success value and thereafter terminate the signal, unless a failure where the signal will be terminated with that failure error. var valueThenEndSignal: FiniteSignal<Value> { return FiniteSignal(onEvent: { callback in self.onValue { callback(.value($0)) callback(.end) }.onError { callback(.end($0)) }.disposable }) } /// Returns a new future, where `signal`'s value is will be set to the success value of `self`. @discardableResult func bindTo<P: SignalProvider>(_ signal: P) -> Future where P.Value == Value, P.Kind == ReadWrite { let signal = signal.providedSignal return onValue { signal.value = $0 } } /// Returns a new future, where the success value will be hold until `signal`'s value is or becomes true. func hold<S>(until signal: S) -> Future where S: SignalProvider, S.Value == Bool, S.Kind.DropWrite == Read { return flatMap { val in signal.atOnce().filter { $0 }.future.map { _ in val } } } }
42.325843
202
0.637377
ac9723b3f765a69717cc42c2a354f1b1b87d0312
2,290
// // URLTransform.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-27. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // 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 open class URLTransform: TransformType { public typealias Object = URL public typealias JSON = String private let shouldEncodeURLString: Bool /** Initializes the URLTransform with an option to encode URL strings before converting them to an NSURL - parameter shouldEncodeUrlString: when true (the default) the string is encoded before passing to `NSURL(string:)` - returns: an initialized transformer */ public init(shouldEncodeURLString: Bool = true) { self.shouldEncodeURLString = shouldEncodeURLString } open func transformFromJSON(_ value: Any?) -> URL? { guard let URLString = value as? String else { return nil } if !shouldEncodeURLString { return URL(string: URLString) } guard let escapedURLString = URLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return nil } return URL(string: escapedURLString) } open func transformToJSON(_ value: URL?) -> String? { if let URL = value { return URL.absoluteString } return nil } }
34.69697
122
0.748035
f4b29d50ccee68e0cb188859a35f68c0a366d9e5
555
import TwitterAPIKit import XCTest class GetComplianceJobRequestV2Tests: XCTestCase { override func setUpWithError() throws { } override func tearDownWithError() throws { } func test() throws { let req = GetComplianceJobRequestV2( id: 1 ) XCTAssertEqual(req.method, .get) XCTAssertEqual(req.baseURLType, .api) XCTAssertEqual(req.path, "/2/compliance/jobs/1") XCTAssertEqual(req.bodyContentType, .wwwFormUrlEncoded) AssertEqualAnyDict(req.parameters, [:]) } }
24.130435
63
0.657658
ace03189b0daf1d9ab76c896fd0f7b0b42f4dc1a
2,452
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s func markUsed<T>(t: T) {} // rdar://17772217 func testSwitchOnExistential(value: Any) { switch value { case true as Bool: markUsed("true") case false as Bool: markUsed("false") default: markUsed("default") } } // CHECK-LABEL: sil hidden @_TF10switch_isa23testSwitchOnExistentialFP_T_ : // CHECK: [[ANY:%.*]] = alloc_stack $protocol<> // CHECK: copy_addr %0 to [initialization] [[ANY]] // CHECK: [[BOOL:%.*]] = alloc_stack $Bool // CHECK: checked_cast_addr_br copy_on_success protocol<> in [[ANY]] : $*protocol<> to Bool in [[BOOL]] : $*Bool, [[IS_BOOL:bb[0-9]+]], [[IS_NOT_BOOL:bb[0-9]+]] // CHECK: [[IS_BOOL]]: // CHECK: [[T0:%.*]] = load [[BOOL]] enum Foo { case A } enum Bar<T> { case B(T) } func testSwitchEnumOnExistential(value: Any) { switch value { case Foo.A: () case Bar<Int>.B(let i): () case Bar<Foo>.B(let f): () default: () } } // CHECK-LABEL: sil hidden @_TF10switch_isa27testSwitchEnumOnExistentialFP_T_ : $@convention(thin) (@in protocol<>) -> () // CHECK: checked_cast_addr_br copy_on_success protocol<> in {{%.*}} : $*protocol<> to Foo // CHECK: checked_cast_addr_br copy_on_success protocol<> in {{%.*}} : $*protocol<> to Bar<Int> // CHECK: checked_cast_addr_br copy_on_success protocol<> in {{%.*}} : $*protocol<> to Bar<Foo> class B {} class D: B {} func guardFn(l: D, _ r: D) -> Bool { return true } // rdar://problem/21087371 // CHECK-LABEL: sil hidden @_TF10switch_isa32testSwitchTwoIsPatternsWithGuardFTCS_1B1rS0__T_ // CHECK: checked_cast_br {{%.*}} : $B to $D, [[R_CAST_YES:bb[0-9]+]], [[R_CAST_NO:bb[0-9]+]] // CHECK: [[R_CAST_YES]]({{.*}}): // CHECK: checked_cast_br {{%.*}} : $B to $D, [[L_CAST_YES:bb[0-9]+]], [[L_CAST_NO:bb[0-9]+]] // CHECK: [[L_CAST_YES]]({{.*}}): // CHECK: function_ref @_TF10switch_isa7guardFnFTCS_1DS0__Sb // CHECK: cond_br {{%.*}}, [[GUARD_YES:bb[0-9]+]], [[GUARD_NO:bb[0-9]+]] // CHECK: [[GUARD_NO]]: // CHECK-NEXT: strong_release [[R2:%.*]] : $D // CHECK-NEXT: strong_release [[L2:%.*]] : $D // CHECK-NEXT: br [[CONT:bb[0-9]+]] // CHECK: [[L_CAST_NO]]: // CHECK-NEXT: strong_release [[R2:%.*]] : $D // CHECK-NEXT: br [[CONT]] func testSwitchTwoIsPatternsWithGuard(l: B, r: B) { switch (l, r) { case (let l2 as D, let r2 as D) where guardFn(l2, r2): break default: break } }
33.135135
162
0.606036
fbc32451f0f4e26f409dbed6354eb5705dcb6a07
3,756
// Copyright (C) 2019 Parrot Drones SAS // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import Foundation /// Utility protocol allowing to access gutma log engine internal storage. /// /// This mainly allows to query the location where GutmaLog files should be stored and /// to notify the engine when new GutmaLogs have been converted. public protocol GutmaLogStorageCore: UtilityCore { /// Directory where new gutma logs files may be stored. /// /// Multiple converters may be assigned the same convert directory. As a consequence, GutmaLog directories /// that a converter may create should have a name as unique as possible to avoid collision. /// /// The directory in question might not be existing, and the caller as the responsibility to create it if necessary, /// but should ensure to do so on a background thread. var workDir: URL { get } /// Notifies the gutma Log engine that a new GutmaLog as been converted. /// /// - Note: the GutmaLog file must be located in `workDir`. /// /// - Parameter gutmaLogUrl: URL of the converted Gutma log func notifyGutmaLogReady(gutmaLogUrl: URL) } /// Implementation of the `GutmaLogStorage` utility. class GutmaLogStorageCoreImpl: GutmaLogStorageCore { let desc: UtilityCoreDescriptor = Utilities.gutmaLogStorage /// Engine that acts as a backend for this utility. unowned let engine: GutmaLogEngine var workDir: URL { return engine.workDir } /// Constructor /// /// - Parameter engine: the engine acting as a backend for this utility init(engine: GutmaLogEngine) { self.engine = engine } func notifyGutmaLogReady(gutmaLogUrl: URL) { guard gutmaLogUrl.deletingLastPathComponent() == workDir else { ULog.w(.gutmaLogEngineTag, "GutmaLogUrl \(gutmaLogUrl) " + "is not located in the GutmaLog directory \(workDir)") return } engine.add(gutmaLog: gutmaLogUrl) } } /// Gutma Log storage utility description public class GutmaLogStorageCoreDesc: NSObject, UtilityCoreApiDescriptor { public typealias ApiProtocol = GutmaLogStorageCore public let uid = UtilityUid.gutmaLogStorage.rawValue }
42.681818
120
0.715389
ebdd35c1021a66ac33207023f74cf748bb2635c0
472
// // TranslatorViewModel.swift // TranslatorKing // // Created by skillist on 2022/01/24. // import RxCocoa import RxSwift struct TranslatorViewModel { let selectLanguageViewModel = SelectLanguageViewModel() let translatedTextOutputViewModel = TranslatedTextOutputViewModel() let sourceTextInputViewModel = SourceTextInputViewModel() //view -> viewModel let isAPIRequesting = BehaviorRelay<Bool>(value: false) //viewModel -> view }
22.47619
71
0.737288
46479a3bd130e4dbef736856be0cff03c6319e50
950
// RUN: %target-swift-frontend -primary-file %s -emit-ir -o - | %FileCheck %s // Marker protocols should have no ABI impact at all, so this source file checks // for the absence of symbols related to marker protocols. // CHECK-NOT: $s15marker_protocol1PP // CHECK-NOT: $s15marker_protocol1PMp // REQUIRES: PTRSIZE=64 @_marker public protocol P { } extension Int: P { } extension Array: P where Element: P { } // CHECK: @"$s15marker_protocol1QMp" = {{(dllexport |protected )?}}constant // CHECK-SAME: i32 trunc{{.*}}s15marker_protocolMXM{{.*}}s15marker_protocol1QMp // CHECK-SAME: i32 0, i32 5, i32 0 public protocol Q: P { func f() func g() func h() func i() func j() } // Note: no witness tables // CHECK: swiftcc void @"$s15marker_protocol7genericyyxAA1PRzlF"(%swift.opaque* noalias nocapture %0, %swift.type* %T) public func generic<T: P>(_: T) { } public func testGeneric(i: Int, array: [Int]) { generic(i) generic(array) }
27.142857
118
0.692632
14a7ac3cf7aa83d920ed1f6b7ae92c0f475064d2
3,010
// // SearchViewModel.swift // FlickrApp // // Created by aSqar on 26.11.2017. // Copyright © 2017 Askar Bakirov. All rights reserved. // import Realm import RBQFetchedResultsController import ReactiveCocoa class SearchViewModel : BaseViewModel, RBQFetchedResultsControllerDelegate { // MARK: - Public methods private(set) var updatedContentSignal:RACSignal! private var _fetchedResultsController:RBQFetchedResultsController! var fetchedResultsController:RBQFetchedResultsController! { get { if _fetchedResultsController == nil { _fetchedResultsController = RBQFetchedResultsController(fetchRequest:self.fetchRequest(), sectionNameKeyPath:nil, cacheName:nil) _fetchedResultsController.delegate = self _fetchedResultsController.performFetch() } return _fetchedResultsController } set { _fetchedResultsController = newValue } } override init() { super.init() self.updatedContentSignal = RACSubject() self.updatedContentSignal.name = "SearchResultViewModel updatedContentSignal" self.didBecomeActiveSignal.subscribeNext({ (x) in self.loadHistory() }) } func loadHistory() { self.fetchedResultsController.performFetch() } func numberOfSections() -> Int { return self.fetchedResultsController.numberOfSections() } func numberOfItemsInSection(section:Int) -> Int { return self.fetchedResultsController.numberOfRows(forSectionIndex: section) } func objectAtIndexPath(indexPath:IndexPath!) -> SearchAttemptViewModel! { let search:SearchAttempt! = self.fetchedResultsController.object(at: indexPath) as! SearchAttempt return SearchAttemptViewModel(searchAttempt:search) } // MARK: - Fetched results controller func fetchRequest() -> RBQFetchRequest! { let sd1:RLMSortDescriptor! = RLMSortDescriptor(keyPath:"dateSearched", ascending:false) let sortDescriptors:[RLMSortDescriptor]! = [ sd1 ] let fetchRequest:RBQFetchRequest! = RBQFetchRequest(entityName:"SearchAttempt", in:self.realm(), predicate:nil) fetchRequest.sortDescriptors = sortDescriptors return fetchRequest } // `fetchedResultsController` has moved as a getter. func controllerDidChangeContent(_ controller:RBQFetchedResultsController) { (self.updatedContentSignal as! RACSubject).sendNext({ (x:Any!) in }) } func controllerWillChangeContent(_ controller:RBQFetchedResultsController) { } func controller(_ controller:RBQFetchedResultsController, didChange anObject:RBQSafeRealmObject, at indexPath:IndexPath?, for type:NSFetchedResultsChangeType, newIndexPath:IndexPath?) { } func controller(_ controller:RBQFetchedResultsController, didChangeSection section:RBQFetchedResultsSectionInfo, at sectionIndex:UInt, for type:NSFetchedResultsChangeType) { } }
33.076923
189
0.716611
89db3329f381eb434e8cebf0f320c8e89c687a3a
9,642
// // ViewController.swift // URLLinker // // Created by horimislime on 2017/09/10. // Copyright © 2017 horimislime. All rights reserved. // import Cocoa import SafariServices private let extensionIdentifier = "\(Bundle.main.bundleIdentifier!).SafariExtension" final class TextFieldCellView: NSView { let textField: NSTextField = { let field = NSTextField(frame: .zero) field.drawsBackground = false field.isBezeled = false field.cell?.usesSingleLineMode = true field.cell?.lineBreakMode = .byTruncatingTail return field }() convenience init(string: String) { self.init(frame: .zero) textField.stringValue = string } override init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(textField) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func resizeSubviews(withOldSize oldSize: NSSize) { super.resizeSubviews(withOldSize: oldSize) let spacing: CGFloat = 2 textField.frame = CGRect(x: spacing, y: spacing, width: frame.width - spacing * 2, height: frame.height - spacing * 2) } } protocol CheckBoxCellViewDelegate: AnyObject { func checkBoxCellView(_ view: CheckBoxCellView, didUpdateCheckStatus status: Bool) } final class CheckBoxCellView: NSView { weak var delegate: CheckBoxCellViewDelegate? let checkBox = NSButton(checkboxWithTitle: "", target: self, action: #selector(checkBoxDidChanged(_:))) convenience init(checked: Bool) { self.init(frame: .zero) checkBox.state = checked ? .on : .off } override init(frame frameRect: NSRect) { super.init(frame: frameRect) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { addSubview(checkBox) checkBox.target = self checkBox.action = #selector(checkBoxDidChanged(_:)) } override func resizeSubviews(withOldSize oldSize: NSSize) { super.resizeSubviews(withOldSize: oldSize) let boxSize: CGFloat = 24 checkBox.frame = CGRect(x: (frame.width - boxSize) / 2, y: (frame.height - boxSize) / 2, width: boxSize, height: boxSize) } @objc private func checkBoxDidChanged(_ sender: NSButton) { delegate?.checkBoxCellView(self, didUpdateCheckStatus: sender.state == .on) } } enum ExtensionStatus { case enabled case disabled case unknown(NSError) var image: NSImage { switch self { case .enabled: return NSImage(named: NSImage.statusAvailableName)! case .disabled, .unknown(_): return NSImage(named: NSImage.statusUnavailableName)! } } var text: String { switch self { case .enabled: return "Extension is enabled." case .disabled: return "Extension is not enabled." case .unknown(let error): return "Unknown status. (\(error.localizedDescription))" } } } final class ViewController: NSViewController { @IBOutlet private weak var statusIconImageView: NSImageView! @IBOutlet private weak var extensionStatusText: NSTextField! @IBOutlet private weak var urlFormatListTableView: NSTableView! @IBOutlet private weak var segmentedControl: NSSegmentedControl! @IBOutlet private weak var nameColumn: NSTableColumn! @IBOutlet private weak var formatColumn: NSTableColumn! @IBOutlet private weak var enabledColumn: NSTableColumn! private var setting: Setting! private func updateView(withStatus status: ExtensionStatus) { DispatchQueue.main.async { self.statusIconImageView.image = status.image self.extensionStatusText.stringValue = status.text } } private func getExtensionState() { SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: extensionIdentifier) { [weak self] state, error in guard let strongSelf = self else { return } if let error = error { strongSelf.updateView(withStatus: .unknown(error as NSError)) return } if let state = state, state.isEnabled { strongSelf.updateView(withStatus: .enabled) } else { strongSelf.updateView(withStatus: .disabled) } } } override func viewWillAppear() { super.viewWillAppear() getExtensionState() } override func viewDidLoad() { super.viewDidLoad() urlFormatListTableView.delegate = self urlFormatListTableView.dataSource = self urlFormatListTableView.rowHeight = 24 NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(handleNotification(_:)), name: NSWorkspace.didActivateApplicationNotification, object: nil) if let setting = Setting.load() { self.setting = setting } else { setting = Setting.default setting.save() } urlFormatListTableView.reloadData() segmentedControl.target = self segmentedControl.action = #selector(handleSegmentedControlClicked(_:)) updateSegmentedControlState() } deinit { NSWorkspace.shared.notificationCenter.removeObserver(self) } @objc private func handleNotification(_ notification: Notification) { if NSRunningApplication.current.isActive { getExtensionState() } } @IBAction private func openExtensionButtonClicked(_ sender: NSButton) { SFSafariApplication.showPreferencesForExtension(withIdentifier: extensionIdentifier) { _ in } } @objc private func handleSegmentedControlClicked(_ sender: NSSegmentedCell) { switch sender.selectedSegment { case 0: setting.addFormat(name: "Sample", pattern: "Title: %TITLE, URL: %URL") case 1: for i in urlFormatListTableView.selectedRowIndexes { setting.urlFormats.remove(at: i) } default: preconditionFailure() } setting.save() urlFormatListTableView.reloadData() updateSegmentedControlState() } private func updateSegmentedControlState() { segmentedControl.setEnabled(urlFormatListTableView.numberOfRows < 5, forSegment: 0) segmentedControl.setEnabled(urlFormatListTableView.numberOfSelectedRows > 0, forSegment: 1) } } // MARK: - NSTableViewDelegate extension ViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { switch (tableColumn) { case nameColumn: let field = TextFieldCellView(string: setting.urlFormats[row].name) field.textField.delegate = self return field case formatColumn: let field = TextFieldCellView(string: setting.urlFormats[row].pattern) field.textField.delegate = self return field case enabledColumn: let cell = CheckBoxCellView(checked: setting.urlFormats[row].isEnabled) cell.delegate = self return cell default: preconditionFailure("Table column is illegally configured.") } } func tableViewSelectionDidChange(_ notification: Notification) { updateSegmentedControlState() } } // MARK: - NSTableViewDataSource extension ViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { guard let setting = setting else { return 0 } return setting.urlFormats.count } } // MARK: - NSTextFieldDelegate extension ViewController: NSTextFieldDelegate { func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool { let rowNumber = urlFormatListTableView.row(for: control) let columnNumber = urlFormatListTableView.column(for: control) let editedFormat = setting.urlFormats[rowNumber] switch columnNumber { case 0: setting.urlFormats[rowNumber] = URLFormat( name: fieldEditor.string, pattern: editedFormat.pattern, isEnabled: editedFormat.isEnabled, commandName: editedFormat.commandName) case 1: setting.urlFormats[rowNumber] = URLFormat( name: editedFormat.name, pattern: fieldEditor.string, isEnabled: editedFormat.isEnabled, commandName: editedFormat.commandName) default: preconditionFailure() } setting.save() return true } } // MARK: - CheckBoxCellViewDelegate extension ViewController: CheckBoxCellViewDelegate { func checkBoxCellView(_ view: CheckBoxCellView, didUpdateCheckStatus status: Bool) { let rowNumber = urlFormatListTableView.row(for: view) let editedFormat = setting.urlFormats[rowNumber] setting.urlFormats[rowNumber] = URLFormat( name: editedFormat.name, pattern: editedFormat.pattern, isEnabled: status, commandName: editedFormat.commandName) setting.save() } }
33.248276
129
0.63379
c1d9c22ea305cd9fa2110c06fa29176560a46e72
161
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(HelloKituraTests.allTests), ] } #endif
16.1
45
0.677019
75d6caffa14d4a75d52d9f0e15946904c482b42d
1,354
// // AppDelegate.swift // Repository // // Created by Julien Sechaud on 05/10/2020. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.594595
179
0.746677
29358a2656e92e8d8dde04910b59835360841e45
1,934
// // Scaffold.swift // Puyopuyo_Example // // Created by Jrwong on 2019/12/8. // Copyright © 2019 CocoaPods. All rights reserved. // import Puyopuyo import UIKit class NavBar: ZBox, Eventable { enum Event { case tapLeading case tapTrailing case tapTitle } var emitter = SimpleIO<Event>() init(title: @escaping ViewBuilder, leading: ViewBuilder? = nil, tailing: ViewBuilder? = nil, navHeight: State<CGFloat> = State(44)) { super.init(frame: .zero) attach { VBox().attach($0) { leading?($0).attach($0) } .alignment(.left) .onTap(to: self) { s, _ in s.emitter.input(value: .tapLeading) } VBox().attach($0) { title($0).attach($0) .size(.wrap, .wrap) } .alignment(.center) .onTap(to: self) { s, _ in s.emitter.input(value: .tapTitle) } VBox().attach($0) { tailing?($0).attach($0) } .alignment(.right) .onTap(to: self) { s, _ in s.emitter.input(value: .tapTrailing) } } .justifyContent(.vertCenter) .padding(left: 16, right: 16) .width(.fill) .height(navHeight) } convenience init(title: String) { self.init( title: { Label(title).attach($0) .fontSize(20, weight: .bold) .view }, leading: { UIButton().attach($0) .image(UIImage(systemName: "arrow.backward.circle.fill")) .margin(all: 10, left: 0) .view } ) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError() } }
24.481013
77
0.457084
8759bc8141e0fc6afbeb4d5de2e023a6837269d2
527
// // UITableView+Extension.swift // BookMadi // // Created by Siddhant Mishra on 08/02/21. // import Foundation import UIKit extension UITableView { func showActivityIndicator() { DispatchQueue.main.async { let activityView = UIActivityIndicatorView(style: .large) self.backgroundView = activityView activityView.startAnimating() } } func hideActivityIndicator() { DispatchQueue.main.async { self.backgroundView = nil } } }
20.269231
69
0.626186
7af34c154c28236f28eff689c2dbd70e7ff7dcce
9,724
// // DraggableView.swift // Charts // // Created by Daria Novodon on 15/03/2019. // Copyright © 2019 dnovodon. All rights reserved. // import UIKit private struct Constants { static let handleWidth: CGFloat = 11 static let iconHeight: CGFloat = 10 static let iconWidth: CGFloat = 5.5 } class DraggableView: UIView, DayNightViewConfigurable { // MARK: - Properties private let leftEdgeView = UIView() private let leftIconView = UIImageView(image: #imageLiteral(resourceName: "chevron-left")) private let leftEdgeDraggingView = UIView() private let rightEdgeView = UIView() private let rightIconView = UIImageView(image: #imageLiteral(resourceName: "chevron-right")) private let rightEdgeDraggingView = UIView() private let centerDraggingView = UIView() private let topSeparator = UIView() private let bottomSeparator = UIView() private let leftDimmingView = UIView() private let rightDimmingView = UIView() private let leftDraggingThrottler = Throttler(mustRunOnceInInterval: 0.016) private let rightDraggingThrottler = Throttler(mustRunOnceInInterval: 0.016) private var ignoreValueChange = false private var updatedSubviewsForBounds: CGRect = .zero private var centerDraggingViewWidth: CGFloat = 0 private var leftEdgeViewOriginX: CGFloat = 0 { willSet { guard !ignoreValueChange, abs(newValue - leftEdgeViewOriginX) > 0.01 else { return } leftDraggingThrottler.addWork { [weak self] in guard let self = self else { return } self.onLeftHandleValueChanged?(Double(newValue / self.bounds.width)) } } } private var rightEdgeViewMaxX: CGFloat = 0 { willSet { guard !ignoreValueChange, abs(newValue - rightEdgeViewMaxX) > 0.01 else { return } rightDraggingThrottler.addWork { [weak self] in guard let self = self else { return } self.onRightHandleValueChanged?(Double(newValue / self.bounds.width)) } } } var leftHandleValue: Double { get { return Double(leftEdgeView.frame.minX / bounds.width) } set { ignoreValueChange = true leftEdgeViewOriginX = CGFloat(newValue) * bounds.width updateSubviewFrames() ignoreValueChange = false } } var rightHandleValue: Double { get { return Double(rightEdgeView.frame.maxX / bounds.width) } set { ignoreValueChange = true rightEdgeViewMaxX = CGFloat(newValue) * bounds.width updateSubviewFrames() ignoreValueChange = false } } // MARK: - Callbacks var onBothValueChanged: ((Double, Double) -> Void)? var onRightHandleValueChanged: ((Double) -> Void)? var onLeftHandleValueChanged: ((Double) -> Void)? // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overrides override func layoutSubviews() { super.layoutSubviews() guard bounds.width > 0, bounds.height > 0 else { return } if rightEdgeViewMaxX == 0 { rightEdgeViewMaxX = bounds.size.width } if bounds != updatedSubviewsForBounds { updatedSubviewsForBounds = bounds updateSubviewFrames() } } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { if leftEdgeDraggingView.frame.contains(point) || rightEdgeDraggingView.frame.contains(point) { return true } return bounds.contains(point) } // MARK: - Public methods func configure(dayNightModeToggler: DayNightModeToggler) { let backgroundColor = dayNightModeToggler.draggableViewHandleColor let overlayColor = dayNightModeToggler.draggableViewOverlayColor leftEdgeView.backgroundColor = backgroundColor rightEdgeView.backgroundColor = backgroundColor topSeparator.backgroundColor = backgroundColor bottomSeparator.backgroundColor = backgroundColor leftDimmingView.backgroundColor = overlayColor rightDimmingView.backgroundColor = overlayColor } // MARK: - Setup private func setup() { addSubview(leftDimmingView) addSubview(rightDimmingView) addSubview(leftEdgeView) addSubview(leftIconView) addSubview(rightEdgeView) addSubview(rightIconView) addSubview(centerDraggingView) addSubview(leftEdgeDraggingView) addSubview(rightEdgeDraggingView) addSubview(topSeparator) addSubview(bottomSeparator) leftIconView.tintColor = .white leftIconView.frame.size = CGSize(width: Constants.iconWidth, height: Constants.iconHeight) leftEdgeView.contentMode = .scaleAspectFit rightIconView.tintColor = .white rightIconView.frame.size = CGSize(width: Constants.iconWidth, height: Constants.iconHeight) rightIconView.contentMode = .scaleAspectFit leftEdgeDraggingView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(dragLeft(_:)))) rightEdgeDraggingView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(dragRight(_:)))) centerDraggingView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(dragCenter(_:)))) } // MARK: - Private methods private func updateSubviewFrames() { leftEdgeView.frame = CGRect(x: leftEdgeViewOriginX, y: 0, width: Constants.handleWidth, height: bounds.size.height) leftEdgeView.roundCorners(corners: [.bottomLeft, .topLeft], radius: 2) leftIconView.center = leftEdgeView.center rightEdgeView.frame = CGRect(x: rightEdgeViewMaxX - Constants.handleWidth, y: 0, width: Constants.handleWidth, height: bounds.size.height) rightEdgeView.roundCorners(corners: [.topRight, .bottomRight], radius: 2) rightIconView.center = rightEdgeView.center topSeparator.frame = CGRect(x: leftEdgeView.frame.maxX, y: 0, width: rightEdgeView.frame.minX - leftEdgeView.frame.maxX, height: 1) bottomSeparator.frame = CGRect(x: leftEdgeView.frame.maxX, y: bounds.size.height - 1, width: rightEdgeView.frame.minX - leftEdgeView.frame.maxX, height: 1) let isFullyCollapsed = abs(leftEdgeViewOriginX + 2 * Constants.handleWidth - rightEdgeViewMaxX) < 1 let draggingViewsWidth: CGFloat = isFullyCollapsed ? 2 * Constants.handleWidth : 3 * Constants.handleWidth leftEdgeDraggingView.frame.size = CGSize(width: draggingViewsWidth, height: leftEdgeView.frame.height) leftEdgeDraggingView.center = leftEdgeView.center rightEdgeDraggingView.frame.size = leftEdgeDraggingView.frame.size rightEdgeDraggingView.center = rightEdgeView.center let centerWidth = rightEdgeView.frame.origin.x - leftEdgeView.frame.maxX centerDraggingView.frame = CGRect(x: leftEdgeView.frame.maxX, y: 0, width: centerWidth, height: bounds.size.height) leftDimmingView.frame = CGRect(x: 0, y: 1, width: leftEdgeView.frame.minX + Constants.handleWidth, height: bounds.size.height - 2) rightDimmingView.frame = CGRect(x: rightEdgeView.frame.maxX - Constants.handleWidth, y: 1, width: bounds.size.width - rightEdgeView.frame.maxX + Constants.handleWidth, height: bounds.size.height - 2) } // MARK: - Actions @objc private func dragLeft(_ gestureRecognizer: UIPanGestureRecognizer) { switch gestureRecognizer.state { case .began, .changed: let translation = gestureRecognizer.translation(in: self) var newOriginX = max(leftEdgeViewOriginX + translation.x, 0) newOriginX = min(newOriginX, rightEdgeViewMaxX - 2 * Constants.handleWidth) leftEdgeViewOriginX = newOriginX updateSubviewFrames() gestureRecognizer.setTranslation(.zero, in: self) default: break } } @objc private func dragRight(_ gestureRecognizer: UIPanGestureRecognizer) { switch gestureRecognizer.state { case .began, .changed: let translation = gestureRecognizer.translation(in: self) var newMaxX = min(rightEdgeViewMaxX + translation.x, bounds.width) newMaxX = max(newMaxX, leftEdgeViewOriginX + 2 * Constants.handleWidth) rightEdgeViewMaxX = newMaxX updateSubviewFrames() gestureRecognizer.setTranslation(.zero, in: self) default: break } } @objc private func dragCenter(_ gestureRecognizer: UIPanGestureRecognizer) { if gestureRecognizer.state == .began { centerDraggingViewWidth = centerDraggingView.frame.width } switch gestureRecognizer.state { case .began, .changed: var translationX = gestureRecognizer.translation(in: self).x var newOriginX = leftEdgeView.frame.origin.x + translationX if newOriginX < 0 { translationX -= newOriginX newOriginX = 0 } var newMaxX = rightEdgeView.frame.maxX + translationX if newMaxX > bounds.width { translationX -= newMaxX - bounds.width newOriginX = leftEdgeView.frame.origin.x + translationX newMaxX = bounds.width } ignoreValueChange = true leftEdgeViewOriginX = newOriginX rightEdgeViewMaxX = newMaxX ignoreValueChange = false DispatchQueue.main.async { self.onBothValueChanged?(self.leftHandleValue, self.rightHandleValue) } updateSubviewFrames() gestureRecognizer.setTranslation(.zero, in: self) default: break } } }
37.114504
119
0.687988
fb6603dcd773952a5d8fb0392c09f40e2b94536c
1,397
// // Landmark.swift // SwiftUIExample // // Created by 이광용 on 2019/06/11. // Copyright © 2019 GwangYongLee. All rights reserved. // import Foundation import SwiftUI import CoreLocation struct Landmark: Hashable, Codable, Identifiable { var id: Int var name: String var imageName: String fileprivate var coordinates: Coordinates var state: String var park: String var category: Category var isFavorite: Bool var isFeatured: Bool var locationCoordinate: CLLocationCoordinate2D { CLLocationCoordinate2D( latitude: coordinates.latitude, longitude: coordinates.longitude) } enum Category: String, CaseIterable, Codable, Hashable { case featured = "Featured" case lakes = "Lakes" case rivers = "Rivers" case mountains = "Mountains" } } let mockLandmark = Landmark(id: 1001, name: "Turtle Rock", imageName: "turtlerock", coordinates: Coordinates(latitude: -116.166868, longitude: 34.011286), state: "California", park: "Joshua Tree National Park", category: .rivers, isFavorite: true, isFeatured: true)
30.369565
75
0.553329
23505883a042bd763fcb861ef4070118805866e7
2,172
// // AppDelegate.swift // Una_iOS // // Created by 하준혁 on 2016. 11. 4.. // Copyright © 2016년 하준혁(Enoxaiming). All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.212766
285
0.753683
f888ae7c60f8331c9e04f211377549ad21e9aa0e
726
class AmenityItem: NamedHotelDetailsItem { var image: UIImage init(name: String, image: UIImage) { self.image = image super.init(name: name) } override func cellHeight(tableWidth: CGFloat) -> CGFloat { return HLHotelDetailsFeaturesCell.estimatedHeight(first, last: last) } override func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let amenityCell = tableView.dequeueReusableCell(withIdentifier: HLHotelDetailsFeaturesCell.hl_reuseIdentifier(), for: indexPath) as! HLHotelDetailsFeaturesCell amenityCell.configureForAmenity(self) amenityCell.first = first amenityCell.last = last return amenityCell } }
33
167
0.709366
61a90940c277d0ffff13f94aa6ef3bf6522c09ca
3,468
// // ChannelsNS.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 16/05/18. // import Foundation class ChannelsNS: BaseNS { static let shared = ChannelsNS() lazy var awesomeRequester: AwesomeCoreRequester = AwesomeCoreRequester(cacheType: .realm) override init() {} var channelsRequest: URLSessionDataTask? var allChannelsRequest: URLSessionDataTask? let method: URLMethod = .GET func fetchChannelData(with academyId: Int, params: AwesomeCoreNetworkServiceParams = .standard, response: @escaping (ChannelData?, ErrorData?) -> Void) { func processResponse(data: Data?, error: ErrorData? = nil, response: @escaping (ChannelData?, ErrorData?) -> Void ) -> Bool { if let jsonObject = data { self.channelsRequest = nil response(ChannelsMP.parseChannelsFrom(jsonObject), nil) return true } else { self.channelsRequest = nil if let error = error { response(nil, error) return false } response(nil, ErrorData(.unknown, "response Data for Member Benefits could not be parsed")) return false } } let url = ACConstants.buildURLWith(format: ACConstants.shared.channelsWithAcademy, with: academyId) if params.contains(.shouldFetchFromCache) { _ = processResponse(data: dataFromCache(url, method: method, params: params, bodyDict: nil), response: response) } channelsRequest = awesomeRequester.performRequestAuthorized( url, forceUpdate: true, method: method, completion: { (data, error, responseType) in if processResponse(data: data, error: error, response: response) { self.saveToCache(url, method: self.method, bodyDict: nil, data: data) } }) } func fetchAllChannels(params: AwesomeCoreNetworkServiceParams = .standard, response: @escaping ([AllChannels], ErrorData?) -> Void) { func processResponse(data: Data?, error: ErrorData? = nil, response: @escaping ([AllChannels], ErrorData?) -> Void ) -> Bool { if let jsonObject = data { self.allChannelsRequest = nil response(ChannelsMP.parseAllChannelsFrom(jsonObject), nil) return true } else { self.allChannelsRequest = nil if let error = error { response([], error) return false } response([], ErrorData(.unknown, "response Data for Member Benefits could not be parsed")) return false } } let url = ACConstants.shared.channels if params.contains(.shouldFetchFromCache) { _ = processResponse(data: dataFromCache(url, method: method, params: params, bodyDict: nil), response: response) } allChannelsRequest = awesomeRequester.performRequestAuthorized( url, forceUpdate: true, method: method, completion: { (data, error, responseType) in if processResponse(data: data, error: error, response: response) { self.saveToCache(url, method: self.method, bodyDict: nil, data: data) } }) } }
40.325581
157
0.586794
d65e2fd379cf628d73af7a2c78bb301a8784a58a
5,507
import XCTest import CryptoKit @testable import WalletConnect extension Curve25519.KeyAgreement.PrivateKey: GenericPasswordConvertible {} final class KeychainStorageTests: XCTestCase { var sut: KeychainStorage! var fakeKeychain: KeychainServiceFake! let defaultIdentifier = "key" override func setUp() { fakeKeychain = KeychainServiceFake() sut = KeychainStorage(keychainService: fakeKeychain) } override func tearDown() { try? sut.deleteAll() sut = nil fakeKeychain = nil } func testAdd() { let privateKey = Curve25519.KeyAgreement.PrivateKey() XCTAssertNoThrow(try sut.add(privateKey, forKey: "id-1")) XCTAssertNoThrow(try sut.add(privateKey, forKey: "id-2")) } func testAddDuplicateItemError() { let privateKey = Curve25519.KeyAgreement.PrivateKey() try? sut.add(privateKey, forKey: defaultIdentifier) XCTAssertThrowsError(try sut.add(privateKey, forKey: defaultIdentifier)) { error in guard let error = error as? KeychainError else { XCTFail(); return } XCTAssertEqual(error.status, errSecDuplicateItem) } } func testAddUnknownFailure() { fakeKeychain.errorStatus = errSecMissingEntitlement let privateKey = Curve25519.KeyAgreement.PrivateKey() XCTAssertThrowsError(try sut.add(privateKey, forKey: defaultIdentifier)) { error in XCTAssert(error is KeychainError) } } func testRead() { let privateKey = Curve25519.KeyAgreement.PrivateKey() do { try sut.add(privateKey, forKey: defaultIdentifier) let retrievedKey: Curve25519.KeyAgreement.PrivateKey = try sut.read(key: defaultIdentifier) XCTAssertEqual(privateKey, retrievedKey) } catch { XCTFail() } } func testReadItemNotFoundFails() { do { let _: Curve25519.KeyAgreement.PrivateKey = try sut.read(key: "") XCTFail() } catch { guard let error = error as? KeychainError else { XCTFail(); return } XCTAssertEqual(error.status, errSecItemNotFound) } } func testReadUnknownFailure() { let privateKey = Curve25519.KeyAgreement.PrivateKey() do { try sut.add(privateKey, forKey: defaultIdentifier) fakeKeychain.errorStatus = errSecMissingEntitlement let _: Curve25519.KeyAgreement.PrivateKey = try sut.read(key: defaultIdentifier) XCTFail() } catch { XCTAssert(error is KeychainError) } } func testUpdate() { let privateKeyA = Curve25519.KeyAgreement.PrivateKey() let privateKeyB = Curve25519.KeyAgreement.PrivateKey() do { try sut.add(privateKeyA, forKey: defaultIdentifier) try sut.update(privateKeyB, forKey: defaultIdentifier) let retrievedKey: Curve25519.KeyAgreement.PrivateKey = try sut.read(key: defaultIdentifier) XCTAssertEqual(privateKeyB, retrievedKey) } catch { XCTFail() } } func testUpdateItemNotFoundFails() { let privateKey = Curve25519.KeyAgreement.PrivateKey() XCTAssertThrowsError(try sut.update(privateKey, forKey: defaultIdentifier)) { error in guard let error = error as? KeychainError else { XCTFail(); return } XCTAssertEqual(error.status, errSecItemNotFound) } } func testUpdateUnknownFailure() { let privateKeyA = Curve25519.KeyAgreement.PrivateKey() let privateKeyB = Curve25519.KeyAgreement.PrivateKey() do { try sut.add(privateKeyA, forKey: defaultIdentifier) fakeKeychain.errorStatus = errSecMissingEntitlement try sut.update(privateKeyB, forKey: defaultIdentifier) XCTFail() } catch { XCTAssert(error is KeychainError) } } func testDelete() { let privateKey = Curve25519.KeyAgreement.PrivateKey() try? sut.add(privateKey, forKey: defaultIdentifier) do { try sut.delete(key: defaultIdentifier) XCTAssertNil(try sut.readData(key: defaultIdentifier)) } catch { XCTFail() } } func testDeleteNotFoundDoesntThrowError() { XCTAssertNoThrow(try sut.delete(key: defaultIdentifier)) } func testDeleteUnknownFailure() { fakeKeychain.errorStatus = errSecMissingEntitlement let privateKey = Curve25519.KeyAgreement.PrivateKey() try? sut.add(privateKey, forKey: defaultIdentifier) do { try sut.delete(key: defaultIdentifier) XCTFail() } catch { XCTAssert(error is KeychainError) } } func testDeleteAll() { do { let keys = (1...10).map { "key-\($0)" } try keys.forEach { let privateKey = Curve25519.KeyAgreement.PrivateKey() try sut.add(privateKey, forKey: $0) } try sut.deleteAll() try keys.forEach { XCTAssertNil(try sut.readData(key: $0)) } } catch { XCTFail() } } func testDeleteAllFromCleanKeychain() { XCTAssertThrowsError(try sut.deleteAll()) { error in XCTAssert(error is KeychainError) } } }
33.375758
103
0.614127
9c39f6d6a56b5e5f26e53d42f04aefc346f07402
515
// // SelectThemeCell.swift // Demo // // Created by Gesen on 16/3/2. // Copyright © 2016年 Gesen. All rights reserved. // import UIKit class SelectThemeCell: BaseCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var themeIcon: UIImageView! override func awakeFromNib() { super.awakeFromNib() title.theme_textColor = GlobalPicker.textColor themeIcon.theme_image = ["icon_theme_red", "icon_theme_yellow", "icon_theme_blue", "icon_theme_light"] } }
21.458333
110
0.669903
8f62faf2bfc6c4e6ce59397a9838b78bddb089dd
205
/// Importing FuentSQLite should also import Fluent and SQLite /// since they are almost always needed. @_exported import Core @_exported import Fluent @_exported import SQLite @_exported import FluentSQL
29.285714
62
0.809756
7a1de4b8b171dbe6e55faca6353943c380a524e4
908
// // FirstAppTests.swift // FirstAppTests // // Created by SALMAN ZAFAR on 06/01/20. // Copyright © 2020 SALMAN ZAFAR. All rights reserved. // import XCTest @testable import FirstApp class FirstAppTests: XCTestCase { override func 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. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.942857
111
0.655286
23bd3d438ddacdae4ba8b1858b98f8fa7e9383d8
547
// // Buildkite_Fastlane_DemoUITests.swift // Buildkite Fastlane DemoUITests // // Created by Tim Lucas on 8/08/2015. // Copyright © 2015 Buildkite. All rights reserved. // import XCTest class Buildkite_Fastlane_DemoUITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } func testExample() { // Do something stupid XCUIApplication().images["Logo"].tap() XCTAssert(1 == 1) } }
18.862069
52
0.601463
0a563b47ffb5f8607e446ff5648d870e0ac7ceb5
6,454
// // SearchViewModel.swift // GitHubSearchApp // // Created by burt on 2018. 9. 25.. // Copyright © 2018년 Burt.K. All rights reserved. // import Foundation import ReactComponentKit import RxSwift import RxCocoa // namespace enum SearchView { } struct SearchState: State { enum SearchScope { case user case repo } enum ViewState: Equatable { case hello case loading case loadingIncicator case empty case list case error(action: Action) static func == (lhs: SearchState.ViewState, rhs: SearchState.ViewState) -> Bool { switch (lhs, rhs) { case (.hello, .hello): return true case (.loading, loading): return true case (.loadingIncicator, loadingIncicator): return true case (.empty, empty): return true case (.list, list): return true default: return false } } } var searchScope: SearchScope = .user var viewState: ViewState = .hello var keyword: String = "" var canLoadMore: Bool = false var isLoadingMore: Bool = false var page: Int = 1 var perPage: Int = 20 var users: [User] = [] var userSort: GitHubSearchService.UserSort = .repositories var repos: [Repo] = [] var repoSort: GitHubSearchService.RepoSort = .stars var sections: [DefaultSectionModel] = [] var route: String? = nil var error: RCKError? = nil } class SearchViewModel: RCKViewModel<SearchState> { struct Outputs { let viewState = Output<SearchState.ViewState>(value: .hello) let sections = Output<[DefaultSectionModel]>(value: []) let route = Output<String?>(value: nil) fileprivate init() { } } lazy var output: Outputs = { return Outputs() }() override func setupStore() { initStore { store in store.initial(state: SearchState()) store.beforeActionFlow { [unowned self] in self.setViewState(for: $0) let action = self.makeAction($0) return logAction(action) } store.afterStateFlow { $0.copy { $0.route = nil $0.isLoadingMore = false } } store.flow(action: ShowEmptyViewAction.self) .flow( { [weak self] state, _ in self?.setPage(state: state) }, { [weak self] state, _ in self?.makeSectionModel(state: state) }, selectViewState ) store.flow(action: ClickItemAction.self) .flow(handleClickItem) store.flow(action: SearchUsersAction.self) .flow( selectSearchScope, setKeyword, setPage, awaitFlow(searchUsersReducer), { [weak self] state, _ in self?.makeSectionModel(state: state) }, selectViewState ) store.flow(action: SearchReposAction.self) .flow( selectSearchScope, setKeyword, setPage, awaitFlow(searchReposReducer), { [weak self] state, _ in self?.makeSectionModel(state: state) }, selectViewState ) } } private func makeAction(_ action: Action) -> Action { return withState { state in switch action { case let act as InputSearchKeywordAction: if state.searchScope == .user { return SearchUsersAction(keyword: act.keyword, page: 1, perPage: state.perPage, sort: state.userSort) } else { return SearchReposAction(keyword: act.keyword, page: 1, perPage: state.perPage, sort: state.repoSort) } case let act as SelectSearchScopeAction: if act.searchScope == .user { return SearchUsersAction(keyword: state.keyword, page: 1, perPage: state.perPage, sort: state.userSort) } else { return SearchReposAction(keyword: state.keyword, page: 1, perPage: state.perPage, sort: state.repoSort) } case is LoadMoreAction: if state.canLoadMore == false || state.isLoadingMore { return VoidAction() } if state.searchScope == .user { return SearchUsersAction(keyword: state.keyword, page: state.page + 1, perPage: state.perPage, sort: state.userSort) } else { return SearchReposAction(keyword: state.keyword, page: state.page + 1, perPage: state.perPage, sort: state.repoSort) } default: break } return action } } override func on(newState: SearchState) { output.sections.accept(newState.sections) output.viewState.accept(newState.viewState) output.route.accept(newState.route) } override func on(error: RCKError) { output.viewState.accept(.error(action: error.action)) } func showEmptyView() { dispatch(action: ShowEmptyViewAction()) } private func setViewState(for action: Action) { func viewState(for action: Action, state: SearchState) -> SearchState.ViewState { let hasContent = state.sections.isEmpty == false switch action { case let act as InputSearchKeywordAction: if act.keyword.isEmpty { return hasContent ? .list : .hello } else { return hasContent ? .loadingIncicator : .loading } case is SelectSearchScopeAction: return .loadingIncicator default: return state.viewState } } setState { state in let vs = viewState(for: action, state: state) return state.copy { $0.viewState = vs } } } }
32.59596
136
0.522157
798d6c74c24231a2cf239784d798b0ed7642166c
1,764
// // StatisticsViewController.swift // Textor // // Created by Matteo Bart on 8/2/19. // Copyright © 2019 Silver Fox. All rights reserved. // import UIKit class StatisticsViewController: UIViewController { @IBOutlet weak var statisticsLabel: UILabel! @IBOutlet weak var linesLabel: UILabel! @IBOutlet weak var wordsLabel: UILabel! @IBOutlet weak var characterWSpacesLabel: UILabel! @IBOutlet weak var characterWoSpacesLabel: UILabel! @IBOutlet weak var numLinesLabel: UILabel! @IBOutlet weak var numWordsLabel: UILabel! @IBOutlet weak var numCharactersWSpacesLabel: UILabel! @IBOutlet weak var numCharactersWoSpacesLabel: UILabel! @IBOutlet weak var countNoteLabel: UILabel! var text: String = "" override func viewDidLoad() { super.viewDidLoad() //calculate statistics var numLines = 0 let numCharsWSpaces = text.count var numCharsWoSpaces = text.count for char in text { if char == "\n"{ numLines += 1 numCharsWoSpaces -= 1 } else if char == " " { numCharsWoSpaces -= 1 } else if char == "\t" { numCharsWoSpaces -= 1 } } let comp = text.components(separatedBy: [",", " ", "!",".","?", "\n"]).filter({!$0.isEmpty}) let numWords = comp.count numCharactersWoSpacesLabel.text = numCharsWoSpaces.description numCharactersWSpacesLabel.text = numCharsWSpaces.description numWordsLabel.text = numWords.description numLinesLabel.text = numLines.description } /* // 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. } */ }
28
103
0.720522
bb79f58c77387c34b24ebd61a34ea47e809c1c77
11,117
// swiftlint:disable all // This file is generated. import Foundation import Turf public struct PointAnnotation: Annotation { /// Identifier for this annotation public let id: String /// The feature backing this annotation public internal(set) var feature: Turf.Feature /// Properties associated with the annotation public var userInfo: [String: Any]? { didSet { feature.properties?["userInfo"] = userInfo } } public var type: AnnotationType = .point /// Create a point annotation with a `Turf.Point` and an optional identifier. public init(id: String = UUID().uuidString, point: Turf.Point) { self.id = id self.feature = Turf.Feature(point) self.feature.properties = ["annotation-id": id] } /// Create a point annotation with a coordinate and an optional identifier /// - Parameters: /// - id: Optional identifier for this annotation /// - coordinate: Coordinate where this annotation should be rendered public init(id: String = UUID().uuidString, coordinate: CLLocationCoordinate2D) { let point = Turf.Point(coordinate) self.init(id: id, point: point) } // MARK: - Properties - /// Set of used data driven properties internal var dataDrivenPropertiesUsedSet: Set<String> = [] /// Part of the icon placed closest to the anchor. public var iconAnchor: IconAnchor? { didSet { feature.properties?["icon-anchor"] = iconAnchor?.rawValue if iconAnchor != nil { dataDrivenPropertiesUsedSet.insert("icon-anchor") } } } /// Name of image in sprite to use for drawing an image background. public var iconImage: String? { didSet { feature.properties?["icon-image"] = iconImage if iconImage != nil { dataDrivenPropertiesUsedSet.insert("icon-image") } } } /// Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. Each component is multiplied by the value of `icon-size` to obtain the final offset in pixels. When combined with `icon-rotate` the offset will be as if the rotated direction was up. public var iconOffset: [Double]? { didSet { feature.properties?["icon-offset"] = iconOffset if iconOffset != nil { dataDrivenPropertiesUsedSet.insert("icon-offset") } } } /// Rotates the icon clockwise. public var iconRotate: Double? { didSet { feature.properties?["icon-rotate"] = iconRotate if iconRotate != nil { dataDrivenPropertiesUsedSet.insert("icon-rotate") } } } /// Scales the original size of the icon by the provided factor. The new pixel size of the image will be the original pixel size multiplied by `icon-size`. 1 is the original size; 3 triples the size of the image. public var iconSize: Double? { didSet { feature.properties?["icon-size"] = iconSize if iconSize != nil { dataDrivenPropertiesUsedSet.insert("icon-size") } } } /// Sorts features in ascending order based on this value. Features with lower sort keys are drawn and placed first. When `icon-allow-overlap` or `text-allow-overlap` is `false`, features with a lower sort key will have priority during placement. When `icon-allow-overlap` or `text-allow-overlap` is set to `true`, features with a higher sort key will overlap over features with a lower sort key. public var symbolSortKey: Double? { didSet { feature.properties?["symbol-sort-key"] = symbolSortKey if symbolSortKey != nil { dataDrivenPropertiesUsedSet.insert("symbol-sort-key") } } } /// Part of the text placed closest to the anchor. public var textAnchor: TextAnchor? { didSet { feature.properties?["text-anchor"] = textAnchor?.rawValue if textAnchor != nil { dataDrivenPropertiesUsedSet.insert("text-anchor") } } } /// Value to use for a text label. If a plain `string` is provided, it will be treated as a `formatted` with default/inherited formatting options. public var textField: String? { didSet { feature.properties?["text-field"] = textField if textField != nil { dataDrivenPropertiesUsedSet.insert("text-field") } } } /// Text justification options. public var textJustify: TextJustify? { didSet { feature.properties?["text-justify"] = textJustify?.rawValue if textJustify != nil { dataDrivenPropertiesUsedSet.insert("text-justify") } } } /// Text tracking amount. public var textLetterSpacing: Double? { didSet { feature.properties?["text-letter-spacing"] = textLetterSpacing if textLetterSpacing != nil { dataDrivenPropertiesUsedSet.insert("text-letter-spacing") } } } /// The maximum line width for text wrapping. public var textMaxWidth: Double? { didSet { feature.properties?["text-max-width"] = textMaxWidth if textMaxWidth != nil { dataDrivenPropertiesUsedSet.insert("text-max-width") } } } /// Offset distance of text from its anchor. Positive values indicate right and down, while negative values indicate left and up. If used with text-variable-anchor, input values will be taken as absolute values. Offsets along the x- and y-axis will be applied automatically based on the anchor position. public var textOffset: [Double]? { didSet { feature.properties?["text-offset"] = textOffset if textOffset != nil { dataDrivenPropertiesUsedSet.insert("text-offset") } } } /// Radial offset of text, in the direction of the symbol's anchor. Useful in combination with `text-variable-anchor`, which defaults to using the two-dimensional `text-offset` if present. public var textRadialOffset: Double? { didSet { feature.properties?["text-radial-offset"] = textRadialOffset if textRadialOffset != nil { dataDrivenPropertiesUsedSet.insert("text-radial-offset") } } } /// Rotates the text clockwise. public var textRotate: Double? { didSet { feature.properties?["text-rotate"] = textRotate if textRotate != nil { dataDrivenPropertiesUsedSet.insert("text-rotate") } } } /// Font size. public var textSize: Double? { didSet { feature.properties?["text-size"] = textSize if textSize != nil { dataDrivenPropertiesUsedSet.insert("text-size") } } } /// Specifies how to capitalize text, similar to the CSS `text-transform` property. public var textTransform: TextTransform? { didSet { feature.properties?["text-transform"] = textTransform?.rawValue if textTransform != nil { dataDrivenPropertiesUsedSet.insert("text-transform") } } } /// The color of the icon. This can only be used with sdf icons. public var iconColor: ColorRepresentable? { didSet { feature.properties?["icon-color"] = iconColor?.rgbaDescription if iconColor != nil { dataDrivenPropertiesUsedSet.insert("icon-color") } } } /// Fade out the halo towards the outside. public var iconHaloBlur: Double? { didSet { feature.properties?["icon-halo-blur"] = iconHaloBlur if iconHaloBlur != nil { dataDrivenPropertiesUsedSet.insert("icon-halo-blur") } } } /// The color of the icon's halo. Icon halos can only be used with SDF icons. public var iconHaloColor: ColorRepresentable? { didSet { feature.properties?["icon-halo-color"] = iconHaloColor?.rgbaDescription if iconHaloColor != nil { dataDrivenPropertiesUsedSet.insert("icon-halo-color") } } } /// Distance of halo to the icon outline. public var iconHaloWidth: Double? { didSet { feature.properties?["icon-halo-width"] = iconHaloWidth if iconHaloWidth != nil { dataDrivenPropertiesUsedSet.insert("icon-halo-width") } } } /// The opacity at which the icon will be drawn. public var iconOpacity: Double? { didSet { feature.properties?["icon-opacity"] = iconOpacity if iconOpacity != nil { dataDrivenPropertiesUsedSet.insert("icon-opacity") } } } /// The color with which the text will be drawn. public var textColor: ColorRepresentable? { didSet { feature.properties?["text-color"] = textColor?.rgbaDescription if textColor != nil { dataDrivenPropertiesUsedSet.insert("text-color") } } } /// The halo's fadeout distance towards the outside. public var textHaloBlur: Double? { didSet { feature.properties?["text-halo-blur"] = textHaloBlur if textHaloBlur != nil { dataDrivenPropertiesUsedSet.insert("text-halo-blur") } } } /// The color of the text's halo, which helps it stand out from backgrounds. public var textHaloColor: ColorRepresentable? { didSet { feature.properties?["text-halo-color"] = textHaloColor?.rgbaDescription if textHaloColor != nil { dataDrivenPropertiesUsedSet.insert("text-halo-color") } } } /// Distance of halo to the font outline. Max text halo width is 1/4 of the font-size. public var textHaloWidth: Double? { didSet { feature.properties?["text-halo-width"] = textHaloWidth if textHaloWidth != nil { dataDrivenPropertiesUsedSet.insert("text-halo-width") } } } /// The opacity at which the text will be drawn. public var textOpacity: Double? { didSet { feature.properties?["text-opacity"] = textOpacity if textOpacity != nil { dataDrivenPropertiesUsedSet.insert("text-opacity") } } } // MARK: - Image Convenience - public var image: Image? { didSet { self.iconImage = image?.name } } } // End of generated file. // swiftlint:enable all
35.404459
401
0.589458
ddae04a72cc5b734e6c5ba25b7f33f5fb4054394
7,912
// // ControlsViewController.swift // CustomControls // // Copyright © 2019 Brightcove, Inc. All rights reserved. // import UIKit import BrightcovePlayerSDK fileprivate struct ControlConstants { static let VisibleDuration: TimeInterval = 5.0 static let AnimateInDuration: TimeInterval = 0.1 static let AnimateOutDuraton: TimeInterval = 0.2 } class ControlsViewController: UIViewController { weak var delegate: ControlsViewControllerFullScreenDelegate? private weak var currentPlayer: AVPlayer? @IBOutlet weak private var controlsContainer: UIView! @IBOutlet weak private var playPauseButton: UIButton! @IBOutlet weak private var playheadLabel: UILabel! @IBOutlet weak private var playheadSlider: UISlider! @IBOutlet weak private var durationLabel: UILabel! @IBOutlet weak private var fullscreenButton: UIView! @IBOutlet weak private var externalScreenButton: MPVolumeView! private var controlTimer: Timer? private var playingOnSeek: Bool = false private lazy var numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.paddingCharacter = "0" formatter.minimumIntegerDigits = 2 return formatter }() // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Used for hiding and showing the controls. let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapDetected)) tapRecognizer.numberOfTapsRequired = 1 tapRecognizer.numberOfTouchesRequired = 1 tapRecognizer.delegate = self view.addGestureRecognizer(tapRecognizer) externalScreenButton.showsRouteButton = true externalScreenButton.showsVolumeSlider = false } // MARK: - Misc @objc private func tapDetected() { if playPauseButton.isSelected { if controlsContainer.alpha == 0.0 { fadeControlsIn() } else if (controlsContainer.alpha == 1.0) { fadeControlsOut() } } } private func fadeControlsIn() { UIView.animate(withDuration: ControlConstants.AnimateInDuration, animations: { self.showControls() }) { [weak self](finished: Bool) in if finished { self?.reestablishTimer() } } } @objc private func fadeControlsOut() { UIView.animate(withDuration: ControlConstants.AnimateOutDuraton) { self.hideControls() } } private func reestablishTimer() { controlTimer?.invalidate() controlTimer = Timer.scheduledTimer(timeInterval: ControlConstants.VisibleDuration, target: self, selector: #selector(fadeControlsOut), userInfo: nil, repeats: false) } private func hideControls() { controlsContainer.alpha = 0.0 } private func showControls() { controlsContainer.alpha = 1.0 } private func invalidateTimerAndShowControls() { controlTimer?.invalidate() showControls() } private func formatTime(timeInterval: TimeInterval) -> String? { if (timeInterval.isNaN || !timeInterval.isFinite || timeInterval == 0) { return "00:00" } let hours = floor(timeInterval / 60.0 / 60.0) let minutes = (timeInterval / 60).truncatingRemainder(dividingBy: 60) let seconds = timeInterval.truncatingRemainder(dividingBy: 60) guard let formattedMinutes = numberFormatter.string(from: NSNumber(value: minutes)), let formattedSeconds = numberFormatter.string(from: NSNumber(value: seconds)) else { return nil } return hours > 0 ? "\(hours):\(formattedMinutes):\(formattedSeconds)" : "\(formattedMinutes):\(formattedSeconds)" } // MARK: - IBActions @IBAction func handleFullScreenButtonPressed(_ button: UIButton) { if button.isSelected { button.isSelected = false delegate?.handleExitFullScreenButtonPressed() } else { button.isSelected = true delegate?.handleEnterFullScreenButtonPressed() } } @IBAction func handlePlayheadSliderTouchEnd(_ slider: UISlider) { if let currentTime = currentPlayer?.currentItem { let newCurrentTime = Float64(slider.value) * CMTimeGetSeconds(currentTime.duration) let seekToTime = CMTimeMakeWithSeconds(newCurrentTime, preferredTimescale: 600) currentPlayer?.seek(to: seekToTime, completionHandler: { [weak self] (finished: Bool) in self?.playingOnSeek = false self?.currentPlayer?.play() }) } } @IBAction func handlePlayheadSliderTouchBegin(_ slider: UISlider) { playingOnSeek = playPauseButton.isSelected currentPlayer?.pause() } @IBAction func handlePlayheadSliderValueChanged(_ slider: UISlider) { if let currentTime = currentPlayer?.currentItem { let currentTime = Float64(slider.value) * CMTimeGetSeconds(currentTime.duration) playheadLabel.text = formatTime(timeInterval: currentTime) } } @IBAction func handlePlayPauseButtonPressed(_ button: UIButton) { if button.isSelected { currentPlayer?.pause() } else { currentPlayer?.play() } } } // MARK: - UIGestureRecognizerDelegate extension ControlsViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { // This makes sure that we don't try and hide the controls if someone is pressing any of the buttons // or slider. guard let view = touch.view else { return true } if ( view.isKind(of: UIButton.classForCoder()) || view.isKind(of: UISlider.classForCoder()) ) { return false } return true } } // MARK: - BCOVPlaybackSessionConsumer extension ControlsViewController: BCOVPlaybackSessionConsumer { func didAdvance(to session: BCOVPlaybackSession!) { currentPlayer = session.player // Reset State playingOnSeek = false playheadLabel.text = formatTime(timeInterval: 0) playheadSlider.value = 0.0 invalidateTimerAndShowControls() } func playbackSession(_ session: BCOVPlaybackSession!, didChangeDuration duration: TimeInterval) { durationLabel.text = formatTime(timeInterval: duration) } func playbackSession(_ session: BCOVPlaybackSession!, didProgressTo progress: TimeInterval) { playheadLabel.text = formatTime(timeInterval: progress) guard let currentItem = session.player.currentItem else { return } let duration = CMTimeGetSeconds(currentItem.duration) let percent = Float(progress / duration) playheadSlider.value = percent.isNaN ? 0.0 : percent } func playbackSession(_ session: BCOVPlaybackSession!, didReceive lifecycleEvent: BCOVPlaybackSessionLifecycleEvent!) { switch lifecycleEvent.eventType { case kBCOVPlaybackSessionLifecycleEventPlay: playPauseButton?.isSelected = true reestablishTimer() case kBCOVPlaybackSessionLifecycleEventPause: playPauseButton.isSelected = false invalidateTimerAndShowControls() default: break } } } // MARK: - ControlsViewControllerFullScreenDelegate protocol ControlsViewControllerFullScreenDelegate: class { func handleEnterFullScreenButtonPressed() func handleExitFullScreenButtonPressed() }
32.829876
177
0.649646
d9a93064ec989aecd4f314f3c5ffbe9ed01e3ab6
711
// // AlgorithmIdentifier.swift // Shield // // Copyright © 2019 Outfox, inc. // // // Distributed under the MIT License, See LICENSE for details. // import Foundation import PotentASN1 public struct AlgorithmIdentifier: Equatable, Hashable, Codable { public var algorithm: ObjectIdentifier public var parameters: ASN1 public init(algorithm: ObjectIdentifier, parameters: ASN1 = .null) { self.algorithm = algorithm self.parameters = parameters } } // MARK: Schemas public extension Schemas { static func AlgorithmIdentifier(_ ioSet: Schema.DynamicMap) -> Schema { .sequence([ "algorithm": .type(.objectIdentifier()), "parameters": .dynamic(ioSet), ]) } }
17.341463
73
0.69339
d638f0324b7afd42f8cf8da4ac143dc9d4296fa4
3,067
import XCTest class CGRectUtilsTests: XCTestCase { // MARK: - Centering Rects func test_CenteringRect() { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) let center = CGPoint(x: 2, y: 2) let out = rect.centered(at: center) let expected = CGRect(x: 1.5, y: 1.5, width: 1, height: 1) XCTAssertEqual(out, expected) XCTAssertEqual(out.center, center) } // MARK: - Clamping Rects func test_ClampingToInfiniteDoesNothing() { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) let out = rect.clamped(to: .infinite) XCTAssertEqual(out, rect) } func test_ClampedIsContainedInClamping() { let rect = CGRect(x: -10, y: -20, width: 4, height: 4) let clamping = CGRect(x: 0, y: 0, width: 1, height: 1) let out = rect.clamped(to: clamping) XCTAssertTrue(clamping.contains(out)) } func test_BiggerClampedEqualsClamping() { let rect = CGRect(x: -10, y: -20, width: 4, height: 4) let clamping = CGRect(x: 0, y: 0, width: 1, height: 1) let out = rect.clamped(to: clamping) XCTAssertEqual(out, clamping) } func test_SmallerNonContainedClampedIsMovedButNotResized() { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) let clamping = CGRect(x: 1, y: 1, width: 2, height: 2) let out = rect.clamped(to: clamping) XCTAssertNotEqual(out.origin, rect.origin) XCTAssertEqual(out.size, rect.size) XCTAssertTrue(clamping.contains(out)) } func test_ContainedClampedIsLeftAlone() { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) let clamping = CGRect(x: -1, y: -1, width: 10, height: 10) let out = rect.clamped(to: clamping) XCTAssertEqual(out, rect) XCTAssertTrue(clamping.contains(out)) } func test_ClampingFromSpecificDirectionsMovesClampedToTheCorrectEdge() { let clamping = CGRect(x: 0, y: 0, width: 3, height: 3) let left = CGRect(x: -5, y: 1, width: 1, height: 1) let right = CGRect(x: 5, y: 1, width: 1, height: 1) let below = CGRect(x: 1, y: -5, width: 1, height: 1) let above = CGRect(x: 1, y: 5, width: 1, height: 1) let outLeft = left.clamped(to: clamping) let outRight = right.clamped(to: clamping) let outBelow = below.clamped(to: clamping) let outAbove = above.clamped(to: clamping) XCTAssertTrue(clamping.contains(outLeft)) XCTAssertEqual(outLeft.x, clamping.x) XCTAssertNotEqual(outLeft.y, clamping.y) XCTAssertTrue(clamping.contains(outRight)) XCTAssertEqual(outRight.maxX, clamping.maxX) XCTAssertNotEqual(outRight.y, clamping.y) XCTAssertTrue(clamping.contains(outBelow)) XCTAssertEqual(outBelow.y, clamping.y) XCTAssertNotEqual(outBelow.x, clamping.x) XCTAssertTrue(clamping.contains(outAbove)) XCTAssertEqual(outAbove.maxY, clamping.maxY) XCTAssertNotEqual(outAbove.x, clamping.x) } }
31.947917
76
0.62015
9cb0f503f6346909b79c4f3027eaef707d4687ce
659
// // Tweet.swift // TwitterClient // // Created by Graphic on 3/27/18. // Copyright © 2018 KarimEbrahem. All rights reserved. // import Foundation import SwiftyJSON import RealmSwift class Tweet: Object { @objc dynamic var tweetId = "" @objc dynamic var tweetText = "" @objc dynamic var tweetCreatedAt = "" convenience required init(tweetId: String, tweetText: String, tweetCreatedAt: String) { self.init() self.tweetId = tweetId self.tweetText = tweetText self.tweetCreatedAt = tweetCreatedAt } override static func primaryKey() -> String? { return "tweetId" } }
21.258065
91
0.640364
2faa64bec9a269749cdd48a5675b3ed2cdc471fe
21,268
import Foundation private struct PrivatePeerId: Hashable { typealias Namespace = Int32 typealias Id = Int32 let namespace: Namespace let id: Id init(namespace: Namespace, id: Id) { self.namespace = namespace self.id = id } init(_ n: Int64) { self.namespace = Int32((n >> 32) & 0x7fffffff) self.id = Int32(bitPattern: UInt32(n & 0xffffffff)) } func toInt64() -> Int64 { return (Int64(self.namespace) << 32) | Int64(bitPattern: UInt64(UInt32(bitPattern: self.id))) } } private func localChatListPinningIndexFromKeyValue(_ value: UInt16) -> UInt16? { if value == 0 { return nil } else { return UInt16.max - 1 - value } } private func extractChatListKey(_ key: ValueBoxKey) -> (groupId: Int32?, pinningIndex: UInt16?, index: MessageIndex, type: Int8) { let groupIdValue = key.getInt32(0) return ( groupId: groupIdValue == 0 ? nil : groupIdValue, pinningIndex: localChatListPinningIndexFromKeyValue(key.getUInt16(4)), index: MessageIndex( id: MessageId( peerId: PeerId(key.getInt64(4 + 2 + 4 + 1 + 4)), namespace: Int32(key.getInt8(4 + 2 + 4)), id: key.getInt32(4 + 2 + 4 + 1) ), timestamp: key.getInt32(4 + 2) ), type: key.getInt8(4 + 2 + 4 + 1 + 4 + 8) ) } private struct MessageDataFlags: OptionSet { var rawValue: Int8 init() { self.rawValue = 0 } init(rawValue: Int8) { self.rawValue = rawValue } static let hasGloballyUniqueId = MessageDataFlags(rawValue: 1 << 0) static let hasGlobalTags = MessageDataFlags(rawValue: 1 << 1) static let hasGroupingKey = MessageDataFlags(rawValue: 1 << 2) static let hasGroupInfo = MessageDataFlags(rawValue: 1 << 3) static let hasLocalTags = MessageDataFlags(rawValue: 1 << 4) } private enum MediaEntryType: Int8 { case Direct case MessageReference } private func mediaTableKey(_ id: MediaId) -> ValueBoxKey { let key = ValueBoxKey(length: 4 + 8) key.setInt32(0, value: id.namespace) key.setInt64(4, value: id.id) return key } private func removeMediaReference(valueBox: ValueBox, table: ValueBoxTable, id: MediaId, sharedWriteBuffer: WriteBuffer = WriteBuffer()) { guard let value = valueBox.get(table, key: mediaTableKey(id)) else { return } var type: Int8 = 0 value.read(&type, offset: 0, length: 1) if type == MediaEntryType.Direct.rawValue { var dataLength: Int32 = 0 value.read(&dataLength, offset: 0, length: 4) value.skip(Int(dataLength)) sharedWriteBuffer.reset() sharedWriteBuffer.write(value.memory, offset: 0, length: value.offset) var messageReferenceCount: Int32 = 0 value.read(&messageReferenceCount, offset: 0, length: 4) messageReferenceCount -= 1 sharedWriteBuffer.write(&messageReferenceCount, offset: 0, length: 4) if messageReferenceCount <= 0 { valueBox.remove(table, key: mediaTableKey(id), secure: false) } else { withExtendedLifetime(sharedWriteBuffer, { valueBox.set(table, key: mediaTableKey(id), value: sharedWriteBuffer.readBufferNoCopy()) }) } } else if type == MediaEntryType.MessageReference.rawValue { var idPeerId: Int64 = 0 var idNamespace: Int32 = 0 var idId: Int32 = 0 var idTimestamp: Int32 = 0 value.read(&idPeerId, offset: 0, length: 8) value.read(&idNamespace, offset: 0, length: 4) value.read(&idId, offset: 0, length: 4) value.read(&idTimestamp, offset: 0, length: 4) valueBox.remove(table, key: mediaTableKey(id), secure: false) } else { assertionFailure() } } func postboxUpgrade_19to20(metadataTable: MetadataTable, valueBox: ValueBox, progress: (Float) -> Void) { postboxLog("Upgrade 19->20 started") let startTime = CFAbsoluteTimeGetCurrent() let messageHistoryIndexTable = ValueBoxTable(id: 4, keyType: .binary, compactValuesOnCreation: true) let messageHistoryTable = ValueBoxTable(id: 7, keyType: .binary, compactValuesOnCreation: false) let messageHistoryMetadataTable = ValueBoxTable(id: 10, keyType: .binary, compactValuesOnCreation: true) let chatListIndexTable = ValueBoxTable(id: 8, keyType: .int64, compactValuesOnCreation: false) let chatListTable = ValueBoxTable(id: 9, keyType: .binary, compactValuesOnCreation: true) let globalMessageIdsTable = ValueBoxTable(id: 3, keyType: .int64, compactValuesOnCreation: false) let messageHistoryTagsTable = ValueBoxTable(id: 12, keyType: .binary, compactValuesOnCreation: true) let globalMessageHistoryTagsTable = ValueBoxTable(id: 39, keyType: .binary, compactValuesOnCreation: true) let localMessageHistoryTagsTable = ValueBoxTable(id: 52, keyType: .binary, compactValuesOnCreation: true) let mediaTable = ValueBoxTable(id: 6, keyType: .binary, compactValuesOnCreation: false) var totalMessageCount = 0 let absoluteLowerBound = ValueBoxKey(length: 8) absoluteLowerBound.setInt64(0, value: 0) let absoluteUpperBound = ValueBoxKey(length: 8) absoluteUpperBound.setInt64(0, value: Int64.max - 1) let sharedMessageHistoryKey = ValueBoxKey(length: 8 + 4 + 4 + 4) let sharedPeerHistoryInitializedKey = ValueBoxKey(length: 8 + 1) let sharedChatListIndexKey = ValueBoxKey(length: 8) let sharedGlobalIdsKey = ValueBoxKey(length: 8) let sharedMessageHistoryTagsKey = ValueBoxKey(length: 8 + 4 + 4 + 4 + 4) let sharedGlobalTagsKey = ValueBoxKey(length: 4 + 4 + 4 + 4 + 8) let sharedLocalTagsKey = ValueBoxKey(length: 4 + 4 + 4 + 8) let sharedMediaWriteBuffer = WriteBuffer() var matchingPeerIds: [PrivatePeerId] = [] var expectedTotalCount = 0 let currentLowerBound: ValueBoxKey = absoluteLowerBound while true { var currentPeerId: PrivatePeerId? valueBox.range(messageHistoryIndexTable, start: currentLowerBound, end: absoluteUpperBound, keys: { key in currentPeerId = PrivatePeerId(key.getInt64(0)) return true }, limit: 1) if let currentPeerId = currentPeerId { if currentPeerId.namespace == 0 || currentPeerId.namespace == 1 { // CloudUser || CloudGroup matchingPeerIds.append(currentPeerId) let nextLowerBound = ValueBoxKey(length: 8) nextLowerBound.setInt64(0, value: currentPeerId.toInt64() + 1) expectedTotalCount += valueBox.count(messageHistoryIndexTable, start: currentLowerBound, end: nextLowerBound) } currentLowerBound.setInt64(0, value: currentPeerId.toInt64() + 1) } else { break } } var messageIndex = -1 let reportBase = max(1, expectedTotalCount / 100) for peerId in matchingPeerIds { let peerCloudLowerBound = ValueBoxKey(length: 8 + 4) peerCloudLowerBound.setInt64(0, value: peerId.toInt64()) peerCloudLowerBound.setInt32(8, value: 0) // Cloud valueBox.range(messageHistoryIndexTable, start: peerCloudLowerBound, end: peerCloudLowerBound.successor, values: { key, indexValue in totalMessageCount += 1 if messageIndex % reportBase == 0 { progress(min(1.0, Float(messageIndex) / Float(expectedTotalCount))) } messageIndex += 1 var flags: Int8 = 0 indexValue.read(&flags, offset: 0, length: 1) var timestamp: Int32 = 0 indexValue.read(&timestamp, offset: 0, length: 4) let id = key.getInt32(8 + 4) let HistoryEntryTypeMask: Int8 = 1 let HistoryEntryTypeMessage: Int8 = 0 if (flags & HistoryEntryTypeMask) == HistoryEntryTypeMessage { sharedGlobalIdsKey.setInt64(0, value: Int64(id)) valueBox.remove(globalMessageIdsTable, key: sharedGlobalIdsKey, secure: false) } sharedMessageHistoryKey.setInt64(0, value: peerId.toInt64()) sharedMessageHistoryKey.setInt32(8, value: timestamp) sharedMessageHistoryKey.setInt32(8 + 4, value: 0) sharedMessageHistoryKey.setInt32(8 + 4 + 4, value: id) if let value = valueBox.get(messageHistoryTable, key: sharedMessageHistoryKey) { var type: Int8 = 0 value.read(&type, offset: 0, length: 1) if type == 0 { var stableId: UInt32 = 0 value.read(&stableId, offset: 0, length: 4) var stableVersion: UInt32 = 0 value.read(&stableVersion, offset: 0, length: 4) var dataFlagsValue: Int8 = 0 value.read(&dataFlagsValue, offset: 0, length: 1) let dataFlags = MessageDataFlags(rawValue: dataFlagsValue) if dataFlags.contains(.hasGloballyUniqueId) { var globallyUniqueIdValue: Int64 = 0 value.read(&globallyUniqueIdValue, offset: 0, length: 8) } var globalTags: GlobalMessageTags = [] if dataFlags.contains(.hasGlobalTags) { var globalTagsValue: UInt32 = 0 value.read(&globalTagsValue, offset: 0, length: 4) globalTags = GlobalMessageTags(rawValue: globalTagsValue) } if dataFlags.contains(.hasGroupingKey) { var groupingKeyValue: Int64 = 0 value.read(&groupingKeyValue, offset: 0, length: 8) } if dataFlags.contains(.hasGroupInfo) { var stableIdValue: UInt32 = 0 value.read(&stableIdValue, offset: 0, length: 4) } var localTags: LocalMessageTags = [] if dataFlags.contains(.hasLocalTags) { var localTagsValue: UInt32 = 0 value.read(&localTagsValue, offset: 0, length: 4) localTags = LocalMessageTags(rawValue: localTagsValue) } var flagsValue: UInt32 = 0 value.read(&flagsValue, offset: 0, length: 4) var tagsValue: UInt32 = 0 value.read(&tagsValue, offset: 0, length: 4) let tags = MessageTags(rawValue: tagsValue) var forwardInfoFlags: Int8 = 0 value.read(&forwardInfoFlags, offset: 0, length: 1) if forwardInfoFlags != 0 { var forwardAuthorId: Int64 = 0 var forwardDate: Int32 = 0 value.read(&forwardAuthorId, offset: 0, length: 8) value.read(&forwardDate, offset: 0, length: 4) if (forwardInfoFlags & (1 << 1)) != 0 { var forwardSourceIdValue: Int64 = 0 value.read(&forwardSourceIdValue, offset: 0, length: 8) } if (forwardInfoFlags & (1 << 2)) != 0 { var forwardSourceMessagePeerId: Int64 = 0 var forwardSourceMessageNamespace: Int32 = 0 var forwardSourceMessageIdId: Int32 = 0 value.read(&forwardSourceMessagePeerId, offset: 0, length: 8) value.read(&forwardSourceMessageNamespace, offset: 0, length: 4) value.read(&forwardSourceMessageIdId, offset: 0, length: 4) } if (forwardInfoFlags & (1 << 3)) != 0 { var signatureLength: Int32 = 0 value.read(&signatureLength, offset: 0, length: 4) value.skip(Int(signatureLength)) } } var hasAuthor: Int8 = 0 value.read(&hasAuthor, offset: 0, length: 1) if hasAuthor == 1 { var varAuthorId: Int64 = 0 value.read(&varAuthorId, offset: 0, length: 8) } var textLength: Int32 = 0 value.read(&textLength, offset: 0, length: 4) value.skip(Int(textLength)) var attributeCount: Int32 = 0 value.read(&attributeCount, offset: 0, length: 4) for _ in 0 ..< attributeCount { var attributeLength: Int32 = 0 value.read(&attributeLength, offset: 0, length: 4) value.skip(Int(attributeLength)) } let embeddedMediaOffset = value.offset var embeddedMediaCount: Int32 = 0 value.read(&embeddedMediaCount, offset: 0, length: 4) for _ in 0 ..< embeddedMediaCount { var mediaLength: Int32 = 0 value.read(&mediaLength, offset: 0, length: 4) value.skip(Int(mediaLength)) } let embeddedMediaLength = value.offset - embeddedMediaOffset let embeddedMediaBytes = malloc(embeddedMediaLength)! memcpy(embeddedMediaBytes, value.memory + embeddedMediaOffset, embeddedMediaLength) let embeddedMediaData = ReadBuffer(memory: embeddedMediaBytes, length: embeddedMediaLength, freeWhenDone: true) var referencedMediaIds: [MediaId] = [] var referencedMediaIdsCount: Int32 = 0 value.read(&referencedMediaIdsCount, offset: 0, length: 4) for _ in 0 ..< referencedMediaIdsCount { var idNamespace: Int32 = 0 var idId: Int64 = 0 value.read(&idNamespace, offset: 0, length: 4) value.read(&idId, offset: 0, length: 8) referencedMediaIds.append(MediaId(namespace: idNamespace, id: idId)) } for tag in tags { sharedMessageHistoryTagsKey.setInt64(0, value: peerId.toInt64()) sharedMessageHistoryTagsKey.setUInt32(8, value: tag.rawValue) sharedMessageHistoryTagsKey.setInt32(8 + 4, value: timestamp) sharedMessageHistoryTagsKey.setInt32(8 + 4 + 4, value: 0) sharedMessageHistoryTagsKey.setInt32(8 + 4 + 4 + 4, value: id) valueBox.remove(messageHistoryTagsTable, key: sharedMessageHistoryTagsKey, secure: false) } for tag in globalTags { sharedGlobalTagsKey.setUInt32(0, value: tag.rawValue) sharedGlobalTagsKey.setInt32(4, value: timestamp) sharedGlobalTagsKey.setInt32(4 + 4, value: 0) sharedGlobalTagsKey.setInt32(4 + 4 + 4, value: id) sharedGlobalTagsKey.setInt64(4 + 4 + 4 + 4, value: peerId.toInt64()) valueBox.remove(globalMessageHistoryTagsTable, key: sharedGlobalTagsKey, secure: false) } for tag in localTags { sharedLocalTagsKey.setUInt32(0, value: tag.rawValue) sharedLocalTagsKey.setInt32(4, value: 0) sharedLocalTagsKey.setInt32(4 + 4, value: id) sharedLocalTagsKey.setInt64(4 + 4 + 4, value: peerId.toInt64()) valueBox.remove(localMessageHistoryTagsTable, key: sharedLocalTagsKey, secure: false) } for mediaId in referencedMediaIds { removeMediaReference(valueBox: valueBox, table: mediaTable, id: mediaId, sharedWriteBuffer: sharedMediaWriteBuffer) } if embeddedMediaData.length > 4 { var embeddedMediaCount: Int32 = 0 embeddedMediaData.read(&embeddedMediaCount, offset: 0, length: 4) for _ in 0 ..< embeddedMediaCount { var mediaLength: Int32 = 0 embeddedMediaData.read(&mediaLength, offset: 0, length: 4) if let media = PostboxDecoder(buffer: MemoryBuffer(memory: embeddedMediaData.memory + embeddedMediaData.offset, capacity: Int(mediaLength), length: Int(mediaLength), freeWhenDone: false)).decodeRootObject() as? Media { if let mediaId = media.id { removeMediaReference(valueBox: valueBox, table: mediaTable, id: mediaId, sharedWriteBuffer: sharedMediaWriteBuffer) } } embeddedMediaData.skip(Int(mediaLength)) } } } else { var stableId: UInt32 = 0 value.read(&stableId, offset: 0, length: 4) var minId: Int32 = 0 value.read(&minId, offset: 0, length: 4) var tags: UInt32 = 0 value.read(&tags, offset: 0, length: 4) for tag in MessageTags(rawValue: tags) { sharedMessageHistoryTagsKey.setInt64(0, value: peerId.toInt64()) sharedMessageHistoryTagsKey.setUInt32(8, value: tag.rawValue) sharedMessageHistoryTagsKey.setInt32(8 + 4, value: timestamp) sharedMessageHistoryTagsKey.setInt32(8 + 4 + 4, value: 0) sharedMessageHistoryTagsKey.setInt32(8 + 4 + 4 + 4, value: id) valueBox.remove(messageHistoryTagsTable, key: sharedMessageHistoryTagsKey, secure: false) } } valueBox.remove(messageHistoryTable, key: sharedMessageHistoryKey, secure: false) } return true }, limit: 0) valueBox.removeRange(messageHistoryIndexTable, start: peerCloudLowerBound, end: peerCloudLowerBound.successor) sharedPeerHistoryInitializedKey.setInt64(0, value: peerId.toInt64()) sharedPeerHistoryInitializedKey.setInt8(8, value: 1) valueBox.remove(messageHistoryMetadataTable, key: sharedPeerHistoryInitializedKey, secure: false) sharedChatListIndexKey.setInt64(0, value: peerId.toInt64()) valueBox.remove(chatListIndexTable, key: sharedChatListIndexKey, secure: false) } var removeChatListKeys: [ValueBoxKey] = [] valueBox.scan(chatListTable, keys: { key in let (_, _, index, type) = extractChatListKey(key) if index.id.peerId.namespace != 3 { // Secret Chat sharedChatListIndexKey.setInt64(0, value: index.id.peerId.toInt64()) valueBox.remove(chatListIndexTable, key: sharedChatListIndexKey, secure: false) removeChatListKeys.append(key) } else if type == 2 { // Hole removeChatListKeys.append(key) } return true }) for key in removeChatListKeys { valueBox.remove(chatListTable, key: key, secure: false) } let chatListInitializedKey = ValueBoxKey(length: 1) chatListInitializedKey.setInt8(0, value: 0) valueBox.remove(messageHistoryMetadataTable, key: chatListInitializedKey, secure: false) let shouldReindexUnreadCountsKey = ValueBoxKey(length: 1) shouldReindexUnreadCountsKey.setInt8(0, value: 8) valueBox.set(messageHistoryMetadataTable, key: shouldReindexUnreadCountsKey, value: MemoryBuffer()) let endTime = CFAbsoluteTimeGetCurrent() postboxLog("Upgrade 19->20 (\(totalMessageCount) messages) took \(endTime - startTime) s") metadataTable.setUserVersion(20) }
46.742857
246
0.55379
fe9f2e2ca0e09063e28b097ea39a6e77ef1941cf
249
import ComposableArchitecture public let shapeReducer = Reducer<ShapeState, ShapeAction, Void> { state, action, _ in switch action { case let .didSelectType(value): state.type = value return .none case .apply: return .none } }
19.153846
86
0.702811
872717b71d2e2e919cf3fc81698f8c9fa92ff63f
4,573
// // ModalTableViewController.swift // TeamProject // // Created by Nayeon Kim on 2021/01/15. // import UIKit class ModalTableViewController: UITableViewController, UITextFieldDelegate { var getImageChange: String = "category_purple" @IBOutlet weak var showColorImage: UIImageView! @IBOutlet weak var nameTextField: UITextField! @IBAction func completeModal(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func cancelModal(_ sender: Any) { self.dismiss(animated: true, completion: nil) } override func viewWillAppear(_ animated: Bool) { self.nameTextField.becomeFirstResponder() } override func viewDidLoad() { super.viewDidLoad() nameTextField.delegate = self self.showColorImage.image = UIImage(named: getImageChange) // self.showColorImage.image?.accessibilityIdentifier = // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.nameTextField.resignFirstResponder() self.dismiss(animated: true, completion: nil) return true } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 1 { self.performSegue(withIdentifier: "chooseColor", sender: nil) } } // override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // let colorCell = segue.destination as! // } // // func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { // if textField.text != "" {return true} // else { // textField.placeholder = "카테고리 이름" // return false // } // } // // func textFieldDidEndEditing(_ textField: UITextField) { // textField.text = "" // } // MARK: - Table view data source // override func numberOfSections(in tableView: UITableView) -> Int { // // #warning Incomplete implementation, return the number of sections // return 0 // } // // override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // // #warning Incomplete implementation, return the number of rows // return 2 // } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... 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: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // 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?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
31.756944
145
0.647715
61d7db969f154db137785a7f2ce018af1c5b48f1
4,307
// // StockPhotoCollectionViewController.swift // Stock MessagesExtension // // Created by Ayden Panhuyzen on 2019-07-21. // Copyright © 2019 Ayden Panhuyzen. All rights reserved. // import UIKit import StockKit class StockPhotoCollectionViewController: UICollectionViewController { static let reuseIdentifier = "Cell", titledHeaderReuseIdentifier = "TitledHeader" private let downloader = AttachmentDownloader() var numberOfColumns: CGFloat = 0 convenience init() { self.init(collectionViewLayout: StockPhotoCollectionViewControllerLayout()) } override func viewDidLoad() { super.viewDidLoad() downloader.delegate = self // Collection view appearance and behaviour collectionView.backgroundColor = .clear collectionView.keyboardDismissMode = .interactive collectionView.alwaysBounceVertical = true // Register cell & supplementary view classes collectionView!.register(StockPhotoCollectionViewCell.self, forCellWithReuseIdentifier: StockPhotoCollectionViewController.reuseIdentifier) collectionView.register(StockPhotoCollectionViewSectionHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: StockPhotoCollectionViewController.titledHeaderReuseIdentifier) determineNumberOfColumns() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.collectionView.collectionViewLayout.invalidateLayout() }, completion: nil) } private func determineNumberOfColumns() { numberOfColumns = ceil(collectionView.frame.size.width / 150) } var messagesViewController: MessagesViewController { return parent as! MessagesViewController } var layout: StockPhotoCollectionViewControllerLayout { return collectionView.collectionViewLayout as! StockPhotoCollectionViewControllerLayout } func attach(photo: StockPhoto) { downloader.download(photo: photo) { (result) in switch result { case .success(let attachment): self.messagesViewController.activeConversation?.insertAttachment(attachment.fileURL, withAlternateFilename: nil) { (error) in if let error = error { self.showErrorAlert(title: "Couldn't Attach Photo", error: error) } PresentationStyleManager.shared.style = .compact attachment.cleanUp() } case .failure(let error): self.showErrorAlert(title: "Couldn't Attach Photo", error: error) } } } // MARK: - Collection view delegate override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? StockPhotoCollectionViewCell else { return } cell.isDownloadingFullImage = cell.photo != nil && cell.photo?.fullImageURL == downloader.currentlyDownloadingPhoto?.fullImageURL } } // MARK: - Collection view layout delegate extension StockPhotoCollectionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { determineNumberOfColumns() let usableContainerWidth = collectionView.frame.size.width - (layout.minimumInteritemSpacing * (numberOfColumns - 1)) - layout.sectionInset.horizontal - collectionView.contentInset.horizontal let size = usableContainerWidth / numberOfColumns return CGSize(width: size, height: size) } } // MARK: - Attachment Downloader Delegate extension StockPhotoCollectionViewController: AttachmentDownloaderDelegate { func currentlyDownloadingPhotoChanged(to photo: StockPhoto?) { for cell in collectionView.visibleCells as! [StockPhotoCollectionViewCell] { cell.isDownloadingFullImage = cell.photo != nil && cell.photo?.fullImageURL == photo?.fullImageURL } } }
42.643564
231
0.720455
035bd2990cd6c279976daf0a08f01abe69d24def
9,121
// // GPHUser.swift // GiphyCoreSDK // // Created by Cem Kozinoglu, Gene Goykhman, Giorgia Marenda on 4/24/17. // Copyright © 2017 Giphy. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // import Foundation /// Represents a Giphy User Object /// /// http://api.giphy.com/v1/gifs/categories/animals/cats?api_key=4OMJYpPoYwVpe @objcMembers public class GPHUser: GPHFilterable, NSCoding { // MARK: Properties /// Username. public fileprivate(set) var username: String = "" /// User ID. public fileprivate(set) var userId: String? /// Name of the User. public fileprivate(set) var name: String? /// Description of the User. public fileprivate(set) var userDescription: String? /// Attribution Display Name. public fileprivate(set) var attributionDisplayName: String? /// Display Name for the User. public fileprivate(set) var displayName: String? /// Twitter Handler. public fileprivate(set) var twitter: String? /// URL of the Twitter Handler. public fileprivate(set) var twitterUrl: String? /// URL of the Facebook Handler. public fileprivate(set) var facebookUrl: String? /// URL of the Instagram Handler. public fileprivate(set) var instagramUrl: String? /// URL of the Website public fileprivate(set) var websiteUrl: String? /// Displayable URL of the Website. public fileprivate(set) var websiteDisplayUrl: String? /// URL of the Tumblr Handler. public fileprivate(set) var tumblrUrl: String? /// URL of the Avatar. public fileprivate(set) var avatarUrl: String? /// URL of the Banner. public fileprivate(set) var bannerUrl: String? /// URL of the Profile. public fileprivate(set) var profileUrl: String? /// User Public/Private. public fileprivate(set) var isPublic: Bool = false /// User is Staff. public fileprivate(set) var isStaff: Bool = false /// User is Verified public fileprivate(set) var isVerified: Bool = false /// Suppress Chrome. public fileprivate(set) var suppressChrome: Bool = false /// Last Login Date/Time. public fileprivate(set) var loginDate: Date? /// Join Date/Time. public fileprivate(set) var joinDate: Date? /// JSON Representation. public fileprivate(set) var jsonRepresentation: GPHJSONObject? /// User Dictionary to Store data in Obj by the Developer public var userDictionary: [String: Any]? // MARK: Initializers /// Convenience Initializer /// /// - parameter username: Username of the User. /// convenience public init(_ username: String) { self.init() self.username = username } //MARK: NSCoding required convenience public init?(coder aDecoder: NSCoder) { guard let username = aDecoder.decodeObject(forKey: "username") as? String else { return nil } self.init(username) self.userId = aDecoder.decodeObject(forKey: "userId") as? String self.isPublic = aDecoder.decodeBool(forKey: "isPublic") self.isStaff = aDecoder.decodeBool(forKey: "isStaff") self.isVerified = aDecoder.decodeBool(forKey: "isVerified") self.suppressChrome = aDecoder.decodeBool(forKey: "suppressChrome") self.name = aDecoder.decodeObject(forKey: "name") as? String self.displayName = aDecoder.decodeObject(forKey: "displayName") as? String self.userDescription = aDecoder.decodeObject(forKey: "userDescription") as? String self.attributionDisplayName = aDecoder.decodeObject(forKey: "attributionDisplayName") as? String self.twitter = aDecoder.decodeObject(forKey: "twitter") as? String self.twitterUrl = aDecoder.decodeObject(forKey: "twitterUrl") as? String self.facebookUrl = aDecoder.decodeObject(forKey: "facebookUrl") as? String self.instagramUrl = aDecoder.decodeObject(forKey: "instagramUrl") as? String self.websiteUrl = aDecoder.decodeObject(forKey: "websiteUrl") as? String self.websiteDisplayUrl = aDecoder.decodeObject(forKey: "websiteDisplayUrl") as? String self.tumblrUrl = aDecoder.decodeObject(forKey: "tumblrUrl") as? String self.avatarUrl = aDecoder.decodeObject(forKey: "avatarUrl") as? String self.bannerUrl = aDecoder.decodeObject(forKey: "bannerUrl") as? String self.profileUrl = aDecoder.decodeObject(forKey: "profileUrl") as? String self.loginDate = aDecoder.decodeObject(forKey: "loginDate") as? Date self.joinDate = aDecoder.decodeObject(forKey: "joinDate") as? Date self.jsonRepresentation = aDecoder.decodeObject(forKey: "jsonRepresentation") as? GPHJSONObject self.userDictionary = aDecoder.decodeObject(forKey: "userDictionary") as? [String: Any] } public func encode(with aCoder: NSCoder) { aCoder.encode(self.username, forKey: "username") aCoder.encode(self.userId, forKey: "userId") aCoder.encode(self.isPublic, forKey: "isPublic") aCoder.encode(self.isStaff, forKey: "isStaff") aCoder.encode(self.isVerified, forKey: "isVerified") aCoder.encode(self.suppressChrome, forKey: "suppressChrome") aCoder.encode(self.name, forKey: "name") aCoder.encode(self.displayName, forKey: "displayName") aCoder.encode(self.userDescription, forKey: "userDescription") aCoder.encode(self.attributionDisplayName, forKey: "attributionDisplayName") aCoder.encode(self.twitter, forKey: "twitter") aCoder.encode(self.twitterUrl, forKey: "twitterUrl") aCoder.encode(self.facebookUrl, forKey: "facebookUrl") aCoder.encode(self.instagramUrl, forKey: "instagramUrl") aCoder.encode(self.websiteUrl, forKey: "websiteUrl") aCoder.encode(self.websiteDisplayUrl, forKey: "websiteDisplayUrl") aCoder.encode(self.tumblrUrl, forKey: "tumblrUrl") aCoder.encode(self.avatarUrl, forKey: "avatarUrl") aCoder.encode(self.bannerUrl, forKey: "bannerUrl") aCoder.encode(self.profileUrl, forKey: "profileUrl") aCoder.encode(self.loginDate, forKey: "loginDate") aCoder.encode(self.joinDate, forKey: "joinDate") aCoder.encode(self.jsonRepresentation, forKey: "jsonRepresentation") aCoder.encode(self.userDictionary, forKey: "userDictionary") } // MARK: NSObject override public func isEqual(_ object: Any?) -> Bool { if object as? GPHUser === self { return true } if let other = object as? GPHUser, self.username == other.username { return true } return false } override public var hash: Int { return "gph_user_\(self.username)".hashValue } } // MARK: Extension -- Human readable /// Make objects human readable. /// extension GPHUser { override public var description: String { return "GPHUser(\(self.username))" } } // MARK: Extension -- Parsing & Mapping /// For parsing/mapping protocol. /// extension GPHUser: GPHMappable { /// This is where the magic/mapping happens + error handling. public static func mapData(_ data: GPHJSONObject, options: [String: Any?]) throws -> GPHUser { guard let username = data["username"] as? String else { throw GPHJSONMappingError(description: "Couldn't map GPHUser for \(data)") } let obj = GPHUser(username) obj.userId = data["id"] as? String ?? parseString(data["id"] as? Int) obj.isPublic = data["is_public"] as? Bool ?? false obj.isStaff = data["is_staff"] as? Bool ?? false obj.isVerified = data["is_verified"] as? Bool ?? false obj.suppressChrome = data["suppress_chrome"] as? Bool ?? false obj.name = data["name"] as? String obj.displayName = data["display_name"] as? String obj.userDescription = data["description"] as? String obj.attributionDisplayName = data["attribution_display_name"] as? String obj.twitter = data["twitter"] as? String obj.twitterUrl = data["twitter_url"] as? String obj.facebookUrl = data["facebook_url"] as? String obj.instagramUrl = data["instagram_url"] as? String obj.websiteUrl = data["website_url"] as? String obj.websiteDisplayUrl = data["website_display_url"] as? String obj.tumblrUrl = data["tumblr_url"] as? String obj.avatarUrl = data["avatar_url"] as? String obj.bannerUrl = data["banner_url"] as? String obj.profileUrl = data["profile_url"] as? String obj.loginDate = parseDate(data["last_login"] as? String) obj.joinDate = parseDate(data["date_joined"] as? String) obj.jsonRepresentation = data return obj } }
37.690083
104
0.659248