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
ff78d47b500c6771538c3992682c83ea9eeb1f41
8,252
import Dispatch import Foundation import XCTest import Nimble final class AsyncTest: XCTestCase, XCTestCaseProvider { static var allTests: [(String, (AsyncTest) -> () throws -> Void)] { return [ ("testToEventuallyPositiveMatches", testToEventuallyPositiveMatches), ("testToEventuallyNegativeMatches", testToEventuallyNegativeMatches), ("testWaitUntilPositiveMatches", testWaitUntilPositiveMatches), ("testToEventuallyWithCustomDefaultTimeout", testToEventuallyWithCustomDefaultTimeout), ("testWaitUntilTimesOutIfNotCalled", testWaitUntilTimesOutIfNotCalled), ("testWaitUntilTimesOutWhenExceedingItsTime", testWaitUntilTimesOutWhenExceedingItsTime), ("testWaitUntilNegativeMatches", testWaitUntilNegativeMatches), ("testWaitUntilDetectsStalledMainThreadActivity", testWaitUntilDetectsStalledMainThreadActivity), ("testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed", testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed), ("testWaitUntilErrorsIfDoneIsCalledMultipleTimes", testWaitUntilErrorsIfDoneIsCalledMultipleTimes), ("testWaitUntilMustBeInMainThread", testWaitUntilMustBeInMainThread), ("testToEventuallyMustBeInMainThread", testToEventuallyMustBeInMainThread), ] } class Error: Swift.Error {} let errorToThrow = Error() private func doThrowError() throws -> Int { throw errorToThrow } func testToEventuallyPositiveMatches() { var value = 0 deferToMainQueue { value = 1 } expect { value }.toEventually(equal(1)) deferToMainQueue { value = 0 } expect { value }.toEventuallyNot(equal(1)) } func testToEventuallyNegativeMatches() { let value = 0 failsWithErrorMessage("expected to eventually not equal <0>, got <0>") { expect { value }.toEventuallyNot(equal(0)) } failsWithErrorMessage("expected to eventually equal <1>, got <0>") { expect { value }.toEventually(equal(1)) } failsWithErrorMessage("expected to eventually equal <1>, got an unexpected error thrown: <\(errorToThrow)>") { expect { try self.doThrowError() }.toEventually(equal(1)) } failsWithErrorMessage("expected to eventually not equal <0>, got an unexpected error thrown: <\(errorToThrow)>") { expect { try self.doThrowError() }.toEventuallyNot(equal(0)) } } func testToEventuallyWithCustomDefaultTimeout() { AsyncDefaults.Timeout = 2 defer { AsyncDefaults.Timeout = 1 } var value = 0 let sleepThenSetValueTo: (Int) -> () = { newValue in Thread.sleep(forTimeInterval: 1.1) value = newValue } var asyncOperation: () -> () = { sleepThenSetValueTo(1) } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } expect { value }.toEventually(equal(1)) asyncOperation = { sleepThenSetValueTo(0) } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } expect { value }.toEventuallyNot(equal(1)) } func testWaitUntilPositiveMatches() { waitUntil { done in done() } waitUntil { done in deferToMainQueue { done() } } } func testWaitUntilTimesOutIfNotCalled() { failsWithErrorMessage("Waited more than 1.0 second") { waitUntil(timeout: 1) { done in return } } } func testWaitUntilTimesOutWhenExceedingItsTime() { var waiting = true failsWithErrorMessage("Waited more than 0.01 seconds") { waitUntil(timeout: 0.01) { done in let asyncOperation: () -> () = { Thread.sleep(forTimeInterval: 0.1) done() waiting = false } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } } } // "clear" runloop to ensure this test doesn't poison other tests repeat { RunLoop.main.run(until: Date().addingTimeInterval(0.2)) } while(waiting) } func testWaitUntilNegativeMatches() { failsWithErrorMessage("expected to equal <2>, got <1>") { waitUntil { done in Thread.sleep(forTimeInterval: 0.1) expect(1).to(equal(2)) done() } } } func testWaitUntilDetectsStalledMainThreadActivity() { let msg = "-waitUntil() timed out but was unable to run the timeout handler because the main thread is unresponsive (0.5 seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run." failsWithErrorMessage(msg) { waitUntil(timeout: 1) { done in Thread.sleep(forTimeInterval: 5.0) done() } } } func testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed() { // Currently we are unable to catch Objective-C exceptions when built by the Swift Package Manager #if !SWIFT_PACKAGE let referenceLine = #line + 9 var msg = "Unexpected exception raised: Nested async expectations are not allowed " msg += "to avoid creating flaky tests." msg += "\n\n" msg += "The call to\n\t" msg += "expect(...).toEventually(...) at \(#file):\(referenceLine + 7)\n" msg += "triggered this exception because\n\t" msg += "waitUntil(...) at \(#file):\(referenceLine + 1)\n" msg += "is currently managing the main run loop." failsWithErrorMessage(msg) { // reference line waitUntil(timeout: 2.0) { done in var protected: Int = 0 DispatchQueue.main.async { protected = 1 } expect(protected).toEventually(equal(1)) done() } } #endif } func testWaitUntilErrorsIfDoneIsCalledMultipleTimes() { #if !SWIFT_PACKAGE waitUntil { done in deferToMainQueue { done() expect { done() }.to(raiseException(named: "InvalidNimbleAPIUsage")) } } #endif } func testWaitUntilMustBeInMainThread() { #if !SWIFT_PACKAGE var executedAsyncBlock: Bool = false let asyncOperation: () -> () = { expect { waitUntil { done in done() } }.to(raiseException(named: "InvalidNimbleAPIUsage")) executedAsyncBlock = true } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } expect(executedAsyncBlock).toEventually(beTruthy()) #endif } func testToEventuallyMustBeInMainThread() { #if !SWIFT_PACKAGE var executedAsyncBlock: Bool = false let asyncOperation: () -> () = { expect { expect(1).toEventually(equal(2)) }.to(raiseException(named: "InvalidNimbleAPIUsage")) executedAsyncBlock = true } if #available(OSX 10.10, *) { DispatchQueue.global().async(execute: asyncOperation) } else { DispatchQueue.global(priority: .default).async(execute: asyncOperation) } expect(executedAsyncBlock).toEventually(beTruthy()) #endif } }
37.004484
385
0.601188
8934b33c98d230458eb4bfae175d723bcbde289c
1,976
// // SDWebImageStyle.swift // Alamofire // // Created by Fanxx on 2019/8/20. // #if canImport(Kingfisher) import UIKit import Kingfisher extension EasyStyleSetting where TargetType: UIButton { ///图片 public static func kf(_ url:URL?, for state: UIControl.State = .normal) -> EasyStyleSetting<TargetType> { return .init(action: { (target) in target.kf.setImage(with: url, for: state) }) } ///图片 public static func kf(_ url:String?, for state: UIControl.State = .normal) -> EasyStyleSetting<TargetType> { return .init(action: { (target) in if let u = url { target.kf.setImage(with: URL(string: u), for: state) } }) } ///图片 public static func kf(bg url:URL?, for state: UIControl.State = .normal) -> EasyStyleSetting<TargetType> { return .init(action: { (target) in target.kf.setBackgroundImage(with: url, for: state) }) } ///图片 public static func kf(bg url:String?, for state: UIControl.State = .normal) -> EasyStyleSetting<TargetType> { return .init(action: { (target) in if let u = url { target.kf.setBackgroundImage(with: URL(string: u), for: state) } }) } } extension EasyStyleSetting where TargetType: UIImageView { ///图片 public static func kf(_ url:URL?, completed: ((Result<RetrieveImageResult, KingfisherError>)->Void)? = nil) -> EasyStyleSetting<TargetType> { return .init(action: { (target) in target.kf.setImage(with: url, completionHandler: completed) }) } ///图片 public static func kf(_ url:String?, completed: ((Result<RetrieveImageResult, KingfisherError>)->Void)? = nil) -> EasyStyleSetting<TargetType> { return .init(action: { (target) in if let u = url { target.kf.setImage(with: URL(string: u), completionHandler: completed) } }) } } #endif
34.068966
148
0.602733
234fb0a4d637b93e88271cf4697257dc30d0693a
13,498
// -------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // The MIT License (MIT) // // 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 AzureCore import Foundation /// Structure containing properties of a blob or blob snapshot. public struct BlobProperties: XMLModel, Codable, Equatable { /// The date that the blob was created. public let creationTime: Date? /// The date that the blob was last modified. public let lastModified: Date? /// The entity tag for the blob. public let eTag: String? /// The size of the blob in bytes. public internal(set) var contentLength: Int? /// The content type specified for the blob. public let contentType: String? /// The value of the blob's Content-Disposition request header, if previously set. public let contentDisposition: String? /// The value of the blob's Content-Encoding request header, if previously set. public let contentEncoding: String? /// The value of the blob's Content-Language request header, if previously set. public let contentLanguage: String? /// The value of the blob's Content-MD5 request header, if previously set. public let contentMD5: String? /// The value of the blob's x-ms-content-crc64 request header, if previously set. public let contentCRC64: String? /// The value of the blob's Cache-Control request header, if previously set. public let cacheControl: String? /// The current sequence number for a page blob. This value is nil for block or append blobs. public let sequenceNumber: Int? /// The type of the blob. public let blobType: BlobType? /// The access tier of the blob. public let accessTier: AccessTier? /// The lease status of the blob. public let leaseStatus: LeaseStatus? /// The lease state of the blob. public let leaseState: LeaseState? /// Specifies whether the lease on a blob is of infinite or fixed duration. public let leaseDuration: LeaseDuration? /// String identifier for the last attempted Copy Blob operation where this blob was the destination blob. public let copyId: String? /// Status of the copy operation identified by `copyId`. public let copyStatus: CopyStatus? /// The URL of the source blob used in the copy operation identified by `copyId`. public let copySource: URL? /// Contains the number of bytes copied and the total bytes in the source blob, for the copy operation identified by /// `copyId`. public let copyProgress: String? /// Completion time of the copy operation identified by `copyId`. public let copyCompletionTime: Date? /// Describes the cause of a fatal or non-fatal copy operation failure encounted in the copy operation identified by /// `copyId`. public let copyStatusDescription: String? /// Indicates whether the blob data and application metadata are completely encrypted. public let serverEncrypted: Bool? /// Indicates whether the blob is an incremental copy blob. public let incrementalCopy: Bool? /// If the access tier is not explicitly set on the blob, indicates whether the access tier is inferred based on the /// blob's content length. public let accessTierInferred: Bool? /// The date that the access tier was last changed on the blob. public let accessTierChangeTime: Date? /// The date that the blob was soft-deleted. public let deletedTime: Date? /// The number of days remaining in the blob's time-based retention policy. public let remainingRetentionDays: Int? // MARK: XMLModel Delegate /// :nodoc: public static func xmlMap() -> XMLMap { return XMLMap([ "Creation-Time": XMLMetadata(jsonName: "creationTime"), "Last-Modified": XMLMetadata(jsonName: "lastModified"), "Etag": XMLMetadata(jsonName: "eTag"), "Content-Length": XMLMetadata(jsonName: "contentLength"), "Content-Type": XMLMetadata(jsonName: "contentType"), "Content-Disposition": XMLMetadata(jsonName: "contentDisposition"), "Content-Encoding": XMLMetadata(jsonName: "contentEncoding"), "Content-Language": XMLMetadata(jsonName: "contentLanguage"), "Content-MD5": XMLMetadata(jsonName: "contentMD5"), "Content-CRC64": XMLMetadata(jsonName: "contentCRC64"), "Cache-Control": XMLMetadata(jsonName: "cacheControl"), "x-ms-blob-sequence-number": XMLMetadata(jsonName: "sequenceNumber"), "BlobType": XMLMetadata(jsonName: "blobType"), "AccessTier": XMLMetadata(jsonName: "accessTier"), "LeaseStatus": XMLMetadata(jsonName: "leaseStatus"), "LeaseState": XMLMetadata(jsonName: "leaseState"), "LeaseDuration": XMLMetadata(jsonName: "leaseDuration"), "CopyId": XMLMetadata(jsonName: "copyId"), "CopyStatus": XMLMetadata(jsonName: "copyStatus"), "CopySource": XMLMetadata(jsonName: "copySource"), "CopyProgress": XMLMetadata(jsonName: "copyProgress"), "CopyCompletionTime": XMLMetadata(jsonName: "copyCompletionTime"), "CopyStatusDescription": XMLMetadata(jsonName: "copyStatusDescription"), "ServerEncrypted": XMLMetadata(jsonName: "serverEncrypted"), "IncrementalCopy": XMLMetadata(jsonName: "incrementalCopy"), "AccessTierInferred": XMLMetadata(jsonName: "accessTierInferred"), "AccessTierChangeTime": XMLMetadata(jsonName: "accessTierChangeTime"), "DeletedTime": XMLMetadata(jsonName: "deletedTime"), "RemainingRetentionDays": XMLMetadata(jsonName: "remainingRetentionDays") ]) } } extension BlobProperties { /// Initialize a `BlobProperties` structure. /// - Parameters: /// - contentType: The content type specified for the blob. /// - contentDisposition: The value of the blob's Content-Disposition request header. /// - contentEncoding: The value of the blob's Content-Encoding request header. /// - contentLanguage: The value of the blob's Content-Language request header. /// - contentMD5: The value of the blob's Content-MD5 request header. /// - contentCRC64: The value of the blob's x-ms-content-crc64 request header. /// - cacheControl: The value of the blob's Cache-Control request header. /// - accessTier: The access tier of the blob. public init( contentType: String? = nil, contentDisposition: String? = nil, contentEncoding: String? = nil, contentLanguage: String? = nil, contentMD5: String? = nil, contentCRC64: String? = nil, cacheControl: String? = nil, accessTier: AccessTier? = nil ) { self.creationTime = nil self.lastModified = nil self.eTag = nil self.contentLength = nil self.contentType = contentType self.contentDisposition = contentDisposition self.contentEncoding = contentEncoding self.contentLanguage = contentLanguage self.contentMD5 = contentMD5 self.contentCRC64 = contentCRC64 self.cacheControl = cacheControl self.sequenceNumber = nil self.blobType = nil self.accessTier = accessTier self.leaseStatus = nil self.leaseState = nil self.leaseDuration = nil self.copyId = nil self.copyStatus = nil self.copySource = nil self.copyProgress = nil self.copyCompletionTime = nil self.copyStatusDescription = nil self.serverEncrypted = nil self.incrementalCopy = nil self.accessTierInferred = nil self.accessTierChangeTime = nil self.deletedTime = nil self.remainingRetentionDays = nil } internal init(from headers: HTTPHeaders) { self.creationTime = Date(headers[.creationTime], format: .rfc1123) self.lastModified = Date(headers[.lastModified], format: .rfc1123) self.copyCompletionTime = Date(headers[.copyCompletionTime], format: .rfc1123) self.eTag = headers[.etag] self.contentType = headers[.contentType] self.contentDisposition = headers[.contentDisposition] self.contentEncoding = headers[.contentEncoding] self.contentLanguage = headers[.contentLanguage] self.contentMD5 = headers[.contentMD5] self.contentCRC64 = headers[.contentCRC64] self.cacheControl = headers[.cacheControl] self.copyId = headers[.copyId] self.copyProgress = headers[.copyProgress] self.copyStatusDescription = headers[.copyStatusDescription] self.contentLength = Int(headers[.contentLength]) self.sequenceNumber = Int(headers[.blobSequenceNumber]) self.serverEncrypted = Bool(headers[.serverEncrypted]) self.blobType = BlobType(rawValue: headers[.blobType]) self.leaseStatus = LeaseStatus(rawValue: headers[.leaseStatus]) self.leaseState = LeaseState(rawValue: headers[.leaseState]) self.leaseDuration = LeaseDuration(rawValue: headers[.leaseDuration]) self.copyStatus = CopyStatus(rawValue: headers[.copyStatus]) self.copySource = URL(string: headers[.copySource]) // Not documented as a valid response header self.accessTier = nil self.incrementalCopy = nil self.accessTierInferred = nil self.accessTierChangeTime = nil self.deletedTime = nil self.remainingRetentionDays = nil } /// :nodoc: public init(from decoder: Decoder) throws { let root = try decoder.container(keyedBy: CodingKeys.self) self.init( creationTime: try root.decodeIfPresent(Date.self, forKey: .creationTime), lastModified: try root.decodeIfPresent(Date.self, forKey: .lastModified), eTag: try root.decodeIfPresent(String.self, forKey: .eTag), contentLength: try root.decodeIntIfPresent(forKey: .contentLength), contentType: try root.decodeIfPresent(String.self, forKey: .contentType), contentDisposition: try root.decodeIfPresent(String.self, forKey: .contentDisposition), contentEncoding: try root.decodeIfPresent(String.self, forKey: .contentEncoding), contentLanguage: try root.decodeIfPresent(String.self, forKey: .contentLanguage), contentMD5: try root.decodeIfPresent(String.self, forKey: .contentMD5), contentCRC64: try root.decodeIfPresent(String.self, forKey: .contentCRC64), cacheControl: try root.decodeIfPresent(String.self, forKey: .cacheControl), sequenceNumber: try root.decodeIntIfPresent(forKey: .sequenceNumber), blobType: try root.decodeIfPresent(BlobType.self, forKey: .blobType), accessTier: try root.decodeIfPresent(AccessTier.self, forKey: .accessTier), leaseStatus: try root.decodeIfPresent(LeaseStatus.self, forKey: .leaseStatus), leaseState: try root.decodeIfPresent(LeaseState.self, forKey: .leaseState), leaseDuration: try root.decodeIfPresent(LeaseDuration.self, forKey: .leaseDuration), copyId: try root.decodeIfPresent(String.self, forKey: .copyId), copyStatus: try root.decodeIfPresent(CopyStatus.self, forKey: .copyStatus), copySource: try URL(string: root.decodeIfPresent(String.self, forKey: .copySource) ?? ""), copyProgress: try root.decodeIfPresent(String.self, forKey: .copyProgress), copyCompletionTime: try root.decodeIfPresent(Date.self, forKey: .copyCompletionTime), copyStatusDescription: try root.decodeIfPresent(String.self, forKey: .copyStatusDescription), serverEncrypted: try root.decodeBoolIfPresent(forKey: .serverEncrypted), incrementalCopy: try root.decodeBoolIfPresent(forKey: .incrementalCopy), accessTierInferred: try root.decodeBoolIfPresent(forKey: .accessTierInferred), accessTierChangeTime: try root.decodeIfPresent(Date.self, forKey: .accessTierChangeTime), deletedTime: try root.decodeIfPresent(Date.self, forKey: .deletedTime), remainingRetentionDays: try root.decodeIntIfPresent(forKey: .remainingRetentionDays) ) } }
52.521401
120
0.682027
4685324ae799020da6d1d7d13aab2a021f880ae3
569
// // FriendsTableViewCell.swift // AppIdea // // Created by Ryan Vanderhoef on 7/23/15. // Copyright (c) 2015 Ryan Vanderhoef. All rights reserved. // import UIKit import Parse class FriendsTableViewCell: UITableViewCell { @IBOutlet weak var friendsLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
21.884615
63
0.674868
b91a3ae3545c2881af8b89b25e9e127eddd54ac5
4,480
// // AppDelegate.swift // FoodTracker // // Created by Jane Appleseed on 10/17/16. // Copyright © 2016 Apple Inc. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // 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: "Model") 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)") } } } }
49.230769
285
0.683259
71b875bf96329860058787b9d7e6fb9bbb17b3c2
9,726
// // StepOkDepositCheckViewController.swift // Cosmostation // // Created by 정용주 on 2020/08/27. // Copyright © 2020 wannabit. All rights reserved. // import UIKit import Alamofire import HDWalletKit class StepOkDepositCheckViewController: BaseViewController, PasswordViewDelegate, SBCardPopupDelegate { @IBOutlet weak var toDepositAmountLabel: UILabel! @IBOutlet weak var toDepositAmountDenom: UILabel! @IBOutlet weak var feeAmountLabel: UILabel! @IBOutlet weak var feeAmountDenom: UILabel! @IBOutlet weak var memoLabel: UILabel! @IBOutlet weak var beforeBtn: UIButton! @IBOutlet weak var confirmBtn: UIButton! var pageHolderVC: StepGenTxViewController! override func viewDidLoad() { super.viewDidLoad() self.account = BaseData.instance.selectAccountById(id: BaseData.instance.getRecentAccountId()) self.chainType = WUtils.getChainType(account!.account_base_chain) pageHolderVC = self.parent as? StepGenTxViewController WUtils.setDenomTitle(chainType, toDepositAmountDenom) WUtils.setDenomTitle(chainType, feeAmountDenom) } @IBAction func onClickConfirm(_ sender: Any) { let popupVC = DelegateWarnPopup(nibName: "DelegateWarnPopup", bundle: nil) popupVC.warnImgType = 14 let cardPopup = SBCardPopupViewController(contentViewController: popupVC) cardPopup.resultDelegate = self cardPopup.show(onViewController: self) } @IBAction func onClickBack(_ sender: Any) { self.beforeBtn.isUserInteractionEnabled = false self.confirmBtn.isUserInteractionEnabled = false pageHolderVC.onBeforePage() } override func enableUserInteraction() { self.onUpdateView() self.beforeBtn.isUserInteractionEnabled = true self.confirmBtn.isUserInteractionEnabled = true } func onUpdateView() { toDepositAmountLabel.attributedText = WUtils.displayAmount2(pageHolderVC.mOkToStaking.amount, toDepositAmountLabel.font, 0, 18) feeAmountLabel.attributedText = WUtils.displayAmount2((pageHolderVC.mFee?.amount[0].amount)!, feeAmountLabel.font, 0, 18) memoLabel.text = pageHolderVC.mMemo } func SBCardPopupResponse(type:Int, result: Int) { if (result == 1) { let passwordVC = UIStoryboard(name: "Password", bundle: nil).instantiateViewController(withIdentifier: "PasswordViewController") as! PasswordViewController self.navigationItem.title = "" self.navigationController!.view.layer.add(WUtils.getPasswordAni(), forKey: kCATransition) passwordVC.mTarget = PASSWORD_ACTION_CHECK_TX passwordVC.resultDelegate = self self.navigationController?.pushViewController(passwordVC, animated: false) } } func passwordResponse(result: Int) { if (result == PASSWORD_RESUKT_OK) { self.onFetchAccountInfo(pageHolderVC.mAccount!) } } func onFetchAccountInfo(_ account: Account) { self.showWaittingAlert() let request = Alamofire.request(BaseNetWork.accountInfoUrl(chainType, account.account_address), method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:]) request.responseJSON { (response) in switch response.result { case .success(let res): guard let info = res as? NSDictionary else { _ = BaseData.instance.deleteBalance(account: account) self.hideWaittingAlert() self.onShowToast(NSLocalizedString("error_network", comment: "")) return } let okAccountInfo = OkAccountInfo.init(info) _ = BaseData.instance.updateAccount(WUtils.getAccountWithOkAccountInfo(account, okAccountInfo)) BaseData.instance.mOkAccountInfo = okAccountInfo self.onGenOkDepositTx() case .failure(let error): self.hideWaittingAlert() self.onShowToast(NSLocalizedString("error_network", comment: "")) print("onFetchAccountInfo ", error) } } } func onGenOkDepositTx() { DispatchQueue.global().async { var stdTx:StdTx! do { let msg = MsgGenerator.genOkDepositMsg(self.pageHolderVC.mAccount!.account_address, self.pageHolderVC.mOkToStaking) var msgList = Array<Msg>() msgList.append(msg) let stdMsg = MsgGenerator.getToSignMsg(BaseData.instance.getChainId(self.chainType), String(self.pageHolderVC.mAccount!.account_account_numner), String(self.pageHolderVC.mAccount!.account_sequence_number), msgList, self.pageHolderVC.mFee!, self.pageHolderVC.mMemo!) let encoder = JSONEncoder() encoder.outputFormatting = .sortedKeys let data = try? encoder.encode(stdMsg) let rawResult = String(data:data!, encoding:.utf8)?.replacingOccurrences(of: "\\/", with: "/") let rawData: Data? = rawResult!.data(using: .utf8) if (self.pageHolderVC.mAccount!.account_custom_path == 0) { print("Tender Type") let hash = rawData!.sha256() let signedData = try! ECDSA.compactsign(hash, privateKey: self.pageHolderVC.privateKey!) var genedSignature = Signature.init() var genPubkey = PublicKey.init() genPubkey.type = COSMOS_KEY_TYPE_PUBLIC genPubkey.value = self.pageHolderVC.publicKey!.base64EncodedString() genedSignature.pub_key = genPubkey genedSignature.signature = signedData.base64EncodedString() genedSignature.account_number = String(self.pageHolderVC.mAccount!.account_account_numner) genedSignature.sequence = String(self.pageHolderVC.mAccount!.account_sequence_number) var signatures: Array<Signature> = Array<Signature>() signatures.append(genedSignature) stdTx = MsgGenerator.genSignedTx(msgList, self.pageHolderVC.mFee!, self.pageHolderVC.mMemo!, signatures) } else { print("Ether Type") let hash = HDWalletKit.Crypto.sha3keccak256(data: rawData!) let signedData: Data? = try ECDSA.compactsign(hash, privateKey: self.pageHolderVC.privateKey!) var genedSignature = Signature.init() var genPubkey = PublicKey.init() genPubkey.type = ETHERMINT_KEY_TYPE_PUBLIC genPubkey.value = self.pageHolderVC.publicKey!.base64EncodedString() genedSignature.pub_key = genPubkey genedSignature.signature = signedData!.base64EncodedString() genedSignature.account_number = String(self.pageHolderVC.mAccount!.account_account_numner) genedSignature.sequence = String(self.pageHolderVC.mAccount!.account_sequence_number) var signatures: Array<Signature> = Array<Signature>() signatures.append(genedSignature) stdTx = MsgGenerator.genSignedTx(msgList, self.pageHolderVC.mFee!, self.pageHolderVC.mMemo!, signatures) } } catch { print(error) } DispatchQueue.main.async(execute: { let postTx = PostTx.init("sync", stdTx.value) let encoder = JSONEncoder() encoder.outputFormatting = .sortedKeys let data = try? encoder.encode(postTx) do { let params = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] let request = Alamofire.request(BaseNetWork.broadcastUrl(self.chainType), method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:]) request.responseJSON { response in var txResult = [String:Any]() switch response.result { case .success(let res): print("Deposit ", res) if let result = res as? [String : Any] { txResult = result } case .failure(let error): print("Deposit error ", error) if (response.response?.statusCode == 500) { txResult["net_error"] = 500 } } if (self.waitAlert != nil) { self.waitAlert?.dismiss(animated: true, completion: { self.onStartTxDetail(txResult) }) } } } catch { print(error) } }); } } }
47.213592
179
0.567859
7927554a3f392ca0ef1cecd15d92d0736c7e1fa3
2,506
// // web3swift_numberFormattingUtil_Tests.swift // web3swift-iOS_Tests // // Created by Антон Григорьев on 02.07.2018. // Copyright © 2018 Bankex Foundation. All rights reserved. // import BigInt //import CryptoSwift import XCTest @testable import web3swift class NumberFormattingUtilTests: XCTestCase { func testNumberFormattingUtil() { let balance = BigInt("-1000000000000000000")! let formatted = balance.string(unitDecimals: 18, decimals: 4, decimalSeparator: ",") XCTAssertEqual(formatted, "-1") } func testNumberFormattingUtil2() { let balance = BigInt("-1000000000000000")! let formatted = balance.string(unitDecimals: 18, decimals: 4, decimalSeparator: ",") XCTAssertEqual(formatted, "-0,001") } func testNumberFormattingUtil3() { let balance = BigInt("-1000000000000")! let formatted = balance.string(unitDecimals: 18, decimals: 4, decimalSeparator: ",") XCTAssertEqual(formatted, "-0") } func testNumberFormattingUtil4() { let balance = BigInt("-1000000000000")! let formatted = balance.string(unitDecimals: 18, decimals: 9, decimalSeparator: ",") XCTAssertEqual(formatted, "-0,000001") } func testNumberFormattingUtil5() { let balance = BigInt("-1")! let formatted = balance.string(unitDecimals: 18, decimals: 9, decimalSeparator: ",", options: [.stripZeroes,.fallbackToScientific]) XCTAssertEqual(formatted, "-1e-18") } func testNumberFormattingUtil6() { let balance = BigInt("0")! let formatted = balance.string(unitDecimals: 18, decimals: 9, decimalSeparator: ",") XCTAssertEqual(formatted, "0") } func testNumberFormattingUtil7() { let balance = BigInt("-1100000000000000000")! let formatted = balance.string(unitDecimals: 18, decimals: 4, decimalSeparator: ",") XCTAssertEqual(formatted, "-1,1") } func testNumberFormattingUtil8() { let balance = BigInt("100")! let formatted = balance.string(unitDecimals: 18, decimals: 4, decimalSeparator: ",", options: [.stripZeroes,.fallbackToScientific]) XCTAssertEqual(formatted, "1,00e-16") } func testNumberFormattingUtil9() { let balance = BigInt("1000000")! let formatted = balance.string(unitDecimals: 18, decimals: 4, decimalSeparator: ",", options: [.stripZeroes,.fallbackToScientific]) XCTAssertEqual(formatted, "1,0000e-12") } }
35.8
139
0.666002
ff0c8fddac6fac9640e777ee0e623e0b422f2e00
5,639
// // TaskDetailsView.swift // TasKit // // Created by Kyle Dold on 15/02/2021. // import SwiftUI struct TaskDetailsView<ViewModel: TaskDetailsViewModelProtocol>: View { // MARK: - Properties @ObservedObject var viewModel: ViewModel @State private var feedback = UINotificationFeedbackGenerator() @State private var showDeleteConfirmationAlert = false @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> // MARK: - View var body: some View { VStack { navigationBarView ScrollView { VStack { taskBasicDetailsView SubTaskListView(viewModel: viewModel.subTaskListViewModel) Spacer() } } } .padding(.horizontal) .navigationBarHidden(true) .alert(isPresented: $showDeleteConfirmationAlert, content: { deleteConfirmationAlert }) .bottomSheet(isPresented: $viewModel.showCalendarView, height: 450) { CalendarView(viewModel: viewModel.calendarViewModel) } .onAppear { // TODO: find a better way to handle this UITextView.appearance().backgroundColor = .clear } } // MARK: - Events private func backButtonTapped() { UIApplication.shared.endEditing() presentationMode.wrappedValue.dismiss() } private func calendarButtonTapped() { viewModel.calendarButtonTapped() } private func deleteButtonTapped() { showDeleteConfirmationAlert = true } } extension TaskDetailsView { private var navigationBarView: some View { HStack { Button(action: backButtonTapped, label: { Image(systemName: Image.Icons.back) }).buttonStyle(ImageButtonStyle(buttonColor: .primary)) Spacer() Button(action: deleteButtonTapped, label: { Text(viewModel.deleteButtonText) }) .buttonStyle(TextNavigationButtonStyle(buttonColor: .t_red, textColor: .white)) }.padding(.bottom, Layout.Spacing.compact) } private var taskBasicDetailsView: some View { VStack(spacing: Layout.Spacing.cozy) { VStack(spacing: Layout.Spacing.cozy) { HStack { CheckBox(isChecked: $viewModel.isComplete) TextField(viewModel.taskNamePlaceholderText, text: $viewModel.taskName) .textFieldStyle(SimpleTextFieldStyle()) } VStack(spacing: Layout.Spacing.compact) { dueDateRow timeRow } .padding(Layout.Spacing.cozy) .background(Color.t_input_background) .cornerRadius(Layout.Spacing.compact) TextBox(viewModel.taskNotesPlaceholderText, text: $viewModel.taskNotes) } } } private var dueDateRow: some View { VStack { HStack { Text(viewModel.taskDateText) Spacer() Button(action: calendarButtonTapped, label: { HStack { Text(viewModel.formattedDueDate) .foregroundColor(.primary) } .padding(Layout.Spacing.compact) .background(Color.t_input_background_2) .cornerRadius(Layout.Spacing.compact) }) } } } private var timeRow: some View { VStack { HStack { Text(viewModel.timeText) Spacer() Toggle(isOn: $viewModel.isTimeToggledOn, label: {}).toggleStyle(SwitchToggleStyle(tint: .t_action)) .padding(Layout.Spacing.tight) } if viewModel.isTimeToggledOn { VStack { HStack { Spacer() DatePicker(String.empty, selection: $viewModel.dueTime, displayedComponents: .hourAndMinute) .datePickerStyle(GraphicalDatePickerStyle()) .scaleEffect(0.85) .padding(.trailing, -Layout.Spacing.spacious) .padding(.vertical, -Layout.Spacing.compact) } HStack { Text(viewModel.reminderText) Spacer() Toggle(isOn: $viewModel.isReminderToggledOn, label: {}).toggleStyle(SwitchToggleStyle(tint: .t_action)) .padding(Layout.Spacing.tight) } } } } } var deleteConfirmationAlert: Alert { Alert( title: Text(viewModel.deleteAlertTitleText), message: Text(viewModel.deleteAlertMessageText), primaryButton: .destructive(Text(viewModel.deleteButtonText), action: { viewModel.deleteButtonTapped { presentationMode.wrappedValue.dismiss() } }), secondaryButton: .cancel() ) } } // MARK: - PreviewProvider - struct AddTaskView_Previews: PreviewProvider { static var previews: some View { TaskDetailsView(viewModel: FakeTaskDetailsViewModel()) } }
32.784884
127
0.530236
e2fcada5fc6c7c37b2d953f37dd1b08b116a553c
10,323
// // ZcashRustBackendWelding.swift // ZcashLightClientKit // // Created by Francisco Gindre on 12/09/2019. // Copyright © 2019 Electric Coin Company. All rights reserved. // import Foundation public enum RustWeldingError: Error { case genericError(message: String) case dataDbInitFailed(message: String) case dataDbNotEmpty case saplingSpendParametersNotFound case malformedStringInput case noConsensusBranchId(height: Int32) } public struct ZcashRustBackendWeldingConstants { static let validChain: Int32 = -1 } public protocol ZcashRustBackendWelding { /** gets the latest error if available. Clear the existing error */ static func lastError() -> RustWeldingError? /** gets the latest error message from librustzcash. Does not clear existing error */ static func getLastError() -> String? /** initializes the data db - Parameter dbData: location of the data db sql file */ static func initDataDb(dbData: URL) throws /** - Returns: true when the address is valid and shielded. Returns false in any other case - Throws: Error when the provided address belongs to another network */ static func isValidShieldedAddress(_ address: String) throws -> Bool /** - Returns: true when the address is valid and transparent. false in any other case - Throws: Error when the provided address belongs to another network */ static func isValidTransparentAddress(_ address: String) throws -> Bool /** - Returns: true when the address is valid and transparent. false in any other case - Throws: Error when there's another problem not related to validity of the string in question */ static func isValidExtendedFullViewingKey(_ key: String) throws -> Bool /** initialize the accounts table from a given seed and a number of accounts - Parameters: - dbData: location of the data db - seed: byte array of the zip32 seed - accounts: how many accounts you want to have */ static func initAccountsTable(dbData: URL, seed: [UInt8], accounts: Int32) -> [String]? /** initialize the accounts table from a given seed and a number of accounts - Parameters: - dbData: location of the data db - exfvks: byte array of the zip32 seed - Returns: a boolean indicating if the database was initialized or an error */ static func initAccountsTable(dbData: URL, exfvks: [String]) throws -> Bool /** initialize the blocks table from a given checkpoint (birthday) - Parameters: - dbData: location of the data db - height: represents the block height of the given checkpoint - hash: hash of the merkle tree - time: in milliseconds from reference - saplingTree: hash of the sapling tree */ static func initBlocksTable(dbData: URL, height: Int32, hash: String, time: UInt32, saplingTree: String) throws /** gets the address from data db from the given account - Parameters: - dbData: location of the data db - account: index of the given account - Returns: an optional string with the address if found */ static func getAddress(dbData: URL, account: Int32) -> String? /** get the (unverified) balance from the given account - Parameters: - dbData: location of the data db - account: index of the given account */ static func getBalance(dbData: URL, account: Int32) -> Int64 /** get the verified balance from the given account - Parameters: - dbData: location of the data db - account: index of the given account */ static func getVerifiedBalance(dbData: URL, account: Int32) -> Int64 /** get received memo from note - Parameters: - dbData: location of the data db file - idNote: note_id of note where the memo is located */ static func getReceivedMemoAsUTF8(dbData: URL, idNote: Int64) -> String? /** get sent memo from note - Parameters: - dbData: location of the data db file - idNote: note_id of note where the memo is located */ static func getSentMemoAsUTF8(dbData: URL, idNote: Int64) -> String? /** Checks that the scanned blocks in the data database, when combined with the recent `CompactBlock`s in the cache database, form a valid chain. This function is built on the core assumption that the information provided in the cache database is more likely to be accurate than the previously-scanned information. This follows from the design (and trust) assumption that the `lightwalletd` server provides accurate block information as of the time it was requested. - Returns: * `-1` if the combined chain is valid. * `upper_bound` if the combined chain is invalid. * `upper_bound` is the height of the highest invalid block (on the assumption that the highest block in the cache database is correct). * `0` if there was an error during validation unrelated to chain validity. - Important: This function does not mutate either of the databases. */ static func validateCombinedChain(dbCache: URL, dbData: URL) -> Int32 /** rewinds the compact block storage to the given height. clears up all derived data as well - Parameters: - dbData: location of the data db file - height: height to rewind to */ static func rewindToHeight(dbData: URL, height: Int32) -> Bool /** Scans new blocks added to the cache for any transactions received by the tracked accounts. This function pays attention only to cached blocks with heights greater than the highest scanned block in `db_data`. Cached blocks with lower heights are not verified against previously-scanned blocks. In particular, this function **assumes** that the caller is handling rollbacks. For brand-new light client databases, this function starts scanning from the Sapling activation height. This height can be fast-forwarded to a more recent block by calling [`zcashlc_init_blocks_table`] before this function. Scanned blocks are required to be height-sequential. If a block is missing from the cache, an error will be signalled. - Parameters: - dbCache: location of the compact block cache db - dbData: location of the data db file returns false if fails to scan. */ static func scanBlocks(dbCache: URL, dbData: URL) -> Bool /** Scans a transaction for any information that can be decrypted by the accounts in the wallet, and saves it to the wallet. - Parameters: - dbData: location of the data db file - tx: the transaction to decrypt returns false if fails to decrypt. */ static func decryptAndStoreTransaction(dbData: URL, tx: [UInt8]) -> Bool /** Creates a transaction to the given address from the given account - Parameters: - dbData: URL for the Data DB - account: the account index that will originate the transaction - extsk: extended spending key string - consensusBranchId: the current consensus ID - to: recipient address - value: transaction amount in Zatoshi - memo: the memo string for this transaction - spendParamsPath: path escaped String for the filesystem locations where the spend parameters are located - outputParamsPath: path escaped String for the filesystem locations where the output parameters are located */ static func createToAddress(dbData: URL, account: Int32, extsk: String, consensusBranchId: Int32, to: String, value: Int64, memo: String?, spendParamsPath: String, outputParamsPath: String) -> Int64 /** Derives a full viewing key from a seed - Parameter spendingKey: a string containing the spending key - Returns: the derived key - Throws: RustBackendError if fatal error occurs */ static func deriveExtendedFullViewingKey(_ spendingKey: String) throws -> String? /** Derives a set of full viewing keys from a seed - Parameter spendingKey: a string containing the spending key - Parameter accounts: the number of accounts you want to derive from this seed - Returns: an array containing the derived keys - Throws: RustBackendError if fatal error occurs */ static func deriveExtendedFullViewingKeys(seed: [UInt8], accounts: Int32) throws -> [String]? /** Derives a set of full viewing keys from a seed - Parameter seed: a string containing the seed - Parameter accounts: the number of accounts you want to derive from this seed - Returns: an array containing the spending keys - Throws: RustBackendError if fatal error occurs */ static func deriveExtendedSpendingKeys(seed: [UInt8], accounts: Int32) throws -> [String]? /** Derives a shielded address from a seed - Parameter seed: an array of bytes of the seed - Parameter accountIndex: the index of the account you want the address for - Returns: an optional String containing the Shielded address - Throws: RustBackendError if fatal error occurs */ static func deriveShieldedAddressFromSeed(seed: [UInt8], accountIndex: Int32) throws -> String? /** Derives a shielded address from an Extended Full Viewing Key - Parameter extfvk: a string containing the extended full viewing key - Returns: an optional String containing the Shielded address - Throws: RustBackendError if fatal error occurs */ static func deriveShieldedAddressFromViewingKey(_ extfvk: String) throws -> String? /** Derives a shielded address from an Extended Full Viewing Key - Parameter seed: an array of bytes of the seed - Returns: an optional String containing the transparent address - Throws: RustBackendError if fatal error occurs */ static func deriveTransparentAddressFromSeed(seed: [UInt8]) throws -> String? /** Gets the consensus branch id for the given height - Parameter height: the height you what to know the branch id for */ static func consensusBranchIdFor(height: Int32) throws -> Int32 }
41.292
202
0.692337
7aa6e890e716e994cda55fee87de2ba4c6d2c215
12,245
// // ContentView.swift // SideMenu // // Created by Vidhyadharan Mohanram on 11/06/19. // Copyright © 2019 Vid. All rights reserved. // Override by Ethan 2021/12/02 import SwiftUI public struct SideMenu : View { // MARK: Custom initializers public init<Menu: View, CenterView: View>(leftMenu: Menu, centerView: CenterView, config: SideMenuConfig = SideMenuConfig()) { self.leftMenu = AnyView(leftMenu) self.config = config self._sideMenuCenterView = State(initialValue: AnyView(centerView)) } public init<Menu: View, CenterView: View>(rightMenu: Menu, centerView: CenterView, config: SideMenuConfig = SideMenuConfig()) { self.rightMenu = AnyView(rightMenu) self.config = config self._sideMenuCenterView = State(initialValue: AnyView(centerView)) } public init<LMenu: View, RMenu: View, CenterView: View>(leftMenu: LMenu, rightMenu: RMenu, centerView: CenterView, config: SideMenuConfig = SideMenuConfig()) { self.leftMenu = AnyView(leftMenu) self.rightMenu = AnyView(rightMenu) self.config = config self._sideMenuCenterView = State(initialValue: AnyView(centerView)) } private var leftMenu: AnyView? = nil private var rightMenu: AnyView? = nil private var config: SideMenuConfig @State private var leftMenuBGOpacity: Double = 0 @State private var rightMenuBGOpacity: Double = 0 @State private var leftMenuOffsetX: CGFloat = 0 @State private var rightMenuOffsetX: CGFloat = 0 @Environment (\.editMode) var editMode; @State private var sideMenuGestureMode: SideMenuGestureMode = SideMenuGestureMode.active; @State private var sideMenuLeftPanel: Bool = false @State private var sideMenuRightPanel: Bool = false @State private var sideMenuCenterView: AnyView private var menuAnimation: Animation { .easeOut(duration: self.config.animationDuration) } public var body: some View { return GeometryReader { geometry in ZStack { self.sideMenuCenterView .opacity(1) .transition(.opacity) if self.sideMenuLeftPanel && self.leftMenu != nil { MenuBackgroundView(sideMenuLeftPanel: self.$sideMenuLeftPanel, sideMenuRightPanel: self.$sideMenuRightPanel, bgColor: self.config.menuBGColor, bgOpacity: self.leftMenuBGOpacity) .zIndex(1) self.leftMenu! .edgesIgnoringSafeArea(Edge.Set.all) .frame(width: self.config.menuWidth) .offset(x: self.leftMenuOffsetX, y: 0) .transition(.move(edge: Edge.leading)) .zIndex(2) } if self.sideMenuRightPanel && self.rightMenu != nil { MenuBackgroundView(sideMenuLeftPanel: self.$sideMenuLeftPanel, sideMenuRightPanel: self.$sideMenuRightPanel, bgColor: self.config.menuBGColor, bgOpacity: self.rightMenuBGOpacity) .zIndex(3) self.rightMenu! .edgesIgnoringSafeArea(Edge.Set.all) .frame(width: self.config.menuWidth) .offset(x: self.rightMenuOffsetX, y: 0) .transition(.move(edge: Edge.trailing)) .zIndex(4) } }.gesture(self.panelDragGesture(geometry.size.width)) .animation(self.menuAnimation) .onAppear { self.leftMenuOffsetX = -self.menuXOffset(geometry.size.width) self.rightMenuOffsetX = self.menuXOffset(geometry.size.width) self.leftMenuBGOpacity = self.config.menuBGOpacity self.rightMenuBGOpacity = self.config.menuBGOpacity NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: OperationQueue.main) { _ in self.sideMenuRightPanel = false self.sideMenuLeftPanel = false // self.rightMenuOffsetX = self.menuXOffset(geometry.size.width) // self.leftMenuOffsetX = -self.menuXOffset(geometry.size.width) } } .environment(\.sideMenuGestureModeKey, self.$sideMenuGestureMode) .environment(\.sideMenuCenterViewKey, self.$sideMenuCenterView) .environment(\.sideMenuLeftPanelKey, self.$sideMenuLeftPanel) .environment(\.sideMenuRightPanelKey, self.$sideMenuRightPanel) .environment(\.horizontalSizeClass, .compact) } } private func panelDragGesture(_ screenWidth: CGFloat) -> _EndedGesture<_ChangedGesture<DragGesture>>? { if let mode = self.editMode?.wrappedValue, mode != EditMode.inactive { return nil } if self.sideMenuGestureMode == SideMenuGestureMode.inactive { return nil } return DragGesture() .onChanged { (value) in self.onChangedDragGesture(value: value, screenWidth: screenWidth) } .onEnded { (value) in self.onEndedDragGesture(value: value, screenWidth: screenWidth) } } private func menuXOffset(_ screenWidth: CGFloat) -> CGFloat { return (screenWidth - (self.config.menuWidth))/2 } // MARK: Drag gesture methods func onChangedDragGesture(value: DragGesture.Value, screenWidth: CGFloat) { let startLocX = value.startLocation.x let translation = value.translation let translationWidth = translation.width > 0 ? translation.width : -(translation.width) let leftMenuGesturePositionX = screenWidth * 0.1 let rightMenuGesturePositionX = screenWidth * 0.9 guard translationWidth <= self.config.menuWidth else { return } if self.sideMenuLeftPanel, value.dragDirection == .left, self.leftMenu != nil { let newXOffset = -self.menuXOffset(screenWidth) - translationWidth self.leftMenuOffsetX = newXOffset let translationPercentage = (self.config.menuWidth - translationWidth) / self.config.menuWidth guard translationPercentage > 0 else { return } self.leftMenuBGOpacity = self.config.menuBGOpacity * Double(translationPercentage) } else if self.sideMenuRightPanel, value.dragDirection == .right, self.rightMenu != nil { let newXOffset = self.menuXOffset(screenWidth) + translationWidth self.rightMenuOffsetX = newXOffset let translationPercentage = (self.config.menuWidth - translationWidth) / self.config.menuWidth guard translationPercentage > 0 else { return } self.rightMenuBGOpacity = self.config.menuBGOpacity * Double(translationPercentage) } else if startLocX < leftMenuGesturePositionX, value.dragDirection == .right, self.leftMenu != nil { if !self.sideMenuLeftPanel { self.sideMenuLeftPanel.toggle() } let defaultOffset = -(self.menuXOffset(screenWidth) + self.config.menuWidth) let newXOffset = defaultOffset + translationWidth self.leftMenuOffsetX = newXOffset let translationPercentage = translationWidth / self.config.menuWidth guard translationPercentage > 0 else { return } self.leftMenuBGOpacity = self.config.menuBGOpacity * Double(translationPercentage) } else if startLocX > rightMenuGesturePositionX, value.dragDirection == .left, self.rightMenu != nil { if !self.sideMenuRightPanel { self.sideMenuRightPanel.toggle() } let defaultOffset = self.menuXOffset(screenWidth) + self.config.menuWidth let newXOffset = defaultOffset - translationWidth self.rightMenuOffsetX = newXOffset let translationPercentage = translationWidth / self.config.menuWidth guard translationPercentage > 0 else { return } self.rightMenuBGOpacity = self.config.menuBGOpacity * Double(translationPercentage) } } func onEndedDragGesture(value: DragGesture.Value, screenWidth: CGFloat) { let midXPoint = (0.5 * self.config.menuWidth) if self.sideMenuRightPanel, self.rightMenu != nil { let rightMenuMidX = self.menuXOffset(screenWidth) + midXPoint if self.rightMenuOffsetX > rightMenuMidX { self.sideMenuRightPanel.toggle() } self.rightMenuOffsetX = self.menuXOffset(screenWidth) self.rightMenuBGOpacity = self.config.menuBGOpacity } else if self.sideMenuLeftPanel, self.leftMenu != nil { let leftMenuMidX = -self.menuXOffset(screenWidth) - midXPoint if self.leftMenuOffsetX < leftMenuMidX { self.sideMenuLeftPanel.toggle() } self.leftMenuOffsetX = -self.menuXOffset(screenWidth) self.leftMenuBGOpacity = self.config.menuBGOpacity } } } @available(iOS 14.0, *) struct SideMenuViewProvider: LibraryContentProvider { @LibraryContentBuilder var views: [LibraryItem] { LibraryItem(SideMenu(leftMenu: LeftMenuPanel(), centerView: CenterView()), visible: true, title: "SideMenu with left menu", category: .control) LibraryItem(SideMenu(rightMenu: RightMenuPanel(), centerView: CenterView()), visible: true, title: "SideMenu with right menu", category: .control) LibraryItem(SideMenu(leftMenu: LeftMenuPanel(), rightMenu: RightMenuPanel(), centerView: CenterView()), visible: true, title: "SideMenu with both left and right menu", category: .control) } } // MARK: Menu background view struct MenuBackgroundView : View { @Binding var sideMenuLeftPanel: Bool @Binding var sideMenuRightPanel: Bool let bgColor: Color let bgOpacity: Double var body: some View { Rectangle() .background(bgColor) .opacity(bgOpacity) .transition(.opacity) .onTapGesture { withAnimation { if self.sideMenuLeftPanel { self.sideMenuLeftPanel.toggle() } if self.sideMenuRightPanel { self.sideMenuRightPanel.toggle() } } } .edgesIgnoringSafeArea(Edge.Set.all) } } #if DEBUG struct ContentView_Previews : PreviewProvider { static var previews: some View { let leftMenu = LeftMenuPanel() let rightMenu = RightMenuPanel() return Group { SideMenu(leftMenu: leftMenu, centerView: AnyView(CenterView())) SideMenu(rightMenu: rightMenu, centerView: AnyView(CenterView())) SideMenu(leftMenu: leftMenu, rightMenu: rightMenu, centerView: AnyView(CenterView())) } } } #endif
41.368243
154
0.57305
1a3d92d9bead09bca9541079051e900d50977e64
2,358
// // SceneDelegate.swift // KanjiLookup-UIKit // // Created by Morten Bertz on 2020/07/03. // Copyright © 2020 telethon k.k. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.666667
147
0.71374
219de72ccb5447a0cd82fc1ca9816a5e8da73feb
2,024
// // ImageURLBuilderTests.swift // MarvelTests // // Created by Diego Rogel on 12/2/22. // @testable import Marvel_Debug import XCTest class ImageURLBuilderTests: XCTestCase { private var sut: ImageURLBuilder! private var imageStub: Image! private let imageSchemeStub = "http://" private let imageDomainStub = "test.com" private let imagePathStub = "/test" private let imageExtensionStub = "jpg" private var imageFullPathStub: String { imageSchemeStub + imageDomainStub + imagePathStub } override func setUp() { super.setUp() sut = SecureImageURLBuilder() imageStub = Image(path: imageFullPathStub, imageExtension: imageExtensionStub) } override func tearDown() { sut = nil imageStub = nil super.tearDown() } func test_whenBuildingURL_returnsHTTPSImagePathWithAppendedExtension() { let actualURL = whenBuildingURLFromImageStub() let expectedURLScheme = "https://" let expectedURL = expectedURLScheme + imageDomainStub + imagePathStub + "." + imageExtensionStub XCTAssertEqual(actualURL.absoluteString, expectedURL) } func test_whenBuildingInvalidURL_returnsNil() { let imageWithoutExtension = Image(path: " ", imageExtension: "") let actualURL = sut.buildURL(from: imageWithoutExtension) XCTAssertNil(actualURL) } func test_givenAVariant_whenBuildingURL_returnsURLWithAppendedVariant() { let actualURL = whenBuildingURL(withVariant: .landscapeLarge) let expectedPath = imagePathStub + "/" + ImageVariant.landscapeLarge.rawValue + "." + imageExtensionStub XCTAssertEqual(actualURL.path, expectedPath) } } private extension ImageURLBuilderTests { func whenBuildingURLFromImageStub() -> URL { try! XCTUnwrap(sut.buildURL(from: imageStub)) } func whenBuildingURL(withVariant variant: ImageVariant) -> URL { try! XCTUnwrap(sut.buildURL(from: imageStub, variant: variant)) } }
32.126984
112
0.698617
ebd982d2301aafdd481401f28e053844ccfdb241
2,148
// // AppDelegate.swift // ViewControllerTransition // // Created by Ben on 15/7/20. // Copyright (c) 2015年 X-Team. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.702128
285
0.75419
2196393eca47dc541fe38bdce1d36af7dc748efe
2,176
// // AppDelegate.swift // HPFloatMenuExample // // Created by Hoang on 4/22/19. // Copyright © 2019 Quang Hoang. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } 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.297872
285
0.755515
7a7db1e77bf1f33765a5c6d2e2b6ac65fd425a7c
10,195
// // WebimClient.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 10.08.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ final class WebimClientBuilder { // MARK: - Properties private var appVersion: String? private var prechat: String? private var authorizationData: AuthorizationData? private var baseURL: String? private var completionHandlerExecutor: ExecIfNotDestroyedHandlerExecutor? private var deltaCallback: DeltaCallback? private var deviceID: String? private var deviceToken: String? private var internalErrorListener: InternalErrorListener? private var location: String? private var providedAuthenticationToken: String? private weak var providedAuthenticationTokenStateListener: ProvidedAuthorizationTokenStateListener? private var sessionID: String? private var sessionParametersListener: SessionParametersListener? private var title: String? private var visitorFieldsJSONString: String? private var visitorJSONString: String? // MARK: - Builder methods func set(appVersion: String?) -> WebimClientBuilder { self.appVersion = appVersion return self } func set(baseURL: String) -> WebimClientBuilder { self.baseURL = baseURL return self } func set(location: String) -> WebimClientBuilder { self.location = location return self } func set(deltaCallback: DeltaCallback) -> WebimClientBuilder { self.deltaCallback = deltaCallback return self } func set(sessionParametersListener: SessionParametersListener) -> WebimClientBuilder { self.sessionParametersListener = sessionParametersListener return self } func set(internalErrorListener: InternalErrorListener) -> WebimClientBuilder { self.internalErrorListener = internalErrorListener return self } func set(visitorJSONString: String?) -> WebimClientBuilder { self.visitorJSONString = visitorJSONString return self } func set(visitorFieldsJSONString: String?) -> WebimClientBuilder { self.visitorFieldsJSONString = visitorFieldsJSONString return self } func set(providedAuthenticationTokenStateListener: ProvidedAuthorizationTokenStateListener?, providedAuthenticationToken: String? = nil) -> WebimClientBuilder { self.providedAuthenticationTokenStateListener = providedAuthenticationTokenStateListener self.providedAuthenticationToken = providedAuthenticationToken return self } func set(sessionID: String?) -> WebimClientBuilder { self.sessionID = sessionID return self } func set(authorizationData: AuthorizationData?) -> WebimClientBuilder { self.authorizationData = authorizationData return self } func set(completionHandlerExecutor: ExecIfNotDestroyedHandlerExecutor?) -> WebimClientBuilder { self.completionHandlerExecutor = completionHandlerExecutor return self } func set(title: String) -> WebimClientBuilder { self.title = title return self } func set(deviceToken: String?) -> WebimClientBuilder { self.deviceToken = deviceToken return self } func set(deviceID: String) -> WebimClientBuilder { self.deviceID = deviceID return self } func set(prechat:String?) -> WebimClientBuilder { self.prechat = prechat return self } func build() -> WebimClient { let actionRequestLoop = ActionRequestLoop(completionHandlerExecutor: completionHandlerExecutor!, internalErrorListener: internalErrorListener!) actionRequestLoop.set(authorizationData: authorizationData) let deltaRequestLoop = DeltaRequestLoop(deltaCallback: deltaCallback!, completionHandlerExecutor: completionHandlerExecutor!, sessionParametersListener: SessionParametersListenerWrapper(withSessionParametersListenerToWrap: sessionParametersListener, actionRequestLoop: actionRequestLoop), internalErrorListener: internalErrorListener!, baseURL: baseURL!, title: title!, location: location!, appVersion: appVersion, visitorFieldsJSONString: visitorFieldsJSONString, providedAuthenticationTokenStateListener: providedAuthenticationTokenStateListener, providedAuthenticationToken: providedAuthenticationToken, deviceID: deviceID!, deviceToken: deviceToken, visitorJSONString: visitorJSONString, sessionID: sessionID, prechat: prechat, authorizationData: authorizationData ) return WebimClient(withActionRequestLoop: actionRequestLoop, deltaRequestLoop: deltaRequestLoop, webimActions: WebimActions(baseURL: baseURL!, actionRequestLoop: actionRequestLoop)) } } // MARK: - // Need to update deviceToken in DeltaRequestLoop on update in WebimActions. /** Class that is responsible for history storage when it is set to memory mode. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ final class WebimClient { // MARK: - Properties private let actionRequestLoop: ActionRequestLoop private let deltaRequestLoop: DeltaRequestLoop private let webimActions: WebimActions // MARK: - Initialization init(withActionRequestLoop actionRequestLoop: ActionRequestLoop, deltaRequestLoop: DeltaRequestLoop, webimActions: WebimActions) { self.actionRequestLoop = actionRequestLoop self.deltaRequestLoop = deltaRequestLoop self.webimActions = webimActions } // MARK: - Methods func start() { deltaRequestLoop.start() actionRequestLoop.start() } func pause() { deltaRequestLoop.pause() actionRequestLoop.pause() } func resume() { deltaRequestLoop.resume() actionRequestLoop.resume() } func stop() { deltaRequestLoop.stop() actionRequestLoop.stop() } func set(deviceToken: String) { deltaRequestLoop.set(deviceToken: deviceToken) webimActions.update(deviceToken: deviceToken) } func getDeltaRequestLoop() -> DeltaRequestLoop { return deltaRequestLoop } func getActions() -> WebimActions { return webimActions } } // MARK: - // Need to update AuthorizationData in ActionRequestLoop on update in DeltaRequestLoop. /** - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ final private class SessionParametersListenerWrapper: SessionParametersListener { // MARK: - Properties private let wrappedSessionParametersListener: SessionParametersListener? private let actionRequestLoop: ActionRequestLoop // MARK: - Initializers init(withSessionParametersListenerToWrap wrappingSessionParametersListener: SessionParametersListener?, actionRequestLoop: ActionRequestLoop) { wrappedSessionParametersListener = wrappingSessionParametersListener self.actionRequestLoop = actionRequestLoop } // MARK: - SessionParametersListener protocol methods func onSessionParametersChanged(visitorFieldsJSONString visitorJSONString: String, sessionID: String, authorizationData: AuthorizationData) { actionRequestLoop.set(authorizationData: authorizationData) wrappedSessionParametersListener?.onSessionParametersChanged(visitorFieldsJSONString: visitorJSONString, sessionID: sessionID, authorizationData: authorizationData) } }
35.897887
171
0.622756
5d59b5f688a1e15b3cd620e4990acda5444fca54
10,542
// // ViewController.swift // MacTerminal // // Created by Miguel de Icaza on 3/11/20. // Copyright © 2020 Miguel de Icaza. All rights reserved. // import Cocoa import SwiftTerm class ViewController: NSViewController, LocalProcessTerminalViewDelegate, NSUserInterfaceValidations { @IBOutlet var loggingMenuItem: NSMenuItem? var changingSize = false var logging: Bool = false var zoomGesture: NSMagnificationGestureRecognizer? var postedTitle: String = "" var postedDirectory: String? = nil func sizeChanged(source: LocalProcessTerminalView, newCols: Int, newRows: Int) { if changingSize { return } changingSize = true //var border = view.window!.frame - view.frame var newFrame = terminal.getOptimalFrameSize () let windowFrame = view.window!.frame newFrame = CGRect (x: windowFrame.minX, y: windowFrame.minY, width: newFrame.width, height: windowFrame.height - view.frame.height + newFrame.height) view.window?.setFrame(newFrame, display: true, animate: true) changingSize = false } func updateWindowTitle () { var newTitle: String if let dir = postedDirectory { if let uri = URL(string: dir) { if postedTitle == "" { newTitle = uri.path } else { newTitle = "\(postedTitle) - \(uri.path)" } } else { newTitle = postedTitle } } else { newTitle = postedTitle } view.window?.title = newTitle } func setTerminalTitle(source: LocalProcessTerminalView, title: String) { postedTitle = title updateWindowTitle () } func hostCurrentDirectoryUpdate (source: TerminalView, directory: String?) { self.postedDirectory = directory updateWindowTitle() } func processTerminated(source: TerminalView, exitCode: Int32?) { view.window?.close() if let e = exitCode { print ("Process terminated with code: \(e)") } else { print ("Process vanished") } } var terminal: LocalProcessTerminalView! static var lastTerminal: LocalProcessTerminalView! func getBufferAsData () -> Data { return terminal.getTerminal().getBufferAsData () } func updateLogging () { let path = logging ? "/Users/miguel/Downloads/Logs" : nil terminal.setHostLogging (directory: path) NSUserDefaultsController.shared.defaults.set (logging, forKey: "LogHostOutput") } override func viewDidLoad() { super.viewDidLoad() terminal = LocalProcessTerminalView(frame: view.frame) zoomGesture = NSMagnificationGestureRecognizer(target: self, action: #selector(zoomGestureHandler)) terminal.addGestureRecognizer(zoomGesture!) ViewController.lastTerminal = terminal terminal.processDelegate = self terminal.feed(text: "Welcome to SwiftTerm") terminal.startProcess () view.addSubview(terminal) logging = NSUserDefaultsController.shared.defaults.bool(forKey: "LogHostOutput") updateLogging () } @objc func zoomGestureHandler (_ sender: NSMagnificationGestureRecognizer) { if sender.magnification > 0 { biggerFont (sender) } else { smallerFont(sender) } } override func viewDidLayout() { super.viewDidLayout() changingSize = true terminal.frame = view.frame changingSize = false terminal.needsLayout = true } @objc @IBAction func set80x25 (_ source: AnyObject) { terminal.resize(cols: 80, rows: 25) } var lowerCol = 80 var lowerRow = 25 var higherCol = 160 var higherRow = 60 func queueNextSize () { // If they requested a stop if resizificating == 0 { return } var next = terminal.getTerminal().getDims () if resizificating > 0 { if next.cols < higherCol { next.cols += 1 } if next.rows < higherRow { next.rows += 1 } } else { if next.cols > lowerCol { next.cols -= 1 } if next.rows > lowerRow { next.rows -= 1 } } terminal.resize (cols: next.cols, rows: next.rows) var direction = resizificating if next.rows == higherRow && next.cols == higherCol { direction = -1 } if next.rows == lowerRow && next.cols == lowerCol { direction = 1 } DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { self.resizificating = direction self.queueNextSize() } } var resizificating = 0 @objc @IBAction func resizificator (_ source: AnyObject) { if resizificating != 1 { resizificating = 1 queueNextSize () } else { resizificating = 0 } } @objc @IBAction func resizificatorDown (_ source: AnyObject) { if resizificating != -1 { resizificating = -1 queueNextSize () } else { resizificating = 0 } } @objc @IBAction func allowMouseReporting (_ source: AnyObject) { terminal.allowMouseReporting.toggle () } @objc @IBAction func exportBuffer (_ source: AnyObject) { saveData { self.terminal.getTerminal().getBufferAsData () } } @objc @IBAction func exportSelection (_ source: AnyObject) { saveData { if let str = self.terminal.getSelection () { return str.data (using: .utf8) ?? Data () } return Data () } } func saveData (_ getData: @escaping () -> Data) { let savePanel = NSSavePanel () savePanel.canCreateDirectories = true savePanel.allowedFileTypes = ["txt"] savePanel.title = "Export Buffer Contents As Text" savePanel.nameFieldStringValue = "TerminalCapture" savePanel.begin { (result) in if result.rawValue == NSApplication.ModalResponse.OK.rawValue { let data = getData () if let url = savePanel.url { do { try data.write(to: url) } catch let error as NSError { let alert = NSAlert (error: error) alert.runModal() } } } } } @objc @IBAction func softReset (_ source: AnyObject) { terminal.getTerminal().softReset () terminal.setNeedsDisplay(terminal.frame) } @objc @IBAction func hardReset (_ source: AnyObject) { terminal.getTerminal().resetToInitialState () terminal.setNeedsDisplay(terminal.frame) } @objc @IBAction func toggleOptionAsMetaKey (_ source: AnyObject) { terminal.optionAsMetaKey.toggle () } @objc @IBAction func biggerFont (_ source: AnyObject) { let size = terminal.font.pointSize guard size < 72 else { return } terminal.font = NSFont.monospacedSystemFont(ofSize: size+1, weight: .regular) } @objc @IBAction func smallerFont (_ source: AnyObject) { let size = terminal.font.pointSize guard size > 5 else { return } terminal.font = NSFont.monospacedSystemFont(ofSize: size-1, weight: .regular) } @objc @IBAction func defaultFontSize (_ source: AnyObject) { terminal.font = NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular) } @objc @IBAction func addTab (_ source: AnyObject) { // if let win = view.window { // win.tabbingMode = .preferred // if let wc = win.windowController { // if let d = wc.document as? Document { // do { // let x = Document() // x.makeWindowControllers() // // try NSDocumentController.shared.newDocument(self) // } catch {} // print ("\(d.debugDescription)") // } // } // } // win.tabbingMode = .preferred // win.addTabbedWindow(win, ordered: .above) // // if let wc = win.windowController { // wc.newWindowForTab(self() // wc.showWindow(source) // } // } } func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool { if item.action == #selector(debugToggleHostLogging(_:)) { if let m = item as? NSMenuItem { m.state = logging ? NSControl.StateValue.on : NSControl.StateValue.off } } if item.action == #selector(resizificator(_:)) { if let m = item as? NSMenuItem { m.state = resizificating == 1 ? NSControl.StateValue.on : NSControl.StateValue.off } } if item.action == #selector(resizificatorDown(_:)) { if let m = item as? NSMenuItem { m.state = resizificating == -1 ? NSControl.StateValue.on : NSControl.StateValue.off } } if item.action == #selector(allowMouseReporting(_:)) { if let m = item as? NSMenuItem { m.state = terminal.allowMouseReporting ? NSControl.StateValue.on : NSControl.StateValue.off } } if item.action == #selector(toggleOptionAsMetaKey(_:)) { if let m = item as? NSMenuItem { m.state = terminal.optionAsMetaKey ? NSControl.StateValue.on : NSControl.StateValue.off } } // Only enable "Export selection" if we have a selection if item.action == #selector(exportSelection(_:)) { return terminal.selectionActive } return true } @objc @IBAction func debugToggleHostLogging (_ source: AnyObject) { logging = !logging updateLogging() } }
29.121547
157
0.549706
f7c3d9668a4271cf654f689bbdeef8b799db0eff
524
// // File.swift // // // Created by Vamsi Katragadda on 09/10/19. // import Foundation open class ResponseParserJson: ResponseParser { open func parse(_ data: Data) -> Any? { do { let responseBody = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) return responseBody as Any? } catch let error as NSError { print("error parsing data: \(error.localizedDescription)") return nil } } }
24.952381
133
0.629771
bb0e690a0e303b1ad6cf8133295076a7bcaefcdb
1,447
// // DateViewModel.swift // EventKitDemo // // Created by Jeffrey Chang on 6/17/19. // Copyright © 2019 Jeffrey Chang. All rights reserved. // import Foundation class DateViewModel { private let indexPath: IndexPath private let firstWeekDayOfMonth: Int private let todaysDate: Int private let currentYear: Int private let presentYear: Int private let currentMonthIndex: Int private let presentMonthIndex: Int init(indexPath: IndexPath, firstWeekDayOfMonth: Int, todaysDate: Int, currentYear: Int, presentYear: Int, currentMonthIndex: Int, presentMonthIndex: Int) { self.indexPath = indexPath self.firstWeekDayOfMonth = firstWeekDayOfMonth self.todaysDate = todaysDate self.currentYear = currentYear self.presentYear = presentYear self.currentMonthIndex = currentMonthIndex self.presentMonthIndex = presentMonthIndex } func shouldHideDateCell() -> Bool { return indexPath.item <= firstWeekDayOfMonth - 2 ? true : false } func calcuateDateString() -> String { let calcDate = indexPath.row - firstWeekDayOfMonth + 2 return String(calcDate) } func shouldUserInteractionEnable() -> Bool { let calcDate = indexPath.row - firstWeekDayOfMonth + 2 return calcDate < todaysDate && currentYear == presentYear && currentMonthIndex == presentMonthIndex ? false : true } }
32.155556
159
0.689703
21ea3d77cb5481ed78de367f0c9ab7402d21eac7
585
// // iTunesApp.swift // Knil // // Created by Ethanhuang on 2018/6/25. // Copyright © 2018年 Elaborapp Co., Ltd. All rights reserved. // import Foundation public struct iTunesApp: Codable { public let appStoreURL: URL public let bundleID: String public let productID: Int public let appName: String public let iconURL: URL enum CodingKeys: String, CodingKey { case appStoreURL = "trackViewUrl" case bundleID = "bundleId" case productID = "trackId" case appName = "trackName" case iconURL = "artworkUrl512" } }
22.5
62
0.654701
086a6ae43bdc845b89b2daa403bd5aa24326d0a2
1,964
// // UIViewExtensions.swift // // Created by nya on 2018/04/10. // import UIKit @IBDesignable public extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return layer.borderColor.flatMap({ UIColor(cgColor: $0) }) } set { layer.borderColor = newValue?.cgColor } } @IBInspectable var shadowColor: UIColor? { get { return layer.shadowColor.flatMap({ UIColor(cgColor: $0) }) } set { layer.shadowColor = newValue?.cgColor } } @IBInspectable var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } @IBInspectable var shadowOffset: CGSize { get { return layer.shadowOffset } set { layer.shadowOffset = newValue } } @IBInspectable var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } @IBInspectable var transformX: CGFloat { get { return transform.tx } set { var t = transform t.tx = newValue transform = t } } @IBInspectable var transformY: CGFloat { get { return transform.ty } set { var t = transform t.ty = newValue transform = t } } }
18.528302
70
0.478106
14eb899f1ab1475fea52fcb11cded215bb2fde89
7,217
// // UIView+Extension.swift // BaseProject // // Created by 沙庭宇 on 2019/7/15. // Copyright © 2019 沙庭宇. All rights reserved. // import UIKit /** * ViewGeometry */ public extension UIView { /// 顶部距离父控件的距离 /// /// self.frame.origin.y var top: CGFloat { get{ return self.frame.origin.y } set{ var frame = self.frame frame.origin.y = newValue self.frame = frame } } /// 左边距离父控件的距离 /// /// self.frame.origin.x var left: CGFloat { get{ return self.frame.origin.x } set{ var frame = self.frame frame.origin.x = newValue self.frame = frame } } /// 当前View的底部,距离父控件顶部的距离 /// /// self.frame.maxY var bottom: CGFloat { get { return self.frame.maxY } set { var frame = self.frame frame.origin.y = newValue - frame.size.height self.frame = frame } } /// 当前View的右边,距离父控件左边的距离 /// /// self.frame.maxX var right: CGFloat { get { return self.frame.maxX } set { guard let superW = superview?.width else { return } var frame = self.frame frame.origin.x = superW - newValue - frame.width self.frame = frame } } /// 宽度 var width: CGFloat { get { return self.frame.size.width } set { var frame = self.frame frame.size.width = newValue self.frame = frame } } /// 高度 var height: CGFloat { get { return self.frame.size.height } set { var frame = self.frame frame.size.height = newValue self.frame = frame } } /// X轴的中心位置 var centerX: CGFloat { get { return self.center.x } set { self.center = CGPoint(x: newValue, y: self.center.y) } } /// Y轴的中心位置 var centerY: CGFloat { get { return self.center.y } set { self.center = CGPoint(x: self.center.x, y: newValue) } } /// 左上角的顶点,在父控件中的位置 var origin: CGPoint { get { return self.frame.origin } set { var frame = self.frame frame.origin = newValue self.frame = frame } } /// 尺寸大小 var size: CGSize { get { return self.frame.size } set { var frame = self.frame frame.size = newValue self.frame = frame } } } public extension UIView { /// 移除父视图中的所有子视图 func removeAllSubviews() { while (self.subviews.count > 0) { self.subviews.last?.removeFromSuperview() } } } public extension UIView { /// 裁剪 view 的圆角,裁一角或者全裁 /// /// 其实就是根据当前View的Size绘制了一个 CAShapeLayer,将其遮在了当前View的layer上,就是Mask层,使mask以外的区域不可见 /// - parameter direction: 需要裁切的圆角方向,左上角(topLeft)、右上角(topRight)、左下角(bottomLeft)、右下角(bottomRight)或者所有角落(allCorners) /// - parameter cornerRadius: 圆角半径 func clipRectCorner(direction: UIRectCorner, cornerRadius: CGFloat) { let cornerSize = CGSize(width:cornerRadius, height:cornerRadius) let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: direction, cornerRadii: cornerSize) let maskLayer = CAShapeLayer() maskLayer.frame = bounds maskLayer.path = maskPath.cgPath layer.addSublayer(maskLayer) layer.mask = maskLayer } /// 根据需要,裁剪各个顶点为圆角 /// /// 其实就是根据当前View的Size绘制了一个 CAShapeLayer,将其遮在了当前View的layer上,就是Mask层,使mask以外的区域不可见 /// - parameter directionList: 需要裁切的圆角方向,左上角(topLeft)、右上角(topRight)、左下角(bottomLeft)、右下角(bottomRight)或者所有角落(allCorners) /// - parameter cornerRadius: 圆角半径 /// - note: .pi等于180度,圆角计算,默认以圆横直径的右半部分顺时针开始计算(就类似上面那个圆形中的‘=====’线),当然如果参数 clockwies 设置false.则逆时针开始计算角度 func clipRectCorner(directionList: [UIRectCorner], cornerRadius radius: CGFloat) { let bezierPath = UIBezierPath() // 以左边中间节点开始绘制 bezierPath.move(to: CGPoint(x: 0, y: height/2)) // 如果左上角需要绘制圆角 if directionList.contains(.topLeft) { bezierPath.move(to: CGPoint(x: 0, y: radius)) bezierPath.addArc(withCenter: CGPoint(x: radius, y: radius), radius: radius, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true) } else { bezierPath.addLine(to: origin) } // 如果右上角需要绘制 if directionList.contains(.topRight) { bezierPath.addLine(to: CGPoint(x: right - radius, y: 0)) bezierPath.addArc(withCenter: CGPoint(x: width - radius, y: radius), radius: radius, startAngle: CGFloat.pi * 1.5, endAngle: CGFloat.pi * 2, clockwise: true) } else { bezierPath.addLine(to: CGPoint(x: width, y: 0)) } // 如果右下角需要绘制 if directionList.contains(.bottomRight) { bezierPath.addLine(to: CGPoint(x: width, y: height - radius)) bezierPath.addArc(withCenter: CGPoint(x: width - radius, y: height - radius), radius: radius, startAngle: 0, endAngle: CGFloat.pi/2, clockwise: true) } else { bezierPath.addLine(to: CGPoint(x: width, y: height)) } // 如果左下角需要绘制 if directionList.contains(.bottomLeft) { bezierPath.addLine(to: CGPoint(x: radius, y: height)) bezierPath.addArc(withCenter: CGPoint(x: radius, y: height - radius), radius: radius, startAngle: CGFloat.pi/2, endAngle: CGFloat.pi, clockwise: true) } else { bezierPath.addLine(to: CGPoint(x: 0, y: height)) } // 与开始节点闭合 bezierPath.addLine(to: CGPoint(x: 0, y: height/2)) let maskLayer = CAShapeLayer() maskLayer.frame = bounds maskLayer.path = bezierPath.cgPath layer.mask = maskLayer } /// 高斯模糊 func setBlurEffect(style: UIBlurEffect.Style = .light) { let blur = UIBlurEffect(style: style) let effectView = UIVisualEffectView(effect: blur) self.addSubview(effectView) effectView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } } public extension UIView { /// 显示Toast提示,基于当前的View,不影响其他页面的操作 func toast(_ message: String, duration: TimeInterval = 1.5, completion: ((_ didTap: Bool) -> Void)? = nil) { DispatchQueue.main.async { [weak self] in guard let self = self else { return } var style = ToastStyle() style.messageAlignment = .center self.toast(message, duration: duration, point: self.center, title: nil, image: nil, style: style, completion: completion) } } /// 显示Toast提示,基于最顶层,可能会影响其他的操作 class func topToast(_ message: String) { if let topWindow = UIApplication.shared.windows.last { topWindow.toast(message) } } }
28.191406
169
0.555217
48bdf4d0f06ca742ce6de7391f48b3c9739b9d3d
8,891
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. #if compiler(>=5.5.2) && canImport(_Concurrency) import SotoCore @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension MediaPackageVod { // MARK: Async API Calls /// Changes the packaging group's properities to configure log subscription public func configureLogs(_ input: ConfigureLogsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ConfigureLogsResponse { return try await self.client.execute(operation: "ConfigureLogs", path: "/packaging_groups/{Id}/configure_logs", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a new MediaPackage VOD Asset resource. public func createAsset(_ input: CreateAssetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreateAssetResponse { return try await self.client.execute(operation: "CreateAsset", path: "/assets", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a new MediaPackage VOD PackagingConfiguration resource. public func createPackagingConfiguration(_ input: CreatePackagingConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreatePackagingConfigurationResponse { return try await self.client.execute(operation: "CreatePackagingConfiguration", path: "/packaging_configurations", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a new MediaPackage VOD PackagingGroup resource. public func createPackagingGroup(_ input: CreatePackagingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> CreatePackagingGroupResponse { return try await self.client.execute(operation: "CreatePackagingGroup", path: "/packaging_groups", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes an existing MediaPackage VOD Asset resource. public func deleteAsset(_ input: DeleteAssetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeleteAssetResponse { return try await self.client.execute(operation: "DeleteAsset", path: "/assets/{Id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes a MediaPackage VOD PackagingConfiguration resource. public func deletePackagingConfiguration(_ input: DeletePackagingConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeletePackagingConfigurationResponse { return try await self.client.execute(operation: "DeletePackagingConfiguration", path: "/packaging_configurations/{Id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes a MediaPackage VOD PackagingGroup resource. public func deletePackagingGroup(_ input: DeletePackagingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DeletePackagingGroupResponse { return try await self.client.execute(operation: "DeletePackagingGroup", path: "/packaging_groups/{Id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a description of a MediaPackage VOD Asset resource. public func describeAsset(_ input: DescribeAssetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribeAssetResponse { return try await self.client.execute(operation: "DescribeAsset", path: "/assets/{Id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a description of a MediaPackage VOD PackagingConfiguration resource. public func describePackagingConfiguration(_ input: DescribePackagingConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribePackagingConfigurationResponse { return try await self.client.execute(operation: "DescribePackagingConfiguration", path: "/packaging_configurations/{Id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a description of a MediaPackage VOD PackagingGroup resource. public func describePackagingGroup(_ input: DescribePackagingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> DescribePackagingGroupResponse { return try await self.client.execute(operation: "DescribePackagingGroup", path: "/packaging_groups/{Id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a collection of MediaPackage VOD Asset resources. public func listAssets(_ input: ListAssetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListAssetsResponse { return try await self.client.execute(operation: "ListAssets", path: "/assets", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a collection of MediaPackage VOD PackagingConfiguration resources. public func listPackagingConfigurations(_ input: ListPackagingConfigurationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListPackagingConfigurationsResponse { return try await self.client.execute(operation: "ListPackagingConfigurations", path: "/packaging_configurations", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a collection of MediaPackage VOD PackagingGroup resources. public func listPackagingGroups(_ input: ListPackagingGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListPackagingGroupsResponse { return try await self.client.execute(operation: "ListPackagingGroups", path: "/packaging_groups", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a list of the tags assigned to the specified resource. public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> ListTagsForResourceResponse { return try await self.client.execute(operation: "ListTagsForResource", path: "/tags/{ResourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Adds tags to the specified resource. You can specify one or more tags to add. public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws { return try await self.client.execute(operation: "TagResource", path: "/tags/{ResourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Removes tags from the specified resource. You can specify one or more tags to remove. public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws { return try await self.client.execute(operation: "UntagResource", path: "/tags/{ResourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates a specific packaging group. You can't change the id attribute or any other system-generated attributes. public func updatePackagingGroup(_ input: UpdatePackagingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) async throws -> UpdatePackagingGroupResponse { return try await self.client.execute(operation: "UpdatePackagingGroup", path: "/packaging_groups/{Id}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } #endif // compiler(>=5.5.2) && canImport(_Concurrency)
78.681416
227
0.744236
f4ed8e3bc2dc671e44b9c7e7647084ad55cc0e9f
884
// // StudioDtoTests.swift // EmbyApiClient // import XCTest @testable import EmbyApiClient class StudioDtoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testBaseItemPersonHasNoPrimaryImage() { let studioDto = StudioDto(name: "name", id: "id", primaryImageTag: nil) XCTAssertFalse(studioDto.hasPrimaryImage) } func testBaseItemPersonHasPrimaryImage() { let studioDto = StudioDto(name: "name", id: "id", primaryImageTag: "primaryImageTag") XCTAssertTrue(studioDto.hasPrimaryImage) } }
26.787879
111
0.661765
e5fe2fe06258a65b98f9eb6b3b6630c31c1c8c71
234
import Foundation @testable import xcodeproj import XCTest final class XCConfigurationListSpec: XCTestCase { func test_isa_returnsTheCorrectValue() { XCTAssertEqual(XCConfigurationList.isa, "XCConfigurationList") } }
23.4
70
0.786325
d7d7c2734c4518cc91553b9cb81929cf1caa0540
640
// // BinanceHexEncoding.swift // Cosmostation // // Created by yongjoo jung on 2021/06/30. // Copyright © 2021 wannabit. All rights reserved. // import Foundation import Alamofire struct HexEncoding: ParameterEncoding { private let data: Data init(data: Data) { self.data = data } func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() urlRequest.setValue("text/plain", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = data.hexdata return urlRequest } }
22.857143
105
0.673438
71f98fb9bdd3e80cc4422e1d67be0ef26570afe3
347
// // CheckinModel.swift // WoopEventsApp // // Created by Ludgero Gil Mascarenhas on 01/08/19. // Copyright © 2019 Ludgero Gil Mascarenhas. All rights reserved. // import Foundation struct CheckInModel: Codable { var eventId: String var name: String var email: String } struct CheckInResponse: Codable { var code: String }
17.35
66
0.70317
ac716c913be0e9391e01aac6add3c390df893be4
804
// // OptionalView.swift // nexd // // Created by Tobias Schröpf on 02.06.20. // Copyright © 2020 Tobias Schröpf. All rights reserved. // import SwiftUI struct OptionalView<Value, Content>: View where Content: View { var content: (Value) -> Content var value: Value init?(_ value: Value?, @ViewBuilder content: @escaping (Value) -> Content) { guard let value = value else { return nil } self.value = value self.content = content } var body: some View { content(value) } } extension Optional where Wrapped: View { func whenNil<T: View>(_ transform: () -> T) -> AnyView? { switch self { case .none: return AnyView(transform()) case let .some(view): return AnyView(view) } } }
21.72973
80
0.589552
90f8741028bddbc3e368354063bc4c2de5021016
908
// // webKitSampleTests.swift // webKitSampleTests // // Created by Mahesh on 03/02/21. // import XCTest @testable import webKitSample class webKitSampleTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.705882
111
0.668502
0a557e3398bf8137496a6753a0d7cb66c7936638
2,297
// // HighLowCardGame // COPYRIGHT © 2020 Tobias Schaarschmidt // // https://tosc.dev // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.339623
147
0.713539
e4e57e378ff79ffd385e9f797349f1a0fc0764da
1,763
// // ProjectQRPermissionCheckerView.swift // PayForMe // // Created by Max Tharr on 03.10.20. // Copyright © 2020 Mayflower GmbH. All rights reserved. // import AVFoundation import SwiftUI struct ProjectQRPermissionCheckerView: View { @State var cameraAuthStatus = AVCaptureDevice.authorizationStatus(for: .video) var body: some View { switch cameraAuthStatus { case .authorized: return AddProjectQRView().eraseToAnyView() case .denied: return permissionDeniedView.eraseToAnyView() default: AVCaptureDevice.requestAccess(for: .video) { _ in cameraAuthStatus = AVCaptureDevice.authorizationStatus(for: .video) } return Text("Please allow us to use the camera in order to scan the Cospend QR code").padding(20).eraseToAnyView() } } var permissionDeniedView: some View { VStack(spacing: 20) { Text("If you want to scan your project as a QR code, you need to allow this app to use your camera. Otherwise please navigate back and fill out the information manually.") Button("Go to settings") { if let url = URL(string: UIApplication.openSettingsURLString) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: { _ in cameraAuthStatus = AVCaptureDevice.authorizationStatus(for: .video) }) } } } }.padding(20) } } struct ProjectQRPermissionCheckerView_Previews: PreviewProvider { static var previews: some View { ProjectQRPermissionCheckerView() } }
34.568627
183
0.621668
0e0cbe2cf10229463a905dc4d26ddd2d6060b032
2,777
import SwiftUI import ZwaaiLogic struct HistoryList: View { @Binding var history: [HistoryItem] @Binding var allTimePersonZwaaiCount: UInt @Binding var allTimeSpaceZwaaiCount: UInt var body: some View { List { Section(header: PersonenHeader(count: allTimePersonZwaaiCount)) { ForEach(history.filter({ $0.type.isPerson })) {item in Text(verbatim: timestampString(item)) .accessibility(label: Text("\(timestampString(item)) gezwaaid met een persoon")) } } Section(header: SpacesHeader(count: allTimeSpaceZwaaiCount)) { ForEach(history.filter({ $0.type.isSpace })) { item in SpaceRow(item: item) } } } } } private struct PersonenHeader: View { let count: UInt let formatString = NSLocalizedString( "Gezwaaid met %d personen", tableName: "HistoryList", bundle: .zwaaiView, comment: "Header of persons section in history list") var body: some View { HStack { Image(systemName: "person.fill") .accessibility(hidden: true) Text(verbatim: String.localizedStringWithFormat(formatString, count)) .font(.subheadline) }.accessibility(addTraits: .isHeader) } } private struct SpacesHeader: View { let count: UInt let formatString = NSLocalizedString( "Gezwaaid bij %d ruimtes", tableName: "HistoryList", bundle: .zwaaiView, comment: "Header of spaces section in history list") var body: some View { HStack { Image(systemName: "mappin.and.ellipse") .accessibility(hidden: true) Text(verbatim: String.localizedStringWithFormat(formatString, count)) .font(.subheadline) }.accessibility(addTraits: .isHeader) } } private struct SpaceRow: View { let item: HistoryItem var space: CheckedInSpace { return self.item.type.space! } var body: some View { VStack(alignment: .leading) { Text(verbatim: timestampString(item)) .accessibility(label: Text("\(timestampString(item)) gezwaaid bij ruimte \(space.name)")) HStack { Text("\(space.name)") if space.checkedOut != nil { Text(verbatim: "|") Text("uitgecheckt: \(DateFormatter.relativeMedium.string(from: space.checkedOut!).lowercased())") } }.font(.caption).padding([.top], 4) } } } private func timestampString(_ item: HistoryItem) -> String { return DateFormatter.relativeMedium.string(from: item.timestamp) }
33.059524
117
0.588405
67e53220c83dcdc862864bbcdafb5d41f7144b4d
1,937
import Foundation public extension TypeRegistry { static func createFromTypesDefinition(data: Data, additionalNodes: [Node]) throws -> TypeRegistry { let jsonDecoder = JSONDecoder() let json = try jsonDecoder.decode(JSON.self, from: data) return try createFromTypesDefinition(json: json, additionalNodes: additionalNodes) } static func createFromTypesDefinition(json: JSON, additionalNodes: [Node]) throws -> TypeRegistry { guard let types = json.types else { throw TypeRegistryError.unexpectedJson } let factories: [TypeNodeFactoryProtocol] = [ StructNodeFactory(parser: TypeMappingParser.structure()), EnumNodeFactory(parser: TypeMappingParser.enumeration()), EnumValuesNodeFactory(parser: TypeValuesParser.enumeration()), NumericSetNodeFactory(parser: TypeSetParser.generic()), TupleNodeFactory(parser: ComponentsParser.tuple()), FixedArrayNodeFactory(parser: FixedArrayParser.generic()), VectorNodeFactory(parser: RegexParser.vector()), OptionNodeFactory(parser: RegexParser.option()), CompactNodeFactory(parser: RegexParser.compact()), AliasNodeFactory(parser: TermParser.generic()) ] let resolvers: [TypeResolving] = [ CaseInsensitiveResolver(), TableResolver.noise(), RegexReplaceResolver.noise(), RegexReplaceResolver.genericsFilter() ] return try TypeRegistry(json: types, nodeFactory: OneOfTypeNodeFactory(children: factories), typeResolver: OneOfTypeResolver(children: resolvers), additionalNodes: additionalNodes) } }
43.044444
91
0.605059
d65ed7970de93750258bfb92219647bef01c071a
13,539
// // CommonTableViewController.swift // Example // // Created by Nathan Tannar on 2018-07-10. // Copyright © 2018 Nathan Tannar. All rights reserved. // import UIKit import InputBarAccessoryView class CommonTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let inputBar: InputBarAccessoryView let tableView = UITableView() let conversation: SampleData.Conversation private let mentionTextAttributes: [NSAttributedString.Key : Any] = [ .font: UIFont.preferredFont(forTextStyle: .body), .foregroundColor: UIColor.systemBlue, .backgroundColor: UIColor.systemBlue.withAlphaComponent(0.1) ] /// The object that manages attachments open lazy var attachmentManager: AttachmentManager = { [unowned self] in let manager = AttachmentManager() manager.delegate = self return manager }() /// The object that manages autocomplete open lazy var autocompleteManager: AutocompleteManager = { [unowned self] in let manager = AutocompleteManager(for: self.inputBar.inputTextView) manager.delegate = self manager.dataSource = self return manager }() var hashtagAutocompletes: [AutocompleteCompletion] = { var array: [AutocompleteCompletion] = [] for _ in 1...100 { array.append(AutocompleteCompletion(text: Lorem.word(), context: nil)) } return array }() // Completions loaded async that get appeneded to local cached completions var asyncCompletions: [AutocompleteCompletion] = [] init(style: InputBarStyle, conversation: SampleData.Conversation) { self.conversation = conversation self.inputBar = style.generate() super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 13, *) { view.backgroundColor = .systemBackground } else { view.backgroundColor = .white } view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.keyboardDismissMode = .interactive tableView.register(ConversationCell.self, forCellReuseIdentifier: "\(ConversationCell.self)") tableView.tableFooterView = UIView() tableView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leftAnchor.constraint(equalTo: view.leftAnchor), tableView.rightAnchor.constraint(equalTo: view.rightAnchor), tableView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor), ]) inputBar.delegate = self inputBar.inputTextView.keyboardType = .twitter // Configure AutocompleteManager autocompleteManager.register(prefix: "@", with: mentionTextAttributes) autocompleteManager.register(prefix: "#") autocompleteManager.maxSpaceCountDuringCompletion = 1 // Allow for autocompletes with a space // Set plugins inputBar.inputPlugins = [autocompleteManager, attachmentManager] // RTL Support // autocompleteManager.paragraphStyle.baseWritingDirection = .rightToLeft // inputBar.inputTextView.textAlignment = .right // inputBar.inputTextView.placeholderLabel.textAlignment = .right } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return conversation.messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "\(ConversationCell.self)", for: indexPath) cell.imageView?.image = conversation.messages[indexPath.row].user.image cell.imageView?.layer.cornerRadius = 5 cell.imageView?.clipsToBounds = true cell.textLabel?.text = conversation.messages[indexPath.row].user.name cell.textLabel?.font = .boldSystemFont(ofSize: 15) cell.textLabel?.numberOfLines = 0 if #available(iOS 13, *) { cell.detailTextLabel?.textColor = .secondaryLabel } else { cell.detailTextLabel?.textColor = .darkGray } cell.detailTextLabel?.font = .systemFont(ofSize: 14) cell.detailTextLabel?.text = conversation.messages[indexPath.row].text cell.detailTextLabel?.numberOfLines = 0 cell.selectionStyle = .none return cell } } extension CommonTableViewController: InputBarAccessoryViewDelegate { // MARK: - InputBarAccessoryViewDelegate func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) { // Here we can parse for which substrings were autocompleted let attributedText = inputBar.inputTextView.attributedText! let range = NSRange(location: 0, length: attributedText.length) attributedText.enumerateAttribute(.autocompleted, in: range, options: []) { (attributes, range, stop) in let substring = attributedText.attributedSubstring(from: range) let context = substring.attribute(.autocompletedContext, at: 0, effectiveRange: nil) print("Autocompleted: `", substring, "` with context: ", context ?? []) } inputBar.inputTextView.text = String() inputBar.invalidatePlugins() // Send button activity animation inputBar.sendButton.startAnimating() inputBar.inputTextView.placeholder = "Sending..." DispatchQueue.global(qos: .default).async { // fake send request task sleep(1) DispatchQueue.main.async { [weak self] in inputBar.sendButton.stopAnimating() inputBar.inputTextView.placeholder = "Aa" self?.conversation.messages.append(SampleData.Message(user: SampleData.shared.currentUser, text: text)) let indexPath = IndexPath(row: (self?.conversation.messages.count ?? 1) - 1, section: 0) self?.tableView.insertRows(at: [indexPath], with: .automatic) self?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true) } } } func inputBar(_ inputBar: InputBarAccessoryView, didChangeIntrinsicContentTo size: CGSize) { // Adjust content insets print(size) tableView.contentInset.bottom = size.height + 300 // keyboard size estimate } func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) { guard autocompleteManager.currentSession != nil, autocompleteManager.currentSession?.prefix == "#" else { return } // Load some data asyncronously for the given session.prefix DispatchQueue.global(qos: .default).async { // fake background loading task var array: [AutocompleteCompletion] = [] for _ in 1...10 { array.append(AutocompleteCompletion(text: Lorem.word())) } sleep(1) DispatchQueue.main.async { [weak self] in self?.asyncCompletions = array self?.autocompleteManager.reloadData() } } } } extension CommonTableViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) dismiss(animated: true, completion: { if let pickedImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage { let handled = self.attachmentManager.handleInput(of: pickedImage) if !handled { // throw error } } }) } } extension CommonTableViewController: AttachmentManagerDelegate { // MARK: - AttachmentManagerDelegate func attachmentManager(_ manager: AttachmentManager, shouldBecomeVisible: Bool) { setAttachmentManager(active: shouldBecomeVisible) } func attachmentManager(_ manager: AttachmentManager, didReloadTo attachments: [AttachmentManager.Attachment]) { inputBar.sendButton.isEnabled = manager.attachments.count > 0 } func attachmentManager(_ manager: AttachmentManager, didInsert attachment: AttachmentManager.Attachment, at index: Int) { inputBar.sendButton.isEnabled = manager.attachments.count > 0 } func attachmentManager(_ manager: AttachmentManager, didRemove attachment: AttachmentManager.Attachment, at index: Int) { inputBar.sendButton.isEnabled = manager.attachments.count > 0 } func attachmentManager(_ manager: AttachmentManager, didSelectAddAttachmentAt index: Int) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) } // MARK: - AttachmentManagerDelegate Helper func setAttachmentManager(active: Bool) { let topStackView = inputBar.topStackView if active && !topStackView.arrangedSubviews.contains(attachmentManager.attachmentView) { topStackView.insertArrangedSubview(attachmentManager.attachmentView, at: topStackView.arrangedSubviews.count) topStackView.layoutIfNeeded() } else if !active && topStackView.arrangedSubviews.contains(attachmentManager.attachmentView) { topStackView.removeArrangedSubview(attachmentManager.attachmentView) topStackView.layoutIfNeeded() } } } extension CommonTableViewController: AutocompleteManagerDelegate, AutocompleteManagerDataSource { // MARK: - AutocompleteManagerDataSource func autocompleteManager(_ manager: AutocompleteManager, autocompleteSourceFor prefix: String) -> [AutocompleteCompletion] { if prefix == "@" { return conversation.users .filter { $0.name != SampleData.shared.currentUser.name } .map { user in return AutocompleteCompletion(text: user.name, context: ["id": user.id]) } } else if prefix == "#" { return hashtagAutocompletes + asyncCompletions } return [] } func autocompleteManager(_ manager: AutocompleteManager, tableView: UITableView, cellForRowAt indexPath: IndexPath, for session: AutocompleteSession) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: AutocompleteCell.reuseIdentifier, for: indexPath) as? AutocompleteCell else { fatalError("Oops, some unknown error occurred") } let users = SampleData.shared.users let name = session.completion?.text ?? "" let user = users.filter { return $0.name == name }.first cell.imageView?.image = user?.image cell.textLabel?.attributedText = manager.attributedText(matching: session, fontSize: 15) return cell } // MARK: - AutocompleteManagerDelegate func autocompleteManager(_ manager: AutocompleteManager, shouldBecomeVisible: Bool) { setAutocompleteManager(active: shouldBecomeVisible) } // Optional func autocompleteManager(_ manager: AutocompleteManager, shouldRegister prefix: String, at range: NSRange) -> Bool { return true } // Optional func autocompleteManager(_ manager: AutocompleteManager, shouldUnregister prefix: String) -> Bool { return true } // Optional func autocompleteManager(_ manager: AutocompleteManager, shouldComplete prefix: String, with text: String) -> Bool { return true } // MARK: - AutocompleteManagerDelegate Helper func setAutocompleteManager(active: Bool) { let topStackView = inputBar.topStackView if active && !topStackView.arrangedSubviews.contains(autocompleteManager.tableView) { topStackView.insertArrangedSubview(autocompleteManager.tableView, at: topStackView.arrangedSubviews.count) topStackView.layoutIfNeeded() } else if !active && topStackView.arrangedSubviews.contains(autocompleteManager.tableView) { topStackView.removeArrangedSubview(autocompleteManager.tableView) topStackView.layoutIfNeeded() } inputBar.invalidateIntrinsicContentSize() } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue }
41.530675
174
0.673979
675c9e1697ac522f474c3b4673e35b92031c0061
1,117
// // Landmark.swift // SwiftUI-demo // // Created by Hancock on 2020/6/25. // Copyright © 2020 hancock. All rights reserved. // import SwiftUI import CoreLocation struct Landmark: Hashable, Codable, Identifiable { var id: Int var name: String fileprivate var imageName: String fileprivate var coordinates: Coordinates var state: String var park: String var category: Category 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" } } extension Landmark { var image: Image { ImageStore.shared.image(name: imageName) } } struct Coordinates: Hashable, Codable { var latitude: Double var longitude: Double } struct Landmark_Previews: PreviewProvider { static var previews: some View { /*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/ } }
21.901961
71
0.66607
ab81845066f3a0697dc0ef7f28d3003e8b35f412
370
// // BaseApi.swift // Candy // // Created by QY on 2020/1/14. // Copyright © 2020 Insect. All rights reserved. // import Moya /// 为 Moya TargetType 添加默认实现 public extension TargetType { var method: Moya.Method { .get } var headers: [String: String]? { nil } var validationType: ValidationType { .successCodes } }
14.230769
49
0.591892
3827bd94cce078718070516a362ea414e24fbdde
800
// // AllTrailsUITestsLaunchTests.swift // AllTrailsUITests // // Created by Arun Kumar on 9/13/21. // import XCTest class AllTrailsUITestsLaunchTests: 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.242424
88
0.67375
f93a97b9c0dd74e6ddf171505064ffbcdce0a8c6
10,334
//Chapter13 : Classes //클래스는 구조체와 매우 유사하다. 둘 모두 속성과 메서드가 있는 named type 이다. //클래스는 value type과는 대조적인 reference type이며, 구조체와 다른 기능과 이점이 있다. //종종 구조체로 값(value)를 나타내지만, 일반적으로는 클래스를 사용해 객체를 나타낸다. //Creating classes class Person { var firstName: String var lastName: String init(firstName: String, lastName: String) { //구조체와 달리 memberwise initializer가 자동으로 구현되지 않는다. self.firstName = firstName self.lastName = lastName } var fullName: String { "\(firstName) \(lastName)" } } let john = Person(firstName: "Johnny", lastName: "Appleseed") //구조체와 거의 동일하다. class 키워드 다음에 해당 클래스의 이름이 오며, 중괄호 안의 모든 것은 해당 클래스의 멤버가 된다. //구조체와 다르게 클래스는 memberwise initializer를 자동으로 제공하지 않으므로, 필요한 경우 직접 작성해야 한다. //위의 경우에는 initializer를 작성하지 않으면, 변수들이 초기화 되지 않으므로 컴파일러가 오류를 표시한다. //클래스의 초기화 규칙은 구조체와 매우 비슷하다. 클래스의 initializer는 init로 표시된 함수이며, 모든 stored property는 init 함수가 끝나기 전에 초기 값이 할당되어야 한다. //Reference types //Swift에서 구조체 인스턴스는 변강할 수 없는 값 타입이지만(immutable value), 클래스 인스턴스는 변경할 수 있는 객체이다(mutable object). //클래스는 Reference type으로, 클래스 변수는 실제 인스턴스를 저장하지 않는다. 대신 인스턴스를 저장하는 메모리 위치에 대한 참조를 저장한다. class SimplePersonClass { let name: String init(name: String) { self.name = name } } var var1 = SimplePersonClass(name: "John") //이와 같이 클래스 인스턴스를 생성하면, 메모리에서는 해당 객체를 가리키게 된다. p.249 var var2 = var1 //새 변수에 이전 변수를 할당하면, 두 변수는 메모리에서 동일한 위치를 참조한다. p.249 //이와 반대로, value type인 구조체는 실제 value를 저장하여 직접 액세스 한다. struct SimplePersonStructure { let name: String } var var3 = SimplePersonStructure(name: "John") //구조체로 인스턴스를 생성하면, 메모리 위치를 참조하지 않고, value는 var3에만 속한다. p.250 var var4 = var3 //var3을 할당하면, var3의 value를 복사한다. p.250 //value type과 reference type은 각각 고유한 장단점이 있다. 주어진 상황에 맞게 어떤 유형을 사용해야 하는지 고려해야 한다. //The heap vs. the stack //클래스와 같은 reference type을 작성하면, 시스템은 실제 인스턴스를 heap이라고 하는 메모리 영역에 저장한다. //구조체와 같은 value type은 stack이라는 메모리 영역에 존재하게 된다. 구조체가 클래스 인스턴스의 일부인 경우에는 클래스 인스턴스의 나머지 부분과 함께 heap에 저장된다. //힙과 스택은 프로그램 실행에 필수적인 역할을 한다. 힙과 스택이 무엇이고 어떻게 작동하는지 이해하는 것은 클래스와 구조체의 기능적 차이점을 시각화하는 데 도움을 준다. // • 시스템은 즉시 실행되는 스레드에 어떤 것이든 저장하기 위해 stack을 사용하며, 이는 CPU에 의해 엄격하게 관리되고 최적화된다. // 함수가 변수를 생성하면, stack은 해당 변수를 저장한 다음 함수가 종료될 때 이를 삭제한다. stack은 매우 엄밀하게 구성되기 때문에 굉장히 효율적이며 매우 빠르다. // • 시스템은 heap을 사용하여 참조 유형의 인스턴스를 저장한다. heap은 일반적으로 시스템이 메모리 블록을 요청하고 동적으로 할당할 수 있는 큰 메모리 풀이다. // heap의 lifetime은 유연하고 역동적이다. //힙은 스택처럼 데이터를 자동적으로 삭제하지 않으므로, 이를 위해서 추가적인 작업이 필요하다. 따라서 힙은 스택에서보다 데이터를 작성 제거하는 속도가 느리다. p.251 // • 클래스 인스턴스를 생성할 때, 힙에 메모리 블록을 요청하여 인스턴스 자체를 저장한다. 이후, 스택에 있는 명명된 변수에 해당 메모리 주소를 저장한다. // 따라서 stack에 있는 변수가 heap에 있는 인스턴스를 참조하게 된다. // • 구조체 인스턴스(클래스 인스턴스의 일부가 아닌 경우)를 만들면, 인스턴스 자체가 스택에 저장되고, 힙은 이 작업에 아무런 관여도 하지 않는다. //Working with references //이전에 살펴 본 것과 같이 구조체를 비롯한 value type을 다룰 때, copy semantic이 포함된다(값이 복사 된다). struct Location { let x: Int let y: Int } struct DeliveryArea { var range: Double let center: Location } var area1 = DeliveryArea(range: 2.5, center: Location(x: 2, y: 4)) //구조체 var area2 = area1 //area1을 area2에 할당하면, area2는 area1의 사본을 받는다. print(area1.range) // 2.5 print(area2.range) // 2.5 area1.range = 4 //area1.range에 새 값을 할당해도, area1에만 반영되고, area2는 여전히 원래 값을 가진다(copy semantic). print(area1.range) // 4.0 print(area2.range) // 2.5 //area1을 area2에 할당하면, area2는 area1의 사본을 받는다. //area1.range에 새 값을 할당해도, area1에만 반영되고, area2는 여전히 원래 값을 가진다(copy semantic). //하지만, 클래스는 reference type 이므로 클래스 인스턴스를 변수에 지정하면, 시스템은 인스턴스를 복사하지 않고, 참조만 복사한다. var homeOwner = john //클래스 john.firstName = "John" // John wants to use his short name! john.firstName // "John" homeOwner.firstName // "John" //구조체에서와 달리, 클래스에서는 john과 homeOwner가 같은 value를 가지게 된다. 이러한 특성은 클래스 인스턴스를 공유해 객체를 전달할 때 새로운 사고 방식을 만들게 된다. //ex. john 객체가 변경되면, john에 대한 참조를 보유한 모든 항목은 자동으로 업데이트 된다. //구조체의 경우에는, 각 사본을 개별적으로 업데이트하지 않으면 이전 값인 "Johnny"를 가지게 된다. //Object identity //이전 예제에서 john과 homeOwner가 동일한 객체를 가리키고 있음을 쉽게 알 수 있다. 두 변수가 실제 John을 제대로 가리키고 있는지 확인해야 할 수 있다. //firstName의 value를 비교해 확인할 수 있겠지만, 이는 적절하지 않은 방법이다. 동명 이인 일 수도 있고, John이 이름을 바꿀 수도 있다. //Swift에서는 === 연산자를 사용해, 한 객체의 identity가 다른 객체의 identity와 같은지 확인할 수 있다. john === homeOwner // true //== 연산자가 두 값이 같은지 확인하는 것 처럼, === 연산자는 두 참조의 메모리 주소를 비교해 참조값이 동일한지 여부(heap에서 동일한 데이터를 가리키는 지)를 알려준다. let imposterJohn = Person(firstName: "Johnny", lastName: "Appleseed") john === homeOwner // true john === imposterJohn // false imposterJohn === homeOwner // false // Assignment of existing variables changes the instances the variables reference. homeOwner = imposterJohn john === homeOwner // false homeOwner = john john === homeOwner // true //기존 변수를 다시 할당하면, 변수가 참조하는 인스턴스가 변경된다. //=== 연산자는 객체를 비교하고 식별하기 위해 ==를 사용할 수 없을 때 특히 유용하다. // Create fake, imposter Johns. Use === to see if any of these imposters are our real John. var imposters = (0...100).map { _ in Person(firstName: "John", lastName: "Appleseed") } // Equality (==) is not effective when John cannot be identified by his name alone imposters.contains { $0.firstName == john.firstName && $0.lastName == john.lastName } // true //identity operator를 사용하면, 참조 자체가 동일한지 확인해 실제 john과 같은지 구분할 수 있다. // Check to ensure the real John is not found among the imposters. imposters.contains { $0 === john } // false // Now hide the "real" John somewhere among the imposters. imposters.insert(john, at: Int.random(in: 0..<100)) // John can now be found among the imposters. imposters.contains { $0 === john } // true // Since `Person` is a reference type, you can use === to grab the real John out of the list of imposters and modify the value. // The original `john` variable will print the new last name! if let indexOfJohn = imposters.firstIndex(where:{ $0 === john }) { imposters[indexOfJohn].lastName = "Bananapeel" } john.fullName // John Bananapeel //Methods and mutability //클래스 인스턴스는 변경 가능한 객체(mutable object)인 반면, 구조체 인스턴스는 변경할 수 없는 값이다(immutable value). struct Grade { let letter: String let points: Double let credits: Double } class Student { var firstName: String var lastName: String var grades: [Grade] = [] var credits = 0.0 //updated init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } func recordGrade(_ grade: Grade) { grades.append(grade) credits += grade.credits //updated //해당 함수를 호출해서, 클래스 인스턴스의 credits를 업데이트한다. 이는 side effect를 불러온다. } } let jane = Student(firstName: "Jane", lastName: "Appleseed") let history = Grade(letter: "B", points: 9.0, credits: 3.0) var math = Grade(letter: "A", points: 16.0, credits: 4.0) jane.recordGrade(history) jane.recordGrade(math) //recordGrade(_:)는 grades 배열의 뒤에 value를 추가해 해당 배열을 변경할 수 있다. 이는 현재 객체의 멤버를 변경시키지만, mutating 키워드가 필요하지 않다. //구조체에서 같은 함수를 작성했다면, 구조체는 immutable이므로 컴파일러가 오류를 발생시켰을 것이다. //구조체에서 값을 변경할 때는, 그 값을 수정하는 대신 새로운 값을 만드는 것임을 기억해야 한다. //mutating 키워드는 현재 값을 새로운 값으로 대체하는 메서드를 표시한다. 클래스를 사용하면 인스턴스 자체가 변경 가능하므로 해당 키워드를 사용하지 않아도 된다. //Mutability and constants //상수(constant)를 정의하면, 상수 value는 값을 변경할 수 없다. 참조 유형의 경우, value가 reference 임을 기억해야 한다. //p.255 //참조 유형을 상수로 선언하면, 해당 참조가 상수가 된다. 다른 값을 할당하려 하면, 컴파일 오류가 발생한다. //jane = Student(firstName: "John", lastName: "Appleseed") // Error: jane is a `let` constant //jane을 변수로 선언하면, 힙에 다른 Student 인스턴스를 할당할 수 있다. var jane1 = Student(firstName: "Jane", lastName: "Appleseed") jane1 = Student(firstName: "John", lastName: "Appleseed") //참조가 새 Student 객체를 가리키도록 업데이트 된다. //이 때, 원본인 "jane1" 을 참조하는 객체가 없어지므로, 해당 메모리를 다른 곳에서 사용할 수 있다. //클래스의 모든 개별 멤버는 상수를 사용하여 수정되지 않도록 할 수 있지만, 참조 유형 자체는 value로 처리되지 않으므로 mutation으로부터 전체적으로 보호되진 않는다. //ex. 참조를 상수로 가지고 있는 것이지, 해당 참조 인스턴스의 멤버 변수의 값까지 변경할 수 없는 것이 아니다. // 위의 예에서 jane은 상수로 선언 되었기 때문에 다른 인스턴스로 할당할 수 없다. 하지만, jane 인스턴스의 property인 firstName, lastName, grades는 모두 var로 선언되었기 때문에 변경 가능하다. // jane은 상수이지만, jane.firstName는 변수이므로 jane.firstName = "John" 등 으로 변경할 수 있다. 이런 변경을 막으려면, jane.firstName 를 let으로 선언해야 한다. //Understanding state and side effects //클래스는 참조 가능하고(reference) 가변적이라(mutable)는 특성때문에 많은 가능성이 있지만, 우려 또한 존재한다. //클래스를 새 값으로 업데이트 하면, 해당 인스턴스에 대한 모든 참조에서도 새 값이 표시된다는걸 기억해야 한다. //이것을 장점으로 사용할 수 있다. Roster 클래스와 Sports 클래스가 모두 학생 클래스의 Grade를 참조하고 있을 때 grade만 업데이트 하면, 모든 인스턴스에서 해당 학생의 성적을 확인할 수 있다. //이 공유의 결과는 클래스 인스턴스가 state를 가진다는 것이다. 상태의 변화는 때로 명백하지만, 그렇지 않은 경우도 있다. //이 예를 확인하기 위해 credits 변수를 Student 클래스에 추가하고, recordGrade(_:) 함수를 업데이트 한다. //recordGrade(_:)에서 인스턴스의 credits를 업데이트하게 되는데 이는 side effect를 불러온다. //side effect는 명백하지 않은 행동을 초래할 수 있다. jane.credits // 7 // The teacher made a mistake; math has 5 credits math = Grade(letter: "A", points: 20.0, credits: 5.0) jane.recordGrade(math) jane.credits // 12, not 8! //recordGrade(_:)가 같은 grade를 두 번 기록되지 않는다고 가정하여 느슨하게 구현되었기 때문이다. //클래스 인스턴스는 mutable하므로 공유되는 reference에서 이와 같이 예기치 못한 side effect에 유의해야 한다. //클래스의 크기와 복잡성이 증가함에 따라 mutability와 state를 관리하기가 매우 어려워 질 수 있다. //Extending a class using an extension //구조체에서와 같이 extension 키워드를 사용하여 클래스에 method와 computed property를 추가할 수 있다. extension Student { var fullName: String { "\(firstName) \(lastName)" } } //inheritance(상속)을 사용해 클래스에 새로운 기능을 추가할 수도 있다. 상속된 클래스 역시 새로운 computed property를 추가할 수 있다. //When to use a class versus a struct //경우에 따라 구조체와 클래스 중 어떤 것을 사용해야 하는지 잘 판단해야 한다. //Values vs. objects //엄격하거나 간결한 규칙은 없지만, value와 reference의 semantic에 대해 생각해 봐야 한다. 구조체는 value, 클래스는 identity가 있는 object로 사용한다. //객체(object)는 참조 유형의 인스턴스이며, 이러한 인스턴스는 모두 객체가 고유하다는 의미를 가진다. //동일한 state를 갖고 있다 해서, 두 객체가 동일하다고 간주해선 안 된다. === 를 사용해 객체가 동일한 state를 포함한 것이 아니라 실제로 동일한 지 확인해야 한다. //반대로 value type인 인스턴스(구조체)는 동일한 값인 경우 동일한 것으로 간주한다. //ex. 위의 Student 예제에서 두 학생이 동일한 이름이 가지고 있다 해서 같다고 판단하지 않는다. //Speed //구조체는 Stack을 사용하는 반면, 클래스는 이보다 느린 heap을 사용한다. 많은 인스턴스(수백 개 이상)가 있거나, 이러한 인스턴스가 짧은 시간 동안에만 메모리에 존재하는 경우 구조체를 사용하는 것이 좋다. //인스턴스의 lifecycle이 길거나 상대적으로 적은 수의 인스턴스를 생성하는 경우, heap을 사용하는 클래스 인스턴스는 오버헤드(overhead)를 많이 발생시키지 않아야 한다. //Minimalist approach //또 다른 접근방법은 필요한 것만 사용하는 것이다. 데이터가 변경되지 않거나 간단한 데이터 저장소가 필요한 경우 구조체를 사용한다. //데이터를 업데이트해야 하고, 자체 state를 업데이트 하는 논리를 포함하는 경우에는 클래스를 사용한다. //보통 구조체로 시작하는 것이 가장 좋다. 나중에 클래스의 추가 기능이 필요한 경우 구조체를 클래스로 변환하기만 하면 된다. //Structures vs. classes recap //구조체 // • value를 나타내는 데 유용하다. // • 값을 암시적으로 복사한다. // • let으로 선언하면, 완전히 immutable 하다. // • 빠른 메모리 할당(stack) //클래스 // • identity가 있는 object를 나타내는 데 유용하다. // • 객체를 암시적으로 공유한다. // • let으로 선언한 경우에도 내부 멤버는 변경 가능하다. // • 느린 메모리 할당(heap)
40.52549
131
0.703503
ef29abc700c61699a3726675f52e7296cad289a3
350
// // Event.swift // RxSpriteKit // // Created by Maxim Volgin on 27/10/2018. // Copyright (c) RxSwiftCommunity. All rights reserved. // import SpriteKit // MARK: - SKViewDelegate // MARK: - SKSceneDelegate @available(iOS 10.0, *) public typealias EventUpdate = (currentTime: TimeInterval, scene: SKScene) //MARK: - SKPhysicsContactDelegate
18.421053
74
0.714286
463e669e5c6e77779d6f48386540229b774dc7f3
5,353
// // LayerThumbnail.swift // ComponentStudio // // Created by devin_abbott on 10/3/17. // Copyright © 2017 Devin Abbott. All rights reserved. // import Foundation import AppKit private let layerOutlineColor = NSColor.black.withAlphaComponent(0.5) private let layerDirectionColor1 = NSColor.parse(css: "rgba(124,124,124,0.8)")! private let layerDirectionColor2 = NSColor.parse(css: "rgba(124,124,124,0.65)")! private let layerDirectionColor3 = NSColor.parse(css: "rgba(124,124,124,0.5)")! class LayerThumbnail { static var cache: NSCache<NSString, NSImage> { let nsCache = NSCache<NSString, NSImage>() nsCache.countLimit = 100 return nsCache } static func cacheKeyForView(at scale: CGFloat, direction: String, backgroundColor: String? = nil) -> NSString { if let backgroundColor = backgroundColor { return NSString(string: "\(backgroundColor):\(scale):\(direction)") } else { return NSString(string: "View:\(scale):\(direction)") } } static func image(for layer: CSLayer) -> NSImage? { let scale = NSApplication.shared.windows.first?.backingScaleFactor ?? 1 let size = 16 * scale switch layer.type { case .builtIn(.view): let cacheKey = cacheKeyForView(at: scale, direction: layer.flexDirection ?? "column", backgroundColor: layer.backgroundColor) if let cached = cache.object(forKey: cacheKey) { return cached } let image = NSImage(size: NSSize(width: size, height: size), flipped: true, drawingHandler: { rect in NSGraphicsContext.saveGraphicsState() NSBezierPath.defaultLineWidth = scale let borderPath = NSBezierPath(rect: rect.insetBy(dx: 2.5 * scale, dy: 2.5 * scale)) var outlineColor = layerOutlineColor if let backgroundColor = layer.backgroundColor { let color = CSColors.parse(css: backgroundColor).color color.set() outlineColor = color.contrastingLabelColor.withAlphaComponent(0.5) NSBezierPath(rect: rect.insetBy(dx: 2 * scale, dy: 2 * scale)).fill() } outlineColor.setStroke() borderPath.stroke() let rowThickness = 2 * scale let rowLength = 8 * scale let rowStart1 = 4 * scale let rowStart2 = 7 * scale let rowStart3 = 10 * scale if layer.flexDirection == "row" { outlineColor.withAlphaComponent(0.4).setFill() NSBezierPath(rect: NSRect(x: rowStart1, y: rowStart1, width: rowThickness, height: rowLength)).fill() outlineColor.withAlphaComponent(0.3).setFill() NSBezierPath(rect: NSRect(x: rowStart2, y: rowStart1, width: rowThickness, height: rowLength)).fill() outlineColor.withAlphaComponent(0.2).setFill() NSBezierPath(rect: NSRect(x: rowStart3, y: rowStart1, width: rowThickness, height: rowLength)).fill() } else { outlineColor.withAlphaComponent(0.4).setFill() NSBezierPath(rect: NSRect(x: rowStart1, y: rowStart1, width: rowLength, height: rowThickness)).fill() outlineColor.withAlphaComponent(0.3).setFill() NSBezierPath(rect: NSRect(x: rowStart1, y: rowStart2, width: rowLength, height: rowThickness)).fill() outlineColor.withAlphaComponent(0.2).setFill() NSBezierPath(rect: NSRect(x: rowStart1, y: rowStart3, width: rowLength, height: rowThickness)).fill() } NSGraphicsContext.restoreGraphicsState() return true }) cache.setObject(image, forKey: cacheKey) return image case .builtIn(.text): let template: NSImage = #imageLiteral(resourceName: "icon-layer-list-text") if let font = layer.font { let cacheKey = font as NSString // TODO: Can't use font name, since these may change. Or we need to invalidate on refresh if let cached = cache.object(forKey: cacheKey) { return cached } else { let color = CSTypography.getFontBy(id: font).font.color let image = template.tinted(color: color ?? layerOutlineColor) cache.setObject(image, forKey: cacheKey) return image } } return template case .builtIn(.image): if let urlString = layer.image, let url = URL(string: urlString) { let cacheKey = NSString(string: urlString) if let cached = cache.object(forKey: cacheKey) { return cached } else if let image = NSImage(contentsOf: url) { image.size = NSSize(width: 14, height: 14) cache.setObject(image, forKey: cacheKey) return image } } return #imageLiteral(resourceName: "icon-layer-list-image") default: return nil } } }
41.820313
137
0.574631
0e61d2d3b56d435c0ef2a714d5344314388e32a0
13,340
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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 COPYRIGHT HOLDER OR CONTRIBUTORS 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 SystemConfiguration import Foundation public let ReachabilityChangedNotification = "ReachabilityChangedNotification" public class ATReachability: NSObject { public typealias NetworkReachable = (ATReachability) -> () public typealias NetworkUnreachable = (ATReachability) -> () public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } // MARK: - *** Public properties *** public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? public var reachableOnWWAN: Bool public var notificationCenter = NotificationCenter.default public var currentReachabilityStatus: NetworkStatus { if isReachable() { if isReachableViaWiFi() { return .reachableViaWiFi } if isRunningOnDevice { return .reachableViaWWAN } } return .notReachable } public var currentReachabilityString: String { return "\(currentReachabilityStatus)" } // MARK: - *** Initialisation methods *** required public init?(reachabilityRef: SCNetworkReachability?) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } public convenience init?(hostname: String) { let nodename = (hostname as NSString).utf8String let ref = SCNetworkReachabilityCreateWithName(nil, nodename!) self.init(reachabilityRef: ref) } public class func reachabilityForInternetConnection() -> ATReachability? { if #available(iOS 9.0, *) { var zeroAddress = sockaddr_in6() zeroAddress.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size) zeroAddress.sin6_family = sa_family_t(AF_INET6) let ref = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } return ATReachability(reachabilityRef: ref) } else { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) zeroAddress.sin_family = sa_family_t(AF_INET) let ref = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } return ATReachability(reachabilityRef: ref) } } // MARK: - *** Notifier methods *** public func startNotifier() -> Bool { if notifierRunning { return true } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<ATReachability>.passUnretained(self).toOpaque()) SCNetworkReachabilitySetCallback(reachabilityRef!, { (_, flags, info) in let reachability = Unmanaged<ATReachability>.fromOpaque(info!).takeUnretainedValue() DispatchQueue.main.async { reachability.reachabilityChanged(flags: flags) } }, &context) if SCNetworkReachabilitySetDispatchQueue(reachabilityRef!, reachabilitySerialQueue) { notifierRunning = true return true } stopNotifier() return false } public func stopNotifier() { if let reachabilityRef = reachabilityRef { SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) } notifierRunning = false } // MARK: - *** Connection test methods *** public func isReachable() -> Bool { return isReachableWithTest(test: { (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isReachableWithFlags(flags: flags) }) } public func isReachableViaWWAN() -> Bool { if isRunningOnDevice { return isReachableWithTest() { flags -> Bool in // Check we're REACHABLE if self.isReachable(flags: flags) { // Now, check we're on WWAN if self.isOnWWAN(flags: flags) { return true } } return false } } return false } public func isReachableViaWiFi() -> Bool { return isReachableWithTest() { flags -> Bool in // Check we're reachable if self.isReachable(flags: flags) { if self.isRunningOnDevice { // Check we're NOT on WWAN if self.isOnWWAN(flags: flags) { return false } } return true } return false } } // MARK: - *** Private methods *** private var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false #else return true #endif }() private var notifierRunning = false private var reachabilityRef: SCNetworkReachability? private let reachabilitySerialQueue = DispatchQueue.init(label: "uk.co.ashleymills.reachability") private func reachabilityChanged(flags: SCNetworkReachabilityFlags) { if isReachableWithFlags(flags: flags) { if let block = whenReachable { block(self) } } else { if let block = whenUnreachable { block(self) } } notificationCenter.post(name: NSNotification.Name(rawValue: ReachabilityChangedNotification), object:self) } private func isReachableWithFlags(flags: SCNetworkReachabilityFlags) -> Bool { let reachable = isReachable(flags: flags) if !reachable { return false } if isConnectionRequiredOrTransient(flags: flags) { return false } if isRunningOnDevice { if isOnWWAN(flags: flags) && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } private func isReachableWithTest(test: (SCNetworkReachabilityFlags) -> (Bool)) -> Bool { if let reachabilityRef = reachabilityRef { var flags = SCNetworkReachabilityFlags(rawValue: 0) let gotFlags = withUnsafeMutablePointer(to: &flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return test(flags) } } return false } // WWAN may be available, but not active until a connection has been established. // WiFi may require a connection for VPN on Demand. private func isConnectionRequired() -> Bool { return connectionRequired() } private func connectionRequired() -> Bool { return isReachableWithTest(test: { (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isConnectionRequired(flags: flags) }) } // Dynamic, on demand connection? private func isConnectionOnDemand() -> Bool { return isReachableWithTest(test: { (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isConnectionRequired(flags: flags) && self.isConnectionOnTrafficOrDemand(flags: flags) }) } // Is user intervention required? private func isInterventionRequired() -> Bool { return isReachableWithTest(test: { (flags: SCNetworkReachabilityFlags) -> (Bool) in return self.isConnectionRequired(flags: flags) && self.isInterventionRequired(flags: flags) }) } private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool { #if os(iOS) return flags.contains(.isWWAN) #else return false #endif } private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.reachable) } private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.connectionRequired) } private func isInterventionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.interventionRequired) } private func isConnectionOnTraffic(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.connectionOnTraffic) } private func isConnectionOnDemand(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.connectionOnDemand) } func isConnectionOnTrafficOrDemand(flags: SCNetworkReachabilityFlags) -> Bool { return !flags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } private func isTransientConnection(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.transientConnection) } private func isLocalAddress(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.isLocalAddress) } private func isDirect(flags: SCNetworkReachabilityFlags) -> Bool { return flags.contains(.isDirect) } private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool { let testcase:SCNetworkReachabilityFlags = [.connectionRequired, .transientConnection] return flags.intersection(testcase) == testcase } private var reachabilityFlags: SCNetworkReachabilityFlags { if let reachabilityRef = reachabilityRef { var flags = SCNetworkReachabilityFlags(rawValue: 0) let gotFlags = withUnsafeMutablePointer(to: &flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return flags } } return [] } override public var description: String { var W: String if isRunningOnDevice { W = isOnWWAN(flags: reachabilityFlags) ? "W" : "-" } else { W = "X" } let R = isReachable(flags: reachabilityFlags) ? "R" : "-" let c = isConnectionRequired(flags: reachabilityFlags) ? "c" : "-" let t = isTransientConnection(flags: reachabilityFlags) ? "t" : "-" let i = isInterventionRequired(flags: reachabilityFlags) ? "i" : "-" let C = isConnectionOnTraffic(flags: reachabilityFlags) ? "C" : "-" let D = isConnectionOnDemand(flags: reachabilityFlags) ? "D" : "-" let l = isLocalAddress(flags: reachabilityFlags) ? "l" : "-" let d = isDirect(flags: reachabilityFlags) ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } deinit { stopNotifier() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } }
35.668449
128
0.59985
62df267c51a81be3bddb2254fb57c90672d27cd2
3,443
// // Copyright (c) 2018 University of Helsinki, Aalto University // // 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 os.log /// Convenience class to perform MIDAS RESTful fetches class MidasSession { /// Address of midas server static let midasAddress: String = "127.0.0.1" /// Port of midas server static let midasPort: String = "8085" /// Tests midas by querying the test url. /// Callbacks the given function with true if the test succeeded. static func test(callback: @escaping (Bool) -> Void) { let urlSession = URLSession(configuration: .default) let testURL = URL(string: "http://\(midasAddress):\(midasPort)/test")! let urlRequest = URLRequest(url: testURL, timeoutInterval: 5) urlSession.dataTask(with: urlRequest) { data, response, error in if error == nil { callback(true) } else { if #available(OSX 10.12, *) { let errorDesc = error?.localizedDescription ?? "<nil>" os_log("Failed to connect to Midas: %@", type: .fault, errorDesc) } callback(false) } }.resume() } /// Fetches a chunk of data from Midas. Suffix specifies the exact path /// (to get exactly the sensor / channel we want). /// Calls the given callback with the returned JSON, if the operation /// succeeded, nil otherwise. static func fetch(suffix: String, callback: @escaping (JSON?, Error?) -> Void) { let urlSession = URLSession(configuration: .ephemeral) let baseAddress = "http://\(midasAddress):\(midasPort)/" let fullAddress = (baseAddress + suffix).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let fullURL = URL(string: fullAddress)! let urlRequest = URLRequest(url: fullURL, timeoutInterval: 2) urlSession.dataTask(with: urlRequest) { data, response, error in if let data = data, error == nil { callback(try? JSON(data: data), nil) } else { if #available(OSX 10.12, *) { os_log("Failed to fetch Midas data for %@", type: .fault, fullAddress) } callback(nil, error) } }.resume() } }
40.988095
112
0.634331
edb1fb3ed24eb454fd13026115fe2b89d6a0ca82
8,694
// // SwiftLocalNotification.swift // SwiftLocalNotification // // Created by Salar Soleimani on 2020-04-01. // Copyright © 2020 SaSApps.ca All rights reserved. // import UserNotifications import CoreLocation ///Sas Local Notification @available(iOS 10.0, *) public class SwiftLocalNotificationModel: NSObject { ///Contains the internal instance of the notification request internal var localNotificationRequest: UNNotificationRequest? ///Holds the repeat interval of the notification with Enum Type Repeats var repeatInterval: RepeatingInterval = .none ///Holds the body of the message of the notification fileprivate(set) public var body: String? ///Holds the title of the message of the notification fileprivate(set) public var title: String? ///Holds the subtitle of the message of the notification fileprivate(set) public var subtitle: String? ///Holds name of the music file of the notification fileprivate(set) public var soundName: String? ///Holds the date that the notification will be first fired fileprivate(set) public var fireDate: Date? ///Know if a notification repeats from this value fileprivate(set) public var repeats: Bool = false ///Hold the identifier of the notification to keep track of it fileprivate(set) public var identifier: String ///Number to display on the application icon. fileprivate(set) public var badge: Int? ///Hold the attachments for the notifications public var attachments: [UNNotificationAttachment]? ///Hold the category of the notification if you want to set one public var category: String? ///If it is a region based notification then you can access the notification var region: CLRegion? /// The status of the notification. internal(set) public var isScheduled: Bool = false /// A dictionary that holds additional information. private(set) public var userInfo: [AnyHashable : Any]! /// A key that holds the identifier of the notification which; stored in the `userInfo` property. public static let identifierKey: String = "SwiftLocalNotificationIdentifierKey" /// A key that holds the date of the notification; stored in the `userInfo` property. public static let dateKey: String = "SwiftLocalNotificationDateKey" /// A key that holds the repeating of the notification; stored in the `userInfo` property. public static let repeatingKey: String = "SwiftLocalNotificationRepeatingKey" /// A key that holds the repeating of the notification; stored in the `userInfo` property. public static let soundNameKey: String = "SwiftLocalNotificationSoundNameKey" enum CodingKeys: String, CodingKey { case localNotificationRequest case repeatInterval case body case title case subtitle case soundName case fireDate case repeats case identifier case region case attachments case badge case launchImageName case category case userInfo case isScheduled } public init(title: String, body: String, subtitle: String? = "", date: Date, repeating: RepeatingInterval, identifier: String = UUID().uuidString, soundName: String? = nil, badge: Int? = 1) { self.body = title self.title = body self.subtitle = subtitle self.fireDate = date self.repeatInterval = repeating self.identifier = identifier == "" ? UUID().uuidString : identifier self.soundName = soundName self.badge = badge self.repeats = repeating == .none ? false : true self.userInfo = [ SwiftLocalNotificationModel.identifierKey : identifier, SwiftLocalNotificationModel.dateKey : date, SwiftLocalNotificationModel.repeatingKey: repeating.rawValue, SwiftLocalNotificationModel.soundNameKey: soundName ?? "" ] } /// Region based notification /// Default notifyOnExit and notifyOnEntry is public init(identifier: String = UUID().uuidString, title: String, body: String, subtitle: String = "", region: CLRegion?, notifyOnExit: Bool = true, notifyOnEntry: Bool = true, soundName: String? = nil, badge: Int = 1, repeats: Bool = false) { self.body = body self.title = title self.subtitle = subtitle self.identifier = identifier == "" ? UUID().uuidString : identifier self.region = region self.soundName = soundName self.repeats = repeats region?.notifyOnExit = notifyOnExit region?.notifyOnEntry = notifyOnEntry self.userInfo = [ SwiftLocalNotificationModel.identifierKey : identifier, SwiftLocalNotificationModel.dateKey : Date(), SwiftLocalNotificationModel.soundNameKey: soundName ?? "" ] } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let repeatString = try container.decode(String.self, forKey: .repeatInterval) self.repeatInterval = RepeatingInterval(rawValue: repeatString)! self.title = try container.decodeIfPresent(String.self, forKey: .title) self.body = try container.decodeIfPresent(String.self, forKey: .body) self.subtitle = try container.decodeIfPresent(String.self, forKey: .subtitle) self.soundName = try container.decode(String.self, forKey: .soundName) self.fireDate = try container.decodeIfPresent(Date.self, forKey: .fireDate) self.repeats = try container.decode(Bool.self, forKey: .repeats) self.identifier = try container.decode(String.self, forKey: .identifier) self.badge = try container.decodeIfPresent(Int.self, forKey: .badge) self.category = try container.decodeIfPresent(String.self, forKey: .category) self.isScheduled = try container.decode(Bool.self, forKey: .isScheduled) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(repeatInterval.rawValue, forKey: CodingKeys.repeatInterval) try container.encode(title, forKey: .title) try container.encode(body, forKey: .body) try container.encode(subtitle, forKey: .subtitle) try container.encode(soundName, forKey: .soundName) try container.encode(fireDate, forKey: .fireDate) try container.encode(repeats, forKey: .repeats) try container.encode(identifier, forKey: .identifier) try container.encode(badge, forKey: .badge) try container.encode(category, forKey: .category) try container.encode(isScheduled, forKey: .isScheduled) } /// Adds a value to the specified key in the `userInfo` property. Note that the value is not added if the key is equal to the `identifierKey` or `dateKey`. /// /// - Parameters: /// - value: The value to set. /// - key: The key to set the value of. public func setUserInfo(value: Any, forKey key: AnyHashable) { if let keyString = key as? String { if (keyString == SwiftLocalNotificationModel.identifierKey || keyString == SwiftLocalNotificationModel.dateKey) { return } } self.userInfo[key] = value } public func setAllUserInfo(_ with: [AnyHashable : Any]) { self.userInfo = with } /// Removes the value of the specified key. Note that the value is not removed if the key is equal to the `identifierKey` or `dateKey`. /// /// - Parameter key: The key to remove the value of. public func removeUserInfoValue(forKey key: AnyHashable) { if let keyString = key as? String { if (keyString == SwiftLocalNotificationModel.identifierKey || keyString == SwiftLocalNotificationModel.dateKey) { return } } self.userInfo.removeValue(forKey: key) } public func updateFireDate(_ fireDate: Date) { self.fireDate = fireDate } public override var description: String { var result = "" result += "SwiftLocalNotification: \(String(describing: self.identifier))\n" result += "\tTitle: \(title ?? "no title")\n" result += "\tBody: \(self.body ?? "nobody")\n" result += "\tFires at: \(String(describing: self.fireDate))\n" result += "\tUser info: \(String(describing: self.userInfo))\n" if let badge = self.badge { result += "\tBadge: \(badge)\n" } result += "\tSound name: \(self.soundName ?? "defualt soundName")\n" result += "\tRepeats every: \(self.repeatInterval.rawValue)\n" result += "\tScheduled: \(self.isScheduled)" return result } } extension SwiftLocalNotificationModel { public static func == (lhs: SwiftLocalNotificationModel, rhs: SwiftLocalNotificationModel) -> Bool { return lhs.identifier == rhs.identifier } public static func <(lhs: SwiftLocalNotificationModel, rhs: SwiftLocalNotificationModel) -> Bool { return lhs.fireDate?.compare(rhs.fireDate ?? Date()) == ComparisonResult.orderedAscending } }
39.880734
246
0.715206
874af5c6f794d17255e1d3160872c6c66eaf23f0
227
import Foundation import XCTest @testable import TicTacToe final class SquareStatusTests: XCTestCase { func test_init() { let square = Square(status: .nobody) XCTAssertEqual(square.status, .nobody) } }
20.636364
46
0.704846
895fc6ab99eb32451b3f1512e24bd4a162dcf6fc
254
import Foundation public enum TestResultsRequestFilterOptionV3: FilterOption { case creator(_ value: String) case participant(_ value: String) } public class TestResultsRequestFiltersV3: RequestFilters<TestResultsRequestFilterOptionV3> {}
25.4
93
0.80315
dee38ba4643e9208f71716e29ffa7e831c43887e
3,658
// // ViewController.swift // RxSwiftExample // // Created by Lukasz Mroz on 08.02.2016. // Copyright © 2016 Droids on Roids. All rights reserved. // // // // Here we have basic example of RxSwift. UI is pretty simple, take a look at Main.storyboard. // It is basically UISearchBar + UITableView. The main idea of this app is that every time // someone types something in the search bar, we want to get the cities from API that starts // with the letters someone typed. The main problems here are: // a) What if the text(here query) in search bar is empty? // b) What if someone will spam API by continuesly changing letters? // // We want to be safe with our app so we will filter the empty queries to protect against a). // About the b), we will use RxSwift's debounce() & distinctUntilChanged(). The first one // waits given time for a change. If the change occured before the time given, timer will reset // and Rx will wait again for a change. If change didn't happen in specified time, the next value // will go through. Basically it means that we will wait X time before sending API request, if someone // changed his mind (or just spam), we will wait patiently. If not, we will just do the API request. // Second function distinctUntilChanged() will protect us against searching the same phrase again. // So if someone type A, then will type AB and go back to A, we will not fire another request (it is // just in our case that we want that behavior, if you have dynamically changed fields, you better // leave this function). // import UIKit import RxCocoa import RxSwift class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! var shownCities = [String]() // Data source for UITableView let allCities = ["New York", "London", "Oslo", "Warsaw", "Berlin", "Praga"] // Our mocked API data source let disposeBag = DisposeBag() // Bag of disposables to release them when view is being deallocated override func viewDidLoad() { super.viewDidLoad() setup() } func setup() { tableView.dataSource = self searchBar .rx.text // Observable property thanks to RxCocoa .orEmpty // Make it non-optional .debounce(0.5, scheduler: MainScheduler.instance) // Wait 0.5 for changes. .distinctUntilChanged() // If they didn't occur, check if the new value is the same as old. .filter { !$0.isEmpty } // If the new value is really new, filter for non-empty query. .subscribe(onNext: { [unowned self] query in // Here we subscribe to every new value, that is not empty (thanks to filter above). self.shownCities = self.allCities.filter { $0.hasPrefix(query) } // We now do our "API Request" to find cities. self.tableView.reloadData() // And reload table view data. }) .addDisposableTo(disposeBag) // Don't forget to add this to disposeBag. We want to dispose it on deinit. } } // MARK: - UITableViewDataSource /// Here we have standard data source extension for ViewController extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shownCities.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cityPrototypeCell", for: indexPath) cell.textLabel?.text = shownCities[indexPath.row] return cell } }
46.897436
141
0.692182
8935a4ad5954a12cf9fa44fedcdb5156c1245f2c
1,793
// // ServerManager.swift // ShopFinder // // Created by Marcos Pianelli on 15/07/15. // Copyright (c) 2015 Barkala Studios. All rights reserved. // import Foundation import Alamofire //import ReachabilitySwift class ServerManager : NSObject { class func retrieveShops(completionHandler: (Result<AnyObject>) -> Void) -> Void { Alamofire.request(.GET, API.shops).responseJSON { (request, response, result) -> Void in if result.isSuccess { NSUserDefaults.standardUserDefaults().setObject(result.value!, forKey: DefaultKeys.ShopsJSON) } completionHandler(result) } // if Reachability.reachabilityForInternetConnection().isReachable() { // Alamofire.request(.GET, API.shops ) // .responseJSON { (_, _, obj, error) in // NSUserDefaults.standardUserDefaults().setObject(obj, forKey: DefaultKeys.ShopsJSON) // completionHandler(obj,error) // } // }else{ // let obj: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(DefaultKeys.ShopsJSON) // if obj != nil { // completionHandler(obj,nil) // } // } } class func fetchSettings(completionHandler: (Result<AnyObject>) -> Void) -> Void { Alamofire.request(.GET, API.settings ).responseJSON { (request, response, result) -> Void in if result.isSuccess { NSUserDefaults.standardUserDefaults().setObject(result.value!, forKey: DefaultKeys.ShopsJSON) } completionHandler(result) } } }
28.015625
109
0.560513
edb614d5e5a7d0a70b8df16a86215efda2c8b8ba
277
import Foundation @testable import TuistCache extension LabCacheResponse { public static func test(url: URL = URL.test(), expiresAt: TimeInterval = 0) -> LabCacheResponse { LabCacheResponse( url: url, expiresAt: expiresAt ) } }
23.083333
101
0.635379
20daf20e9531ba99a8bcb996888a8a486fedbec2
919
// // Receive+MoreInfo.swift // falcon // // Created by Manu Herrera on 23/04/2020. // Copyright © 2020 muun. All rights reserved. // import Foundation extension BottomDrawerInfo { static func onChainAddress(_ address: String) -> MoreInfo { return MoreInfo( title: L10n.Receive.s1, description: address.attributedForDescription(), type: .onChainAddress, action: nil ) } static func lightningInvoice(_ invoice: String) -> MoreInfo { return MoreInfo( title: L10n.Receive.s2, description: invoice.attributedForDescription(), type: .lightningInvoice, action: nil ) } static let segwitLegacyInfo = MoreInfo( title: L10n.Receive.s3, description: L10n.Receive.s4.attributedForDescription(), type: .segwitLegacyInfo, action: nil ) }
23.564103
65
0.606094
e4723b70d779df02370f19742f76671a85249dc9
514
// // UITabBarExtension.swift // LoansDebts // // Created by Francisco Depascuali on 5/17/16. // Copyright © 2016 DepaStudios. All rights reserved. // import UIKit public extension UITabBar { public func indexForItem(item: UITabBarItem) -> Int? { for (index, _item) in items!.enumerate() { if _item == item { return index } } return nil } public func selectItemAt(index: Int) { selectedItem = items![index] } }
20.56
58
0.57393
1cfee4c812be7cb9822053a91cef6aac56b2d3c3
110
import Foundation class ff: OneUptoTwoOther, PluralizationRule { let locale: LocaleIdentifier = "ff" }
13.75
46
0.745455
db6d36e35d40c78d6f3b120f08420d85315047f4
5,301
// // ListViewModel.swift // DCM_iOS // // Created by 강민석 on 2020/09/09. // Copyright © 2020 MinseokKang. All rights reserved. // import RxSwift import RxCocoa import FirebaseFirestore class ListViewModel: BaseViewModel { struct Input { let selection: Driver<MyListSectionItem> let segmented: Driver<Int> let submitButton: Driver<Void> } struct Output { let items: BehaviorRelay<[MyListSection]> } let elements = BehaviorRelay<[MyListSection]>(value: []) func transform(input: Input) -> Output { input.selection .drive(onNext: { item in switch item { case .rentItem(let model): self.steps.accept(DCMStep.productIsRequired(product: model)) case .submitItem(var model): model.isSubmit = true self.steps.accept(DCMStep.productIsRequired(product: model)) } }).disposed(by: disposeBag) input.segmented .drive(onNext: { [weak self] index in print(index) self?.productRequest(index: index) }).disposed(by: disposeBag) input.submitButton .drive(onNext: { [weak self] in self?.steps.accept(DCMStep.submitIsRequired) }).disposed(by: disposeBag) return Output(items: elements) } func productRequest(index: Int) { let db = Firestore.firestore() self.loading.accept(true) if index == 0 { db.collection("product") .whereField("rentUser", isEqualTo: KeychainManager.getToken()) .addSnapshotListener { (querySnapShot, error) in guard let documents = querySnapShot?.documents else { print("No documents") return } let product = documents.compactMap { (queryDocumentSnapshot) -> ProductModel? in let data = queryDocumentSnapshot.data() let name = data["name"] as? String ?? "" let imageUrl = data["imageUrl"] as? String ?? "" let content = data["content"] as? String ?? "" let rentAble = data["rentAble"] as? Int ?? 0 let rentUser = data["rentUser"] as? String ?? "" let createAt = data["createAt"] as? String ?? "" return ProductModel(name: name, imageUrl: imageUrl, content: content, rentAble: rentAble, rentUser: rentUser, createAt: createAt) } self.loading.accept(false) var items: [MyListSectionItem] = [] product.forEach { (model) in items.append(MyListSectionItem.rentItem(model: model)) } self.elements.accept([MyListSection.list(title: "", items: items)]) } } else { db.collection("submit") .whereField("submitUser", isEqualTo: KeychainManager.getToken()) .whereField("submitAble", isEqualTo: 0) .addSnapshotListener { (querySnapShot, error) in guard let documents = querySnapShot?.documents else { print("No documents") return } let product = documents.compactMap { (queryDocumentSnapshot) -> ProductModel? in let data = queryDocumentSnapshot.data() let name = data["name"] as? String ?? "" let imageUrl = data["imageUrl"] as? String ?? "" let content = data["content"] as? String ?? "" let submitAble = data["submitAble"] as? Int ?? 0 let submitUser = data["submitUser"] as? String ?? "" let createAt = data["createAt"] as? String ?? "" return ProductModel(name: name, imageUrl: imageUrl, content: content, rentAble: submitAble, rentUser: submitUser, createAt: createAt) } self.loading.accept(false) var items: [MyListSectionItem] = [] product.forEach { (model) in items.append(MyListSectionItem.submitItem(model: model)) } self.elements.accept([MyListSection.list(title: "", items: items)]) } } } }
40.776923
100
0.44652
dd223710ce88278728a228e0f5f113f4020b13fe
240
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing init { for in { func b { for var d { class C { struct S { class case ,
17.142857
87
0.725
fb9eedcf81aad655ae6832abb6b62831eabada13
949
//___FILEHEADER___ import UIKit extension NSLayoutConstraint { /** Returns same constraint with updated multiplier. Do not use for UITableViewCell / CollectionCell */ func changeMultiplier(_ multiplier: CGFloat) -> NSLayoutConstraint { guard let item = firstItem else { let message: String = "Unable to change constraint multiplier" ErrorLoggerService.logWithTrace(message) return self } let newConstraint = NSLayoutConstraint( item: item, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier, constant: constant) newConstraint.priority = priority NSLayoutConstraint.deactivate([self]) NSLayoutConstraint.activate([newConstraint]) return newConstraint } }
28.757576
74
0.622761
6aa7692b69b5825a2067f7415fb6842b640d632a
10,585
/* SQLiteEncoder.swift Copyright (c) 2020, Valentin Debon This file is part of SQLiteCodable subject the BSD 3-Clause License, see LICENSE */ import CSQLite fileprivate extension CodingKey { var sqliteParameterValue : String { ":" + self.stringValue } } fileprivate struct SQLiteKeyedEncodingContainer<Key> : KeyedEncodingContainerProtocol where Key : CodingKey { let codingPath: [CodingKey] = [] let prepared: OpaquePointer private func check(forKey key: Key, binding: @escaping (OpaquePointer, Int32) -> Int32) throws { let parameterIndex = key.sqliteParameterValue.withCString { sqlite3_bind_parameter_index(self.prepared, $0) } guard parameterIndex > 0 else { let encodingContext = EncodingError.Context(codingPath: self.codingPath, debugDescription: "Invalid key \(key) for query") throw EncodingError.invalidValue(key, encodingContext) } let errorCode = binding(self.prepared, parameterIndex) if errorCode != SQLITE_OK { throw SQLiteError(rawValue: errorCode)! } } mutating func encodeNil(forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_null($0, $1) } } mutating func encode(_ value: Bool, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value ? 1 : 0)) } } mutating func encode(_ value: String, forKey key: Key) throws { try value.withCString { cString in try self.check(forKey: key) { sqlite3_bind_text($0, $1, cString, Int32(value.utf8.count), sqlite_transient) } } } mutating func encode(_ value: Double, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_double($0, $1, value) } } mutating func encode(_ value: Float, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_double($0, $1, Double(value)) } } mutating func encode(_ value: Int, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: Int8, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: Int16, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: Int32, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: Int64, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt8, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt16, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt32, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt64, forKey key: Key) throws { try self.check(forKey: key) { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable { switch value { case let losslessStringValue as LosslessStringConvertible: try self.encode(losslessStringValue.description, forKey: key) default: let encodingContext = EncodingError.Context(codingPath: self.codingPath, debugDescription: "Unsupported encoding for key \(key)") throw EncodingError.invalidValue(key, encodingContext) } } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey { fatalError() } mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { fatalError() } mutating func superEncoder() -> Encoder { fatalError() } mutating func superEncoder(forKey key: Key) -> Encoder { fatalError() } } fileprivate struct SQLiteUnkeyedEncodingContainer : UnkeyedEncodingContainer, SingleValueEncodingContainer { private(set) var count: Int = 0 let codingPath: [CodingKey] = [] let prepared: OpaquePointer private mutating func check(binding: @escaping (OpaquePointer, Int32) -> Int32) throws { let parameterIndex = Int32(self.count + 1) let errorCode = binding(self.prepared, parameterIndex) if errorCode != SQLITE_OK { throw SQLiteError(rawValue: errorCode)! } self.count += 1 } mutating func encodeNil() throws { try self.check { sqlite3_bind_null($0, $1) } } mutating func encode(_ value: Bool) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value ? 1 : 0)) } } mutating func encode(_ value: String) throws { try value.withCString { cString in try self.check { sqlite3_bind_text($0, $1, cString, Int32(value.utf8.count), sqlite_transient) } } } mutating func encode(_ value: Double) throws { try self.check { sqlite3_bind_double($0, $1, value) } } mutating func encode(_ value: Float) throws { try self.check { sqlite3_bind_double($0, $1, Double(value)) } } mutating func encode(_ value: Int) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: Int8) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: Int16) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: Int32) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: Int64) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt8) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt16) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt32) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode(_ value: UInt64) throws { try self.check { sqlite3_bind_int64($0, $1, sqlite3_int64(value)) } } mutating func encode<T>(_ value: T) throws where T : Encodable { switch value { case let losslessStringValue as LosslessStringConvertible: try self.encode(losslessStringValue.description) default: let encodingContext = EncodingError.Context(codingPath: self.codingPath, debugDescription: "Unsupported encoding") throw EncodingError.invalidValue(value, encodingContext) } } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey { fatalError() } mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { fatalError() } mutating func superEncoder() -> Encoder { fatalError() } } fileprivate struct SQLiteSingleValueEncodingContainer : SingleValueEncodingContainer { let codingPath: [CodingKey] = [] let prepared: OpaquePointer private func check(binding errorCode: Int32) throws { if errorCode != SQLITE_OK { throw SQLiteError(rawValue: errorCode)! } } mutating func encodeNil() throws { try self.check(binding: sqlite3_bind_null(self.prepared, 1)) } mutating func encode(_ value: Bool) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value ? 1 : 0))) } mutating func encode(_ value: String) throws { try value.withCString { cString in try self.check(binding: sqlite3_bind_text(self.prepared, 1, cString, Int32(value.utf8.count), sqlite_transient)) } } mutating func encode(_ value: Double) throws { try self.check(binding: sqlite3_bind_double(self.prepared, 1, value)) } mutating func encode(_ value: Float) throws { try self.check(binding: sqlite3_bind_double(self.prepared, 1, Double(value))) } mutating func encode(_ value: Int) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode(_ value: Int8) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode(_ value: Int16) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode(_ value: Int32) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode(_ value: Int64) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode(_ value: UInt) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode(_ value: UInt8) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode(_ value: UInt16) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode(_ value: UInt32) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode(_ value: UInt64) throws { try self.check(binding: sqlite3_bind_int64(self.prepared, 1, sqlite3_int64(value))) } mutating func encode<T>(_ value: T) throws where T : Encodable { switch value { case let losslessStringValue as LosslessStringConvertible: try self.encode(losslessStringValue.description) default: let encodingContext = EncodingError.Context(codingPath: self.codingPath, debugDescription: "Unsupported encoding") throw EncodingError.invalidValue(value, encodingContext) } } } /// Encoder for `SQLiteStatement`. struct SQLiteEncoder : Encoder { let codingPath: [CodingKey] = [] let userInfo: [CodingUserInfoKey : Any] = [:] let prepared: OpaquePointer func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey { KeyedEncodingContainer(SQLiteKeyedEncodingContainer<Key>(prepared: self.prepared)) } func unkeyedContainer() -> UnkeyedEncodingContainer { SQLiteUnkeyedEncodingContainer(prepared: self.prepared) } func singleValueContainer() -> SingleValueEncodingContainer { SQLiteSingleValueEncodingContainer(prepared: self.prepared) } }
32.173252
158
0.734908
296cc227106e53e7f55e96866a40db8f14c20166
2,600
// // UILabel+Extension.swift // Swift-Useful-Files // // Created by Husar Maksym on 2/16/17. // Copyright © 2017 Husar Maksym. All rights reserved. // import UIKit extension UILabel { func setText(_ text: String, lineHeight: CGFloat, isScalable: Bool = Utils.isTextSizeScaleEnabledDefaultValue) { self.text = text let newLineHeight = isScalable ? lineHeight * Utils.deviceScaleMultiplier : lineHeight setLineHeight(newLineHeight) } func setText(_ text: String, letterSpacing: CGFloat) { self.text = text setLetterSpacing(letterSpacing) } private func setLetterSpacing(_ letterSpacing: CGFloat) { if let attributedString = self.attributedText { let newAttributedString = NSMutableAttributedString(attributedString: attributedString) newAttributedString.addAttribute(NSAttributedStringKey.kern, value: letterSpacing, range: NSRange(location: 0, length: attributedString.string.count)) self.attributedText = newAttributedString } else if let text = self.text { let attributedString = NSMutableAttributedString(string: text) attributedString.addAttribute(NSAttributedStringKey.kern, value: letterSpacing, range: NSRange(location: 0, length: text.count)) self.attributedText = attributedString } } private func setLineHeight(_ lineHeight: CGFloat) { let style = NSMutableParagraphStyle() style.lineHeightMultiple = lineHeight / self.font.lineHeight style.lineBreakMode = .byTruncatingTail style.alignment = self.textAlignment if let attributedString = self.attributedText { let newAttributedString = NSMutableAttributedString(attributedString: attributedString) newAttributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: attributedString.string.count)) self.attributedText = newAttributedString } else if let text = self.text { let attributeString = NSMutableAttributedString(string: text) attributeString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: text.count)) self.attributedText = attributeString } } }
40.625
162
0.635769
d7815d3fd9bff51ef97ae79ab2f26bd797071893
6,477
// // SignInViewController.swift // PictionView // // Created by jhseo on 17/06/2019. // Copyright © 2019 Piction Network. All rights reserved. // import UIKit import RxSwift import RxCocoa import ViewModelBindable import SafariServices // MARK: - UIViewController final class SignInViewController: UIViewController { var disposeBag = DisposeBag() @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var closeButton: UIBarButtonItem! @IBOutlet weak var findPasswordButton: UIButton! @IBOutlet weak var loginIdInputView: DynamicInputView! { didSet { loginIdInputView.delegate = self } } @IBOutlet weak var passwordInputView: DynamicInputView! { didSet { passwordInputView.delegate = self } } // password textfield에서 return key 누르면 login 되도록 함 private let keyboardReturnSignIn = PublishSubject<Void>() deinit { // 메모리 해제되는지 확인 print("[deinit] \(String(describing: type(of: self)))") } } // MARK: - ViewModelBindable extension SignInViewController: ViewModelBindable { typealias ViewModel = SignInViewModel func bindViewModel(viewModel: ViewModel) { let input = SignInViewModel.Input( viewWillAppear: rx.viewWillAppear.asDriver(), // 화면이 보여지기 전에 viewWillDisappear: rx.viewWillDisappear.asDriver(), // 화면이 사라지기 전에 signInBtnDidTap: Driver.merge(signInButton.rx.tap.asDriver(), keyboardReturnSignIn.asDriver(onErrorDriveWith: .empty())), // 로그인 버튼이나 키보드의 return 버튼을 눌렀을 때 signUpBtnDidTap: signUpButton.rx.tap.asDriver(), // 회원가입 버튼을 눌렀을 때 loginIdTextFieldDidInput: loginIdInputView.inputTextField.rx.text.orEmpty.asDriver(), // id textfield를 입력했을 때 passwordTextFieldDidInput: passwordInputView.inputTextField.rx.text.orEmpty.asDriver(), // password textfield를 입력했을 때 findPasswordBtnDidTap: findPasswordButton.rx.tap.asDriver(), // 비밀번호 찾기 버튼을 눌렀을 때 closeBtnDidTap: closeButton.rx.tap.asDriver() // 닫기 버튼을 눌렀을 때 ) let output = viewModel.build(input: input) // 화면이 보여지기 전에 NavigationBar 설정 output .viewWillAppear .drive(onNext: { [weak self] in self?.navigationController?.configureNavigationBar(transparent: false, shadow: true) }) .disposed(by: disposeBag) // 화면이 사라지기전에 viewModel에서 keyboard를 숨기고 disposed하기 위함 output .viewWillDisappear .drive() .disposed(by: disposeBag) // 이미 로그인 되어있는데 딥링크 등을 통해 진입할 경우 화면을 닫고 토스트 출력 output .userInfo .filter { $0.loginId != "" } .drive(onNext: { [weak self] _ in self?.dismiss(animated: true) { Toast.showToast(LocalizationKey.msg_already_sign_in.localized()) } }) .disposed(by: disposeBag) // 회원가입 화면으로 push output .openSignUpViewController .map { .signUp } .drive(onNext: { [weak self] in self?.openView(type: $0, openType: .push) }) .disposed(by: disposeBag) // 비밀번호 찾기는 safari로 open output .openFindPassword .drive(onNext: { [weak self] in let stagingPath = AppInfo.isStaging ? "staging." : "" self?.openSafariViewController(url: "https://\(stagingPath)piction.network/forgot_password") }) .disposed(by: disposeBag) // keyboard가 나타나거나 사라질때 scrollView의 크기 조정 output .keyboardWillChangeFrame .drive(onNext: { [weak self] changedFrameInfo in guard let `self` = self, let endFrame = changedFrameInfo.endFrame else { return } if endFrame.origin.y >= SCREEN_H { self.scrollView.contentInset = .zero } else { self.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: endFrame.size.height, right: 0) } UIView.animate(withDuration: changedFrameInfo.duration, animations: { self.view.layoutIfNeeded() }) }) .disposed(by: disposeBag) // 로딩 뷰 output .activityIndicator .loadingActivity() .disposed(by: disposeBag) // 로그인 후 pincode 등록이 안되있으면 화면을 닫은 후 pincode 등록 화면 출력 output .dismissViewController .drive(onNext: { [weak self] pincodeEmpty in self?.dismiss(animated: true) { if pincodeEmpty { self?.openView(type: .registerPincode, openType: .present) } } }) .disposed(by: disposeBag) // 에러 메시지를 각 field 밑에 출력 output .errorMsg .drive(onNext: { [weak self] error in switch error.field ?? "" { case "loginId": self?.loginIdInputView.showError(error.message ?? "") case "password": self?.passwordInputView.showError(error.message ?? "") default: break } }) .disposed(by: disposeBag) // 토스트 메시지 출력 (키보드에 가리기 때문에 키보드 숨긴 후 출력) output .toastMessage .do(onNext: { [weak self] message in self?.view.endEditing(true) }) .showToast() .disposed(by: disposeBag) } } // MARK: - IBAction extension SignInViewController { // 화면 tap 시 키보드 숨기기 @IBAction func tapGesture(_ sender: Any) { view.endEditing(true) } } // MARK: - DynamicInputViewDelegate extension SignInViewController: DynamicInputViewDelegate { // 키보드의 return 키 눌렀을 때 다음 textField로 이동 func returnKeyAction(_ textField: UITextField) { if textField === loginIdInputView.inputTextField { passwordInputView.inputTextField.becomeFirstResponder() } else { passwordInputView.inputTextField.resignFirstResponder() // 마지막 textField는 편하게 바로 로그인 할 수 있도록 함 keyboardReturnSignIn.onNext(()) } } }
33.734375
167
0.575884
5b0fa2ec0a5c436de5306d43c362282f1e2252f2
2,284
// // SearchedFeedLocationCell.swift // Yep // // Created by NIX on 16/4/19. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit import MapKit import YepKit final class SearchedFeedLocationCell: SearchedFeedBasicCell { override class func heightOfFeed(feed: DiscoveredFeed) -> CGFloat { let height = super.heightOfFeed(feed) + (10 + 20) return ceil(height) } var tapLocationAction: ((locationName: String, locationCoordinate: CLLocationCoordinate2D) -> Void)? lazy var locationContainerView: IconTitleContainerView = { let view = IconTitleContainerView() view.frame = CGRect(x: 0, y: 0, width: 200, height: 200) return view }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(locationContainerView) locationContainerView.iconImageView.image = UIImage.yep_iconLocation } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func configureWithFeed(feed: DiscoveredFeed, layout: SearchedFeedCellLayout, keyword: String?) { super.configureWithFeed(feed, layout: layout, keyword: keyword) if let attachment = feed.attachment { if case let .Location(locationInfo) = attachment { if locationInfo.name.isEmpty { locationContainerView.titleLabel.text = NSLocalizedString("Unknown location", comment: "") } else { locationContainerView.titleLabel.text = locationInfo.name } } } locationContainerView.tapAction = { [weak self] in guard let attachment = feed.attachment else { return } if case .Location = feed.kind { if case let .Location(locationInfo) = attachment { self?.tapLocationAction?(locationName: locationInfo.name, locationCoordinate: locationInfo.coordinate) } } } let locationLayout = layout.locationLayout! locationContainerView.frame = locationLayout.locationContainerViewFrame } }
30.453333
122
0.644046
750affeec9862e71daece499d0790535945fa55e
1,067
// // ZSIndicatorTextView.swift // Pods-ZSViewUtil_Example // // Created by 张森 on 2020/1/15. // import UIKit @objcMembers open class ZSIndicatorTextView: UIView { public lazy var loadView: UIActivityIndicatorView = { let loadView = UIActivityIndicatorView() addSubview(loadView) return loadView }() public lazy var textLabel: UILabel = { let textLabel = UILabel() addSubview(textLabel) return textLabel }() override open func layoutSubviews() { super.layoutSubviews() textLabel.frame = CGRect(x: 0, y: bounds.height - 35, width: bounds.width, height: 20) loadView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: textLabel.frame.origin.y) } open func configLoadView() { loadView.style = .whiteLarge textLabel.textAlignment = .center textLabel.textColor = .white textLabel.font = .systemFont(ofSize: 15) layer.cornerRadius = 8 clipsToBounds = true } }
24.813953
98
0.611059
f4a3956e77ff6cef514c81b9cd182791da204789
54,406
// // HubConnectionTests.swift // SignalRClient // // Created by Pawel Kadluczka on 3/4/17. // Copyright © 2017 Pawel Kadluczka. All rights reserved. // import XCTest @testable import SignalRClient class HubConnectionTests: XCTestCase { func testThatOpeningHubConnectionFailsIfHandshakeFails() { let didFailToOpenExpectation = expectation(description: "connection failed to open") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { _ in XCTFail() } hubConnectionDelegate.connectionDidFailToOpenHandler = { error in didFailToOpenExpectation.fulfill() switch (error as? SignalRError) { case .handshakeError(let errorMessage)?: XCTAssertEqual("The protocol 'fakeProtocol' is not supported.", errorMessage) break default: XCTFail() break } } hubConnectionDelegate.connectionDidCloseHandler = { error in didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withLogging(minLogLevel: .debug) .withHubProtocol(hubProtocolFactory: {_ in HubProtocolFake()}) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatHubMethodCanBeInvoked() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didCloseExpectation = expectation(description: "connection closed") let message = "Hello, World!" let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() hubConnection.invoke(method: "Echo", arguments: [message], resultType: String.self) {result, error in XCTAssertNil(error) XCTAssertEqual(message, result) didReceiveInvocationResult.fulfill() hubConnection.stop() } } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatHubMethodWithHeterogenousArgumentsCanBeInvoked() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() hubConnection.invoke(method: "Concatenate", arguments: ["This is number:", 42], resultType: String.self) {result, error in XCTAssertNil(error) XCTAssertEqual("This is number: 42", result) didReceiveInvocationResult.fulfill() hubConnection.stop() } } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withLogging(minLogLevel: .debug) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatInvokingHubMethodRetunsErrorIfInvokedBeforeHandshakeReceived() { let didComplete = expectation(description: "test completed") let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL).build() hubConnection.start() hubConnection.invoke(method: "x", arguments: [], resultType: String.self) {result, error in XCTAssertNotNil(error) XCTAssertEqual("\(SignalRError.invalidOperation(message: "Attempting to send data before connection has been started."))", "\(error!)") hubConnection.stop() didComplete.fulfill() } waitForExpectations(timeout: 5 /*seconds*/) } func testThatVoidHubMethodCanBeInvoked() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() hubConnection.invoke(method: "VoidMethod", arguments: [], invocationDidComplete: { error in XCTAssertNil(error) didReceiveInvocationResult.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatInvokingVoidHubMethodRetunsErrorIfInvokedBeforeHandshakeReceived() { let didOpenExpectation = expectation(description: "connection opened") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in XCTAssertNotNil(hubConnection.connectionId) didOpenExpectation.fulfill() hubConnection.stop() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withLogging(minLogLevel: .debug) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatCanGetConnectionId() { let didComplete = expectation(description: "test completed") let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL).build() hubConnection.start() hubConnection.invoke(method: "x", arguments: []) {error in XCTAssertNotNil(error) XCTAssertEqual("\(SignalRError.invalidOperation(message: "Attempting to send data before connection has been started."))", "\(error!)") hubConnection.stop() didComplete.fulfill() } waitForExpectations(timeout: 5 /*seconds*/) } func testThatExceptionsInHubMethodsAreTurnedIntoErrors() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() hubConnection.invoke(method: "ErrorMethod", arguments: [], resultType: String.self, invocationDidComplete: { result, error in XCTAssertNotNil(error) switch (error as! SignalRError) { case .hubInvocationError(let errorMessage): XCTAssertEqual("An unexpected error occurred invoking 'ErrorMethod' on the server. InvalidOperationException: Error occurred.", errorMessage) break default: XCTFail() break } didReceiveInvocationResult.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatPendingInvocationsAreCancelledWhenConnectionIsClosed() { let invocationCancelledExpectation = expectation(description: "invocation cancelled") let testConnection = TestConnection() let logger = PrintLogger() let hubConnection = HubConnection(connection: testConnection, hubProtocol: JSONHubProtocol(logger: logger), logger: logger) let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in hubConnection.invoke(method: "TestMethod", arguments: [], invocationDidComplete: { error in XCTAssertNotNil(error) switch (error as! SignalRError) { case .hubInvocationCancelled: invocationCancelledExpectation.fulfill() break default: XCTFail() break } }) hubConnection.stop() } hubConnection.delegate = hubConnectionDelegate hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatPendingInvocationsAreAbortedWhenConnectionIsClosedWithError() { let invocationCancelledExpectation = expectation(description: "invocation cancelled") let testError = SignalRError.invalidOperation(message: "testError") let testConnection = TestConnection() let hubConnection = HubConnection(connection: testConnection, hubProtocol: JSONHubProtocol(logger: NullLogger())) let hubConnectionDelegate = TestHubConnectionDelegate() hubConnection.delegate = hubConnectionDelegate hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in hubConnection.invoke(method: "TestMethod", arguments: [], invocationDidComplete: { error in switch (error as! SignalRError) { case .invalidOperation(let errorMessage): XCTAssertEqual("testError", errorMessage) break default: XCTFail() break } invocationCancelledExpectation.fulfill() }) testConnection.delegate?.connectionDidClose(error: testError) } hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatStreamingHubMethodCanBeInvoked() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveStreamItems = expectation(description: "received stream items") let didCloseExpectation = expectation(description: "connection closed") var items: [Int] = [] let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() _ = hubConnection.stream(method: "StreamNumbers", arguments: [10, 1], streamItemReceived: { item in items.append(item!) }, invocationDidComplete: { error in XCTAssertNil(error) XCTAssertEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], items) didReceiveStreamItems.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatInvokingStreamingMethodRetunsErrorIfInvokedBeforeHandshakeReceived() { let didComplete = expectation(description: "test completed") let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL).build() hubConnection.start() _ = hubConnection.stream(method: "StreamNumbers", arguments: [], streamItemReceived: { (_: Int) in }, invocationDidComplete: {error in XCTAssertNotNil(error) XCTAssertEqual("\(SignalRError.invalidOperation(message: "Attempting to send data before connection has been started."))", "\(error!)") hubConnection.stop() didComplete.fulfill() }) waitForExpectations(timeout: 5 /*seconds*/) } func testThatExceptionsInHubStreamingMethodsCloseStreamWithError() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationError = expectation(description: "received invocation error") let didCloseExpectation = expectation(description: "connection closed") var receivedItems: [String?] = [] let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() _ = hubConnection.stream(method: "ErrorStreamMethod", arguments: [], streamItemReceived: { item in receivedItems.append(item)} , invocationDidComplete: { error in XCTAssertNotNil(error) switch (error as! SignalRError) { case .hubInvocationError(let errorMessage): XCTAssertEqual("An error occurred on the server while streaming results. InvalidOperationException: Error occurred while streaming.", errorMessage) break default: XCTFail() break } XCTAssertEqual(2, receivedItems.count) XCTAssertEqual("abc", receivedItems[0]) XCTAssertEqual(nil, receivedItems[1]) didReceiveInvocationError.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withLogging(minLogLevel: .debug) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatExceptionsWhileProcessingStreamItemCloseStreamWithError() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationError = expectation(description: "received invocation error") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() _ = hubConnection.stream(method: "StreamNumbers", arguments: [5, 5], streamItemReceived: { (_: String) in XCTFail() } , invocationDidComplete: { error in XCTAssertNotNil(error) switch (error as! SignalRError) { case .serializationError: break default: XCTFail() break } didReceiveInvocationError.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withLogging(minLogLevel: .debug) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatPendingStreamInvocationsAreCancelledWhenConnectionIsClosed() { let invocationCancelledExpectation = expectation(description: "invocation cancelled") let testConnection = TestConnection() let hubConnection = HubConnection(connection: testConnection, hubProtocol: JSONHubProtocol(logger: NullLogger())) let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = {hubConnection in _ = hubConnection.stream(method: "StreamNumbers", arguments: [5, 100], streamItemReceived: { (_: Int) in }, invocationDidComplete: { error in XCTAssertNotNil(error) switch (error as! SignalRError) { case .hubInvocationCancelled: invocationCancelledExpectation.fulfill() break default: XCTFail() break } }) hubConnection.stop() } hubConnection.delegate = hubConnectionDelegate hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatPendingStreamInvocationsAreAbortedWhenConnectionIsClosedWithError() { let invocationCancelledExpectation = expectation(description: "invocation cancelled") let testError = SignalRError.invalidOperation(message: "testError") let testConnection = TestConnection() let hubConnection = HubConnection(connection: testConnection, hubProtocol: JSONHubProtocol(logger: NullLogger())) let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = {hubConnection in _ = hubConnection.stream(method: "StreamNumbers", arguments: [5, 100], streamItemReceived: { (_: Int) in }, invocationDidComplete: { error in switch (error as! SignalRError) { case .invalidOperation(let errorMessage): XCTAssertEqual("testError", errorMessage) break default: XCTFail() break } invocationCancelledExpectation.fulfill() }) testConnection.delegate?.connectionDidClose(error: testError) } hubConnection.delegate = hubConnectionDelegate hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatCanCancelStreamingInvocations() { let didOpenExpectation = expectation(description: "connection opened") let didCloseExpectation = expectation(description: "connection closed") let invocationDidComplete = expectation(description: "stream cancellation completed") let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withLogging(minLogLevel: .debug) .build() var lastItem = -1 let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() var streamHandle: StreamHandle? = nil streamHandle = hubConnection.stream(method: "StreamNumbers", arguments: [1000, 1], streamItemReceived: { (item: Int) in lastItem = item if item == 42 { hubConnection.cancelStreamInvocation(streamHandle: streamHandle!, cancelDidFail: { _ in XCTFail() }) DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { hubConnection.stop() } } }, invocationDidComplete: { error in XCTAssertNil(error) invocationDidComplete.fulfill() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) XCTAssert(lastItem < 500) didCloseExpectation.fulfill() } hubConnection.delegate = hubConnectionDelegate hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatCallbackInvokedIfSendingCancellationMessageFailed() { let cancelDidFailExpectation = expectation(description: "cancelDidFail invoked") let invocationDidCompleteExpectation = expectation(description: "invocationDidComplete") let testConnection = TestConnection() testConnection.sendDelegate = { data, sendDidComplete in let msg = String(data: data, encoding: .utf8)! sendDidComplete(msg.contains("\"type\":5") ? SignalRError.invalidOperation(message: "test") : nil) } let hubConnection = HubConnection(connection: testConnection, hubProtocol: JSONHubProtocol(logger: NullLogger())) let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = {hubConnection in let streamHandle = hubConnection.stream(method: "TestStream", arguments: [], streamItemReceived: { (_: Int) in XCTFail() }, invocationDidComplete: { error in switch(error as! SignalRError) { case .hubInvocationCancelled: break default: XCTFail() break } invocationDidCompleteExpectation.fulfill() }) hubConnection.cancelStreamInvocation(streamHandle: streamHandle, cancelDidFail: { error in switch (error as! SignalRError) { case .invalidOperation(let errorMessage): XCTAssertEqual("test", errorMessage) break default: XCTFail() break } hubConnection.stop() cancelDidFailExpectation.fulfill() }) } hubConnection.delegate = hubConnectionDelegate hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatCancellingStreamingInvocationRetunsErrorIfInvokedBeforeHandshakeReceived() { let didComplete = expectation(description: "test completed") let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL).build() hubConnection.start() hubConnection.cancelStreamInvocation(streamHandle: StreamHandle(invocationId: "123")) {error in XCTAssertEqual("\(SignalRError.invalidOperation(message: "Attempting to send data before connection has been started."))", "\(error)") hubConnection.stop() didComplete.fulfill() } waitForExpectations(timeout: 5 /*seconds*/) } func testThatCancellingStreamingInvocationWithInvalidStreamHandleRetunsErrorIfInvokedBeforeHandshakeReceived() { let didComplete = expectation(description: "test completed") let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL).build() let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = {hubConnection in hubConnection.cancelStreamInvocation(streamHandle: StreamHandle(invocationId: "")) {error in XCTAssertEqual("\(SignalRError.invalidOperation(message: "Invalid stream handle."))", "\(error)") hubConnection.stop() didComplete.fulfill() } } hubConnection.delegate = hubConnectionDelegate hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatClientMethodsCanBeInvoked() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didInvokeClientMethod = expectation(description: "client method invoked") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() hubConnection.invoke(method: "InvokeGetNumber", arguments: [42], invocationDidComplete: { error in XCTAssertNil(error) didReceiveInvocationResult.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withLogging(minLogLevel: .debug) .build() hubConnection.on(method: "GetNumber", callback: { argumentExtractor in XCTAssertTrue(argumentExtractor.hasMoreArgs()) XCTAssertEqual(42, try argumentExtractor.getArgument(type: Int.self)) XCTAssertFalse(argumentExtractor.hasMoreArgs()) didInvokeClientMethod.fulfill() }) hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatClientMethodsCanBeInvokedMultipleArgs() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didInvokeClientMethod = expectation(description: "client method invoked") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() hubConnection.invoke(method: "InvokeManyArgs", arguments: [[42, 43]], invocationDidComplete: { error in XCTAssertNil(error) didReceiveInvocationResult.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withLogging(minLogLevel: .debug) .build() hubConnection.on(method: "ManyArgs", callback: { argumentExtractor in XCTAssertTrue(argumentExtractor.hasMoreArgs()) XCTAssertEqual(42, try argumentExtractor.getArgument(type: Int.self)) XCTAssertTrue(argumentExtractor.hasMoreArgs()) XCTAssertEqual(43, try argumentExtractor.getArgument(type: Int.self)) XCTAssertFalse(argumentExtractor.hasMoreArgs()) didInvokeClientMethod.fulfill() }) hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatClientMethodsCanBeOverwritten() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didInvokeClientMethod = expectation(description: "client method invoked") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() hubConnection.invoke(method: "InvokeGetNumber", arguments: [42], invocationDidComplete: { error in XCTAssertNil(error) didReceiveInvocationResult.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.on(method: "GetNumber", callback: { argumentExtractor in XCTFail("Should not be invoked") }) hubConnection.on(method: "GetNumber", callback: { argumentExtractor in XCTAssertNotNil(argumentExtractor) XCTAssertEqual(42, try argumentExtractor.getArgument(type: Int.self)) XCTAssertFalse(argumentExtractor.hasMoreArgs()) didInvokeClientMethod.fulfill() }) hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatClientMethodsCanBeInvokedWithTypedStructuralArgument() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didInvokeClientMethod = expectation(description: "client method invoked") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() let person = User(firstName: "Jerzy", lastName: "Meteor", age: 34, height: 179.0, sex: Sex.Male) hubConnection.invoke(method: "InvokeGetPerson", arguments: [person], invocationDidComplete: { error in XCTAssertNil(error) didReceiveInvocationResult.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withJSONHubProtocol() .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.on(method: "GetPerson", callback: { argumentExtractor in XCTAssertNotNil(argumentExtractor) let person = try argumentExtractor.getArgument(type: User.self) XCTAssertFalse(argumentExtractor.hasMoreArgs()) XCTAssertEqual("Jerzy", person.firstName) XCTAssertEqual("Meteor", person.lastName) XCTAssertEqual(34, person.age) XCTAssertEqual(179.0, person.height) XCTAssertEqual(Sex.Male, person.sex) didInvokeClientMethod.fulfill() }) hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatSendInvokesMethodsOnServer() { let didOpenExpectation = expectation(description: "connection opened") let sendCompletedExpectation = expectation(description: "send completed") let didInvokeClientMethod = expectation(description: "client method invoked") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() hubConnection.send(method: "InvokeGetNumber", arguments: [42], sendDidComplete: { error in XCTAssertNil(error) sendCompletedExpectation.fulfill() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.on(method: "GetNumber", callback: { argumentExtractor in XCTAssertNotNil(argumentExtractor) XCTAssertEqual(42, try argumentExtractor.getArgument(type: Int.self)) XCTAssertFalse(argumentExtractor.hasMoreArgs()) didInvokeClientMethod.fulfill() hubConnection.stop() }) hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatSendRetunsErrorIfInvokedBeforeHandshakeReceived() { let didComplete = expectation(description: "test completed") let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL).build() hubConnection.start() hubConnection.send(method: "x", arguments: []) {error in XCTAssertNotNil(error) XCTAssertEqual("\(SignalRError.invalidOperation(message: "Attempting to send data before connection has been started."))", "\(error!)") hubConnection.stop() didComplete.fulfill() } waitForExpectations(timeout: 5 /*seconds*/) } enum Sex: Int, Codable { case Male case Female } struct User: Codable { public let firstName: String let lastName: String let age: Int? let height: Double? let sex: Sex? } func testThatHubMethodUsingComplexTypesCanBeInvoked() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didCloseExpectation = expectation(description: "connection closed") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() let input = [User(firstName: "Klara", lastName: "Smetana", age: nil, height: 166.5, sex: Sex.Female), User(firstName: "Jerzy", lastName: "Meteor", age: 34, height: 179.0, sex: Sex.Male)] hubConnection.invoke(method: "SortByName", arguments: [input], resultType: [User].self, invocationDidComplete: { people, error in XCTAssertNil(error) XCTAssertNotNil(people) XCTAssertEqual(2, people!.count) XCTAssertEqual("Jerzy", people![0].firstName) XCTAssertEqual("Meteor", people![0].lastName) XCTAssertEqual(34, people![0].age) XCTAssertEqual(179.0, people![0].height) XCTAssertEqual(Sex.Male, people![0].sex) XCTAssertEqual("Klara", people![1].firstName) XCTAssertEqual("Smetana", people![1].lastName) XCTAssertNil(people![1].age) XCTAssertEqual(166.5, people![1].height) XCTAssertEqual(Sex.Female, people![1].sex) didReceiveInvocationResult.fulfill() hubConnection.stop() }) } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withJSONHubProtocol() .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatHubConnectionSendsHeaders() { let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in hubConnection.invoke(method: "GetHeader", arguments: ["TestHeader"], resultType: String.self, invocationDidComplete: { result, error in XCTAssertNil(error) XCTAssertEqual("header", result) hubConnection.stop() }) } let didCloseExpectation = expectation(description: "connection closed") hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHttpConnectionOptions() { httpConnectionOptions in httpConnectionOptions.headers["TestHeader"] = "header" } .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatHubConnectionSendsAuthToken() { let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in hubConnection.invoke(method: "GetHeader", arguments: ["Authorization"], resultType: String.self, invocationDidComplete: { result, error in XCTAssertNil(error) XCTAssertEqual("Bearer abc", result) // This assert fails with SignalR Azure Service hubConnection.stop() }) } let didCloseExpectation = expectation(description: "connection closed") hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHttpConnectionOptions() { httpConnectionOptions in httpConnectionOptions.accessTokenProvider = { return "abc" } } .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatStopDoesNotPassStopErrorToUnderlyingConnection() { class FakeHttpConnection: HttpConnection { var stopCalled: Bool = false init(url: URL) { let logger = NullLogger() super.init(url: url, options: HttpConnectionOptions(), transportFactory: DefaultTransportFactory(logger: logger), logger: logger) } override func stop(stopError: Error?) { XCTAssertNil(stopError) stopCalled = true } } let fakeConnection = FakeHttpConnection(url: URL(string: "http://fakeuri.org")!) let hubConnection = HubConnection(connection: fakeConnection, hubProtocol: JSONHubProtocol(logger: NullLogger())) hubConnection.stop() XCTAssertTrue(fakeConnection.stopCalled) } func testThatHubConnectionClosesConnectionUponReceivingCloseMessage() { class FakeHttpConnection: HttpConnection { var stopError: Error? init(url: URL) { let logger = NullLogger() super.init(url: url, options: HttpConnectionOptions(), transportFactory: DefaultTransportFactory(logger: logger), logger: logger) } override func start() { delegate?.connectionDidOpen(connection: self) } override func stop(stopError: Error?) { self.stopError = stopError } override var inherentKeepAlive: Bool { return true } } let fakeConnection = FakeHttpConnection(url: URL(string: "http://fakeuri.org")!) let hubConnection = HubConnection(connection: fakeConnection, hubProtocol: JSONHubProtocol(logger: NullLogger())) hubConnection.start() let payload = "{}\u{1e}{ \"type\": 7, \"error\": \"Server Error\" }\u{1e}" fakeConnection.delegate!.connectionDidReceiveData(connection: fakeConnection, data: payload.data(using: .utf8)!) XCTAssertEqual(String(describing: SignalRError.serverClose(message: "Server Error")), String(describing: fakeConnection.stopError!)) } /// Only applicable to websockets transport due to requirement for skipNegotiation flag. func testThatDeadlockDoesNotHappen() { let didStop = expectation(description: "connection stopped") let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didStop.fulfill() } let hubConnection = HubConnectionBuilder(url: TESTHUB_WEBSOCKETS_URL) .withLogging(minLogLevel: .debug) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withHttpConnectionOptions(configureHttpOptions: {options in options.skipNegotiation = true }) .build() hubConnection.start() hubConnection.stop() waitForExpectations(timeout: 5 /*seconds*/) } func testThatConnectionCanReconnect() { let connectionWillReconnectExpectation = expectation(description: "connection will reconnect") let connectionDidReconnectExpectation = expectation(description: "connection did reconnect") let connectionDidCloseExpectation = expectation(description: "connection closed") let testTransportFactory = TestTransportFactory() let hubConnectionDelegate = TestHubConnectionDelegate() let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withLogging(minLogLevel: .debug) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withCustomTransportFactory(transportFactory: {_, _ in return testTransportFactory}) .withAutoReconnect(reconnectPolicy: DefaultReconnectPolicy(retryIntervals: [DispatchTimeInterval.milliseconds(0)])) .build() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in testTransportFactory.currentTransport!.close() } hubConnectionDelegate.connectionWillReconnectHandler = { error in connectionWillReconnectExpectation.fulfill() } hubConnectionDelegate.connectionDidReconnectHandler = { connectionDidReconnectExpectation.fulfill() hubConnection.invoke(method: "VoidMethod") { error in XCTAssertNil(error) hubConnection.stop() } } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) connectionDidCloseExpectation.fulfill() } hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatConnectionCanReconnectMultipleTimes() { let testTransportFactory = TestTransportFactory() let connectionWillReconnectExpectation = expectation(description: "connection will reconnect") connectionWillReconnectExpectation.expectedFulfillmentCount = 10 let connectionDidReconnectExpectation = expectation(description: "connection did reconnect") connectionDidReconnectExpectation.expectedFulfillmentCount = 10 let connectionDidCloseExpectation = expectation(description: "connection closed") var reconnectAttemptCount = 9 let hubConnectionDelegate = TestHubConnectionDelegate() let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withLogging(minLogLevel: .debug) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withAutoReconnect(reconnectPolicy: DefaultReconnectPolicy(retryIntervals: [DispatchTimeInterval.milliseconds(0)])) .withCustomTransportFactory(transportFactory: {_, _ in return testTransportFactory }) .build() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in testTransportFactory.currentTransport!.close() } hubConnectionDelegate.connectionWillReconnectHandler = { error in connectionWillReconnectExpectation.fulfill() } hubConnectionDelegate.connectionDidReconnectHandler = { connectionDidReconnectExpectation.fulfill() if (reconnectAttemptCount > 0) { reconnectAttemptCount -= 1 testTransportFactory.currentTransport!.close() } else { hubConnection.stop() } } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) connectionDidCloseExpectation.fulfill() } hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatConnectionCanBeRestarted() { let connectionDidCloseExpectation = expectation(description: "connection closed") connectionDidCloseExpectation.expectedFulfillmentCount = 5 let hubConnectionDelegate = TestHubConnectionDelegate() let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withLogging(minLogLevel: .debug) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .build() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in hubConnection.stop() } var numRestarts = 4 // initial start + 4 restarts = 5 (expectedFulfillmentCount) hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) if (numRestarts > 0) { numRestarts -= 1 hubConnection.start() } connectionDidCloseExpectation.fulfill() } hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatConnectionCanBeRestartedAfterFailedReconnect() { let connectionDidCloseExpectation = expectation(description: "connection closed") connectionDidCloseExpectation.expectedFulfillmentCount = 2 let hubConnectionDelegate = TestHubConnectionDelegate() let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withLogging(minLogLevel: .debug) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withAutoReconnect(reconnectPolicy: DefaultReconnectPolicy(retryIntervals: [])) .build() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in hubConnection.send(method: "KillConnection") } var shouldRestart = true hubConnectionDelegate.connectionDidCloseHandler = { error in connectionDidCloseExpectation.fulfill() if shouldRestart { shouldRestart = false hubConnection.start() } } hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatHubMethodCanBeInvokedWithLegacyHttpConnection() { let didOpenExpectation = expectation(description: "connection opened") let didReceiveInvocationResult = expectation(description: "received invocation result") let didCloseExpectation = expectation(description: "connection closed") let message = "Hello, World!" let hubConnectionDelegate = TestHubConnectionDelegate() hubConnectionDelegate.connectionDidOpenHandler = { hubConnection in didOpenExpectation.fulfill() hubConnection.invoke(method: "Echo", arguments: [message], resultType: String.self) {result, error in XCTAssertNil(error) XCTAssertEqual(message, result) didReceiveInvocationResult.fulfill() hubConnection.stop() } } hubConnectionDelegate.connectionDidCloseHandler = { error in XCTAssertNil(error) didCloseExpectation.fulfill() } let hubConnection = HubConnectionBuilder(url: TARGET_TESTHUB_URL) .withHubConnectionDelegate(delegate: hubConnectionDelegate) .withLegacyHttpConnection() .build() hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatKeepAlivePingIsSentWhenInherentKeepAliveIsNotActive() { let didSendPingExpectation = expectation(description: "ping sent") let testConnection = TestConnection() testConnection.inherentKeepAlive = false testConnection.sendDelegate = { data, sendDidComplete in let msg = String(data: data, encoding: .utf8)! if msg.contains("\"type\":6") { didSendPingExpectation.fulfill() } } let hubConnectionOptions = HubConnectionOptions() hubConnectionOptions.keepAliveInterval = 4 let hubConnection = HubConnection(connection: testConnection, hubProtocol: JSONHubProtocol(logger: NullLogger()), hubConnectionOptions: hubConnectionOptions) hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } func testThatKeepAlivePingIsNoLongerSentWhenConnectionIsStopped() { let didSendPingExpectation = expectation(description: "ping sent") didSendPingExpectation.isInverted = true let testConnection = TestConnection() testConnection.inherentKeepAlive = false testConnection.sendDelegate = { data, sendDidComplete in let msg = String(data: data, encoding: .utf8)! if msg.contains("\"type\":6") { didSendPingExpectation.fulfill() } } let hubConnectionOptions = HubConnectionOptions() hubConnectionOptions.keepAliveInterval = 4 let hubConnection = HubConnection(connection: testConnection, hubProtocol: JSONHubProtocol(logger: NullLogger()), hubConnectionOptions: hubConnectionOptions) hubConnection.start() Thread.sleep(forTimeInterval: 2) hubConnection.stop() waitForExpectations(timeout: 5 /*seconds*/) } func testThatNoKeepAlivePingIsSentWhenInherentKeepAliveIsActive() { let didSendPingExpectation = expectation(description: "ping sent") didSendPingExpectation.isInverted = true let testConnection = TestConnection() testConnection.inherentKeepAlive = true testConnection.sendDelegate = { data, sendDidComplete in let msg = String(data: data, encoding: .utf8)! if msg.contains("\"type\":6") { didSendPingExpectation.fulfill() } } let hubConnectionOptions = HubConnectionOptions() hubConnectionOptions.keepAliveInterval = 4 let hubConnection = HubConnection(connection: testConnection, hubProtocol: JSONHubProtocol(logger: NullLogger()), hubConnectionOptions: hubConnectionOptions) hubConnection.start() waitForExpectations(timeout: 5 /*seconds*/) } } class TestHubConnectionDelegate: HubConnectionDelegate { var connectionDidOpenHandler: ((_ hubConnection: HubConnection) -> Void)? var connectionDidFailToOpenHandler: ((_ error: Error) -> Void)? var connectionDidCloseHandler: ((_ error: Error?) -> Void)? var connectionWillReconnectHandler: ((_ error: Error) -> Void)? var connectionDidReconnectHandler: (() -> Void)? func connectionDidOpen(hubConnection: HubConnection) { connectionDidOpenHandler?(hubConnection) } func connectionDidFailToOpen(error: Error) { connectionDidFailToOpenHandler?(error) } func connectionDidClose(error: Error?) { connectionDidCloseHandler?(error) } func connectionWillReconnect(error: Error) { connectionWillReconnectHandler?(error) } func connectionDidReconnect() { connectionDidReconnectHandler?() } } class TestConnection: Connection { var connectionId: String? var delegate: ConnectionDelegate? var sendDelegate: ((_ data: Data, _ sendDidComplete: (_ error: Error?) -> Void) -> Void)? var inherentKeepAlive = false func start() { connectionId = "00000000-0000-0000-C000-000000000046" delegate?.connectionDidOpen(connection: self) delegate?.connectionDidReceiveData(connection: self, data: "{}\u{1e}".data(using: .utf8)!) } func send(data: Data, sendDidComplete: (_ error: Error?) -> Void) { sendDelegate?(data, sendDidComplete) } func stop(stopError: Error? = nil) -> Void { connectionId = nil delegate?.connectionDidClose(error: stopError) } } class TestTransportFactory: TransportFactory { public var currentTransport: Transport? func createTransport(availableTransports: [TransportDescription]) throws -> Transport { if availableTransports.contains(where: {$0.transportType == .webSockets}) { currentTransport = WebsocketsTransport(logger: PrintLogger()) } else if availableTransports.contains(where: {$0.transportType == .longPolling}) { currentTransport = LongPollingTransport(logger: PrintLogger()) } return currentTransport! } } class ArgumentExtractorTests: XCTestCase { func testThatArgumentExtractorCallsIntoClientInvocationMessage() { let payload = "{ \"type\": 1, \"target\": \"method\", \"arguments\": [42, \"abc\"] }\u{001e}" let hubMessages = try! JSONHubProtocol(logger: NullLogger()).parseMessages(input: payload.data(using: .utf8)!) XCTAssertEqual(1, hubMessages.count) let msg = hubMessages[0] as! ClientInvocationMessage let argumentExtractor = ArgumentExtractor(clientInvocationMessage: msg) XCTAssertTrue(argumentExtractor.hasMoreArgs()) XCTAssertEqual(42, try! argumentExtractor.getArgument(type: Int.self)) XCTAssertTrue(argumentExtractor.hasMoreArgs()) XCTAssertEqual("abc", try! argumentExtractor.getArgument(type: String.self)) XCTAssertFalse(argumentExtractor.hasMoreArgs()) } }
41.467988
174
0.656031
abc086ad0245055db73e40fed1ae260e1b9aa46a
151
// // Article.swift // CacheDemo // // Created by 曾問 on 2021/6/29. // import Foundation struct Article { var id: String var content: String }
10.785714
31
0.642384
e85d1289578d6516ca77147f9b4d47e34cb2519e
713
// // PieChartDataSource.swift // PieChartKit // // Created by Ankit Kumar Bharti on 02/08/18. // Copyright © 2018 Exilant. All rights reserved. // import Cocoa /// PieChartViewDataSource @objc protocol PieChartViewDataSource: class { @objc func numberOfSection(_ pieChartView: PieChartView) -> Int @objc func color(_ pieChartView: PieChartView, at section: Int) -> NSColor? @objc func data(pieChartView: PieChartView, at section: Int) -> Double } /// PieChartViewDelegate @objc protocol PieChartViewDelegate: class { @objc optional func sectionTitle(_ pieChartView: PieChartView, for section: Int) -> String? @objc optional func didSelect(section: Int, _ pieChartView: PieChartView) }
28.52
95
0.73913
1ea4c21528b34d63f2836cf56f604a5914e99248
12,390
// // MethodChain.swift // TextureSwiftSupport // // Created by muukii on 2019/10/09. // Copyright © 2019 muukii. All rights reserved. // import Foundation import UIKit import AsyncDisplayKit public enum Edge: Int8, CaseIterable { case top = 0 case left = 1 case bottom = 2 case right = 3 public struct Set: OptionSet { public var rawValue: Int8 public var isEmpty: Bool { rawValue == 0 } public init(rawValue: Int8) { self.rawValue = rawValue } public static let top: Set = .init(rawValue: 1 << 1) public static let left: Set = .init(rawValue: 1 << 2) public static let bottom: Set = .init(rawValue: 1 << 3) public static let right: Set = .init(rawValue: 1 << 4) public static var horizontal: Set { [.left, .right] } public static var vertical: Set { [.top, .bottom] } public static var all: Set { [.top, .bottom, .right, left] } } } @inline(__always) fileprivate func makeInsets(_ padding: CGFloat) -> UIEdgeInsets { .init(top: padding, left: padding, bottom: padding, right: padding) } @inline(__always) fileprivate func makeInsets(_ edges: Edge.Set, _ padding: CGFloat) -> UIEdgeInsets { var insets = UIEdgeInsets.zero if edges.contains(.top) { insets.top = padding } if edges.contains(.left) { insets.left = padding } if edges.contains(.bottom) { insets.bottom = padding } if edges.contains(.right) { insets.right = padding } return insets } fileprivate func combineInsets(_ lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> UIEdgeInsets { var base = lhs base.top += rhs.top base.right += rhs.right base.left += rhs.left base.bottom += rhs.bottom return base } // MARK: - Padding extension _ASLayoutElementType { public func padding(_ padding: CGFloat) -> InsetLayout<Self> { InsetLayout(insets: makeInsets(padding)) { self } } public func padding(_ edgeInsets: UIEdgeInsets) -> InsetLayout<Self> { InsetLayout(insets: edgeInsets) { self } } public func padding(_ edges: Edge.Set, _ padding: CGFloat) -> InsetLayout<Self> { return InsetLayout(insets: makeInsets(edges, padding)) { self } } } extension InsetLayout { public func padding(_ padding: CGFloat) -> Self { var _self = self _self.insets = combineInsets(_self.insets, rhs: makeInsets(padding)) return _self } public func padding(_ edgeInsets: UIEdgeInsets) -> Self { var _self = self _self.insets = combineInsets(_self.insets, rhs: edgeInsets) return _self } public func padding(_ edges: Edge.Set, _ padding: CGFloat) -> Self { var _self = self _self.insets = combineInsets(_self.insets, rhs: makeInsets(edges, padding)) return _self } } // MARK: - Background extension _ASLayoutElementType { public func background<Background: _ASLayoutElementType>(_ backgroundContent: Background) -> BackgroundLayout<Background, Self> { BackgroundLayout(content: { self }, background: { backgroundContent }) } public func background<Background: _ASLayoutElementType>(@ASLayoutSpecBuilder _ backgroundContent: () -> Background) -> BackgroundLayout<Background, Self> { BackgroundLayout(content: { self }, background: backgroundContent) } public func overlay<Overlay: _ASLayoutElementType>(_ overlayContent: Overlay) -> OverlayLayout<Overlay, Self> { OverlayLayout(content: { self }, overlay: { overlayContent }) } public func overlay<Overlay: _ASLayoutElementType>(@ASLayoutSpecBuilder _ overlayContent: () -> Overlay) -> OverlayLayout<Overlay, Self> { OverlayLayout(content: { self }, overlay: overlayContent) } /// Make aspectRatio /// /// - Parameters: /// - aspectRatio: The ratio of width to height to use for the resulting view public func aspectRatio(_ aspectRatio: CGFloat) -> AspectRatioLayout<Self> { AspectRatioLayout(ratio: aspectRatio, content: { self }) } /// Make aspectRatio /// /// - Parameters: /// - aspectRatio: The ratio of CGSize to use for the resulting view public func aspectRatio(_ aspectRatio: CGSize) -> AspectRatioLayout<Self> { AspectRatioLayout(ratio: aspectRatio, content: { self }) } } // MARK: - Relative extension _ASLayoutElementType { /// Make it relative layout public func relativePosition( horizontal: ASRelativeLayoutSpecPosition, vertical: ASRelativeLayoutSpecPosition, sizingOption: ASRelativeLayoutSpecSizingOption = .minimumSize ) -> RelativeLayout<Self> { RelativeLayout(horizontalPosition: horizontal, verticalPosition: vertical, sizingOption: sizingOption, content: { self }) } } public struct FlexGlowModifier: ModifierType { private let flexGrow: CGFloat init(flexGrow: CGFloat) { self.flexGrow = flexGrow } public func modify(element: ASLayoutElement) -> ASLayoutElement { element.style.flexGrow = flexGrow return element } } public struct FlexShrinkModifier: ModifierType { private let flexShrink: CGFloat init(flexShrink: CGFloat) { self.flexShrink = flexShrink } public func modify(element: ASLayoutElement) -> ASLayoutElement { element.style.flexShrink = flexShrink return element } } public struct SpacingModifier: ModifierType { public let after: CGFloat? public let before: CGFloat? public func modify(element: ASLayoutElement) -> ASLayoutElement { after.map { element.style.spacingAfter = $0 } before.map { element.style.spacingBefore = $0 } return element } } public struct AlignSelfModifier: ModifierType { public var alignSelf: ASStackLayoutAlignSelf public init(alignSelf: ASStackLayoutAlignSelf) { self.alignSelf = alignSelf } public func modify(element: ASLayoutElement) -> ASLayoutElement { element.style.alignSelf = alignSelf return element } } public struct SizeModifier: ModifierType { public var width: ASDimension? public var height: ASDimension? public init(size: CGSize) { self.width = .init(unit: .points, value: size.width) self.height = .init(unit: .points, value: size.height) } public init(width: ASDimension?, height: ASDimension?) { self.width = width self.height = height } public func modify(element: ASLayoutElement) -> ASLayoutElement { width.map { element.style.width = $0 } height.map { element.style.height = $0 } return element } } public struct MinSizeModifier: ModifierType { public var minWidth: ASDimension? public var minHeight: ASDimension? public init(minSize: CGSize) { self.minWidth = .init(unit: .points, value: minSize.width) self.minHeight = .init(unit: .points, value: minSize.height) } public init(minWidth: ASDimension?, minHeight: ASDimension?) { self.minWidth = minWidth self.minHeight = minHeight } public func modify(element: ASLayoutElement) -> ASLayoutElement { minWidth.map { element.style.minWidth = $0 } minHeight.map { element.style.minHeight = $0 } return element } } public struct MaxSizeModifier: ModifierType { public var maxWidth: ASDimension? public var maxHeight: ASDimension? public init(maxSize: CGSize) { self.maxWidth = .init(unit: .points, value: maxSize.width) self.maxHeight = .init(unit: .points, value: maxSize.height) } public init(maxWidth: ASDimension?, maxHeight: ASDimension?) { self.maxWidth = maxWidth self.maxHeight = maxHeight } public func modify(element: ASLayoutElement) -> ASLayoutElement { maxWidth.map { element.style.maxWidth = $0 } maxHeight.map { element.style.maxHeight = $0 } return element } } public struct FlexBasisModifieer: ModifierType { public let flexBasis: ASDimension public init(flexBasis: ASDimension) { self.flexBasis = flexBasis } public func modify(element: ASLayoutElement) -> ASLayoutElement { element.style.flexBasis = flexBasis return element } } extension _ASLayoutElementType { public func modify(_ modify: @escaping (ASLayoutElement) -> Void) -> ModifiedContent<Self, Modifier> { modifier( .init { element in modify(element) return element } ) } public func flexGrow(_ flexGlow: CGFloat) -> ModifiedContent<Self, FlexGlowModifier> { modifier(FlexGlowModifier(flexGrow: flexGlow)) } public func flexShrink(_ flexShrink: CGFloat) -> ModifiedContent<Self, FlexShrinkModifier> { modifier(FlexShrinkModifier(flexShrink: flexShrink)) } public func flexBasis(fraction: CGFloat) -> ModifiedContent<Self, FlexBasisModifieer> { modifier(FlexBasisModifieer(flexBasis: .init(unit: .fraction, value: fraction))) } public func preferredSize(_ preferredSize: CGSize) -> ModifiedContent<Self, SizeModifier> { modifier(SizeModifier(size: preferredSize)) } public func alignSelf(_ alignSelf: ASStackLayoutAlignSelf) -> ModifiedContent<Self, AlignSelfModifier> { modifier(AlignSelfModifier(alignSelf: alignSelf)) } public func minWidth(_ width: CGFloat) -> ModifiedContent<Self, MinSizeModifier> { modifier(MinSizeModifier(minWidth: .init(unit: .points, value: width), minHeight: nil)) } public func minHeight(_ height: CGFloat) -> ModifiedContent<Self, MinSizeModifier> { modifier(MinSizeModifier(minWidth: nil, minHeight: .init(unit: .points, value: height))) } /// might be deprecated in favor of `width(points:)` public func width(_ width: CGFloat) -> ModifiedContent<Self, SizeModifier> { modifier(SizeModifier(width: .init(unit: .points, value: width), height: nil)) } /// might be deprecated in favor of `height(points:)` public func height(_ height: CGFloat) -> ModifiedContent<Self, SizeModifier> { modifier(SizeModifier(width: nil, height: .init(unit: .points, value: height))) } public func width(fraction: CGFloat) -> ModifiedContent<Self, SizeModifier> { modifier(SizeModifier(width: .init(unit: .fraction, value: fraction), height: nil)) } public func height(fraction: CGFloat) -> ModifiedContent<Self, SizeModifier> { modifier(SizeModifier(width: nil, height: .init(unit: .fraction, value: fraction))) } public func minSize(_ size: CGSize) -> ModifiedContent<Self, MinSizeModifier> { modifier(MinSizeModifier(minSize: size)) } public func maxWidth(_ width: CGFloat) -> ModifiedContent<Self, MaxSizeModifier> { modifier(MaxSizeModifier(maxWidth: .init(unit: .points, value: width), maxHeight: nil)) } public func maxHeight(_ height: CGFloat) -> ModifiedContent<Self, MaxSizeModifier> { modifier(MaxSizeModifier(maxWidth: nil, maxHeight: .init(unit: .points, value: height))) } public func maxSize(_ size: CGSize) -> ModifiedContent<Self, MaxSizeModifier> { modifier(MaxSizeModifier(maxSize: size)) } public func spacingAfter(_ spacing: CGFloat) -> ModifiedContent<Self, SpacingModifier> { modifier(SpacingModifier(after: spacing, before: nil)) } public func spacingBefore(_ spacing: CGFloat) -> ModifiedContent<Self, SpacingModifier> { modifier(SpacingModifier(after: nil, before: spacing)) } } extension ModifiedContent where Modifier == MinSizeModifier { public func minWidth(_ width: CGFloat) -> Self { var _self = self _self.modifier.minWidth = .init(unit: .points, value: width) return _self } public func minHeight(_ height: CGFloat) -> Self { var _self = self _self.modifier.minWidth = .init(unit: .points, value: height) return _self } public func minSize(_ size: CGSize) -> Self { var _self = self _self.modifier = MinSizeModifier(minSize: size) return _self } } extension ModifiedContent where Modifier == MaxSizeModifier { public func maxWidth(_ width: CGFloat) -> Self { var _self = self _self.modifier.maxWidth = .init(unit: .points, value: width) return _self } public func maxHeight(_ height: CGFloat) -> Self { var _self = self _self.modifier.maxWidth = .init(unit: .points, value: height) return _self } public func maxSize(_ size: CGSize) -> Self { var _self = self _self.modifier = MaxSizeModifier(maxSize: size) return _self } }
26.760259
158
0.686602
4b66faeb03176e8795fb079abfcc700a2e4b8a7d
5,997
// // Copyright © 2020 Paris Android User Group. All rights reserved. // import SwiftUI import URLImage struct AboutView: View { @ObservedObject private var viewModel = AboutViewModel() var body: some View { NavigationView { ZStack { Color(.secondarySystemBackground).edgesIgnoringSafeArea(.all) ScrollView { VStack { Card { VStack(spacing: 16) { Image("logo_oneline_black_text") .resizable() .aspectRatio(contentMode: .fit) Text(L10n.About.explanation) .foregroundColor(Color.black) HStack(spacing: 24) { WebButton(url: URL(string: "https://androidmakers.fr/faq")!) { Text(L10n.About.faq) } .foregroundColor(Color(Asset.Colors.link.color)) WebButton(url: URL(string: "https://androidmakers.fr/coc")!) { Text(L10n.About.coc) } .foregroundColor(Color(Asset.Colors.link.color)) }.padding(8) }.padding(8) } Card { VStack { Text(L10n.About.social) .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) .foregroundColor(Color(Asset.Colors.link.color)) Button(action: { self.viewModel.openHashtagPage() }) { Text("#AndroidMakers") .foregroundColor(Color(Asset.Colors.link.color)) } HStack(spacing: 16) { Button(action: { self.viewModel.openTwitterPage() }) { Image("twitter") .resizable() .aspectRatio(contentMode: .fit) .foregroundColor(Color(Asset.Colors.twitter.color)) } Button(action: { self.viewModel.openYoutubePage() }) { Image("youtube") .resizable() .aspectRatio(contentMode: .fit) .padding(.vertical, 16) } }.frame(maxHeight: 50) }.padding(8) } Card { VStack(spacing: 16) { Text(L10n.About.sponsors) .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) .foregroundColor(Color(Asset.Colors.link.color)) ForEach(self.viewModel.partnerCategories, id: \.self) { category in VStack { Text(category.categoryName) .foregroundColor(Color.black) .bold() .padding(16) ForEach(category.partners, id: \.self) { partner in Button(action: { self.viewModel.openPartnerPage(partner) }) { URLImage(partner.logoUrl) { image in image .renderingMode(.original) .resizable() .aspectRatio(contentMode: .fit) } } .frame(maxHeight: 50) } } } Spacer(minLength: 8) }.padding(8) } } .frame(minWidth: 0, maxWidth: .infinity) } .padding(0) .background(Color(.secondarySystemBackground)) .navigationBarTitle(Text(L10n.About.navTitle), displayMode: .inline) } } // must ensure that the stack navigation is used otherwise it is considered as a master view // and nothing is shown in the detail .navigationViewStyle(StackNavigationViewStyle()) .padding(0) } } struct Card<Content: View>: View { let content: () -> Content var body: some View { VStack { content() }.frame(minWidth: 0, maxWidth: .infinity) .background(Color(Asset.Colors.cardBackground.color)) .cornerRadius(8) .padding(8) } } #if DEBUG struct AboutView_Previews: PreviewProvider { static var previews: some View { injectMockModel() return AboutView() } } #endif
45.778626
105
0.352343
d64eb73adb8957824cca2b392589bd9c89d14163
36
class TestSpacesBeforeClass { }
5.142857
29
0.722222
c123242050f97e346f4e5f82d544f7956c6313ee
2,885
// // JXPagingListRefreshView.swift // JXPagingView // // Created by jiaxin on 2018/8/28. // Copyright © 2018年 jiaxin. All rights reserved. // import UIKit open class JXPagingListRefreshView: JXPagingView { fileprivate var lastScrollingListViewContentOffsetY: CGFloat = 0 override open func initializeViews() { super.initializeViews() mainTableView.bounces = false } override open func preferredProcessMainTableViewDidScroll(_ scrollView: UIScrollView) { if (self.currentScrollingListView != nil && self.currentScrollingListView!.contentOffset.y > 0) { //mainTableView的header已经滚动不见,开始滚动某一个listView,那么固定mainTableView的contentOffset,让其不动 self.mainTableView.contentOffset = CGPoint(x: 0, y: self.delegate.tableHeaderViewHeight(in: self)) } if (mainTableView.contentOffset.y < getTableHeaderViewHeight()) { //mainTableView已经显示了header,listView的contentOffset需要重置 for list in self.validListDict.values { //正在下拉刷新时,不需要重置 if list.listScrollView().contentOffset.y > 0 { list.listScrollView().contentOffset = CGPoint.zero } } } } override open func preferredProcessListViewDidScroll(scrollView: UIScrollView) { var shouldProcess = true if currentScrollingListView!.contentOffset.y > self.lastScrollingListViewContentOffsetY { //往上滚动 }else { //往下滚动 if self.mainTableView.contentOffset.y == 0 { shouldProcess = false }else { if (self.mainTableView.contentOffset.y < getTableHeaderViewHeight()) { //mainTableView的header还没有消失,让listScrollView一直为0 currentScrollingListView!.contentOffset = CGPoint.zero; currentScrollingListView!.showsVerticalScrollIndicator = false; } } } if shouldProcess { if (self.mainTableView.contentOffset.y < getTableHeaderViewHeight()) { //处于下拉刷新的状态,scrollView.contentOffset.y为负数,就重置为0 if currentScrollingListView!.contentOffset.y > 0 { //mainTableView的header还没有消失,让listScrollView一直为0 currentScrollingListView!.contentOffset = CGPoint.zero; currentScrollingListView!.showsVerticalScrollIndicator = false; } } else { //mainTableView的header刚好消失,固定mainTableView的位置,显示listScrollView的滚动条 self.mainTableView.contentOffset = CGPoint(x: 0, y: self.delegate.tableHeaderViewHeight(in: self)); currentScrollingListView!.showsVerticalScrollIndicator = false; } } self.lastScrollingListViewContentOffsetY = currentScrollingListView!.contentOffset.y; } }
40.633803
115
0.640208
5bb181f45cc38ef8526f3fd429848e74ef5d1b02
1,547
// // ViewController.swift // macapp // // Created by 郭斌 on 2020/7/9. // Copyright © 2020 guobin. All rights reserved. // import Cocoa class ViewController: NSViewController { var isOpen: Bool = false var btnTitle: String = "开始录制" override func viewDidLoad() { super.viewDidLoad() print("size: {width: \(view.frame.width), height: \(view.frame.height)}") let center: CGFloat = view.frame.width / 2 - 60 // 打开录音 let openBtn = NSButton(title: "开始录制", target: self, action: nil) openBtn.frame = NSRect(x: center, y: 100, width: 120, height: 30) openBtn.bezelStyle = .rounded openBtn.setButtonType(.pushOnPushOff) openBtn.action = #selector(onOpenClick) view.addSubview(openBtn) // 关闭录音 let closeBtn = NSButton(title: "停止录制", target: self, action: nil) closeBtn.frame = NSRect(x: center, y: 140, width: 120, height: 30) closeBtn.bezelStyle = .rounded closeBtn.setButtonType(.pushOnPushOff) closeBtn.action = #selector(onCloseClick) view.addSubview(closeBtn) } @objc func onCloseClick() { print("closeBtn Click") // call c function // handleClick() } @objc func onOpenClick() { if isOpen { btnTitle = "停止录制" isOpen = !isOpen } print("openBtn Click") } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
24.951613
81
0.580478
0a92f72b738cd0360649bf7d1eb23bcdd9005913
5,684
import Foundation import UIKit extension UIImage { public var original: UIImage { return withRenderingMode(.alwaysOriginal) } public var template: UIImage { return withRenderingMode(.alwaysTemplate) } public var aspectRatio: CGFloat { guard size.height > 0 else { return 1 } return size.width / size.height } /** Returns a copy of self, tinted by the given color. - parameter tintColor: The UIColor to tint by. - returns: A copy of self, tinted by the tintColor. */ public func tinted(_ tintColor: UIColor) -> UIImage { guard let cgImage = cgImage else { return self } UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) defer { UIGraphicsEndImageContext() } let context = UIGraphicsGetCurrentContext() context?.saveGState() tintColor.setFill() context?.translateBy(x: 0, y: size.height) context?.scaleBy(x: 1, y: -1) context?.setBlendMode(.normal) let rect = CGRect(origin: .zero, size: size) context?.draw(cgImage, in: rect) context?.clip(to: rect, mask: cgImage) context?.addRect(rect) context?.drawPath(using: .fill) context?.restoreGState() return UIGraphicsGetImageFromCurrentImageContext() ?? self } /** Returns a copy of self, scaled by a specified scale factor (with an optional image orientation). Example: ``` let image = UIImage(named: <image_name>) // image size = (width: 200, height: 100) image?.resized(width: 50, height: 50) // image size = (width: 50, height: 50) image?.resized(width: 50, height: 50, maintainAspectRatio: true) // image size = (width: 50, height: 25) ``` - parameter width: The width to which to resize the image. - parameter height: The height to which to resize the image. - parameter maintainAspectRatio: A Boolean flag indicating whether or not to maintain the image's aspect ratio when resizing (optional, defaults to `false`). - returns: A copy of self, resized to a specified width and heigh (with an option to maintain the original aspect ratio). */ public func resized(width: CGFloat, height: CGFloat, maintainAspectRatio: Bool = false, insets: UIEdgeInsets = .zero) -> UIImage? { let inputSize = CGSize(width: width, height: height) let newSize: CGSize if maintainAspectRatio { let ratio = min(inputSize.width / size.width, inputSize.height / size.height) newSize = CGSize(width: size.width * ratio, height: size.height * ratio) } else { newSize = inputSize } let contextSize = CGSize(width: newSize.width + insets.right + insets.left, height: newSize.height + insets.bottom + insets.top) UIGraphicsBeginImageContextWithOptions(contextSize, false, UIScreen.main.scale) defer { UIGraphicsEndImageContext() } draw(in: CGRect(origin: CGPoint(x: insets.left, y: insets.top), size: newSize)) return UIGraphicsGetImageFromCurrentImageContext() } public func resized(size: CGSize, maintainAspectRatio: Bool = false, insets: UIEdgeInsets = .zero) -> UIImage? { return self.resized(width: size.width, height: size.height, maintainAspectRatio: maintainAspectRatio, insets: insets) } /** Returns a copy of self, scaled by a specified scale factor (with an optional image orientation). Example: ``` let image = UIImage(named: <image_name>) // image size = (width: 200, height: 100) image?.scaled(by: 0.25) // image size = (width: 50, height: 25) image?.scaled(by: 2) // image size = (width: 400, height: 200) ``` - parameter scaleFactor: The factor at which to scale this image. - parameter orientiation: The orientation to use for the scaled image (optional, defaults to the image's `imageOrientation` property). - returns: A copy of self, scaled by the scaleFactor (with an optional image orientation). */ public func scaled(by scaleFactor: CGFloat, withOrientation orientation: UIImage.Orientation? = nil) -> UIImage? { guard let coreImage = cgImage else { return nil } return UIImage(cgImage: coreImage, scale: 1/scaleFactor, orientation: orientation ?? imageOrientation) } /** Returns an optional image using the `drawingCommands` Example: let image = UIImage(size: CGSize(width: 12, height: 24)) { let path = UIBezierPath() path.move(to: ...) path.addLine(to: ...) path.addLine(to: ...) path.lineWidth = 2 UIColor.white.setStroke() path.stroke() } - parameter size: The image size. - parameter drawingCommands: A closure describing the path, fill/stroke color, etc. - returns: An optional image based on `drawingCommands`. */ public convenience init?(size: CGSize, drawingCommands commands: () -> Void) { UIGraphicsBeginImageContextWithOptions(size, false, 0) commands() defer { UIGraphicsEndImageContext() } guard let image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { return nil } self.init(cgImage: image) } /** Returns an optional image using the specified color - parameter color: The color of the image. - returns: An optional image based on `color`. */ public convenience init?(color: UIColor) { let size = CGSize(width: 1, height: 1) let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) defer { UIGraphicsEndImageContext() } guard let image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { return nil } self.init(cgImage: image) } }
34.240964
160
0.679451
9b482a3fcb0affad205ecc50beccc71d7590e597
3,266
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore //MARK: Paginators extension Kendra { /// Gets statistics about synchronizing Amazon Kendra with a data source. public func listDataSourceSyncJobsPaginator( _ input: ListDataSourceSyncJobsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListDataSourceSyncJobsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: listDataSourceSyncJobs, tokenKey: \ListDataSourceSyncJobsResponse.nextToken, on: eventLoop, onPage: onPage) } /// Lists the data sources that you have created. public func listDataSourcesPaginator( _ input: ListDataSourcesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListDataSourcesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: listDataSources, tokenKey: \ListDataSourcesResponse.nextToken, on: eventLoop, onPage: onPage) } /// Lists the Amazon Kendra indexes that you have created. public func listIndicesPaginator( _ input: ListIndicesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListIndicesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate(input: input, command: listIndices, tokenKey: \ListIndicesResponse.nextToken, on: eventLoop, onPage: onPage) } } extension Kendra.ListDataSourceSyncJobsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Kendra.ListDataSourceSyncJobsRequest { return .init( id: self.id, indexId: self.indexId, maxResults: self.maxResults, nextToken: token, startTimeFilter: self.startTimeFilter, statusFilter: self.statusFilter ) } } extension Kendra.ListDataSourcesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Kendra.ListDataSourcesRequest { return .init( indexId: self.indexId, maxResults: self.maxResults, nextToken: token ) } } extension Kendra.ListIndicesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Kendra.ListIndicesRequest { return .init( maxResults: self.maxResults, nextToken: token ) } }
35.89011
161
0.66289
f80ec0f2bd969e349c2a331fb17b55743be73353
7,219
// // JBViewController.swift // SparkGame // // Created by Bruce Jiang on 2017/5/17. // Copyright © 2017年 Bruce Jiang. All rights reserved. // import UIKit import SpriteKit class JBViewController: JBSuperViewController,UITextFieldDelegate { //MARK: - parameters var mainSKView = JBMainSKView() var logView = JBLogMainView() var resetView = JBLogResetView() var backBtn = UIButton() fileprivate var keyBoardHeight : CGFloat = 0 fileprivate var kIfKeyboardShowed : Bool = false //MARK: - Init override func viewDidLoad() { super.viewDidLoad() setConfigures() addObserverForKeyBoard() } func setConfigures() -> () { /// mainSKView mainSKView = JBMainSKView.init(frame: self.view.bounds) mainSKView.subNodeCallBack = {[weak self] (hash) in guard let huochaiNodeHash = self?.mainSKView.huochaiNode.hash else { fatalError("can not get hash value of host Node !") } switch hash { case huochaiNodeHash: print("HuoChaiNode clicked ! very cool !") break default:break } } mainSKViewTouchHandler() self.view.addSubview(mainSKView) /// LogView logView = JBLogMainView.init(frame: CGRect.init(x: (self.view.bounds.width-600)/2, y: (self.view.bounds.size.height-500)/2, width: 600, height: 500)) JBControl.instance.setScale(from: 0.75, to: 1, with: self.logView) { //动画完后 } logView.centerBtnTouchHandler = { [weak self](btn,hash) in print(" >>>>>>>>>> 💕\(btn.tag)") switch btn.tag { case hash >> 1://Login // Present the scene with a transition. self?.logView.removeFromSuperview() self?.resetView.removeFromSuperview() self?.mainSKView.resetScene(bgImage: "image 1") self?.mainSKView.setWebView(to:CGRect.zero) // test of custom button. let btnNode = JBButtonNode.init(texture: SKTexture.init(image: #imageLiteral(resourceName: "redstar")), color: UIColor.blue, size: CGSize.init(width: 100, height: 50),title:"Hello!") btnNode.position = CGPoint.init(x: 64, y:80) self?.mainSKView.mainScene.addChild(btnNode) break case hash >> 2://Remember break case hash >> 3://Forget self?.logView.isHidden = true self?.backBtn.isHidden = false self?.resetView.isHidden = false self?.logView.nameTextField.resignFirstResponder() self?.logView.secretTextField.resignFirstResponder() self?.logView.leftEmmiterNode.particleBirthRate = 0 self?.logView.rightEmmiterNode.particleBirthRate = 0 break default:break } } self.view.addSubview(logView) resetView = JBLogResetView.init(frame: CGRect.init(x: (self.view.bounds.width-600)/2, y: (self.view.bounds.size.height-500)/2, width: 600, height: 500)) resetView.getModifyCodeHandler = { //获取验证码 } resetView.isHidden = true self.view.addSubview(resetView) backBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 100)) backBtn.setImage(#imageLiteral(resourceName: "back"), for: .normal) backBtn.isHidden = true backBtn.addTarget(self, action: #selector(backToMain), for: .touchUpInside) self.view.addSubview(backBtn) } //MARK: - mainView touch delegate func mainSKViewTouchHandler() -> () { mainSKView.touchBegan = {[weak self] (touches,event) in self?.logView.nameTextField.resignFirstResponder() self?.logView.secretTextField.resignFirstResponder() } mainSKView.toucheMoved = {[weak self] (touches,event) in } mainSKView.toucheEnded = {[weak self] (touches,event) in } } /// back @objc func backToMain() -> () { logView.isHidden = false logView.leftEmmiterNode.particleBirthRate = 1 logView.rightEmmiterNode.particleBirthRate = 1 resetView.phoneFeild.resignFirstResponder() resetView.isHidden = true backBtn.isHidden = true } //MARK: - Add Observer func addObserverForKeyBoard() -> () { NotificationCenter.default.addObserver(self, selector: #selector(changeCenterPartFrame(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(recoverCenterpartFrame(noti:)), name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(willChangeF(noti:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) } //MARK: - 键盘Frame即将改变 @objc func willChangeF(noti:Notification) -> () { ifRealNeedSet(noti: noti) } //MARK: - 键盘出现 @objc func changeCenterPartFrame(noti:Notification) -> () { ifRealNeedSet(noti: noti) } /// set真正的位置 func ifRealNeedSet(noti:Notification) -> () { let userInfo = noti.userInfo let value = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] let boardRect = value as! CGRect if boardRect.height<=55 { }else { if kIfKeyboardShowed { }else{ keyBoardHeight = boardRect.height centerSetShowed() kIfKeyboardShowed = true } } } /// set func centerSetShowed() -> () { UIView.animate(withDuration: 0.3) { self.logView.frame = CGRect.init(x: self.logView.frame.origin.x, y: -100, width: self.logView.frame.size.width, height: self.logView.frame.size.height) self.resetView.frame = CGRect.init(x: self.resetView.frame.origin.x, y: -100, width: self.resetView.frame.size.width, height: self.resetView.frame.size.height) } } //MARK: - 键盘隐藏 @objc func recoverCenterpartFrame(noti:Notification) -> () { centerSetHide() kIfKeyboardShowed = false } /// set func centerSetHide() -> () { UIView.animate(withDuration: 0.3) { self.logView.frame = CGRect.init(x: self.logView.frame.origin.x, y: (self.view.bounds.size.height-500)/2, width: self.logView.frame.size.width, height: self.logView.frame.size.height) self.resetView.frame = CGRect.init(x: self.resetView.frame.origin.x, y: (self.view.bounds.size.height-500)/2, width: self.resetView.frame.size.width, height: self.resetView.frame.size.height) } } deinit { NotificationCenter.default.removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
37.994737
203
0.601191
894ec896ece49e1ce6b697b4b519574aa6fb9aae
230
import Foundation protocol OnboardingViewModelDelegate: class { func onClose() } class OnboardingViewModel { weak var delegate: OnboardingViewModelDelegate? func onCloseClick() { delegate?.onClose() } }
16.428571
51
0.713043
01bc8a6bc9e3aba928e442ce4dd5ad960b0dbef8
729
// // HowToWorkDotSelf.swift // CoreDataTechnique // // Created by Mehmet Ateş on 21.05.2022. // import SwiftUI struct Student: Hashable { let name: String } struct HowToWorkDotSelf: View { let students = [Student(name: "Harry Potter"), Student(name: "Hermione Granger")] var body: some View { VStack{ List { ForEach([2, 4, 6, 8, 10], id: \.self) { Text("\($0) is even") } } List(students, id: \.self) { student in Text(student.name) } } } } struct HowToWorkDotSelf_Previews: PreviewProvider { static var previews: some View { HowToWorkDotSelf() } }
18.692308
85
0.525377
f51f5a41b44c3d7e4e4651e8008df0b5a01506b7
323
// // FormModel.swift // GeoBudgeting // // Created by Prateek Kambadkone on 2019/05/09. // Copyright © 2019 DVT. All rights reserved. // import Foundation struct FormModel { var storeName: String? var category: [String]? var date: Date? var total: Double? var lat: Double? var lng: Double? }
17
48
0.650155
6458e8d2dee9bee6c29ddf2aaf2be9e3071392e2
9,629
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift import _Concurrency // ==== Any Actor ------------------------------------------------------------- /// Shared "base" protocol for both (local) `Actor` and (potentially remote) /// `DistributedActor`. /// /// FIXME(distributed): We'd need Actor to also conform to this, but don't want to add that conformance in _Concurrency yet. @_marker @available(SwiftStdlib 5.5, *) public protocol AnyActor: Sendable, AnyObject {} // ==== Distributed Actor ----------------------------------------------------- /// Common protocol to which all distributed actors conform implicitly. /// /// It is not possible to conform to this protocol manually explicitly. /// Only a 'distributed actor' declaration or protocol with 'DistributedActor' /// requirement may conform to this protocol. /// /// The 'DistributedActor' protocol provides the core functionality of any /// distributed actor. @available(SwiftStdlib 5.5, *) public protocol DistributedActor: AnyActor, Identifiable, Hashable, Codable { /// Resolves the passed in `identity` against the `transport`, returning /// either a local or remote actor reference. /// /// The transport will be asked to `resolve` the identity and return either /// a local instance or request a proxy to be created for this identity. /// /// A remote distributed actor reference will forward all invocations through /// the transport, allowing it to take over the remote messaging with the /// remote actor instance. /// /// - Parameter identity: identity uniquely identifying a, potentially remote, actor in the system /// - Parameter transport: `transport` which should be used to resolve the `identity`, and be associated with the returned actor // FIXME: Partially blocked on SE-309, because then we can store ActorIdentity directly // We want to move to accepting a generic or existential identity here // static func resolve<Identity>(_ identity: Identity, using transport: ActorTransport) // throws -> Self where Identity: ActorIdentity static func resolve(_ identity: AnyActorIdentity, using transport: ActorTransport) throws -> Self /// The `ActorTransport` associated with this actor. /// It is immutable and equal to the transport passed in the local/resolve /// initializer. /// /// Conformance to this requirement is synthesized automatically for any /// `distributed actor` declaration. nonisolated var actorTransport: ActorTransport { get } // TODO: rename to `transport`? /// Logical identity of this distributed actor. /// /// Many distributed actor references may be pointing at, logically, the same actor. /// For example, calling `resolve(address:using:)` multiple times, is not guaranteed /// to return the same exact resolved actor instance, however all the references would /// represent logically references to the same distributed actor, e.g. on a different node. /// /// An address is always uniquely pointing at a specific actor instance. /// /// Conformance to this requirement is synthesized automatically for any /// `distributed actor` declaration. nonisolated var id: AnyActorIdentity { get } } // ==== Hashable conformance --------------------------------------------------- @available(SwiftStdlib 5.5, *) extension DistributedActor { nonisolated public func hash(into hasher: inout Hasher) { self.id.hash(into: &hasher) } nonisolated public static func == (lhs: Self, rhs: Self) -> Bool { lhs.id == rhs.id } } // ==== Codable conformance ---------------------------------------------------- extension CodingUserInfoKey { @available(SwiftStdlib 5.5, *) public static let actorTransportKey = CodingUserInfoKey(rawValue: "$dist_act_transport")! } @available(SwiftStdlib 5.5, *) extension DistributedActor { nonisolated public init(from decoder: Decoder) throws { guard let transport = decoder.userInfo[.actorTransportKey] as? ActorTransport else { throw DistributedActorCodingError(message: "Missing ActorTransport (for key .actorTransportKey) " + "in Decoder.userInfo, while decoding \(Self.self).") } let id: AnyActorIdentity = try transport.decodeIdentity(from: decoder) self = try Self.resolve(id, using: transport) } nonisolated public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.id) } } // ==== Local actor special handling ------------------------------------------- @available(SwiftStdlib 5.5, *) extension DistributedActor { /// Executes the passed 'body' only when the distributed actor is local instance. /// /// The `Self` passed to the the body closure is isolated, meaning that the /// closure can be used to call non-distributed functions, or even access actor /// state. /// /// When the actor is remote, the closure won't be executed and this function will return nil. public nonisolated func whenLocal<T>(_ body: @Sendable (isolated Self) async throws -> T) async rethrows -> T? where T: Sendable { if __isLocalActor(self) { return try await body(self) } else { return nil } } } /******************************************************************************/ /***************************** Actor Identity *********************************/ /******************************************************************************/ /// Uniquely identifies a distributed actor, and enables sending messages and identifying remote actors. @available(SwiftStdlib 5.5, *) public protocol ActorIdentity: Sendable, Hashable, Codable {} @available(SwiftStdlib 5.5, *) public struct AnyActorIdentity: ActorIdentity, @unchecked Sendable, CustomStringConvertible { public let underlying: Any @usableFromInline let _hashInto: (inout Hasher) -> () @usableFromInline let _equalTo: (Any) -> Bool @usableFromInline let _encodeTo: (Encoder) throws -> () @usableFromInline let _description: () -> String public init<ID>(_ identity: ID) where ID: ActorIdentity { self.underlying = identity _hashInto = { hasher in identity .hash(into: &hasher) } _equalTo = { other in guard let otherAnyIdentity = other as? AnyActorIdentity else { return false } guard let rhs = otherAnyIdentity.underlying as? ID else { return false } return identity == rhs } _encodeTo = { encoder in try identity.encode(to: encoder) } _description = { () in "\(identity)" } } public init(from decoder: Decoder) throws { let userInfoTransport = decoder.userInfo[.actorTransportKey] guard let transport = userInfoTransport as? ActorTransport else { throw DistributedActorCodingError(message: "ActorTransport not available under the decoder.userInfo") } self = try transport.decodeIdentity(from: decoder) } public func encode(to encoder: Encoder) throws { try _encodeTo(encoder) } public var description: String { "\(Self.self)(\(self._description()))" } public func hash(into hasher: inout Hasher) { _hashInto(&hasher) } public static func == (lhs: AnyActorIdentity, rhs: AnyActorIdentity) -> Bool { lhs._equalTo(rhs) } } /******************************************************************************/ /******************************** Misc ****************************************/ /******************************************************************************/ /// Error protocol to which errors thrown by any `ActorTransport` should conform. @available(SwiftStdlib 5.5, *) public protocol ActorTransportError: Error { } @available(SwiftStdlib 5.5, *) public struct DistributedActorCodingError: ActorTransportError { public let message: String public init(message: String) { self.message = message } public static func missingTransportUserInfo<Act>(_ actorType: Act.Type) -> Self where Act: DistributedActor { .init(message: "Missing ActorTransport userInfo while decoding") } } /******************************************************************************/ /************************* Runtime Functions **********************************/ /******************************************************************************/ // ==== isRemote / isLocal ----------------------------------------------------- @_silgen_name("swift_distributed_actor_is_remote") func __isRemoteActor(_ actor: AnyObject) -> Bool func __isLocalActor(_ actor: AnyObject) -> Bool { return !__isRemoteActor(actor) } // ==== Proxy Actor lifecycle -------------------------------------------------- @_silgen_name("swift_distributedActor_remote_initialize") func _distributedActorRemoteInitialize(_ actorType: Builtin.RawPointer) -> Any /// Called to destroy the default actor instance in an actor. /// The implementation will call this within the actor's deinit. /// /// This will call `actorTransport.resignIdentity(self.id)`. @_silgen_name("swift_distributedActor_destroy") func _distributedActorDestroy(_ actor: AnyObject)
38.059289
132
0.624883
abfdbdcf2f2e987e861b256c9f18f6b850fec536
187
// // FeedLoadingViewModel.swift // EDNLearn // // Created by Pankaj Mangotra on 25/11/21. // import Foundation public struct FeedLoadingViewModel { public let isLoading: Bool }
14.384615
43
0.716578
90785c4d8339e58974f34af0549c0d94d973776d
212
// // ActivityView.swift // spendsterIOS // // Created by Dmytro Holovko on 5/21/19. // Copyright © 2019 KeyToTech. All rights reserved. // import Foundation protocol ActivityView { func reloadData() }
15.142857
52
0.693396
f9b53ff144f4a338029c1622027bc2e523019e9e
227
// // Screen.swift // Sonar // // Created by NHSX on 03/04/2020. // Copyright © 2020 NHSX. All rights reserved. // import Foundation enum Screen: String, Codable { // Flows case onboarding case status }
12.611111
47
0.621145
1a2f908961a1c82ae7a9d1e1097a74819298321a
10,183
// // HomeController.swift // U17Demo // // Created by zainguo on 2020/7/15. // Copyright © 2020 zainguo. All rights reserved. // import UIKit import LLCycleScrollView class HomeController: BaseViewController { private var galleryItems = [GalleryItems]() private var textItems = [TextItems]() private var modules = [Modules]() private var defaultSrarch: String? private lazy var navView: FindNavView = { FindNavView() }() var style: UIStatusBarStyle = .lightContent // 重写statusBar相关方法 override var preferredStatusBarStyle: UIStatusBarStyle { return self.style } lazy var bannerView: LLCycleScrollView = { let banner = LLCycleScrollView() banner.backgroundColor = backgroundColor banner.autoScrollTimeInterval = 6 banner.placeHolderImage = UIImage(named: "normal_placeholder_h") banner.coverImage = UIImage(named: "normal_placeholder_h") banner.pageControlBottom = 20 banner.titleBackgroundColor = .clear banner.customPageControlStyle = .image banner.pageControlPosition = .left banner.pageControlActiveImage = UIImage(named: "finishobj") // 点击item回调 banner.lldidSelectItemAtIndex = didSelectBanner(index:) return banner }() lazy var collectionView: UICollectionView = { let layout = UCollectionViewSectionBackgroundLayout() layout.minimumInteritemSpacing = 5; layout.minimumLineSpacing = 10 let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.backgroundColor = .white collectionView.dataSource = self collectionView.delegate = self collectionView.alwaysBounceVertical = true collectionView.contentInset = UIEdgeInsets(top: screenHeight/2.0, left: 0, bottom: 0, right: 0) collectionView.scrollIndicatorInsets = collectionView.contentInset collectionView.register(cellType: ComicCollectionViewCell.self) collectionView.register(cellType: BoardCollectionViewCell.self) collectionView.register(supplementaryViewType: ComicCollectionHeaderView.self, ofKind: UICollectionView.elementKindSectionHeader) collectionView.register(supplementaryViewType: ComicCollectionFooterView.self, ofKind: UICollectionView.elementKindSectionFooter) // 刷新控件 collectionView.uHead = URefreshHeader { [weak self] in self?.setupLoadData() } collectionView.uFood = URefreshDiscoverFooter() collectionView.uempty = UEmptyView(verticalOffset: -(collectionView.contentInset.top)) { self.setupLoadData() } return collectionView }() override func viewDidLoad() { super.viewDidLoad() setupLoadData() } override func viewWillAppear(_ animated: Bool) { navigationController?.navigationBar.isHidden = true } override func setupLayout() { view.addSubview(collectionView) collectionView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } view.addSubview(bannerView) bannerView.snp.makeConstraints { (make) in make.top.left.right.equalToSuperview() make.height.equalTo(collectionView.contentInset.top) } view.addSubview(navView) navView.snp.makeConstraints { (make) in make.top.left.right.equalToSuperview() make.height.equalTo(120) } } } extension HomeController { private func didSelectBanner(index: NSInteger) { print("轮播图被点击了...") if galleryItems.count <= 0 { return } let item = galleryItems[index] if item.linkType == 3 { guard let comicId = item.ext?.first?.val else { return } // let vc = ComicIntroController() // vc.comicId = comicId let storyboard = UIStoryboard(name: "ComicIntroVC", bundle: nil) let cimicIntroVC = storyboard.instantiateViewController(withIdentifier: "ComicIntroVC") as! ComicIntroVC cimicIntroVC.comicId = Int(comicId) navigationController?.pushViewController(cimicIntroVC, animated: true) } } private func setupLoadData() { ApiLoadingProvider.request(Api.findHome, model: HomeDatasModel.self) { [weak self] (returnData) in self?.galleryItems = returnData?.galleryItems ?? [] self?.textItems = returnData?.textItems ?? [] self?.modules = returnData?.modules ?? [] self?.collectionView.uHead.endRefreshing() self?.collectionView.uempty?.allowShow = true self?.collectionView.reloadData() self?.bannerView.imagePaths = self?.galleryItems.filter { $0.cover != nil}.map {$0.cover!} ?? [] self?.defaultSrarch = returnData?.defaultSearch self?.navView.defaultSearch = self?.defaultSrarch } } } extension HomeController: UICollectionViewDataSource, UICollectionViewDelegate, UCollectionViewSectionBackgroundLayoutDelegateLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let model = modules[section] return model.items?.count ?? 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let model = modules[indexPath.section] let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: ComicCollectionViewCell.self) cell.model = model.items?[indexPath.item].first cell.cellStyle = .withTitleAndDesc return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let model = modules[indexPath.section] let comicModel = model.items?[indexPath.item].first let storyboard = UIStoryboard(name: "ComicIntroVC", bundle: nil) let cimicIntroVC = storyboard.instantiateViewController(withIdentifier: "ComicIntroVC") as! ComicIntroVC cimicIntroVC.comicId = comicModel?.comicId ?? 0 navigationController?.pushViewController(cimicIntroVC, animated: true) } func numberOfSections(in collectionView: UICollectionView) -> Int { modules.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor { .white } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) } // 头尾视图 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionView.elementKindSectionHeader { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, for: indexPath, viewType: ComicCollectionHeaderView.self) let model = modules[indexPath.section] header.iconView.yx_setImage(model.moduleInfo?.icon) header.titleLabel.text = model.moduleInfo?.title header.moreActionClosure { [weak self] in kLog("222222") } return header } else { let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, for: indexPath, viewType: ComicCollectionFooterView.self) footer.backgroundColor = backgroundColor return footer } } // 头部高度 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { CGSize(width: screenWidth, height: 50) } // 尾部高度 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return modules.count - 1 != section ? CGSize(width: screenWidth, height: 10) : CGSize.zero } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let model = modules[indexPath.section] switch model.items?.count { case 4: let width = floor(Double(screenWidth - 30.0) / 2.0) return CGSize(width: width, height: width * 0.85) case 5: if indexPath.row == 0 { let width = floor(Double(screenWidth - 30.0) / 3.0) return CGSize(width: width * 2, height: width * 1.75) } let width = floor(Double(screenWidth - 30.0) / 3.0) return CGSize(width: width, height: width * 1.75) case 3, 6: let width = floor(Double(screenWidth - 30.0) / 3.0) return CGSize(width: width, height: width * 1.75) default: let width = floor(Double(screenWidth - 30.0) / 3.0) return CGSize(width: width, height: width * 1.75) } } } extension HomeController { func scrollViewDidScroll(_ scrollView: UIScrollView) { navView.value = scrollView.contentOffset.y if scrollView.contentOffset.y >= -200 { self.style = .default } else { self.style = .lightContent } setNeedsStatusBarAppearanceUpdate() if scrollView == collectionView { bannerView.snp.updateConstraints { (make) in make.top.equalToSuperview().offset(min(0, -(scrollView.contentOffset.y + scrollView.contentInset.top))) } } } }
40.895582
181
0.656192
2050acdc6b3308ca55c4511fdec7e96966a591a1
711
import XCTest class AppForDevelopNativeModulesUITestsLaunchTests: 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) } }
26.333333
88
0.679325
4803e15939de45e3b68dfa0c738bfcc6b79d2fc7
2,676
// // Created by Dmitry Gorin on 04.05.2020. // Copyright (c) 2020 gordiig. All rights reserved. // import Foundation import UIKit import Combine class PlaceGetter { typealias ApiError = PlaceRequester.ApiError typealias Entity = Place typealias Completion = ((Entity?, ApiError?) -> Void)? typealias CompletionList = (([Entity]?, ApiError?) -> Void)? private var entitySubscriber: AnyCancellable? private var entitiesSubscriber: AnyCancellable? private var acceptSubscriber: AnyCancellable? deinit { cancel() } func cancel() { entitySubscriber?.cancel() entitiesSubscriber?.cancel() } func getPlace(_ id: Entity.ID, completion: Completion = nil) { entitySubscriber = Entity.manager.fetch(id: id) .sink(receiveCompletion: { c in switch c { case .failure(let err): self.getEntityFailure(err, completion) case .finished: break } }, receiveValue: { entity in self.getEntitySuccess(entity, completion) }) } func getPlaces(search: String, onlyMine: Bool? = nil, withDeleted: Bool? = nil, completion: CompletionList = nil) { entitiesSubscriber = PlaceRequester().searchByName(search, onlyMine: onlyMine, deletedFlg: withDeleted) .sink(receiveCompletion: { c in switch c { case .failure(let err): self.getEntitiesFailure(err, completion) case .finished: break } }, receiveValue: { entities in self.getEntitiesSuccess(entities, completion) }) } func getAccept(place: Place) { acceptSubscriber = AcceptRequester().getForPlace(place) .sink(receiveCompletion: { completion in }, receiveValue: { entities in entities.forEach { Accept.manager.addLocaly($0) } }) } private func getEntitySuccess(_ entity: Entity, _ completion: Completion) { Entity.manager.replace(entity, with: entity) getAccept(place: entity) completion?(entity, nil) } private func getEntityFailure(_ err: ApiError, _ completion: Completion) { completion?(nil, err) } private func getEntitiesSuccess(_ entities: [Entity], _ completion: CompletionList) { entities.forEach { Entity.manager.addLocaly($0) } completion?(entities, nil) } private func getEntitiesFailure(_ err: ApiError, _ completion: CompletionList) { completion?(nil, err) } }
31.482353
119
0.600897
0828c332588da4b2eefb44fe74c2a2374ab4247b
2,678
// // MacroDefinition.swift // TodayNews // // Created by shi_mhua on 2019/7/9. // Copyright © 2019 chisalsoft. All rights reserved. // import Foundation import UIKit /** * 网络相关 * 外网:skey: iOS20190621UUY8HDO0S1@Bob 测试: testSkey */ let apskey = "testSkey" let SUCCESS = "success" let interfaceVersion = "interfaceVersion" /** * 系统相关 */ // 屏幕高度 let SCREEN_WIDTH = UIScreen.main.bounds.size.width // 屏幕宽度 let SCREEN_HEIGHT = UIScreen.main.bounds.size.height // 系统版本 let IOS_VERSION = Float(UIDevice.current.systemVersion) //颜色值 extension UIColor { convenience init(r red:CGFloat, g green:CGFloat, b blue:CGFloat, a alpha: CGFloat = 1.0) { if #available(iOS 10.0, *) { self.init(displayP3Red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha) //该方法能提升性能 } else { self.init(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha) } } } /// 默认颜色值 let DefaultColor = UIColor(r: 247, g: 247, b: 247) // //public func RGBColor(r red:CGFloat, g green:CGFloat, b blue:CGFloat) -> UIColor { // return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1.0) //} // ////@available(iOS 10.0, *) if #available(iOS 10.0, *) //public func RGBColor(r red:CGFloat, g green:CGFloat, b blue:CGFloat, a alpha:CGFloat) -> UIColor { // return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1.0) //} /** * 适配 相关 */ // 判断是iPhoneX 的宏 let is_iPhoneX = (SCREEN_HEIGHT >= 812.0) ? true : false // 判断是 小屏 的宏 (iPhone 5\SE) let is_iPhoneMin = (SCREEN_HEIGHT <= 568.0) ? true : false // 顶部和底部安全区域宏 let SafeAreaTopHeight: CGFloat = (SCREEN_HEIGHT >= 812.0) ? 88.0 : 64.0 let SafeAreaBottomHeight: CGFloat = (SCREEN_HEIGHT >= 812.0) ? 34.0 : 0 // 状态栏高度 let TopStatuBarHeight: CGFloat = (SCREEN_HEIGHT >= 812.0) ? 44.0 : 20.0 // iPhone X系列机型导航栏多出高度 let MoreNavigationBarHeight: CGFloat = (SCREEN_HEIGHT >= 812.0) ? 24.0 : 0 // 高度比例(原值4.7英寸iPhone6、S系列) let HeightRatio = ((SCREEN_HEIGHT <= 736.0 ? SCREEN_HEIGHT : (SCREEN_HEIGHT == 896.0 ? 736.0 : 667.0) ) / 667.0) // 宽度比例(原值4.7英寸iPhone6、S系列) let WidthRatio = SCREEN_WIDTH / 375.0 /// 全局函数自定义输出 优化性能 //func DPrint(_ item: @autoclosure () -> Any) { // //https://www.jianshu.com/p/ba7701fa194a // #if DEBUG // print(item()) // #endif //} // 使用DPrint好处之一: 系统的print打印需要表达式或值为非可选类型,所有会有烦人的警告,消除需要 as 或 , 而DPrint没有 func DPrint<T>(_ message: T, file: String = #file , line: Int = #line) { //https://www.jianshu.com/p/e7219f0f5ac7 //如果DEBUG存在,就说明是在项目调试下运行程序 #if DEBUG let fileName = (file as NSString).lastPathComponent print("\(fileName) : [\(line)] - \(message)") #endif }
28.795699
112
0.65534
5bed10134a26a0eaafd13f6c80ea2ace0f262866
1,080
// // AppError.swift // FrameIOFoundation // // Created by Vlad Z. on 1/14/20. // Copyright © 2020 Vlad Z. All rights reserved. // public protocol AppError: Error { var description: String { get } } /// Common applicatin errors. public enum ApplicationError: AppError { case commonError, noResultsError, apiError(type: ApiErrorType) public var description: String { switch self { case .commonError: return "Common error" case .noResultsError: return "No results" case .apiError(let apiError): return apiError.description } } } /// Errors, which can occur while working with API. public enum ApiErrorType: AppError { case commonError, serverError, parseError, responseError(error: String?) public var description: String { switch self { case .commonError: return "Common API error" case .parseError: return "Parse Error" case let .responseError(error): return "Response Error: \(error ?? "unknown")" case .serverError: return "Server Error" } } }
27
86
0.658333
c1273c6976d3d6bd58d72e7360059b7e7e06077d
1,172
// Aurora framework for Swift // // The **Aurora.framework** contains a base for your project. // // It has a lot of extensions built-in to make development easier. // // - Version: 1.0 // - Copyright: [Wesley de Groot](https://wesleydegroot.nl) ([WDGWV](https://wdgwv.com))\ // and [Contributors](https://github.com/AuroraFramework/Aurora.swift/graphs/contributors). // // Thanks for using! // // Licence: MIT import Foundation #if canImport(UIKit) && !os(watchOS) && !os(tvOS) import UIKit import QuartzCore @IBDesignable open class UIViewRounded: UIView { /// Radius for the UIViewRounded @IBInspectable public var radius: CGFloat = 24 /// Draw a rounded view /// - Parameter rect: The portion of the view’s bounds that needs to be updated.\ /// The first time your view is drawn, this rectangle is typically the entire visible bounds of your view.\ /// However, during subsequent drawing operations, the rectangle may specify only part of your view. override public func draw(_ rect: CGRect) { super.draw(rect) self.roundCorners( corners: [.allCorners], radius: radius ) } } #endif
29.3
111
0.678328
f777f48c156f27f62955bd6b10325e2ffe595f57
797
// // SaveFavoriteRequestModel.swift // BaseProject // // Created by Cüneyt AYVAZ on 8.07.2019. // Copyright © 2019 OtiHolding. All rights reserved. // import Foundation import ObjectMapper public class SaveFavoriteRequestModel: Mappable { public var destinationId: Int! public var customerId: Int! public var excursionId: Int! public required init?(map: Map) { } public init(customerId: Int?, destinationId: Int?, excursionId: Int?) { self.customerId = customerId self.destinationId = destinationId self.excursionId = excursionId } public func mapping(map: Map) { customerId <- map["CustomerId"] destinationId <- map["DestinationId"] excursionId <- map["ExcursionId"] } }
22.771429
75
0.643664
e8c7f973d68ca9c535500dae5fe5b55e08b2d172
292
// // UIviewController+TaxesCalculator.swift // comprasUSA // // Created by Guilherme Santos on 09/05/19. // Copyright © 2019 Guilherme Santos. All rights reserved. // import UIKit extension UIViewController { var tc: TaxesCalculator { return TaxesCalculator.shared } }
18.25
59
0.705479
89cec6776adefabe821b600e063da14c16e5fb11
1,265
// // Tip_CalculatorUITests.swift // Tip_CalculatorUITests // // Created by rohit sriram on 12/22/18. // Copyright © 2018 rohit sriram. All rights reserved. // import XCTest class Tip_CalculatorUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.189189
182
0.667984
725c50efb2f4e48190b13b3331c295f75db30b83
1,618
// // Web3Provider.swift // Web3 // // Created by Koray Koska on 30.12.17. // Copyright © 2018 Boilertalk. All rights reserved. // import Foundation import Ethereum public protocol DataProvider { func send(data: Data, response: @escaping(Swift.Result<Data, Error>) -> Void) } public enum ProviderError: Swift.Error { case emptyResponse case requestFailed(Swift.Error?) case connectionFailed(Swift.Error?) case serverError(Swift.Error?) case signProviderError(SignProviderError) case rpcError(RPCError) case decodingError(Swift.Error?) } public protocol Provider { typealias Response<R: Codable> = Swift.Result<R, ProviderError> typealias Completion<R: Codable> = (Response<R>) -> Void var dataProvider: DataProvider { get } func send<Params, Result>(request: RPCRequest<Params>, response: @escaping Completion<Result>) } extension Provider where Self: DataProvider { public var dataProvider: DataProvider { return self } } public protocol InjectedProvider: Provider { var provider: Provider { get } } extension InjectedProvider { public var dataProvider: DataProvider { return provider.dataProvider } } extension Swift.Result where Failure == ProviderError, Success: Codable { public init(rpcResponse: RPCResponse<Success>) { if let result = rpcResponse.result { self = .success(result) } else if let error = rpcResponse.error { self = .failure(ProviderError.rpcError(error)) } else { self = .failure(ProviderError.emptyResponse) } } }
26.096774
98
0.686032
232fcbe159f59b40de1aa998921d29ee3986441a
1,089
// // TouchIDSettingTableViewCell.swift // Throttle // // Created by Kaitlyn Lee on 3/20/16. // Copyright © 2016 Gigster. All rights reserved. // import UIKit class TouchIDSettingTableViewCell: UITableViewCell { @IBOutlet weak var enableTouchIDSwitch: UISwitch! override func awakeFromNib() { super.awakeFromNib() // Initialization code } @IBAction func switchToggled(sender: AnyObject) { if (self.enableTouchIDSwitch.on) { dispatch_async(dispatch_get_main_queue(), { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName("enableTouchIDNotification", object: nil) }); } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName("disableTouchIDNotification", object: nil) }); } } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
25.325581
108
0.657484
f81bb8e9845933952ccb632a731d1ac614f8e0a6
1,860
// // DatabaseConverterTests.swift // UserslistDBTests // // Created by Чайка on 2018/07/10. // Copyright © 2018 Чайка. All rights reserved. // import XCTest class DatabaseConverterTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test01_convert() { do { let converter: DatabaseConverter = try DatabaseConverter(databasePath: "~/Library/Application Support/Charleston") let success = converter.parse() XCTAssertTrue(success, "parser parse fail") if success { let result: Bool = converter.writeJson() XCTAssertTrue(result, "write test jaon failed") }// end if } catch { XCTFail("database can not read") } } func test02_decode() { let usersListUFolderURL: URL = URL(fileURLWithPath: (NSHomeDirectory() + "/Library/Application Support/Charleston"), isDirectory: true) let usersListJSonURL: URL = usersListUFolderURL.appendingPathComponent("userslist").appendingPathExtension("json") let decoder: JSONDecoder = JSONDecoder() do { let data: Data = try Data(contentsOf: usersListJSonURL, options: Data.ReadingOptions.uncachedRead) let allUsers: JSONizableAllUsers = try decoder.decode(JSONizableAllUsers.self, from: data) XCTAssertNotNil(allUsers, "all user decode from json file is incorrect") } catch let error { XCTAssertNil(error, "\(error.localizedDescription)") } } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
32.068966
137
0.698387
f97ec00eb2f93e9141e264f507fb5cb6d2cc2097
1,393
// // CompleteProfileVC.swift // BaseProject // // Copyright © 2018 Wave. All rights reserved. // import UIKit class CompleteProfileVC: BaseViewController { override func viewDidLoad() { super.viewDidLoad() self.tabBarController?.tabBar.isHidden = true // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func get_free_budz_map(_ sender: Any) { let move = self.GetView(nameViewController: "NewBudzMapViewController", nameStoryBoard: "Main") as! NewBudzMapViewController move.afterCompleting = 1 self.navigationController?.pushViewController(move, animated: true) } @IBAction func view_reward_section(_ sender: Any) { let rewards_vc = self.GetView(nameViewController: "MyRewardsVC", nameStoryBoard: "Rewards") as! MyRewardsVC rewards_vc.afterCompleting = 1 self.navigationController?.pushViewController(rewards_vc, animated: true) } @IBAction func view_my_profile(_ sender: Any) { self.afterCompletionBase = 1 self.OpenProfileVC(id: (DataManager.sharedInstance.getPermanentlySavedUser()?.ID)!) } @IBAction func Remember_Me(_ sender: Any) { self.ShowMenuBaseView() } }
30.955556
132
0.687724
1e85fb7ec10370a8fd0ae713c994e23ed198ad06
1,427
// // CalendarPickerViewModel.swift // Calendr // // Created by Paker on 14/01/21. // import Foundation import RxSwift import RxRelay class CalendarPickerViewModel { // Observers let toggleCalendar: AnyObserver<String> // Observables let calendars: Observable<[CalendarModel]> let enabledCalendars: Observable<[String]> init(calendarService: CalendarServiceProviding, userDefaults: UserDefaults) { self.calendars = calendarService.changeObservable .flatMapLatest(calendarService.calendars) .share(replay: 1) let toggleCalendarSubject = PublishRelay<String>() self.toggleCalendar = toggleCalendarSubject.asObserver() self.enabledCalendars = calendars.map { calendars in { userDefaults .stringArray(forKey: Prefs.enabledCalendars)? .filter($0.contains) ?? $0 }(calendars.map(\.identifier)) } .flatMapLatest { initial in toggleCalendarSubject.scan(initial) { identifiers, toggled in identifiers.contains(toggled) ? identifiers.filter { $0 != toggled } : identifiers + [toggled] } .startWith(initial) } .do(onNext: { userDefaults.setValue($0, forKey: Prefs.enabledCalendars) }) .share(replay: 1) } }
25.945455
81
0.602663
acaf5b32481099830b2575738796f50f7b21a7a5
5,568
// // Menu.swift // RSwitch // // Created by hrbrmstr on 8/24/19. // Copyright © 2019 Bob Rudis. All rights reserved. // import Foundation import Cocoa extension AppDelegate: NSMenuDelegate { @objc func toggle_dock_icon(_ sender: NSMenuItem) { Preferences.showDockIcon = !Preferences.showDockIcon DockIcon.standard.setVisibility(Preferences.showDockIcon) if let menu = statusItem.menu, let item = menu.item(withTag: 99) { item.state = Preferences.showDockIcon.stateValue } } @objc func toggle_hourly_rstudio_check(_ sender: NSMenuItem) { Preferences.hourlyRStudioCheck = !Preferences.hourlyRStudioCheck if (Preferences.hourlyRStudioCheck) { performRStudioCheck(sender) } if let menu = statusItem.menu, let item = menu.item(withTag: 98) { item.state = Preferences.hourlyRStudioCheck.stateValue } } @objc func toggle_ensure_file_handlers(_ sender: NSMenuItem) { Preferences.ensureFileHandlers = !Preferences.ensureFileHandlers if (Preferences.ensureFileHandlers) { FileAssociationUtils.setHandlers() } if let menu = statusItem.menu, let item = menu.item(withTag: 98) { item.state = Preferences.ensureFileHandlers.stateValue } } @objc func subscribeToMailingList(_ sender: NSMenuItem) { NSWorkspace.shared.open(URL(string: "https://lists.sr.ht/~hrbrmstr/rswitch")!) } func menuWillOpen(_ menu: NSMenu) { if (menu != self.statusMenu) { return } // clear the menu menu.removeAllItems() // add selection to open frameworks dir in Finder menu.addItem(NSMenuItem(title: "Open R Frameworks Directory", action: #selector(openFrameworksDir), keyEquivalent: "")) menu.addItem(NSMenuItem.separator()) menu.addItem(NSMenuItem(title: "Current R Version:", action: nil, keyEquivalent: "")) // populate installed versions RVersions.populateRVersionsMenu(menu: menu, handler: #selector(handleRSwitch)) // Add items to download latest r-devel tarball and latest macOS daily menu.addItem(NSMenuItem.separator()) let rdevelItem = NSMenuItem(title: NSLocalizedString("Download latest R-devel tarball", comment: "Download latest tarball item"), action: self.rdevel_enabled ? #selector(download_latest_tarball) : nil, keyEquivalent: "") rdevelItem.isEnabled = self.rdevel_enabled menu.addItem(rdevelItem) let rstudioItem = NSMenuItem(title: NSLocalizedString("Download latest RStudio daily build", comment: "Download latest RStudio item"), action: self.rstudio_enabled ? #selector(download_latest_rstudio) : nil, keyEquivalent: "") rstudioItem.isEnabled = self.rstudio_enabled menu.addItem(rstudioItem) menu.addItem(NSMenuItem.separator()) let refsDropdown = NSMenuItem(title: "Reference Desk", action: nil, keyEquivalent: "") let refsSub = NSMenu() menu.addItem(refsDropdown) menu.setSubmenu(refsSub, for: refsDropdown) // Add items to open various R for macOS pages BrowseMenuAction.populateWebItems(menu: refsSub) menu.addItem(NSMenuItem.separator()) // Add links to local copies of the R Manuals BrowseMenuAction.populateLocalRManualsItems(menu: refsSub) // Add links to free R online books BrowseMenuAction.populateRBooksItems(menu: refsSub) // Add running apps populateRunningApps(menu: menu) // Add launchers AppMenuAction.populateLaunchers(menu: menu) RStudioServerMenuAction.populateRStudioServerSessions(menu: menu, manager: sess) menu.addItem(NSMenuItem.separator()) // Toggle Dock Icon menu.addItem(NSMenuItem.separator()) let prefsDropdown = NSMenuItem(title: "Preferences", action: nil, keyEquivalent: "") let prefSub = NSMenu() menu.addItem(prefsDropdown) menu.setSubmenu(prefSub, for: prefsDropdown) let dockItem = NSMenuItem(title: "Show Dock Icon", action: #selector(toggle_dock_icon), keyEquivalent: "") dockItem.tag = 99 dockItem.target = self dockItem.state = Preferences.showDockIcon.stateValue prefSub.addItem(dockItem) let rstudioCheckItem = NSMenuItem(title: "Notify me when a new RStudio Daily is available", action: #selector(toggle_hourly_rstudio_check), keyEquivalent: "") rstudioCheckItem.tag = 98 rstudioCheckItem.target = self rstudioCheckItem.state = Preferences.hourlyRStudioCheck.stateValue prefSub.addItem(rstudioCheckItem) let fileHandlersCheckItem = NSMenuItem(title: "Ensure RStudio opens R/Rmd files", action: #selector(toggle_ensure_file_handlers), keyEquivalent: "") fileHandlersCheckItem.tag = 97 fileHandlersCheckItem.target = self fileHandlersCheckItem.state = Preferences.ensureFileHandlers.stateValue prefSub.addItem(fileHandlersCheckItem) menu.addItem(NSMenuItem(title: "Check for update…", action: #selector(checkForUpdate), keyEquivalent: "")) menu.addItem(NSMenuItem(title: "Subscribe to mailing list…", action: #selector(subscribeToMailingList), keyEquivalent: "")) menu.addItem(NSMenuItem(title: "About RSwitch…", action: #selector(showAbout), keyEquivalent: "")) menu.addItem(NSMenuItem(title: "RSwitch Help…", action: #selector(rswitch_help), keyEquivalent: "")) // Add a Quit item menu.addItem(NSMenuItem.separator()) let quitItem = NSMenuItem(title: "Quit", action: #selector(NSApp.terminate), keyEquivalent: "q") quitItem.keyEquivalentModifierMask = NSEvent.ModifierFlags.option menu.addItem(quitItem) } }
37.12
230
0.721444
c1b99154300c95e95da19fd40ff5417768850697
619
// // Fact.swift // HistoryBlam // // Created by Brittany Shimshock on 4/18/16. // Copyright © 2016 Brittany Shimshock. All rights reserved. // import Foundation class Fact { var info : String? var dateKey : String? var year : String? var numberOfResources : Int? //wikipedia searching //remember that these are 0 indexed! like ["photoSearchURL0" : URL] ["resourceEndpoint0" : ""] var resourceEndpoints = [String : String]() var photoSearchURLs = [String : NSURL]() var photoURL : NSURL? var photoTag : String? var photoWikipediaURL : NSURL? }
19.34375
99
0.636511
fcffc56492bc8edf3cd8fcc794af71c73fae1f0c
503
// // ColorView.swift // UIGridView // // Created by Cao Phuoc Thanh on 11/28/20. // Copyright © 2020 Cao Phuoc Thanh. All rights reserved. // import UIKit extension CGFloat { static func random() -> CGFloat { return CGFloat(arc4random()) / CGFloat(UInt32.max) } } public extension UIColor { static var random: UIColor { return UIColor( red: .random(), green: .random(), blue: .random(), alpha: 1.0 ) } }
18.62963
58
0.55666
76076447cf4845c485cb676b034f592d454a0e90
2,235
// Corona-Warn-App // // SAP SE and all other contributors // copyright owners license this file to you under the Apache // License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Foundation import UIKit class AppInformationHelpViewController: UITableViewController { var model: AppInformationHelpModel! override func numberOfSections(in _: UITableView) -> Int { model.numberOfSections } override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? { model.title(for: section) } override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { model.questions(in: section).count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let question = model.question(indexPath.row, in: indexPath.section) let cell = tableView.dequeueReusableCell(withIdentifier: ReusableCellIdentifier.question.rawValue, for: indexPath) cell.textLabel?.text = question.title return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender _: Any?) { let destination = segue.destination guard let segueIdentifier = segue.identifier, let segue = SegueIdentifier(rawValue: segueIdentifier) else { return } switch segue { case .detail: (destination as? AppInformationDetailViewController)?.model = .helpTracing } } } extension AppInformationHelpViewController { enum SegueIdentifier: String { case detail = "detailSegue" } } extension AppInformationHelpViewController { fileprivate enum ReusableCellIdentifier: String { case question = "questionCell" } }
29.407895
116
0.763758
c11cf005918887b6d65c7694df5c6cd9919fae6a
7,761
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftAWSLambdaRuntime open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftAWSLambdaRuntime project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// @testable import AWSLambdaRuntime @testable import AWSLambdaRuntimeCore import Logging import NIOCore import NIOFoundationCompat import NIOPosix import XCTest class CodableLambdaTest: XCTestCase { var eventLoopGroup: EventLoopGroup! let allocator = ByteBufferAllocator() override func setUp() { self.eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) } override func tearDown() { XCTAssertNoThrow(try self.eventLoopGroup.syncShutdownGracefully()) } func testCodableVoidEventLoopFutureHandler() { let request = Request(requestId: UUID().uuidString) var inputBuffer: ByteBuffer? var outputBuffer: ByteBuffer? struct Handler: EventLoopLambdaHandler { typealias Event = Request typealias Output = Void var expected: Request? static func makeHandler(context: Lambda.InitializationContext) -> EventLoopFuture<Handler> { context.eventLoop.makeSucceededFuture(Handler()) } func handle(_ event: Request, context: LambdaContext) -> EventLoopFuture<Void> { XCTAssertEqual(event, self.expected) return context.eventLoop.makeSucceededVoidFuture() } } let handler = Handler(expected: request) XCTAssertNoThrow(inputBuffer = try JSONEncoder().encode(request, using: self.allocator)) XCTAssertNoThrow(outputBuffer = try handler.handle(XCTUnwrap(inputBuffer), context: self.newContext()).wait()) XCTAssertNil(outputBuffer) } func testCodableEventLoopFutureHandler() { let request = Request(requestId: UUID().uuidString) var inputBuffer: ByteBuffer? var outputBuffer: ByteBuffer? var response: Response? struct Handler: EventLoopLambdaHandler { typealias Event = Request typealias Output = Response var expected: Request? static func makeHandler(context: Lambda.InitializationContext) -> EventLoopFuture<Handler> { context.eventLoop.makeSucceededFuture(Handler()) } func handle(_ event: Request, context: LambdaContext) -> EventLoopFuture<Response> { XCTAssertEqual(event, self.expected) return context.eventLoop.makeSucceededFuture(Response(requestId: event.requestId)) } } let handler = Handler(expected: request) XCTAssertNoThrow(inputBuffer = try JSONEncoder().encode(request, using: self.allocator)) XCTAssertNoThrow(outputBuffer = try handler.handle(XCTUnwrap(inputBuffer), context: self.newContext()).wait()) XCTAssertNoThrow(response = try JSONDecoder().decode(Response.self, from: XCTUnwrap(outputBuffer))) XCTAssertEqual(response?.requestId, request.requestId) } #if compiler(>=5.5) && canImport(_Concurrency) @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) func testCodableVoidHandler() { struct Handler: LambdaHandler { typealias Event = Request typealias Output = Void var expected: Request? init(context: Lambda.InitializationContext) async throws {} func handle(_ event: Request, context: LambdaContext) async throws { XCTAssertEqual(event, self.expected) } } XCTAsyncTest { let request = Request(requestId: UUID().uuidString) var inputBuffer: ByteBuffer? var outputBuffer: ByteBuffer? var handler = try await Handler(context: self.newInitContext()) handler.expected = request XCTAssertNoThrow(inputBuffer = try JSONEncoder().encode(request, using: self.allocator)) XCTAssertNoThrow(outputBuffer = try handler.handle(XCTUnwrap(inputBuffer), context: self.newContext()).wait()) XCTAssertNil(outputBuffer) } } @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) func testCodableHandler() { struct Handler: LambdaHandler { typealias Event = Request typealias Output = Response var expected: Request? init(context: Lambda.InitializationContext) async throws {} func handle(_ event: Request, context: LambdaContext) async throws -> Response { XCTAssertEqual(event, self.expected) return Response(requestId: event.requestId) } } XCTAsyncTest { let request = Request(requestId: UUID().uuidString) var response: Response? var inputBuffer: ByteBuffer? var outputBuffer: ByteBuffer? var handler = try await Handler(context: self.newInitContext()) handler.expected = request XCTAssertNoThrow(inputBuffer = try JSONEncoder().encode(request, using: self.allocator)) XCTAssertNoThrow(outputBuffer = try handler.handle(XCTUnwrap(inputBuffer), context: self.newContext()).wait()) XCTAssertNoThrow(response = try JSONDecoder().decode(Response.self, from: XCTUnwrap(outputBuffer))) XCTAssertEqual(response?.requestId, request.requestId) } } #endif // convenience method func newContext() -> LambdaContext { LambdaContext( requestID: UUID().uuidString, traceID: "abc123", invokedFunctionARN: "aws:arn:", deadline: .now() + .seconds(3), cognitoIdentity: nil, clientContext: nil, logger: Logger(label: "test"), eventLoop: self.eventLoopGroup.next(), allocator: ByteBufferAllocator() ) } func newInitContext() -> Lambda.InitializationContext { Lambda.InitializationContext( logger: Logger(label: "test"), eventLoop: self.eventLoopGroup.next(), allocator: ByteBufferAllocator() ) } } private struct Request: Codable, Equatable { let requestId: String init(requestId: String) { self.requestId = requestId } } private struct Response: Codable, Equatable { let requestId: String init(requestId: String) { self.requestId = requestId } } #if compiler(>=5.5) && canImport(_Concurrency) // NOTE: workaround until we have async test support on linux // https://github.com/apple/swift-corelibs-xctest/pull/326 extension XCTestCase { @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) func XCTAsyncTest( expectationDescription: String = "Async operation", timeout: TimeInterval = 3, file: StaticString = #file, line: Int = #line, operation: @escaping () async throws -> Void ) { let expectation = self.expectation(description: expectationDescription) Task { do { try await operation() } catch { XCTFail("Error thrown while executing async function @ \(file):\(line): \(error)") Thread.callStackSymbols.forEach { print($0) } } expectation.fulfill() } self.wait(for: [expectation], timeout: timeout) } } #endif
35.438356
122
0.626595
f90d39f2701028131b3e0a8f467cb3cc6c4ab5c3
7,014
/* See LICENSE folder for this sample’s licensing information. Abstract: Contains the object recognition view controller for the Breakfast Finder. */ import UIKit import AVFoundation import Vision class VideoViewController: ViewController { private var detectionOverlay: CALayer! = nil @IBOutlet weak var containerResults: UIView! @IBOutlet weak var result: UILabel! // Vision parts private var requests = [VNRequest]() private var alphabet = [Character]() private var alphabetFine = [Character("e"),Character("h"), Character("n"), Character("i"), Character("f")] private var lastIndex = -1 override func viewDidLoad() { super.viewDidLoad() drawVisionRequestResults() let startingValue = Int(("a" as UnicodeScalar).value) for i in 0..<26{ if let unicode = UnicodeScalar(i + startingValue){ alphabet.append(Character(unicode)) } } alphabet.sort{$0 > $1} containerResults.layer.cornerRadius = 10.0 containerResults.layer.shadowColor = UIColor(hexString: "004B68").cgColor containerResults.layer.shadowOffset = CGSize(width: 2.0, height: 3.0) containerResults.layer.shadowRadius = 4.0 containerResults.layer.shadowOpacity = 0.4 } @discardableResult func setupVision() -> NSError? { // Setup Vision parts let error: NSError! = nil guard let modelURL = Bundle.main.url(forResource: "inception_v3_hi", withExtension: "mlmodelc") else { return NSError(domain: "VisionObjectRecognitionViewController", code: -1, userInfo: [NSLocalizedDescriptionKey: "Model file is missing"]) } do { let visionModel = try VNCoreMLModel(for: MLModel(contentsOf: modelURL)) let objectRecognition = VNCoreMLRequest(model: visionModel, completionHandler: { (request, error) in DispatchQueue.main.async(execute: { // perform all the UI updates on the main queue if let results = request.results { let featureVec = (results[0] as! VNCoreMLFeatureValueObservation).featureValue if let multiArray = featureVec.multiArrayValue{ //print(multiArray) var bestIdxSoFar = -1 var bestValue: Decimal = 0.0 for i in 0..<multiArray.count{ if multiArray[i].decimalValue > bestValue{ bestValue = multiArray[i].decimalValue bestIdxSoFar = i } } print(featureVec) if bestValue > 0.90{ print(self.alphabetFine[bestIdxSoFar]) if self.lastIndex != bestIdxSoFar{ //self.result.text?.append(self.alphabetFine[bestIdxSoFar]) self.result.text?.append(bestIdxSoFar == 0 ? "i" : "h") self.lastIndex = bestIdxSoFar } } } } }) }) objectRecognition.imageCropAndScaleOption = .centerCrop self.requests = [objectRecognition] } catch let error as NSError { print("Model loading went wrong: \(error)") } return error } func drawVisionRequestResults() { CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) detectionOverlay.sublayers = nil // remove all the old recognized objects let shapeLayer = self.createRoundedRectLayerWithBounds(CGRect(x: 0, y: 0, width: 200, height: 200)) detectionOverlay.addSublayer(shapeLayer) self.updateLayerGeometry() CATransaction.commit() } override func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { connection.videoOrientation = .portrait guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } let exifOrientation = exifOrientationFromDeviceOrientation() let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: exifOrientation, options: [:]) do { try imageRequestHandler.perform(self.requests) } catch { print(error) } } override func setupAVCapture() { super.setupAVCapture() // setup Vision parts setupLayers() updateLayerGeometry() setupVision() // start the capture startCaptureSession() } func setupLayers() { detectionOverlay = CALayer() // container layer that has all the renderings of the observations detectionOverlay.name = "DetectionOverlay" detectionOverlay.bounds = CGRect(x: 0, y: 0, width: 200, height: 200) detectionOverlay.position = CGPoint(x: rootLayer.bounds.midX, y: rootLayer.bounds.midY) rootLayer.addSublayer(detectionOverlay) } func updateLayerGeometry() { let bounds = rootLayer.bounds var scale: CGFloat scale = 1.0 CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) // rotate the layer into screen orientation and scale and mirror detectionOverlay.setAffineTransform(CGAffineTransform(rotationAngle: CGFloat(.pi / 2.0)).scaledBy(x: scale, y: -scale)) // center the layer detectionOverlay.position = CGPoint (x: bounds.midX, y: bounds.midY) CATransaction.commit() } func createRoundedRectLayerWithBounds(_ bounds: CGRect) -> CALayer { let shapeLayer = CALayer() shapeLayer.bounds = bounds shapeLayer.position = CGPoint(x: bounds.midX, y: bounds.midY) shapeLayer.name = "Found Object" shapeLayer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [0.0, 0.65, 0.91, 0.4]) shapeLayer.cornerRadius = 7 return shapeLayer } @IBAction func textToSpeech(_ sender: Any) { if let text = result.text{ let utterance = AVSpeechUtterance(string: text) utterance.voice = AVSpeechSynthesisVoice(language: "en-US") let synth = AVSpeechSynthesizer() synth.speak(utterance) } } }
39.184358
149
0.573852
f948019c56158bf374a245ffca33f3e7e9812fde
3,212
// // AppDelegate.swift // LoadingManagerExample // // Created by Lin Sheng on 2018/5/4. // Copyright © 2018年 linsheng. All rights reserved. // import UIKit import LoadingManager @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let vc = ViewController() let nav = UINavigationController(rootViewController: vc) self.window?.rootViewController = nav // config var images = [UIImage]() for i in 1..<4 { images.append(UIImage(named: "img_loading_\(i)")!) } LoadingManager.setLoadingConfig(loadingImages: images, loadingDefaultImage: UIImage(named: "img_loading_0")!, loadingBackgroundImage: nil, loadingAnimationDuration: 0.4) let title = NSAttributedString(string: "Failed", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 30)]) let content = NSAttributedString(string: "Tap to refresh", attributes: [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20)]) LoadingManager.setLoadFailedConfig(image: nil, title: title, content: content) LoadingManager.backgroundColor = .blue 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:. } }
50.1875
285
0.738792
08d70cb0d9e36315d9e7478717f6739970c9a48d
967
// // AlertViewTests.swift // AlertViewTests // // Created by Shadi on 29/03/2018. // Copyright © 2018 Shadi. All rights reserved. // import XCTest @testable import AlertView class AlertViewTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.135135
111
0.632885
894b1d1cd2051511f7ca14cf02cee5d497945ecb
29,102
// // AppDelegate.swift // MechKey // // Created by Bogdan Ryabyshchuk on 9/5/18. // Copyright © 2018 Bogdan Ryabyshchuk. All rights reserved. // import Cocoa import AVFoundation import Darwin import AppKit import Foundation @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { // MARK: App Wide Variables and Settings // Player Arrays and Sound Profiles var profile: Int = 0 let soundFiles: [[Int: (String, String)]] = [[0: ("keySoundNormDown", "keySoundNormUp"), 1: ("keySoundLargeDown", "keySoundLargeUp"), 2: ("keySoundLargeDown", "keySoundLargeUp")], [0: ("tap-set-normal-down", "tap-set-normal-up"), 1: ("tap-set-enter-down", "tap-set-enter-down"), 2: ("tap-set-enter-down", "tap-set-enter-up")], [0: ("click-set-normal-down", "click-set-normal-up"), 1: ("click-set-space-down", "click-set-space-up"), 2: ("click-set-enter-down", "click-set-enter-up")]] var players: [Int: ([AVAudioPlayer?], [AVAudioPlayer?])] = [:] var playersCurrentPlayer: [Int: (Int, Int)] = [:] var playersMax: Int = 15 // App Settings var volumeLevel:Float = 1.0 var volumeMuted:Bool = false var modKeysMuted:Bool = false var stereoWidth:Float = 0.2 var stereoWidthDefult:Float = 0.2 var keyUpSound = true var keyRandomize = false // Other Variables var menuItem:NSStatusItem? = nil // Debugging Messages var debugging = false // MARK: Start and Exit Functions func applicationDidFinishLaunching(_ notification: Notification) { // Load Settings volumeLoad() modKeyMutedLoad() stereoWidthLoad() profileLoad() keyUpSoundLoad() keyRandomizeLoad() volumeUpdate() // Create the Menu menuCreate() // Check for Permissions checkPrivecyAccess() // Add Key Listeners loadKeyListeners() } // MARK: Key Press Listeners func loadKeyListeners() { NSEvent.addGlobalMonitorForEvents(matching: NSEvent.EventTypeMask.keyDown, handler: { (event) -> Void in self.keyPressDown(event: event) }) NSEvent.addGlobalMonitorForEvents(matching: NSEvent.EventTypeMask.keyUp, handler: { (event) -> Void in self.keyPressUp(event: event) }) NSEvent.addGlobalMonitorForEvents(matching: NSEvent.EventTypeMask.flagsChanged, handler: { (event) -> Void in self.keyPressMod(event: event) }) } // Key Press Function for Normal Keys func keyPressDown(event:NSEvent){ if !volumeMuted { if !event.isARepeat { playSoundForKey(key: Int(event.keyCode), keyIsDown: true) systemMenuMessage(message: "\(event.keyCode)") } } // Some Hot Key Processing Code if modKeysPrevMask == modKeyMask["keyFunction"]! { if !event.isARepeat { // Fn+Esc Mute Keys if event.keyCode == 53 { if volumeMuted { volumeSet(vol: self.volumeLevel, muted: false) } else { volumeSet(vol: self.volumeLevel, muted: true) } } } } } func keyPressUp(event:NSEvent){ if !volumeMuted { if !event.isARepeat { playSoundForKey(key: Int(event.keyCode), keyIsDown: false) } } } // Key Press Functions for Mod Keys var modKeysPrev: [String: Bool] = ["keyShiftRight": false, "keyShiftLeft": false, "keyAltLeft": false, "keyAltRight": false, "keyCMDLeft": false, "keyCMDRight": false, "keyControl": false, "keyFunction": false] var modKeysPrevMask: UInt = 0 let modKeyMask: [String: UInt] = ["keyShiftRight": 0b000000100000000100000100, "keyShiftLeft": 0b000000100000000100000010, "keyAltLeft": 0b000010000000000100100000, "keyAltRight": 0b000010000000000101000000, "keyCMDLeft": 0b000100000000000100001000, "keyCMDRight": 0b000100000000000100010000, "keyControl": 0b000001000000000100000001, "keyFunction": 0b100000000000000100000000] var modKeysPrevEvent: NSDate = NSDate() func keyPressMod(event:NSEvent){ // Record Event Time Interval Since Last let timeSinceLastModKeyEvent = modKeysPrevEvent.timeIntervalSinceNow self.modKeysPrevEvent = NSDate() let prevEventNotTooClose: Bool = (timeSinceLastModKeyEvent <= -0.045) if self.debugging { if prevEventNotTooClose { systemMenuMessage(message: "Too Close") } else { systemMenuMessage(message: "Not Too Close") } } // Grab the Current Mod Key Mask let bitmask = event.modifierFlags.rawValue // Key Maps for the Keys var modKeysCodes: [String: Int] = ["keyShiftRight": 60, "keyShiftLeft": 57, "keyAltLeft": 58, "keyAltRight": 61, "keyCMDLeft": 55, "keyCMDRight": 555, // Not the actual Key code. Used to Diff left from right. "keyControl": 59, "keyFunction": 63] // Create New Key Press Array var modKeysCurrent: [String: Bool] = ["keyShiftRight": false, "keyShiftLeft": false, "keyAltLeft": false, "keyAltRight": false, "keyCMDLeft": false, "keyCMDRight": false, "keyControl": false, "keyFunction": false] // Create New Mod Key Array and See Which Key was Pressed or Released for (key, _) in self.modKeysPrev { modKeysCurrent[key] = (bitmask & modKeyMask[key]! == modKeyMask[key]) if modKeysCurrent[key] != self.modKeysPrev[key] && !self.modKeysMuted && !self.volumeMuted && prevEventNotTooClose { if let keyWasDown = self.modKeysPrev[key] { if keyWasDown { // Key was Released playSoundForKey(key: modKeysCodes[key]!, keyIsDown: false) systemMenuMessage(message: "\(key) Up") } else { // Key was Pressed playSoundForKey(key: modKeysCodes[key]!, keyIsDown: true) systemMenuMessage(message: "\(key) Down") } } } } // Now Let's Update the Stored Key Mask self.modKeysPrev = modKeysCurrent self.modKeysPrevMask = bitmask } // MARK: Key Sound Function // The Map of All the Keys with Location and Sound to Play. // [key: [location, sound]] // The key is the numarical key, location is 0-10, 0 is left 10 is right, 5 is middle // Sounds are 0, 1, or 2 with 0 being normal key sounds, 1 being larger keys, // and all of the mod keys are 3, for a shifting like sound that I may add in the future let keyMap: [Int: Array<Int>] = [53: [0,0], 50: [0,0], 48: [0,1], 57: [0,2], 63: [0,2], 122: [1,0], 18: [1,0], 19: [1,0], 12: [1,0], 0: [1,0], 59: [1,2], 120: [2,0], 99: [2,0], 20: [2,0], 13: [2,0], 1: [2,0], 6: [2,0], 7: [2,0], 58: [2,2], 118: [3,0], 21: [3,0], 14: [3,0], 15: [3,0], 2: [3,0], 8: [3,0], 55: [3,2], 96: [4,0], 23: [4,0], 22: [4,0], 17: [4,0], 3: [4,0], 5: [4,0], 9: [4,0], 97: [5,0], 26: [5,0], 16: [5,0], 4: [5,0], 11: [5,0], 45: [5,0], 49: [5,1], 98: [6,0], 28: [6,0], 32: [6,0], 34: [6,0], 38: [6,0], 40: [6,0], 46: [6,0], 100: [7,0], 25: [7,0], 29: [7,0], 31: [7,0], 37: [7,0], 43: [7,0], 555: [7,2], 101: [8,0], 109: [8,0], 27: [8,0], 35: [8,0], 41: [8,0], 47: [8,0], 44: [8,0], 61: [8,2], 103: [9,0], 24: [9,0], 33: [9,0], 30: [9,0], 39: [9,0], 123: [9,1], 111: [10,0], 51: [10,1], 42: [10,0], 76: [10,1], 36: [10,1], 60: [10,2], 126: [10,1], 125: [10,1], 124: [10,1]] // Load an Array of Sound Players func loadSounds() { for (sound, files) in soundFiles[self.profile] { var downFiles: [AVAudioPlayer?] = [] if let soundURL = Bundle.main.url(forResource: files.0, withExtension: "wav"){ for _ in 0...self.playersMax { do { try downFiles.append( AVAudioPlayer(contentsOf: soundURL) ) } catch { print("Failed to load \(files.0)") } } } var upFiles: [AVAudioPlayer?] = [] if let soundURL = Bundle.main.url(forResource: files.1, withExtension: "wav"){ for _ in 0...self.playersMax { do { try upFiles.append( AVAudioPlayer(contentsOf: soundURL) ) } catch { print("Failed to load \(files.0)") } } } self.players[sound] = (downFiles, upFiles) self.playersCurrentPlayer[sound] = (0, 0) } // Set the Sound Level to the Settings Level volumeUpdate() } func playSoundForKey(key: Int, keyIsDown down: Bool){ var keyLocation: Float = 0 var keySound: Int = 0 if let keySetings = keyMap[key] { keyLocation = (Float(keySetings[0]) - 5) / 5 * self.stereoWidth keySound = keySetings[1] } func play(player: AVAudioPlayer, keyLocation: Float){ if !player.isPlaying { // Randomize pitch and Sound. if self.keyRandomize { // Randomize Pitch player.enableRate = true player.rate = Float.random(in: 0.9 ... 1.1 ) // Randomize Volume player.volume = self.volumeLevel * Float.random(in: 0.95 ... 1.0 ) } // Set the Location of the Key and Play the sound player.pan = keyLocation player.play() } } if down { if let player = self.players[keySound]?.0[(self.playersCurrentPlayer[keySound]?.0)!]{ play(player: player, keyLocation: keyLocation) } self.playersCurrentPlayer[keySound]?.0 += 1 if (self.playersCurrentPlayer[keySound]?.0)! >= self.playersMax { self.playersCurrentPlayer[keySound]?.0 = 0 } } else if self.keyUpSound { if let player = self.players[keySound]?.1[(self.playersCurrentPlayer[keySound]?.1)!]{ play(player: player, keyLocation: keyLocation) } self.playersCurrentPlayer[keySound]?.1 += 1 if (self.playersCurrentPlayer[keySound]?.1)! >= self.playersMax { self.playersCurrentPlayer[keySound]?.1 = 0 } } } // MARK: System Menu Setup let menuItemVolumeMute = NSMenuItem(title: "Mute Keys", action: #selector(menuSetVolMute), keyEquivalent: "") let menuItemVolume25 = NSMenuItem(title: "25% Volume", action: #selector(menuSetVol1), keyEquivalent: "") let menuItemVolume50 = NSMenuItem(title: "50% Volume", action: #selector(menuSetVol2), keyEquivalent: "") let menuItemVolume75 = NSMenuItem(title: "75% Volume", action: #selector(menuSetVol3), keyEquivalent: "") let menuItemVolume100 = NSMenuItem(title: "100% Volume", action: #selector(menuSetVol4), keyEquivalent: "") let menuItemSoundStereo = NSMenuItem(title: "Stereo Sound", action: #selector(menuStereo), keyEquivalent: "") let menuItemSoundMono = NSMenuItem(title: "Mono Sound", action: #selector(menuMono), keyEquivalent: "") let menuItemModKeysOn = NSMenuItem(title: "Mod Keys On", action: #selector(menuModsOn), keyEquivalent: "") let menuItemModKeysOff = NSMenuItem(title: "Mod Keys Off", action: #selector(menuModKeysMuted), keyEquivalent: "") let menuItemKeyUpOn = NSMenuItem(title: "Keyup Sound On", action: #selector(menuKeyupSoundOn), keyEquivalent: "") let menuItemKeyUpOff = NSMenuItem(title: "Keyup Sound Off", action: #selector(menuKeyupSoundOff), keyEquivalent: "") let menuItemRandomizeOn = NSMenuItem(title: "Randomize Pitch On", action: #selector(menuRandomizeOn), keyEquivalent: "") let menuItemRandomizeOff = NSMenuItem(title: "Randomize Pitch Off", action: #selector(menuRandomizeOff), keyEquivalent: "") let menuItemProfile0 = NSMenuItem(title: "Tappy Profile 1", action: #selector(menuProfile0), keyEquivalent: "") let menuItemProfile1 = NSMenuItem(title: "Tappy Profile 2", action: #selector(menuProfile1), keyEquivalent: "") let menuItemProfile2 = NSMenuItem(title: "Clicky Profile", action: #selector(menuProfile2), keyEquivalent: "") let menuItemAbout = NSMenuItem(title: "About MKS", action: #selector(menuAbout), keyEquivalent: "") let menuItemQuit = NSMenuItem(title: "Quit", action: #selector(menuQuit), keyEquivalent: "") func menuCreate(){ self.menuItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) self.menuItem?.highlightMode = true if let imgURL = Bundle.main.url(forResource: "sysmenuicon", withExtension: "png"){ let image = NSImage(byReferencing: imgURL) image.isTemplate = true image.size.width = 18 image.size.height = 18 self.menuItem?.image = image } else { self.menuItem?.title = "MechKey" } let menu = NSMenu() menu.addItem(self.menuItemVolumeMute) menu.addItem(self.menuItemVolume25) menu.addItem(self.menuItemVolume50) menu.addItem(self.menuItemVolume75) menu.addItem(self.menuItemVolume100) menu.addItem(NSMenuItem.separator()) menu.addItem(self.menuItemSoundStereo) menu.addItem(self.menuItemSoundMono) menu.addItem(NSMenuItem.separator()) menu.addItem(self.menuItemModKeysOn) menu.addItem(self.menuItemModKeysOff) menu.addItem(NSMenuItem.separator()) menu.addItem(self.menuItemKeyUpOn) menu.addItem(self.menuItemKeyUpOff) menu.addItem(NSMenuItem.separator()) menu.addItem(self.menuItemRandomizeOn) menu.addItem(self.menuItemRandomizeOff) menu.addItem(NSMenuItem.separator()) menu.addItem(self.menuItemProfile0) menu.addItem(self.menuItemProfile1) menu.addItem(self.menuItemProfile2) menu.addItem(NSMenuItem.separator()) menu.addItem(self.menuItemAbout) menu.addItem(self.menuItemQuit) self.menuItem?.menu = menu } @objc func menuSetVolMute(){ volumeSet(vol: self.volumeLevel, muted: true) } @objc func menuSetVol1(){ volumeSet(vol: 0.25, muted: false) } @objc func menuSetVol2(){ volumeSet(vol: 0.50, muted: false) } @objc func menuSetVol3(){ volumeSet(vol: 0.75, muted: false) } @objc func menuSetVol4(){ volumeSet(vol: 1.00, muted: false) } @objc func menuStereo(){ stereoWidthSet(width: self.stereoWidthDefult) } @objc func menuMono(){ stereoWidthSet(width: 0) } @objc func menuModsOn(){ modKeyMutedSet(muted: false) } @objc func menuModKeysMuted(){ modKeyMutedSet(muted: true) } @objc func menuKeyupSoundOn(){ keyUpSoundSet(on: true) } @objc func menuKeyupSoundOff(){ keyUpSoundSet(on: false) } @objc func menuRandomizeOn(){ keyRandomizeSet(on: true) } @objc func menuRandomizeOff(){ keyRandomizeSet(on: false) } @objc func menuProfile0(){ profileSet(profile: 0) } @objc func menuProfile1(){ profileSet(profile: 1) } @objc func menuProfile2(){ profileSet(profile: 2) } @objc func menuAbout(){ NSWorkspace.shared.open(NSURL(string: "http://www.zynath.com/MKS")! as URL) } @objc func menuQuit(){ NSApp.terminate(nil) } // MARK: Volume Settings func volumeLoad(){ if UserDefaults.standard.object(forKey: "VolumeLevel") != nil { self.volumeLevel = UserDefaults.standard.float(forKey: "VolumeLevel") } if UserDefaults.standard.object(forKey: "VolumeMuted") != nil { self.volumeMuted = UserDefaults.standard.bool(forKey: "VolumeMuted") } } func volumeSave(){ UserDefaults.standard.set(self.volumeLevel, forKey: "VolumeLevel") UserDefaults.standard.set(self.volumeMuted, forKey: "VolumeMuted") UserDefaults.standard.synchronize() } func volumeSet(vol: Float, muted: Bool){ self.volumeMuted = muted self.volumeLevel = vol volumeUpdate() volumeSave() playSoundForKey(key: 0, keyIsDown: true) } func volumeUpdate(){ for (_, players) in self.players{ for player in players.0 { player?.volume = self.volumeLevel player?.enableRate = false player?.rate = 1 } for player in players.1 { player?.volume = self.volumeLevel player?.enableRate = false player?.rate = 1 } } // Update Menu to Match the Setting self.menuItemVolumeMute.state = NSControl.StateValue.off self.menuItemVolume25.state = NSControl.StateValue.off self.menuItemVolume50.state = NSControl.StateValue.off self.menuItemVolume75.state = NSControl.StateValue.off self.menuItemVolume100.state = NSControl.StateValue.off if self.volumeMuted { self.menuItemVolumeMute.state = NSControl.StateValue.on } else if self.volumeLevel == 0.25 { self.menuItemVolume25.state = NSControl.StateValue.on } else if self.volumeLevel == 0.50 { self.menuItemVolume50.state = NSControl.StateValue.on } else if self.volumeLevel == 0.75 { self.menuItemVolume75.state = NSControl.StateValue.on } else if self.volumeLevel == 1 { self.menuItemVolume100.state = NSControl.StateValue.on } } // MARK: Stereo Settings func stereoWidthLoad(){ if UserDefaults.standard.object(forKey: "stereoWidth") != nil { self.stereoWidth = UserDefaults.standard.float(forKey: "stereoWidth") } stereoWidthUpdate() } func stereoWidthSet(width: Float){ self.stereoWidth = width UserDefaults.standard.set(self.stereoWidth, forKey: "stereoWidth") UserDefaults.standard.synchronize() stereoWidthUpdate() } func stereoWidthUpdate(){ if self.stereoWidth == 0 { menuItemSoundMono.state = NSControl.StateValue.on menuItemSoundStereo.state = NSControl.StateValue.off } else { menuItemSoundMono.state = NSControl.StateValue.off menuItemSoundStereo.state = NSControl.StateValue.on } } // MARK: Mod Key Settings func modKeyMutedLoad() { if UserDefaults.standard.object(forKey: "modKeysMuted") != nil { self.modKeysMuted = UserDefaults.standard.bool(forKey: "modKeysMuted") } modKeyMutedUpdate() } func modKeyMutedSet(muted: Bool) { self.modKeysMuted = muted UserDefaults.standard.set(self.modKeysMuted, forKey: "modKeysMuted") UserDefaults.standard.synchronize() modKeyMutedUpdate() } func modKeyMutedUpdate() { if self.modKeysMuted { menuItemModKeysOff.state = NSControl.StateValue.on menuItemModKeysOn.state = NSControl.StateValue.off } else { menuItemModKeysOff.state = NSControl.StateValue.off menuItemModKeysOn.state = NSControl.StateValue.on } } // MARK: KeyUp Sound Settings func keyUpSoundLoad() { if UserDefaults.standard.object(forKey: "keyUpSound") != nil { self.keyUpSound = UserDefaults.standard.bool(forKey: "keyUpSound") } keyUpSoundUpdate() } func keyUpSoundSet(on: Bool) { self.keyUpSound = on UserDefaults.standard.set(self.keyUpSound, forKey: "keyUpSound") UserDefaults.standard.synchronize() keyUpSoundUpdate() } func keyUpSoundUpdate() { if self.keyUpSound { menuItemKeyUpOn.state = NSControl.StateValue.on menuItemKeyUpOff.state = NSControl.StateValue.off } else { menuItemKeyUpOn.state = NSControl.StateValue.off menuItemKeyUpOff.state = NSControl.StateValue.on } } // MARK: Randomize Sound Setting func keyRandomizeLoad() { if UserDefaults.standard.object(forKey: "keyRandomize") != nil { self.keyRandomize = UserDefaults.standard.bool(forKey: "keyRandomize") } keyRandomizeUpdate() } func keyRandomizeSet(on: Bool) { self.keyRandomize = on UserDefaults.standard.set(self.keyRandomize, forKey: "keyRandomize") UserDefaults.standard.synchronize() keyRandomizeUpdate() } func keyRandomizeUpdate() { if self.keyRandomize { menuItemRandomizeOn.state = NSControl.StateValue.on menuItemRandomizeOff.state = NSControl.StateValue.off } else { menuItemRandomizeOn.state = NSControl.StateValue.off menuItemRandomizeOff.state = NSControl.StateValue.on // Update the preset Volume and Rates volumeUpdate() } } // MARK: Profile Settings func profileLoad(){ if UserDefaults.standard.object(forKey: "profile") != nil { self.profile = UserDefaults.standard.integer(forKey: "profile") } profileUpdate() } func profileSet(profile: Int) { self.profile = profile UserDefaults.standard.set(self.profile, forKey: "profile") UserDefaults.standard.synchronize() profileUpdate() } func profileUpdate(){ self.players = [:] self.playersCurrentPlayer = [:] loadSounds() self.menuItemProfile0.state = NSControl.StateValue.off self.menuItemProfile1.state = NSControl.StateValue.off self.menuItemProfile2.state = NSControl.StateValue.off if self.profile == 0 { self.menuItemProfile0.state = NSControl.StateValue.on } else if self.profile == 1 { self.menuItemProfile1.state = NSControl.StateValue.on } else if self.profile == 2 { self.menuItemProfile2.state = NSControl.StateValue.on } } // MARK: Permissions Request func checkPrivecyAccess(){ //get the value for accesibility let checkOptPrompt = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString //set the options: false means it wont ask //true means it will popup and ask let options = [checkOptPrompt: true] //translate into boolean value let accessEnabled = AXIsProcessTrustedWithOptions(options as CFDictionary?) if !accessEnabled { let alert = NSAlert() alert.messageText = "MKS Needs Permissions" alert.informativeText = "macOS is awesome at protecting your privacy! However, as a result, in order for MKS to work, you will need to add it to the list of apps that are allowed to control your computer. That's the only way MKS can know when you press a key to play that sweet mechanical keyboard sound :) To add MKS to the list of trusted apps do the following: \n\nOpen System Preferences > Security & Privacy > Privacy > Accessibility, click on the Padlock in the bottom lefthand corner, and drag the MKS app into the list. \n\nHitting OK will close MKS. After you have done this, restart the app." alert.runModal() NSApp.terminate(nil) } } // MARK: Debugging Functions func systemMenuMessage(message: String){ if self.debugging { self.menuItem?.title = message } } }
39.010724
614
0.498866
030e738ab4c8c30b69ffde7e37a92666fe1abb6a
918
// // ViewController.swift // 7_SOPT_Social_Login // // Created by 조경진 on 2019/12/07. // Copyright © 2019 조경진. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let loginBtn = FBLoginButton() loginBtn.permissions = ["email"] loginBtn.center = view.center view.addSubview(loginBtn) } override func viewWillAppear(_ animated: Bool) { super .viewWillAppear(animated) getAccessToken() } func getAccessToken() { guard let token = AccessToken.current else {return} print("### AccessToken ####") print(token) print(token.appID, token.userID) print("### AccessToken ####") } }
21.348837
58
0.604575