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
eb08bf5776e72a548bd2c3182a046d60a8253f58
2,855
// // CallDirectoryHandler.swift // CallDirectoryExtension // // Created by kotetu on 2021/07/25. // import Foundation import CallKit import CoreModule final class CallDirectoryHandler: CXCallDirectoryProvider { override func beginRequest(with context: CXCallDirectoryExtensionContext) { printToConsole("Start.") context.delegate = self guard let appGroupID = appGroupID else { context.cancelRequest(withError: CallDirectoryError.gettingAppGroupIDIsFailed) return } let userDefaultsDriver = UserDefaultsDriver(suiteName: appGroupID) guard let phoneNumberText = userDefaultsDriver.string(forKey: UserDefaultsKeys.phoneNumber.rawValue), let phoneNumber = CXCallDirectoryPhoneNumber(phoneNumberText), let displayName = userDefaultsDriver.string(forKey: UserDefaultsKeys.displayName.rawValue) else { context.cancelRequest(withError: CallDirectoryError.invalidParameter) return } // カスタムエラーを意図的に出したい場合はtrueにしてください。 #if false context.cancelRequest(withError: CallDirectoryError.invalidParameter) return #endif printToConsole("phoneNumber:\(phoneNumberText), displayName:\(displayName)") context.removeAllIdentificationEntries() context.addIdentificationEntry(withNextSequentialPhoneNumber: phoneNumber, label: displayName) // 重複エラーを意図的に出したい場合はtrueにしてください。 #if false context.addIdentificationEntry(withNextSequentialPhoneNumber: phoneNumber, label: displayName) #endif // メモリサイズオーバーエラーを意図的に出したい場合はtrueにしてください。 #if false let tooMatchMemory = Data(count: 1000_000_000) _ = tooMatchMemory.base64EncodedString() #endif context.completeRequest() printToConsole("Complete.") } private var appGroupID: String? { Bundle.main.object(forInfoDictionaryKey: "AppGroupID") as? String } private func printToConsole(_ text: String) { #if DEBUG NSLog("[Debug]:" + text) #endif } } extension CallDirectoryHandler: CXCallDirectoryExtensionContextDelegate { func requestFailed(for extensionContext: CXCallDirectoryExtensionContext, withError error: Error) { // An error occurred while adding blocking or identification entries, check the NSError for details. // For Call Directory error codes, see the CXErrorCodeCallDirectoryManagerError enum in <CallKit/CXError.h>. // // This may be used to store the error details in a location accessible by the extension's containing app, so that the // app may be notified about errors which occurred while loading data even if the request to load data was initiated by // the user in Settings instead of via the app itself. } }
37.077922
127
0.70683
222a6fa8f1091c5a23135a3e4209b519a61710e4
2,064
// // ViewController.swift // machineLearningApp // // Created by Amina on 5/29/21. // import UIKit import CoreML import Vision class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { let imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. imagePicker.delegate = self imagePicker.sourceType = .camera imagePicker.allowsEditing = false } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let userImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { imageView.image = userImage guard let ciimage = CIImage(image: userImage) else { fatalError() } detect(image: ciimage) } imagePicker.dismiss(animated: true, completion: nil) } func detect(image: CIImage) { guard let model = try? VNCoreMLModel(for: Inceptionv3().model) else { fatalError() } let request = VNCoreMLRequest(model: model) { (request, error) in guard let results = request.results as? [VNClassificationObservation] else { fatalError() } if let firstResult = results.first { if firstResult.identifier.contains("hotdog") { self.navigationItem.title = "Hotdog!" } else { self.navigationItem.title = "Not hotdog!" } } } let handler = VNImageRequestHandler(ciImage: image) do { try handler.perform([request]) } catch { print(error) } } @IBOutlet weak var imageView: UIImageView! @IBAction func cameraTapped(_ sender: UIBarButtonItem) { present(imagePicker, animated: true, completion: nil) } }
30.80597
144
0.606105
9cc2f4cf9043d201a77802a180d248afc97d0dff
2,860
// // ActivityListViewController.swift // SuperTicket // // Created by wanli.yang on 16/4/12. // Copyright © 2016年 wanli.yang. All rights reserved. // import UIKit class ActivityListViewController: UITableViewController { var company: Company! var activities: [Activity] = [] override func viewDidLoad() { super.viewDidLoad() configureUI() fetchData() } private func configureUI() { tableView.emptyDataSetSource = self tableView.emptyDataSetDelegate = self navigationItem.rightBarButtonItem = ImageBarButtonItem(image: UIImage(named: "add")!, tap: {[weak self] in WLLinkUtil.sharedInstance.linkToCreateActivityVc(self!, company: self!.company) }) } private func fetchData() { // let query = company.activities?.query() // query?.cachePolicy = .CacheThenNetwork // showHud() // query?.findObjectsInBackgroundWithBlock({[weak self] (activities, error) in // self?.hideHud() // if let activities = activities as? [Activity] { // if activities.count > 0 { // self?.activities = activities // self?.tableView.reloadData() // } else { // self?.tableView.reloadEmptyDataSet() // } // // } else { // self?.tableView.reloadEmptyDataSet() // } // }) let query = Activity.query() showHud() query.whereKey("companyId", equalTo: company.companyId) query.findObjectsInBackgroundWithBlock {[weak self] (activies, error) in self?.hideHud() if let activities = activies as? [Activity] { if activities.count > 0 { self?.activities = activities self?.tableView.reloadData() } else { self?.tableView.reloadEmptyDataSet() } } else { self?.tableView.reloadEmptyDataSet() } } } } extension ActivityListViewController { override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ActivityListCell", forIndexPath: indexPath) as! ActivityListCell cell.activity = activities[indexPath.row] return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return activities.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { WLLinkUtil.sharedInstance.linkToScanActivityVc(self, activity: activities[indexPath.row]) } }
30.425532
128
0.58951
9b3853f35f3454836f237edea870ba7cdc98285d
72,295
// // ParseInstallation.swift // ParseSwift // // Created by Corey Baker on 9/6/20. // Copyright © 2020 Parse Community. All rights reserved. // import Foundation /** Objects that conform to the `ParseInstallation` protocol have a local representation of an installation persisted to the Parse cloud. This protocol inherits from the `ParseObject` protocol, and retains the same functionality of a `ParseObject`, but also extends it with installation-specific fields and related immutability and validity checks. A valid `ParseInstallation` can only be instantiated via *current* because the required identifier fields are readonly. The `timeZone` is also a readonly property which is automatically updated to match the device's time zone when the `ParseInstallation` is saved, thus these fields might not reflect the latest device state if the installation has not recently been saved. `ParseInstallation`s which have a valid `deviceToken` and are saved to the Parse Server can be used to target push notifications. Use `setDeviceToken` to set the `deviceToken` properly. - warning: If the use of badge is desired, it should be retrieved by using UIKit, AppKit, etc. and stored in `ParseInstallation.badge` before saving/updating the installation. - warning: Linux developers should set `appName`, `appIdentifier`, and `appVersion` manually as `ParseSwift` doesn't have access to Bundle.main. */ public protocol ParseInstallation: ParseObject { /** The device type for the `ParseInstallation`. */ var deviceType: String? { get set } /** The installationId for the `ParseInstallation`. */ var installationId: String? { get set } /** The device token for the `ParseInstallation`. */ var deviceToken: String? { get set } /** The badge for the `ParseInstallation`. */ var badge: Int? { get set } /** The name of the time zone for the `ParseInstallation`. */ var timeZone: String? { get set } /** The channels for the `ParseInstallation`. */ var channels: [String]? { get set } /** The application name for the `ParseInstallation`. */ var appName: String? { get set } /** The application identifier for the `ParseInstallation`. */ var appIdentifier: String? { get set } /** The application version for the `ParseInstallation`. */ var appVersion: String? { get set } /** The sdk version for the `ParseInstallation`. */ var parseVersion: String? { get set } /** The locale identifier for the `ParseInstallation`. */ var localeIdentifier: String? { get set } } // MARK: Default Implementations public extension ParseInstallation { static var className: String { "_Installation" } func mergeParse(with object: Self) throws -> Self { guard hasSameObjectId(as: object) == true else { throw ParseError(code: .unknownError, message: "objectId's of objects don't match") } var updatedInstallation = self if shouldRestoreKey(\.ACL, original: object) { updatedInstallation.ACL = object.ACL } if shouldRestoreKey(\.deviceType, original: object) { updatedInstallation.deviceType = object.deviceType } if shouldRestoreKey(\.installationId, original: object) { updatedInstallation.installationId = object.installationId } if shouldRestoreKey(\.deviceToken, original: object) { updatedInstallation.deviceToken = object.deviceToken } if shouldRestoreKey(\.badge, original: object) { updatedInstallation.badge = object.badge } if shouldRestoreKey(\.timeZone, original: object) { updatedInstallation.timeZone = object.timeZone } if shouldRestoreKey(\.channels, original: object) { updatedInstallation.channels = object.channels } if shouldRestoreKey(\.appName, original: object) { updatedInstallation.appName = object.appName } if shouldRestoreKey(\.appIdentifier, original: object) { updatedInstallation.appIdentifier = object.appIdentifier } if shouldRestoreKey(\.appVersion, original: object) { updatedInstallation.appVersion = object.appVersion } if shouldRestoreKey(\.parseVersion, original: object) { updatedInstallation.parseVersion = object.parseVersion } if shouldRestoreKey(\.localeIdentifier, original: object) { updatedInstallation.localeIdentifier = object.localeIdentifier } return updatedInstallation } func merge(with object: Self) throws -> Self { try mergeParse(with: object) } } // MARK: Convenience extension ParseInstallation { var endpoint: API.Endpoint { if let objectId = objectId { return .installation(objectId: objectId) } return .installations } func endpoint(_ method: API.Method) -> API.Endpoint { if !ParseSwift.configuration.isAllowingCustomObjectIds || method != .POST { return endpoint } else { return .installations } } func hasSameInstallationId<T: ParseInstallation>(as other: T) -> Bool { return other.className == className && other.installationId == installationId && installationId != nil } /** Sets the device token string property from an `Data`-encoded token. - parameter data: A token that identifies the device. */ mutating public func setDeviceToken(_ data: Data) { let deviceTokenString = data.hexEncodedString() if deviceToken != deviceTokenString { deviceToken = deviceTokenString } } } // MARK: CurrentInstallationContainer struct CurrentInstallationContainer<T: ParseInstallation>: Codable { var currentInstallation: T? var installationId: String? } // MARK: Current Installation Support public extension ParseInstallation { internal static var currentContainer: CurrentInstallationContainer<Self> { get { guard let installationInMemory: CurrentInstallationContainer<Self> = try? ParseStorage.shared.get(valueFor: ParseStorage.Keys.currentInstallation) else { #if !os(Linux) && !os(Android) && !os(Windows) guard let installationFromKeyChain: CurrentInstallationContainer<Self> = try? KeychainStore.shared.get(valueFor: ParseStorage.Keys.currentInstallation) else { let newInstallationId = UUID().uuidString.lowercased() var newInstallation = BaseParseInstallation() newInstallation.installationId = newInstallationId newInstallation.createInstallationId(newId: newInstallationId) newInstallation.updateAutomaticInfo() let newBaseInstallationContainer = CurrentInstallationContainer<BaseParseInstallation>(currentInstallation: newInstallation, installationId: newInstallationId) try? KeychainStore.shared.set(newBaseInstallationContainer, for: ParseStorage.Keys.currentInstallation) guard let installationFromKeyChain: CurrentInstallationContainer<Self> = try? KeychainStore.shared.get(valueFor: ParseStorage.Keys.currentInstallation) else { // Couldn't create container correctly, return empty one. return CurrentInstallationContainer<Self>() } try? ParseStorage.shared.set(installationFromKeyChain, for: ParseStorage.Keys.currentInstallation) return installationFromKeyChain } return installationFromKeyChain #else let newInstallationId = UUID().uuidString.lowercased() var newInstallation = BaseParseInstallation() newInstallation.installationId = newInstallationId newInstallation.createInstallationId(newId: newInstallationId) newInstallation.updateAutomaticInfo() let newBaseInstallationContainer = CurrentInstallationContainer<BaseParseInstallation>(currentInstallation: newInstallation, installationId: newInstallationId) try? ParseStorage.shared.set(newBaseInstallationContainer, for: ParseStorage.Keys.currentInstallation) guard let installationFromMemory: CurrentInstallationContainer<Self> = try? ParseStorage.shared.get(valueFor: ParseStorage.Keys.currentInstallation) else { // Couldn't create container correctly, return empty one. return CurrentInstallationContainer<Self>() } return installationFromMemory #endif } return installationInMemory } set { try? ParseStorage.shared.set(newValue, for: ParseStorage.Keys.currentInstallation) } } internal static func updateInternalFieldsCorrectly() { if Self.currentContainer.currentInstallation?.installationId != Self.currentContainer.installationId! { //If the user made changes, set back to the original Self.currentContainer.currentInstallation?.installationId = Self.currentContainer.installationId! } //Always pull automatic info to ensure user made no changes to immutable values Self.currentContainer.currentInstallation?.updateAutomaticInfo() } internal static func saveCurrentContainerToKeychain() { Self.currentContainer.currentInstallation?.originalData = nil #if !os(Linux) && !os(Android) && !os(Windows) try? KeychainStore.shared.set(currentContainer, for: ParseStorage.Keys.currentInstallation) #endif } internal static func deleteCurrentContainerFromKeychain() { try? ParseStorage.shared.delete(valueFor: ParseStorage.Keys.currentInstallation) #if !os(Linux) && !os(Android) && !os(Windows) try? KeychainStore.shared.delete(valueFor: ParseStorage.Keys.currentInstallation) #endif //Prepare new installation BaseParseInstallation.createNewInstallationIfNeeded() } /** Gets/Sets properties of the current installation in the Keychain. - returns: Returns a `ParseInstallation` that is the current device. If there is none, returns `nil`. */ internal(set) static var current: Self? { get { return Self.currentContainer.currentInstallation } set { Self.currentContainer.currentInstallation = newValue Self.updateInternalFieldsCorrectly() } } } // MARK: Automatic Info extension ParseInstallation { mutating func updateAutomaticInfo() { updateDeviceTypeFromDevice() updateTimeZoneFromDevice() updateVersionInfoFromDevice() updateLocaleIdentifierFromDevice() } mutating func createInstallationId(newId: String) { if installationId == nil { installationId = newId } } mutating func updateDeviceTypeFromDevice() { if deviceType != ParseConstants.deviceType { deviceType = ParseConstants.deviceType } } mutating func updateTimeZoneFromDevice() { let currentTimeZone = TimeZone.current.identifier if timeZone != currentTimeZone { timeZone = currentTimeZone } } mutating func updateVersionInfoFromDevice() { guard let appInfo = Bundle.main.infoDictionary else { return } #if !os(Linux) && !os(Android) && !os(Windows) #if TARGET_OS_MACCATALYST // If using an Xcode new enough to know about Mac Catalyst: // Mac Catalyst Apps use a prefix to the bundle ID. This should not be transmitted // to Parse Server. Catalyst apps should look like iOS apps otherwise // push and other services don't work properly. if let currentAppIdentifier = appInfo[String(kCFBundleIdentifierKey)] as? String { let macCatalystBundleIdPrefix = "maccatalyst." if currentAppIdentifier.hasPrefix(macCatalystBundleIdPrefix) { appIdentifier = currentAppIdentifier.replacingOccurrences(of: macCatalystBundleIdPrefix, with: "") } } #else if let currentAppIdentifier = appInfo[String(kCFBundleIdentifierKey)] as? String { if appIdentifier != currentAppIdentifier { appIdentifier = currentAppIdentifier } } #endif if let currentAppName = appInfo[String(kCFBundleNameKey)] as? String { if appName != currentAppName { appName = currentAppName } } if let currentAppVersion = appInfo[String(kCFBundleVersionKey)] as? String { if appVersion != currentAppVersion { appVersion = currentAppVersion } } #endif if parseVersion != ParseConstants.version { parseVersion = ParseConstants.version } } /** Save localeIdentifier in the following format: [language code]-[COUNTRY CODE]. The language codes are two-letter lowercase ISO language codes (such as "en") as defined by <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1</a>. The country codes are two-letter uppercase ISO country codes (such as "US") as defined by <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-3">ISO 3166-1</a>. Many iOS locale identifiers don't contain the country code -> inconsistencies with Android/Windows Phone. */ mutating func updateLocaleIdentifierFromDevice() { guard let language = Locale.current.languageCode else { return } let currentLocalIdentifier: String! if let regionCode = Locale.current.regionCode { currentLocalIdentifier = "\(language)-\(regionCode)" } else { currentLocalIdentifier = language } if localeIdentifier != currentLocalIdentifier { localeIdentifier = currentLocalIdentifier } } } // MARK: Fetchable extension ParseInstallation { internal static func updateKeychainIfNeeded(_ results: [Self], deleting: Bool = false) throws { guard let currentInstallation = Self.current else { return } var foundCurrentInstallationObjects = results.filter { $0.hasSameInstallationId(as: currentInstallation) } foundCurrentInstallationObjects = try foundCurrentInstallationObjects.sorted(by: { guard let firstUpdatedAt = $0.updatedAt, let secondUpdatedAt = $1.updatedAt else { throw ParseError(code: .unknownError, message: "Objects from the server should always have an \"updatedAt\"") } return firstUpdatedAt.compare(secondUpdatedAt) == .orderedDescending }) if let foundCurrentInstallation = foundCurrentInstallationObjects.first { if !deleting { Self.current = foundCurrentInstallation Self.saveCurrentContainerToKeychain() } else { Self.deleteCurrentContainerFromKeychain() } } } /** Fetches the `ParseInstallation` *synchronously* with the current data from the server. - parameter includeKeys: The name(s) of the key(s) to include that are `ParseObject`s. Use `["*"]` to include all keys one level deep. This is similar to `include` and `includeAll` for `Query`. - parameter options: A set of header options sent to the server. Defaults to an empty set. - throws: An error of `ParseError` type. - important: If an object fetched has the same objectId as current, it will automatically update the current. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ public func fetch(includeKeys: [String]? = nil, options: API.Options = []) throws -> Self { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) let result: Self = try fetchCommand(include: includeKeys) .execute(options: options) try Self.updateKeychainIfNeeded([result]) return result } /** Fetches the `ParseInstallation` *asynchronously* and executes the given callback block. - parameter includeKeys: The name(s) of the key(s) to include that are `ParseObject`s. Use `["*"]` to include all keys one level deep. This is similar to `include` and `includeAll` for `Query`. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute when completed. It should have the following argument signature: `(Result<Self, ParseError>)`. - important: If an object fetched has the same objectId as current, it will automatically update the current. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ public func fetch( includeKeys: [String]? = nil, options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<Self, ParseError>) -> Void ) { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) do { try fetchCommand(include: includeKeys) .executeAsync(options: options, callbackQueue: callbackQueue) { result in if case .success(let foundResult) = result { do { try Self.updateKeychainIfNeeded([foundResult]) completion(.success(foundResult)) } catch { let returnError: ParseError! if let parseError = error as? ParseError { returnError = parseError } else { returnError = ParseError(code: .unknownError, message: error.localizedDescription) } completion(.failure(returnError)) } } else { completion(result) } } } catch { callbackQueue.async { if let error = error as? ParseError { completion(.failure(error)) } else { completion(.failure(ParseError(code: .unknownError, message: error.localizedDescription))) } } } } func fetchCommand(include: [String]?) throws -> API.Command<Self, Self> { guard objectId != nil else { throw ParseError(code: .missingObjectId, message: "objectId must not be nil") } var params: [String: String]? if let includeParams = include { params = ["include": "\(Set(includeParams))"] } return API.Command(method: .GET, path: endpoint, params: params) { (data) -> Self in try ParseCoding.jsonDecoder().decode(Self.self, from: data) } } } // MARK: Savable extension ParseInstallation { /** Saves the `ParseInstallation` *synchronously* and throws an error if there's an issue. - parameter options: A set of header options sent to the server. Defaults to an empty set. - throws: An error of type `ParseError`. - returns: Returns saved `ParseInstallation`. - important: If an object saved has the same objectId as current, it will automatically update the current. */ public func save(options: API.Options = []) throws -> Self { try save(ignoringCustomObjectIdConfig: false, options: options) } /** Saves the `ParseInstallation` *synchronously* and throws an error if there's an issue. - parameter ignoringCustomObjectIdConfig: Ignore checking for `objectId` when `ParseConfiguration.isAllowingCustomObjectIds = true` to allow for mixed `objectId` environments. Defaults to false. - parameter options: A set of header options sent to the server. Defaults to an empty set. - throws: An error of type `ParseError`. - returns: Returns saved `ParseInstallation`. - important: If an object saved has the same objectId as current, it will automatically update the current. - warning: If you are using `ParseConfiguration.isAllowingCustomObjectIds = true` and plan to generate all of your `objectId`'s on the client-side then you should leave `ignoringCustomObjectIdConfig = false`. Setting `ParseConfiguration.isAllowingCustomObjectIds = true` and `ignoringCustomObjectIdConfig = true` means the client will generate `objectId`'s and the server will generate an `objectId` only when the client does not provide one. This can increase the probability of colliding `objectId`'s as the client and server `objectId`'s may be generated using different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the client-side checks are disabled. Developers are responsible for handling such cases. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ public func save(ignoringCustomObjectIdConfig: Bool, options: API.Options = []) throws -> Self { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) var childObjects: [String: PointerType]? var childFiles: [UUID: ParseFile]? var error: ParseError? let group = DispatchGroup() group.enter() self.ensureDeepSave(options: options) { (savedChildObjects, savedChildFiles, parseError) in childObjects = savedChildObjects childFiles = savedChildFiles error = parseError group.leave() } group.wait() if let error = error { throw error } let result: Self = try saveCommand(ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig) .execute(options: options, childObjects: childObjects, childFiles: childFiles) try Self.updateKeychainIfNeeded([result]) return result } /** Saves the `ParseInstallation` *asynchronously* and executes the given callback block. - parameter ignoringCustomObjectIdConfig: Ignore checking for `objectId` when `ParseConfiguration.isAllowingCustomObjectIds = true` to allow for mixed `objectId` environments. Defaults to false. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<Self, ParseError>)`. - important: If an object saved has the same objectId as current, it will automatically update the current. - warning: If you are using `ParseConfiguration.isAllowingCustomObjectIds = true` and plan to generate all of your `objectId`'s on the client-side then you should leave `ignoringCustomObjectIdConfig = false`. Setting `ParseConfiguration.isAllowingCustomObjectIds = true` and `ignoringCustomObjectIdConfig = true` means the client will generate `objectId`'s and the server will generate an `objectId` only when the client does not provide one. This can increase the probability of colliding `objectId`'s as the client and server `objectId`'s may be generated using different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the client-side checks are disabled. Developers are responsible for handling such cases. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ public func save( ignoringCustomObjectIdConfig: Bool = false, options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<Self, ParseError>) -> Void ) { command(method: .save, ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig, options: options, callbackQueue: callbackQueue, completion: completion) } /** Creates the `ParseInstallation` *asynchronously* and executes the given callback block. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<Self, ParseError>)`. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ public func create( options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<Self, ParseError>) -> Void ) { command(method: .create, options: options, callbackQueue: callbackQueue, completion: completion) } /** Replaces the `ParseInstallation` *asynchronously* and executes the given callback block. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<Self, ParseError>)`. - important: If an object replaced has the same objectId as current, it will automatically replace the current. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ public func replace( options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<Self, ParseError>) -> Void ) { command(method: .replace, options: options, callbackQueue: callbackQueue, completion: completion) } /** Updates the `ParseInstallation` *asynchronously* and executes the given callback block. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<Self, ParseError>)`. - important: If an object updated has the same objectId as current, it will automatically update the current. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func update( options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<Self, ParseError>) -> Void ) { command(method: .update, options: options, callbackQueue: callbackQueue, completion: completion) } func command( method: Method, ignoringCustomObjectIdConfig: Bool = false, options: API.Options, callbackQueue: DispatchQueue, completion: @escaping (Result<Self, ParseError>) -> Void ) { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) self.ensureDeepSave(options: options) { (savedChildObjects, savedChildFiles, error) in guard let parseError = error else { do { let command: API.Command<Self, Self>! switch method { case .save: command = try self.saveCommand(ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig) case .create: command = self.createCommand() case .replace: command = try self.replaceCommand() case .update: command = try self.updateCommand() } command .executeAsync(options: options, callbackQueue: callbackQueue, childObjects: savedChildObjects, childFiles: savedChildFiles) { result in if case .success(let foundResult) = result { try? Self.updateKeychainIfNeeded([foundResult]) } completion(result) } } catch { callbackQueue.async { if let parseError = error as? ParseError { completion(.failure(parseError)) } else { completion(.failure(.init(code: .unknownError, message: error.localizedDescription))) } } } return } callbackQueue.async { completion(.failure(parseError)) } } } func saveCommand(ignoringCustomObjectIdConfig: Bool = false) throws -> API.Command<Self, Self> { if ParseSwift.configuration.isAllowingCustomObjectIds && objectId == nil && !ignoringCustomObjectIdConfig { throw ParseError(code: .missingObjectId, message: "objectId must not be nil") } if isSaved { return try replaceCommand() // MARK: Should be switched to "updateCommand" when server supports PATCH. } return createCommand() } // MARK: Saving ParseObjects - private func createCommand() -> API.Command<Self, Self> { var object = self if object.ACL == nil, let acl = try? ParseACL.defaultACL() { object.ACL = acl } let mapper = { (data) -> Self in try ParseCoding.jsonDecoder().decode(CreateResponse.self, from: data).apply(to: object) } return API.Command<Self, Self>(method: .POST, path: endpoint(.POST), body: object, mapper: mapper) } func replaceCommand() throws -> API.Command<Self, Self> { guard self.objectId != nil else { throw ParseError(code: .missingObjectId, message: "objectId must not be nil") } let mapper = { (data: Data) -> Self in var updatedObject = self updatedObject.originalData = nil let object = try ParseCoding.jsonDecoder().decode(ReplaceResponse.self, from: data).apply(to: updatedObject) // MARK: The lines below should be removed when server supports PATCH. guard let originalData = self.originalData, let original = try? ParseCoding.jsonDecoder().decode(Self.self, from: originalData), original.hasSameObjectId(as: object) else { return object } return try object.merge(with: original) } return API.Command<Self, Self>(method: .PUT, path: endpoint, body: self, mapper: mapper) } func updateCommand() throws -> API.Command<Self, Self> { guard self.objectId != nil else { throw ParseError(code: .missingObjectId, message: "objectId must not be nil") } let mapper = { (data: Data) -> Self in var updatedObject = self updatedObject.originalData = nil let object = try ParseCoding.jsonDecoder().decode(UpdateResponse.self, from: data).apply(to: updatedObject) guard let originalData = self.originalData, let original = try? ParseCoding.jsonDecoder().decode(Self.self, from: originalData), original.hasSameObjectId(as: object) else { return object } return try object.merge(with: original) } return API.Command<Self, Self>(method: .PATCH, path: endpoint, body: self, mapper: mapper) } } // MARK: Deletable extension ParseInstallation { /** Deletes the `ParseInstallation` *synchronously* with the current data from the server. - parameter options: A set of header options sent to the server. Defaults to an empty set. - throws: An error of `ParseError` type. - important: If an object deleted has the same objectId as current, it will automatically update the current. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ public func delete(options: API.Options = []) throws { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) _ = try deleteCommand().execute(options: options) try Self.updateKeychainIfNeeded([self], deleting: true) } /** Deletes the `ParseInstallation` *asynchronously* and executes the given callback block. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute when completed. It should have the following argument signature: `(Result<Void, ParseError>)`. - important: If an object deleted has the same objectId as current, it will automatically update the current. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ public func delete( options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<Void, ParseError>) -> Void ) { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) do { try deleteCommand() .executeAsync(options: options, callbackQueue: callbackQueue) { result in switch result { case .success: do { try Self.updateKeychainIfNeeded([self], deleting: true) completion(.success(())) } catch { let returnError: ParseError! if let parseError = error as? ParseError { returnError = parseError } else { returnError = ParseError(code: .unknownError, message: error.localizedDescription) } completion(.failure(returnError)) } case .failure(let error): completion(.failure(error)) } } } catch let error as ParseError { callbackQueue.async { completion(.failure(error)) } } catch { callbackQueue.async { completion(.failure(ParseError(code: .unknownError, message: error.localizedDescription))) } } } func deleteCommand() throws -> API.NonParseBodyCommand<NoBody, NoBody> { guard isSaved else { throw ParseError(code: .unknownError, message: "Cannot Delete an object without id") } return API.NonParseBodyCommand<NoBody, NoBody>( method: .DELETE, path: endpoint ) { (data) -> NoBody in let error = try? ParseCoding.jsonDecoder().decode(ParseError.self, from: data) if let error = error { throw error } else { return NoBody() } } } } // MARK: Batch Support public extension Sequence where Element: ParseInstallation { /** Saves a collection of installations *synchronously* all at once and throws an error if necessary. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter ignoringCustomObjectIdConfig: Ignore checking for `objectId` when `ParseConfiguration.isAllowingCustomObjectIds = true` to allow for mixed `objectId` environments. Defaults to false. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - returns: Returns a Result enum with the object if a save was successful or a `ParseError` if it failed. - throws: An error of type `ParseError`. - important: If an object saved has the same objectId as current, it will automatically update the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - warning: If you are using `ParseConfiguration.isAllowingCustomObjectIds = true` and plan to generate all of your `objectId`'s on the client-side then you should leave `ignoringCustomObjectIdConfig = false`. Setting `ParseConfiguration.isAllowingCustomObjectIds = true` and `ignoringCustomObjectIdConfig = true` means the client will generate `objectId`'s and the server will generate an `objectId` only when the client does not provide one. This can increase the probability of colliding `objectId`'s as the client and server `objectId`'s may be generated using different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the client-side checks are disabled. Developers are responsible for handling such cases. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func saveAll(batchLimit limit: Int? = nil, // swiftlint:disable:this function_body_length transaction: Bool = ParseSwift.configuration.isUsingTransactions, ignoringCustomObjectIdConfig: Bool = false, options: API.Options = []) throws -> [(Result<Self.Element, ParseError>)] { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) var childObjects = [String: PointerType]() var childFiles = [UUID: ParseFile]() var error: ParseError? let installations = map { $0 } for installation in installations { let group = DispatchGroup() group.enter() installation.ensureDeepSave(options: options) { (savedChildObjects, savedChildFiles, parseError) -> Void in //If an error occurs, everything should be skipped if parseError != nil { error = parseError } savedChildObjects.forEach {(key, value) in if error != nil { return } if childObjects[key] == nil { childObjects[key] = value } else { error = ParseError(code: .unknownError, message: "circular dependency") return } } savedChildFiles.forEach {(key, value) in if error != nil { return } if childFiles[key] == nil { childFiles[key] = value } else { error = ParseError(code: .unknownError, message: "circular dependency") return } } group.leave() } group.wait() if let error = error { throw error } } var returnBatch = [(Result<Self.Element, ParseError>)]() let commands = try map { try $0.saveCommand(ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig) } let batchLimit = limit != nil ? limit! : ParseConstants.batchLimit try canSendTransactions(transaction, objectCount: commands.count, batchLimit: batchLimit) let batches = BatchUtils.splitArray(commands, valuesPerSegment: batchLimit) try batches.forEach { let currentBatch = try API.Command<Self.Element, Self.Element> .batch(commands: $0, transaction: transaction) .execute(options: options, childObjects: childObjects, childFiles: childFiles) returnBatch.append(contentsOf: currentBatch) } try Self.Element.updateKeychainIfNeeded(returnBatch.compactMap {try? $0.get()}) return returnBatch } /** Saves a collection of installations all at once *asynchronously* and executes the completion block when done. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter ignoringCustomObjectIdConfig: Ignore checking for `objectId` when `ParseConfiguration.isAllowingCustomObjectIds = true` to allow for mixed `objectId` environments. Defaults to false. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<[(Result<Element, ParseError>)], ParseError>)`. - important: If an object saved has the same objectId as current, it will automatically update the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - warning: If you are using `ParseConfiguration.isAllowingCustomObjectIds = true` and plan to generate all of your `objectId`'s on the client-side then you should leave `ignoringCustomObjectIdConfig = false`. Setting `ParseConfiguration.isAllowingCustomObjectIds = true` and `ignoringCustomObjectIdConfig = true` means the client will generate `objectId`'s and the server will generate an `objectId` only when the client does not provide one. This can increase the probability of colliding `objectId`'s as the client and server `objectId`'s may be generated using different algorithms. This can also lead to overwriting of `ParseObject`'s by accident as the client-side checks are disabled. Developers are responsible for handling such cases. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func saveAll( // swiftlint:disable:this function_body_length cyclomatic_complexity batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.isUsingTransactions, ignoringCustomObjectIdConfig: Bool = false, options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<[(Result<Element, ParseError>)], ParseError>) -> Void ) { batchCommand(method: .save, batchLimit: limit, transaction: transaction, ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig, options: options, callbackQueue: callbackQueue, completion: completion) } /** Creates a collection of installations all at once *asynchronously* and executes the completion block when done. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<[(Result<Element, ParseError>)], ParseError>)`. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func createAll( // swiftlint:disable:this function_body_length cyclomatic_complexity batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.isUsingTransactions, options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<[(Result<Element, ParseError>)], ParseError>) -> Void ) { batchCommand(method: .create, batchLimit: limit, transaction: transaction, options: options, callbackQueue: callbackQueue, completion: completion) } /** Replaces a collection of installations all at once *asynchronously* and executes the completion block when done. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<[(Result<Element, ParseError>)], ParseError>)`. - important: If an object replaced has the same objectId as current, it will automatically replace the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func replaceAll( // swiftlint:disable:this function_body_length cyclomatic_complexity batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.isUsingTransactions, options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<[(Result<Element, ParseError>)], ParseError>) -> Void ) { batchCommand(method: .replace, batchLimit: limit, transaction: transaction, options: options, callbackQueue: callbackQueue, completion: completion) } /** Updates a collection of installations all at once *asynchronously* and executes the completion block when done. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<[(Result<Element, ParseError>)], ParseError>)`. - important: If an object updated has the same objectId as current, it will automatically update the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ internal func updateAll( // swiftlint:disable:this function_body_length cyclomatic_complexity batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.isUsingTransactions, options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<[(Result<Element, ParseError>)], ParseError>) -> Void ) { batchCommand(method: .update, batchLimit: limit, transaction: transaction, options: options, callbackQueue: callbackQueue, completion: completion) } internal func batchCommand( // swiftlint:disable:this function_parameter_count method: Method, batchLimit limit: Int?, transaction: Bool, ignoringCustomObjectIdConfig: Bool = false, options: API.Options, callbackQueue: DispatchQueue, completion: @escaping (Result<[(Result<Element, ParseError>)], ParseError>) -> Void ) { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) let uuid = UUID() let queue = DispatchQueue(label: "com.parse.batch.\(uuid)", qos: .default, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil) queue.sync { var childObjects = [String: PointerType]() var childFiles = [UUID: ParseFile]() var error: ParseError? let installations = map { $0 } for installation in installations { let group = DispatchGroup() group.enter() installation .ensureDeepSave(options: options, // swiftlint:disable:next line_length isShouldReturnIfChildObjectsFound: true) { (savedChildObjects, savedChildFiles, parseError) -> Void in //If an error occurs, everything should be skipped if parseError != nil { error = parseError } savedChildObjects.forEach {(key, value) in if error != nil { return } if childObjects[key] == nil { childObjects[key] = value } else { error = ParseError(code: .unknownError, message: "circular dependency") return } } savedChildFiles.forEach {(key, value) in if error != nil { return } if childFiles[key] == nil { childFiles[key] = value } else { error = ParseError(code: .unknownError, message: "circular dependency") return } } group.leave() } group.wait() if let error = error { callbackQueue.async { completion(.failure(error)) } return } } do { var returnBatch = [(Result<Self.Element, ParseError>)]() let commands: [API.Command<Self.Element, Self.Element>]! switch method { case .save: commands = try map { try $0.saveCommand(ignoringCustomObjectIdConfig: ignoringCustomObjectIdConfig) } case .create: commands = map { $0.createCommand() } case .replace: commands = try map { try $0.replaceCommand() } case .update: commands = try map { try $0.updateCommand() } } let batchLimit = limit != nil ? limit! : ParseConstants.batchLimit try canSendTransactions(transaction, objectCount: commands.count, batchLimit: batchLimit) let batches = BatchUtils.splitArray(commands, valuesPerSegment: batchLimit) var completed = 0 for batch in batches { API.Command<Self.Element, Self.Element> .batch(commands: batch, transaction: transaction) .executeAsync(options: options, callbackQueue: callbackQueue, childObjects: childObjects, childFiles: childFiles) { results in switch results { case .success(let saved): returnBatch.append(contentsOf: saved) if completed == (batches.count - 1) { try? Self.Element.updateKeychainIfNeeded(returnBatch.compactMap {try? $0.get()}) completion(.success(returnBatch)) } completed += 1 case .failure(let error): callbackQueue.async { completion(.failure(error)) } return } } } } catch { callbackQueue.async { if let parseError = error as? ParseError { completion(.failure(parseError)) } else { completion(.failure(.init(code: .unknownError, message: error.localizedDescription))) } } } } } /** Fetches a collection of installations *synchronously* all at once and throws an error if necessary. - parameter includeKeys: The name(s) of the key(s) to include that are `ParseObject`s. Use `["*"]` to include all keys one level deep. This is similar to `include` and `includeAll` for `Query`. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns a Result enum with the object if a fetch was successful or a `ParseError` if it failed. - throws: An error of type `ParseError`. - important: If an object fetched has the same objectId as current, it will automatically update the current. - warning: The order in which installations are returned are not guarenteed. You shouldn't expect results in any particular order. */ func fetchAll(includeKeys: [String]? = nil, options: API.Options = []) throws -> [(Result<Self.Element, ParseError>)] { if (allSatisfy { $0.className == Self.Element.className}) { let uniqueObjectIds = Set(compactMap { $0.objectId }) var query = Self.Element.query(containedIn(key: "objectId", array: [uniqueObjectIds])) .limit(uniqueObjectIds.count) if let include = includeKeys { query = query.include(include) } let fetchedObjects = try query.find(options: options) var fetchedObjectsToReturn = [(Result<Self.Element, ParseError>)]() uniqueObjectIds.forEach { let uniqueObjectId = $0 if let fetchedObject = fetchedObjects.first(where: {$0.objectId == uniqueObjectId}) { fetchedObjectsToReturn.append(.success(fetchedObject)) } else { fetchedObjectsToReturn.append(.failure(ParseError(code: .objectNotFound, // swiftlint:disable:next line_length message: "objectId \"\(uniqueObjectId)\" was not found in className \"\(Self.Element.className)\""))) } } try Self.Element.updateKeychainIfNeeded(fetchedObjects) return fetchedObjectsToReturn } else { throw ParseError(code: .unknownError, message: "all items to fetch must be of the same class") } } /** Fetches a collection of installations all at once *asynchronously* and executes the completion block when done. - parameter includeKeys: The name(s) of the key(s) to include that are `ParseObject`s. Use `["*"]` to include all keys one level deep. This is similar to `include` and `includeAll` for `Query`. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<[(Result<Element, ParseError>)], ParseError>)`. - important: If an object fetched has the same objectId as current, it will automatically update the current. - warning: The order in which installations are returned are not guarenteed. You shouldn't expect results in any particular order. */ func fetchAll( includeKeys: [String]? = nil, options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<[(Result<Element, ParseError>)], ParseError>) -> Void ) { if (allSatisfy { $0.className == Self.Element.className}) { let uniqueObjectIds = Set(compactMap { $0.objectId }) var query = Self.Element.query(containedIn(key: "objectId", array: [uniqueObjectIds])) if let include = includeKeys { query = query.include(include) } query.find(options: options, callbackQueue: callbackQueue) { result in switch result { case .success(let fetchedObjects): var fetchedObjectsToReturn = [(Result<Self.Element, ParseError>)]() uniqueObjectIds.forEach { let uniqueObjectId = $0 if let fetchedObject = fetchedObjects.first(where: {$0.objectId == uniqueObjectId}) { fetchedObjectsToReturn.append(.success(fetchedObject)) } else { fetchedObjectsToReturn.append(.failure(ParseError(code: .objectNotFound, // swiftlint:disable:next line_length message: "objectId \"\(uniqueObjectId)\" was not found in className \"\(Self.Element.className)\""))) } } try? Self.Element.updateKeychainIfNeeded(fetchedObjects) completion(.success(fetchedObjectsToReturn)) case .failure(let error): callbackQueue.async { completion(.failure(error)) } } } } else { callbackQueue.async { completion(.failure(ParseError(code: .unknownError, message: "all items to fetch must be of the same class"))) } } } /** Deletes a collection of installations *synchronously* all at once and throws an error if necessary. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter options: A set of header options sent to the server. Defaults to an empty set. - returns: Returns `nil` if the delete successful or a `ParseError` if it failed. 1. A `ParseError.Code.aggregateError`. This object's "errors" property is an array of other Parse.Error objects. Each error object in this array has an "object" property that references the object that could not be deleted (for instance, because that object could not be found). 2. A non-aggregate Parse.Error. This indicates a serious error that caused the delete operation to be aborted partway through (for instance, a connection failure in the middle of the delete). - throws: An error of type `ParseError`. - important: If an object deleted has the same objectId as current, it will automatically update the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func deleteAll(batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.isUsingTransactions, options: API.Options = []) throws -> [(Result<Void, ParseError>)] { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) var returnBatch = [(Result<Void, ParseError>)]() let commands = try map { try $0.deleteCommand() } let batchLimit = limit != nil ? limit! : ParseConstants.batchLimit try canSendTransactions(transaction, objectCount: commands.count, batchLimit: batchLimit) let batches = BatchUtils.splitArray(commands, valuesPerSegment: batchLimit) try batches.forEach { let currentBatch = try API.Command<Self.Element, (Result<Void, ParseError>)> .batch(commands: $0, transaction: transaction) .execute(options: options) returnBatch.append(contentsOf: currentBatch) } try Self.Element.updateKeychainIfNeeded(compactMap {$0}, deleting: true) return returnBatch } /** Deletes a collection of installations all at once *asynchronously* and executes the completion block when done. - parameter batchLimit: The maximum number of objects to send in each batch. If the items to be batched. is greater than the `batchLimit`, the objects will be sent to the server in waves up to the `batchLimit`. Defaults to 50. - parameter transaction: Treat as an all-or-nothing operation. If some operation failure occurs that prevents the transaction from completing, then none of the objects are committed to the Parse Server database. - parameter options: A set of header options sent to the server. Defaults to an empty set. - parameter callbackQueue: The queue to return to after completion. Default value of .main. - parameter completion: The block to execute. It should have the following argument signature: `(Result<[ParseError?], ParseError>)`. Each element in the array is either `nil` if the delete successful or a `ParseError` if it failed. 1. A `ParseError.Code.aggregateError`. This object's "errors" property is an array of other Parse.Error objects. Each error object in this array has an "object" property that references the object that could not be deleted (for instance, because that object could not be found). 2. A non-aggregate Parse.Error. This indicates a serious error that caused the delete operation to be aborted partway through (for instance, a connection failure in the middle of the delete). - important: If an object deleted has the same objectId as current, it will automatically update the current. - warning: If `transaction = true`, then `batchLimit` will be automatically be set to the amount of the objects in the transaction. The developer should ensure their respective Parse Servers can handle the limit or else the transactions can fail. - note: The default cache policy for this method is `.reloadIgnoringLocalCacheData`. If a developer desires a different policy, it should be inserted in `options`. */ func deleteAll( batchLimit limit: Int? = nil, transaction: Bool = ParseSwift.configuration.isUsingTransactions, options: API.Options = [], callbackQueue: DispatchQueue = .main, completion: @escaping (Result<[(Result<Void, ParseError>)], ParseError>) -> Void ) { var options = options options.insert(.cachePolicy(.reloadIgnoringLocalCacheData)) do { var returnBatch = [(Result<Void, ParseError>)]() let commands = try map({ try $0.deleteCommand() }) let batchLimit = limit != nil ? limit! : ParseConstants.batchLimit try canSendTransactions(transaction, objectCount: commands.count, batchLimit: batchLimit) let batches = BatchUtils.splitArray(commands, valuesPerSegment: batchLimit) var completed = 0 for batch in batches { API.Command<Self.Element, ParseError?> .batch(commands: batch, transaction: transaction) .executeAsync(options: options, callbackQueue: callbackQueue) { results in switch results { case .success(let saved): returnBatch.append(contentsOf: saved) if completed == (batches.count - 1) { try? Self.Element.updateKeychainIfNeeded(self.compactMap {$0}, deleting: true) completion(.success(returnBatch)) } completed += 1 case .failure(let error): completion(.failure(error)) return } } } } catch { callbackQueue.async { guard let parseError = error as? ParseError else { completion(.failure(ParseError(code: .unknownError, message: error.localizedDescription))) return } completion(.failure(parseError)) } } } } // swiftlint:disable:this file_length
48.325535
179
0.608604
724b5910e470414956a290458242cba325ad25a7
1,778
// // NSDateFormatter.swift // SodesCore // // Created by Jared Sinclair on 7/10/16. // // import Foundation public class RFC822Formatter { public static let sharedFormatter = RFC822Formatter() private let formatterWithWeekdays: DateFormatter private let formatterWithoutWeekdays: DateFormatter private let lock = NSLock() public init() { formatterWithWeekdays = DateFormatter.RFC822Formatter(includeWeekdays: true) formatterWithoutWeekdays = DateFormatter.RFC822Formatter(includeWeekdays: false) } public func string(from date: Date) -> String? { lock.lock() let withWeekdays = formatterWithWeekdays.string(from: date) lock.unlock() return withWeekdays } public func date(from string: String) -> Date? { // TODO: [MEDIUM] Ensure that we don't need a more efficient means of knowing // which formatter to try first (or not at all), etc. lock.lock() let withWeekdays = formatterWithWeekdays.date(from: string) lock.unlock() if let with = withWeekdays { return with } lock.lock() let withoutWeekdays = formatterWithoutWeekdays.date(from: string) lock.unlock() return withoutWeekdays } } private extension DateFormatter { static func RFC822Formatter(includeWeekdays include: Bool) -> DateFormatter { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") if include { formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z" } else { formatter.dateFormat = "dd MMM yyyy HH:mm:ss z" } return formatter } }
26.939394
88
0.624297
e641a75c2070599745b80cf10be584d6b1db0651
3,973
// // CountryAPI.swift // Concurrency // // Created by Cameron Rivera on 12/5/19. // Copyright © 2019 Cameron Rivera. All rights reserved. // import Foundation import UIKit enum NetworkingError: Error{ case badURL(String) case invalidData case networkClientError(Error) case invalidStatusCode(Int) case decodingError(Error) case noResponse case noImageFound } struct CountryAPI { static func obtainCountries(completion: @escaping (Result<[CountryInfo], NetworkingError>) -> ()) { let countryAPIURL = "https://restcountries.eu/rest/v2/name/united" // Start by creating URL guard let fileURL = URL(string: countryAPIURL) else { completion(.failure(.badURL(countryAPIURL))) return } let dataTask = URLSession.shared.dataTask(with: fileURL) { (data,response,error) in // Unwrap your data. guard let unwrappedData = data else { completion(.failure(.invalidData)) return } // Unwrap you error. if let unwrappedError = error{ completion(.failure(.networkClientError(unwrappedError))) return } // unwrap your response as a HTTPURLResponse guard let unwrappedResponse = response as? HTTPURLResponse else{ completion(.failure(.noResponse)) return } switch unwrappedResponse.statusCode{ case 200...299: break default: completion(.failure(.invalidStatusCode(unwrappedResponse.statusCode))) } // Decode do{ let countries = try JSONDecoder().decode([CountryInfo].self, from: unwrappedData) completion(.success(countries)) } catch { completion(.failure(.decodingError(error))) } } dataTask.resume() } static func obtainCountryFlag(_ countryCode: String, completion: @escaping (Result<UIImage?,NetworkingError>) -> ()){ DispatchQueue.global(qos: .userInitiated).async { var code: String = "" if countryCode == "uk"{ code = "vg" } else { code = countryCode } let flagURL = "https://www.countryflags.io/\(code)/flat/64.png" // URL guard let fileURL = URL(string: flagURL) else { completion(.failure(.badURL(flagURL))) return } // Get some data using URLSession this is asynchronous by default let dataTask = URLSession.shared.dataTask(with: fileURL) { (data, response, error) in guard let unwrappedData = data else { completion(.failure(.invalidData)) return } if let unwrappedError = error { completion(.failure(.networkClientError(unwrappedError))) } guard let unwrappedResponse = response as? HTTPURLResponse else { completion(.failure(.noResponse)) return } switch unwrappedResponse.statusCode{ case 200...299: break default: completion(.failure(.invalidStatusCode(unwrappedResponse.statusCode))) } guard let image = UIImage(data: unwrappedData) else { completion(.failure(.noImageFound)) return } completion(.success(image)) } dataTask.resume() } } }
32.834711
121
0.50969
673bef0784f590036ebeac949e182226c0d6db9d
2,887
// // TextTransformer.swift // ProtonTests // // Created by Rajdeep Kwatra on 11/1/20. // Copyright © 2020 Rajdeep Kwatra. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import UIKit import Proton struct TextEncoder: EditorContentEncoder { let textEncoders: [EditorContent.Name: AnyEditorTextEncoding<String>] = [ EditorContent.Name.paragraph: AnyEditorTextEncoding(ParagraphTextEncoder()), .text: AnyEditorTextEncoding(TextTransformer()), .newline: AnyEditorTextEncoding(NewlineTextEncoder()), ] let attachmentEncoders: [EditorContent.Name: AnyEditorContentAttachmentEncoding<String>] = [ EditorContent.Name("textField") : AnyEditorContentAttachmentEncoding(TextTransformer()), ] } struct ParagraphTextEncoder: EditorTextEncoding { func encode(name: EditorContent.Name, string: NSAttributedString) -> String { return contentsFrom(string).joined(separator: "\n") } } struct NewlineTextEncoder: EditorTextEncoding { func encode(name: EditorContent.Name, string: NSAttributedString) -> String { return "Name: `\(EditorContent.Name.newline.rawValue)` Text: `\n`" } } extension ParagraphTextEncoder { func contentsFrom(_ string: NSAttributedString) -> [String] { var contents = [String]() string.enumerateInlineContents().forEach { content in switch content.type { case .viewOnly: break case let .text(name, attributedString): let text = TextTransformer().encode(name: name, string: attributedString) contents.append(text) case let .attachment(name, _, contentView, _): let text = TextTransformer().encode(name: name, view: contentView) contents.append(text) } } return contents } } struct TextTransformer: EditorTextEncoding, AttachmentEncoding { func encode(name: EditorContent.Name, string: NSAttributedString) -> String { return "Name: `\(name.rawValue)` Text: `\(string.string)`" } func encode(name: EditorContent.Name, view: UIView) -> String { let contentViewType = String(describing: type(of: view)) return "Name: `\(name.rawValue)` ContentView: `\(contentViewType)`" //Type: `\(attachmentType)` } }
35.641975
96
0.680291
dd6b180c00abd32c53bd5ec71ccd4994ddbef3a0
5,971
/* * Copyright (c) 2014-present Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class ViewController: UIViewController { //MARK: IB outlets @IBOutlet var tableView: UITableView! @IBOutlet var buttonMenu: UIButton! @IBOutlet var titleLabel: UILabel! @IBOutlet weak var menuHeightConstraint: NSLayoutConstraint! //MARK: further class variables var slider: HorizontalItemList! var isMenuOpen = false var items: [Int] = [5, 6, 7] //MARK: class methods @IBAction func actionToggleMenu(_ sender: AnyObject) { titleLabel.superview?.constraints.forEach { constraint in print(" -> \(constraint.description)\n") } isMenuOpen = !isMenuOpen titleLabel.superview?.constraints.forEach { constraint in if constraint.firstItem === titleLabel && constraint.firstAttribute == .centerX { constraint.constant = isMenuOpen ? -100.0 : 0.0 return } if constraint.identifier == "TitleCenterY" { constraint.isActive = false let newConstraint = NSLayoutConstraint( item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: titleLabel.superview!, attribute: .centerY, multiplier: isMenuOpen ? 0.67 : 1.0, constant: 0) newConstraint.identifier = "TitleCenterY" newConstraint.isActive = true return } } menuHeightConstraint.constant = isMenuOpen ? 184.0 : 44.0 titleLabel.text = isMenuOpen ? "Select Item" : "Packing List" UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 10.0, options: .curveEaseIn, animations: { self.view.layoutIfNeeded() let angle: CGFloat = self.isMenuOpen ? .pi / 4 : 0.0 self.buttonMenu.transform = CGAffineTransform(rotationAngle: angle) }, completion: nil ) if isMenuOpen { slider = HorizontalItemList(inView: view) slider.didSelectItem = {index in print("add \(index)") self.items.append(index) self.tableView.reloadData() self.actionToggleMenu(self) } self.titleLabel.superview!.addSubview(slider) } else { slider.removeFromSuperview() } } func showItem(_ index: Int) { print("tapped item \(index)") let imageView = UIImageView(image: UIImage(named: "summericons_100px_0\(index).png")) imageView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5) imageView.layer.cornerRadius = 5.0 imageView.layer.masksToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(imageView) let conX = imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor) let conBottom = imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: imageView.frame.height) let conWidth = imageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.33, constant: -50.0) let conHeight = imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor) NSLayoutConstraint.activate([conX, conBottom, conWidth, conHeight]) view.layoutIfNeeded() UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, animations: { conBottom.constant = -imageView.frame.size.height/2 conWidth.constant = 0.0 self.view.layoutIfNeeded() }, completion: nil ) } } let itemTitles = ["Icecream money", "Great weather", "Beach ball", "Swim suit for him", "Swim suit for her", "Beach games", "Ironing board", "Cocktail mood", "Sunglasses", "Flip flops"] extension ViewController: UITableViewDelegate, UITableViewDataSource { // MARK: View Controller methods override func viewDidLoad() { super.viewDidLoad() self.tableView?.rowHeight = 54.0 } // MARK: Table View methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell cell.accessoryType = .none cell.textLabel?.text = itemTitles[items[indexPath.row]] cell.imageView?.image = UIImage(named: "summericons_100px_0\(items[indexPath.row]).png") return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) showItem(items[indexPath.row]) } }
36.187879
185
0.673589
db841e519fa06215e6c8ff27b0d1600dcf81b2b1
4,297
// // NewSelectLabelVC.swift // WorkspaceSettings.xcsettings FabricCareSymbols // // Created by 김광수 on 2020/06/21. // Copyright © 2020 김광수. All rights reserved. // import UIKit class NewSelectLabelVC: UIViewController { //MARK: - Passed Properties var laundryData: LaundryData? var userSelectIndex:Int? //MARK: - Local Properties var tableView = UITableView() var sectionTitle:[String] = [] var labelData:[[String]] = [] var userSelectLabel:[String] = [] // 사용자가 선택한 라벨 데이터 var tempUserSelectLabel:[String] = [] // 사용자가 SelectLabel 화면에서 선택한 데이터 lazy var titleHeight:CGFloat = view.frame.height/5/5 lazy var cellHeigh:CGFloat = view.frame.height/5/5*3 fileprivate func configureNavBar() { navigationItem.title = "라벨을 선택하세요" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "완료", style: .plain, target: self, action: #selector(tabCompleteButton(_:))) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "취소", style: .plain, target: self, action: #selector(tabCompleteButton(_:))) } //MARK: - Init fileprivate func configureTableView() { // configure TableView tableView.frame = view.frame tableView.dataSource = self tableView.delegate = self tableView.register(SelectLabelCell.self, forCellReuseIdentifier: SelectLabelCell.identifier) view.addSubview(tableView) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .blue // User seleced Label data Load fetchData() // configure navbar configureNavBar() // configure TableView configureTableView() } //MARK: - API //tabbar 엑션 처리 @objc func tabCompleteButton(_ sender:UIBarButtonItem) { guard let buttonTitle = sender.title, let userSelectIndex = userSelectIndex else { return } if buttonTitle == "완료" { laundryData?.saveUSerLabelData(index: userSelectIndex, labelList: tempUserSelectLabel) } navigationController?.popViewController(animated: true) } // 데이터 불러오기 func fetchData() { guard let laundryData = laundryData, let userSelectIndex = userSelectIndex else { return } sectionTitle = laundryData.labelCategoryData userSelectLabel = laundryData.fetchUserLabelData(index: userSelectIndex) for keyString in sectionTitle { labelData.append(laundryData.fetchLabelArray(category: keyString)) } } } //MARK: - UITableViewDataSource extension NewSelectLabelVC: UITableViewDataSource { // secton configure func numberOfSections(in tableView: UITableView) -> Int { return sectionTitle.count } // cell configure func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SelectLabelCell.identifier, for: indexPath) as! SelectLabelCell // 라벨데이터 전달 cell.delegate = self cell.userSelctLabelArray = userSelectLabel cell.labelDataArray = labelData[indexPath.section] return cell } } //MARK: - UITableViewDelegate extension NewSelectLabelVC: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return titleHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let label = UILabel() label.backgroundColor = UIColor(red: 17/255, green: 154/255, blue: 237/255, alpha: 1) label.text = sectionTitle[section] label.font = .boldSystemFont(ofSize: 20) label.textColor = .white return label } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeigh } } //MARK: - Protocol extension NewSelectLabelVC: SelectLabelDelegate { //사용자가 선택한 버튼 임시저장 func tabLabelButtonDelegate(labelName name: String) { if tempUserSelectLabel.contains(name) { // 이미 선택한 버튼 삭제(체크 해제) guard let index = tempUserSelectLabel.firstIndex(of: name) else { return } tempUserSelectLabel.remove(at: index) } else { // 선택한 버튼 추가 tempUserSelectLabel.append(name) } } }
28.084967
139
0.702583
264d6117d04f391b4eacb03407ed9289a41f798f
1,186
/* ExtensionDeclSyntax.swift This source file is part of the SDGSwift open source project. https://sdggiesbrecht.github.io/SDGSwift Copyright ©2018–2021 Jeremy David Giesbrecht and the SDGSwift project contributors. Soli Deo gloria. Licensed under the Apache Licence, Version 2.0. See http://www.apache.org/licenses/LICENSE-2.0 for licence information. */ #if !PLATFORM_NOT_SUPPORTED_BY_SWIFT_SYNTAX import SDGLogic import SwiftSyntax extension ExtensionDeclSyntax: Attributed, APISyntax, Constrained, Hidable, Inheritor { // MARK: - APISyntax internal func isPublic() -> Bool { return true } internal var shouldLookForChildren: Bool { return true } internal func createAPI(children: [APIElement]) -> [APIElement] { guard ¬children.isEmpty else { return [] } return [ .extension( ExtensionAPI( type: extendedType, constraints: genericWhereClause, children: children ) ) ] } // MARK: - Hidable internal var hidabilityIdentifier: TokenSyntax? { return extendedType.hidabilityIdentifier } } #endif
21.962963
89
0.664418
890a3ea8b8a0369bef3f9a10a4ff362a323bfc22
13,658
// // INSPhotosOverlayView.swift // INSPhotoViewer // // Created by Michal Zaborowski on 28.02.2016. // Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this library except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit public protocol INSPhotosOverlayViewable:class { var photosViewController: INSPhotosViewController? { get set } func populateWithPhoto(_ photo: INSPhotoViewable) func setHidden(_ hidden: Bool, animated: Bool) func view() -> UIView } extension INSPhotosOverlayViewable where Self: UIView { public func view() -> UIView { return self } } open class INSPhotosOverlayView: UIView , INSPhotosOverlayViewable { open private(set) var navigationBar: UINavigationBar! open private(set) var captionLabel: UILabel! open private(set) var deleteToolbar: UIToolbar! open private(set) var navigationItem: UINavigationItem! open weak var photosViewController: INSPhotosViewController? var configuration: INSConfiguration! private var currentPhoto: INSPhotoViewable? private var topShadow: CAGradientLayer! private var bottomShadow: CAGradientLayer! open var leftBarButtonItem: UIBarButtonItem? { didSet { navigationItem.leftBarButtonItem = leftBarButtonItem } } open var rightBarButtonItem: UIBarButtonItem? { didSet { navigationItem.rightBarButtonItem = rightBarButtonItem } } #if swift(>=4.0) open var titleTextAttributes: [NSAttributedString.Key : AnyObject] = [:] { didSet { navigationBar.titleTextAttributes = titleTextAttributes } } #else open var titleTextAttributes: [String : AnyObject] = [:] { didSet { navigationBar.titleTextAttributes = titleTextAttributes } } #endif init(frame: CGRect, configuration: INSConfiguration) { self.configuration = configuration super.init(frame: frame) setupShadows() setupNavigationBar() setupCaptionLabel() setupDeleteButton() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Pass the touches down to other views open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if let hitView = super.hitTest(point, with: event) , hitView != self { return hitView } return nil } open override func layoutSubviews() { // The navigation bar has a different intrinsic content size upon rotation, so we must update to that new size. // Do it without animation to more closely match the behavior in `UINavigationController` UIView.performWithoutAnimation { () -> Void in self.navigationBar.invalidateIntrinsicContentSize() self.navigationBar.layoutIfNeeded() } super.layoutSubviews() self.updateShadowFrames() } open func setHidden(_ hidden: Bool, animated: Bool) { if self.isHidden == hidden { return } if animated { self.isHidden = false self.alpha = hidden ? 1.0 : 0.0 UIView.animate(withDuration: 0.2, delay: 0.0, options: [.allowAnimatedContent, .allowUserInteraction], animations: { () -> Void in self.alpha = hidden ? 0.0 : 1.0 }, completion: { result in self.alpha = 1.0 self.isHidden = hidden }) } else { self.isHidden = hidden } } open func populateWithPhoto(_ photo: INSPhotoViewable) { self.currentPhoto = photo if let photosViewController = photosViewController { if let index = photosViewController.dataSource.indexOfPhoto(photo) { navigationItem.title = String(format:NSLocalizedString("%d of %d",comment:""), index+1, photosViewController.dataSource.numberOfPhotos) } captionLabel.attributedText = photo.attributedTitle } self.deleteToolbar.isHidden = photo.isDeletable != true } @objc private func closeButtonTapped(_ sender: UIBarButtonItem) { photosViewController?.dismiss(animated: true, completion: nil) } @objc private func actionButtonTapped(_ sender: UIBarButtonItem) { if let currentPhoto = currentPhoto { currentPhoto.loadImageWithCompletionHandler({ [weak self] (image, error) -> () in if let image = (image ?? currentPhoto.thumbnailImage) { let activityController = UIActivityViewController(activityItems: [image], applicationActivities: nil) activityController.popoverPresentationController?.barButtonItem = sender self?.photosViewController?.present(activityController, animated: true, completion: nil) } }); } } @objc private func deleteButtonTapped(_ sender: UIBarButtonItem) { photosViewController?.handleDeleteButtonTapped() } private func setupNavigationBar() { let spacer = UIView() spacer.translatesAutoresizingMaskIntoConstraints = false spacer.backgroundColor = configuration.navigationBarBackgroundColor addSubview(spacer) navigationBar = UINavigationBar() navigationBar.translatesAutoresizingMaskIntoConstraints = false navigationBar.backgroundColor = configuration.navigationBarBackgroundColor navigationBar.barTintColor = nil navigationBar.isTranslucent = true navigationBar.shadowImage = UIImage() navigationBar.setBackgroundImage(UIImage(), for: .default) navigationItem = UINavigationItem(title: "") navigationBar.items = [navigationItem] addSubview(navigationBar) let sTopConstraint: NSLayoutConstraint = NSLayoutConstraint(item: spacer, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0) let sLeadingConstraint: NSLayoutConstraint = NSLayoutConstraint(item: spacer, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0) let sTrailingConstraint: NSLayoutConstraint = NSLayoutConstraint(item: spacer, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0) let sBottomConstraint: NSLayoutConstraint = NSLayoutConstraint(item: spacer, attribute: .bottom, relatedBy: .equal, toItem: navigationBar!, attribute: .bottom, multiplier: 1, constant: 0.0) let topConstraint: NSLayoutConstraint if #available(iOS 11.0, *) { topConstraint = NSLayoutConstraint(item: navigationBar!, attribute: .top, relatedBy: .equal, toItem: self.safeAreaLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0.0) } else { topConstraint = NSLayoutConstraint(item: navigationBar!, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0) } let widthConstraint = NSLayoutConstraint(item: navigationBar!, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0.0) let horizontalPositionConstraint = NSLayoutConstraint(item: navigationBar!, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0) self.addConstraints([topConstraint, widthConstraint, horizontalPositionConstraint, sTopConstraint, sLeadingConstraint, sTrailingConstraint, sBottomConstraint ]) if !configuration.rightBarButtonHidden { rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(INSPhotosOverlayView.actionButtonTapped(_:))) } if configuration.leftBarButtonHidden { return } if let bundlePath = Bundle(for: type(of: self)).path(forResource: "INSPhotoGallery", ofType: "bundle") { let bundle = Bundle(path: bundlePath) leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "INSPhotoGalleryClose", in: bundle, compatibleWith: nil), landscapeImagePhone: UIImage(named: "INSPhotoGalleryCloseLandscape", in: bundle, compatibleWith: nil), style: .plain, target: self, action: #selector(INSPhotosOverlayView.closeButtonTapped(_:))) } else { leftBarButtonItem = UIBarButtonItem(title: "CLOSE".uppercased(), style: .plain, target: self, action: #selector(INSPhotosOverlayView.closeButtonTapped(_:))) } } private func setupCaptionLabel() { captionLabel = UILabel() captionLabel.translatesAutoresizingMaskIntoConstraints = false captionLabel.backgroundColor = UIColor.clear captionLabel.textColor = configuration.navigationTitleTextColor captionLabel.numberOfLines = 0 addSubview(captionLabel) let bottomConstraint: NSLayoutConstraint let leadingConstraint: NSLayoutConstraint let trailingConstraint: NSLayoutConstraint if #available(iOS 11.0, *) { bottomConstraint = NSLayoutConstraint(item: self.safeAreaLayoutGuide, attribute: .bottom, relatedBy: .equal, toItem: captionLabel, attribute: .bottom, multiplier: 1.0, constant: 8.0) leadingConstraint = NSLayoutConstraint(item: captionLabel!, attribute: .leading, relatedBy: .equal, toItem: self.safeAreaLayoutGuide, attribute: .leading, multiplier: 1.0, constant: 8.0) trailingConstraint = NSLayoutConstraint(item: self.safeAreaLayoutGuide, attribute: .trailing, relatedBy: .equal, toItem: captionLabel!, attribute: .trailing, multiplier: 1.0, constant: 8.0) } else { bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: captionLabel, attribute: .bottom, multiplier: 1.0, constant: 8.0) leadingConstraint = NSLayoutConstraint(item: captionLabel!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0) trailingConstraint = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: captionLabel!, attribute: .trailing, multiplier: 1.0, constant: 8.0) } self.addConstraints([bottomConstraint,leadingConstraint,trailingConstraint]) } private func setupShadows() { let startColor = configuration.shadowStartColor let endColor = configuration.shadowEndColor self.topShadow = CAGradientLayer() topShadow.colors = [startColor.cgColor, endColor.cgColor] self.layer.insertSublayer(topShadow, at: 0) self.bottomShadow = CAGradientLayer() bottomShadow.colors = [endColor.cgColor, startColor.cgColor] self.layer.insertSublayer(bottomShadow, at: 0) topShadow.isHidden = configuration.shadowHidden bottomShadow.isHidden = configuration.shadowHidden self.updateShadowFrames() } private func updateShadowFrames(){ topShadow.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 60) bottomShadow.frame = CGRect(x: 0, y: self.frame.height - 60, width: self.frame.width, height: 60) } private func setupDeleteButton() { deleteToolbar = UIToolbar() deleteToolbar.translatesAutoresizingMaskIntoConstraints = false deleteToolbar.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default) deleteToolbar.setShadowImage(UIImage(), forToolbarPosition: .any) deleteToolbar.isTranslucent = true let item = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(INSPhotosOverlayView.deleteButtonTapped(_:))) deleteToolbar.setItems([item], animated: false) addSubview(deleteToolbar) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: deleteToolbar, attribute: .bottom, multiplier: 1.0, constant: 0.0) let trailingConstraint = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: deleteToolbar, attribute: .trailing, multiplier: 1.0, constant: 0.0) let widthConstraint = NSLayoutConstraint(item: deleteToolbar!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 65) let heightConstraint = NSLayoutConstraint(item: deleteToolbar!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50) self.addConstraints([bottomConstraint,trailingConstraint,widthConstraint, heightConstraint]) } }
47.922807
322
0.671401
fc0f8b299892e491182f4838aff7d8941c74d0e8
2,099
// MIT License // // Copyright (c) 2017 Wesley Wickwire // // 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. func metadataPointer(type: Any.Type) -> UnsafeMutablePointer<Int> { return unsafeBitCast(type, to: UnsafeMutablePointer<Int>.self) } func metadata(of type: Any.Type) throws -> MetadataInfo { let kind = Kind(type: type) switch kind { case .struct: return StructMetadata(type: type) case .class: return ClassMetadata(type: type) case .existential: return ProtocolMetadata(type: type) case .tuple: return TupleMetadata(type: type) case .enum: return EnumMetadata(type: type) default: throw RuntimeError.couldNotGetTypeInfo(type: type, kind: kind) } } func swiftObject() -> Any.Type { class Temp {} let md = ClassMetadata(type: Temp.self) return md.pointer.pointee.superClass } func classIsSwiftMask() -> Int { #if canImport(Darwin) if #available(macOS 10.14.4, iOS 12.2, tvOS 12.2, watchOS 5.2, *) { return 2 } #endif return 1 }
34.409836
81
0.707003
ac0df4ce596e5bee184716339daaebb77a25a0a4
2,414
// // TaskEditorViewController.swift // Todobox // // Created by 전수열 on 12/26/15. // Copyright © 2015 Suyeol Jeon. All rights reserved. // import UIKit class TaskEditorViewController: UIViewController { @IBOutlet var titleInput: UITextField! @IBOutlet var textView: UITextView! var didAddHandler: ((Task) -> Void)? override func viewDidLoad() { super.viewDidLoad() self.textView.layer.cornerRadius = 5 self.textView.layer.borderColor = UIColor.lightGray.cgColor self.textView.layer.borderWidth = 1 / UIScreen.main.scale } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.titleInput.becomeFirstResponder() } @IBAction func cancelButtonDidTap() { self.titleInput.resignFirstResponder() if self.titleInput.text?.isEmpty == true { self.dismiss(animated: true, completion: nil) return } let yes = UIAlertAction(title: "작성 취소", style: .destructive) { _ in self.dismiss(animated: true, completion: nil) } let no = UIAlertAction(title: "계속 작성", style: .default) { _ in self.titleInput.becomeFirstResponder() } let alertController = UIAlertController( title: "앗!", message: "취소하면 작성중인 내용이 손실됩니다.\n취소하시겠어요?", preferredStyle: .alert ) alertController.addAction(yes) alertController.addAction(no) self.present(alertController, animated: true, completion: nil) } @IBAction func doneButtonDidTap() { guard let title = self.titleInput.text, !title.isEmpty else { self.shakeTitleInput() return } self.titleInput.resignFirstResponder() let newTask = Task(title: title, note: self.textView.text) self.didAddHandler?(newTask) self.dismiss(animated: true, completion: nil) } func shakeTitleInput() { UIView.animate(withDuration: 0.05, animations: { self.titleInput.frame.origin.x -= 5 }, completion: { _ in UIView.animate(withDuration: 0.05, animations: { self.titleInput.frame.origin.x += 10 }, completion: { _ in UIView.animate(withDuration: 0.05, animations: { self.titleInput.frame.origin.x -= 10 }, completion: { _ in UIView.animate(withDuration: 0.05, animations: { self.titleInput.frame.origin.x += 10 }, completion: { _ in UIView.animate(withDuration: 0.05, animations: { self.titleInput.frame.origin.x -= 5 }) }) }) }) }) } }
29.802469
117
0.675642
166c2f5db733ef55fb1ee6e7943072977d9af4ba
24,089
import Foundation import MQTTClientGJ @testable import CourierCore @testable import CourierMQTT class MockMQTTSession: IMQTTSession { var invokedPersistenceSetter = false var invokedPersistenceSetterCount = 0 var invokedPersistence: MQTTPersistence? var invokedPersistenceList = [MQTTPersistence?]() var invokedPersistenceGetter = false var invokedPersistenceGetterCount = 0 var stubbedPersistence: MQTTPersistence! var persistence: MQTTPersistence! { set { invokedPersistenceSetter = true invokedPersistenceSetterCount += 1 invokedPersistence = newValue invokedPersistenceList.append(newValue) } get { invokedPersistenceGetter = true invokedPersistenceGetterCount += 1 return stubbedPersistence } } var invokedDelegateSetter = false var invokedDelegateSetterCount = 0 var invokedDelegate: MQTTSessionDelegate? var invokedDelegateList = [MQTTSessionDelegate?]() var invokedDelegateGetter = false var invokedDelegateGetterCount = 0 var stubbedDelegate: MQTTSessionDelegate! var delegate: MQTTSessionDelegate! { set { invokedDelegateSetter = true invokedDelegateSetterCount += 1 invokedDelegate = newValue invokedDelegateList.append(newValue) } get { invokedDelegateGetter = true invokedDelegateGetterCount += 1 return stubbedDelegate } } var invokedStreamSSLLevelSetter = false var invokedStreamSSLLevelSetterCount = 0 var invokedStreamSSLLevel: String? var invokedStreamSSLLevelList = [String?]() var invokedStreamSSLLevelGetter = false var invokedStreamSSLLevelGetterCount = 0 var stubbedStreamSSLLevel: String! var streamSSLLevel: String! { set { invokedStreamSSLLevelSetter = true invokedStreamSSLLevelSetterCount += 1 invokedStreamSSLLevel = newValue invokedStreamSSLLevelList.append(newValue) } get { invokedStreamSSLLevelGetter = true invokedStreamSSLLevelGetterCount += 1 return stubbedStreamSSLLevel } } var invokedClientIdSetter = false var invokedClientIdSetterCount = 0 var invokedClientId: String? var invokedClientIdList = [String?]() var invokedClientIdGetter = false var invokedClientIdGetterCount = 0 var stubbedClientId: String! var clientId: String! { set { invokedClientIdSetter = true invokedClientIdSetterCount += 1 invokedClientId = newValue invokedClientIdList.append(newValue) } get { invokedClientIdGetter = true invokedClientIdGetterCount += 1 return stubbedClientId } } var invokedUserNameSetter = false var invokedUserNameSetterCount = 0 var invokedUserName: String? var invokedUserNameList = [String?]() var invokedUserNameGetter = false var invokedUserNameGetterCount = 0 var stubbedUserName: String! var userName: String! { set { invokedUserNameSetter = true invokedUserNameSetterCount += 1 invokedUserName = newValue invokedUserNameList.append(newValue) } get { invokedUserNameGetter = true invokedUserNameGetterCount += 1 return stubbedUserName } } var invokedPasswordSetter = false var invokedPasswordSetterCount = 0 var invokedPassword: String? var invokedPasswordList = [String?]() var invokedPasswordGetter = false var invokedPasswordGetterCount = 0 var stubbedPassword: String! var password: String! { set { invokedPasswordSetter = true invokedPasswordSetterCount += 1 invokedPassword = newValue invokedPasswordList.append(newValue) } get { invokedPasswordGetter = true invokedPasswordGetterCount += 1 return stubbedPassword } } var invokedKeepAliveIntervalSetter = false var invokedKeepAliveIntervalSetterCount = 0 var invokedKeepAliveInterval: UInt16? var invokedKeepAliveIntervalList = [UInt16]() var invokedKeepAliveIntervalGetter = false var invokedKeepAliveIntervalGetterCount = 0 var stubbedKeepAliveInterval: UInt16! = 0 var keepAliveInterval: UInt16 { set { invokedKeepAliveIntervalSetter = true invokedKeepAliveIntervalSetterCount += 1 invokedKeepAliveInterval = newValue invokedKeepAliveIntervalList.append(newValue) } get { invokedKeepAliveIntervalGetter = true invokedKeepAliveIntervalGetterCount += 1 return stubbedKeepAliveInterval } } var invokedCleanSessionFlagSetter = false var invokedCleanSessionFlagSetterCount = 0 var invokedCleanSessionFlag: Bool? var invokedCleanSessionFlagList = [Bool]() var invokedCleanSessionFlagGetter = false var invokedCleanSessionFlagGetterCount = 0 var stubbedCleanSessionFlag: Bool! = false var cleanSessionFlag: Bool { set { invokedCleanSessionFlagSetter = true invokedCleanSessionFlagSetterCount += 1 invokedCleanSessionFlag = newValue invokedCleanSessionFlagList.append(newValue) } get { invokedCleanSessionFlagGetter = true invokedCleanSessionFlagGetterCount += 1 return stubbedCleanSessionFlag } } var invokedWillFlagSetter = false var invokedWillFlagSetterCount = 0 var invokedWillFlag: Bool? var invokedWillFlagList = [Bool]() var invokedWillFlagGetter = false var invokedWillFlagGetterCount = 0 var stubbedWillFlag: Bool! = false var willFlag: Bool { set { invokedWillFlagSetter = true invokedWillFlagSetterCount += 1 invokedWillFlag = newValue invokedWillFlagList.append(newValue) } get { invokedWillFlagGetter = true invokedWillFlagGetterCount += 1 return stubbedWillFlag } } var invokedWillTopicSetter = false var invokedWillTopicSetterCount = 0 var invokedWillTopic: String? var invokedWillTopicList = [String?]() var invokedWillTopicGetter = false var invokedWillTopicGetterCount = 0 var stubbedWillTopic: String! var willTopic: String! { set { invokedWillTopicSetter = true invokedWillTopicSetterCount += 1 invokedWillTopic = newValue invokedWillTopicList.append(newValue) } get { invokedWillTopicGetter = true invokedWillTopicGetterCount += 1 return stubbedWillTopic } } var invokedWillMsgSetter = false var invokedWillMsgSetterCount = 0 var invokedWillMsg: Data? var invokedWillMsgList = [Data?]() var invokedWillMsgGetter = false var invokedWillMsgGetterCount = 0 var stubbedWillMsg: Data! var willMsg: Data! { set { invokedWillMsgSetter = true invokedWillMsgSetterCount += 1 invokedWillMsg = newValue invokedWillMsgList.append(newValue) } get { invokedWillMsgGetter = true invokedWillMsgGetterCount += 1 return stubbedWillMsg } } var invokedWillQoSSetter = false var invokedWillQoSSetterCount = 0 var invokedWillQoS: MQTTQosLevel? var invokedWillQoSList = [MQTTQosLevel]() var invokedWillQoSGetter = false var invokedWillQoSGetterCount = 0 var stubbedWillQoS: MQTTQosLevel! var willQoS: MQTTQosLevel { set { invokedWillQoSSetter = true invokedWillQoSSetterCount += 1 invokedWillQoS = newValue invokedWillQoSList.append(newValue) } get { invokedWillQoSGetter = true invokedWillQoSGetterCount += 1 return stubbedWillQoS } } var invokedWillRetainFlagSetter = false var invokedWillRetainFlagSetterCount = 0 var invokedWillRetainFlag: Bool? var invokedWillRetainFlagList = [Bool]() var invokedWillRetainFlagGetter = false var invokedWillRetainFlagGetterCount = 0 var stubbedWillRetainFlag: Bool! = false var willRetainFlag: Bool { set { invokedWillRetainFlagSetter = true invokedWillRetainFlagSetterCount += 1 invokedWillRetainFlag = newValue invokedWillRetainFlagList.append(newValue) } get { invokedWillRetainFlagGetter = true invokedWillRetainFlagGetterCount += 1 return stubbedWillRetainFlag } } var invokedProtocolLevelSetter = false var invokedProtocolLevelSetterCount = 0 var invokedProtocolLevel: MQTTProtocolVersion? var invokedProtocolLevelList = [MQTTProtocolVersion]() var invokedProtocolLevelGetter = false var invokedProtocolLevelGetterCount = 0 var stubbedProtocolLevel: MQTTProtocolVersion! var protocolLevel: MQTTProtocolVersion { set { invokedProtocolLevelSetter = true invokedProtocolLevelSetterCount += 1 invokedProtocolLevel = newValue invokedProtocolLevelList.append(newValue) } get { invokedProtocolLevelGetter = true invokedProtocolLevelGetterCount += 1 return stubbedProtocolLevel } } var invokedQueueSetter = false var invokedQueueSetterCount = 0 var invokedQueue: DispatchQueue? var invokedQueueList = [DispatchQueue?]() var invokedQueueGetter = false var invokedQueueGetterCount = 0 var stubbedQueue: DispatchQueue! var queue: DispatchQueue! { set { invokedQueueSetter = true invokedQueueSetterCount += 1 invokedQueue = newValue invokedQueueList.append(newValue) } get { invokedQueueGetter = true invokedQueueGetterCount += 1 return stubbedQueue } } var invokedTransportSetter = false var invokedTransportSetterCount = 0 var invokedTransport: MQTTTransportProtocol? var invokedTransportList = [MQTTTransportProtocol?]() var invokedTransportGetter = false var invokedTransportGetterCount = 0 var stubbedTransport: MQTTTransportProtocol! var transport: MQTTTransportProtocol! { set { invokedTransportSetter = true invokedTransportSetterCount += 1 invokedTransport = newValue invokedTransportList.append(newValue) } get { invokedTransportGetter = true invokedTransportGetterCount += 1 return stubbedTransport } } var invokedCertificatesSetter = false var invokedCertificatesSetterCount = 0 var invokedCertificates: [Any]? var invokedCertificatesList = [[Any]?]() var invokedCertificatesGetter = false var invokedCertificatesGetterCount = 0 var stubbedCertificates: [Any]! var certificates: [Any]! { set { invokedCertificatesSetter = true invokedCertificatesSetterCount += 1 invokedCertificates = newValue invokedCertificatesList.append(newValue) } get { invokedCertificatesGetter = true invokedCertificatesGetterCount += 1 return stubbedCertificates } } var invokedVoipSetter = false var invokedVoipSetterCount = 0 var invokedVoip: Bool? var invokedVoipList = [Bool]() var invokedVoipGetter = false var invokedVoipGetterCount = 0 var stubbedVoip: Bool! = false var voip: Bool { set { invokedVoipSetter = true invokedVoipSetterCount += 1 invokedVoip = newValue invokedVoipList.append(newValue) } get { invokedVoipGetter = true invokedVoipGetterCount += 1 return stubbedVoip } } var invokedUserPropertySetter = false var invokedUserPropertySetterCount = 0 var invokedUserProperty: [String: String]? var invokedUserPropertyList = [[String: String]?]() var invokedUserPropertyGetter = false var invokedUserPropertyGetterCount = 0 var stubbedUserProperty: [String: String]! var userProperty: [String: String]! { set { invokedUserPropertySetter = true invokedUserPropertySetterCount += 1 invokedUserProperty = newValue invokedUserPropertyList.append(newValue) } get { invokedUserPropertyGetter = true invokedUserPropertyGetterCount += 1 return stubbedUserProperty } } var invokedShouldEnableActivityCheckTimeoutSetter = false var invokedShouldEnableActivityCheckTimeoutSetterCount = 0 var invokedShouldEnableActivityCheckTimeout: Bool? var invokedShouldEnableActivityCheckTimeoutList = [Bool]() var invokedShouldEnableActivityCheckTimeoutGetter = false var invokedShouldEnableActivityCheckTimeoutGetterCount = 0 var stubbedShouldEnableActivityCheckTimeout: Bool! = false var shouldEnableActivityCheckTimeout: Bool { set { invokedShouldEnableActivityCheckTimeoutSetter = true invokedShouldEnableActivityCheckTimeoutSetterCount += 1 invokedShouldEnableActivityCheckTimeout = newValue invokedShouldEnableActivityCheckTimeoutList.append(newValue) } get { invokedShouldEnableActivityCheckTimeoutGetter = true invokedShouldEnableActivityCheckTimeoutGetterCount += 1 return stubbedShouldEnableActivityCheckTimeout } } var invokedShouldEnableConnectCheckTimeoutSetter = false var invokedShouldEnableConnectCheckTimeoutSetterCount = 0 var invokedShouldEnableConnectCheckTimeout: Bool? var invokedShouldEnableConnectCheckTimeoutList = [Bool]() var invokedShouldEnableConnectCheckTimeoutGetter = false var invokedShouldEnableConnectCheckTimeoutGetterCount = 0 var stubbedShouldEnableConnectCheckTimeout: Bool! = false var shouldEnableConnectCheckTimeout: Bool { set { invokedShouldEnableConnectCheckTimeoutSetter = true invokedShouldEnableConnectCheckTimeoutSetterCount += 1 invokedShouldEnableConnectCheckTimeout = newValue invokedShouldEnableConnectCheckTimeoutList.append(newValue) } get { invokedShouldEnableConnectCheckTimeoutGetter = true invokedShouldEnableConnectCheckTimeoutGetterCount += 1 return stubbedShouldEnableConnectCheckTimeout } } var invokedActivityCheckTimerIntervalSetter = false var invokedActivityCheckTimerIntervalSetterCount = 0 var invokedActivityCheckTimerInterval: TimeInterval? var invokedActivityCheckTimerIntervalList = [TimeInterval]() var invokedActivityCheckTimerIntervalGetter = false var invokedActivityCheckTimerIntervalGetterCount = 0 var stubbedActivityCheckTimerInterval: TimeInterval! var activityCheckTimerInterval: TimeInterval { set { invokedActivityCheckTimerIntervalSetter = true invokedActivityCheckTimerIntervalSetterCount += 1 invokedActivityCheckTimerInterval = newValue invokedActivityCheckTimerIntervalList.append(newValue) } get { invokedActivityCheckTimerIntervalGetter = true invokedActivityCheckTimerIntervalGetterCount += 1 return stubbedActivityCheckTimerInterval } } var invokedConnectTimeoutCheckTimerIntervalSetter = false var invokedConnectTimeoutCheckTimerIntervalSetterCount = 0 var invokedConnectTimeoutCheckTimerInterval: TimeInterval? var invokedConnectTimeoutCheckTimerIntervalList = [TimeInterval]() var invokedConnectTimeoutCheckTimerIntervalGetter = false var invokedConnectTimeoutCheckTimerIntervalGetterCount = 0 var stubbedConnectTimeoutCheckTimerInterval: TimeInterval! var connectTimeoutCheckTimerInterval: TimeInterval { set { invokedConnectTimeoutCheckTimerIntervalSetter = true invokedConnectTimeoutCheckTimerIntervalSetterCount += 1 invokedConnectTimeoutCheckTimerInterval = newValue invokedConnectTimeoutCheckTimerIntervalList.append(newValue) } get { invokedConnectTimeoutCheckTimerIntervalGetter = true invokedConnectTimeoutCheckTimerIntervalGetterCount += 1 return stubbedConnectTimeoutCheckTimerInterval } } var invokedConnectTimeoutSetter = false var invokedConnectTimeoutSetterCount = 0 var invokedConnectTimeout: TimeInterval? var invokedConnectTimeoutList = [TimeInterval]() var invokedConnectTimeoutGetter = false var invokedConnectTimeoutGetterCount = 0 var stubbedConnectTimeout: TimeInterval! var connectTimeout: TimeInterval { set { invokedConnectTimeoutSetter = true invokedConnectTimeoutSetterCount += 1 invokedConnectTimeout = newValue invokedConnectTimeoutList.append(newValue) } get { invokedConnectTimeoutGetter = true invokedConnectTimeoutGetterCount += 1 return stubbedConnectTimeout } } var invokedConnectTimestampGetter = false var invokedConnectTimestampGetterCount = 0 var stubbedConnectTimestamp: TimeInterval! var connectTimestamp: TimeInterval { invokedConnectTimestampGetter = true invokedConnectTimestampGetterCount += 1 return stubbedConnectTimestamp } var invokedInactivityTimeoutSetter = false var invokedInactivityTimeoutSetterCount = 0 var invokedInactivityTimeout: TimeInterval? var invokedInactivityTimeoutList = [TimeInterval]() var invokedInactivityTimeoutGetter = false var invokedInactivityTimeoutGetterCount = 0 var stubbedInactivityTimeout: TimeInterval! var inactivityTimeout: TimeInterval { set { invokedInactivityTimeoutSetter = true invokedInactivityTimeoutSetterCount += 1 invokedInactivityTimeout = newValue invokedInactivityTimeoutList.append(newValue) } get { invokedInactivityTimeoutGetter = true invokedInactivityTimeoutGetterCount += 1 return stubbedInactivityTimeout } } var invokedReadTimeoutSetter = false var invokedReadTimeoutSetterCount = 0 var invokedReadTimeout: TimeInterval? var invokedReadTimeoutList = [TimeInterval]() var invokedReadTimeoutGetter = false var invokedReadTimeoutGetterCount = 0 var stubbedReadTimeout: TimeInterval! var readTimeout: TimeInterval { set { invokedReadTimeoutSetter = true invokedReadTimeoutSetterCount += 1 invokedReadTimeout = newValue invokedReadTimeoutList.append(newValue) } get { invokedReadTimeoutGetter = true invokedReadTimeoutGetterCount += 1 return stubbedReadTimeout } } var invokedFastReconnectTimestampGetter = false var invokedFastReconnectTimestampGetterCount = 0 var stubbedFastReconnectTimestamp: TimeInterval! var fastReconnectTimestamp: TimeInterval { invokedFastReconnectTimestampGetter = true invokedFastReconnectTimestampGetterCount += 1 return stubbedFastReconnectTimestamp } var invokedLastInboundActivityTimestampGetter = false var invokedLastInboundActivityTimestampGetterCount = 0 var stubbedLastInboundActivityTimestamp: TimeInterval! var lastInboundActivityTimestamp: TimeInterval { invokedLastInboundActivityTimestampGetter = true invokedLastInboundActivityTimestampGetterCount += 1 return stubbedLastInboundActivityTimestamp } var invokedLastOutboundActivityTimestampGetter = false var invokedLastOutboundActivityTimestampGetterCount = 0 var stubbedLastOutboundActivityTimestamp: TimeInterval! var lastOutboundActivityTimestamp: TimeInterval { invokedLastOutboundActivityTimestampGetter = true invokedLastOutboundActivityTimestampGetterCount += 1 return stubbedLastOutboundActivityTimestamp } var invokedConnect = false var invokedConnectCount = 0 var invokedConnectParameters: (connectHandler: MQTTConnectHandler?, Void)? var invokedConnectParametersList = [(connectHandler: MQTTConnectHandler?, Void)]() func connect(connectHandler: MQTTConnectHandler!) { invokedConnect = true invokedConnectCount += 1 invokedConnectParameters = (connectHandler, ()) invokedConnectParametersList.append((connectHandler, ())) } var invokedClose = false var invokedCloseCount = 0 var invokedCloseParameters: (disconnectHandler: MQTTDisconnectHandler?, Void)? var invokedCloseParametersList = [(disconnectHandler: MQTTDisconnectHandler?, Void)]() func close(disconnectHandler: MQTTDisconnectHandler!) { invokedClose = true invokedCloseCount += 1 invokedCloseParameters = (disconnectHandler, ()) invokedCloseParametersList.append((disconnectHandler, ())) } var invokedSubscribe = false var invokedSubscribeCount = 0 var invokedSubscribeParameters: (topics: [String: NSNumber]?, subscribeHandler: MQTTSubscribeHandler?)? var invokedSubscribeParametersList = [(topics: [String: NSNumber]?, subscribeHandler: MQTTSubscribeHandler?)]() var stubbedSubscribeResult: UInt16! = 0 func subscribe(toTopics topics: [String: NSNumber]!, subscribeHandler: MQTTSubscribeHandler!) -> UInt16 { invokedSubscribe = true invokedSubscribeCount += 1 invokedSubscribeParameters = (topics, subscribeHandler) invokedSubscribeParametersList.append((topics, subscribeHandler)) return stubbedSubscribeResult } var invokedUnsubscribeTopics = false var invokedUnsubscribeTopicsCount = 0 var invokedUnsubscribeTopicsParameters: (topics: [String]?, unsubscribeHandler: MQTTUnsubscribeHandler?)? var invokedUnsubscribeTopicsParametersList = [(topics: [String]?, unsubscribeHandler: MQTTUnsubscribeHandler?)]() var stubbedUnsubscribeTopicsResult: UInt16! = 0 func unsubscribeTopics(_ topics: [String]!, unsubscribeHandler: MQTTUnsubscribeHandler!) -> UInt16 { invokedUnsubscribeTopics = true invokedUnsubscribeTopicsCount += 1 invokedUnsubscribeTopicsParameters = (topics, unsubscribeHandler) invokedUnsubscribeTopicsParametersList.append((topics, unsubscribeHandler)) return stubbedUnsubscribeTopicsResult } var invokedPublishData = false var invokedPublishDataCount = 0 var invokedPublishDataParameters: (data: Data?, topic: String?, retainFlag: Bool, qos: MQTTQosLevel, publishHandler: MQTTPublishHandler?)? var invokedPublishDataParametersList = [(data: Data?, topic: String?, retainFlag: Bool, qos: MQTTQosLevel, publishHandler: MQTTPublishHandler?)]() var stubbedPublishDataResult: UInt16! = 0 func publishData(_ data: Data!, onTopic topic: String!, retain retainFlag: Bool, qos: MQTTQosLevel, publishHandler: MQTTPublishHandler!) -> UInt16 { invokedPublishData = true invokedPublishDataCount += 1 invokedPublishDataParameters = (data, topic, retainFlag, qos, publishHandler) invokedPublishDataParametersList.append((data, topic, retainFlag, qos, publishHandler)) return stubbedPublishDataResult } }
35.11516
152
0.689609
e01c410e76f1a01e26b855abd8af5384b45a2cb4
1,568
// // InputTableViewCell.swift // iOSGenesisSample // import UIKit import GenesisSwift final class InputTableViewCell: UITableViewCell { @IBOutlet weak var inputTitleLabel: UILabel! @IBOutlet weak var inputTextField: UITextField! var delegate: CellDidChangeDelegate? var data: DataProtocol! { didSet { inputTitleLabel.text = data.title inputTextField.text = data.value } } var indexPath: IndexPath! } // MARK: - UITextFieldDelegate extension InputTableViewCell: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let text = textField.text, let textRange = Range(range, in: text) { let updatedText = text.replacingCharacters(in: textRange, with: string) delegate?.cellTextFieldDidChange(value: updatedText, IndexPath: indexPath) } return true } func textFieldDidEndEditing(_ textField: UITextField) { if data is ValidatedInputData { let predicate = NSPredicate(format:"SELF MATCHES %@", data.regex) let evaluation = predicate.evaluate(with: inputTextField.text!) if evaluation == false { delegate?.cellTextFieldValidationError(indexPath, textField: inputTextField) } else { delegate?.cellTextFieldValidationPassed(indexPath) } } } }
30.745098
129
0.627551
9b8858c66571d096b0e1822f7dd9b558d438612f
1,533
// // NSObject+Rx+KVORepresentable.swift // Rx // // Created by Krunoslav Zaher on 11/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif extension Reactive where Base: NSObject { /** Specialization of generic `observe` method. This is a special overload because to observe values of some type (for example `Int`), first values of KVO type need to be observed (`NSNumber`), and then converted to result type. For more information take a look at `observe` method. */ // @warn_unused_result(message:"http://git.io/rxs.uo") public func observe<E: KVORepresentable>(_ type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable<E?> { return observe(E.KVOType.self, keyPath, options: options, retainSelf: retainSelf) .map(E.init) } } #if !DISABLE_SWIZZLING // KVO extension Reactive where Base: NSObject { /** Specialization of generic `observeWeakly` method. For more information take a look at `observeWeakly` method. */ // @warn_unused_result(message:"http://git.io/rxs.uo") public func observeWeakly<E: KVORepresentable>(_ type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable<E?> { return observeWeakly(E.KVOType.self, keyPath, options: options) .map(E.init) } } #endif
33.326087
180
0.664057
71a7625545848a6a8205e2e574c83d09aab1f104
370
// // UIImageView+AsyncLoading.swift // EBS_TEST // // Created by Vasile Morari on 29.10.2020. // import UIKit extension UIImageView { func setImage(stringURL: String) { guard let url = URL(string: stringURL) else { return } ImageCache.publicCache.load(url: url as NSURL) { [weak self] image in self?.image = image } } }
20.555556
77
0.624324
7a342608c86ce58f5dd49a42ffc91f918ccb5850
804
// // SidebarCategory.swift // Final Car Pro // // Created by Xudong Xu on 2/13/21. // import Foundation struct SidebarCategory: Codable { var name: String var symbol: String var label: String } extension SidebarCategory { static let `default` = [ (name: "All", symbol: "square.grid.2x2", label: ""), (name: "Pixel", symbol: "photo.on.rectangle.angled", label: "CUIThemePixelRendition"), (name: "Internal Link", symbol: "link.circle", label: "CUIInternalLinkRendition"), (name: "PDF", symbol: "doc", label: "CUIThemePDFRendition"), (name: "SVG", symbol: "doc.text", label: "CUIThemeSVGRendition"), (name: "Multisize ImageSet", symbol: "doc.on.doc", label: "CUIThemeMultisizeImageSetRendition"), ].map(SidebarCategory.init) }
29.777778
104
0.645522
164e7b4e5d67dc94523e34051a57a0212c689193
1,102
// Copyright 2022 Pera Wallet, LDA // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // PreviewLoadingCell.swift import Foundation import MacaroonUIKit import UIKit final class PreviewLoadingCell: BaseCollectionViewCell<PreviewLoadingView> { override init( frame: CGRect ) { super.init( frame: frame ) contextView.customize(PreviewLoadingViewCommonTheme()) } } extension PreviewLoadingCell { func startAnimating() { contextView.startAnimating() } func stopAnimating() { contextView.stopAnimating() } }
25.627907
76
0.708711
69d15e8bb9402e04edecc4522bc751331b506d50
2,386
// // addNewPostViewController.swift // Instagram // // Created by Mayank Gandhi on 16/08/18. // Copyright © 2018 Mayank Gandhi. All rights reserved. // import UIKit class addNewPostViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var PostImage: UIImageView! @IBOutlet weak var captionField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func AddPost(_ sender: Any) { print("add Post Pressed") let caption = captionField.text let image = PostImage.image Post.postUserImage(image: image, withCaption: caption, withCompletion: nil) } @IBAction func goBacktoPosts(_ sender: Any) { self.performSegue(withIdentifier: "BacktoPosts", sender: nil) } @IBAction func takeAPicture(_ sender: Any) { let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = true vc.sourceType = UIImagePickerControllerSourceType.photoLibrary self.present(vc, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // Get the image captured by the UIImagePickerController let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage let editedImage = info[UIImagePickerControllerEditedImage] as! UIImage // Do something with the images (based on your use case) PostImage.image = editedImage // Dismiss UIImagePickerController to go back to your original view controller dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
32.243243
115
0.66974
7592fe1fd130a144613565cc02aee179ef596c71
953
// // XCTestCase+FatalError.swift // SwiftyRequestTests // // Created by Steven Sherry on 4/22/19. // Copyright © 2019 Steven Sherry. All rights reserved. // import Foundation import XCTest @testable import SwiftyRequest extension XCTestCase { func expectFatalError(expectedMessage: String, testcase: @escaping () -> Void) { let expectation = self.expectation(description: "expectingFatalError") var assertionMessage: String? = nil FatalErrorUtil.replaceFatalError { message, _, _ in assertionMessage = message expectation.fulfill() self.unreachable() } DispatchQueue.global(qos: .userInitiated).async(execute: testcase) waitForExpectations(timeout: 2) { _ in XCTAssertEqual(assertionMessage, expectedMessage) FatalErrorUtil.restoreFatalError() } } private func unreachable() -> Never { repeat { RunLoop.current.run() } while (true) } }
23.825
82
0.685205
dd1ceaf51868b631408067c0977b8ef73254b359
915
// // Enterable.swift // // // Created by Kison Ho on 11/2/21. // import PythonKit /// An enterable protocol that can be entered and exited public protocol Enterable { /// Function to call when entering object mutating func enter() /// Function to call when exiting object mutating func exit() } /// disable gradients tracking public struct NoGrad: Enterable { /// Previous status private var prev = Bool(torch.is_grad_enabled())! public func enter() { torch.set_grad_enabled(false) } public func exit() { torch.set_grad_enabled(prev) } } /// A Python with like statement /// - Parameters: /// - obj: PythonObject that accept with statement /// - fn: function to call public func with<T: Enterable>( _ obj: inout T, fn: (T) throws -> Any) throws -> Any { // enter obj.enter() defer { obj.exit() } return try fn(obj) }
21.27907
86
0.63388
11ff50b80ab0b6f061c2b4d99b98a18feeeca107
3,591
// // InnerTextView.swift // SavannaKit // // Created by Louis D'hauwe on 09/07/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import Foundation import CoreGraphics #if os(macOS) import AppKit #else import UIKit #endif protocol InnerTextViewDelegate: AnyObject { func didUpdateCursorFloatingState() } class InnerTextView: TextView { weak var innerDelegate: InnerTextViewDelegate? var theme: SyntaxColorTheme? var cachedParagraphs: [Paragraph]? func invalidateCachedParagraphs() { cachedParagraphs = nil } func hideGutter() { gutterWidth = theme?.gutterStyle.minimumWidth ?? 0.0 } func updateGutterWidth(for numberOfCharacters: Int) { let leftInset: CGFloat = 4.0 let rightInset: CGFloat = 4.0 let charWidth: CGFloat = 10.0 gutterWidth = max(theme?.gutterStyle.minimumWidth ?? 0.0, CGFloat(numberOfCharacters) * charWidth + leftInset + rightInset) } #if os(iOS) var isCursorFloating = false override func beginFloatingCursor(at point: CGPoint) { super.beginFloatingCursor(at: point) isCursorFloating = true innerDelegate?.didUpdateCursorFloatingState() } override func endFloatingCursor() { super.endFloatingCursor() isCursorFloating = false innerDelegate?.didUpdateCursorFloatingState() } override public func draw(_ rect: CGRect) { guard let theme = theme else { super.draw(rect) hideGutter() return } let textView = self if theme.lineNumbersStyle == nil { hideGutter() let gutterRect = CGRect(x: 0, y: rect.minY, width: textView.gutterWidth, height: rect.height) let path = BezierPath(rect: gutterRect) path.fill() } else { let components = textView.text.components(separatedBy: .newlines) let count = components.count let maxNumberOfDigits = "\(count)".count textView.updateGutterWidth(for: maxNumberOfDigits) var paragraphs: [Paragraph] if let cached = textView.cachedParagraphs { paragraphs = cached } else { paragraphs = generateParagraphs(for: textView, flipRects: false) textView.cachedParagraphs = paragraphs } theme.gutterStyle.backgroundColor.setFill() let gutterRect = CGRect(x: 0, y: rect.minY, width: textView.gutterWidth, height: rect.height) let path = BezierPath(rect: gutterRect) path.fill() drawLineNumbers(paragraphs, in: rect, for: self) } super.draw(rect) } #endif var gutterWidth: CGFloat { set { #if os(macOS) textContainerInset = NSSize(width: newValue, height: 0) #else textContainerInset = UIEdgeInsets(top: 0, left: newValue, bottom: 0, right: 0) #endif } get { #if os(macOS) return textContainerInset.width #else return textContainerInset.left #endif } } // var gutterWidth: CGFloat = 0.0 { // didSet { // // textContainer.exclusionPaths = [UIBezierPath(rect: CGRect(x: 0.0, y: 0.0, width: gutterWidth, height: .greatestFiniteMagnitude))] // // } // // } #if os(iOS) override func caretRect(for position: UITextPosition) -> CGRect { var superRect = super.caretRect(for: position) guard let theme = theme else { return superRect } let font = theme.font // "descender" is expressed as a negative value, // so to add its height you must subtract its value superRect.size.height = font.pointSize - font.descender return superRect } #endif }
20.288136
134
0.657477
d9bd904b3ab79c7f3b0b34e43f6f49263cfc2401
3,563
import Foundation import ProjectDescription import TSCBasic import TSCUtility import TuistCore import TuistGraph import TuistSupport extension TuistGraph.Config { /// Maps a ProjectDescription.Config instance into a TuistGraph.Config model. /// - Parameters: /// - manifest: Manifest representation of Tuist config. /// - path: The path of the config file. static func from(manifest: ProjectDescription.Config, at path: AbsolutePath) throws -> TuistGraph.Config { let generatorPaths = GeneratorPaths(manifestDirectory: path) let generationOptions = try manifest.generationOptions.map { try TuistGraph.Config.GenerationOption.from(manifest: $0) } let compatibleXcodeVersions = TuistGraph.CompatibleXcodeVersions.from(manifest: manifest.compatibleXcodeVersions) let plugins = try manifest.plugins.map { try PluginLocation.from(manifest: $0, generatorPaths: generatorPaths) } let swiftVersion: TSCUtility.Version? if let configuredVersion = manifest.swiftVersion { swiftVersion = TSCUtility.Version(configuredVersion.major, configuredVersion.minor, configuredVersion.patch) } else { swiftVersion = nil } var cloud: TuistGraph.Cloud? if let manifestCloud = manifest.cloud { cloud = try TuistGraph.Cloud.from(manifest: manifestCloud) } var cache: TuistGraph.Cache? if let manifestCache = manifest.cache { cache = try TuistGraph.Cache.from(manifest: manifestCache, generatorPaths: generatorPaths) } if let forcedCacheDirectiory = forcedCacheDirectiory { cache = cache.map { TuistGraph.Cache(profiles: $0.profiles, path: forcedCacheDirectiory) } ?? TuistGraph.Cache(profiles: [], path: forcedCacheDirectiory) } return TuistGraph.Config( compatibleXcodeVersions: compatibleXcodeVersions, cloud: cloud, cache: cache, swiftVersion: swiftVersion, plugins: plugins, generationOptions: generationOptions, path: path ) } private static var forcedCacheDirectiory: AbsolutePath? { ProcessInfo.processInfo.environment[Constants.EnvironmentVariables.forceConfigCacheDirectory].map { AbsolutePath($0) } } } extension TuistGraph.Config.GenerationOption { /// Maps a ProjectDescription.Config.GenerationOptions instance into a TuistGraph.Config.GenerationOptions model. /// - Parameters: /// - manifest: Manifest representation of Tuist config generation options static func from(manifest: ProjectDescription.Config.GenerationOptions) throws -> TuistGraph.Config.GenerationOption { switch manifest { case let .xcodeProjectName(templateString): return .xcodeProjectName(templateString.description) case let .organizationName(name): return .organizationName(name) case let .developmentRegion(developmentRegion): return .developmentRegion(developmentRegion) case .disableShowEnvironmentVarsInScriptPhases: return .disableShowEnvironmentVarsInScriptPhases case .resolveDependenciesWithSystemScm: return .resolveDependenciesWithSystemScm case .disablePackageVersionLocking: return .disablePackageVersionLocking case let .lastXcodeUpgradeCheck(version): return .lastUpgradeCheck(.init(version.major, version.minor, version.patch)) } } }
43.45122
126
0.698007
e4153fedaefa8e70816726cca5bd1fb2b56c6bfe
219
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation class TestCommonConstants { static let networkTimeout = TimeInterval(180) }
18.25
49
0.730594
0a9522815e3219e8c2f5780a8ecf34ccad954988
1,539
// // Copyright © 2019 Juice Project. All rights reserved. // import XCTest import Juice final class ExternalInstanceRegistrationTests: XCTestCase { func testRegistrationOfInstance() throws { let apple = Apple() let container = try Container { builder in builder.register(instance: apple) .ownedByContainer() .asSelf() } XCTAssertNoThrow(try container.resolve(Apple.self)) let appleFromContainer = try container.resolve(Apple.self) XCTAssert(apple === appleFromContainer) } func testDoesNotKeepAReferenceToExternalInstanceIfOwnedExternally() throws { var orange: Orange? = Orange() let container = try Container { builder in builder.register(instance: orange!) .ownedExternally() .asSelf() } weak var weakReferenceToOrange = try container.resolve(Orange.self) XCTAssertNotNil(weakReferenceToOrange) orange = nil XCTAssertNil(weakReferenceToOrange) } func testKeepsAReferenceToExternalInstanceIfConfigured() throws { var orange: Orange? = Orange() let container = try Container { builder in builder.register(instance: orange!) .ownedByContainer() .asSelf() } weak var weakReferenceToOrange = try container.resolve(Orange.self) orange = nil XCTAssertNotNil(weakReferenceToOrange) } }
26.084746
80
0.617284
092daaec11d652a8e6ce00f409a225bdfee3c448
451
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 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 // RUN: not %target-swift-frontend %s -typecheck struct B<T{func a{class A a{class A:A{struct B<T:T.r
45.1
79
0.749446
b9b809b1c71734b586199991eba18d675a96ec4c
1,601
/*: ## Character Collections In Swift 4 Strings are back to being collections of characters. You can access different representations of the string through the appropriate collection view. */ import Foundation let country = "España" country.unicodeScalars // Unicode scalar 21-bit codes country.utf16 // UTF-16 encoding country.utf8 // UTF-8 encoding /*: ### Strings Are Collections Of Characters (Swift 4) A `String` is now a collection of characters by default so iterating over a `String` or `Substring` gives you each character in the `String`: */ // Swift 4 for character in country { print(character) } /*: To get the first or last character in a `String`. The result is an optional returning nil if the `String` is empty. */ country.first // "E" country.last // "a" /*: ### Random Element and Shuffle Swift 4.2 allows you to get a random element from any collection. When used on a `String` you get a random character or `nil` if the `String` is empty: */ let suits = "♠︎♣︎♥︎♦︎" suits.randomElement() /*: Iterate over shuffled `String` */ for suit in suits.shuffled() { print(suit) } /*: ### Counting Count is implemented for each of the collection views as it is dependent on the representation. The `count` property of a String is the character count. */ let spain = "España" spain.count // 6 spain.unicodeScalars.count // 6 spain.utf16.count // 6 spain.utf8.count // 7 /*: * * * [Previous page](@previous) - [Next page](@next) [Back to Introduction](Introduction) * * * */
22.236111
142
0.670206
50494394fe98f7b462b2c3f694c25e9026d5359c
7,704
// // APIStub.swift // Hint // // Created by Denys Telezhkin on 11.12.15. // Copyright © 2015 - present MLSDev. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Alamofire private func delay(_ delay:Double, closure:@escaping ()->Void) { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: closure) } public extension APIStub { /** Build stub model from file in specified bundle - parameter fileName: Name of the file to build response from - parameter bundle: bundle to look for file. */ public func buildModel(fromFileNamed fileName: String, inBundle bundle: Bundle = Bundle.main) { if let filePath = bundle.path(forResource: fileName as String, ofType: nil) { successData = try? Data(contentsOf: URL(fileURLWithPath: filePath)) } else { print("Failed to build model from \(fileName) in \(bundle)") } } } /// Error, that will be thrown if model creation failed while stubbing network request. public struct APIStubConstructionError : Error {} /** `APIStub` instance that is used to represent stubbed successful or unsuccessful response value. */ open class APIStub<Model, ErrorModel> { /// Should the stub be successful. By default - true open var successful = true /// Data to be passed to successful stub open var successData : Data? open var successDownloadURL : URL? /// Error to be passed into request's `errorParser` if stub is failureful. open var errorRequest : URLRequest? /// HTTP response to be passed into request's `errorParser` if stub is failureful. open var errorResponse: HTTPURLResponse? /// Error Data to be passed into request's `errorParser` if stub is failureful. open var errorData : Data? /// Loading error to be passed into request's `errorParser` if stub is failureful. open var loadingError : Error? /// Response model closure for successful API stub open var modelClosure : (() -> Model?)! /// Error model closure for unsuccessful API stub open var errorClosure: () -> APIError<ErrorModel> = { APIError(request: nil, response: nil, data: nil, error: nil) } /// Delay before stub is executed open var stubDelay = 0.1 /// Creates `APIStub`, and configures it for `request`. public init(request: BaseRequest<Model,ErrorModel>) { if let request = request as? APIRequest<Model,ErrorModel>{ let serializer = request.responseParser let errorSerializer = request.errorParser modelClosure = { [unowned self] in return serializer(nil,nil,self.successData,nil).value } errorClosure = { [unowned self] in return errorSerializer(nil, self.errorRequest, self.errorResponse, self.errorData, self.loadingError) } } else if let request = request as? UploadAPIRequest<Model,ErrorModel> { let serializer = request.responseParser let errorSerializer = request.errorParser modelClosure = { [unowned self] in return serializer(nil,nil,self.successData,nil).value } errorClosure = { [unowned self] in return errorSerializer(nil, self.errorRequest, self.errorResponse, self.errorData, self.loadingError) } } else if let request = request as? DownloadAPIRequest<Model,ErrorModel> { let serializer = request.responseParser let errorSerializer = request.errorParser modelClosure = { [unowned self] in return serializer(nil,nil,self.successDownloadURL,nil).value } errorClosure = { [unowned self] in return errorSerializer(nil, self.errorRequest, self.errorResponse, nil, self.loadingError) } } else { modelClosure = { return nil } } } /** Stub current request. - parameter successBlock: Success block to be executed when request finished - parameter failureBlock: Failure block to be executed if request fails. Nil by default. */ open func performStub(withSuccess successBlock: ((Model) -> Void)? = nil, failure failureBlock: ((APIError<ErrorModel>) -> Void)? = nil) { performStub { (dataResponse:DataResponse<Model>) -> Void in switch dataResponse.result { case .success(let model): successBlock?(model) case .failure(let error): if let error = error as? APIError<ErrorModel> { failureBlock?(error) } else { failureBlock?(APIError(request: nil, response:nil,data: nil, error: error)) } } } } /** Stub current request. - parameter completionBlock: Completion block to be executed when request is stubbed. */ open func performStub(withCompletion completionBlock : @escaping ((Alamofire.DataResponse<Model>) -> Void)) { delay(stubDelay) { let result : Alamofire.Result<Model> if self.successful { if let model = self.modelClosure?() { result = Result.success(model) } else { result = Result.failure(APIStubConstructionError()) } } else { result = Result.failure(self.errorClosure()) } let response: Alamofire.DataResponse<Model> = Alamofire.DataResponse(request: nil, response: nil, data: nil, result: result) completionBlock(response) } } /** Stub current download request. - parameter completionBlock: Completion block to be executed when request is stubbed. */ open func performStub(withCompletion completionBlock : @escaping ((Alamofire.DownloadResponse<Model>) -> Void)) { delay(stubDelay) { let result : Alamofire.Result<Model> if self.successful { if let model = self.modelClosure?() { result = Result.success(model) } else { result = .failure(APIStubConstructionError()) } } else { result = Result.failure(self.errorClosure()) } let response: DownloadResponse<Model> = DownloadResponse(request: nil, response: nil, temporaryURL: nil, destinationURL: nil, resumeData: nil, result: result) completionBlock(response) } } }
41.197861
170
0.634995
9130fb57d777a527939cc03b2eade12a5adbcb0d
1,575
// // detailViewController.swift // Flicks // // Created by Daniel Sung on 2/7/17. // Copyright © 2017 Daniel Sung. All rights reserved. // import UIKit class detailViewController: UIViewController { @IBOutlet weak var posterImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! var movie: NSDictionary! override func viewDidLoad() { super.viewDidLoad() let title = movie["title"] as? String titleLabel.text = title; let description = movie["overview"] as? String descriptionLabel.text = description let baseURL = "https://image.tmdb.org/t/p/w500" if let posterPath = movie["poster_path"] as? String{ let imageURL = NSURL(string: baseURL + posterPath) posterImageView.setImageWith(imageURL! as URL) } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
27.631579
106
0.640635
f42ee383ca2179b57f4fd6dd5e8e5e1e43f11e85
364
// // File.swift // // // Created by Daven.Gomes on 18/10/2021. // import Foundation protocol URLSessionProtocol { func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> Foundation.URLSessionDataTask func dataTask(with request: URLRequest) -> Foundation.URLSessionDataTask }
22.75
118
0.68956
29cbf3b228baa2e0578053046985853aa48a5d48
3,734
// // R1Interval+Interval.swift // S2Geometry // // Created by Marc Rollin on 4/17/17. // Copyright © 2017 Marc Rollin. All rights reserved. // import Foundation // MARK: Interval compliance extension R1Interval: Interval { /// Midpoint of the interval. var center: Double { return 0.5 * (low + high) } /// Length of the interval. /// The length of an empty interval is negative. var length: Double { return high - low } /// Whether the interval is empty. var isEmpty: Bool { return low > high } /// Interval representing a single point. init(point: Double) { low = point high = point } /// - returns: true iff the interval contains the point. func contains(point: Double) -> Bool { return low <= point && point <= high } /// - returns: true iff the interval contains the other interval. func contains(interval other: R1Interval) -> Bool { return other.isEmpty ? true : low <= other.low && other.high <= high } /// - returns: true iff the interval strictly contains the point. func interiorContains(point: Double) -> Bool { return low < point && point < high } /// - returns: true iff the interval strictly contains the other interval. func interiorContains(interval other: R1Interval) -> Bool { return other.isEmpty ? true : low < other.low && other.high < high } /// - returns: true iff the interval contains any points in common with the other interval. func intersects(with other: R1Interval) -> Bool { if low <= other.low { // interval.low ∈ self and interval is not empty return other.low <= high && other.low <= other.high } // low ∈ interval and self is not empty return low <= other.high && low <= high } /// Including the the other interval's boundary. /// /// - returns: true iff the interval's interior contains any points in common. func interiorIntersects(with other: R1Interval) -> Bool { return other.low < high && low < other.high && low < high && other.low <= other.high } /// - returns: the interval expanded so that it contains the given point. func add(point: Double) -> R1Interval { if isEmpty { return R1Interval(low: point, high: point) } else if point < low { return R1Interval(low: point, high: high) } else if point > high { return R1Interval(low: low, high: point) } return self } /// If margin is negative, then the function shrinks the interval on /// each side by margin instead. The resulting interval may be empty. Any /// expansion of an empty interval remains empty. /// /// - returns: an interval that has been expanded on each side by margin. func expanded(by margin: Double) -> R1Interval { if isEmpty { return self } return R1Interval(low: low - margin, high: high + margin) } /// - returns: the interval containing all points common with the given interval. func intersection(with other: R1Interval) -> R1Interval { return R1Interval(low: max(low, other.low), high: min(high, other.high)) } /// - returns: the smallest interval that contains this interval and the given interval. func union(with other: R1Interval) -> R1Interval { if isEmpty { return other } else if other.isEmpty { return self } return R1Interval(low: min(low, other.low), high: max(high, other.high)) } }
30.859504
95
0.596947
233710afb023abc4803637930a7721252dfb540d
10,980
import Foundation import JSONUtilities import xcproj public struct LegacyTarget { public var toolPath: String public var arguments: String? public var passSettings: Bool public var workingDirectory: String? public init( toolPath: String, passSettings: Bool = false, arguments: String? = nil, workingDirectory: String? = nil ) { self.toolPath = toolPath self.arguments = arguments self.passSettings = passSettings self.workingDirectory = workingDirectory } } extension LegacyTarget: Equatable { public static func == (lhs: LegacyTarget, rhs: LegacyTarget) -> Bool { return lhs.toolPath == rhs.toolPath && lhs.arguments == rhs.arguments && lhs.passSettings == rhs.passSettings && lhs.workingDirectory == rhs.workingDirectory } } public struct Target { public var name: String public var type: PBXProductType public var platform: Platform public var settings: Settings public var sources: [TargetSource] public var dependencies: [Dependency] public var prebuildScripts: [BuildScript] public var postbuildScripts: [BuildScript] public var configFiles: [String: String] public var scheme: TargetScheme? public var legacy: LegacyTarget? public var deploymentTarget: Version? internal var productName: String? public var isLegacy: Bool { return legacy != nil } public var filename: String { var filename = productName ?? name if let fileExtension = type.fileExtension { filename += ".\(fileExtension)" } return filename } public init( name: String, type: PBXProductType, platform: Platform, deploymentTarget: Version? = nil, settings: Settings = .empty, configFiles: [String: String] = [:], sources: [TargetSource] = [], dependencies: [Dependency] = [], prebuildScripts: [BuildScript] = [], postbuildScripts: [BuildScript] = [], scheme: TargetScheme? = nil, legacy: LegacyTarget? = nil ) { self.name = name self.type = type self.platform = platform self.deploymentTarget = deploymentTarget self.settings = settings self.configFiles = configFiles self.sources = sources self.dependencies = dependencies self.prebuildScripts = prebuildScripts self.postbuildScripts = postbuildScripts self.scheme = scheme self.legacy = legacy } } extension Target: CustomStringConvertible { public var description: String { return "\(platform.emoji) \(name): \(type)" } } extension Target { static func generateCrossPlaformTargets(jsonDictionary: JSONDictionary) throws -> JSONDictionary { guard let targetsDictionary: [String: JSONDictionary] = jsonDictionary["targets"] as? [String: JSONDictionary] else { return jsonDictionary } let platformReplacement = "$platform" var crossPlatformTargets: [String: JSONDictionary] = [:] for (targetName, target) in targetsDictionary { if let platforms = target["platform"] as? [String] { for platform in platforms { var platformTarget = target func replacePlatform(_ dictionary: JSONDictionary) -> JSONDictionary { var replaced = dictionary for (key, value) in dictionary { switch value { case let dictionary as JSONDictionary: replaced[key] = replacePlatform(dictionary) case let string as String: replaced[key] = string.replacingOccurrences(of: platformReplacement, with: platform) case let array as [JSONDictionary]: replaced[key] = array.map(replacePlatform) case let array as [String]: replaced[key] = array.map { $0.replacingOccurrences(of: platformReplacement, with: platform) } default: break } } return replaced } platformTarget = replacePlatform(platformTarget) platformTarget["platform"] = platform let platformSuffix = platformTarget["platformSuffix"] as? String ?? "_\(platform)" let platformPrefix = platformTarget["platformPrefix"] as? String ?? "" let newTargetName = platformPrefix + targetName + platformSuffix var settings = platformTarget["settings"] as? JSONDictionary ?? [:] if settings["configs"] != nil || settings["groups"] != nil || settings["base"] != nil { var base = settings["base"] as? JSONDictionary ?? [:] if base["PRODUCT_NAME"] == nil { base["PRODUCT_NAME"] = targetName } settings["base"] = base } else { if settings["PRODUCT_NAME"] == nil { settings["PRODUCT_NAME"] = targetName } } platformTarget["productName"] = targetName platformTarget["settings"] = settings crossPlatformTargets[newTargetName] = platformTarget } } else { crossPlatformTargets[targetName] = target } } var merged = jsonDictionary merged["targets"] = crossPlatformTargets return merged } } extension Target: Equatable { public static func == (lhs: Target, rhs: Target) -> Bool { return lhs.name == rhs.name && lhs.type == rhs.type && lhs.platform == rhs.platform && lhs.deploymentTarget == rhs.deploymentTarget && lhs.settings == rhs.settings && lhs.configFiles == rhs.configFiles && lhs.sources == rhs.sources && lhs.dependencies == rhs.dependencies && lhs.prebuildScripts == rhs.prebuildScripts && lhs.postbuildScripts == rhs.postbuildScripts && lhs.scheme == rhs.scheme && lhs.legacy == rhs.legacy } } public struct TargetScheme { public var testTargets: [String] public var configVariants: [String] public var gatherCoverageData: Bool public var commandLineArguments: [String: Bool] public var environmentVariables: [XCScheme.EnvironmentVariable] public init( testTargets: [String] = [], configVariants: [String] = [], gatherCoverageData: Bool = false, commandLineArguments: [String: Bool] = [:], environmentVariables: [XCScheme.EnvironmentVariable] = [] ) { self.testTargets = testTargets self.configVariants = configVariants self.gatherCoverageData = gatherCoverageData self.commandLineArguments = commandLineArguments self.environmentVariables = environmentVariables } } extension TargetScheme: Equatable { public static func == (lhs: TargetScheme, rhs: TargetScheme) -> Bool { return lhs.testTargets == rhs.testTargets && lhs.configVariants == rhs.configVariants } } extension TargetScheme: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { testTargets = jsonDictionary.json(atKeyPath: "testTargets") ?? [] configVariants = jsonDictionary.json(atKeyPath: "configVariants") ?? [] gatherCoverageData = jsonDictionary.json(atKeyPath: "gatherCoverageData") ?? false commandLineArguments = jsonDictionary.json(atKeyPath: "commandLineArguments") ?? [:] environmentVariables = try XCScheme.EnvironmentVariable.parseAll(jsonDictionary: jsonDictionary) } } extension LegacyTarget: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { toolPath = try jsonDictionary.json(atKeyPath: "toolPath") arguments = jsonDictionary.json(atKeyPath: "arguments") passSettings = jsonDictionary.json(atKeyPath: "passSettings") ?? false workingDirectory = jsonDictionary.json(atKeyPath: "workingDirectory") } } extension Target: NamedJSONDictionaryConvertible { public init(name: String, jsonDictionary: JSONDictionary) throws { self.name = jsonDictionary.json(atKeyPath: "name") ?? name productName = jsonDictionary.json(atKeyPath: "productName") let typeString: String = try jsonDictionary.json(atKeyPath: "type") if let type = PBXProductType(string: typeString) { self.type = type } else { throw SpecParsingError.unknownTargetType(typeString) } let platformString: String = try jsonDictionary.json(atKeyPath: "platform") if let platform = Platform(rawValue: platformString) { self.platform = platform } else { throw SpecParsingError.unknownTargetPlatform(platformString) } if let string: String = jsonDictionary.json(atKeyPath: "deploymentTarget") { deploymentTarget = try Version(string) } else if let double: Double = jsonDictionary.json(atKeyPath: "deploymentTarget") { deploymentTarget = try Version(double) } else { deploymentTarget = nil } settings = jsonDictionary.json(atKeyPath: "settings") ?? .empty configFiles = jsonDictionary.json(atKeyPath: "configFiles") ?? [:] if let source: String = jsonDictionary.json(atKeyPath: "sources") { sources = [TargetSource(path: source)] } else if let array = jsonDictionary["sources"] as? [Any] { sources = try array.flatMap { source in if let string = source as? String { return TargetSource(path: string) } else if let dictionary = source as? [String: Any] { return try TargetSource(jsonDictionary: dictionary) } else { return nil } } } else { sources = [] } if jsonDictionary["dependencies"] == nil { dependencies = [] } else { dependencies = try jsonDictionary.json(atKeyPath: "dependencies", invalidItemBehaviour: .fail) } prebuildScripts = jsonDictionary.json(atKeyPath: "prebuildScripts") ?? [] postbuildScripts = jsonDictionary.json(atKeyPath: "postbuildScripts") ?? [] scheme = jsonDictionary.json(atKeyPath: "scheme") legacy = jsonDictionary.json(atKeyPath: "legacy") } }
38.25784
126
0.595719
0a25ff72930b516f33d8ae2672d2b959686a9ee6
2,528
// // PodcastEpisodeCollectionViewItem.swift // Sphinx // // Created by Tomas Timinskas on 14/10/2020. // Copyright © 2020 Sphinx. All rights reserved. // import Cocoa class PodcastEpisodeCollectionViewItem: NSCollectionViewItem { @IBOutlet weak var playArrow: NSTextField! @IBOutlet weak var episodeImageView: NSImageView! @IBOutlet weak var episodeNameLabel: NSTextField! @IBOutlet weak var divider: NSBox! @IBOutlet weak var itemButton: CustomButton! var episode: PodcastEpisode! = nil public static var podcastImage: NSImage? = nil override func viewDidLoad() { super.viewDidLoad() itemButton.cursor = .pointingHand } func configureWidth(podcast: PodcastFeed?, and episode: PodcastEpisode, isLastRow: Bool, playing: Bool) { self.episode = episode episodeNameLabel.stringValue = episode.title ?? "No title" divider.isHidden = isLastRow self.view.wantsLayer = true self.view.layer?.backgroundColor = (playing ? NSColor.Sphinx.ChatListSelected : NSColor.clear).cgColor playArrow.isHidden = !playing if let img = PodcastEpisodeCollectionViewItem.podcastImage { loadEpisodeImage(episode: episode, with: img) } else if let image = podcast?.image, let url = URL(string: image) { MediaLoader.asyncLoadImage(imageView: episodeImageView, nsUrl: url, placeHolderImage: nil, completion: { img in PodcastEpisodeCollectionViewItem.podcastImage = img self.loadEpisodeImage(episode: episode, with: img) }, errorCompletion: { _ in self.loadEpisodeImage(episode: episode, with: NSImage(named: "profileAvatar")!) }) } } func loadEpisodeImage(episode: PodcastEpisode, with defaultImg: NSImage) { if let image = episode.image, let url = URL(string: image) { MediaLoader.asyncLoadImage(imageView: episodeImageView, nsUrl: url, placeHolderImage: nil, id: episode.id ?? -1, completion: { (img, id) in if self.isDifferentEpisode(episodeId: id) { return } self.episodeImageView.image = img }, errorCompletion: { _ in self.episodeImageView.image = defaultImg }) } else { self.episodeImageView.image = defaultImg } } func isDifferentEpisode(episodeId: Int) -> Bool { return episodeId != self.episode.id } }
37.176471
151
0.643987
fee1d1a586e3da4b5c20705b8e5c96f85b93374a
2,739
// // OptionsMethodTests.swift // QuickHatchTests // // Created by Daniel Koster on 9/17/20. // Copyright © 2020 DaVinci Labs. All rights reserved. // import XCTest import QuickHatch // swiftlint:disable force_try // swiftlint:disable force_cast class OptionsMethodTests: URLRequest_MethodTests { // OPTIONS Method tests func testOptionsRequest() { let request = try! URLRequest.options(url: commonURl, encoding: URLEncoding.default) XCTAssertTrue(request.url!.absoluteString == commonURl.absoluteString) XCTAssertTrue(request.httpMethod == "OPTIONS") } func testOptionsRequestWithURLString() { let request = try! URLRequest.options(url: "www.quickhatch.com", encoding: URLEncoding.default) XCTAssertTrue(request.url!.absoluteString == commonURl.absoluteString) XCTAssertTrue(request.httpMethod == "OPTIONS") } func testOptionsRequestWithParams() { let request = try! URLRequest.options(url: commonURl, params: ["age": 12], encoding: URLEncoding.default, headers: [:]) XCTAssertTrue(request.httpMethod == "OPTIONS") let body = String(data: request.httpBody!, encoding: .utf8) XCTAssertTrue(body == "age=12") } func testOptionsRequestWithParamsAndHeaders() { let request = try! URLRequest.options(url: commonURl, params: ["age": 12, "name": "quickhatch"], encoding: URLEncoding(destination: .httpBody), headers: ["auth": "123"]) let body = String(data: request.httpBody!, encoding: .utf8) XCTAssertTrue(body == "age=12&name=quickhatch") XCTAssertTrue(request.allHTTPHeaderFields!["auth"] == "123") XCTAssertTrue(request.httpMethod == "OPTIONS") } func testOptionsRequestWithParamsJsonEncoding() { let request = try! URLRequest.options(url: commonURl, params: ["age": 12, "name": "quickhatch"], encoding: JSONEncoding.default, headers: ["auth": "123"]) let dicBody = try! JSONSerialization.jsonObject(with: request.httpBody!, options: .allowFragments) as! [String: Any] XCTAssertTrue(dicBody["age"] as! Int == 12) XCTAssertTrue(dicBody["name"] as! String == "quickhatch") XCTAssertTrue(request.allHTTPHeaderFields!["auth"] == "123") XCTAssertTrue(request.httpMethod == "OPTIONS") } }
44.177419
124
0.579043
efbc14e5d56b4a30a96f44d48bb8aefff08e329f
905
// // StyleDictionaryColor.swift // // Do not edit directly // Generated on Fri, 15 Oct 2021 16:41:41 GMT import UIKit public enum StyleDictionaryColor { public static let baseGrayDark = UIColor(red: 0.067, green: 0.067, blue: 0.067, alpha: 1) public static let baseGrayLight = UIColor(red: 0.800, green: 0.800, blue: 0.800, alpha: 1) public static let baseGrayMedium = UIColor(red: 0.600, green: 0.600, blue: 0.600, alpha: 1) public static let baseGreen = UIColor(red: 0.000, green: 1.000, blue: 0.000, alpha: 1) public static let baseRed = UIColor(red: 1.000, green: 0.000, blue: 0.000, alpha: 1) public static let fontBase = UIColor(red: 1.000, green: 0.000, blue: 0.000, alpha: 1) public static let fontSecondary = UIColor(red: 0.000, green: 1.000, blue: 0.000, alpha: 1) public static let fontTertiary = UIColor(red: 0.800, green: 0.800, blue: 0.800, alpha: 1) }
41.136364
95
0.683978
20b2c3ae70b24e0b37a7192523118c2feafc87ce
506
// // FetchAccountDetailsUseCaseMock.swift // AccountTV-Unit-Tests // // Created by Jeans Ruiz on 8/8/20. // import RxSwift @testable import Account final class FetchAccountDetailsUseCaseMock: FetchAccountDetailsUseCase { var result: AccountResult? var error: Error? func execute() -> Observable<AccountResult> { if let error = error { return Observable.error(error) } if let result = result { return Observable.just(result) } return Observable.empty() } }
18.071429
72
0.693676
0af164058eded836e9697af8bb3e47d846c06746
989
// // ShakeShakeTests.swift // ShakeShakeTests // // Created by Štefan Töltési on 27/09/2018. // Copyright © 2018 Štefan Töltési. All rights reserved. // import XCTest @testable import ShakeShake class ShakeShakeTests: 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.72973
111
0.639029
cc31c8d8c6ec165d4b13edbc10d3eeccf20cafc2
71
import UIKit import DifferenceKit extension String: Differentiable {}
14.2
35
0.830986
56bd148c192186a962969ef5b7b2d6970483abdc
927
// // SwiftLibExampleTests.swift // SwiftLibExampleTests // // Created by Xuan Huy on 2/21/20. // Copyright © 2020 Xuan Huy. All rights reserved. // import XCTest @testable import SwiftLibExample class SwiftLibExampleTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.485714
111
0.662352
29dfae137b715d1a7b9c16028658598beb9bac09
2,007
import UIKit import ASWaveformPlayerView open class PlayerVC: UIViewController { var playerView: ASWaveformPlayerView! let localAudioURL = Bundle.main.url(forResource: "testAudio", withExtension: "mp3")! let remoteTrackURLString = "https://soundcloud.com/purplewerewolfs/the-guess-who-shakin-all-over" public var apiClient = APIClient() override open func viewDidLoad() { super.viewDidLoad() // init with track url load(trackURLString: remoteTrackURLString) view.addSubview(playerView) playerView.translatesAutoresizingMaskIntoConstraints = false let safeArea = view.safeAreaLayoutGuide let constrs = [ playerView.centerXAnchor.constraint(equalTo: safeArea.centerXAnchor), playerView.centerYAnchor.constraint(equalTo: safeArea.centerYAnchor), playerView.heightAnchor.constraint(equalToConstant: 128), playerView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor), playerView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor) ] NSLayoutConstraint.activate(constrs) } /// loads track in WaveformPlayerView public func load(trackURLString: String) { load(trackURL: URL(string: trackURLString)!) } /// loads track in WaveformPlayerView public func load(trackURL: URL) { do { try initPlayerView(trackURL) } catch { print(error.localizedDescription) } } private func initPlayerView(_ url: URL) throws { playerView = try ASWaveformPlayerView(audioURL: url, sampleCount: 1024, amplificationFactor: 500) playerView.normalColor = .lightGray playerView.progressColor = .orange playerView.allowSpacing = false } }
29.086957
101
0.620827
d96f2a89d83468db35de98b7a6736d9966fbdada
532
// // LoadingMoreCell.swift // BaseProject // // Created by MAC MINI on 25/04/2018. // Copyright © 2018 Wave. All rights reserved. // import UIKit class LoadingMoreCell: UITableViewCell { @IBOutlet weak var btnLoadMore: UIButton! 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 } }
20.461538
65
0.663534
6903f0554f6e6f685ba281711ff85e00307084ee
5,352
import CoreLocation import UIKit import MapboxCoreNavigation import MapboxMaps /** An object that notifies a map view when the user’s location changes, minimizing the noise that normally accompanies location updates from a `CLLocationManager` object. Unlike `Router` classes such as `RouteController` and `LegacyRouteController`, this class operates without a predefined route, matching the user’s location to the road network at large. If your application displays a `MapView` before starting turn-by-turn navigation, call `LocationManager.overrideLocationProvider(with:)` to override default location provider so that the map view always shows the location snapped to the road network. For example, use this class to show the user’s current location as they wander around town. This class depends on `PassiveLocationManager` to detect the user’s location as it changes. If you want location updates but do not need to display them on a map and do not want a dependency on the MapboxNavigation module, you can use `PassiveLocationManager` instead of this class. */ open class PassiveLocationProvider: NSObject, LocationProvider { /** Initializes the location provider with the given location manager. - parameter locationManager: A location manager that detects the user’s location as it changes. */ public init(locationManager: PassiveLocationManager) { self.locationManager = locationManager self.locationProviderOptions = LocationOptions() super.init() locationManager.delegate = self } /** The location provider's delegate. */ public weak var delegate: LocationProviderDelegate? // TODO: Consider replacing with public property. public func setDelegate(_ delegate: LocationProviderDelegate) { self.delegate = delegate } /** The location provider's location manager, which detects the user’s location as it changes. */ public let locationManager: PassiveLocationManager public var locationProviderOptions: LocationOptions // MARK: Heading And Location Updates public var heading: CLHeading? { return locationManager.systemLocationManager.heading } public func startUpdatingLocation() { locationManager.startUpdatingLocation() } public func stopUpdatingLocation() { locationManager.systemLocationManager.stopUpdatingLocation() } public var headingOrientation: CLDeviceOrientation { get { locationManager.systemLocationManager.headingOrientation } set { locationManager.systemLocationManager.headingOrientation = newValue } } public func startUpdatingHeading() { locationManager.systemLocationManager.startUpdatingHeading() } public func stopUpdatingHeading() { locationManager.systemLocationManager.stopUpdatingHeading() } public func dismissHeadingCalibrationDisplay() { locationManager.systemLocationManager.dismissHeadingCalibrationDisplay() } // MARK: Authorization Process public var authorizationStatus: CLAuthorizationStatus { CLLocationManager.authorizationStatus() } public func requestAlwaysAuthorization() { locationManager.systemLocationManager.requestAlwaysAuthorization() } public func requestWhenInUseAuthorization() { locationManager.systemLocationManager.requestWhenInUseAuthorization() } public var accuracyAuthorization: CLAccuracyAuthorization { if #available(iOS 14.0, *) { return locationManager.systemLocationManager.accuracyAuthorization } else { return .fullAccuracy } } @available(iOS 14.0, *) public func requestTemporaryFullAccuracyAuthorization(withPurposeKey purposeKey: String) { // CLLocationManager.requestTemporaryFullAccuracyAuthorization(withPurposeKey:) was introduced in the iOS 14 SDK in Xcode 12, so Xcode 11 doesn’t recognize it. let requestTemporaryFullAccuracyAuthorization = Selector(("requestTemporaryFullAccuracyAuthorizationWithPurposeKey:" as NSString) as String) guard locationManager.systemLocationManager.responds(to: requestTemporaryFullAccuracyAuthorization) else { return } locationManager.systemLocationManager.perform(requestTemporaryFullAccuracyAuthorization, with: purposeKey) } } extension PassiveLocationProvider: PassiveLocationManagerDelegate { @available(iOS 14.0, *) public func passiveLocationManagerDidChangeAuthorization(_ manager: PassiveLocationManager) { delegate?.locationProviderDidChangeAuthorization(self) } public func passiveLocationManager(_ manager: PassiveLocationManager, didUpdateLocation location: CLLocation, rawLocation: CLLocation) { delegate?.locationProvider(self, didUpdateLocations: [location]) } public func passiveLocationManager(_ manager: PassiveLocationManager, didUpdateHeading newHeading: CLHeading) { delegate?.locationProvider(self, didUpdateHeading: newHeading) } public func passiveLocationManager(_ manager: PassiveLocationManager, didFailWithError error: Error) { delegate?.locationProvider(self, didFailWithError: error) } }
41.169231
529
0.741592
08f9ecfbfd61015bff6f8cd6df6300cbdcd1352b
3,906
import Foundation /// Color scheme scenario, describing how the *foreground* color of the content should be configured to use appropriate color variants based on *background* color scheme. /// In Fiori UI design language, light color variants are mostly white, or a color with low alpha. Dark color variants are mostly black, charcoal, navy. /// /// - device: Use device interface style for background scheme. Foreground colors should be dynamically adjusted to natural variants (e.g. *light* or *dark* color variants) based on user interface style settings on iOS/macOS. This is the default setting for most content. /// - deviceInverse: Use inversed device interface style for background scheme. Foreground colors are inverted based on user interface style settings on iOS/macOS. If the device setting is in *light* user interface style, foreground colors will be adjusted to use *dark* color variants. /// - lightConstant: Use constant light background scheme. Foreground colors should constantly use *light* variants regardless of user interface style settings on iOS/macOS. /// - darkConstant: Use constant dark background scheme. Foreground colors should constantly use *dark* variants regardless of user interface style settings on iOS/macOS. public enum BackgroundColorScheme: String, CaseIterable { /// - Use device interface style for background scheme, so foreground colors will be adjusted based on device background case device /// - Use inversed device interface style for background scheme, so foreground colors will be adjusted as opposite to device background case deviceInverse /// - Use constant light background scheme regardless of device settings, which means components will use dark variants of foreground colors case lightConstant /// - Use constant dark background scheme regardless of device settings, which means components will use light variants of foreground colors case darkConstant /// - Foreground color scheme that matches with light background color @available(*, deprecated, renamed: "lightConstant") public static let light = BackgroundColorScheme.lightConstant /// - Foreground color scheme that matches with dark background color @available(*, deprecated, renamed: "darkConstant") public static let dark = BackgroundColorScheme.darkConstant /// :nodoc: @available(*, unavailable, renamed: "dark") public static let darkBackground = BackgroundColorScheme(rawValue: "unavailable") /// :nodoc: @available(*, unavailable, renamed: "light") public static let lightBackground = BackgroundColorScheme(rawValue: "unavailable") /// Helper function to return an opposite color scheme of current value. /// /// - Returns: inverse of current color scheme. public func inverse() -> BackgroundColorScheme { switch self { case .device: return .deviceInverse case .deviceInverse: return .device case .lightConstant: return .darkConstant case .darkConstant: return .lightConstant } } /// :nodoc: public init?(rawValue: String) { switch rawValue { case "device": self = .device case "deviceInverse": self = .deviceInverse case "lightConstant": self = .lightConstant case "darkConstant": self = .darkConstant default: return nil } } } extension BackgroundColorScheme: CustomDebugStringConvertible { /// :nodoc: public var debugDescription: String { switch self { case .deviceInverse: return "deviceInverse" case .device: return "device" case .darkConstant: return "darkConstant" case .lightConstant: return "lightConstant" } } }
46.5
286
0.697389
50de794e0d76e1f76fb43a85ca819db26da2215c
2,923
// // StickerBrowserFlow.swift // MessagesExtension // // Created by Jochen on 02.04.19. // Copyright © 2019 Jochen Pfeiffer. All rights reserved. // import Messages import RxCocoa import RxFlow import RxSwift import UIKit class StickerBrowserFlow: Flow { var root: Presentable { return rootViewController } private lazy var rootViewController: UINavigationController = { let viewController = UINavigationController() viewController.setNavigationBarHidden(true, animated: false) return viewController }() private let services: AppServices private let requestPresentationStyle: PublishSubject<MSMessagesAppPresentationStyle> private let currentPresentationStyle: Driver<MSMessagesAppPresentationStyle> init(withServices services: AppServices, requestPresentationStyle: PublishSubject<MSMessagesAppPresentationStyle>, currentPresentationStyle: Driver<MSMessagesAppPresentationStyle>) { self.services = services self.requestPresentationStyle = requestPresentationStyle self.currentPresentationStyle = currentPresentationStyle } deinit { print("\(type(of: self)): \(#function)") } func navigate(to step: Step) -> FlowContributors { guard let step = step as? PhotoStickerStep else { return .none } switch step { case .stickerBrowserIsRequired: return navigateToStickerBrowserScreen() case .addStickerIsPicked: return navigateToEditStickerScreen() case let .stickerIsPicked(sticker): return navigateToEditStickerScreen(with: sticker) default: return .none } } private func navigateToStickerBrowserScreen() -> FlowContributors { let viewController = StickerBrowserViewController.instantiate(withViewModel: StickerBrowserViewModel(), andServices: services) viewController.requestPresentationStyle = requestPresentationStyle viewController.currentPresentationStyle = currentPresentationStyle rootViewController.pushViewController(viewController, animated: false) return .one(flowContributor: .contribute(withNextPresentable: viewController, withNextStepper: viewController.viewModel)) } private func navigateToEditStickerScreen(with sticker: Sticker? = nil) -> FlowContributors { let existingOrNewSticker = sticker ?? Sticker() let editStickerFlow = EditStickerFlow(withServices: services) Flows.whenReady(flow1: editStickerFlow) { [unowned self] root in self.rootViewController.present(root, animated: true, completion: nil) } return .one(flowContributor: .contribute(withNextPresentable: editStickerFlow, withNextStepper: OneStepper(withSingleStep: PhotoStickerStep.editStickerIsRequired(existingOrNewSticker)))) } }
37
156
0.718782
26dafbdca14009f57e30261ec237656947210d71
2,139
// // ViewController.swift // Ceres // // Created by James Havinga on 2020/05/25. // Copyright © 2020 James Havinga. All rights reserved. // import UIKit import RealityKit class ViewController: UIViewController { @IBOutlet var arView: ARView! @IBOutlet weak var textPanel: UIVisualEffectView! @IBOutlet weak var dropButton: UIButton! @IBOutlet weak var websiteLink: UIButton! override func viewDidLoad() { super.viewDidLoad() // Load the "Box" scene from the "Experience" Reality File let boxAnchor = try! Experience.loadBox() // Add the box anchor to the scene arView.scene.anchors.append(boxAnchor) //Custom Behaviour boxAnchor.actions.showInterface.onAction = handleShowInterface(_:) boxAnchor.actions.startDropGrapes.onAction = handleStartDropGrapes(_:) boxAnchor.actions.stopDropGrapes.onAction = handleStopDropGrapes(_:) } //MARK: - Custom Behaviour func handleShowInterface(_ entity: Entity?) { guard entity != nil else { return } print("Scene Started") textPanel.isHidden = false websiteLink.isHidden = false dropButton.isHidden = true } func handleStartDropGrapes(_ entity: Entity?) { guard entity != nil else { return } print("Start Drop Grapes") textPanel.isHidden = false websiteLink.isHidden = true dropButton.isHidden = false } func handleStopDropGrapes(_ entity: Entity?) { guard entity != nil else { return } print("Stop Drop Grapes") textPanel.isHidden = true websiteLink.isHidden = true dropButton.isHidden = true } //MARK: - Custom Trigger @IBAction func onDropGrapesTapped(_ sender: Any) { if let sceneAnchor = arView.scene.anchors[0] as? Experience.Box { sceneAnchor.notifications.dropGrapes.post() } } }
25.464286
78
0.58906
2886292e35266ad0391a168e05e3782c9251006e
2,832
// RUN: %target-swift-frontend -g -Xllvm -sil-print-debuginfo -emit-silgen %s | %FileCheck %s func nop1() {} func nop2() {} enum Binary { case On case Off } func isOn(_ b: Binary) -> Bool { return b == .On } // CHECK: [[LOC:loc "[^"]+"]] // First, check that we don't assign fresh locations to each case statement, // except for any relevant debug value instructions. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test11iySi_tF func test1(i: Int) { switch i { // CHECK-NOT: [[LOC]]:[[@LINE+1]] case 0: // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]] // CHECK-NOT: [[LOC]]:[[@LINE-1]] nop1() // CHECK-NOT: [[LOC]]:[[@LINE+1]] case 1: // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]] // CHECK-NOT: [[LOC]]:[[@LINE-1]] nop1() default: // CHECK-NOT: [[LOC]]:[[@LINE]] nop1() } } // Next, check that case statements and switch subjects have the same locations. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test21sySS_tF func test2(s: String) { switch s { case "a": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10 nop1() case "b": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10 nop2() default: nop1() } } // Fallthrough shouldn't affect case statement locations. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test31sySS_tF func test3(s: String) { switch s { case "a", "b": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-2]]:10 // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10 nop1() fallthrough case "b", "c": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-7]]:10 // CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE-8]]:10 nop2() fallthrough default: nop1() } } // It should be possible to set breakpoints on where clauses. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test41byAA6BinaryO_tF func test4(b: Binary) { switch b { case let _ // CHECK-NOT: [[LOC]]:[[@LINE]] where isOn(b): // CHECK: [[LOC]]:[[@LINE]]:11 nop1() case let _ // CHECK-NOT: [[LOC]]:[[@LINE]] where !isOn(b): // CHECK: [[LOC]]:[[@LINE]]:11 nop2() default: nop1() } } // Check that we set the right locations before/after nested switches. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test51sySS_tF func test5(s: String) { switch s { case "a": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10 switch "b" { case "b": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-1]]:12 nop1() default: nop2() } if "c" == "c" { // CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE]] nop1() } default: nop1() } if "d" == "d" { // CHECK: string_literal utf8 "d", [[LOC]]:[[@LINE]] nop1() } }
26.971429
93
0.569562
7af9938c50a1a37ba28bc8d273ccb81ae8aa4e0f
1,691
// // SHSearchBarConfig.swift // SHSearchBar // // Created by Stefan Herold on 17/08/16. // Copyright © 2016 StefanHerold. All rights reserved. // import UIKit @available(iOS 11.0, *) public struct DBSideMenuItemConfig { /// The animation duration for showing/hiding the cancel button. public var titleTextColor: UIColor = defaultTextColor /// The animation duration for showing/hiding the cancel button. public var selectedTitleTextColor: UIColor = defaultTextColor /// The width and height for one square of the layout raster. All sizes, margins, distances, etc. are calculated as multiples of this value. public var titleFontSize: CGFloat = 15.0 /// The animation duration for showing/hiding the cancel button. public var imageColor: UIColor = defaultImageColor /// The animation duration for showing/hiding the cancel button. public var backgroundItemColor: UIColor = defaultBackgroundItemColor /// The animation duration for showing/hiding the cancel button. public var selectedBackgroundItemColor: UIColor = defaultBackgroundItemSelectedColor // MARK: - Lifecycle /// Use this initializer and then set the properties to your desired values. public init() {} // MARK: - Defaults /// This is used as the default text foreground color for button and text in the searchbar if nothing has been set by the user. public static var defaultTextColor = UIColor.white public static var defaultImageColor = UIColor.white public static var defaultBackgroundItemColor = UIColor.clear public static var defaultBackgroundItemSelectedColor = UIColor.darkGray }
36.76087
144
0.730928
46a1c99b27ea6bddb2436671ebf071bd2dfcb907
1,457
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // // This file was generated by Project Xcode Templates // Created by Wahyu Ady Prasetyo, // import Foundation import L10n_swift // [START] Start of example using plural localize helper // Plural localizable index by self cannot generate by SwiftGen // Normal localize use Localizable.strings for input data and generate by SwiftGen extension L10n { internal enum Plurals { /// Plural localization number of items /// /// 0: You don't gave any items /// /// 1: You have 1 item /// /// more than 1: You have %@ items /// /// Example definition localization when need to localize based on number of items /// /// - Parameter p1: Number of item /// - Returns: Localization text based on number of items internal static func pluralsNumberOfItems(_ p1: Int) -> String { return L10n.tr("PluralLocalizable", "numberOfItems", p1) } } } extension L10n { // No need change this method private static func tr(_ table: String, _ key: String, _ args: Int) -> String { // swiftlint:disable:next nslocalizedstring_key let localize = NSLocalizedString(key, tableName: table, bundle: .main, value: "No data", comment: "No comment") return String(format: localize, args) } }
30.354167
119
0.642416
9c4a0170edceb95b5fccf68ab129e4efd4dcafef
1,557
// // Copyright (c) 2018 KxCoding <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class ImageViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! var image: UIImage? @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBAction func dismiss(_ sender: Any) { dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() imageView.image = image } }
35.386364
81
0.725112
39133e3442787fe2e87985c42dd6ef44d4228c96
282
// // PictureHitsModel.swift // WeatherApp // // Created by Margiett Gil on 1/31/20. // Copyright © 2020 David Rifkin. All rights reserved. // import Foundation struct PictureHits: Codable { let hits: [Picture] } struct Picture: Codable { let largeImageURL: String }
15.666667
55
0.691489
f86bc2744997fecc539cb6e0fb2103bc6838f3ba
3,642
import UIKit class MenuView: UIView { private weak var delegate: MenuViewDelegate? init(delegate: MenuViewDelegate?) { self.delegate = delegate super.init(frame: .zero) loadSubviews() setupLayout() resumeButton.buttonActionClosure = { [unowned self] in delegate?.menuViewDidTapResume(self) } newGameButton.buttonActionClosure = { [unowned self] in delegate?.menuViewDidTapNewGame(self) } quitButton.buttonActionClosure = { [unowned self] in delegate?.menuViewDidTapQuit(self) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Subviews private func loadSubviews() { addSubview(blurEffectView) addSubview(resumeButton) addSubview(newGameButton) addSubview(quitButton) addSubview(pauseImageView) addSubview(pauseLabelText) } private let blurEffectView = Factory.blurEffectView private let resumeButton = Button(title: resume.localized, color: UIColor(color: .blue0091FC)) private let newGameButton = Button(title: newGame.localized, color: UIColor(color: .green6BE01A)) private let quitButton = Button(title: quit.localized, color: UIColor(color: .redE82654)) private let pauseImageView = Factory.pauseImageView private let pauseLabelText = Factory.pauseLabel // MARK: Layout private func setupLayout() { blurEffectView.snp.makeConstraints { $0.edges.equalToSuperview() } resumeButton.snp.makeConstraints { $0.width.equalTo(200) $0.height.equalTo(50) $0.centerXWithinMargins.equalToSuperview() $0.centerYWithinMargins.equalToSuperview() } newGameButton.snp.makeConstraints { $0.top.equalTo(resumeButton.snp.bottom).offset(15) $0.width.equalTo(200) $0.height.equalTo(50) $0.centerXWithinMargins.equalToSuperview() } quitButton.snp.makeConstraints { $0.width.equalTo(200) $0.height.equalTo(50) $0.centerXWithinMargins.equalToSuperview() $0.bottom.equalTo(-40) } pauseLabelText.snp.makeConstraints { $0.centerXWithinMargins.equalToSuperview() $0.bottom.equalTo(resumeButton.snp.top).offset(-40) } pauseImageView.snp.makeConstraints { $0.bottom.equalTo(pauseLabelText.snp.top).offset(-20) $0.centerXWithinMargins.equalToSuperview() } } } // MARK: - Delegate protocol MenuViewDelegate: class { func menuViewDidTapResume(_ menuView: MenuView) func menuViewDidTapNewGame(_ menuView: MenuView) func menuViewDidTapQuit(_ menuView: MenuView) } private extension MenuView { struct Factory { static var blurEffectView: UIVisualEffectView { let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) return UIVisualEffectView(effect: blurEffect) } static var pauseImageView: UIImageView { let view = UIImageView(frame: .zero) view.image = UIImage(asset: .pauseIcon) view.contentMode = .scaleAspectFit return view } static var pauseLabel: UILabel { let label = UILabel(frame: CGRect.zero) label.text = pause.localized label.font = UIFont(font: FontFamily.BebasNeue.bold, size: 30) label.textColor = UIColor(color: .white) return label } } }
31.947368
101
0.633443
ff8b1596fcb9f0af2f1f2b9b7948867b1f445403
7,703
// // Utils.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit import Darwin internal class ChartUtils { internal struct Math { internal static let FDEG2RAD = CGFloat(Double.pi / 180.0) internal static let FRAD2DEG = CGFloat(180.0 / Double.pi) internal static let DEG2RAD = Double.pi / 180.0 internal static let RAD2DEG = 180.0 / Double.pi } internal class func roundToNextSignificant(_ number: Double) -> Double { if ( number.isInfinite || number.isNaN || number == 0) { return number } let d = ceil(log10(number < 0.0 ? -number : number)) let pw = 1 - Int(d) let magnitude = pow(Double(10.0), Double(pw)) let shifted = round(number * magnitude) return shifted / magnitude } internal class func decimals(_ number: Double) -> Int { if (number == 0.0) { return 0 } let i = roundToNextSignificant(Double(number)) return Int(ceil(-log10(i))) + 2 } internal class func nextUp(_ number: Double) -> Double { if (number.isInfinite || number.isNaN) { return number } else { return number + Double.ulpOfOne } } /// - returns: the index of the DataSet that contains the closest value on the y-axis. This will return -Integer.MAX_VALUE if failure. internal class func closestDataSetIndex(_ valsAtIndex: [ChartSelectionDetail], value: Double, axis: ChartYAxis.AxisDependency?) -> Int { var index = -Int.max var distance = Double.greatestFiniteMagnitude for i in 0 ..< valsAtIndex.count { let sel = valsAtIndex[i] if (axis == nil || sel.dataSet?.axisDependency == axis) { let cdistance = abs(sel.value - value) if (cdistance < distance) { index = valsAtIndex[i].dataSetIndex distance = cdistance } } } return index } /// - returns: the minimum distance from a touch-y-value (in pixels) to the closest y-value (in pixels) that is displayed in the chart. internal class func getMinimumDistance(_ valsAtIndex: [ChartSelectionDetail], val: Double, axis: ChartYAxis.AxisDependency) -> Double { var distance = Double.greatestFiniteMagnitude for i in 0 ..< valsAtIndex.count { let sel = valsAtIndex[i] if (sel.dataSet!.axisDependency == axis) { let cdistance = abs(sel.value - val) if (cdistance < distance) { distance = cdistance } } } return distance } /// Calculates the position around a center point, depending on the distance from the center, and the angle of the position around the center. internal class func getPosition(_ center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint { return CGPoint( x: center.x + dist * cos(angle * Math.FDEG2RAD), y: center.y + dist * sin(angle * Math.FDEG2RAD) ) } internal class func drawText(_ context: CGContext?, text: String, point: CGPoint, align: NSTextAlignment, attributes: [String : AnyObject]?) { var point = point if (align == .center) { point.x -= text.size(withAttributes: convertToOptionalNSAttributedStringKeyDictionary(attributes)).width / 2.0 } else if (align == .right) { point.x -= text.size(withAttributes: convertToOptionalNSAttributedStringKeyDictionary(attributes)).width } UIGraphicsPushContext(context!) (text as NSString).draw(at: point, withAttributes: convertToOptionalNSAttributedStringKeyDictionary(attributes)) UIGraphicsPopContext() } internal class func drawMultilineText(_ context: CGContext?, text: String, knownTextSize: CGSize, point: CGPoint, align: NSTextAlignment, attributes: [String : AnyObject]?, constrainedToSize: CGSize) { var rect = CGRect(origin: CGPoint(), size: knownTextSize) rect.origin.x += point.x rect.origin.y += point.y if (align == .center) { rect.origin.x -= rect.size.width / 2.0 } else if (align == .right) { rect.origin.x -= rect.size.width } UIGraphicsPushContext(context!) (text as NSString).draw(with: rect, options: .usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary(attributes), context: nil) UIGraphicsPopContext() } internal class func drawMultilineText(_ context: CGContext?, text: String, point: CGPoint, align: NSTextAlignment, attributes: [String : AnyObject]?, constrainedToSize: CGSize) { let rect = text.boundingRect(with: constrainedToSize, options: .usesLineFragmentOrigin, attributes: convertToOptionalNSAttributedStringKeyDictionary(attributes), context: nil) drawMultilineText(context, text: text, knownTextSize: rect.size, point: point, align: align, attributes: attributes, constrainedToSize: constrainedToSize) } /// - returns: an angle between 0.0 < 360.0 (not less than zero, less than 360) internal class func normalizedAngleFromAngle( _ angle: CGFloat) -> CGFloat { var angle = angle while (angle < 0.0) { angle += 360.0 } return angle.truncatingRemainder(dividingBy: 360.0) } /// MARK: - Bridging functions internal class func bridgedObjCGetUIColorArray (swift array: [UIColor?]) -> [NSObject] { var newArray = [NSObject]() for val in array { if (val == nil) { newArray.append(NSNull()) } else { newArray.append(val!) } } return newArray } internal class func bridgedObjCGetUIColorArray (objc array: [NSObject]) -> [UIColor?] { var newArray = [UIColor?]() for object in array { newArray.append(object as? UIColor) } return newArray } internal class func bridgedObjCGetStringArray (swift array: [String?]) -> [NSObject] { var newArray = [NSObject]() for val in array { if (val == nil) { newArray.append(NSNull()) } else { newArray.append(val! as NSObject) } } return newArray } internal class func bridgedObjCGetStringArray (objc array: [NSObject]) -> [String?] { var newArray = [String?]() for object in array { newArray.append(object as? String) } return newArray } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
32.365546
203
0.581462
e8aaec75a97962f1c02a1b5e287eb6fdea1633d3
283
// // String+Localized.swift // ios-simple-app // // Created by Maciej Jurgielanis on 24/09/2019. // Copyright © 2019 StethoMe. All rights reserved. // import Foundation extension String { var localized: String { return NSLocalizedString(self, comment: "") } }
17.6875
51
0.667845
d5375922f7974a4c44a6e0cc239dd620d7eb5f4f
680
// // DistributionsAPI.swift // CrowdinSDK // // Created by Serhii Londar on 5/19/19. // import Foundation class DistributionsAPI: CrowdinAPI { let hashString: String init(hashString: String, organizationName: String? = nil, auth: CrowdinAuth? = nil, session: URLSession = .shared) { self.hashString = hashString super.init(organizationName: organizationName, auth: auth, session: session) } override var apiPath: String { return "distributions/metadata?hash=\(hashString)" } func getDistribution(completion: @escaping (DistributionsResponse?, Error?) -> Void) { self.cw_get(url: fullPath, completion: completion) } }
26.153846
120
0.692647
ac2eb7bdc275a0d0c149f840ceac6a9557c760cf
23,985
import UIKit public protocol TimelinePagerViewDelegate: AnyObject { func timelinePagerDidSelectEventView(_ eventView: EventView) func timelinePagerDidLongPressEventView(_ eventView: EventView) func timelinePager(timelinePager: TimelinePagerView, didTapTimelineAt date: Date) func timelinePagerDidBeginDragging(timelinePager: TimelinePagerView) func timelinePagerDidTransitionCancel(timelinePager: TimelinePagerView) func timelinePager(timelinePager: TimelinePagerView, willMoveTo date: Date) func timelinePager(timelinePager: TimelinePagerView, didMoveTo date: Date) func timelinePager(timelinePager: TimelinePagerView, didLongPressTimelineAt date: Date) // Editing func timelinePager(timelinePager: TimelinePagerView, didUpdate event: EventDescriptor) } public final class TimelinePagerView: UIView, UIGestureRecognizerDelegate, UIScrollViewDelegate, DayViewStateUpdating, UIPageViewControllerDataSource, UIPageViewControllerDelegate, TimelineViewDelegate { public weak var dataSource: EventDataSource? public weak var delegate: TimelinePagerViewDelegate? public private(set) var calendar: Calendar = Calendar.autoupdatingCurrent public var eventEditingSnappingBehavior: EventEditingSnappingBehavior { didSet { updateEventEditingSnappingBehavior() } } public var timelineScrollOffset: CGPoint { // Any view is fine as they are all synchronized let offset = (currentTimeline)?.container.contentOffset return offset ?? CGPoint() } private var currentTimeline: TimelineContainerController? { return pagingViewController.viewControllers?.first as? TimelineContainerController } public var autoScrollToFirstEvent = false private var pagingViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) private var style = TimelineStyle() private lazy var panGestureRecoognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:))) public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if otherGestureRecognizer.view is EventResizeHandleView { return false } return true } public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard gestureRecognizer == panGestureRecoognizer else { return super.gestureRecognizerShouldBegin(gestureRecognizer) } guard let pendingEvent = editedEventView else {return true} let eventFrame = pendingEvent.frame let position = panGestureRecoognizer.location(in: self) let contains = eventFrame.contains(position) return contains } public weak var state: DayViewState? { willSet(newValue) { state?.unsubscribe(client: self) } didSet { state?.subscribe(client: self) } } public init(calendar: Calendar) { self.calendar = calendar self.eventEditingSnappingBehavior = SnapTo15MinuteIntervals(calendar) super.init(frame: .zero) configure() } override public init(frame: CGRect) { self.eventEditingSnappingBehavior = SnapTo15MinuteIntervals(calendar) super.init(frame: frame) configure() } required public init?(coder aDecoder: NSCoder) { self.eventEditingSnappingBehavior = SnapTo15MinuteIntervals(calendar) super.init(coder: aDecoder) configure() } private func configure() { let vc = configureTimelineController(date: Date()) pagingViewController.setViewControllers([vc], direction: .forward, animated: false, completion: nil) pagingViewController.dataSource = self pagingViewController.delegate = self addSubview(pagingViewController.view!) addGestureRecognizer(panGestureRecoognizer) panGestureRecoognizer.delegate = self } public func updateStyle(_ newStyle: TimelineStyle) { style = newStyle pagingViewController.viewControllers?.forEach({ (timelineContainer) in if let controller = timelineContainer as? TimelineContainerController { self.updateStyleOfTimelineContainer(controller: controller) } }) pagingViewController.view.backgroundColor = style.backgroundColor } private func updateStyleOfTimelineContainer(controller: TimelineContainerController) { let container = controller.container let timeline = controller.timeline timeline.updateStyle(style) container.backgroundColor = style.backgroundColor } private func updateEventEditingSnappingBehavior() { pagingViewController.viewControllers?.forEach({ (timelineContainer) in if let controller = timelineContainer as? TimelineContainerController { controller.timeline.eventEditingSnappingBehavior = eventEditingSnappingBehavior } }) } public func timelinePanGestureRequire(toFail gesture: UIGestureRecognizer) { for controller in pagingViewController.viewControllers ?? [] { if let controller = controller as? TimelineContainerController { let container = controller.container container.panGestureRecognizer.require(toFail: gesture) } } } public func scrollTo(hour24: Float, animated: Bool = true) { // Any view is fine as they are all synchronized if let controller = currentTimeline { controller.container.scrollTo(hour24: hour24, animated: animated) } } public func scrollToTopIn8AMTo5PMView(y : Int) { // Any view is fine as they are all synchronized if let controller = currentTimeline { controller.container.scrollToTopIn8AMTo5PMView(yVal : y) } } private func configureTimelineController(date: Date) -> TimelineContainerController { let controller = TimelineContainerController() updateStyleOfTimelineContainer(controller: controller) let timeline = controller.timeline timeline.longPressGestureRecognizer.addTarget(self, action: #selector(timelineDidLongPress(_:))) timeline.delegate = self timeline.calendar = calendar timeline.eventEditingSnappingBehavior = eventEditingSnappingBehavior timeline.date = date.dateOnly(calendar: calendar) controller.container.delegate = self updateTimeline(timeline) return controller } private var initialContentOffset = CGPoint.zero public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { initialContentOffset = scrollView.contentOffset } public func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset let diff = offset.y - initialContentOffset.y if let event = editedEventView { var frame = event.frame frame.origin.y -= diff event.frame = frame initialContentOffset = offset } } public func reloadData() { pagingViewController.children.forEach({ (controller) in if let controller = controller as? TimelineContainerController { self.updateTimeline(controller.timeline) } }) } override public func layoutSubviews() { super.layoutSubviews() pagingViewController.view.frame = bounds } private func updateTimeline(_ timeline: TimelineView) { guard let dataSource = dataSource else {return} let date = timeline.date.dateOnly(calendar: calendar) let events = dataSource.eventsForDate(date) let end = calendar.date(byAdding: .day, value: 1, to: date)! let day = DateInterval(start: date, end: end) let validEvents = events.filter{$0.dateInterval.intersects(day)} timeline.layoutAttributes = validEvents.map(EventLayoutAttributes.init) } public func scrollToFirstEventIfNeeded(animated: Bool) { if autoScrollToFirstEvent { if let controller = currentTimeline { controller.container.scrollToFirstEvent(animated: animated) } } } /// Event view with editing mode active. Can be either edited or newly created event private var editedEventView: EventView? /// The `EventDescriptor` that is being edited. It's editable copy is used by the `editedEventView` private var editedEvent: EventDescriptor? /// Tag of the last used resize handle private var resizeHandleTag: Int? /// Creates an EventView and places it on the Timeline /// - Parameter event: the EventDescriptor based on which an EventView will be placed on the Timeline /// - Parameter animated: if true, CalendarKit animates event creation public func create(event: EventDescriptor, animated: Bool) { let eventView = EventView() eventView.updateWithDescriptor(event: event) addSubview(eventView) // layout algo if let currentTimeline = currentTimeline { for handle in eventView.eventResizeHandles { let panGestureRecognizer = handle.panGestureRecognizer panGestureRecognizer.addTarget(self, action: #selector(handleResizeHandlePanGesture(_:))) panGestureRecognizer.cancelsTouchesInView = true } let timeline = currentTimeline.timeline let offset = currentTimeline.container.contentOffset.y // algo needs to be extracted to a separate object let yStart = timeline.dateToY(event.dateInterval.start) - offset let yEnd = timeline.dateToY(event.dateInterval.end) - offset let rightToLeft = UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft let x = rightToLeft ? 0 : timeline.style.leadingInset let newRect = CGRect(x: x, y: yStart, width: timeline.calendarWidth, height: yEnd - yStart) eventView.frame = newRect if animated { eventView.animateCreation() } } editedEventView = eventView accentDateForEditedEventView() } /// Puts timeline in the editing mode and highlights a single event as being edited. /// - Parameter event: the `EventDescriptor` to be edited. An editable copy of the `EventDescriptor` is created by calling `makeEditable()` method on the passed value /// - Parameter animated: if true, CalendarKit animates beginning of the editing public func beginEditing(event: EventDescriptor, animated: Bool = false) { if editedEventView == nil { editedEvent = event let editableCopy = event.makeEditable() create(event: editableCopy, animated: animated) } } private var prevOffset: CGPoint = .zero @objc func handlePanGesture(_ sender: UIPanGestureRecognizer) { if let pendingEvent = editedEventView { let newCoord = sender.translation(in: pendingEvent) if sender.state == .began { prevOffset = newCoord } let diff = CGPoint(x: newCoord.x - prevOffset.x, y: newCoord.y - prevOffset.y) pendingEvent.frame.origin.x += diff.x pendingEvent.frame.origin.y += diff.y prevOffset = newCoord accentDateForEditedEventView() } if sender.state == .ended { commitEditing() } } @objc func handleResizeHandlePanGesture(_ sender: UIPanGestureRecognizer) { if let pendingEvent = editedEventView { let newCoord = sender.translation(in: pendingEvent) if sender.state == .began { prevOffset = newCoord } guard let tag = sender.view?.tag else { return } resizeHandleTag = tag let diff = CGPoint(x: newCoord.x - prevOffset.x, y: newCoord.y - prevOffset.y) var suggestedEventFrame = pendingEvent.frame if tag == 0 { // Top handle suggestedEventFrame.origin.y += diff.y suggestedEventFrame.size.height -= diff.y } else { // Bottom handle suggestedEventFrame.size.height += diff.y } let minimumMinutesEventDurationWhileEditing = CGFloat(style.minimumEventDurationInMinutesWhileEditing) let minimumEventHeight = minimumMinutesEventDurationWhileEditing * style.verticalDiff / 60 let suggestedEventHeight = suggestedEventFrame.size.height if suggestedEventHeight > minimumEventHeight { pendingEvent.frame = suggestedEventFrame prevOffset = newCoord accentDateForEditedEventView(eventHeight: tag == 0 ? 0 : suggestedEventHeight) } } if sender.state == .ended { commitEditing() } } private func accentDateForEditedEventView(eventHeight: CGFloat = 0) { if let currentTimeline = currentTimeline { let timeline = currentTimeline.timeline let converted = timeline.convert(CGPoint.zero, from: editedEventView) let date = timeline.yToDate(converted.y + eventHeight) timeline.accentedDate = date timeline.setNeedsDisplay() } } private func commitEditing() { if let currentTimeline = currentTimeline { let timeline = currentTimeline.timeline timeline.accentedDate = nil setNeedsDisplay() // TODO: Animate cancellation if let editedEventView = editedEventView, let descriptor = editedEventView.descriptor { update(descriptor: descriptor, with: editedEventView) let ytd = yToDate(y: editedEventView.frame.origin.y, timeline: timeline) let snapped = timeline.eventEditingSnappingBehavior.nearestDate(to: ytd) let leftToRight = UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .leftToRight let x = leftToRight ? style.leadingInset : 0 var eventFrame = editedEventView.frame eventFrame.origin.x = x eventFrame.origin.y = timeline.dateToY(snapped) - currentTimeline.container.contentOffset.y if resizeHandleTag == 0 { eventFrame.size.height = timeline.dateToY(descriptor.dateInterval.end) - timeline.dateToY(snapped) } else if resizeHandleTag == 1 { let bottomHandleYTD = yToDate(y: editedEventView.frame.origin.y + editedEventView.frame.size.height, timeline: timeline) let bottomHandleSnappedDate = timeline.eventEditingSnappingBehavior.nearestDate(to: bottomHandleYTD) eventFrame.size.height = timeline.dateToY(bottomHandleSnappedDate) - timeline.dateToY(snapped) } func animateEventSnap() { editedEventView.frame = eventFrame } func completionHandler(_ completion: Bool) { update(descriptor: descriptor, with: editedEventView) delegate?.timelinePager(timelinePager: self, didUpdate: descriptor) } UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: [], animations: animateEventSnap, completion: completionHandler(_:)) } resizeHandleTag = nil prevOffset = .zero } } /// Ends editing mode public func endEventEditing() { prevOffset = .zero editedEventView?.eventResizeHandles.forEach{$0.panGestureRecognizer.removeTarget(self, action: nil)} editedEventView?.removeFromSuperview() editedEventView = nil editedEvent = nil } @objc private func timelineDidLongPress(_ sender: UILongPressGestureRecognizer) { if sender.state == .ended { commitEditing() } } private func yToDate(y: CGFloat, timeline: TimelineView) -> Date { let point = CGPoint(x: 0, y: y) let converted = convert(point, to: timeline).y let date = timeline.yToDate(converted) return date } private func update(descriptor: EventDescriptor, with eventView: EventView) { if let currentTimeline = currentTimeline { let timeline = currentTimeline.timeline let eventFrame = eventView.frame let converted = convert(eventFrame, to: timeline) let beginningY = converted.minY let endY = converted.maxY let beginning = timeline.yToDate(beginningY) let end = timeline.yToDate(endY) descriptor.dateInterval = DateInterval(start: beginning, end: end) } } // MARK: DayViewStateUpdating public func move(from oldDate: Date, to newDate: Date) { let oldDate = oldDate.dateOnly(calendar: calendar) let newDate = newDate.dateOnly(calendar: calendar) let newController = configureTimelineController(date: newDate) delegate?.timelinePager(timelinePager: self, willMoveTo: newDate) func completionHandler(_ completion: Bool) { DispatchQueue.main.async { [self] in // Fix for the UIPageViewController issue: https://stackoverflow.com/questions/12939280/uipageviewcontroller-navigates-to-wrong-page-with-scroll-transition-style let leftToRight = UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .leftToRight let direction: UIPageViewController.NavigationDirection = leftToRight ? .reverse : .forward self.pagingViewController.setViewControllers([newController], direction: direction, animated: false, completion: nil) self.pagingViewController.viewControllers?.first?.view.setNeedsLayout() self.scrollToFirstEventIfNeeded(animated: true) self.delegate?.timelinePager(timelinePager: self, didMoveTo: newDate) } } if newDate < oldDate { let leftToRight = UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .leftToRight let direction: UIPageViewController.NavigationDirection = leftToRight ? .reverse : .forward pagingViewController.setViewControllers([newController], direction: direction, animated: true, completion: completionHandler(_:)) } else if newDate > oldDate { let leftToRight = UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .leftToRight let direction: UIPageViewController.NavigationDirection = leftToRight ? .forward : .reverse pagingViewController.setViewControllers([newController], direction: direction, animated: true, completion: completionHandler(_:)) } } // MARK: UIPageViewControllerDataSource public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let containerController = viewController as? TimelineContainerController else {return nil} let previousDate = calendar.date(byAdding: .day, value: -1, to: containerController.timeline.date)! let vc = configureTimelineController(date: previousDate) let offset = (pageViewController.viewControllers?.first as? TimelineContainerController)?.container.contentOffset vc.pendingContentOffset = offset return vc } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let containerController = viewController as? TimelineContainerController else {return nil} let nextDate = calendar.date(byAdding: .day, value: 1, to: containerController.timeline.date)! let vc = configureTimelineController(date: nextDate) let offset = (pageViewController.viewControllers?.first as? TimelineContainerController)?.container.contentOffset vc.pendingContentOffset = offset return vc } // MARK: UIPageViewControllerDelegate public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { guard completed else { delegate?.timelinePagerDidTransitionCancel(timelinePager: self) return } if let timelineContainerController = pageViewController.viewControllers?.first as? TimelineContainerController { let selectedDate = timelineContainerController.timeline.date delegate?.timelinePager(timelinePager: self, willMoveTo: selectedDate) state?.client(client: self, didMoveTo: selectedDate) scrollToFirstEventIfNeeded(animated: true) delegate?.timelinePager(timelinePager: self, didMoveTo: selectedDate) } } public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { delegate?.timelinePagerDidBeginDragging(timelinePager: self) } // MARK: TimelineViewDelegate public func timelineView(_ timelineView: TimelineView, didTapAt date: Date) { delegate?.timelinePager(timelinePager: self, didTapTimelineAt: date) } public func timelineView(_ timelineView: TimelineView, didLongPressAt date: Date) { delegate?.timelinePager(timelinePager: self, didLongPressTimelineAt: date) } public func timelineView(_ timelineView: TimelineView, didTap event: EventView) { delegate?.timelinePagerDidSelectEventView(event) } public func timelineView(_ timelineView: TimelineView, didLongPress event: EventView) { delegate?.timelinePagerDidLongPressEventView(event) } }
44.91573
203
0.632896
21d89454390771da59464d19ad514a6e36c935b8
263
// // Logs.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation public struct Logs: Codable { public var events: [LogEvent]? public init(events: [LogEvent]? = nil) { self.events = events } }
12.52381
44
0.631179
46b0ad66f4d5b72f5d37089ef2d9644751d46ad5
2,270
// // ThemeManager+Plist.swift // SwiftTheme // // Created by Gesen on 16/9/18. // Copyright © 2016年 Gesen. All rights reserved. // import UIKit extension ThemeManager { public class func value(for keyPath: String) -> Any? { return currentTheme?.value(forKeyPath: keyPath) } public class func string(for keyPath: String) -> String? { guard let string = currentTheme?.value(forKeyPath: keyPath) as? String else { print("SwiftTheme WARNING: Not found string key path: \(keyPath)") return nil } return string } public class func number(for keyPath: String) -> NSNumber? { guard let number = currentTheme?.value(forKeyPath: keyPath) as? NSNumber else { print("SwiftTheme WARNING: Not found number key path: \(keyPath)") return nil } return number } public class func dictionary(for keyPath: String) -> NSDictionary? { guard let dict = currentTheme?.value(forKeyPath: keyPath) as? NSDictionary else { print("SwiftTheme WARNING: Not found dictionary key path: \(keyPath)") return nil } return dict } public class func color(for keyPath: String) -> UIColor? { guard let rgba = string(for: keyPath) else { return nil } guard let color = try? UIColor(rgba_throws: rgba) else { print("SwiftTheme WARNING: Not convert rgba \(rgba) at key path: \(keyPath)") return nil } return color } public class func image(for keyPath: String) -> UIImage? { guard let imageName = string(for: keyPath) else { return nil } if let filePath = currentThemePath?.URL?.appendingPathComponent(imageName).path { guard let image = UIImage(contentsOfFile: filePath) else { print("SwiftTheme WARNING: Not found image at file path: \(filePath)") return nil } return image } else { guard let image = UIImage(named: imageName) else { print("SwiftTheme WARNING: Not found image name at main bundle: \(imageName)") return nil } return image } } }
33.382353
94
0.590749
5d8c47e5b8d4d7eb5f76a646a15cbb90388bc5f3
1,897
// // GoogleInteractiveMediaAdsAdapter+QBPlayerObserverProtocol.swift // ZappGoogleInteractiveMediaAds // // Created by Anton Kononenko on 7/25/19. // Copyright (c) 2020 Applicaster. All rights reserved. // import Foundation import ZappCore extension GoogleInteractiveMediaAdsAdapter: PlayerObserverProtocol { public func playerReadyToPlay(player: PlayerProtocol) -> Bool { return prepareGoogleIMA() } public func playerDidFinishPlayItem(player: PlayerProtocol, completion: @escaping (_ finished: Bool) -> Void) { adsLoader?.contentComplete() handlePlayerFinish(completion: completion) Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { [weak self] _ in if ((self?.postrollCompletion) != nil) && self?.adsManager == nil { self?.postrollCompletion?(true) self?.postrollCompletion = nil } } } private func handlePlayerFinish(completion: @escaping (_ finished: Bool) -> Void) { guard imaConfig.hasData else { return } if imaConfig.isVMap == true { if isVMAPAdsCompleted { completion(true) return } } postrollCompletion = completion } public func playerProgressUpdate(player: PlayerProtocol, currentTime: TimeInterval, duration: TimeInterval) { // do nothing } public func playerDidDismiss(player: PlayerProtocol) { playerPlugin = nil adsLoader?.delegate = nil adsLoader = nil adsManager?.delegate = nil adsManager = nil } public func playerDidCreate(player: PlayerProtocol) { updatePresentationOfActivityIndicatorIfNeeded() } }
30.596774
91
0.598313
8ae192b557542555dcdc8186a5f224db3b41e4d2
13,091
import Foundation import PromiseKit import PMKFoundation import Path import AppleAPI import KeychainAccess /** Lightweight dependency injection using global mutable state :P - SeeAlso: https://www.pointfree.co/episodes/ep16-dependency-injection-made-easy - SeeAlso: https://www.pointfree.co/episodes/ep18-dependency-injection-made-comfortable - SeeAlso: https://vimeo.com/291588126 */ public struct Environment { public var shell = Shell() public var files = Files() public var network = Network() public var logging = Logging() public var keychain = Keychain() } public var Current = Environment() public struct Shell { public var unxip: (URL) -> Promise<ProcessOutput> = { Process.run(Path.root.usr.bin.xip, workingDirectory: $0.deletingLastPathComponent(), "--expand", "\($0.path)") } public var spctlAssess: (URL) -> Promise<ProcessOutput> = { Process.run(Path.root.usr.sbin.spctl, "--assess", "--verbose", "--type", "execute", "\($0.path)") } public var codesignVerify: (URL) -> Promise<ProcessOutput> = { Process.run(Path.root.usr.bin.codesign, "-vv", "-d", "\($0.path)") } public var devToolsSecurityEnable: (String?) -> Promise<ProcessOutput> = { Process.sudo(password: $0, Path.root.usr.sbin.DevToolsSecurity, "-enable") } public var addStaffToDevelopersGroup: (String?) -> Promise<ProcessOutput> = { Process.sudo(password: $0, Path.root.usr.sbin.dseditgroup, "-o", "edit", "-t", "group", "-a", "staff", "_developer") } public var acceptXcodeLicense: (InstalledXcode, String?) -> Promise<ProcessOutput> = { Process.sudo(password: $1, $0.path.join("/Contents/Developer/usr/bin/xcodebuild"), "-license", "accept") } public var runFirstLaunch: (InstalledXcode, String?) -> Promise<ProcessOutput> = { Process.sudo(password: $1, $0.path.join("/Contents/Developer/usr/bin/xcodebuild"),"-runFirstLaunch") } public var buildVersion: () -> Promise<ProcessOutput> = { Process.run(Path.root.usr.bin.sw_vers, "-buildVersion") } public var xcodeBuildVersion: (InstalledXcode) -> Promise<ProcessOutput> = { Process.run(Path.root.usr.libexec.PlistBuddy, "-c", "Print :ProductBuildVersion", "\($0.path.string)/Contents/version.plist") } public var getUserCacheDir: () -> Promise<ProcessOutput> = { Process.run(Path.root.usr.bin.getconf, "DARWIN_USER_CACHE_DIR") } public var touchInstallCheck: (String, String, String) -> Promise<ProcessOutput> = { Process.run(Path.root.usr.bin/"touch", "\($0)com.apple.dt.Xcode.InstallCheckCache_\($1)_\($2)") } public var validateSudoAuthentication: () -> Promise<ProcessOutput> = { Process.run(Path.root.usr.bin.sudo, "-nv") } public var authenticateSudoerIfNecessary: (@escaping () -> Promise<String>) -> Promise<String?> = { passwordInput in firstly { () -> Promise<String?> in Current.shell.validateSudoAuthentication().map { _ in return nil } } .recover { _ -> Promise<String?> in return passwordInput().map(Optional.init) } } public func authenticateSudoerIfNecessary(passwordInput: @escaping () -> Promise<String>) -> Promise<String?> { authenticateSudoerIfNecessary(passwordInput) } public var xcodeSelectPrintPath: () -> Promise<ProcessOutput> = { Process.run(Path.root.usr.bin.join("xcode-select"), "-p") } public var xcodeSelectSwitch: (String?, String) -> Promise<ProcessOutput> = { Process.sudo(password: $0, Path.root.usr.bin.join("xcode-select"), "-s", $1) } public func xcodeSelectSwitch(password: String?, path: String) -> Promise<ProcessOutput> { xcodeSelectSwitch(password, path) } /// Returns the path of an executable within the directories in the PATH environment variable. public var findExecutable: (_ executableName: String) -> Path? = { executableName in guard let path = ProcessInfo.processInfo.environment["PATH"] else { return nil } for directory in path.components(separatedBy: ":") { if let executable = Path(directory)?.join(executableName), executable.isExecutable { return executable } } return nil } public var downloadWithAria2: (Path, URL, Path, [HTTPCookie]) -> (Progress, Promise<Void>) = { aria2Path, url, destination, cookies in let process = Process() process.executableURL = aria2Path.url process.arguments = [ "--header=Cookie: \(cookies.map { "\($0.name)=\($0.value)" }.joined(separator: "; "))", "--max-connection-per-server=16", "--split=16", "--summary-interval=1", "--stop-with-process=\(ProcessInfo.processInfo.processIdentifier)", "--dir=\(destination.parent.string)", "--out=\(destination.basename())", url.absoluteString, ] let stdOutPipe = Pipe() process.standardOutput = stdOutPipe let stdErrPipe = Pipe() process.standardError = stdErrPipe var progress = Progress(totalUnitCount: 100) let observer = NotificationCenter.default.addObserver( forName: .NSFileHandleDataAvailable, object: nil, queue: OperationQueue.main ) { note in guard // This should always be the case for Notification.Name.NSFileHandleDataAvailable let handle = note.object as? FileHandle, handle === stdOutPipe.fileHandleForReading || handle === stdErrPipe.fileHandleForReading else { return } defer { handle.waitForDataInBackgroundAndNotify() } let string = String(decoding: handle.availableData, as: UTF8.self) let regex = try! NSRegularExpression(pattern: #"((?<percent>\d+)%\))"#) let range = NSRange(location: 0, length: string.utf16.count) guard let match = regex.firstMatch(in: string, options: [], range: range), let matchRange = Range(match.range(withName: "percent"), in: string), let percentCompleted = Int64(string[matchRange]) else { return } progress.completedUnitCount = percentCompleted } stdOutPipe.fileHandleForReading.waitForDataInBackgroundAndNotify() stdErrPipe.fileHandleForReading.waitForDataInBackgroundAndNotify() do { try process.run() } catch { return (progress, Promise(error: error)) } let promise = Promise<Void> { seal in DispatchQueue.global(qos: .default).async { process.waitUntilExit() NotificationCenter.default.removeObserver(observer, name: .NSFileHandleDataAvailable, object: nil) guard process.terminationReason == .exit, process.terminationStatus == 0 else { if let aria2cError = Aria2CError(exitStatus: process.terminationStatus) { return seal.reject(aria2cError) } else { return seal.reject(Process.PMKError.execution(process: process, standardOutput: "", standardError: "")) } } seal.fulfill(()) } } return (progress, promise) } public var readLine: (String) -> String? = { prompt in print(prompt, terminator: "") return Swift.readLine() } public func readLine(prompt: String) -> String? { readLine(prompt) } public var readSecureLine: (String, Int) -> String? = { prompt, maximumLength in let buffer = UnsafeMutablePointer<Int8>.allocate(capacity: maximumLength) buffer.initialize(repeating: 0, count: maximumLength) defer { buffer.deinitialize(count: maximumLength) buffer.initialize(repeating: 0, count: maximumLength) buffer.deinitialize(count: maximumLength) buffer.deallocate() } guard let passwordData = readpassphrase(prompt, buffer, maximumLength, 0) else { return nil } return String(validatingUTF8: passwordData) } /** Like `readLine()`, but doesn't echo the user's input to the screen. - Parameter prompt: Prompt printed on the line preceding user input - Parameter maximumLength: The maximum length to read, in bytes - Returns: The entered password, or nil if an error occurred. Buffer is zeroed after use. - SeeAlso: [readpassphrase man page](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/readpassphrase.3.html) */ public func readSecureLine(prompt: String, maximumLength: Int = 8192) -> String? { readSecureLine(prompt, maximumLength) } public var env: (String) -> String? = { key in ProcessInfo.processInfo.environment[key] } public func env(_ key: String) -> String? { env(key) } public var exit: (Int32) -> Void = { Darwin.exit($0) } } public struct Files { public var fileExistsAtPath: (String) -> Bool = { FileManager.default.fileExists(atPath: $0) } public func fileExists(atPath path: String) -> Bool { return fileExistsAtPath(path) } public var moveItem: (URL, URL) throws -> Void = { try FileManager.default.moveItem(at: $0, to: $1) } public func moveItem(at srcURL: URL, to dstURL: URL) throws { try moveItem(srcURL, dstURL) } public var contentsAtPath: (String) -> Data? = { FileManager.default.contents(atPath: $0) } public func contents(atPath path: String) -> Data? { return contentsAtPath(path) } public var removeItem: (URL) throws -> Void = { try FileManager.default.removeItem(at: $0) } public func removeItem(at URL: URL) throws { try removeItem(URL) } public var trashItem: (URL) throws -> URL = { try FileManager.default.trashItem(at: $0) } @discardableResult public func trashItem(at URL: URL) throws -> URL { return try trashItem(URL) } public var createFile: (String, Data?, [FileAttributeKey: Any]?) -> Bool = { FileManager.default.createFile(atPath: $0, contents: $1, attributes: $2) } @discardableResult public func createFile(atPath path: String, contents data: Data?, attributes attr: [FileAttributeKey : Any]? = nil) -> Bool { return createFile(path, data, attr) } public var createDirectory: (URL, Bool, [FileAttributeKey : Any]?) throws -> Void = FileManager.default.createDirectory(at:withIntermediateDirectories:attributes:) public func createDirectory(at url: URL, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = nil) throws { try createDirectory(url, createIntermediates, attributes) } public var installedXcodes = XcodesKit.installedXcodes } private func installedXcodes() -> [InstalledXcode] { ((try? Path.root.join("Applications").ls()) ?? []) .filter { $0.isAppBundle && $0.infoPlist?.bundleID == "com.apple.dt.Xcode" } .map { $0.path } .compactMap(InstalledXcode.init) } public struct Network { private static let client = AppleAPI.Client() public var dataTask: (URLRequestConvertible) -> Promise<(data: Data, response: URLResponse)> = { AppleAPI.Current.network.session.dataTask(.promise, with: $0) } public func dataTask(with convertible: URLRequestConvertible) -> Promise<(data: Data, response: URLResponse)> { dataTask(convertible) } public var downloadTask: (URLRequestConvertible, URL, Data?) -> (Progress, Promise<(saveLocation: URL, response: URLResponse)>) = { AppleAPI.Current.network.session.downloadTask(with: $0, to: $1, resumingWith: $2) } public func downloadTask(with convertible: URLRequestConvertible, to saveLocation: URL, resumingWith resumeData: Data?) -> (progress: Progress, promise: Promise<(saveLocation: URL, response: URLResponse)>) { return downloadTask(convertible, saveLocation, resumeData) } public var validateSession: () -> Promise<Void> = client.validateSession public var login: (String, String) -> Promise<Void> = { client.login(accountName: $0, password: $1) } public func login(accountName: String, password: String) -> Promise<Void> { login(accountName, password) } } public struct Logging { public var log: (String) -> Void = { print($0) } } public struct Keychain { private static let keychain = KeychainAccess.Keychain(service: "com.robotsandpencils.xcodes") public var getString: (String) throws -> String? = keychain.getString(_:) public func getString(_ key: String) throws -> String? { try getString(key) } public var set: (String, String) throws -> Void = keychain.set(_:key:) public func set(_ value: String, key: String) throws { try set(value, key) } public var remove: (String) throws -> Void = keychain.remove(_:) public func remove(_ key: String) throws -> Void { try remove(key) } }
44.832192
219
0.650676
f5af2cd7bbd30ccaa159d4a9ba08782baa96f896
590
// // AnchorGroup.swift // DYZB // // Created by 孙震 on 2020/7/9. // Copyright © 2020 孙震. All rights reserved. // import UIKit class AnchorGroup: BaseGameModel { /// 该组中对应的房间信息 @objc var room_list : [[String : NSObject]]? { didSet { guard let room_list = room_list else { return } for dict in room_list { anchors.append(AnchorModel(dict: dict)) } } } /// 组显示的图标 @objc var icon_name : String = "home_header_normal" /// 定义主播的模型对象数组 @objc lazy var anchors : [AnchorModel] = [AnchorModel]() }
22.692308
60
0.576271
4a36d5f88e46e98a93b10c269a0180e927e6b04a
956
// // Pin+CoreDataProperties.swift // VirtualTourist // // Created by Rakesh on 3/27/17. // Copyright © 2017 Rakesh Kumar. All rights reserved. // import Foundation import CoreData extension Pin { @nonobjc public class func fetchRequest() -> NSFetchRequest<Pin> { return NSFetchRequest<Pin>(entityName: "Pin"); } @NSManaged public var currentPage: Int @NSManaged public var latitude: Double @NSManaged public var longitude: Double @NSManaged public var totalPages: Int @NSManaged public var photos: NSSet? } // MARK: Generated accessors for photos extension Pin { @objc(addPhotosObject:) @NSManaged public func addToPhotos(_ value: Photo) @objc(removePhotosObject:) @NSManaged public func removeFromPhotos(_ value: Photo) @objc(addPhotos:) @NSManaged public func addToPhotos(_ values: NSSet) @objc(removePhotos:) @NSManaged public func removeFromPhotos(_ values: NSSet) }
22.232558
70
0.709205
678c2639ff8336435bc13873dddde4c41a5f7aba
683
// Copyright 2015-present 650 Industries. All rights reserved. import UIKit import ABI45_0_0ExpoModulesCore @objc(ABI45_0_0EXBlurView) public class BlurView: ExpoView { private var blurEffectView: BlurEffectView override init(frame: CGRect) { blurEffectView = BlurEffectView() super.init(frame: frame) blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] clipsToBounds = true addSubview(blurEffectView) } required init?(coder: NSCoder) { nil } @objc public func setTint(_ tint: String) { blurEffectView.tint = tint } @objc public func setIntensity(_ intensity: Double) { blurEffectView.intensity = intensity } }
21.34375
71
0.734993
4669ebaf6d42532bd4447b270f253d91366af9b2
4,015
// // Xoroshiro.swift // RandomKit // // The MIT License (MIT) // // Copyright (c) 2015-2017 Nikolai Vazquez // // 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. // // Copyright (c) 2008-2017 Matt Gallagher (http://cocoawithlove.com). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING // FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH // THE USE OR PERFORMANCE OF THIS SOFTWARE. // /// A generator that uses the [Xoroshiro][1] algorithm. /// /// Its source is located [here][2]. /// /// [1]: http://xoroshiro.di.unimi.it/ /// [2]: http://xoroshiro.di.unimi.it/xoroshiro128plus.c public struct Xoroshiro: RandomBytesGenerator, Seedable, SeedableFromRandomGenerator { /// A default global instance seeded with `DeviceRandom.default`. public static var `default` = seeded /// A default global instance that reseeds itself with `DeviceRandom.default`. public static var defaultReseeding = reseeding /// The internal state. private var _state: (UInt64, UInt64) /// Creates an instance from `seed`. public init(seed: (UInt64, UInt64)) { _state = seed } /// Creates an instance seeded with `randomGenerator`. public init<R: RandomGenerator>(seededWith randomGenerator: inout R) { var seed: Seed = (0, 0) repeat { randomGenerator.randomize(value: &seed) } while seed == (0, 0) self.init(seed: seed) } /// Returns random `Bytes`. public mutating func randomBytes() -> UInt64 { let (l, k0, k1, k2): (UInt64, UInt64, UInt64, UInt64) = (64, 55, 14, 36) let result = _state.0 &+ _state.1 let x = _state.0 ^ _state.1 _state.0 = ((_state.0 << k0) | (_state.0 >> (l - k0))) ^ x ^ (x << k1) _state.1 = (x << k2) | (x >> (l - k2)) return result } /// Advances the generator 2^64 calls forward. public mutating func jump() { var s0: UInt64 = 0 var s1: UInt64 = 0 @inline(__always) func doThings(with value: UInt64) { for i: UInt64 in 0 ..< 64 { if value & 1 << i != 0 { s0 ^= _state.0 s1 ^= _state.1 } _ = randomBytes() } } doThings(with: 0xBEAC0467EBA5FACB) doThings(with: 0xD86B048B86AA9922) _state = (s0, s1) } }
38.980583
91
0.657036
bff232623808bf542b4791dbf5fa90a5874efeb9
4,521
// // ZHTransitionManager.swift // swift17 tumblrMenu // // Created by Aaron on 16/7/20. // Copyright © 2016年 Aaron. All rights reserved. // import UIKit class ZHTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { private var presenting = false func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } //必须要实现的方法, 跳转时 会执行的方法 func animateTransition(transitionContext: UIViewControllerContextTransitioning){ let container = transitionContext.containerView() let screens :(from:UIViewController,to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!,transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!) let menuViewC = !self.presenting ? screens.from as! ZHMenuViewController : screens.to as! ZHMenuViewController let bottomVC = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController let menuView = menuViewC.view let bottomView = bottomVC.view if presenting { off(menuViewC) } container!.addSubview(bottomView) container!.addSubview(menuView) let duration = self.transitionDuration(transitionContext) UIView.animateWithDuration(duration, delay:0.0 , usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: [], animations: { () -> Void in if self.presenting{ self.on(menuViewC) }else{ self.off(menuViewC) } }) { (Bool) -> Void in transitionContext.completeTransition(true) UIApplication.sharedApplication().keyWindow!.addSubview(screens.to.view) } } func offstage(amount:CGFloat)->CGAffineTransform{ return CGAffineTransformMakeTranslation(amount, 0) } func off(menuVC:ZHMenuViewController){ if !presenting{ menuVC.view.alpha = 0 } let topRowOffset : CGFloat = 300 let middleRowOffset : CGFloat = 150 let bottomRowOffset : CGFloat = 50 menuVC.textButton.transform = self.offstage(-topRowOffset) menuVC.textLabel.transform = self.offstage(-topRowOffset) menuVC.quoteButton.transform = self.offstage(-middleRowOffset) menuVC.quoteLabel.transform = self.offstage(-middleRowOffset) menuVC.chatButton.transform = self.offstage(-bottomRowOffset) menuVC.chatLabel.transform = self.offstage(-bottomRowOffset) menuVC.photoButton.transform = self.offstage(topRowOffset) menuVC.photoLabel.transform = self.offstage(topRowOffset) menuVC.linkButton.transform = self.offstage(middleRowOffset) menuVC.linkLabel.transform = self.offstage(middleRowOffset) menuVC.audioButton.transform = self.offstage(bottomRowOffset) menuVC.audioLabel.transform = self.offstage(bottomRowOffset) } func on(menuVC:ZHMenuViewController){ menuVC.view.alpha = 1 menuVC.textButton.transform = CGAffineTransformIdentity menuVC.textLabel.transform = CGAffineTransformIdentity menuVC.quoteButton.transform = CGAffineTransformIdentity menuVC.quoteLabel.transform = CGAffineTransformIdentity menuVC.chatButton.transform = CGAffineTransformIdentity menuVC.chatLabel.transform = CGAffineTransformIdentity menuVC.photoButton.transform = CGAffineTransformIdentity menuVC.photoLabel.transform = CGAffineTransformIdentity menuVC.linkButton.transform = CGAffineTransformIdentity menuVC.linkLabel.transform = CGAffineTransformIdentity menuVC.audioButton.transform = CGAffineTransformIdentity menuVC.audioLabel.transform = CGAffineTransformIdentity } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } }
40.366071
230
0.693431
5d6f8961f25c5eeb4b7156ed5aedc2f4ea61ad9f
1,201
// // CollectionsExtension.swift // EZSwiftExtensions // // Created by Sanyal, Arunav on 3/5/17. // Copyright © 2017 Goktug Yilmaz. All rights reserved. // import Foundation extension Collection { #if os(iOS) // EZSE : A parralelized map for collections, operation is non blocking public func parallelizedMap<R>(_ each: @escaping (Self.Iterator.Element) -> R) -> [R?] { let indices = indicesArray() var res = [R?](repeating: nil, count: indices.count) let queue = OperationQueue() let operations = indices.enumerated().map { index, elementIndex in return BlockOperation { res[index] = each(self[elementIndex]) } } queue.addOperations(operations, waitUntilFinished: true) return res } /// EZSE : Helper method to get an array of collection indices private func indicesArray() -> [Self.Index] { var indicesArray: [Self.Index] = [] var nextIndex = startIndex while nextIndex != endIndex { indicesArray.append(nextIndex) nextIndex = index(after: nextIndex) } return indicesArray } #endif }
27.930233
92
0.609492
ef4350891a116f9388844365714d944bf9ef35c6
663
import Foundation class Shell:ShellProtocol { var provider:ShellProviderProtocol init() { self.provider = StandardShell() } @discardableResult func send(message:String) -> String { var response:String = self.provider.send(message:message) response = self.clean(string:response) return response } private func clean(string:String) -> String { var string:String = string if let last:Character = string.last { if String(last) == SwiftToShellConstants.newLine { string = String(string.dropLast()) } } return string } }
25.5
65
0.598793
01d3ce1764016eec50f5299b0bce224813b71554
1,905
// // FriendsContributionLoader.swift // Slide for Reddit // // Created by Carlos Crane on 9/8/18. // Copyright © 2018 Haptic Apps. All rights reserved. // import Foundation import RealmSwift import reddift class FriendsContributionLoader: ContributionLoader { var content: [Object] var color: UIColor var canGetMore: Bool func reset() { content = [] } init() { color = ColorUtil.getColorForUser(name: "") paginator = Paginator() content = [] canGetMore = false } var paginator: Paginator var delegate: ContentListingViewController? var paging = false func getData(reload: Bool) { if delegate != nil && (canGetMore || reload) { do { if reload { paginator = Paginator() } try delegate?.session?.getFriends(paginator, limit: 50, completion: { (result) in switch result { case .failure(let error): print(error.localizedDescription) case .success(let listing): if reload { self.content = [] } let before = self.content.count for user in listing { self.content.append(RealmDataWrapper.friendToRealm(user: user)) } //self.paginator = listing.paginator //self.canGetMore = listing.paginator.hasMore() DispatchQueue.main.async { self.delegate?.doneLoading(before: before, filter: false) } } }) } catch { print(error) } } } }
28.863636
97
0.474016
1df62acbccb5794a82a386d2eca429164e3b7072
1,765
// // ViewController.swift // CameraTest // // Created by Somi Ogbozor on 11/5/16. // Copyright © 2016 Somi Ogbozor. All rights reserved. // import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imagePicked: UIImageView! // Allows the iPhone Camera to be accessed @IBAction func openCameraButton(sender: AnyObject) { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.camera; imagePicker.allowsEditing = false self.present(imagePicker, animated: true, completion: nil) } } // Allows the photo to be saved to the iPhone Camera Roll (still need to implement actual save button) @IBAction func openPhotoLibraryButton(sender: AnyObject) { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary; imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
30.431034
106
0.688952
d57db2492c0e6fc11855e48b5db53b14f5fb42e5
735
// // APIContacts.swift // picpayment // // Created by Screencorp Desenvolvimento de Software on 01/03/19. // Copyright © 2019 Red Ice. All rights reserved. // import Foundation import Alamofire class APIContacts { static func getContacts(completion:@escaping ([Contact]?, Result<Any>) -> Void) { Client.performRequest(route: .users) { (result) in guard let json = result.value as? [JSON] else { completion(nil, result) return } var contacts = [Contact]() for j in json { contacts.append(Contact(json: j)) } completion(contacts, result) } } }
23.709677
85
0.536054
ed4d3287148faa7ef0be51b9680433dab98fad2f
17,602
// // GaiaKeysController.swift // CosmosSample // // Created by Calin Chitu on 11/01/2019. // Copyright © 2019 Calin Chitu. All rights reserved. // import UIKit import CosmosRestApi class PersistableGaiaKeys: PersistCodable { let keys: [GaiaKey] init(keys: [GaiaKey]) { self.keys = keys } } class GaiaKeysController: UIViewController, GaiaKeysManagementCapable, ToastAlertViewPresentable, GaiaValidatorsCapable { var toast: ToastAlertView? @IBOutlet weak var loadingView: CustomLoadingView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var noDataView: UIView! @IBOutlet weak var toastHolderUnderView: UIView! @IBOutlet weak var toastHolderTopConstraint: NSLayoutConstraint! @IBOutlet weak var topNavBarView: UIView! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var editButton: UIButton! @IBAction func editButtonAction(_ sender: UIButton) { sender.isSelected = !sender.isSelected tableView.setEditing(sender.isSelected, animated: true) } @IBAction func addAction(_ sender: Any) { showCreateOptions() } @IBAction func backAction(_ sender: Any) { if reusePickerMode { self.dismiss(animated: true, completion: nil) } navigationController?.popViewController(animated: true) } @IBAction func swipeAction(_ sender: Any) { } var dataSource: [GaiaKey] = [] var filteredDataSource: [GaiaKey] { return reusePickerMode ? dataSource.filter { $0.mnemonic != "" && $0.watchMode != true } : dataSource.filter { $0.nodeId == AppContext.shared.node?.nodeID && $0.type == AppContext.shared.node?.type.rawValue } } var selectedKey: GaiaKey? var selectedIndex: Int? var reusePickerMode = false private func createTheDefauktKey() { guard AppContext.shared.node?.appleKeyCreated == false, let node = AppContext.shared.node else { return } let mnemonic = "find cliff book sweet clip dwarf minor boat lamp visual maid reject crazy during hollow vanish sunny salt march kangaroo episode crash anger virtual" if let appleKey = AppContext.shared.keysDelegate?.recoverKey(from: mnemonic, name: "appleTest1", password: "test1234") { let gaiaKey = GaiaKey(data: appleKey, nodeId: node.nodeID, networkName: node.network) dataSource.append(gaiaKey) node.appleKeyCreated = true PersistableGaiaKeys(keys: dataSource).savetoDisk() } } override func viewDidLoad() { super.viewDidLoad() addButton.layer.cornerRadius = addButton.frame.size.height / 2 AppContext.shared.keysDelegate = LocalClient(networkType: AppContext.shared.node?.type ?? .stargate, netID: AppContext.shared.node?.nodeID ?? "-1") toast = createToastAlert(creatorView: view, holderUnderView: toastHolderUnderView, holderTopDistanceConstraint: toastHolderTopConstraint, coveringView: topNavBarView) noDataView.isHidden = filteredDataSource.count > 0 || reusePickerMode editButton.isHidden = !noDataView.isHidden let _ = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: OperationQueue.main) { [weak self] note in AppContext.shared.node?.getStatus { if AppContext.shared.node?.state == .unknown { self?.navigationController?.popViewController(animated: true) } } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let savedKeys = PersistableGaiaKeys.loadFromDisk() as? PersistableGaiaKeys { dataSource = savedKeys.keys tableView.reloadData() if filteredDataSource.count == 0 { createTheDefauktKey() } } else { createTheDefauktKey() } noDataView.isHidden = filteredDataSource.count > 0 || reusePickerMode editButton.isHidden = filteredDataSource.count == 0 if reusePickerMode { toast?.showToastAlert("Tap on any key from any node type to recover it on this one. The public address will be generated for this node type's format.", type: .info, dismissable: true) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard let validNode = AppContext.shared.node else { return } AppContext.shared.node?.getStakingInfo() { [weak self] denom in self?.retrieveAllValidators(node: validNode, status: "bonded") { validators, errMsg in if let validValidators = validators { for validator in validValidators { validNode.knownValidators[validator.validator] = validator.moniker } if let savedNodes = PersistableGaiaNodes.loadFromDisk() as? PersistableGaiaNodes { for savedNode in savedNodes.nodes { if savedNode.network == validNode.network { savedNode.knownValidators = validNode.knownValidators } } PersistableGaiaNodes(nodes: savedNodes.nodes).savetoDisk() } } } } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) toast?.hideToast() } func showCreateOptions() { let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let create = UIAlertAction(title: "Create or Recover", style: .default) { [weak self] alertAction in self?.performSegue(withIdentifier: "CreateKeySegue", sender: nil) } let watch = UIAlertAction(title: "Watch Only", style: .default) { [weak self] alertAction in self?.performSegue(withIdentifier: "ShowAddressBookSegue", sender: nil) } let reuse = UIAlertAction(title: "Reuse", style: .default) { [weak self] alertAction in self?.performSegue(withIdentifier: "ReuseKeySegue", sender: nil) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) optionMenu.addAction(create) optionMenu.addAction(watch) optionMenu.addAction(reuse) optionMenu.addAction(cancelAction) optionMenu.popoverPresentationController?.sourceView = self.addButton self.present(optionMenu, animated: true, completion: nil) } func createWatchKey(name: String, address: String) { let matches = dataSource.filter() { $0.name == name && $0.address == address && $0.watchMode == true } if let _ = matches.first { toast?.showToastAlert("This key is already added to your watch list.", autoHideAfter: GaiaConstants.autoHideToastTime, type: .error, dismissable: true) return } let gaiaKey = GaiaKey( name: name, address: address, valAddress: nil, nodeType: AppContext.shared.node?.type ?? .stargate, nodeId: AppContext.shared.node?.nodeID ?? "", networkName: AppContext.shared.node?.network ?? "") DispatchQueue.main.async { self.dataSource.insert(gaiaKey, at: 0) self.tableView.reloadData() PersistableGaiaKeys(keys: self.dataSource).savetoDisk() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { tableView.setEditing(false, animated: true) editButton.isSelected = false if segue.identifier == "ReuseKeySegue" { let dest = segue.destination as? GaiaKeysController dest?.reusePickerMode = true } if segue.identifier == "ShowKeyDetailsSegue" { let dest = segue.destination as? GaiaKeyController dest?.selectedkeyIndex = selectedIndex } if segue.identifier == "ShowAddressBookSegue" { let dest = segue.destination as? AddressPickController dest?.onSelectAddress = { [weak self] selected in if let validAddress = selected { self?.createWatchKey(name: validAddress.name, address: validAddress.address) } } } } func handleDeleteKey(_ key: GaiaKey, completion: ((_ success: Bool) -> ())?) { if key.watchMode == true { completion?(true) return } var alertMessage = "Enter the password for \(key.name) to delete the wallet. The passowrd and seed will be permanentely removed from the keychain." if key.name == "appleTest1" { alertMessage = "This is the Apple Test key, needed for the iOS Appstore review. To delete this address, the password is test1234." } self.showPasswordAlert(title: nil, message: alertMessage, placeholder: "Minimum 8 characters") { [weak self] pass in if key.password == pass { completion?(true) } else { self?.toast?.showToastAlert("Wrong unlock key password.", type: .error, dismissable: true) completion?(false) } } } private func purgeKey(_ key: GaiaKey, index: Array<GaiaKey>.Index) { let _ = key.forgetPassFromKeychain() let _ = key.forgetMnemonicFromKeychain() self.dataSource.remove(at: index) PersistableGaiaKeys(keys: self.dataSource).savetoDisk() tableView.reloadData() toast?.showToastAlert("\(key.name) successfully deleted", autoHideAfter: GaiaConstants.autoHideToastTime, type: .info, dismissable: true) if self.filteredDataSource.count == 0 { self.tableView.setEditing(false, animated: true) self.editButton.isSelected = false self.noDataView.isHidden = false self.editButton.isHidden = !self.noDataView.isHidden } } func createKey(key: GaiaKey) { guard let validNode = AppContext.shared.node, let keysDelegate = AppContext.shared.keysDelegate else { return } let mnemonicOk = [12, 15, 18, 21, 24].contains(key.mnemonic.split(separator: " ").count) if !mnemonicOk { toast?.showToastAlert("The seed must have 12, 15, 18, 21 or 24 words", autoHideAfter: GaiaConstants.autoHideToastTime, type: .info, dismissable: true) return } self.loadingView.startAnimating() self.createKey(node: validNode, clientDelegate: keysDelegate, name: key.name, pass: key.password, mnemonic: key.mnemonic) { [weak self] key, error in DispatchQueue.main.async { self?.loadingView.stopAnimating() if let validKey = key { if let savedKeys = PersistableGaiaKeys.loadFromDisk() as? PersistableGaiaKeys { var list = savedKeys.keys let match = savedKeys.keys.filter { $0.identifier == validKey.identifier } if match.count > 0 { self?.toast?.showToastAlert("This key exist already", autoHideAfter: GaiaConstants.autoHideToastTime, type: .error, dismissable: true) return } else { list.insert(validKey, at: 0) PersistableGaiaKeys(keys: list).savetoDisk() } } if let storedBook = GaiaAddressBook.loadFromDisk() as? GaiaAddressBook { var addrItems: [GaiaAddressBookItem] = [] let item = GaiaAddressBookItem(name: validKey.name, address: validKey.address) addrItems.insert(item, at: 0) storedBook.items.insert(item, at: 0) storedBook.items.mergeElements(newElements: addrItems) storedBook.savetoDisk() } self?.dismiss(animated: true) } else if let errMsg = error { self?.toast?.showToastAlert(errMsg, autoHideAfter: GaiaConstants.autoHideToastTime, type: .info, dismissable: true) } else { self?.toast?.showToastAlert("Ooops! I failed!", autoHideAfter: GaiaConstants.autoHideToastTime, type: .info, dismissable: true) } } } } } extension GaiaKeysController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredDataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "GaiaKeyCellID", for: indexPath) as! GaiaKeyCell let key = filteredDataSource[indexPath.item] cell.onCopy = { [weak self] in if self?.reusePickerMode == true { self?.createKey(key: key) } else { self?.toast?.showToastAlert("Address copied to clipboard", autoHideAfter: GaiaConstants.autoHideToastTime, type: .info, dismissable: true) } } cell.configure(key: key, image: AppContext.shared.node?.nodeLogo, reuseMode: reusePickerMode) return cell } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return editButton.isSelected ? .delete : .none } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return editButton.isSelected } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let key = filteredDataSource[indexPath.item] if let index = dataSource.firstIndex(where: { $0 == key } ) { handleDeleteKey(key) { success in if success { self.purgeKey(key, index: index) } else { let alert = UIAlertController(title: "Do you want to delete this key anyway? This action can't be undone and the mnemonic is lost forever.", message: "", preferredStyle: UIAlertController.Style.alert) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { alertAction in } let action = UIAlertAction(title: "Confirm", style: .destructive) { [weak self] alertAction in self?.toast?.hideToast() self?.purgeKey(key, index: index) } alert.addAction(cancelAction) alert.addAction(action) self.present(alert, animated:true, completion: nil) } } } } } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let skey = filteredDataSource[sourceIndexPath.item] let dkey = filteredDataSource[destinationIndexPath.item] if let sindex = dataSource.firstIndex(where: { $0 == skey } ), let dindex = dataSource.firstIndex(where: { $0 == dkey } ) { dataSource.remove(at: sindex) dataSource.insert(skey, at: dindex) PersistableGaiaKeys(keys: dataSource).savetoDisk() tableView.reloadData() } } } extension GaiaKeysController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let key = filteredDataSource[indexPath.item] if reusePickerMode { createKey(key: key) return } selectedKey = key AppContext.shared.key = key DispatchQueue.main.async { if tableView.isEditing { self.selectedIndex = indexPath.item self.performSegue(withIdentifier: "ShowKeyDetailsSegue", sender: self) } else { self.performSegue(withIdentifier: "WalletSegueID", sender: self) } } } } extension Array where Element : Equatable { public mutating func mergeElements<C : Collection>(newElements: C) where C.Iterator.Element == Element{ let filteredList = newElements.filter({!self.contains($0)}) self.append(contentsOf: filteredList) } }
41.416471
224
0.601182
9b28d6fb212c693b3bee94e0f8e6e7e004bca563
4,313
/// Copyright (c) 2019 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import UIKit final class ViewController: UIViewController { // MARK: - Properties @IBOutlet var tableView: UITableView! private var selectedIndexPath: IndexPath? private let cellIdentifier = "TableViewCell" private let segueIdentifier = "ToCollectionViewController" private let messages: [String] = { let loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." var result: [String] = [] for i in 1...3 { let strArray = Array(repeating: loremIpsum, count: i) let add = strArray.joined(separator: "\n\n") result.append(add) } return result }() // MARK: - Life Cycles override func viewDidLoad() { super.viewDidLoad() setupTableView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let selectedIndexPath = selectedIndexPath else { return } tableView.reloadRows( at: [selectedIndexPath], with: .none) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } // MARK: - Layouts override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard traitCollection.preferredContentSizeCategory != previousTraitCollection?.preferredContentSizeCategory else { return } let indexPaths = (0..<messages.endIndex) .map { IndexPath(row: $0, section: 0) } DispatchQueue.main.async { [weak self] in self?.tableView.reloadRows(at: indexPaths, with: .none) } } // MARK: - Table View private func setupTableView() { tableView.dataSource = self tableView.delegate = self } } // MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell( withIdentifier: cellIdentifier, for: indexPath) as? TableViewCell else { fatalError("Dequeded Unregistered Cell") } let row = indexPath.row let message = messages[row] cell.configureCell(text: message, index: row, setCustomFont: true) cell.selectionStyle = .default return cell } } // MARK: - UITableViewDelegate extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedIndexPath = indexPath } }
38.508929
146
0.729886
69b25212b4089bf60a3357efbde4241b90d8e5f8
6,530
// // DateExtension.swift // SugarSwiftExtensions // // Created by ZY on 19/08/07. // Copyright (c) 2019 ZY. All rights reserved. // import Foundation enum ConstomDateFormatter : String{ case rfc1123 = "EEE',' dd' 'MMM' 'yyyy HH' :'mm' :'ss zzz" case rfc850 = "EEEE',' dd'-'MMM'-'yy HH':'mm':'ss z" case asctime = "EEE MMM d HH':'mm':'ss yyyy" case iso8601DateOnly = "yyyy-MM-dd" case iso8601DateHrMinOnly = "yyyy-MM-dd'T'HH:mmxxxxx" case iso8601DateHrMinSecOnly = "yyyy-MM-dd'T'HH:mm:ssxxxxx" case iso8601DateHrMinSecMs = "yyyy-MM-dd'T'HH:mm:ss.SSSxxxxx" case cnDateOnly = "yyyy年MM月dd日" case cnDateHrMinSec = "yyyy年MM月dd日 HH时mm分ss秒" } extension Date{ /// Initializes Date from string and format public init?(fromString string: String, format: String, timezone: TimeZone = TimeZone.autoupdatingCurrent, locale: Locale = Locale.current) { let formatter = DateFormatter() formatter.timeZone = timezone formatter.locale = locale formatter.dateFormat = format if let date = formatter.date(from: string) { self = date } else { return nil } } /// Initializes Date from string public init?(httpDateString: String) { if let cnDateOnly = Date(fromString: httpDateString, format: ConstomDateFormatter.cnDateOnly.rawValue) { self = cnDateOnly return } if let cnDateHrMinSec = Date(fromString: httpDateString, format: ConstomDateFormatter.cnDateHrMinSec.rawValue) { self = cnDateHrMinSec return } if let rfc1123 = Date(fromString: httpDateString, format: ConstomDateFormatter.rfc1123.rawValue) { self = rfc1123 return } if let rfc850 = Date(fromString: httpDateString, format: ConstomDateFormatter.rfc850.rawValue) { self = rfc850 return } if let asctime = Date(fromString: httpDateString, format: ConstomDateFormatter.asctime.rawValue) { self = asctime return } if let iso8601DateOnly = Date(fromString: httpDateString, format: ConstomDateFormatter.iso8601DateOnly.rawValue) { self = iso8601DateOnly return } if let iso8601DateHrMinOnly = Date(fromString: httpDateString, format: ConstomDateFormatter.iso8601DateHrMinOnly.rawValue) { self = iso8601DateHrMinOnly return } if let iso8601DateHrMinSecOnly = Date(fromString: httpDateString, format: ConstomDateFormatter.iso8601DateHrMinSecOnly.rawValue) { self = iso8601DateHrMinSecOnly return } if let iso8601DateHrMinSecMs = Date(fromString: httpDateString, format: ConstomDateFormatter.iso8601DateHrMinSecMs.rawValue) { self = iso8601DateHrMinSecMs return } return nil } /// Converts Date to String public func toString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String { let formatter = DateFormatter() formatter.dateStyle = dateStyle formatter.timeStyle = timeStyle return formatter.string(from: self) } /// Converts Date to String, with format public func toString(format: String) -> String { let formatter = DateFormatter() formatter.dateFormat = format return formatter.string(from: self) } /// Calculates how many days passed from now to date public func daysInBetweenDate(_ date: Date) -> Double { var diff = self.timeIntervalSince1970 - date.timeIntervalSince1970 diff = fabs(diff/86400) return diff } /// Calculates how many hours passed from now to date public func hoursInBetweenDate(_ date: Date) -> Double { var diff = self.timeIntervalSince1970 - date.timeIntervalSince1970 diff = fabs(diff/3600) return diff } /// Calculates how many minutes passed from now to date public func minutesInBetweenDate(_ date: Date) -> Double { var diff = self.timeIntervalSince1970 - date.timeIntervalSince1970 diff = fabs(diff/60) return diff } /// Calculates how many seconds passed from now to date public func secondsInBetweenDate(_ date: Date) -> Double { var diff = self.timeIntervalSince1970 - date.timeIntervalSince1970 diff = fabs(diff) return diff } /// Check if date is in future. public var isFuture: Bool { return self > Date() } /// Check if date is in past. public var isPast: Bool { return self < Date() } /// Get the year from the date public var year: Int { return Calendar.current.component(Calendar.Component.year, from: self) } /// Get the month from the date public var month: Int { return Calendar.current.component(Calendar.Component.month, from: self) } // Get the day from the date public var day: Int { return Calendar.current.component(.day, from: self) } /// Get the hours from date public var hour: Int { return Calendar.current.component(.hour, from: self) } /// Get the minute from date public var minute: Int { return Calendar.current.component(.minute, from: self) } /// Get the second from the date public var second: Int { return Calendar.current.component(.second, from: self) } /// Gets the nano second from the date public var nanosecond: Int { return Calendar.current.component(.nanosecond, from: self) } /// Gets diff month Date public func getDiffMonthDate(diff:Int) -> Date? { return Calendar.current.date(byAdding: Calendar.Component.month, value: diff, to: self) } /// Gets diff month number public func getDiffMonth(diff:Int) -> Int? { if let diffDate = getDiffMonthDate(diff: diff){ return Calendar.current.dateComponents([.month], from: diffDate).month } return nil } ///Gets nature day in month public func getNatureDayInMonth() -> Int? { return Calendar.current.range(of: .day, in: .month, for: self)?.count } }
34.550265
138
0.615314
dba32f1939f0a4634112e15f9cf5b7dbd94a7c6d
3,822
/* * Copyright (c) 2012-2020 MIRACL UK Ltd. * * This file is part of MIRACL Core * (see https://github.com/miracl/core). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // rom.swift // // Created by Michael Scott on 12/06/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // public struct ROM{ #if D32 // Base Bits= 29 // goldilocks Curve Modulus static public let Modulus:[Chunk] = [0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FDFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFF] static let ROI:[Chunk] = [0x1FFFFFFE,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FDFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFF] static let R2modp:[Chunk] = [0x0,0x10,0x0,0x0,0x0,0x0,0x0,0x0,0x3000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0] static let MConst:Chunk = 0x1 // goldilocks Curve static let CURVE_Cof_I:Int = 4 static let CURVE_Cof:[Chunk] = [0x4,0x10,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0] static let CURVE_B_I:Int = -39081 static let CURVE_B:[Chunk] = [0x1FFF6756,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FDFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFF] static public let CURVE_Order:[Chunk] = [0xB5844F3,0x1BC61495,0x1163D548,0x1984E51B,0x3690216,0xDA4D76B,0xFA7113B,0x1FEF9944,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FF] static public let CURVE_Gx:[Chunk] = [0x15555555,0xAAAAAAA,0x15555555,0xAAAAAAA,0x15555555,0xAAAAAAA,0x15555555,0x152AAAAA,0xAAAAAAA,0x15555555,0xAAAAAAA,0x15555555,0xAAAAAAA,0x15555555,0xAAAAAAA,0x1555] static public let CURVE_Gy:[Chunk] = [0xA9386ED,0x1757DE6F,0x13681AF6,0x19657DA3,0x3098BBB,0x12C19D15,0x12E03595,0xE515B18,0x17B7E36D,0x1AC426E,0xDBB5E8,0x10D8560,0x159D6205,0xB8246D9,0x17A58D2B,0x15C0] #endif #if D64 // Base Bits= 58 // goldilocks Curve Modulus static public let Modulus:[Chunk] = [0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FBFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFF] static let ROI:[Chunk] = [0x3FFFFFFFFFFFFFE,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FBFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFF] static let R2modp:[Chunk] = [0x200000000,0x0,0x0,0x0,0x3000000,0x0,0x0,0x0] static let MConst:Chunk = 0x1 // goldilocks Curve static let CURVE_Cof_I:Int = 4 static let CURVE_Cof:[Chunk] = [0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x0] static let CURVE_B_I:Int = -39081 static let CURVE_B:[Chunk] = [0x3FFFFFFFFFF6756,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FBFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFF] static public let CURVE_Order:[Chunk] = [0x378C292AB5844F3,0x3309CA37163D548,0x1B49AED63690216,0x3FDF3288FA7113B,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0xFFFFFFFFFF] static public let CURVE_Gx:[Chunk] = [0x155555555555555,0x155555555555555,0x155555555555555,0x2A5555555555555,0x2AAAAAAAAAAAAAA,0x2AAAAAAAAAAAAAA,0x2AAAAAAAAAAAAAA,0x2AAAAAAAAAA] static public let CURVE_Gy:[Chunk] = [0x2EAFBCDEA9386ED,0x32CAFB473681AF6,0x25833A2A3098BBB,0x1CA2B6312E03595,0x35884DD7B7E36D,0x21B0AC00DBB5E8,0x17048DB359D6205,0x2B817A58D2B] #endif }
53.830986
209
0.81528
72b34f1246db1d513784e7a6c4f525a5cb952380
2,188
// // PDFLineObject.swift // TPPDF // // Created by Philip Niedertscheider on 06.12.17. // /** Calculates and draws a line. Line is drawn from startPoint and endPoint. */ class PDFLineObject: PDFObject { /** Defines the style of the line */ var style: PDFLineStyle /** Starting point of line */ var startPoint: CGPoint /** Ending point of line */ var endPoint: CGPoint /** Initializer - parameter style: Style of line, defaults to `PDFLineStyle` defaults */ init(style: PDFLineStyle = PDFLineStyle(), startPoint: CGPoint = CGPoint.zero, endPoint: CGPoint = CGPoint.zero) { self.style = style self.startPoint = startPoint self.endPoint = endPoint } /** Calculates the line start and end point - parameter generator: Generator which uses this object - parameter container: Container where the line is set - throws: None - returns: Self */ override func calculate(generator: PDFGenerator, container: PDFContainer) throws -> [(PDFContainer, PDFObject)] { let origin = CGPoint(x: min(startPoint.x, endPoint.x), y: min(startPoint.x, endPoint.x)) let size = CGSize(width: max(startPoint.x, endPoint.x) - origin.x, height: max(startPoint.y, endPoint.y) - origin.y) self.frame = CGRect(origin: origin, size: size) return [(container, self)] } /** Draws the line in the calculated frame - parameter generator: Unused - parameter container: unused - throws: None */ override func draw(generator: PDFGenerator, container: PDFContainer) throws { PDFGraphics.drawLine( start: startPoint, end: endPoint, style: style ) if generator.debug && (style.type == .none) { PDFGraphics.drawRect(rect: self.frame, outline: PDFLineStyle(type: .full, color: .red, width: 1.0), fill: .clear) } } override var copy: PDFObject { return PDFLineObject(style: self.style, startPoint: self.startPoint, endPoint: self.endPoint) } }
25.44186
125
0.609689
26015421a9e15c74b9e1f96a4061e0c1b1e149eb
2,285
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services // // Microsoft Cognitive Services (formerly Project Oxford) GitHub: // https://github.com/Microsoft/Cognitive-Speech-TTS // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // 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 class TTSHttpRequest { typealias Callback = (data: Data?, response: URLResponse?, error: Error?) static func submit(withUrl url: String, andHeaders headers: [String: String]? = nil, andBody body: Data? = nil, _ callback: @escaping (Callback) -> ()) { guard let url = URL(string: url) else { return } var request = URLRequest(url: url) request.httpMethod = "POST" headers?.forEach({ (header: (key: String, value: String)) in request.setValue(header.value, forHTTPHeaderField: header.key) }) if let body = body { request.httpBody = body } let task = URLSession.shared.dataTask(with: request) { (c: Callback) in callback(c) } task.resume() } }
40.087719
157
0.699344
294f47ae3c88ce647897eb872f129b18fd8f30aa
637
// // ViewController.swift // KVOSample // // Created by 关东升 on 15/12/30. // 本书网站:http://www.51work6.com // 智捷课堂在线课堂:http://www.zhijieketang.com/ // 智捷课堂微信公共号:zhijieketang // 作者微博:@tony_关东升 // 作者微信:tony关东升 // QQ:569418560 邮箱:[email protected] // QQ交流群:162030268 // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.90625
80
0.67033
39fb39b18cbec187625bbba8f5f038563ce08c98
1,083
// // CMDTitleLabel.swift // CinemoodApp // // Created by Nikolay Karataev aka Babaka on 03.04.17. // Copyright © 2017 Cinemood. All rights reserved. // import UIKit open class CMDLabelBase: UILabel { override open var text: String? { didSet { super.text = text setLabel() } } open var t: String? { set { self.text = newValue setLabel() } get { return self.text } } convenience init(text: String) { self.init() self.text = text baseInit() setLabel() } override init(frame: CGRect) { super.init(frame: frame) baseInit() setLabel() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) baseInit() setLabel() } private func baseInit() { self.adjustsFontSizeToFitWidth = true self.minimumScaleFactor = 0.5 } func setLabel() { fatalError("Must override") } }
19
55
0.518929
8aaab20a6e9f43fa5117e2e6c785e1391abb5f62
1,360
// Copyright © 2016-2018 Shawn Baker using the MIT License. import Foundation class Settings: NSObject, NSCoding { // instance variables var cameraName = "camera".local var showAllCameras = false var scanTimeout = 500 var port = 5001 //********************************************************************** // init //********************************************************************** override init() { } //********************************************************************** // init //********************************************************************** required init(coder decoder: NSCoder) { cameraName = decoder.decodeObject(forKey: "cameraName") as! String showAllCameras = decoder.decodeBool(forKey: "showAllCameras") scanTimeout = decoder.decodeInteger(forKey: "scanTimeout") port = decoder.decodeInteger(forKey: "port") } //********************************************************************** // encode //********************************************************************** func encode(with encoder: NSCoder) { encoder.encode(cameraName, forKey: "cameraName") encoder.encode(showAllCameras, forKey: "showAllCameras") encoder.encode(scanTimeout, forKey: "scanTimeout") encoder.encode(port, forKey: "port") } }
33.170732
76
0.445588
c10640659312b2528773814b2b1919abbc939230
391
// // AppContext.swift // Erudyte // // Created by Denny Mathew on 6/7/18. // Copyright © 2018 Cabot. All rights reserved. // import UIKit class AppContext { static let shared = AppContext() private init() { Logger.log("The AppContext is born!") } var keyboardWillShowObserver: NSObjectProtocol? var keyboardWillHideObserver: NSObjectProtocol? }
17.772727
51
0.662404
5d80ec23e1771b2a389abc082886d75b67031f68
10,772
//===--- DriverUtils.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Darwin struct BenchResults { var delim: String = "," var sampleCount: UInt64 = 0 var min: UInt64 = 0 var max: UInt64 = 0 var mean: UInt64 = 0 var sd: UInt64 = 0 var median: UInt64 = 0 init() {} init(delim: String, sampleCount: UInt64, min: UInt64, max: UInt64, mean: UInt64, sd: UInt64, median: UInt64) { self.delim = delim self.sampleCount = sampleCount self.min = min self.max = max self.mean = mean self.sd = sd self.median = median // Sanity the bounds of our results precondition(self.min <= self.max, "min should always be <= max") precondition(self.min <= self.mean, "min should always be <= mean") precondition(self.min <= self.median, "min should always be <= median") precondition(self.max >= self.mean, "max should always be >= mean") precondition(self.max >= self.median, "max should always be >= median") } } extension BenchResults : CustomStringConvertible { var description: String { return "\(sampleCount)\(delim)\(min)\(delim)\(max)\(delim)\(mean)\(delim)\(sd)\(delim)\(median)" } } struct Test { let name: String let index: Int let f: (Int) -> () var run: Bool init(name: String, n: Int, f: (Int) -> ()) { self.name = name self.index = n self.f = f run = true } } public var precommitTests: [String : (Int) -> ()] = [:] public var otherTests: [String : (Int) -> ()] = [:] enum TestAction { case Run case ListTests case Fail(String) } struct TestConfig { /// The delimiter to use when printing output. var delim: String = "," /// The filters applied to our test names. var filters = [String]() /// The scalar multiple of the amount of times a test should be run. This /// enables one to cause tests to run for N iterations longer than they /// normally would. This is useful when one wishes for a test to run for a /// longer amount of time to perform performance analysis on the test in /// instruments. var iterationScale: Int = 1 /// If we are asked to have a fixed number of iterations, the number of fixed /// iterations. var fixedNumIters: UInt = 0 /// The number of samples we should take of each test. var numSamples: Int = 1 /// Is verbose output enabled? var verbose: Bool = false /// Should we only run the "pre-commit" tests? var onlyPrecommit: Bool = true /// After we run the tests, should the harness sleep to allow for utilities /// like leaks that require a PID to run on the test harness. var afterRunSleep: Int? = nil /// The list of tests to run. var tests = [Test]() mutating func processArguments() -> TestAction { let validOptions = [ "--iter-scale", "--num-samples", "--num-iters", "--verbose", "--delim", "--run-all", "--list", "--sleep" ] let maybeBenchArgs: Arguments? = parseArgs(validOptions) if maybeBenchArgs == nil { return .Fail("Failed to parse arguments") } let benchArgs = maybeBenchArgs! if let _ = benchArgs.optionalArgsMap["--list"] { return .ListTests } if let x = benchArgs.optionalArgsMap["--iter-scale"] { if x.isEmpty { return .Fail("--iter-scale requires a value") } iterationScale = Int(x)! } if let x = benchArgs.optionalArgsMap["--num-iters"] { if x.isEmpty { return .Fail("--num-iters requires a value") } fixedNumIters = numericCast(Int(x)!) } if let x = benchArgs.optionalArgsMap["--num-samples"] { if x.isEmpty { return .Fail("--num-samples requires a value") } numSamples = Int(x)! } if let _ = benchArgs.optionalArgsMap["--verbose"] { verbose = true print("Verbose") } if let x = benchArgs.optionalArgsMap["--delim"] { if x.isEmpty { return .Fail("--delim requires a value") } delim = x } if let _ = benchArgs.optionalArgsMap["--run-all"] { onlyPrecommit = false } if let x = benchArgs.optionalArgsMap["--sleep"] { if x.isEmpty { return .Fail("--sleep requires a non-empty integer value") } let v: Int? = Int(x) if v == nil { return .Fail("--sleep requires a non-empty integer value") } afterRunSleep = v! } filters = benchArgs.positionalArgs return .Run } mutating func findTestsToRun() { var i = 1 for benchName in precommitTests.keys.sorted() { tests.append(Test(name: benchName, n: i, f: precommitTests[benchName]!)) i += 1 } for benchName in otherTests.keys.sorted() { tests.append(Test(name: benchName, n: i, f: otherTests[benchName]!)) i += 1 } for i in 0..<tests.count { if onlyPrecommit && precommitTests[tests[i].name] == nil { tests[i].run = false } if !filters.isEmpty && !filters.contains(String(tests[i].index)) && !filters.contains(tests[i].name) { tests[i].run = false } } } } func internalMeanSD(_ inputs: [UInt64]) -> (UInt64, UInt64) { // If we are empty, return 0, 0. if inputs.isEmpty { return (0, 0) } // If we have one element, return elt, 0. if inputs.count == 1 { return (inputs[0], 0) } // Ok, we have 2 elements. var sum1: UInt64 = 0 var sum2: UInt64 = 0 for i in inputs { sum1 += i } let mean: UInt64 = sum1 / UInt64(inputs.count) for i in inputs { sum2 = sum2 &+ UInt64((Int64(i) &- Int64(mean))&*(Int64(i) &- Int64(mean))) } return (mean, UInt64(sqrt(Double(sum2)/(Double(inputs.count) - 1)))) } func internalMedian(_ inputs: [UInt64]) -> UInt64 { return inputs.sorted()[inputs.count / 2] } #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER @_silgen_name("swift_leaks_startTrackingObjects") func startTrackingObjects(_: UnsafeMutablePointer<Void>) -> () @_silgen_name("swift_leaks_stopTrackingObjects") func stopTrackingObjects(_: UnsafeMutablePointer<Void>) -> Int #endif class SampleRunner { var info = mach_timebase_info_data_t(numer: 0, denom: 0) init() { mach_timebase_info(&info) } func run(_ name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 { // Start the timer. #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER var str = name startTrackingObjects(UnsafeMutablePointer<Void>(str._core.startASCII)) #endif let start_ticks = mach_absolute_time() fn(Int(num_iters)) // Stop the timer. let end_ticks = mach_absolute_time() #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER stopTrackingObjects(UnsafeMutablePointer<Void>(str._core.startASCII)) #endif // Compute the spent time and the scaling factor. let elapsed_ticks = end_ticks - start_ticks return elapsed_ticks * UInt64(info.numer) / UInt64(info.denom) } } /// Invoke the benchmark entry point and return the run time in milliseconds. func runBench(_ name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResults { var samples = [UInt64](repeating: 0, count: c.numSamples) if c.verbose { print("Running \(name) for \(c.numSamples) samples.") } let sampler = SampleRunner() for s in 0..<c.numSamples { let time_per_sample: UInt64 = 1_000_000_000 * UInt64(c.iterationScale) var scale : UInt var elapsed_time : UInt64 = 0 if c.fixedNumIters == 0 { elapsed_time = sampler.run(name, fn: fn, num_iters: 1) scale = UInt(time_per_sample / elapsed_time) } else { // Compute the scaling factor if a fixed c.fixedNumIters is not specified. scale = c.fixedNumIters } // Rerun the test with the computed scale factor. if scale > 1 { if c.verbose { print(" Measuring with scale \(scale).") } elapsed_time = sampler.run(name, fn: fn, num_iters: scale) } else { scale = 1 } // save result in microseconds or k-ticks samples[s] = elapsed_time / UInt64(scale) / 1000 if c.verbose { print(" Sample \(s),\(samples[s])") } } let (mean, sd) = internalMeanSD(samples) // Return our benchmark results. return BenchResults(delim: c.delim, sampleCount: UInt64(samples.count), min: samples.min()!, max: samples.max()!, mean: mean, sd: sd, median: internalMedian(samples)) } func printRunInfo(_ c: TestConfig) { if c.verbose { print("--- CONFIG ---") print("NumSamples: \(c.numSamples)") print("Verbose: \(c.verbose)") print("IterScale: \(c.iterationScale)") if c.fixedNumIters != 0 { print("FixedIters: \(c.fixedNumIters)") } print("Tests Filter: \(c.filters)") print("Tests to run: ", terminator: "") for t in c.tests { if t.run { print("\(t.name), ", terminator: "") } } print("") print("") print("--- DATA ---") } } func runBenchmarks(_ c: TestConfig) { let units = "us" print("#\(c.delim)TEST\(c.delim)SAMPLES\(c.delim)MIN(\(units))\(c.delim)MAX(\(units))\(c.delim)MEAN(\(units))\(c.delim)SD(\(units))\(c.delim)MEDIAN(\(units))") var SumBenchResults = BenchResults() SumBenchResults.sampleCount = 0 for t in c.tests { if !t.run { continue } let BenchIndex = t.index let BenchName = t.name let BenchFunc = t.f let results = runBench(BenchName, BenchFunc, c) print("\(BenchIndex)\(c.delim)\(BenchName)\(c.delim)\(results.description)") fflush(stdout) SumBenchResults.min += results.min SumBenchResults.max += results.max SumBenchResults.mean += results.mean SumBenchResults.sampleCount += 1 // Don't accumulate SD and Median, as simple sum isn't valid for them. // TODO: Compute SD and Median for total results as well. // SumBenchResults.sd += results.sd // SumBenchResults.median += results.median } print("") print("Totals\(c.delim)\(SumBenchResults.description)") } public func main() { var config = TestConfig() switch (config.processArguments()) { case let .Fail(msg): // We do this since we need an autoclosure... fatalError("\(msg)") case .ListTests: config.findTestsToRun() print("Enabled Tests:") for t in config.tests { print(" \(t.name)") } case .Run: config.findTestsToRun() printRunInfo(config) runBenchmarks(config) if let x = config.afterRunSleep { sleep(UInt32(x)) } } }
28.648936
161
0.624211
fe5cc02c4153ea4c707fe29f3b2ba6c775beda87
1,053
// // AppKit.swift // BothamUI // // Created by Davide Mendolia on 12/02/16. // Copyright © 2016 GoKarumi S.L. All rights reserved. // import Foundation #if os(OSX) // MARK: Typealias typealias UINib = NSNib typealias UIStoryboard = NSStoryboard // MARK: Extension extension UINib { convenience init?(nibName name: String, bundle bundleOrNil: NSBundle?) { self.init(nibNamed: name, bundle: bundleOrNil) } } extension NSStoryboard { func instantiateInitialViewController() -> AnyObject? { return instantiateInitialController() } func instantiateViewControllerWithIdentifier(identifier: String) -> AnyObject { return instantiateControllerWithIdentifier(identifier) } } extension NSBundle { public func loadNibNamed(name: String!, owner: AnyObject!, options: [NSObject : AnyObject]!) -> [AnyObject]! { var topLevelObjects: NSArray? self.loadNibNamed(name, owner: owner, topLevelObjects: &topLevelObjects) return topLevelObjects.map { $0 as [AnyObject] } } } #endif
25.071429
114
0.702754
614182e4c6d8cb71844bf465ca80256796aeaa90
889
/*: ## App Exercise - Counting >These exercises reinforce Swift concepts in the context of a fitness tracking app. The most basic feature of your fitness tracking app is counting steps. Create a variable `steps` and set it equal to 0. Then increment its value by 1 to simulate a user taking a step. */ var steps=0 steps+=1 print(steps) /*: In addition to tracking steps, your fitness tracking app tracks distance traveled. Create a variable `distance` of type `Double` and set it equal to 50. This will represent the user having traveled 50 feet. You decide, however, to display the distance in meters. 1 meter is approximately equal to 3 feet. Use a compound assignment operator to convert `distance` to meters. Print the result. */ var distance = 50 distance /= 3 print(distance) //: [Previous](@previous) | page 4 of 8 | [Next: Exercise - Order of Operations](@next)
40.409091
207
0.742407
db8fa5e9e6ab3c700d96d379226014c8299b7b67
11,320
// // Mat4.swift // SwiftGL // // Created by Scott Bennett on 2014-06-10. // Copyright (c) 2014 Scott Bennett. All rights reserved. // import Darwin public struct Mat4 { public var x, y, z, w: Vec4 public init() { self.x = Vec4() self.y = Vec4() self.z = Vec4() self.w = Vec4() } // Explicit Initializers public init(xCol: Vec4, yCol: Vec4, zCol: Vec4, wCol: Vec4) { self.x = xCol self.y = yCol self.z = zCol self.w = wCol } public init(xx: Float, yx: Float, zx: Float, wx: Float, xy: Float, yy: Float, zy: Float, wy: Float, xz: Float, yz: Float, zz: Float, wz: Float, xw: Float, yw: Float, zw: Float, ww: Float) { self.x = Vec4(x: xx, y: xy, z: xz, w: xw) self.y = Vec4(x: yx, y: yy, z: yz, w: yw) self.z = Vec4(x: zx, y: zy, z: zz, w: zw) self.w = Vec4(x: wx, y: wy, z: wz, w: ww) } // Implicit Initializers public init(_ xCol: Vec4, _ yCol: Vec4, _ zCol: Vec4, _ wCol: Vec4) { self.x = xCol self.y = yCol self.z = zCol self.w = wCol } public init(_ xx: Float, _ yx: Float, _ zx: Float, _ wx: Float, _ xy: Float, _ yy: Float, _ zy: Float, _ wy: Float, _ xz: Float, _ yz: Float, _ zz: Float, _ wz: Float, _ xw: Float, _ yw: Float, _ zw: Float, _ ww: Float) { self.x = Vec4(x: xx, y: xy, z: xz, w: xw) self.y = Vec4(x: yx, y: yy, z: yz, w: yw) self.z = Vec4(x: zx, y: zy, z: zz, w: zw) self.w = Vec4(x: wx, y: wy, z: wz, w: ww) } public var ptr: UnsafePointer<Float> { mutating get { return withUnsafePointer(to: &self) { return UnsafeRawPointer($0).assumingMemoryBound(to: Float.self) } } } } public func * (m: Mat4, v: Vec4) -> Vec4 { return Vec4(x: m.x.x * v.x + m.y.x * v.y + m.z.x * v.z + m.w.x * v.w, y: m.x.y * v.x + m.y.y * v.y + m.z.y * v.z + m.w.y * v.w, z: m.x.z * v.x + m.y.z * v.y + m.z.z * v.z + m.w.z * v.w, w: m.x.w * v.x + m.y.w * v.y + m.z.w * v.z + m.w.w * v.w) } public func * (a: Mat4, b: Mat4) -> Mat4 { return Mat4(xx: a.x.x * b.x.x + a.y.x * b.x.y + a.z.x * b.x.z + a.w.x * b.x.w, yx: a.x.x * b.y.x + a.y.x * b.y.y + a.z.x * b.y.z + a.w.x * b.y.w, zx: a.x.x * b.z.x + a.y.x * b.z.y + a.z.x * b.z.z + a.w.x * b.z.w, wx: a.x.x * b.w.x + a.y.x * b.w.y + a.z.x * b.w.z + a.w.x * b.w.w, xy: a.x.y * b.x.x + a.y.y * b.x.y + a.z.y * b.x.z + a.w.y * b.x.w, yy: a.x.y * b.y.x + a.y.y * b.y.y + a.z.y * b.y.z + a.w.y * b.y.w, zy: a.x.y * b.z.x + a.y.y * b.z.y + a.z.y * b.z.z + a.w.y * b.z.w, wy: a.x.y * b.w.x + a.y.y * b.w.y + a.z.y * b.w.z + a.w.y * b.w.w, xz: a.x.z * b.x.x + a.y.z * b.x.y + a.z.z * b.x.z + a.w.z * b.x.w, yz: a.x.z * b.y.x + a.y.z * b.y.y + a.z.z * b.y.z + a.w.z * b.y.w, zz: a.x.z * b.z.x + a.y.z * b.z.y + a.z.z * b.z.z + a.w.z * b.z.w, wz: a.x.z * b.w.x + a.y.z * b.w.y + a.z.z * b.w.z + a.w.z * b.w.w, xw: a.x.w * b.x.x + a.y.w * b.x.y + a.z.w * b.x.z + a.w.w * b.x.w, yw: a.x.w * b.y.x + a.y.w * b.y.y + a.z.w * b.y.z + a.w.w * b.y.w, zw: a.x.w * b.z.x + a.y.w * b.z.y + a.z.w * b.z.z + a.w.w * b.z.w, ww: a.x.w * b.w.x + a.y.w * b.w.y + a.z.w * b.w.z + a.w.w * b.w.w) } public func *= (a: inout Mat4, b: Mat4) { a = a * b } public extension Mat4 { // Affine transformations public static func identity() -> Mat4 { return Mat4(xx: 1, yx: 0, zx: 0, wx: 0, xy: 0, yy: 1, zy: 0, wy: 0, xz: 0, yz: 0, zz: 1, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func rotateX(_ radians: Float) -> Mat4 { let c = cos(radians) let s = sin(radians) return Mat4(xx: 1, yx: 0, zx: 0, wx: 0, xy: 0, yy: c, zy: -s, wy: 0, xz: 0, yz: s, zz: c, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func rotateY(_ radians: Float) -> Mat4 { let c = cos(radians) let s = sin(radians) return Mat4(xx: c, yx: 0, zx: s, wx: 0, xy: 0, yy: 1, zy: 0, wy: 0, xz: -s, yz: 0, zz: c, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func rotateZ(_ radians: Float) -> Mat4 { let c = cos(radians) let s = sin(radians) return Mat4(xx: c, yx: -s, zx: 0, wx: 0, xy: s, yy: c, zy: 0, wy: 0, xz: 0, yz: 0, zz: 1, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func rotate(_ radians: Float, x: Float, y: Float, z: Float) -> Mat4 { let v = normalize(Vec3(x: x, y: y, z: z)) let c = cos(radians) let p = 1 - c let s = sin(radians) return Mat4(xx: c + p * v.x * v.x, yx: p * v.x * v.y - v.z * s, zx: p * v.x * v.z + v.y * s, wx: 0, xy: p * v.x * v.y + v.z * s, yy: c + p * v.y * v.y, zy: p * v.y * v.z - v.x * s, wy: 0, xz: p * v.x * v.z - v.y * s, yz: p * v.y * v.z + v.x * s, zz: c + p * v.z * v.z, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func rotate(_ radians: Float, v: Vec3) -> Mat4 { let u = normalize(v) let c = cos(radians) let p = 1 - c let s = sin(radians) return Mat4(xx: c + p * u.x * u.x, yx: p * u.x * u.y - u.z * s, zx: p * u.x * u.z + u.y * s, wx: 0, xy: p * u.x * u.y + u.z * s, yy: c + p * u.y * u.y, zy: p * u.y * u.z - u.x * s, wy: 0, xz: p * u.x * u.z - u.y * s, yz: p * u.y * u.z + u.x * s, zz: c + p * u.z * u.z, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func translate(x: Float, y: Float) -> Mat4 { return Mat4(xx: 1, yx: 0, zx: 0, wx: x, xy: 0, yy: 1, zy: 0, wy: y, xz: 0, yz: 0, zz: 1, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func translate(x: Float, y: Float, z: Float) -> Mat4 { return Mat4(xx: 1, yx: 0, zx: 0, wx: x, xy: 0, yy: 1, zy: 0, wy: y, xz: 0, yz: 0, zz: 1, wz: z, xw: 0, yw: 0, zw: 0, ww: 1) } public static func translate(_ offset: Vec2) -> Mat4 { return Mat4(xx: 1, yx: 0, zx: 0, wx: offset.x, xy: 0, yy: 1, zy: 0, wy: offset.y, xz: 0, yz: 0, zz: 1, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func translate(_ offset: Vec3) -> Mat4 { return Mat4(xx: 1, yx: 0, zx: 0, wx: offset.x, xy: 0, yy: 1, zy: 0, wy: offset.y, xz: 0, yz: 0, zz: 1, wz: offset.z, xw: 0, yw: 0, zw: 0, ww: 1) } public static func scale(_ s: Float) -> Mat4 { return Mat4(xx: s, yx: 0, zx: 0, wx: 0, xy: 0, yy: s, zy: 0, wy: 0, xz: 0, yz: 0, zz: s, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func scale(_ x: Float, y: Float) -> Mat4 { return Mat4(xx: x, yx: 0, zx: 0, wx: 0, xy: 0, yy: y, zy: 0, wy: 0, xz: 0, yz: 0, zz: 1, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func scale(_ x: Float, y: Float, z: Float) -> Mat4 { return Mat4(xx: x, yx: 0, zx: 0, wx: 0, xy: 0, yy: y, zy: 0, wy: 0, xz: 0, yz: 0, zz: z, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func scale(_ scale: Vec2) -> Mat4 { return Mat4(xx: scale.x, yx: 0, zx: 0, wx: 0, xy: 0, yy: scale.y, zy: 0, wy: 0, xz: 0, yz: 0, zz: 1, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func scale(_ scale: Vec3) -> Mat4 { return Mat4(xx: scale.x, yx: 0, zx: 0, wx: 0, xy: 0, yy: scale.y, zy: 0, wy: 0, xz: 0, yz: 0, zz: scale.z, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } } public extension Mat4 { // Projection transformations public static func ortho(width: Float, height: Float, depth: Float) -> Mat4 { return Mat4(xx: 0.5 / width, yx: 0, zx: 0, wx: 0, xy: 0, yy: 0.5 / height, zy: 0, wy: 0, xz: 0, yz: 0, zz: -0.5 / depth, wz: 0, xw: 0, yw: 0, zw: 0, ww: 1) } public static func ortho(width: Float, height: Float, near: Float, far: Float) -> Mat4 { let fan = far + near let fsn = far - near return Mat4(xx: 0.5 / width, yx: 0, zx: 0, wx: 0, xy: 0, yy: 0.5 / height, zy: 0, wy: 0, xz: 0, yz: 0, zz: -2 / fsn, wz: -fan / fsn, xw: 0, yw: 0, zw: 0, ww: 1) } public static func ortho(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) -> Mat4 { let ral = right + left let rsl = right - left let tab = top + bottom let tsb = top - bottom let fan = far + near let fsn = far - near return Mat4(xx: 2 / rsl, yx: 0, zx: 0, wx: -ral / rsl, xy: 0, yy: 2 / tsb, zy: 0, wy: -tab / tsb, xz: 0, yz: 0, zz: -2 / fsn, wz: -fan / fsn, xw: 0, yw: 0, zw: 0, ww: 1) } public static func frustum(width: Float, height: Float, near: Float, far: Float) -> Mat4 { let fan = far + near let fsn = far - near return Mat4(xx: near / width, yx: 0, zx: 0, wx: 0, xy: 0, yy: near / height, zy: 0, wy: 0, xz: 0, yz: 0, zz: -fan / fsn, wz: (-2 * far * near) / fsn, xw: 0, yw: 0, zw: -1, ww: 0) } public static func frustum(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) -> Mat4 { let ral = right + left let rsl = right - left let tsb = top - bottom let tab = top + bottom let fan = far + near let fsn = far - near return Mat4(xx: 2 * near / rsl, yx: 0, zx: ral / rsl, wx: 0, xy: 0, yy: 2 * near / tsb, zy: tab / tsb, wy: 0, xz: 0, yz: 0, zz: -fan / fsn, wz: (-2 * far * near) / fsn, xw: 0, yw: 0, zw: -1, ww: 0) } public static func perspective(fovy: Float, aspect: Float, near: Float, far: Float) -> Mat4 { let cot = 1 / tan(fovy / 2) return Mat4(xx: cot / aspect, yx: 0, zx: 0, wx: 0, xy: 0, yy: cot, zy: 0, wy: 0, xz: 0, yz: 0, zz: (far + near) / (near - far), wz: (2 * far * near) / (near - far), xw: 0, yw: 0, zw: -1, ww: 0) } public static func perspective(fovy: Float, width: Float, height: Float, near: Float, far: Float) -> Mat4 { let cot = 1 / tan(fovy / 2) let aspect = width / height return Mat4(xx: cot / aspect, yx: 0, zx: 0, wx: 0, xy: 0, yy: cot, zy: 0, wy: 0, xz: 0, yz: 0, zz: (far + near) / (near - far), wz: (2 * far * near) / (near - far), xw: 0, yw: 0, zw: -1, ww: 0) } public static func lookAt(eye: Vec3, center: Vec3, up: Vec3) -> Mat4 { let n = normalize(eye - center) let u = normalize(cross(up, n)) let v = cross(n, u) return Mat4(xx: u.x, yx: u.y, zx: u.z, wx: dot(-u, eye), xy: v.x, yy: v.y, zy: v.z, wy: dot(-v, eye), xz: n.x, yz: n.y, zz: n.z, wz: dot(-n, eye), xw: 0, yw: 0, zw: 0, ww: 1) } }
37.733333
119
0.44258
bf673e5037809c065291dc609a4c6bac79ff2c8e
959
// // IMUIUserProtocol.swift // IMUIChat // // Created by oshumini on 2017/2/24. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit /** * The `IMUIUserProtocol` protocol defines the common interface with user model objects * It declares the required methods which model should implement it */ @objc public protocol IMUIUserProtocol: NSObjectProtocol { /** * return user id, to identifies this user */ func userId() -> String /** * return user displayName, which will display in IMUIBaseMessageCell.nameLabel */ func displayName() -> String /** * return user header image, which will display in IMUIBaseMessageCell.avatarImage. * if use avatarUrlString function to get web image you can use this function to set avatar placehold image. */ func Avatar() -> UIImage? /** * return avatar image url string, for web image. */ @objc optional func avatarUrlString() -> String? }
23.975
111
0.68926
64fadea1af1ab4528182d1297967e5bac71c2683
2,496
// // SceneDelegate.swift // CryptoChecker // // Created by Kostadin Samardzhiev on 27.12.21. // 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. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } }
44.571429
147
0.716747
71cc803d27d6f3d09ae90de79f41c13955c5d35e
1,909
// // BackNavigationVC.swift // XTUIKit-Swift // // Created by Topredator on 2021/5/27. // import UIKit open class BackNavigationVC: BaseNavigationController { open override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } public override func pushViewController(_ viewController: UIViewController, animated: Bool) { if children.count > 0 { viewController.hidesBottomBarWhenPushed = true viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.backItem(General.image("blackBack"), target: viewController, action: #selector(backAction)) } super.pushViewController(viewController, animated: animated) } } extension UIViewController { @objc open func backAction() { navigationController?.popViewController(animated: true) } } public extension UINavigationBar { override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if self.point(inside: point, with: event) { isUserInteractionEnabled = true } else { isUserInteractionEnabled = false } return super.hitTest(point, with: event) } } public extension UIBarButtonItem { /// 返回Item static func backItem(_ image: UIImage? = nil, highImage: UIImage? = nil, target: Any?, action: Selector) -> UIBarButtonItem { let btn = UIButton(type: .custom) btn.setImage(image, for: .normal) btn.setImage(image, for: .highlighted) btn.frame = CGRect(x: 0.0, y: 0.0, width: 30.0, height: 30.0) btn.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: -25, bottom: 0.0, right: 0.0) btn.addTarget(target, action: action, for: .touchUpInside) btn.isUserInteractionEnabled = true return UIBarButtonItem(customView: btn) } }
32.913793
169
0.650602
6267db97da688465e13bc53fe1d53601faef6108
2,176
// // AppDelegate.swift // ChineseZodiac // // Created by tanhaipeng on 2017/9/5. // Copyright © 2017年 tanhaipeng. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.297872
285
0.756434
f78e7f734178750223aeba3f47d70b6ff6dbc64b
321
// // Ticket.swift // SaleTickets // // Created by CoderDream on 2018/12/11. // Copyright © 2018 CoderDream. All rights reserved. // import Foundation class Ticket: NSObject { // 定义票数变量 var number: Int? // 定义单例对象 static let shareTicket = Ticket() private override init() { } }
15.285714
53
0.607477
ccbf4eb41b850259cff86666f354940091c0cd0f
3,018
import XCTest import JOSESwift @testable import AccountSDKIOSWeb final class JOSEUtilTests: XCTestCase { private static let keyId = "test key" private static var jwsUtil: JWSUtil! private static var jwks: JWKS! override class func setUp() { jwsUtil = JWSUtil() jwks = StaticJWKS(keyId: keyId, rsaPublicKey: jwsUtil.publicKey) } func testVerifySignatureValidJWS() { let payload = "test data".data(using: .utf8)! let jws = JOSEUtilTests.jwsUtil.createJWS(payload: payload, keyId: JOSEUtilTests.keyId) Await.until { done in JOSEUtil.verifySignature(of: jws, withKeys: JOSEUtilTests.jwks!) { result in XCTAssertEqual(result, .success(payload)) done() } } } func testVerifySignatureHandlesMalformedJWS() { Await.until { done in JOSEUtil.verifySignature(of: "not a jws", withKeys: JOSEUtilTests.jwks!) { result in XCTAssertEqual(result, .failure(.invalidJWS)) done() } } } func testVerifySignatureHandlesInvalidSignature() { let jws = JOSEUtilTests.jwsUtil.createJWS(payload: Data(), keyId: JOSEUtilTests.keyId) let jwsComponents = jws.components(separatedBy: ".") let invalidSignature = "invalid_signature".data(using: .utf8)!.base64EncodedString() let jwsWithInvalidSignature = "\(jwsComponents[0]).\(jwsComponents[1]).\(invalidSignature)" Await.until { done in JOSEUtil.verifySignature(of: jwsWithInvalidSignature, withKeys: JOSEUtilTests.jwks!) { result in XCTAssertEqual(result, .failure(.invalidSignature)) done() } } } func testVerifySignatureHandlesJWSWithoutKeyId() { let jws = JOSEUtilTests.jwsUtil.createJWS(payload: Data(), keyId: nil) Await.until { done in JOSEUtil.verifySignature(of: jws, withKeys: JOSEUtilTests.jwks!) { result in XCTAssertEqual(result, .failure(.noKeyId)) done() } } } func testVerifySignatureHandlesUnknownKeyId() { let jws = JOSEUtilTests.jwsUtil.createJWS(payload: Data(), keyId: "unknown") Await.until { done in JOSEUtil.verifySignature(of: jws, withKeys: JOSEUtilTests.jwks!) { result in XCTAssertEqual(result, .failure(.unknownKeyId)) done() } } } func testVerifySignatureHandlesUnsupportedKeyType() { let jws = JOSEUtilTests.jwsUtil.createJWS(payload: Data(), keyId: JOSEUtilTests.keyId) let ecKey = ECPublicKey(crv: .P256, x: "aaa", y: "bbb") Await.until { done in JOSEUtil.verifySignature(of: jws, withKeys: StaticJWKS(keyId: JOSEUtilTests.keyId, jwk: ecKey)) { result in XCTAssertEqual(result, .failure(.unsupportedKeyType)) done() } } } }
35.928571
119
0.611332
f96c2c9251428da7f7bf1e42d9998f78ba5250f6
1,409
// The MIT License (MIT) // // Copyright (c) 2016 Alexander Grebenyuk (github.com/kean). import Foundation /// Compares keys for equivalence. public protocol ImageRequestKeyOwner: class { /// Compares keys for equivalence. This method is called only if two keys have the same owner. func isEqual(lhs: ImageRequestKey, to rhs: ImageRequestKey) -> Bool } /// Makes it possible to use ImageRequest as a key in dictionaries. public final class ImageRequestKey: NSObject { /// Request that the receiver was initailized with. public let request: ImageRequest /// Owner of the receiver. public weak private(set) var owner: ImageRequestKeyOwner? /// Initializes the receiver with a given request and owner. public init(_ request: ImageRequest, owner: ImageRequestKeyOwner) { self.request = request self.owner = owner } /// Returns hash from the NSURL from image request. public override var hash: Int { return request.URLRequest.URL?.hashValue ?? 0 } /// Compares two keys for equivalence if the belong to the same owner. public override func isEqual(other: AnyObject?) -> Bool { guard let other = other as? ImageRequestKey else { return false } guard let owner = owner where owner === other.owner else { return false } return owner.isEqual(self, to: other) } }
32.767442
98
0.677786
3ac317e6e894ef348a3014a800efc7ca8b5bb471
2,194
// // AppDelegate.swift // moviesNLU // // Created by Jacqueline Alves on 11/03/19. // Copyright © 2019 jacqueline.alves.moviesNLU. 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.680851
285
0.756609
1e7fffa425095e135ee0ebfb3ffb8d1fb1ae4feb
384
// // Global.swift // Bitrise-iOS // // Created by Yu Tawata on 2019/06/10. // import Foundation import UIKit import Shared private let (dispatcher, driver) = Driver<AppState, AppMessage>.create(initial: .init(), mutation: { (state, message) -> AppState in return state }) let app = App(window: UIWindow(frame: UIScreen.main.bounds), dispatcher: dispatcher, driver: driver)
22.588235
132
0.710938
91f253da73cee77a40866d7d439940337f473b9f
7,440
// // AddPortfolioViewController.swift // CryptoMarket // // Created by Thomas on 29/04/2021. // Copyright © 2021 Thomas Martins. All rights reserved. // import UIKit import RxSwift import RxCocoa class AddPortfolioViewController: UIViewController { private let viewModel: AddPortfolioViewModel = AddPortfolioViewModel() private let disposeBag: DisposeBag = DisposeBag() private var tableviewDataSources: [Int: [PortfolioCellProtocol]] = [:] private var cryptoRowSelected: Int = 0 private var moneyRowSelected: Int = 0 @IBOutlet private weak var doneButton: UIBarButtonItem! @IBOutlet private weak var cancelButton: UIBarButtonItem! @IBOutlet private weak var tableView: UITableView! @IBAction private func cancelTrigger(_ sender: UIBarButtonItem) { self.dismiss(animated: true) } @IBAction private func doneTrigger(_ sender: UIBarButtonItem) { } override func viewDidLoad() { super.viewDidLoad() self.setupView() self.setupTableView() self.setupViewModel() } private func setupView() { self.navigationItem.title = "title_favorite".localized self.extendedLayoutIncludesOpaqueBars = true self.navigationController?.navigationBar.barTintColor = UIColor.init(named: "MainColor") let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white] navigationController?.navigationBar.titleTextAttributes = textAttributes } private func setupTableView() { self.tableView.register(AddInputTableViewCell.nib, forCellReuseIdentifier: AddInputTableViewCell.identifier) self.tableView.register(AddDateTableViewCell.nib, forCellReuseIdentifier: AddDateTableViewCell.identifier) self.tableView.delegate = self self.tableView.dataSource = self } private func setupViewModel() { let input = AddPortfolioViewModel.Input(doneEvent: self.doneButton.rx.tap.asObservable()) let output = self.viewModel.transform(input: input) output.tableviewDataSources.asObservable() .subscribeOn(MainScheduler.asyncInstance) .observeOn(MainScheduler.instance) .subscribe(onNext: { tableViewSource in self.tableviewDataSources = tableViewSource self.tableView.reloadData() }).disposed(by: self.disposeBag) output.onCryptoItemSelected.asObservable() .subscribeOn(MainScheduler.asyncInstance) .observeOn(MainScheduler.instance) .subscribe(onNext: { event in self.cryptoRowSelected = event.1 self.updateCryptoEvent(symbol: event.0.symbol ?? "") }).disposed(by: self.disposeBag) output.onMoneyItemSelected.asObservable() .subscribeOn(MainScheduler.asyncInstance) .observeOn(MainScheduler.instance) .subscribe(onNext: { event in self.moneyRowSelected = event.1 self.updateMoneyEvent(with: event.1, with: event.0) }).disposed(by: self.disposeBag) output.onCryptoSelectEvent.asObservable() .subscribeOn(MainScheduler.asyncInstance) .observeOn(MainScheduler.instance) .subscribe(onNext: { row in if let vc = UIStoryboard(name: "PortfolioStoryboard", bundle: .main).instantiateViewController(withIdentifier: "AddCryptoStoryboard") as? AddCryptoViewController { vc.setup(with: self.viewModel, with: self.cryptoRowSelected) self.present(vc, animated: true) } }).disposed(by: self.disposeBag) output.onMoneySelectEvent .subscribeOn(MainScheduler.asyncInstance) .observeOn(MainScheduler.instance) .subscribe(onNext: { row in if let vc = UIStoryboard(name: "PortfolioStoryboard", bundle: .main).instantiateViewController(withIdentifier: "AddMoneyStoryboard") as? AddMoneyViewController { vc.setup(with: self.viewModel, with: self.moneyRowSelected) self.present(vc, animated: true) } }).disposed(by: self.disposeBag) output.isFormValid .asObservable() .observeOn(MainScheduler.asyncInstance) .subscribeOn(MainScheduler.instance) .subscribe(onNext: { isValid in self.doneButton.isEnabled = isValid }).disposed(by: self.disposeBag) output.onCreatePortfolio .asObservable() .observeOn(MainScheduler.asyncInstance) .subscribeOn(MainScheduler.instance) .subscribe(onNext: { (portfolio, image) in self.dismiss(animated: true) { AnimationPopup.displayAnimation(with: "\(portfolio.marketName ?? "") Added to your portfolio.", and: image) } }, onError: { error in print("AN ERROR OCCURED = \(error)") }).disposed(by: self.disposeBag) } internal func setup() { } } extension AddPortfolioViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tableviewDataSources[section]?.count ?? 0 } func updateCryptoEvent(symbol name: String) { let item = self.tableviewDataSources[0] if let source = item?[0] as? InputCell { source.buttonName = name self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic) } } func updateMoneyEvent(with row: Int, with money: MoneyModel) { let item = self.tableviewDataSources[0] item?.enumerated().forEach { if $0 > 0, let s = $1 as? InputCell { s.buttonName = money.name.rawValue self.tableView.reloadRows(at: [IndexPath(row: $0, section: 0)], with: .automatic) } } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let data = self.tableviewDataSources[indexPath.section] if let source = data?[indexPath.row] as? InputCell { if let cell = tableView.dequeueReusableCell(withIdentifier: AddInputTableViewCell.identifier, for: indexPath) as? AddInputTableViewCell { if let name = source.buttonName { cell.setButtonName(with: name, isCrypto: source.isCrypto) } cell.setup(with: self.viewModel, with: indexPath.row, isCrypto: source.isCrypto) cell.amountDisplay = source.title return cell } } else if let source = data?[indexPath.row] as? DateCell { if let cell = tableView.dequeueReusableCell(withIdentifier: AddDateTableViewCell.identifier, for: indexPath) as? AddDateTableViewCell { cell.title = source.title return cell } } return UITableViewCell() } func numberOfSections(in tableView: UITableView) -> Int { return self.tableviewDataSources.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } }
41.104972
179
0.635081
f7d8ca08a78aa5c7265f4658bb29fb2963799bd4
13,658
// // CollectionViewSection.swift // AnKit // // Created by Anvipo on 29.08.2021. // // swiftlint:disable unavailable_function import UIKit /// Abstract section for collection view. open class CollectionViewSection { /// The amount of space between the content of the section and its boundaries. public final var contentInsets: NSDirectionalEdgeInsets /// A closure called before each layout cycle to allow modification of the items in the section immediately before they are displayed. open var visibleItemsInvalidationHandler: NSCollectionLayoutSectionVisibleItemsInvalidationHandler? /// Items in section /// /// This property always is not empty. open private(set) var items: [CollectionViewItem] /// The supplementary items that are associated with the boundary edges of the section, such as headers and footers. /// /// Could be empty. open private(set) var boundarySupplementaryItems: [CollectionViewBoundarySupplementaryItem] /// Decoration items in section. /// /// Could be empty. open private(set) var decorationItems: [CollectionViewDecorationItem] // swiftlint:disable:next missing_docs public final let id: ID /// Initializes section with specified parameters. /// - Parameters: /// - items: Items in section. Must not be empty. /// - boundarySupplementaryItems: The supplementary items that are associated with the boundary edges of the section, /// such as headers and footers. Could be empty. /// - decorationItems: Decoration items in section. /// - contentInsets: The amount of space between the content of the section and its boundaries. /// - visibleItemsInvalidationHandler: A closure called before each layout cycle to allow modification of the items /// in the section immediately before they are displayed. /// - id: The stable identity of the entity associated with this instance. /// /// - Throws: `CollectionViewSection.InitError`. public init( items: [CollectionViewItem], boundarySupplementaryItems: [CollectionViewBoundarySupplementaryItem] = [], decorationItems: [CollectionViewDecorationItem] = [], contentInsets: NSDirectionalEdgeInsets = .zero, visibleItemsInvalidationHandler: NSCollectionLayoutSectionVisibleItemsInvalidationHandler? = nil, id: ID = ID() ) throws { if items.isEmpty { throw InitError.itemsAreEmpty } try Self.checkElementKinds( items: items, boundarySupplementaryItems: boundarySupplementaryItems, decorationItems: decorationItems ) self.items = items self.boundarySupplementaryItems = boundarySupplementaryItems self.decorationItems = decorationItems self.contentInsets = contentInsets self.visibleItemsInvalidationHandler = visibleItemsInvalidationHandler self.id = id } /// Creates layout configuration of this section. /// - Parameter context: Detailed information sufficient to build the layout of the section. open func layoutConfiguration( context: LayoutCreationContext ) -> NSCollectionLayoutSection { fatalError("Implement this method in your class") } // MARK: items methods /// Sets specified items. /// - Parameter items: Items, which will be set. /// - Throws: `CollectionViewSection.SetItemsError`. open func set(items: [CollectionViewItem]) throws { if items.isEmpty { throw SetItemsError.itemsAreEmpty } self.items = items } /// Removes specified item. /// - Parameter item: Item, which will be removed. /// - Throws: `CollectionViewSection.RemoveItemError`. open func remove(item: CollectionViewItem) throws { guard let index = items.firstIndex(of: item) else { throw RemoveItemError.noItem } items.remove(at: index) } /// Appends specified item. /// - Parameter item: Item, which will be removed. /// - Throws: `CollectionViewSection.AppendItemError`. open func append(item: CollectionViewItem) throws { if let existingItem = items.first(where: { $0 == item }) { throw AppendItemError.duplicateItem(existingSameItem: existingItem) } items.append(item) } // MARK: boundary supplementary items methods /// Sets specified boundary supplementary items. /// - Parameter boundarySupplementaryItems: Boundary supplementary items, which will be set. /// - Throws: `CollectionViewSection.SetBoundarySupplementaryItemsError`. open func set(boundarySupplementaryItems: [CollectionViewBoundarySupplementaryItem]) throws { for (_, groupedBoundarySupplementaryItems) in Dictionary(grouping: boundarySupplementaryItems, by: { $0.elementKind }) { if groupedBoundarySupplementaryItems.count > 1 { throw SetBoundarySupplementaryItemsError.duplicateBoundarySupplementaryItemsByElementKind( groupedBoundarySupplementaryItems ) } } self.boundarySupplementaryItems = boundarySupplementaryItems } /// Removes specified boundary supplementary item. /// - Parameter boundarySupplementaryItem: Boundary Supplementary item, which will be removed. /// - Throws: `CollectionViewSection.RemoveBoundarySupplementaryItemError`. open func remove(boundarySupplementaryItem: CollectionViewBoundarySupplementaryItem) throws { guard let index = boundarySupplementaryItems.firstIndex(of: boundarySupplementaryItem) else { throw RemoveBoundarySupplementaryItemError.noSuchBoundarySupplementaryItem } boundarySupplementaryItems.remove(at: index) } /// Appends specified boundary supplementary item. /// - Parameter boundarySupplementaryItem: Boundary supplementary item, which will be removed. /// - Throws: `CollectionViewSection.AppendSupplementaryItemError`. open func append(boundarySupplementaryItem: CollectionViewBoundarySupplementaryItem) throws { if let existingItem = boundarySupplementaryItems.first(where: { $0.elementKind == boundarySupplementaryItem.elementKind }) { throw AppendBoundarySupplementaryItemError.duplicateBoundarySupplementaryItem(existingItem) } boundarySupplementaryItems.append(boundarySupplementaryItem) } // MARK: decoration items methods /// Sets specified decoration items. /// - Parameter decorationItems: Decoration items, which will be set. /// - Throws: `CollectionViewSection.SetDecorationItemsError`. open func set(decorationItems: [CollectionViewDecorationItem]) throws { for (_, groupedDecorationItems) in Dictionary(grouping: decorationItems, by: { $0.elementKind }) { if groupedDecorationItems.count > 1 { throw SetDecorationItemsError.duplicateDecorationItemsByElementKind( decorationItemsWithSameElementKind: groupedDecorationItems ) } } self.decorationItems = decorationItems } /// Removes specified decoration item. /// - Parameter decorationItem: Decoration item, which will be removed. /// - Throws: `CollectionViewSection.RemoveDecorationItemError`. open func remove(decorationItem: CollectionViewDecorationItem) throws { guard let index = decorationItems.firstIndex(of: decorationItem) else { throw RemoveDecorationItemError.noDecorationItem } decorationItems.remove(at: index) } /// Appends specified decoration item. /// - Parameter decorationItem: Decoration item, which will be removed. /// - Throws: `CollectionViewSection.AppendDecorationItemError`. open func append(decorationItem: CollectionViewDecorationItem) throws { if let existingItem = decorationItems.first(where: { $0.elementKind == decorationItem.elementKind }) { throw AppendDecorationItemError.duplicateElementKind( existingDecorationItemWithSameElementKind: existingItem ) } decorationItems.append(decorationItem) } // swiftlint:disable:next missing_docs open func hash(into hasher: inout Hasher) { hasher.combine(items) hasher.combine(boundarySupplementaryItems) hasher.combine(decorationItems) hasher.combine(contentInsets) hasher.combine(id) } } public extension CollectionViewSection { /// Invalidates all cached heights. func invalidateCachedHeights() { for item in items { item.invalidateCachedCellHeights() } for boundarySupplementaryItem in boundarySupplementaryItems { boundarySupplementaryItem.invalidateCachedSupplementaryViewHeights() } } /// Invalidates all cached heights. func invalidateCachedWidths() { for item in items { item.invalidateCachedCellWidths() } for boundarySupplementaryItem in boundarySupplementaryItems { boundarySupplementaryItem.invalidateCachedSupplementaryViewWidths() } } /// The absolute width of the section content after content insets are applied. /// - Parameter layoutEnvironment: Information about the layout's container and environment traits, /// such as size classes and display scale factor. func effectiveContentWidthLayoutDimension( layoutEnvironment: NSCollectionLayoutEnvironment ) -> NSCollectionLayoutDimension { .absolute(effectiveContentWidth(layoutEnvironment: layoutEnvironment)) } /// The width of the section content after content insets are applied. /// - Parameter layoutEnvironment: Information about the layout's container and environment traits, /// such as size classes and display scale factor. func effectiveContentWidth( layoutEnvironment: NSCollectionLayoutEnvironment ) -> CGFloat { layoutEnvironment.container.effectiveContentSize.width - contentInsets.leading - contentInsets.trailing } } extension CollectionViewSection: Equatable { public static func == ( lhs: CollectionViewSection, rhs: CollectionViewSection ) -> Bool { lhs.items == rhs.items && lhs.boundarySupplementaryItems == rhs.boundarySupplementaryItems && lhs.decorationItems == rhs.decorationItems && lhs.contentInsets == rhs.contentInsets && lhs.id == rhs.id } } extension CollectionViewSection: Hashable {} extension CollectionViewSection: Identifiable { public typealias ID = UUID } public extension CollectionViewSection { /// Set `isShimmering` property to true in items. func shimmerItems() { for boundarySupplementaryItem in boundarySupplementaryItems { guard var shimmerableBoundarySupplementaryItem = boundarySupplementaryItem as? Shimmerable else { continue } shimmerableBoundarySupplementaryItem.isShimmering = true } for item in items { guard var shimmerableItem = item as? Shimmerable else { continue } shimmerableItem.isShimmering = true } for decorationItem in decorationItems { guard var shimmerableDecorationItem = decorationItem as? Shimmerable else { continue } shimmerableDecorationItem.isShimmering = true } } } public extension Array where Element: CollectionViewSection { /// Set `isShimmering` property to true in sections items. func shimmerItems() { for section in self { section.shimmerItems() } } /// Invalidates all cached heights. func invalidateCachedHeights() { for section in self { section.invalidateCachedHeights() } } /// Invalidates all cached widths. func invalidateCachedWidths() { for section in self { section.invalidateCachedWidths() } } } extension CollectionViewSection { func supplementaryItem(for kind: String) -> CollectionViewSupplementaryItem? { boundarySupplementaryItems.first { $0.elementKind == kind } ?? items.supplementaryItem(for: kind) } } private extension CollectionViewSection { // swiftlint:disable:next cyclomatic_complexity static func checkElementKinds( items: [CollectionViewItem], boundarySupplementaryItems: [CollectionViewBoundarySupplementaryItem], decorationItems: [CollectionViewDecorationItem] ) throws { let groupedItemSupplementaryItems = Dictionary(grouping: items.flatMap { $0.supplementaryItems }) { $0.elementKind } for itemSupplementaryItems in groupedItemSupplementaryItems.values { if itemSupplementaryItems.count > 1 { throw InitError.duplicateItemSupplementaryItemsByElementKind(itemSupplementaryItems) } } let groupedBoundarySupplementaryItems = Dictionary(grouping: boundarySupplementaryItems) { $0.elementKind } for boundarySupplementaryItems in groupedBoundarySupplementaryItems.values { if boundarySupplementaryItems.count > 1 { throw InitError.duplicateBoundarySupplementaryItemsByElementKind(boundarySupplementaryItems) } } let groupedDecorationItems = Dictionary(grouping: decorationItems) { $0.elementKind } for decorationItems in groupedDecorationItems.values { if decorationItems.count > 1 { throw InitError.duplicateDecorationItemsByElementKind(decorationItems) } } if !groupedBoundarySupplementaryItems.isEmpty || !groupedDecorationItems.isEmpty { let boundarySupplementaryItemElementKinds = Set(groupedBoundarySupplementaryItems.keys) let decorationItemElementKinds = Set(groupedDecorationItems.keys) let itemSupplementaryItemElementKinds = Set(groupedItemSupplementaryItems.keys) var sectionElementKinds = boundarySupplementaryItemElementKinds for decorationItemElementKind in decorationItemElementKinds { if !sectionElementKinds.insert(decorationItemElementKind).inserted { throw InitError.duplicateElementKind( decorationItemElementKind, itemSupplementaryItemElementKinds: itemSupplementaryItemElementKinds, boundarySupplementaryItemElementKinds: boundarySupplementaryItemElementKinds, decorationItemElementKinds: decorationItemElementKinds ) } } for itemSupplementaryItemElementKind in itemSupplementaryItemElementKinds { if !sectionElementKinds.insert(itemSupplementaryItemElementKind).inserted { throw InitError.duplicateElementKind( itemSupplementaryItemElementKind, itemSupplementaryItemElementKinds: itemSupplementaryItemElementKinds, boundarySupplementaryItemElementKinds: boundarySupplementaryItemElementKinds, decorationItemElementKinds: decorationItemElementKinds ) } } } } }
35.201031
135
0.781886
fc20260fe5f753c7444cceda57d63ae018658c9a
5,914
import UIKit public class AllDayView: UIView { internal weak var eventViewDelegate: EventViewDelegate? var style = AllDayStyle() let allDayLabelWidth: CGFloat = 53.0 let allDayEventHeight: CGFloat = 24.0 public var events: [EventDescriptor] = [] { didSet { self.reloadData() } } private lazy var textLabel: UILabel = { let label = UILabel(frame: CGRect(x: 8.0, y: 4.0, width: allDayLabelWidth, height: 24.0)) label.text = "all-day" label.autoresizingMask = [.flexibleWidth] return label }() /** vertical scroll view that contains the all day events in rows with only 2 columns at most */ private(set) lazy var scrollView: UIScrollView = { let sv = UIScrollView() sv.translatesAutoresizingMaskIntoConstraints = false addSubview(sv) sv.isScrollEnabled = true sv.alwaysBounceVertical = true sv.clipsToBounds = false let svLeftConstraint = sv.leadingAnchor.constraint(equalTo: leadingAnchor, constant: allDayLabelWidth) /** Why is this constraint 999? Since AllDayView and its constraints are set to its superview and layed out before the superview's width is updated from 0 to it's computed width (screen width), this constraint produces conflicts. Thus, allowing this constraint to be broken prevents conflicts trying to layout this view with the superview.width = 0 More on this: this scope of code is first invoked here: ```` @@ public class TimelineView: UIView, ReusableView, AllDayViewDataSource { ... public var layoutAttributes: [EventLayoutAttributes] { ... allDayView.reloadData() ... } ```` the superview.width is calcuated here: ```` @@ public class TimelineContainer: UIScrollView, ReusableView { ... override public func layoutSubviews() { timeline.frame = CGRect(x: 0, y: 0, width: width, height: timeline.fullHeight) ... } ```` */ svLeftConstraint.priority = UILayoutPriority(rawValue: 999) svLeftConstraint.isActive = true sv.topAnchor.constraint(equalTo: topAnchor, constant: 2).isActive = true sv.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true bottomAnchor.constraint(equalTo: sv.bottomAnchor, constant: 2).isActive = true let maxAllDayViewHeight = allDayEventHeight * 2 + allDayEventHeight * 0.5 heightAnchor.constraint(lessThanOrEqualToConstant: maxAllDayViewHeight).isActive = true return sv }() // MARK: - RETURN VALUES override init(frame: CGRect) { super.init(frame: frame) configure() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } // MARK: - METHODS /** scrolls the contentOffset of the scroll view containg the event views to the bottom */ public func scrollToBottom(animated: Bool = false) { let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height) scrollView.setContentOffset(bottomOffset, animated: animated) } public func updateStyle(_ newStyle: AllDayStyle) { style = newStyle.copy() as! AllDayStyle backgroundColor = style.backgroundColor textLabel.font = style.allDayFont textLabel.textColor = style.allDayColor } private func configure() { clipsToBounds = true //add All-Day UILabel addSubview(textLabel) updateStyle(self.style) } public func reloadData() { defer { layoutIfNeeded() } // clear event views from scroll view scrollView.subviews.forEach { $0.removeFromSuperview() } if self.events.count == 0 { return } // create vertical stack view let verticalStackView = UIStackView( distribution: .fillEqually, spacing: 1.0 ) var horizontalStackView: UIStackView! = nil for (index, anEventDescriptor) in self.events.enumerated() { // create event let eventView = EventView(frame: CGRect.zero) eventView.updateWithDescriptor(event: anEventDescriptor) eventView.delegate = self.eventViewDelegate eventView.heightAnchor.constraint(equalToConstant: allDayEventHeight).isActive = true // create horz stack view if index % 2 == 0 if index % 2 == 0 { horizontalStackView = UIStackView( axis: .horizontal, distribution: .fillEqually, spacing: 1.0 ) horizontalStackView.translatesAutoresizingMaskIntoConstraints = false verticalStackView.addArrangedSubview(horizontalStackView) } // add eventView to horz. stack view horizontalStackView.addArrangedSubview(eventView) } // add vert. stack view inside, pin vert. stack view, update content view by the number of horz. stack views verticalStackView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(verticalStackView) verticalStackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: 0).isActive = true verticalStackView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0).isActive = true verticalStackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 0).isActive = true verticalStackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0).isActive = true verticalStackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1).isActive = true let verticalStackViewHeightConstraint = verticalStackView.heightAnchor.constraint(equalTo: scrollView.heightAnchor, multiplier: 1) verticalStackViewHeightConstraint.priority = UILayoutPriority(rawValue: 999) verticalStackViewHeightConstraint.isActive = true } // MARK: - LIFE CYCLE }
31.625668
134
0.689719
e9fc9f996c1b068314f640421eb1fc7722dcb7c8
2,987
// // HabitHandlerViewModelContract.swift // Habit-Calendar // // Created by Tiago Maia Lopes on 05/12/18. // Copyright © 2018 Tiago Maia Lopes. All rights reserved. // import CoreData /// Protocol defining the interface of any view models to be used with the HabitCreationViewController. protocol HabitHandlerViewModelContract { // MARK: Properties /// Flag indicating if the habit is being edited. var isEditing: Bool { get } /// Flag indicating if the creation/edition operations are valid. var isValid: Bool { get } /// Flag indicating if the deletion operation is available. var canDeleteHabit: Bool { get } /// The container used by the view model. var container: NSPersistentContainer { get } /// The delegate of this view model. var delegate: HabitHandlingViewModelDelegate? { get set } // MARK: Initializers init(habit: HabitMO?, habitStorage: HabitStorage, userStorage: UserStorage, container: NSPersistentContainer, shortcutsManager: HabitsShortcutItemsManager) // MARK: Imperatives /// Deletes the habit, if deletable (The controller only shows the deletion option in case the habit /// is being edited). func deleteHabit() /// Saves the habit, if valid. func saveHabit() /// Returns the name of the habit to be displayed to the user, if set. func getHabitName() -> String? /// Sets the name of the habit. mutating func setHabitName(_ name: String) /// Returns the color of the habit, if set. func getHabitColor() -> HabitMO.Color? /// Sets the color of the habit. mutating func setHabitColor(_ color: HabitMO.Color) /// Returns the days selected for a challenge of days, if set. func getSelectedDays() -> [Date]? /// Sets the selected days for the challenge. mutating func setDays(_ days: [Date]) /// Returns a text describing how many days were selected so far. func getDaysDescriptionText() -> String /// Returns the first date text from the sorted selected days. func getFirstDateDescriptionText() -> String? /// Returns the last date text from the sorted selected days. func getLastDateDescriptionText() -> String? /// Returns the selected fire times components, if set. func getFireTimeComponents() -> [DateComponents]? /// Sets the selected fire time components. mutating func setSelectedFireTimes(_ fireTimes: [DateComponents]) /// Returns a text describing how many fire times were selected. func getFireTimesAmountDescriptionText() -> String /// Returns a text describing the selected fire times. func getFireTimesDescriptionText() -> String? } extension HabitHandlerViewModelContract { var canDeleteHabit: Bool { return isEditing } } protocol HabitHandlingViewModelDelegate: class { /// Handles the errors that might happen while saving the habits. func didReceiveSaveError(_ error: Error) }
30.479592
104
0.699699
f958cdf202a195b9d540f80d3840305653c0d1ea
5,479
// // YYContentView.swift // YYPageView // // Created by Young on 2017/4/29. // Copyright © 2017年 YuYang. All rights reserved. // import UIKit private let kContentViewCellID = "kContentViewCellID" protocol YYContentViewDelegate : class { func yyContentView(_ contentView: YYContentView, targetIndex: Int) func yyContentView(_ contentView: YYContentView, targetIndex: Int, progress: CGFloat) } class YYContentView: UIView { // MARK:-属性 fileprivate var childVcs: [UIViewController] fileprivate var parentVc: UIViewController weak var delegate: YYContentViewDelegate? /// 记录开始滑动的位置 fileprivate lazy var startOffsetX: CGFloat = 0 fileprivate lazy var isForbidScroll : Bool = false // MARK:-控件 fileprivate lazy var contentCollecView : UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = self.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let contentCollecView = UICollectionView(frame: self.bounds, collectionViewLayout: layout) contentCollecView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kContentViewCellID) contentCollecView.isPagingEnabled = true contentCollecView.bounces = false contentCollecView.scrollsToTop = false contentCollecView.showsHorizontalScrollIndicator = false contentCollecView.dataSource = self contentCollecView.delegate = self return contentCollecView }() // MARK:-初始化 init(frame: CGRect, childVcs: [UIViewController], parentVc: UIViewController) { self.childVcs = childVcs self.parentVc = parentVc super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:-UI extension YYContentView { fileprivate func setupUI() { for childVc in childVcs { parentVc.addChild(childVc) } addSubview(contentCollecView) } } // MARK:-DataSource extension YYContentView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kContentViewCellID, for: indexPath) for subView in cell.contentView.subviews { subView.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } // MARK:-Delegate extension YYContentView : UICollectionViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { contentViewEndScroll() scrollView.isScrollEnabled = true } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { contentViewEndScroll() }else { scrollView.isScrollEnabled = false } } /// scrollView停止滚动的时候 通知titleView 调整位置和颜色 private func contentViewEndScroll() { guard !isForbidScroll else { return } let currentIndex = Int(contentCollecView.contentOffset.x / contentCollecView.bounds.width) delegate?.yyContentView(self, targetIndex: currentIndex) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { // 滑动的时候 让处理代理 isForbidScroll = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 1.判断条件, guard startOffsetX != scrollView.contentOffset.x, !isForbidScroll else { return } // 2.定义初始值 var targetIndex: Int = 0 var progress: CGFloat = 0 // 3.计算出当前位置 let currentIndex = Int(startOffsetX / scrollView.bounds.width) // 4.判断是左滑还是右滑动 if startOffsetX < scrollView.contentOffset.x { // 左滑动 index变大 targetIndex = currentIndex + 1 if targetIndex > childVcs.count - 1 { targetIndex = childVcs.count - 1 } progress = (scrollView.contentOffset.x - startOffsetX) / scrollView.bounds.width }else { // 右滑动 index变小 targetIndex = currentIndex - 1 if targetIndex < 0 { targetIndex = 0 } progress = (startOffsetX - scrollView.contentOffset.x) / scrollView.bounds.width } // 5.通知代理 delegate?.yyContentView(self, targetIndex: targetIndex, progress: progress) } } // MARK:-TitleViewDelegate extension YYContentView : YYTitleViewDelegate { func yyTitleViewClick(_ titleView: YYTitleView, targetIndex: Int) { // 点击titleView label时, 不然触发scrollView代理 isForbidScroll = true let indexPath = IndexPath(item: targetIndex, section: 0) contentCollecView.scrollToItem(at: indexPath, at: .left, animated: false) } }
30.270718
121
0.645191
0e6e424b7a74a37084107f52a28ed5f7c97c06ad
2,115
// // SessionManager+ManagedModel.swift // Fritz // // Created by Andrew Barba on 07/14/18. // Copyright © 2018 Fritz Labs Incorporated. All rights reserved. // import Foundation import FritzCore internal enum SessionManagerError: Error { case disabled case downloadMissingModelURL case missingCaseStatement } // MARK: - Measure @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) extension SessionManager { /// Measures a predication result and reports to API func measurePrediction(_ result: PredictionResult, forManagedModel model: FritzMLModel) { let options: RequestOptions = [ "is_ota": model.activeModelConfig.isOTA, "model_version": model.version, "model_uid": model.id, "elapsed_nano_seconds": result.predicationElapsedTime, "uses_cpu_only": result.predictionOptions?.usesCPUOnly ?? false, ] trackEvent(.init(type: .prediction, data: options)) } /// Samples input/output data from a prediction result func sampleInputOutput(_ result: PredictionResult, forManagedModel model: FritzMLModel) { guard session.settings.shouldSampleInputOutput() else { return } var options: RequestOptions = [ "input": result.predictionInput.toJSON(), "model_uid": model.id, "model_version": model.version, ] if let output = result.predictionOutput { options["output"] = output.toJSON() } if let error = result.predictionError { logger.error("Model Prediction Error:", options, error) options["error"] = error.toJSON() } trackEvent(.init(type: .inputOutputSample, data: options)) } } // MARK: - Install @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) extension SessionManager { /// Reports install of a model. func reportInstall(forManagedModel model: FritzMLModel) { logger.debug("Reporting Model Install:", model.id) let options: RequestOptions = [ "is_ota": model.activeModelConfig.isOTA, "model_version": model.version, "model_uid": model.id, ] trackEvent(.init(type: .modelInstalled, data: options)) } }
27.115385
91
0.69409
fbd23fad3386f300f402e5c3536421373001de78
2,339
// // ViewController.swift // hackathonproj // // Created by Mohammed Trama on 6/27/19. // Copyright © 2019 Mohammed Trama. All rights reserved. // import UIKit import Alamofire class ViewController: UIViewController { @IBOutlet weak var upsLogoImage: UIImageView! @IBOutlet weak var userIDtf: UITextField! @IBOutlet weak var passtf: UITextField! @IBOutlet weak var errorLbl: UILabel! var userUuid = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var vc = segue.destination as! HomeViewController vc.uuID = self.userUuid } @IBAction func onClickLogIn(_ sender: Any) { var user : String? = userIDtf.text var pass : String? = passtf.text // if user!.count >= 7 { // errorLbl.text = "Invalid username" // } // // if pass!.count >= 5 { // passErrorLbl.text = "Invalid password" // } // if !(user!.count >= 0 && pass!.count >= 0){ errorLbl?.text = "Invalid login credentials" errorLbl?.textColor = UIColor.red } else { print("printing user") print(user!) Alamofire.request("https://hackathonproj-155e2.firebaseio.com/users/\(user!)/id.json", method: .get, encoding: JSONEncoding.default) .responseJSON { response in debugPrint(response) if let data = response.result.value{ // Response type-1 print("running") print(data) self.userUuid = data as! String self.performSegue(withIdentifier: "loginSegue", sender: self) } } } // check length of user id // check length of pass // if both are long enough then contiue // otehrwise display error message } }
30.776316
144
0.526293