repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
joostholslag/BNRiOS
iOSProgramming6ed/16 - Archiving/Solutions/Homepwner/Homepwner/ImageStore.swift
1
1664
// // Copyright © 2015 Big Nerd Ranch // import UIKit class ImageStore { let cache = NSCache<NSString, UIImage>() func imageURL(forKey key: String) -> URL { let documentsDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentDirectory = documentsDirectories.first! return documentDirectory.appendingPathComponent(key) } func setImage(_ image: UIImage, forKey key: String) { cache.setObject(image, forKey: key as NSString) // Create full URL for image let url = imageURL(forKey: key) // Turn image into JPEG data if let data = UIImageJPEGRepresentation(image, 0.5) { // Write it to full URL let _ = try? data.write(to: url, options: [.atomic]) } } func image(forKey key: String) -> UIImage? { if let existingImage = cache.object(forKey: key as NSString) { return existingImage } let url = imageURL(forKey: key) guard let imageFromDisk = UIImage(contentsOfFile: url.path) else { return nil } cache.setObject(imageFromDisk, forKey: key as NSString) return imageFromDisk } func deleteImage(forKey key: String) { cache.removeObject(forKey: key as NSString) let url = imageURL(forKey: key) do { try FileManager.default.removeItem(at: url) } catch let deleteError { print("Error removing the image from disk: \(deleteError)") } } }
gpl-3.0
f8e6932580b510c7829331ceab4183f5
27.186441
74
0.574865
4.891176
false
false
false
false
ZekeSnider/Jared
Pods/Telegraph/Sources/Protocols/WebSockets/Models/WebSocketParser.swift
1
7700
// // WebSocketParser.swift // Telegraph // // Created by Yvo van Beek on 2/17/17. // Copyright © 2017 Building42. All rights reserved. // import Foundation // // Base Framing Protocol (https://tools.ietf.org/html/rfc6455 - 5.2) // // |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| // +-+-+-+-+-------+-+-------------+-------------------------------+ // |F|R|R|R| opcode|M| Payload len | Extended payload length | // |I|S|S|S| (4) |A| (7) | (16/64) | // |N|V|V|V| |S| | (if payload len==126/127) | // | |1|2|3| |K| | | // +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + // | Extended payload length continued if payload len == 127 | // + - - - - - - - - - - - - - - - +-------------------------------+ // | | Masking-key, if MASK set to 1 | // +-------------------------------+-------------------------------+ // | Masking-key (continued) | Payload Data | // +-------------------------------- - - - - - - - - - - - - - - - + // : Payload Data continued ... : // + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + // | Payload Data continued ... | // +---------------------------------------------------------------+ // // swiftlint:disable function_body_length public protocol WebSocketParserDelegate: class { func parser(_ parser: WebSocketParser, didCompleteMessage message: WebSocketMessage) } public class WebSocketParser { public let maxPayloadLength: UInt64 public weak var delegate: WebSocketParserDelegate? public private(set) lazy var message = WebSocketMessage() public private(set) lazy var maskingKey = [UInt8](repeating: 0, count: 4) public private(set) lazy var payload = Data() public private(set) var nextPart = Part.finAndOpcode public private(set) var bytesParsed = 0 public private(set) var payloadLength: UInt64 = 0 /// Describes the different parts to parse. public enum Part { case finAndOpcode case maskAndPayloadLength case extendedPayloadLength16(byteNo: Int) case extendedPayloadLength64(byteNo: Int) case maskingKey(byteNo: Int) case payload case endOfMessage } /// Initializes a websocket parser. public init(maxPayloadLength: Int = 10_485_760) { self.maxPayloadLength = UInt64(maxPayloadLength) } /// Parses the incoming data into a websocket message. public func parse(data: Data) throws { let stream = DataStream(data: data) while let byte = stream.read() { switch nextPart { case .finAndOpcode: // Extract and store the FIN bit message.finBit = byte & WebSocketMasks.finBit != 0 // Extract and validate the opcode guard let opcode = WebSocketOpcode(rawValue: byte & WebSocketMasks.opcode) else { throw WebSocketError.invalidOpcode } // Store the opcode message.opcode = opcode nextPart = .maskAndPayloadLength case .maskAndPayloadLength: // Extract the mask bit message.maskBit = byte & WebSocketMasks.maskBit != 0 // Extract the payload length payloadLength = UInt64(byte & WebSocketMasks.payloadLength) switch payloadLength { case 0: nextPart = message.maskBit ? .maskingKey(byteNo: 1) : .endOfMessage case 1..<126: nextPart = message.maskBit ? .maskingKey(byteNo: 1) : .payload case 126: nextPart = .extendedPayloadLength16(byteNo: 1) case 127: nextPart = .extendedPayloadLength64(byteNo: 1) default: throw WebSocketError.invalidPayloadLength } case .extendedPayloadLength16(let byteNo): // Extract the extended payload length (2 bytes) switch byteNo { case 1: payloadLength = UInt64(byte) << 8 nextPart = .extendedPayloadLength16(byteNo: 2) case 2: payloadLength += UInt64(byte) nextPart = message.maskBit ? .maskingKey(byteNo: 1) : .payload default: break } case .extendedPayloadLength64(let byteNo): // Extract the extended payload length (8 bytes) switch byteNo { case 1: payloadLength = UInt64(byte) nextPart = .extendedPayloadLength64(byteNo: 2) case 2..<8: payloadLength = payloadLength << 8 + UInt64(byte) nextPart = .extendedPayloadLength64(byteNo: byteNo + 1) case 8: payloadLength = payloadLength << 8 + UInt64(byte) guard payloadLength <= maxPayloadLength else { throw WebSocketError.payloadTooLarge } nextPart = message.maskBit ? .maskingKey(byteNo: 1) : .payload default: break } case .maskingKey(let byteNo): // Extract the masking key switch byteNo { case 1, 2, 3: maskingKey[byteNo - 1] = byte nextPart = .maskingKey(byteNo: byteNo + 1) case 4: maskingKey[3] = byte nextPart = payloadLength > 0 ? .payload : .endOfMessage default: break } case .payload: // For now we can only support payloads that can fit into a Data object, // if the payload is any bigger we should probably offload it to a temporary file let payloadSafeLength = payloadLength > Int.max ? Int.max : Int(payloadLength) // Is this the first payload byte? if payload.isEmpty { payload.reserveCapacity(payloadSafeLength) } // Append the byte we already read payload.append(byte) // Append any payload bytes available in the stream let payloadBytesToRead = payloadSafeLength - payload.count payload.append(stream.read(count: payloadBytesToRead)) // Is the payload complete? if payload.count == payloadSafeLength { nextPart = .endOfMessage } case .endOfMessage: // This case should never be reached, because finishMessage resets // the part that is being processed to the .finAndOpcode break } // Are we done with the message? if case .endOfMessage = nextPart { try finishMessage() } } } /// Resets the parser. public func reset() { message = WebSocketMessage() nextPart = .finAndOpcode maskingKey = [UInt8](repeating: 0, count: 4) payloadLength = 0 payload = Data() } /// Interprets the payload and calls the delegate to inform of the new message. private func finishMessage() throws { // Do we have to unmask the payload? if message.maskBit { payload.mask(with: maskingKey) } switch message.opcode { case .binaryFrame, .continuationFrame: // Binary payload message.payload = .binary(payload) case .textFrame: // Text payload guard let text = String(data: payload, encoding: .utf8) else { throw WebSocketError.payloadIsNotText } message.payload = .text(text) case .connectionClose: // Close payload let buffer = DataStream(data: payload) let code = UInt16(buffer.read() ?? 0) << 8 | UInt16(buffer.read() ?? 0) let reason = String(data: buffer.readToEnd(), encoding: .utf8) ?? "" message.payload = .close(code: code, reason: reason) case .ping, .pong: // Ping / pong with optional payload message.payload = payload.isEmpty ? .none : .binary(payload) } // Keep a reference to the message and reset let completedMessage = message reset() // Inform the delegate delegate?.parser(self, didCompleteMessage: completedMessage) } }
apache-2.0
03302d9b8b5a29189a591ddfa1e98c16
34.643519
108
0.582933
4.344808
false
false
false
false
yinnieryou/DesignPattern
ChainOfResponsibility.playground/contents.swift
1
2501
// Playground - noun: a place where people can play import UIKit //责任链模式 //需要处理的数据 class Level{ var level:Int! init(level:Int){ self.level = level } func above(level:Level) -> Bool{ return self.level >= level.level } } //把相关的数据封装成一个请求 class Request { var level:Level! init(level:Level){ self.level = level } } //响应 class Response { } //抽象的处理 class Handler { private var nexthandler :Handler! final func handleRequest(request:Request) -> Response{ var response:Response = Response() if self.getHandlerLevel().above(request.level) { response = self.response(request) }else{ if self.nexthandler != nil { self.nexthandler.handleRequest(request)//责任链传递 }else{ println("no thing can do") } } return response } func setNextHandler(handler:Handler){ self.nexthandler = handler } func getHandlerLevel() -> Level { assert(false, "must be override") return Level(level: 0) } func response(request:Request) -> Response{ assert(false, "must be override") return Response() } } //具体处理1 class ConcreteHandler1: Handler { override func getHandlerLevel() -> Level { return Level(level: 1) } override func response(request: Request) -> Response { println("concreteHandler1 is handle") return Response() } } //具体处理2 class ConcreteHandler2: Handler { override func getHandlerLevel() -> Level { return Level(level: 3) } override func response(request: Request) -> Response { println("concreteHandler2 is handle") return Response() } } //具体处理3 class ConcreteHandler3: Handler { override func getHandlerLevel() -> Level { return Level(level: 5) } override func response(request: Request) -> Response { println("concreteHandler3 is handle") return Response() } } class Client { init(){ var handler1 = ConcreteHandler1() var handler2 = ConcreteHandler2() var handler3 = ConcreteHandler3() handler1.setNextHandler(handler2) handler2.setNextHandler(handler3) var request:Request = Request(level: Level(level: 3)) handler1.handleRequest(request) } } var client = Client()
mit
8860c67140b384d1413243a1ab82c762
23.03
62
0.606742
4.201049
false
false
false
false
andreamazz/Tropos
Sources/TroposCore/ViewModels/WeatherViewModel.swift
3
4699
import UIKit @objc(TRWeatherViewModel) public final class WeatherViewModel: NSObject { fileprivate let weatherUpdate: WeatherUpdate fileprivate let dateFormatter: RelativeDateFormatter public init(weatherUpdate: WeatherUpdate, dateFormatter: RelativeDateFormatter) { self.weatherUpdate = weatherUpdate self.dateFormatter = dateFormatter } @objc public convenience init(weatherUpdate: WeatherUpdate) { self.init(weatherUpdate: weatherUpdate, dateFormatter: RelativeDateFormatter()) } } public extension WeatherViewModel { @objc var locationName: String { return [weatherUpdate.city, weatherUpdate.state].lazy .compactMap { $0 } .joined(separator: ", ") } @objc var updatedDateString: String { return dateFormatter.localizedStringFromDate(weatherUpdate.date) } @objc var conditionsImage: UIImage? { return weatherUpdate.conditionsDescription.flatMap { UIImage(named: $0, in: .troposBundle, compatibleWith: nil) } } @objc var conditionsDescription: NSAttributedString { let comparison = weatherUpdate.currentTemperature.comparedTo(weatherUpdate.yesterdaysTemperature!) let (description, adjective) = TemperatureComparisonFormatter().localizedStrings( fromComparison: comparison, precipitation: precipitationDescription, date: weatherUpdate.date ) let attributedString = NSMutableAttributedString(string: description) attributedString.font = .defaultLightFont(size: 26) attributedString.textColor = .defaultTextColor let difference = weatherUpdate.currentTemperature .temperatureDifferenceFrom(weatherUpdate.yesterdaysTemperature!) attributedString.setTextColor( colorForTemperatureComparison(comparison, difference: difference.fahrenheitValue), forSubstring: adjective ) return attributedString.copy() as! NSAttributedString } @objc var windDescription: String { return WindSpeedFormatter().localizedString( forWindSpeed: weatherUpdate.windSpeed, bearing: weatherUpdate.windBearing ) } @objc var precipitationDescription: String { let precipitation = Precipitation( probability: weatherUpdate.precipitationPercentage, type: weatherUpdate.precipitationType ) return PrecipitationChanceFormatter().localizedStringFromPrecipitation(precipitation) } @objc var temperatureDescription: NSAttributedString { let formatter = TemperatureFormatter() let temperatures = [weatherUpdate.currentHigh, weatherUpdate.currentTemperature, weatherUpdate.currentLow] let temperatureString = temperatures.lazy.map(formatter.stringFromTemperature).joined(separator: " / ") let attributedString = NSMutableAttributedString(string: temperatureString) let comparison = weatherUpdate.currentTemperature.comparedTo(weatherUpdate.yesterdaysTemperature!) let difference = weatherUpdate.currentTemperature .temperatureDifferenceFrom(weatherUpdate.yesterdaysTemperature!) let rangeOfFirstSlash = (temperatureString as NSString).range(of: "/") let rangeOfLastSlash = (temperatureString as NSString).range(of: "/", options: .backwards) let start = (rangeOfFirstSlash.location + 1) let range = NSRange(location: start, length: rangeOfLastSlash.location - start) attributedString.setTextColor( colorForTemperatureComparison(comparison, difference: difference.fahrenheitValue), forRange: range ) return attributedString.copy() as! NSAttributedString } @objc var dailyForecasts: [DailyForecastViewModel] { return weatherUpdate.dailyForecasts.map(DailyForecastViewModel.init) } } private extension WeatherViewModel { func colorForTemperatureComparison(_ comparison: TemperatureComparison, difference: Int) -> UIColor { let color: UIColor switch comparison { case .same: color = .defaultTextColor case .colder: color = .coldColor case .cooler: color = .coolerColor case .hotter: color = .hotColor case .warmer: color = .warmerColor } if comparison == .cooler || comparison == .warmer { let amount = CGFloat(min(abs(difference), 10)) / 10.0 let lighterAmount = min(1 - amount, 0.8) return color.lighten(by: lighterAmount) } else { return color } } }
mit
6f05694ddc06fa6cf7222159bcbac04a
37.203252
114
0.686742
5.614098
false
false
false
false
VoIPGRID/vialer-ios
Vialer/AppDelegate.swift
1
29067
// // AppDelegate.swift // Copyright © 2017 VoIPGRID. All rights reserved. // import AVFoundation import CoreData import Firebase import UIKit import UserNotifications @UIApplicationMain @objc class AppDelegate: UIResponder { fileprivate struct Configuration { struct LaunchArguments { static let screenShotRun = "ScreenshotRun" static let noAnimations = "NoAnimations" } struct Notifications { struct Identifiers { static let category = "IncomingCall" static let accept = "AcceptCall" static let decline = "DeclineCall" static let missed = "MissedCall" } static let incomingCallIDKey = "CallID" static let startConnectABCall = Notification.Name(rawValue: AppDelegateStartConnectABCallNotification) static let connectABPhoneNumberUserInfoKey = Notification.Name(rawValue: AppDelegateStartConnectABCallUserInfoKey) } struct Vibrations { static let count = 5 static let interval: TimeInterval = 2.0 } struct TimerForCall { static let maxTimesFiring = 10 static let interval: TimeInterval = 1.0 } } var window: UIWindow? let sharedApplication = UIApplication.shared @objc var isScreenshotRun = false var notificationCenter: UNUserNotificationCenter{ return UNUserNotificationCenter.current() } var stopVibrating = false var vibratingTask: UIBackgroundTaskIdentifier? @objc var callKitProviderDelegate: VialerCallKitDelegate! var callAvailabilityTimer: Timer! var callAvailabilityTimesFired: Int = 0 var user = SystemUser.current()! lazy var vialerSIPLib = VialerSIPLib.sharedInstance() var mostRecentCall : VSLCall? let reachability = Reachability(true)! private var _callEventMonitor: Any? = nil fileprivate var callEventMonitor: CallEventsMonitor { if _callEventMonitor == nil { _callEventMonitor = CallEventsMonitor() } return _callEventMonitor as! CallEventsMonitor } let pushKitManager = PushKitManager() } // MARK: - UIApplicationDelegate extension AppDelegate: UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { interpretLaunchArguments() VialerLogger.setup() SAMKeychain.setAccessibilityType(kSecAttrAccessibleAfterFirstUnlock) application.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum) setupUI() setupObservers() setupVoIP() setupFirebase() setupUNUserNotifications() return true } func applicationDidBecomeActive(_ application: UIApplication) { DispatchQueue.global(qos: .background).async { // No completion necessary, because an update will follow over the "SystemUserSIPCredentialsChangedNotifications". if self.user.loggedIn { self.user.updateFromVG(completion: nil) } } } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { return didStartCallFor(userActivity: userActivity) } func applicationWillEnterForeground(_ application: UIApplication) { stopVibratingInBackground() DispatchQueue.main.async { self.pushKitManager.registerForVoIPPushes() self.syncUserWithBackend() } } func applicationDidEnterBackground(_ application: UIApplication) { NotificationCenter.default.post(name: Notification.Name.teardownSip, object: self) saveContext() DispatchQueue.main.async { self.pushKitManager.registerForVoIPPushes() } } func applicationWillTerminate(_ application: UIApplication) { removeObservers() callEventMonitor.stop() // Saves changes in the application's managed object context before the application terminates. saveContext() } } // MARK: - Helper methods extension AppDelegate { /// Check if we're in a screenshot run fileprivate func interpretLaunchArguments() { let arguments = ProcessInfo.processInfo.arguments; if arguments.contains(Configuration.LaunchArguments.screenShotRun) { isScreenshotRun = true let appDomain = Bundle.main.bundleIdentifier! UserDefaults.standard.removePersistentDomain(forName: appDomain) } if arguments.contains(Configuration.LaunchArguments.noAnimations) { UIView.setAnimationsEnabled(false) } } fileprivate func setupFirebase() { if let filePath = Bundle.main.path(forResource: "FirebaseService-Info", ofType: "plist") { guard let fileopts = FirebaseOptions(contentsOfFile: filePath) else { assert(false, "Couldn't load config file") return } FirebaseApp.configure(options: fileopts) } } /// Set global UI settings fileprivate func setupUI() { SVProgressHUD.setDefaultStyle(.dark) #if DEBUG if isScreenshotRun { SDStatusBarManager.sharedInstance().timeString = "09:41" SDStatusBarManager.sharedInstance().enableOverrides() CNContactStore().requestAccess(for: .contacts) { granted, error in VialerLogDebug(granted ? "Contacts access granted" : "Contact access denied") } } #endif } } // MARK: - Observers extension AppDelegate { /// Hook up the observers that AppDelegate should listen to fileprivate func setupObservers() { NotificationCenter.default.addObserver(self, selector: #selector(updatedSIPCredentials), name: NSNotification.Name.SystemUserSIPCredentialsChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateSIPEndpoint(_:)), name: NSNotification.Name.SystemUserEncryptionUsageChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(updateSIPEndpoint(_:)), name: NSNotification.Name.SystemUserStunUsageChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(sipDisabledNotification), name: NSNotification.Name.SystemUserSIPDisabled, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(sipDisabledNotification), name: NSNotification.Name.SystemUserLogout, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(userLoggedIn), name: NSNotification.Name.SystemUserLogin, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(callStateChanged(_:)), name: NSNotification.Name.VSLCallStateChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(callKitCallWasHandled(_:)), name: NSNotification.Name.CallKitProviderDelegateInboundCallAccepted, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(callKitCallWasHandled(_:)), name: NSNotification.Name.CallKitProviderDelegateInboundCallRejected, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(middlewareRegistrationFinished(_:)), name: NSNotification.Name.MiddlewareAccountRegistrationIsDone, object:nil) NotificationCenter.default.addObserver(self, selector: #selector(errorDuringCallSetup(_:)), name: NSNotification.Name.VSLCallErrorDuringSetupCall, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(managedObjectContextSaved(_:)), name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(tearDownSip(_:)), name: Notification.Name.teardownSip, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(receivedApnsToken(_:)), name: Notification.Name.receivedApnsToken, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(receivedApnsToken(_:)), name: Notification.Name.remoteLoggingStateChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: NSNotification.Name(rawValue: ReachabilityChangedNotification),object: reachability) user.addObserver(self, forKeyPath: #keyPath(SystemUser.clientID), options: NSKeyValueObservingOptions(rawValue: 0), context: nil) _ = ReachabilityHelper.instance do { try reachability.startNotifier() } catch { VialerLogDebug("Reachability notifier failed to start.") } } /// Remove the observers that the AppDelegate is listening to fileprivate func removeObservers() { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.SystemUserSIPCredentialsChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.SystemUserEncryptionUsageChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.SystemUserStunUsageChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.SystemUserSIPDisabled, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.SystemUserLogin, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.SystemUserLogout, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.VSLCallStateChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.MiddlewareAccountRegistrationIsDone, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.VSLCallErrorDuringSetupCall, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.teardownSip, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.receivedApnsToken, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.remoteLoggingStateChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: ReachabilityChangedNotification), object: reachability) user.removeObserver(self, forKeyPath: #keyPath(SystemUser.clientID)) reachability.stopNotifier() } } // MARK: - KVO extension AppDelegate { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == #keyPath(SystemUser.clientID) && user.clientID != nil { VialerGAITracker.setCustomDimension(withClientID: user.clientID) } } } // MARK: - Notifications extension AppDelegate: UNUserNotificationCenterDelegate { fileprivate func setupUNUserNotifications() { let options: UNAuthorizationOptions = [.alert, .sound] notificationCenter.delegate = self notificationCenter.requestAuthorization(options: options) { (granted, error) in if !granted { VialerLogInfo("User has declined notifications") } } } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // Called when the app receives a notification. completionHandler([.alert, .sound]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // The user taps on the missed call notification. if response.notification.request.identifier == Configuration.Notifications.Identifiers.missed { // Present the RecentsViewController. if let vialerRootVC = self.window?.rootViewController as? VailerRootViewController, let vialerDrawerVC = vialerRootVC.presentedViewController as? VialerDrawerViewController, let mainTabBarVC = vialerDrawerVC.centerViewController as? UITabBarController { // Make the app open on the recent calls screen. mainTabBarVC.selectedIndex = 2 } } completionHandler() } fileprivate func registerForLocalNotifications() { VialerLogDebug("Starting registration with UNNotification for local notifications.") let acceptCallAction = UNNotificationAction(identifier: Configuration.Notifications.Identifiers.accept, title: NSLocalizedString("Accept", comment: "Accept"), options: [.foreground]) let declineCallAction = UNNotificationAction(identifier: Configuration.Notifications.Identifiers.decline, title: NSLocalizedString("Decline", comment: "Decline"), options: []) let notificationCategory = UNNotificationCategory(identifier: Configuration.Notifications.Identifiers.category, actions: [acceptCallAction, declineCallAction], intentIdentifiers: [], options: []) notificationCenter.setNotificationCategories([notificationCategory]) let options: UNAuthorizationOptions = [.alert, .sound] notificationCenter.requestAuthorization(options: options) { (granted, error) in if !granted { VialerLogDebug("Authorization for using UNUserNotificationCenter is denied.") } } } @objc fileprivate func callKitCallWasHandled(_ notification: NSNotification) { if notification.name == NSNotification.Name.CallKitProviderDelegateInboundCallAccepted { VialerGAITracker.acceptIncomingCallEvent() } else if notification.name == NSNotification.Name.CallKitProviderDelegateInboundCallRejected { VialerGAITracker.declineIncomingCallEvent() if let mostRecentCallUnwrapped = self.mostRecentCall { VialerStats.sharedInstance.incomingCallFailedDeclined(call:mostRecentCallUnwrapped) } } } @objc fileprivate func middlewareRegistrationFinished(_ notification: NSNotification) { if callAvailabilityTimer == nil { callAvailabilityTimer = Timer.scheduledTimer(timeInterval: Configuration.TimerForCall.interval, target: self, selector: #selector(runCallTimer), userInfo: nil, repeats: true) VialerLogDebug("Registration of VoIP account done, start timer for receiving a call."); } } @objc fileprivate func errorDuringCallSetup(_ notification: NSNotification) { let statusCode = notification.userInfo![VSLNotificationUserInfoErrorStatusCodeKey] as! String let statusMessage = notification.userInfo![VSLNotificationUserInfoErrorStatusMessageKey] as! String if statusCode != "401" && statusCode != "407" { let callId = notification.userInfo![VSLNotificationUserInfoCallIdKey] as! String let callIncoming = callAvailabilityTimer != nil if callAvailabilityTimer != nil { resetCallAvailabilityTimer() } VialerStats.sharedInstance.callFailed(callId: callId, incoming: callIncoming, statusCode: statusCode) VialerLogWarning("Error setting up a call with \(statusCode) / \(statusMessage)") } } @objc fileprivate func tearDownSip(_ notification: NSNotification) { resetVoip() } } // MARK: - VoIP extension AppDelegate { /// Make sure the VoIP parts are up and running fileprivate func setupVoIP() { VialerLogDebug("Setting up VoIP") if callKitProviderDelegate == nil { VialerLogDebug("Initializing CallKit") callKitProviderDelegate = VialerCallKitDelegate(callManager: vialerSIPLib.callManager) } else { callKitProviderDelegate.refresh() } callEventMonitor.start() if user.sipEnabled { VialerLogDebug("VoIP is enabled start the endpoint.") updatedSIPCredentials() } setupIncomingCallBack() setupMissedCallBack() } /// Register a callback to the sip library so that the app can handle incoming calls private func setupIncomingCallBack() { VialerLogDebug("Setup the listener for incoming calls through VoIP."); vialerSIPLib.setIncomingCall { call in VialerGAITracker.incomingCallRingingEvent() VoIPPushHandler.incomingCallConfirmed = true DispatchQueue.main.async { VialerLogInfo("Incoming call block invoked, routing through CallKit.") self.mostRecentCall = call self.callKitProviderDelegate.reportIncomingCall(call: call) } } } /// Register a callback to the sip library so that the app can handle missed calls private func setupMissedCallBack() { VialerLogDebug("Setup the listener for missing calls."); vialerSIPLib.setMissedCall { (call) in switch call.terminateReason { case .callCompletedElsewhere: VialerLogDebug("Missed call, call completed elsewhere.") VialerGAITracker.missedIncomingCallCompletedElsewhereEvent() VialerStats.sharedInstance.incomingCallFailedDeclined(call: call) case .originatorCancel: VialerLogDebug("Missed call, originator cancelled.") VialerGAITracker.missedIncomingCallOriginatorCancelledEvent() VialerStats.sharedInstance.incomingCallFailedDeclined(call: call) self.createLocalNotificationMissedCall(forCall: call) default: VialerLogDebug("Missed call, unknown reason.") break } } } private func resetVoip() { self.mostRecentCall = nil let success = SIPUtils.safelyRemoveSipEndpoint() if success { setupVoIP() } else { DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { SIPUtils.safelyRemoveSipEndpoint() self.setupVoIP() } } } /// Setup the endpoint if user has SIP enabled @objc fileprivate func updatedSIPCredentials() { VialerLogInfo("SIP Credentials have changed") if !user.loggedIn { VialerLogWarning("User is not logged in") return } if !user.sipEnabled { VialerLogWarning("SIP not enabled") return } DispatchQueue.main.async { self.refreshMiddlewareRegistration() self.registerForLocalNotifications() self.syncUserWithBackend() } } @objc fileprivate func updateSIPEndpoint(_ notification: NSNotification) { VialerLogInfo("\(notification.name) fired to update SIP endpoint") if !user.loggedIn { VialerLogWarning("User is not logged in") return } if !user.sipEnabled { VialerLogWarning("SIP not enabled") return } resetVoip() } @objc fileprivate func userLoggedIn() { VialerLogInfo("User has been logged in register for push notifications") DispatchQueue.main.async { self.refreshMiddlewareRegistration() self.syncUserWithBackend() } } /** Ensures we have opus enabled on the backend for users. */ private func syncUserWithBackend() { if self.user.isOpusEnabledViaApi { return } if self.user.currentAudioQuality == 0 { return } self.user.updateUseOpus(1) { success, error in if success { VialerLogInfo("OPUS has been enabled for this user") } else { VialerLogError("Unable to enable OPUS for this user") } if error != nil { VialerLogError("Failed to enable OPUS for user: \(error)") } } } /// SIP was disabled, remove the endpoint @objc fileprivate func sipDisabledNotification() { VialerLogInfo("SIP has been disabled") DispatchQueue.main.async { SIPUtils.removeSIPEndpoint() if let token = self.pushKitManager.token { Middleware().deleteDeviceRegistration(token) } else { VialerLogWarning("Unable to delete device from middleware as we have no token") } } } /// Listen for call state change notifications /// /// If call is no longer running, we stop the vibrations and remove the local notification. /// /// - Parameter notification: Notification instance with VSLCall @objc fileprivate func callStateChanged(_ notification: Notification) { resetCallAvailabilityTimer() guard let call = notification.userInfo![VSLNotificationUserInfoCallKey] as? VSLCall, call.callState == .connecting || call.callState == .disconnected else { return } notificationCenter.removePendingNotificationRequests(withIdentifiers: [notification.name.rawValue]) stopVibratingInBackground() } /// Call was initiated from recents, addressbook or via call back on the native call kit ui. This will try to setup a call. /// /// - Parameter userActivity: NSUseractivity instance /// - Returns: success or failure of setting up call fileprivate func didStartCallFor(userActivity: NSUserActivity) -> Bool { guard let phoneNumber = userActivity.startCallHandle else { return false } // When there is no connection for VoIP or VoIP is disabled in the settings setup a connectAB call. if !ReachabilityHelper.instance.connectionFastEnoughForVoIP() { let notificationInfo = [Configuration.Notifications.connectABPhoneNumberUserInfoKey: phoneNumber] NotificationCenter.default.post(name: Configuration.Notifications.startConnectABCall, object: self, userInfo: notificationInfo) return true; } SIPUtils.setupSIPEndpoint() guard let account = SIPUtils.addSIPAccountToEndpoint() else { VialerLogError("Couldn't add account to endpoint, not setting up call to: \(phoneNumber)") return false } VialerGAITracker.setupOutgoingSIPCallEvent() vialerSIPLib.callManager.startCall(toNumber: phoneNumber, for: account) { _, error in if error != nil { VialerLogError("Error starting call through User activity. Error: \(String(describing: error))") } } return true } private func createLocalNotificationMissedCall(forCall call: VSLCall) { let content = UNMutableNotificationContent() let callerNumber = call.callerNumber! // Possible options: a phone number or "anonymous". var displayName = callerNumber // If the call isn't anonymous try to look up the number for a known contact. if callerNumber != "anonymous" { let digits = PhoneNumberUtils.removePrefix(fromPhoneNumber: callerNumber) if let phoneNumber = ContactModel.defaultModel.phoneNumbersToContacts[digits] { displayName = phoneNumber.callerName! } } else { displayName = NSLocalizedString("Anonymous", comment: "Anonymous") } content.title = displayName content.body = NSLocalizedString("Missed call", comment: "Missed call") content.sound = UNNotificationSound.default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) let identifier = Configuration.Notifications.Identifiers.missed let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) notificationCenter.add(request) { (error) in if let error = error { print("Could not add missed call notification: \(error.localizedDescription)") } } } /// Create a background task that will vibrate the phone. private func startVibratingInBackground() { stopVibrating = false vibratingTask = sharedApplication.beginBackgroundTask { self.stopVibrating = true if let task = self.vibratingTask { self.sharedApplication.endBackgroundTask(task) } self.vibratingTask = UIBackgroundTaskIdentifier(rawValue: UIBackgroundTaskIdentifier.invalid.rawValue) } DispatchQueue.global(qos: .userInteractive).async { for _ in 0...Configuration.Vibrations.count { if self.stopVibrating { break } AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) Thread.sleep(forTimeInterval: Configuration.Vibrations.interval) } if let task = self.vibratingTask { self.sharedApplication.endBackgroundTask(task) } self.vibratingTask = UIBackgroundTaskIdentifier(rawValue: UIBackgroundTaskIdentifier.invalid.rawValue) } } /// Stop the vibrations fileprivate func stopVibratingInBackground() { stopVibrating = true guard let task = vibratingTask else { return } sharedApplication.endBackgroundTask(task) } } // MARK: - Core Data extension AppDelegate { fileprivate func saveContext() { guard CoreDataStackHelper.instance.managedObjectContext.hasChanges else { return } do { try CoreDataStackHelper.instance.managedObjectContext.save() } catch let error { VialerLogWarning("Unresolved error while saving Context: \(error)"); abort() } } @objc fileprivate func managedObjectContextSaved(_ notification: Notification) { CoreDataStackHelper.instance.managedObjectContext.perform { CoreDataStackHelper.instance.managedObjectContext.mergeChanges(fromContextDidSave: notification) } } } // MARK: - Timed code extension AppDelegate { @objc fileprivate func runCallTimer() { callAvailabilityTimesFired += 1 if callAvailabilityTimesFired > Configuration.TimerForCall.maxTimesFiring { resetCallAvailabilityTimer() VialerStats.sharedInstance.noIncomingCallReceived() } } fileprivate func resetCallAvailabilityTimer() { callAvailabilityTimesFired = 0; if callAvailabilityTimer != nil { callAvailabilityTimer.invalidate() callAvailabilityTimer = nil } } } // MARK: - Middleware extension AppDelegate { /** This can be called, regardless of the current state, and it will properly set the correct middleware registration status. */ func refreshMiddlewareRegistration() { guard let token = self.pushKitManager.token else { VialerLogInfo("Unable to perform any middleware updates as we do not have a valid APNS token.") self.pushKitManager.registerForVoIPPushes() return } let middleware = Middleware() if user.loggedIn && user.sipEnabled { VialerLogInfo("Registering user with the middleware.") middleware.sentAPNSToken(token) } else { VialerLogInfo("Deleting user from the middleware.") middleware.deleteDeviceRegistration(token) } } @objc fileprivate func receivedApnsToken(_ notification: NSNotification) { refreshMiddlewareRegistration() } } extension Notification.Name { /** A notification that is emitted when a token has been received from the apns servers. */ static let remoteLoggingStateChanged = Notification.Name("remote-logging-state-changed") } // Reachability extension AppDelegate { @objc func reachabilityChanged(note: NSNotification) { VialerLogInfo("Reachability changed, rebooting SIP after delay") if SIPUtils.isSafeToRemoveSipEndpoint() { VialerLogInfo("Rebooting SIP if still safe") DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { SIPUtils.safelyRemoveSipEndpoint() } } } }
gpl-3.0
177e556064cf6e11d25d6c31a2c09940
42.060741
203
0.676151
5.682502
false
false
false
false
jpsim/YamlSwift
Yaml/Parser.swift
2
17485
import Foundation struct Context { let tokens: [TokenMatch] let aliases: [String: Yaml] init (_ tokens: [TokenMatch], _ aliases: [String: Yaml] = [:]) { self.tokens = tokens self.aliases = aliases } } typealias ContextValue = (context: Context, value: Yaml) func createContextValue (_ context: Context) -> (Yaml) -> ContextValue { return { value in (context, value) } } func getContext (_ cv: ContextValue) -> Context { return cv.context } func getValue (_ cv: ContextValue) -> Yaml { return cv.value } func parseDoc (_ tokens: [TokenMatch]) -> Result<Yaml> { let c = lift(Context(tokens)) let cv = c >>=- parseHeader >>=- parse let v = cv >>- getValue return cv >>- getContext >>- ignoreDocEnd >>=- expect(TokenType.End, message: "expected end") >>| v } func parseDocs (_ tokens: [TokenMatch]) -> Result<[Yaml]> { return parseDocs([])(Context(tokens)) } func parseDocs (_ acc: [Yaml]) -> (Context) -> Result<[Yaml]> { return { context in if peekType(context) == .End { return lift(acc) } let cv = lift(context) >>=- parseHeader >>=- parse let v = cv >>- getValue let c = cv >>- getContext >>- ignoreDocEnd let a = appendToArray(acc) <^> v return parseDocs <^> a <*> c |> join } } func peekType (_ context: Context) -> TokenType { return context.tokens[0].type } func peekMatch (_ context: Context) -> String { return context.tokens[0].match } func advance (_ context: Context) -> Context { var tokens = context.tokens tokens.remove(at: 0) return Context(tokens, context.aliases) } func ignoreSpace (_ context: Context) -> Context { if ![.Comment, .Space, .NewLine].contains(peekType(context)) { return context } return ignoreSpace(advance(context)) } func ignoreDocEnd (_ context: Context) -> Context { if ![.Comment, .Space, .NewLine, .DocEnd].contains(peekType(context)) { return context } return ignoreDocEnd(advance(context)) } func expect (_ type: TokenType, message: String) -> (Context) -> Result<Context> { return { context in let check = peekType(context) == type return `guard`(error(message)(context), check: check) >>| lift(advance(context)) } } func expectVersion (_ context: Context) -> Result<Context> { let version = peekMatch(context) let check = ["1.1", "1.2"].contains(version) return `guard`(error("invalid yaml version")(context), check: check) >>| lift(advance(context)) } func error (_ message: String) -> (Context) -> String { return { context in let text = recreateText("", context: context) |> escapeErrorContext return "\(message), \(text)" } } func recreateText (_ string: String, context: Context) -> String { if string.characters.count >= 50 || peekType(context) == .End { return string } return recreateText(string + peekMatch(context), context: advance(context)) } func parseHeader (_ context: Context) -> Result<Context> { return parseHeader(true)(Context(context.tokens, [:])) } func parseHeader (_ yamlAllowed: Bool) -> (Context) -> Result<Context> { return { context in switch peekType(context) { case .Comment, .Space, .NewLine: return lift(context) >>- advance >>=- parseHeader(yamlAllowed) case .YamlDirective: let err = "duplicate yaml directive" return `guard`(error(err)(context), check: yamlAllowed) >>| lift(context) >>- advance >>=- expect(TokenType.Space, message: "expected space") >>=- expectVersion >>=- parseHeader(false) case .DocStart: return lift(advance(context)) default: return `guard`(error("expected ---")(context), check: yamlAllowed) >>| lift(context) } } } func parse (_ context: Context) -> Result<ContextValue> { switch peekType(context) { case .Comment, .Space, .NewLine: return parse(ignoreSpace(context)) case .Null: return lift((advance(context), nil)) case .True: return lift((advance(context), true)) case .False: return lift((advance(context), false)) case .Int: let m = peekMatch(context) // will throw runtime error if overflows let v = Yaml.Int(parseInt(m, radix: 10)) return lift((advance(context), v)) case .IntOct: let m = peekMatch(context) |> replace(regex("0o"), template: "") // will throw runtime error if overflows let v = Yaml.Int(parseInt(m, radix: 8)) return lift((advance(context), v)) case .IntHex: let m = peekMatch(context) |> replace(regex("0x"), template: "") // will throw runtime error if overflows let v = Yaml.Int(parseInt(m, radix: 16)) return lift((advance(context), v)) case .IntSex: let m = peekMatch(context) let v = Yaml.Int(parseInt(m, radix: 60)) return lift((advance(context), v)) case .InfinityP: return lift((advance(context), .Double(Double.infinity))) case .InfinityN: return lift((advance(context), .Double(-Double.infinity))) case .NaN: return lift((advance(context), .Double(Double.nan))) case .Double: let m = NSString(string: peekMatch(context)) return lift((advance(context), .Double(m.doubleValue))) case .Dash: return parseBlockSeq(context) case .OpenSB: return parseFlowSeq(context) case .OpenCB: return parseFlowMap(context) case .QuestionMark: return parseBlockMap(context) case .StringDQ, .StringSQ, .String: return parseBlockMapOrString(context) case .Literal: return parseLiteral(context) case .Folded: let cv = parseLiteral(context) let c = cv >>- getContext let v = cv >>- getValue >>- { value in Yaml.String(foldBlock(value.string ?? "")) } return createContextValue <^> c <*> v case .Indent: let cv = parse(advance(context)) let v = cv >>- getValue let c = cv >>- getContext >>- ignoreSpace >>=- expect(TokenType.Dedent, message: "expected dedent") return createContextValue <^> c <*> v case .Anchor: let m = peekMatch(context) let name = m.substring(from: m.index(after: m.startIndex)) let cv = parse(advance(context)) let v = cv >>- getValue let c = addAlias(name) <^> v <*> (cv >>- getContext) return createContextValue <^> c <*> v case .Alias: let m = peekMatch(context) let name = m.substring(from: m.index(after: m.startIndex)) let value = context.aliases[name] let err = "unknown alias \(name)" return `guard`(error(err)(context), check: value != nil) >>| lift((advance(context), value ?? nil)) case .End, .Dedent: return lift((context, nil)) default: return fail(error("unexpected type \(peekType(context))")(context)) } } func addAlias (_ name: String) -> (Yaml) -> (Context) -> Context { return { value in return { context in var aliases = context.aliases aliases[name] = value return Context(context.tokens, aliases) } } } func appendToArray (_ array: [Yaml]) -> (Yaml) -> [Yaml] { return { value in return array + [value] } } func putToMap (_ map: [Yaml: Yaml]) -> (Yaml) -> (Yaml) -> [Yaml: Yaml] { return { key in return { value in var map = map map[key] = value return map } } } func checkKeyUniqueness (_ acc: [Yaml: Yaml]) -> (_ context: Context, _ key: Yaml) -> Result<ContextValue> { return { (context, key) in let err = "duplicate key \(key)" return `guard`(error(err)(context), check: !acc.keys.contains(key)) >>| lift((context, key)) } } func parseFlowSeq (_ context: Context) -> Result<ContextValue> { return lift(context) >>=- expect(TokenType.OpenSB, message: "expected [") >>=- parseFlowSeq([]) } func parseFlowSeq (_ acc: [Yaml]) -> (Context) -> Result<ContextValue> { return { context in if peekType(context) == .CloseSB { return lift((advance(context), .Array(acc))) } let cv = lift(context) >>- ignoreSpace >>=- (acc.count == 0 ? lift : expect(TokenType.Comma, message: "expected comma")) >>- ignoreSpace >>=- parse let v = cv >>- getValue let c = cv >>- getContext >>- ignoreSpace let a = appendToArray(acc) <^> v return parseFlowSeq <^> a <*> c |> join } } func parseFlowMap (_ context: Context) -> Result<ContextValue> { return lift(context) >>=- expect(TokenType.OpenCB, message: "expected {") >>=- parseFlowMap([:]) } func parseFlowMap (_ acc: [Yaml: Yaml]) -> (Context) -> Result<ContextValue> { return { context in if peekType(context) == .CloseCB { return lift((advance(context), .Dictionary(acc))) } let ck = lift(context) >>- ignoreSpace >>=- (acc.count == 0 ? lift : expect(TokenType.Comma, message: "expected comma")) >>- ignoreSpace >>=- parseString >>=- checkKeyUniqueness(acc) let k = ck >>- getValue let cv = ck >>- getContext >>=- expect(TokenType.Colon, message: "expected colon") >>=- parse let v = cv >>- getValue let c = cv >>- getContext >>- ignoreSpace let a = putToMap(acc) <^> k <*> v return parseFlowMap <^> a <*> c |> join } } func parseBlockSeq (_ context: Context) -> Result<ContextValue> { return parseBlockSeq([])(context) } func parseBlockSeq (_ acc: [Yaml]) -> (Context) -> Result<ContextValue> { return { context in if peekType(context) != .Dash { return lift((context, .Array(acc))) } let cv = lift(context) >>- advance >>=- expect(TokenType.Indent, message: "expected indent after dash") >>- ignoreSpace >>=- parse let v = cv >>- getValue let c = cv >>- getContext >>- ignoreSpace >>=- expect(TokenType.Dedent, message: "expected dedent after dash indent") >>- ignoreSpace let a = appendToArray(acc) <^> v return parseBlockSeq <^> a <*> c |> join } } func parseBlockMap (_ context: Context) -> Result<ContextValue> { return parseBlockMap([:])(context) } func parseBlockMap (_ acc: [Yaml: Yaml]) -> (Context) -> Result<ContextValue> { return { context in switch peekType(context) { case .QuestionMark: return parseQuestionMarkKeyValue(acc)(context) case .String, .StringDQ, .StringSQ: return parseStringKeyValue(acc)(context) default: return lift((context, .Dictionary(acc))) } } } func parseQuestionMarkKeyValue (_ acc: [Yaml: Yaml]) -> (Context) -> Result<ContextValue> { return { context in let ck = lift(context) >>=- expect(TokenType.QuestionMark, message: "expected ?") >>=- parse >>=- checkKeyUniqueness(acc) let k = ck >>- getValue let cv = ck >>- getContext >>- ignoreSpace >>=- parseColonValueOrNil let v = cv >>- getValue let c = cv >>- getContext >>- ignoreSpace let a = putToMap(acc) <^> k <*> v return parseBlockMap <^> a <*> c |> join } } func parseColonValueOrNil (_ context: Context) -> Result<ContextValue> { if peekType(context) != .Colon { return lift((context, nil)) } return parseColonValue(context) } func parseColonValue (_ context: Context) -> Result<ContextValue> { return lift(context) >>=- expect(TokenType.Colon, message: "expected colon") >>- ignoreSpace >>=- parse } func parseStringKeyValue (_ acc: [Yaml: Yaml]) -> (Context) -> Result<ContextValue> { return { context in let ck = lift(context) >>=- parseString >>=- checkKeyUniqueness(acc) let k = ck >>- getValue let cv = ck >>- getContext >>- ignoreSpace >>=- parseColonValue let v = cv >>- getValue let c = cv >>- getContext >>- ignoreSpace let a = putToMap(acc) <^> k <*> v return parseBlockMap <^> a <*> c |> join } } func parseString (_ context: Context) -> Result<ContextValue> { switch peekType(context) { case .String: let m = normalizeBreaks(peekMatch(context)) let folded = m |> replace(regex("^[ \\t\\n]+|[ \\t\\n]+$"), template: "") |> foldFlow return lift((advance(context), .String(folded))) case .StringDQ: let m = unwrapQuotedString(normalizeBreaks(peekMatch(context))) return lift((advance(context), .String(unescapeDoubleQuotes(foldFlow(m))))) case .StringSQ: let m = unwrapQuotedString(normalizeBreaks(peekMatch(context))) return lift((advance(context), .String(unescapeSingleQuotes(foldFlow(m))))) default: return fail(error("expected string")(context)) } } func parseBlockMapOrString (_ context: Context) -> Result<ContextValue> { let match = peekMatch(context) // should spaces before colon be ignored? return context.tokens[1].type != .Colon || matches(match, regex: regex("\n")) ? parseString(context) : parseBlockMap(context) } func foldBlock (_ block: String) -> String { let (body, trail) = block |> splitTrail(regex("\\n*$")) return (body |> replace(regex("^([^ \\t\\n].*)\\n(?=[^ \\t\\n])", options: "m"), template: "$1 ") |> replace( regex("^([^ \\t\\n].*)\\n(\\n+)(?![ \\t])", options: "m"), template: "$1$2") ) + trail } func foldFlow (_ flow: String) -> String { let (lead, rest) = flow |> splitLead(regex("^[ \\t]+")) let (body, trail) = rest |> splitTrail(regex("[ \\t]+$")) let folded = body |> replace(regex("^[ \\t]+|[ \\t]+$|\\\\\\n", options: "m"), template: "") |> replace(regex("(^|.)\\n(?=.|$)"), template: "$1 ") |> replace(regex("(.)\\n(\\n+)"), template: "$1$2") return lead + folded + trail } func parseLiteral (_ context: Context) -> Result<ContextValue> { let literal = peekMatch(context) let blockContext = advance(context) let chomps = ["-": -1, "+": 1] let chomp = chomps[literal |> replace(regex("[^-+]"), template: "")] ?? 0 let indent = parseInt(literal |> replace(regex("[^1-9]"), template: ""), radix: 10) let headerPattern = regex("^(\\||>)([1-9][-+]|[-+]?[1-9]?)( |$)") let error0 = "invalid chomp or indent header" let c = `guard`(error(error0)(context), check: matches(literal, regex: headerPattern!)) >>| lift(blockContext) >>=- expect(TokenType.String, message: "expected scalar block") let block = peekMatch(blockContext) |> normalizeBreaks let (lead, _) = block |> splitLead(regex("^( *\\n)* {1,}(?! |\\n|$)")) let foundIndent = lead |> replace(regex("^( *\\n)*"), template: "") |> count let effectiveIndent = indent > 0 ? indent : foundIndent let invalidPattern = regex("^( {0,\(effectiveIndent)}\\n)* {\(effectiveIndent + 1),}\\n") let check1 = matches(block, regex: invalidPattern!) let check2 = indent > 0 && foundIndent < indent let trimmed = block |> replace(regex("^ {0,\(effectiveIndent)}"), template: "") |> replace(regex("\\n {0,\(effectiveIndent)}"), template: "\n") |> (chomp == -1 ? replace(regex("(\\n *)*$"), template: "") : chomp == 0 ? replace(regex("(?=[^ ])(\\n *)*$"), template: "\n") : { s in s } ) let error1 = "leading all-space line must not have too many spaces" let error2 = "less indented block scalar than the indicated level" return c >>| `guard`(error(error1)(blockContext), check: !check1) >>| `guard`(error(error2)(blockContext), check: !check2) >>| c >>- { context in (context, .String(trimmed))} } func parseInt (_ string: String, radix: Int) -> Int { let (sign, str) = splitLead(regex("^[-+]"))(string) let multiplier = (sign == "-" ? -1 : 1) let ints = radix == 60 ? toSexInts(str) : toInts(str) return multiplier * ints.reduce(0, { acc, i in acc * radix + i }) } func toSexInts (_ string: String) -> [Int] { return string.components(separatedBy: ":").map { c in Int(c) ?? 0 } } func toInts (_ string: String) -> [Int] { return string.unicodeScalars.map { c in switch c { case "0"..."9": return Int(c.value) - Int(("0" as UnicodeScalar).value) case "a"..."z": return Int(c.value) - Int(("a" as UnicodeScalar).value) + 10 case "A"..."Z": return Int(c.value) - Int(("A" as UnicodeScalar).value) + 10 default: fatalError("invalid digit \(c)") } } } func normalizeBreaks (_ s: String) -> String { return replace(regex("\\r\\n|\\r"), template: "\n")(s) } func unwrapQuotedString (_ s: String) -> String { return s[s.index(after: s.startIndex)..<s.index(before: s.endIndex)] } func unescapeSingleQuotes (_ s: String) -> String { return replace(regex("''"), template: "'")(s) } func unescapeDoubleQuotes (_ input: String) -> String { return input |> replace(regex("\\\\([0abtnvfre \"\\/N_LP])")) { escapeCharacters[$0[1]] ?? "" } |> replace(regex("\\\\x([0-9A-Fa-f]{2})")) { String(describing: UnicodeScalar(parseInt($0[1], radix: 16))) } |> replace(regex("\\\\u([0-9A-Fa-f]{4})")) { String(describing: UnicodeScalar(parseInt($0[1], radix: 16))) } |> replace(regex("\\\\U([0-9A-Fa-f]{8})")) { String(describing: UnicodeScalar(parseInt($0[1], radix: 16))) } } let escapeCharacters = [ "0": "\0", "a": "\u{7}", "b": "\u{8}", "t": "\t", "n": "\n", "v": "\u{B}", "f": "\u{C}", "r": "\r", "e": "\u{1B}", " ": " ", "\"": "\"", "\\": "\\", "/": "/", "N": "\u{85}", "_": "\u{A0}", "L": "\u{2028}", "P": "\u{2029}" ]
mit
3580af53154f9fa05704c454147f9f1e
27.900826
91
0.592222
3.748928
false
false
false
false
csujedihy/Twitter
twitter-ios/InfiniteScrollActivityView.swift
1
1209
// // InfiniteScrollActivityView.swift // twitter-ios // // Created by YiHuang on 2/21/16. // Copyright © 2016 c2fun. All rights reserved. // import UIKit class InfiniteScrollActivityView: UIView { var activityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView() static let defaultHeight:CGFloat = 60.0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupActivityIndicator() } override init(frame aRect: CGRect) { super.init(frame: aRect) setupActivityIndicator() } override func layoutSubviews() { super.layoutSubviews() activityIndicatorView.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2) } func setupActivityIndicator() { activityIndicatorView.activityIndicatorViewStyle = .Gray activityIndicatorView.hidesWhenStopped = true self.addSubview(activityIndicatorView) } func stopAnimating() { self.activityIndicatorView.stopAnimating() self.hidden = true } func startAnimating() { self.hidden = false self.activityIndicatorView.startAnimating() } }
gpl-3.0
6a6ca7f43b8c3a8493e7cb3d6495be9c
25.844444
103
0.672185
5.162393
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/Component/SafeArea/CollectionViewController.swift
1
6848
// // CollectionViewController.swift // SafeAreaExample // // Created by Evgeny Mikhaylov on 11/10/2017. // Copyright © 2017 Rosberry. All rights reserved. // import UIKit class CollectionViewController: SafeAreaViewController { lazy var collectionView: UICollectionView = { let collectionViewLayout = UICollectionViewFlowLayout() collectionViewLayout.scrollDirection = .vertical let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout) collectionView.backgroundColor = UIColor.orange.withAlphaComponent(0.5) collectionView.delegate = self collectionView.dataSource = self collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: String(describing: CollectionViewCell.self)) collectionView.register(CollectionViewReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: String(describing: CollectionViewReusableView.self)) return collectionView }() lazy var collectionViewSectionItems: [CollectionViewSectionItem] = { return CollectionViewSectionItemsFactory.sectionItems(for: collectionView) }() init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .grayBackgroundColor view.addSubview(collectionView) } // MARK: - Layout override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } } // MARK: - UICollectionViewDelegate extension CollectionViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: false) let sectionItem = collectionViewSectionItems[indexPath.section] sectionItem.cellItems.enumerated().forEach { (offset, cellItem) in if offset == indexPath.row { cellItem.enabled = true cellItem.selectionHandler?() } else { cellItem.enabled = false } } collectionView.reloadData() } } // MARK: - UICollectionViewDataSource extension CollectionViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return collectionViewSectionItems.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let sectionItem = collectionViewSectionItems[section] return sectionItem.cellItems.count } func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) { view.backgroundColor = UIColor.red.withAlphaComponent(0.7) } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { cell.backgroundColor = .clear cell.contentView.backgroundColor = .white } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let sectionItem = collectionViewSectionItems[indexPath.section] let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: String(describing: CollectionViewReusableView.self), for: indexPath) as! CollectionViewReusableView view.label.text = sectionItem.title view.switcher.isOn = sectionItem.attachContentToSafeArea view.delegate = sectionItem view.setNeedsLayout() view.layoutIfNeeded() return view } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let sectionItem = collectionViewSectionItems[indexPath.section] let cellItem = sectionItem.cellItems[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CollectionViewCell.self), for: indexPath) as! CollectionViewCell cell.label.text = cellItem.title cell.enabledLabel.isHidden = !cellItem.enabled return cell } } // MARK: - UICollectionViewDelegateFlowLayout extension CollectionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cellItem = collectionViewSectionItems[indexPath.section].cellItems[indexPath.item] return cellItem.size } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { let sectionItem = collectionViewSectionItems[section] return sectionItem.insets } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { let sectionItem = collectionViewSectionItems[section] return sectionItem.minimumLineSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { let sectionItem = collectionViewSectionItems[section] return sectionItem.minimumInteritemSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { let sectionItem = collectionViewSectionItems[section] return sectionItem.referenceHeaderSize } }
mit
630d65799d6c8878f2b12e404c7bb8cf
40.246988
140
0.661896
6.951269
false
false
false
false
googlemaps/google-maps-ios-utils
samples/SwiftDemoApp/SwiftDemoApp/ClusteringViewController.swift
1
3244
/* Copyright (c) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import GoogleMaps import UIKit import GoogleMapsUtils /// Point of Interest Item which implements the GMUClusterItem protocol. class POIItem: NSObject, GMUClusterItem { var position: CLLocationCoordinate2D var name: String! init(position: CLLocationCoordinate2D, name: String) { self.position = position self.name = name } } let kClusterItemCount = 10000 let kCameraLatitude = -33.8 let kCameraLongitude = 151.2 class ClusteringViewController: UIViewController, GMSMapViewDelegate { private var mapView: GMSMapView! private var clusterManager: GMUClusterManager! override func loadView() { let camera = GMSCameraPosition.camera(withLatitude: kCameraLatitude, longitude: kCameraLongitude, zoom: 10) mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) self.view = mapView } override func viewDidLoad() { super.viewDidLoad() // Set up the cluster manager with default icon generator and renderer. let iconGenerator = GMUDefaultClusterIconGenerator() let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm() let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator) clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer) // Register self to listen to GMSMapViewDelegate events. clusterManager.setMapDelegate(self) // Generate and add random items to the cluster manager. generateClusterItems() // Call cluster() after items have been added to perform the clustering and rendering on map. clusterManager.cluster() } // MARK: - GMUMapViewDelegate func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { mapView.animate(toLocation: marker.position) if let _ = marker.userData as? GMUCluster { mapView.animate(toZoom: mapView.camera.zoom + 1) NSLog("Did tap cluster") return true } NSLog("Did tap marker") return false } // MARK: - Private /// Randomly generates cluster items within some extent of the camera and adds them to the /// cluster manager. private func generateClusterItems() { let extent = 0.2 for _ in 1...kClusterItemCount { let lat = kCameraLatitude + extent * randomScale() let lng = kCameraLongitude + extent * randomScale() let position = CLLocationCoordinate2D(latitude: lat, longitude: lng) let marker = GMSMarker(position: position) clusterManager.add(marker) } } /// Returns a random value between -1.0 and 1.0. private func randomScale() -> Double { return Double(arc4random()) / Double(UINT32_MAX) * 2.0 - 1.0 } }
apache-2.0
c576b1cec3a13924ebe025d40e155523
32.102041
99
0.72688
4.437756
false
false
false
false
cristianodp/Aulas-IOS
Aula3/Calculadora/Calculadora/ViewController.swift
1
2241
// // ViewController.swift // Calculadora // // Created by Cristiano Diniz Pinto on 28/05/17. // Copyright © 2017 Cristiano Diniz Pinto. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var displayLabel: UILabel! var operador = "" var numero = "0.00" 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. } @IBAction func buttonClick(_ sender: UIButton) { let value = sender.titleLabel!.text! if value.isOperator(){ if value == "=" { calcular() }else{ numero = displayLabel.text! operador = value displayLabel.text = "0.00" } }else{ if Float(displayLabel.text!)! == 0.0 { displayLabel.text = value }else{ displayLabel.text = displayLabel.text! + value } } } func calcular(){ var calc:Float = 0.0 if operador == "+"{ calc = Float(numero)! + Float(displayLabel.text!)! } if operador == "-"{ calc = Float(numero)! - Float(displayLabel.text!)! } if operador == "/"{ calc = Float(numero)! / Float(displayLabel.text!)! } if operador == "X"{ calc = Float(numero)! * Float(displayLabel.text!)! } numero = calc.description displayLabel.text = calc.description } @IBAction func limpar(_ sender: Any) { operador = "" numero = "0.00" displayLabel.text = "0.00" } }
apache-2.0
860ae98a3686b590b201d4a93466cd44
18.649123
80
0.440625
5.530864
false
false
false
false
huonw/swift
stdlib/public/core/SequenceAlgorithms.swift
1
31282
//===--- SequenceAlgorithms.swift -----------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // enumerated() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a sequence of pairs (*n*, *x*), where *n* represents a /// consecutive integer starting at zero and *x* represents an element of /// the sequence. /// /// This example enumerates the characters of the string "Swift" and prints /// each character along with its place in the string. /// /// for (n, c) in "Swift".enumerated() { /// print("\(n): '\(c)'") /// } /// // Prints "0: 'S'" /// // Prints "1: 'w'" /// // Prints "2: 'i'" /// // Prints "3: 'f'" /// // Prints "4: 't'" /// /// When you enumerate a collection, the integer part of each pair is a counter /// for the enumeration, but is not necessarily the index of the paired value. /// These counters can be used as indices only in instances of zero-based, /// integer-indexed collections, such as `Array` and `ContiguousArray`. For /// other collections the counters may be out of range or of the wrong type /// to use as an index. To iterate over the elements of a collection with its /// indices, use the `zip(_:_:)` function. /// /// This example iterates over the indices and elements of a set, building a /// list consisting of indices of names with five or fewer letters. /// /// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] /// var shorterIndices: [SetIndex<String>] = [] /// for (i, name) in zip(names.indices, names) { /// if name.count <= 5 { /// shorterIndices.append(i) /// } /// } /// /// Now that the `shorterIndices` array holds the indices of the shorter /// names in the `names` set, you can use those indices to access elements in /// the set. /// /// for i in shorterIndices { /// print(names[i]) /// } /// // Prints "Sofia" /// // Prints "Mateo" /// /// - Returns: A sequence of pairs enumerating the sequence. @inlinable public func enumerated() -> EnumeratedSequence<Self> { return EnumeratedSequence(_base: self) } } //===----------------------------------------------------------------------===// // min(), max() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the minimum element in the sequence, using the given predicate as /// the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `min(by:)` method on a /// dictionary to find the key-value pair with the lowest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let leastHue = hues.min { a, b in a.value < b.value } /// print(leastHue) /// // Prints "Optional(("Coral", 16))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` /// if its first argument should be ordered before its second /// argument; otherwise, `false`. /// - Returns: The sequence's minimum element, according to /// `areInIncreasingOrder`. If the sequence has no elements, returns /// `nil`. @inlinable @warn_unqualified_access public func min( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(e, result) { result = e } } return result } /// Returns the maximum element in the sequence, using the given predicate /// as the comparison between elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// This example shows how to use the `max(by:)` method on a /// dictionary to find the key-value pair with the highest value. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// let greatestHue = hues.max { a, b in a.value < b.value } /// print(greatestHue) /// // Prints "Optional(("Heliotrope", 296))" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; /// otherwise, `false`. /// - Returns: The sequence's maximum element if the sequence is not empty; /// otherwise, `nil`. @inlinable @warn_unqualified_access public func max( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Element? { var it = makeIterator() guard var result = it.next() else { return nil } while let e = it.next() { if try areInIncreasingOrder(result, e) { result = e } } return result } } extension Sequence where Element: Comparable { /// Returns the minimum element in the sequence. /// /// This example finds the smallest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let lowestHeight = heights.min() /// print(lowestHeight) /// // Prints "Optional(58.5)" /// /// - Returns: The sequence's minimum element. If the sequence has no /// elements, returns `nil`. @inlinable @warn_unqualified_access public func min() -> Element? { return self.min(by: <) } /// Returns the maximum element in the sequence. /// /// This example finds the largest value in an array of height measurements. /// /// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] /// let greatestHeight = heights.max() /// print(greatestHeight) /// // Prints "Optional(67.5)" /// /// - Returns: The sequence's maximum element. If the sequence has no /// elements, returns `nil`. @inlinable @warn_unqualified_access public func max() -> Element? { return self.max(by: <) } } //===----------------------------------------------------------------------===// // starts(with:) //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are equivalent to the elements in another sequence, using /// the given predicate as the equivalence test. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - possiblePrefix: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if the initial elements of the sequence are equivalent /// to the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix, by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool ) rethrows -> Bool { var possiblePrefixIterator = possiblePrefix.makeIterator() for e0 in self { if let e1 = possiblePrefixIterator.next() { if try !areEquivalent(e0, e1) { return false } } else { return true } } return possiblePrefixIterator.next() == nil } } extension Sequence where Element: Equatable { /// Returns a Boolean value indicating whether the initial elements of the /// sequence are the same as the elements in another sequence. /// /// This example tests whether one countable range begins with the elements /// of another countable range. /// /// let a = 1...3 /// let b = 1...10 /// /// print(b.starts(with: a)) /// // Prints "true" /// /// Passing a sequence with no elements or an empty collection as /// `possiblePrefix` always results in `true`. /// /// print(b.starts(with: [])) /// // Prints "true" /// /// - Parameter possiblePrefix: A sequence to compare to this sequence. /// - Returns: `true` if the initial elements of the sequence are the same as /// the elements of `possiblePrefix`; otherwise, `false`. If /// `possiblePrefix` has no elements, the return value is `true`. @inlinable public func starts<PossiblePrefix: Sequence>( with possiblePrefix: PossiblePrefix ) -> Bool where PossiblePrefix.Element == Element { return self.starts(with: possiblePrefix, by: ==) } } //===----------------------------------------------------------------------===// // elementsEqual() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain equivalent elements in the same order, using the given /// predicate as the equivalence test. /// /// At least one of the sequences must be finite. /// /// The predicate must be a *equivalence relation* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areEquivalent(a, a)` is always `true`. (Reflexivity) /// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry) /// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then /// `areEquivalent(a, c)` is also `true`. (Transitivity) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areEquivalent: A predicate that returns `true` if its two arguments /// are equivalent; otherwise, `false`. /// - Returns: `true` if this sequence and `other` contain equivalent items, /// using `areEquivalent` as the equivalence test; otherwise, `false.` @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence, by areEquivalent: (Element, OtherSequence.Element) throws -> Bool ) rethrows -> Bool { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { switch (iter1.next(), iter2.next()) { case let (e1?, e2?): if try !areEquivalent(e1, e2) { return false } case (_?, nil), (nil, _?): return false case (nil, nil): return true } } } } extension Sequence where Element : Equatable { /// Returns a Boolean value indicating whether this sequence and another /// sequence contain the same elements in the same order. /// /// At least one of the sequences must be finite. /// /// This example tests whether one countable range shares the same elements /// as another countable range and an array. /// /// let a = 1...3 /// let b = 1...10 /// /// print(a.elementsEqual(b)) /// // Prints "false" /// print(a.elementsEqual([1, 2, 3])) /// // Prints "true" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence and `other` contain the same elements /// in the same order. @inlinable public func elementsEqual<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.elementsEqual(other, by: ==) } } //===----------------------------------------------------------------------===// // lexicographicallyPrecedes() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the given /// predicate to compare elements. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// - Parameters: /// - other: A sequence to compare to this sequence. /// - areInIncreasingOrder: A predicate that returns `true` if its first /// argument should be ordered before its second argument; otherwise, /// `false`. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that perform /// localized comparison instead. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Bool where OtherSequence.Element == Element { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { if let e1 = iter1.next() { if let e2 = iter2.next() { if try areInIncreasingOrder(e1, e2) { return true } if try areInIncreasingOrder(e2, e1) { return false } continue // Equivalent } return false } return iter2.next() != nil } } } extension Sequence where Element : Comparable { /// Returns a Boolean value indicating whether the sequence precedes another /// sequence in a lexicographical (dictionary) ordering, using the /// less-than operator (`<`) to compare elements. /// /// This example uses the `lexicographicallyPrecedes` method to test which /// array of integers comes first in a lexicographical ordering. /// /// let a = [1, 2, 2, 2] /// let b = [1, 2, 3, 4] /// /// print(a.lexicographicallyPrecedes(b)) /// // Prints "true" /// print(b.lexicographicallyPrecedes(b)) /// // Prints "false" /// /// - Parameter other: A sequence to compare to this sequence. /// - Returns: `true` if this sequence precedes `other` in a dictionary /// ordering; otherwise, `false`. /// /// - Note: This method implements the mathematical notion of lexicographical /// ordering, which has no connection to Unicode. If you are sorting /// strings to present to the end user, use `String` APIs that /// perform localized comparison. @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.lexicographicallyPrecedes(other, by: <) } } //===----------------------------------------------------------------------===// // contains() //===----------------------------------------------------------------------===// extension Sequence { /// Returns a Boolean value indicating whether the sequence contains an /// element that satisfies the given predicate. /// /// You can use the predicate to check for an element of a type that /// doesn't conform to the `Equatable` protocol, such as the /// `HTTPResponse` enumeration in this example. /// /// enum HTTPResponse { /// case ok /// case error(Int) /// } /// /// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)] /// let hadError = lastThreeResponses.contains { element in /// if case .error = element { /// return true /// } else { /// return false /// } /// } /// // 'hadError' == true /// /// Alternatively, a predicate can be satisfied by a range of `Equatable` /// elements or a general condition. This example shows how you can check an /// array for an expense greater than $100. /// /// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41] /// let hasBigPurchase = expenses.contains { $0 > 100 } /// // 'hasBigPurchase' == true /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element represents a match. /// - Returns: `true` if the sequence contains an element that satisfies /// `predicate`; otherwise, `false`. @inlinable public func contains( where predicate: (Element) throws -> Bool ) rethrows -> Bool { for e in self { if try predicate(e) { return true } } return false } /// Returns a Boolean value indicating whether every element of a sequence /// satisfies a given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence /// as its argument and returns a Boolean value that indicates whether /// the passed element satisfies a condition. /// - Returns: `true` if the sequence contains only elements that satisfy /// `predicate`; otherwise, `false`. @inlinable public func allSatisfy( _ predicate: (Element) throws -> Bool ) rethrows -> Bool { return try !contains { try !predicate($0) } } } extension Sequence where Element : Equatable { /// Returns a Boolean value indicating whether the sequence contains the /// given element. /// /// This example checks to see whether a favorite actor is in an array /// storing a movie's cast. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// print(cast.contains("Marlon")) /// // Prints "true" /// print(cast.contains("James")) /// // Prints "false" /// /// - Parameter element: The element to find in the sequence. /// - Returns: `true` if the element was found in the sequence; otherwise, /// `false`. @inlinable public func contains(_ element: Element) -> Bool { if let result = _customContainsEquatableElement(element) { return result } else { return self.contains { $0 == element } } } } //===----------------------------------------------------------------------===// // reduce() //===----------------------------------------------------------------------===// extension Sequence { /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(_:_:)` method to produce a single value from the elements /// of an entire sequence. For example, you can use this method on an array /// of numbers to find their sum or product. /// /// The `nextPartialResult` closure is called sequentially with an /// accumulating value initialized to `initialResult` and each element of /// the sequence. This example shows how to find the sum of an array of /// numbers. /// /// let numbers = [1, 2, 3, 4] /// let numberSum = numbers.reduce(0, { x, y in /// x + y /// }) /// // numberSum == 10 /// /// When `numbers.reduce(_:_:)` is called, the following steps occur: /// /// 1. The `nextPartialResult` closure is called with `initialResult`---`0` /// in this case---and the first element of `numbers`, returning the sum: /// `1`. /// 2. The closure is called again repeatedly with the previous call's return /// value and each element of the sequence. /// 3. When the sequence is exhausted, the last value returned from the /// closure is returned to the caller. /// /// If the sequence has no elements, `nextPartialResult` is never executed /// and `initialResult` is the result of the call to `reduce(_:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// `initialResult` is passed to `nextPartialResult` the first time the /// closure is executed. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the sequence into a new accumulating value, to be used /// in the next call of the `nextPartialResult` closure or returned to /// the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. @inlinable public func reduce<Result>( _ initialResult: Result, _ nextPartialResult: (_ partialResult: Result, Element) throws -> Result ) rethrows -> Result { var accumulator = initialResult for element in self { accumulator = try nextPartialResult(accumulator, element) } return accumulator } /// Returns the result of combining the elements of the sequence using the /// given closure. /// /// Use the `reduce(into:_:)` method to produce a single value from the /// elements of an entire sequence. For example, you can use this method on an /// array of integers to filter adjacent equal entries or count frequencies. /// /// This method is preferred over `reduce(_:_:)` for efficiency when the /// result is a copy-on-write type, for example an Array or a Dictionary. /// /// The `updateAccumulatingResult` closure is called sequentially with a /// mutable accumulating value initialized to `initialResult` and each element /// of the sequence. This example shows how to build a dictionary of letter /// frequencies of a string. /// /// let letters = "abracadabra" /// let letterCount = letters.reduce(into: [:]) { counts, letter in /// counts[letter, default: 0] += 1 /// } /// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1] /// /// When `letters.reduce(into:_:)` is called, the following steps occur: /// /// 1. The `updateAccumulatingResult` closure is called with the initial /// accumulating value---`[:]` in this case---and the first character of /// `letters`, modifying the accumulating value by setting `1` for the key /// `"a"`. /// 2. The closure is called again repeatedly with the updated accumulating /// value and each element of the sequence. /// 3. When the sequence is exhausted, the accumulating value is returned to /// the caller. /// /// If the sequence has no elements, `updateAccumulatingResult` is never /// executed and `initialResult` is the result of the call to /// `reduce(into:_:)`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// - updateAccumulatingResult: A closure that updates the accumulating /// value with an element of the sequence. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. @inlinable public func reduce<Result>( into initialResult: Result, _ updateAccumulatingResult: (_ partialResult: inout Result, Element) throws -> () ) rethrows -> Result { var accumulator = initialResult for element in self { try updateAccumulatingResult(&accumulator, element) } return accumulator } } //===----------------------------------------------------------------------===// // reversed() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the elements of this sequence in reverse /// order. /// /// The sequence must be finite. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. /// /// - Returns: An array containing the elements of this sequence in /// reverse order. @inlinable public func reversed() -> [Element] { // FIXME(performance): optimize to 1 pass? But Array(self) can be // optimized to a memcpy() sometimes. Those cases are usually collections, // though. var result = Array(self) let count = result.count for i in 0..<count/2 { result.swapAt(i, count - ((i + 1) as Int)) } return result } } //===----------------------------------------------------------------------===// // flatMap() //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the concatenated results of calling the /// given transformation with each element of this sequence. /// /// Use this method to receive a single-level collection when your /// transformation produces a sequence or collection for each element. /// /// In this example, note the difference in the result of using `map` and /// `flatMap` with a transformation that returns an array. /// /// let numbers = [1, 2, 3, 4] /// /// let mapped = numbers.map { Array(repeating: $0, count: $0) } /// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]] /// /// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) } /// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] /// /// In fact, `s.flatMap(transform)` is equivalent to /// `Array(s.map(transform).joined())`. /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns a sequence or collection. /// - Returns: The resulting flattened array. /// /// - Complexity: O(*m* + *n*), where *m* is the length of this sequence /// and *n* is the length of the result. @inlinable public func flatMap<SegmentOfResult : Sequence>( _ transform: (Element) throws -> SegmentOfResult ) rethrows -> [SegmentOfResult.Element] { var result: [SegmentOfResult.Element] = [] for element in self { result.append(contentsOf: try transform(element)) } return result } } extension Sequence { /// Returns an array containing the non-`nil` results of calling the given /// transformation with each element of this sequence. /// /// Use this method to receive an array of nonoptional values when your /// transformation produces an optional value. /// /// In this example, note the difference in the result of using `map` and /// `compactMap` with a transformation that returns an optional `Int` value. /// /// let possibleNumbers = ["1", "2", "three", "///4///", "5"] /// /// let mapped: [Int?] = possibleNumbers.map { str in Int(str) } /// // [1, 2, nil, nil, 5] /// /// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) } /// // [1, 2, 5] /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns an optional value. /// - Returns: An array of the non-`nil` results of calling `transform` /// with each element of the sequence. /// /// - Complexity: O(*m* + *n*), where *m* is the length of this sequence /// and *n* is the length of the result. @inlinable public func compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { return try _compactMap(transform) } /// Returns an array containing the non-`nil` results of calling the given /// transformation with each element of this sequence. /// /// Use this method to receive an array of nonoptional values when your /// transformation produces an optional value. /// /// In this example, note the difference in the result of using `map` and /// `flatMap` with a transformation that returns an optional `Int` value. /// /// let possibleNumbers = ["1", "2", "three", "///4///", "5"] /// /// let mapped: [Int?] = possibleNumbers.map { str in Int(str) } /// // [1, 2, nil, nil, 5] /// /// let flatMapped: [Int] = possibleNumbers.flatMap { str in Int(str) } /// // [1, 2, 5] /// /// - Parameter transform: A closure that accepts an element of this /// sequence as its argument and returns an optional value. /// - Returns: An array of the non-`nil` results of calling `transform` /// with each element of the sequence. /// /// - Complexity: O(*m* + *n*), where *m* is the length of this sequence /// and *n* is the length of the result. @inline(__always) @available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value") public func flatMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { return try _compactMap(transform) } // The implementation of flatMap accepting a closure with an optional result. // Factored out into a separate functions in order to be used in multiple // overloads. @inlinable // FIXME(sil-serialize-all) @inline(__always) public func _compactMap<ElementOfResult>( _ transform: (Element) throws -> ElementOfResult? ) rethrows -> [ElementOfResult] { var result: [ElementOfResult] = [] for element in self { if let newElement = try transform(element) { result.append(newElement) } } return result } }
apache-2.0
7e714345bd63dd135a7c9b6c48c174fc
38.052434
94
0.605447
4.393399
false
false
false
false
eure/ReceptionApp
iOS/Pods/RxCocoa/RxCocoa/Common/Observables/Implementations/ControlTarget.swift
32
2174
// // ControlTarget.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) || os(OSX) import Foundation #if !RX_NO_MODULE import RxSwift #endif #if os(iOS) || os(tvOS) import UIKit typealias Control = UIKit.UIControl typealias ControlEvents = UIKit.UIControlEvents #elseif os(OSX) import Cocoa typealias Control = Cocoa.NSControl #endif // This should be only used from `MainScheduler` class ControlTarget: RxTarget { typealias Callback = (Control) -> Void let selector: Selector = "eventHandler:" weak var control: Control? #if os(iOS) || os(tvOS) let controlEvents: UIControlEvents #endif var callback: Callback? #if os(iOS) || os(tvOS) init(control: Control, controlEvents: UIControlEvents, callback: Callback) { MainScheduler.ensureExecutingOnScheduler() self.control = control self.controlEvents = controlEvents self.callback = callback super.init() control.addTarget(self, action: selector, forControlEvents: controlEvents) let method = self.methodForSelector(selector) if method == nil { rxFatalError("Can't find method") } } #elseif os(OSX) init(control: Control, callback: Callback) { MainScheduler.ensureExecutingOnScheduler() self.control = control self.callback = callback super.init() control.target = self control.action = selector let method = self.methodForSelector(selector) if method == nil { rxFatalError("Can't find method") } } #endif func eventHandler(sender: Control!) { if let callback = self.callback, control = self.control { callback(control) } } override func dispose() { super.dispose() #if os(iOS) || os(tvOS) self.control?.removeTarget(self, action: self.selector, forControlEvents: self.controlEvents) #elseif os(OSX) self.control?.target = nil self.control?.action = nil #endif self.callback = nil } } #endif
mit
c278e69de27470a646c1fe3ea1b4236a
22.619565
101
0.639669
4.328685
false
false
false
false
ChrisAU/Locution
Papyrus/Views/GameView.swift
2
3231
// // GameView.swift // Papyrus // // Created by Chris Nevin on 22/02/2016. // Copyright © 2016 CJNevin. All rights reserved. // import UIKit import PapyrusCore typealias Square = (x: Int, y: Int, rect: CGRect) typealias Intersection = (x: Int, y: Int, rect: CGRect, intersection: CGRect) class GameView: UIView { var tileViewDelegate: TileViewDelegate! @IBOutlet weak var blackoutView: UIView! var blanks: Positions { return tileViews?.flatMap({ $0.isPlaced && $0.isBlank ? Position(x: $0.x!, y: $0.y!) : nil }) ?? [] } var placedTiles: LetterPositions { return tileViews?.flatMap({ $0.isPlaced ? LetterPosition(x: $0.x!, y: $0.y!, letter: $0.tile) : nil }) ?? [] } var boardDrawable: BoardDrawable? { didSet { setNeedsDisplay() } } var scoresDrawable: ScoresDrawable? { didSet { setNeedsDisplay() } } var rackedTiles: [RackedTile]? { didSet { func tileView(for tile: RackedTile) -> TileView { let view = TileView(frame: tile.rect, tile: tile.tile, points: tile.points, onBoard: false, delegate: tile.movable ? tileViewDelegate : nil) view.draggable = tile.movable return view } tileViews = rackedTiles?.map(tileView) } } var tileViews: [TileView]? { willSet { tileViews?.forEach { $0.removeFromSuperview() } } didSet { tileViews?.forEach { insertSubview($0, belowSubview: blackoutView) } } } override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } context.saveGState() boardDrawable?.draw(renderer: context) scoresDrawable?.draw(renderer: context) let blackColor = UIColor.black.cgColor context.setStrokeColor(blackColor) context.setLineWidth(0.5) context.strokePath() context.restoreGState() } private var emptySquares: [Square] { guard let board = boardDrawable?.board, let boardRect = boardDrawable?.rect else { return [] } let squareSize = boardRect.width / CGFloat(board.size) func rect(for position: Position) -> CGRect { return CGRect(x: boardRect.origin.x + CGFloat(position.x) * squareSize, y: boardRect.origin.y + CGFloat(position.y) * squareSize, width: squareSize, height: squareSize) } let placed = placedTiles.map({ $0.position }) return board.emptyPositions.filter({ !placed.contains($0) }).flatMap({ ($0.x, $0.y, rect(for: $0)) }) } func bestIntersection(forRect rect: CGRect) -> Intersection? { return emptySquares.flatMap({ (x, y, squareRect) -> Intersection? in let intersection = squareRect.intersection(rect) return intersection.widthPlusHeight > 0 ? (x, y, squareRect, intersection) : nil }).sorted(by: { (lhs, rhs) in return lhs.intersection.widthPlusHeight < rhs.intersection.widthPlusHeight }).last } }
mit
f60615ac8407545d2d6fc0c3c1816d29
33.361702
156
0.585449
4.295213
false
false
false
false
soapyigu/Swift30Projects
Project 07 - PokedexGo/PokedexGo/AppDelegate.swift
1
2870
// // AppDelegate.swift // PokedexGo // // Created by Yi Gu on 7/10/16. // Copyright © 2016 yigu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let splitViewController = self.window!.rootViewController as! UISplitViewController let leftNavController = splitViewController.viewControllers.first as! UINavigationController let masterViewController = leftNavController.topViewController as! MasterViewController let rightNavController = splitViewController.viewControllers.last as! UINavigationController let detailViewController = rightNavController.topViewController as! DetailViewController let firstPokemon = masterViewController.pokemons.first detailViewController.pokemon = firstPokemon masterViewController.delegate = detailViewController detailViewController.navigationItem.leftItemsSupplementBackButton = true detailViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
0ec83eb89476cb547e04b5062fa78b48
46.032787
281
0.787034
6.002092
false
false
false
false
rabbitinspace/Tosoka
Tests/TosokaTests/JSON/Jay/Jay.swift
2
6976
// // Jay.swift // Jay // // Created by Honza Dvorsky on 2/17/16. // Copyright © 2016 Honza Dvorsky. All rights reserved. // //Implemented from scratch based on http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf and https://www.ietf.org/rfc/rfc4627.txt public struct Jay { /// The formatting to apply to the `JSON`. public enum Formatting { case minified case prettified } public struct ParsingOptions: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let none = ParsingOptions(rawValue: 0) /// Allows single line (starting //) or multi-line (/* ... */) comments, /// strips them out during parsing. public static let allowComments = ParsingOptions(rawValue: 1 << 0) } /// The formatting used. public let formatting: Formatting /// Parsing options public let parsing: ParsingOptions /// Initializes and returns the `Jay` object. /// - Parameter formatting: The `Formatting` to use. Defaults to `.minified`. /// - Parameter parsing: The `ParsingOptions` to use. Defaults to `.none`. public init(formatting: Formatting = .minified, parsing: ParsingOptions = .none) { self.formatting = formatting self.parsing = parsing } /// Parses data into a dictionary `[String: Any]` or array `[Any]`. /// - Note: Does not allow fragments. Test by conditional /// casting whether you received what you expected. /// - Throws: A descriptive error in case of any problem. public func anyJsonFromData(_ data: [UInt8]) throws -> Any { return try NativeParser(options: parsing).parse(data) } /// Parses the reader to `Any`. /// - Throws: A descriptive error in case of any problem. public func anyJsonFromReader<R: Reader>(_ reader: R) throws -> Any { return try NativeParser(options: parsing).parse(reader) } /// Formats your JSON-compatible object into data. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(jsonWrapper: JaySON) throws -> [UInt8] { return try self.dataFromAnyJson(jsonWrapper.json) } /// Outputs the data from json to the provided stream. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(jsonWrapper: JaySON, output: JsonOutputStream) throws { try self.dataFromAnyJson(jsonWrapper.json, output: output) } /// Parses the json to data. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(anyDictionary: [String: Any]) throws -> [UInt8] { return try self.dataFromAnyJson(anyDictionary) } /// Outputs the data from json to the provided stream. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(anyDictionary: [String: Any], output: JsonOutputStream) throws { try self.dataFromAnyJson(anyDictionary, output: output) } /// Parses the json to data. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(anyArray: [Any]) throws -> [UInt8] { return try self.dataFromAnyJson(anyArray) } /// Outputs the data from json to the provided stream. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(anyArray: [Any], output: JsonOutputStream) throws { try self.dataFromAnyJson(anyArray, output: output) } /// Parses the json to data. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(any: Any) throws -> [UInt8] { return try self.dataFromAnyJson(any) } /// Outputs the data from json to the provided stream. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(any: Any, output: JsonOutputStream) throws { try self.dataFromAnyJson(any, output: output) } private func dataFromAnyJson(_ json: Any) throws -> [UInt8] { let output = ByteArrayOutputStream() try dataFromAnyJson(json, output: output) return output.bytes } func dataFromAnyJson(_ json: Any, output: JsonOutputStream) throws { let jayType = try NativeTypeConverter().toJayType(json) try jayType.format(to: output, with: formatting.formatter()) } } struct Formatter { let indentStep: Int var indentation: Int = 0 func nextLevel() -> Formatter { return Formatter(indentStep: indentStep, indentation: indentation + indentStep) } func clean() -> Formatter { return Formatter(indentStep: indentStep, indentation: 0) } func indent() -> [JChar] { return Array(repeating: Const.Space, count: indentation) } func newline() -> [JChar] { return indentStep > 0 ? [Const.NewLine] : [] } func newlineAndIndent() -> [JChar] { return newline() + indent() } func separator() -> [JChar] { return indentStep > 0 ? [Const.Space] : [] } } extension Jay.Formatting { func formatter() -> Formatter { switch self { case .minified: return Formatter(indentStep: 0, indentation: 0) case .prettified: return Formatter(indentStep: 4, indentation: 0) } } } //Typesafe extension Jay { /// Allows users to get the `JSON` representation in a typesafe matter. /// However, these types are wrapped, so the user is responsible for /// manually unwrapping each value recursively. /// - SeeAlso: If you just want Swift types with less /// type-information, use `jsonFromData()` above. public func jsonFromData(_ data: [UInt8]) throws -> JSON { return try Parser(parsing: parsing).parseJsonFromData(data) } /// Allows users to get the `JSON` representation in a typesafe matter. /// However, these types are wrapped, so the user is responsible for /// manually unwrapping each value recursively. /// - SeeAlso: If you just want Swift types with less /// type-information, use `jsonFromReader()` above. public func jsonFromReader<R: Reader>(_ reader: R) throws -> JSON { return try Parser(parsing: parsing).parseJsonFromReader(reader) } /// Formats your JSON-compatible object into data. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(json: JSON) throws -> [UInt8] { let output = ByteArrayOutputStream() try dataFromJson(json: json, output: output) return output.bytes } /// Outputs your JSON-compatible object as data to the provided stream. /// - Throws: A descriptive error in case of any problem. public func dataFromJson(json: JSON, output: JsonOutputStream) throws { try json.format(to: output, with: formatting.formatter()) } }
mit
0ed840f62114e9badfd0f3268d73cc06
34.586735
150
0.649462
4.46829
false
false
false
false
kstaring/swift
test/Parse/object_literals.swift
3
527
// RUN: %target-parse-verify-swift let _ = [##] // expected-error{{expected identifier after '#' in object literal expression}} expected-error{{object literal syntax no longer uses '[# ... #]'}} {{9-10=}} {{11-13=}} let _ = [#what#] // expected-error{{object literal syntax no longer uses '[# ... #]'}} {{9-10=}} {{15-17=}} let _ = [#what()#] // expected-error{{object literal syntax no longer uses '[# ... #]'}} {{9-10=}} {{17-19=}} let _ = [#colorLiteral( // expected-error@+1 {{expected expression in list of expressions}}
apache-2.0
f1b1899adbf731a3193d2e7bcfec2ad3
86.833333
180
0.611006
3.585034
false
false
false
false
avilin/BeatTheDay
BeatTheDay/Common/Views/GoalTableViewCell.swift
1
3440
// // GoalTableViewCell.swift // BeatTheDay // // Created by Andrés Vicente Linares on 21/6/17. // Copyright © 2017 Andrés Vicente Linares. All rights reserved. // import UIKit import Anchorage import Chameleon class GoalTableViewCell: UITableViewCell { var view: UIView! var statusImageView: UIImageView! var nameLabel: UILabel! var dateTimeStackView: UIStackView! var dateLabel: UILabel! var timeLabel: UILabel! private var shouldSetupConstraints = true override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupCell() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupCell() } private func setupCell() { backgroundColor = .clear setupView() setupStatusImageView() setupNameLabel() setupDateTimeStackView() setNeedsUpdateConstraints() } private func setupView() { view = UIView() contentView.addSubview(view) } private func setupStatusImageView() { statusImageView = UIImageView() statusImageView.contentMode = .scaleAspectFit view.addSubview(statusImageView) } private func setupNameLabel() { nameLabel = UILabel() view.addSubview(nameLabel) } private func setupDateTimeStackView() { dateLabel = UILabel() dateLabel.textAlignment = .right timeLabel = UILabel() timeLabel.textAlignment = .right dateTimeStackView = UIStackView(arrangedSubviews: [dateLabel, timeLabel]) dateTimeStackView.axis = .vertical dateTimeStackView.alignment = .fill dateTimeStackView.distribution = .fillEqually dateTimeStackView.spacing = 8 dateTimeStackView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(dateTimeStackView) } override func updateConstraints() { if shouldSetupConstraints { view.leadingAnchor == contentView.leadingAnchor + 4 view.topAnchor == contentView.topAnchor + 4 view.bottomAnchor == contentView.bottomAnchor - 4 view.trailingAnchor == contentView.trailingAnchor - 4 statusImageView.leadingAnchor == view.leadingAnchor + 8 statusImageView.topAnchor == view.topAnchor + 16 statusImageView.bottomAnchor == view.bottomAnchor - 16 statusImageView.widthAnchor == statusImageView.heightAnchor nameLabel.leadingAnchor == statusImageView.trailingAnchor + 8 nameLabel.topAnchor == view.topAnchor + 8 nameLabel.bottomAnchor == view.bottomAnchor - 8 dateTimeStackView.leadingAnchor == nameLabel.trailingAnchor + 8 dateTimeStackView.topAnchor == view.topAnchor + 8 dateTimeStackView.bottomAnchor == view.bottomAnchor - 8 dateTimeStackView.trailingAnchor == view.trailingAnchor - 8 shouldSetupConstraints = false } super.updateConstraints() } func styleCellWithBackgroundColor(_ backgroundColor: UIColor) { view.backgroundColor = backgroundColor let textColor = ContrastColorOf(backgroundColor, returnFlat: true) nameLabel.textColor = textColor dateLabel.textColor = textColor timeLabel.textColor = textColor } }
mit
e8ab51ff4c3e346914b89656d75753f5
29.149123
81
0.668315
5.895369
false
false
false
false
shralpmeister/shralptide2
ShralpTide/Shared/State/EnvironmentValues.swift
1
1804
// // EnvironmentValues.swift // SwiftTides // // Created by Michael Parlee on 12/17/20. // import SwiftUI private struct AppStateInteractorEnvironmentKey: EnvironmentKey { static let defaultValue = CoreDataAppStateInteractor() } private struct LegacyStationInteractorEnvironmentKey: EnvironmentKey { static let defaultValue = LegacyTideStationInteractor() } private struct StationInteractorEnvironmentKey: EnvironmentKey { static let defaultValue = StandardTideStationInteractor() } private struct AppStateRepositoryEnvironmentKey: EnvironmentKey { static let defaultValue = AppStateRepository() } private struct LegacyStationRepoEnvironmentKey: EnvironmentKey { static let defaultValue = StationDataRepository(data: LegacyStationData()) } private struct NoaaStationRepoEnvironmentKey: EnvironmentKey { static let defaultValue = StationDataRepository(data: NoaaStationData()) } private struct WatchSessionEnvironmentKey: EnvironmentKey { static let defaultValue = WatchSessionManager() } extension EnvironmentValues { var appStateInteractor: AppStateInteractor { self[AppStateInteractorEnvironmentKey.self] } var legacyStationInteractor: TideStationInteractor { self[LegacyStationInteractorEnvironmentKey.self] } var stationInteractor: TideStationInteractor { self[StationInteractorEnvironmentKey.self] } var appStateRepository: AppStateRepository { self[AppStateRepositoryEnvironmentKey.self] } var standardTideStationRepository: StationDataRepository { self[NoaaStationRepoEnvironmentKey.self] } var legacyTideStationRepository: StationDataRepository { self[LegacyStationRepoEnvironmentKey.self] } var watchSessionManager: WatchSessionManager { self[WatchSessionEnvironmentKey.self] } }
gpl-3.0
831592114a531bd8159e8fefc5a7381e
30.103448
95
0.79878
5.450151
false
false
false
false
AnRanScheme/MagiRefresh
MagiRefresh/Classes/UI/Header/MagiReplicatorHeader.swift
3
2200
// // MagiReplicatorHeader.swift // MagiRefresh // // Created by anran on 2018/9/19. // Copyright © 2018年 anran. All rights reserved. // import UIKit public class MagiReplicatorHeader: MagiRefreshHeaderConrol { fileprivate lazy var replicatorLayer: MagiReplicatorLayer = { let replicatorLayer = MagiReplicatorLayer() return replicatorLayer }() public var animationStyle: MagiReplicatorLayerAnimationStyle = .woody { didSet{ replicatorLayer.animationStyle = animationStyle } } override public var themeColor: UIColor { didSet{ replicatorLayer.themeColor = themeColor } } override public func setupProperties() { super.setupProperties() layer.addSublayer(replicatorLayer) } override public func layoutSubviews() { super.layoutSubviews() replicatorLayer.frame = CGRect(x: 0, y: 0, width: magi_width, height: magi_height) } override public func magiDidScrollWithProgress(progress: CGFloat, max: CGFloat) { switch animationStyle { case .woody: fallthrough case .allen: fallthrough case .circle: fallthrough case .dot: fallthrough case .arc: var progress1 = progress if (progress1 >= 0.7) { progress1 = (progress1-0.7)/(max - 0.7) replicatorLayer.indicatorShapeLayer.strokeEnd = progress1 } case .triangle: break } } override public func magiRefreshStateDidChange(_ status: MagiRefreshStatus) { super.magiRefreshStateDidChange(status) switch status { case .none: fallthrough case .scrolling: fallthrough case .ready: replicatorLayer.opacity = 1.0 case .refreshing: replicatorLayer.startAnimating() case .willEndRefresh: replicatorLayer.stopAnimating() } } }
mit
6da72dfff905c90150815b085bc7d763
25.792683
85
0.559854
5.520101
false
false
false
false
dflax/amazeballs
Legacy Versions/Swift 2.x Version/AmazeBalls/Config.swift
1
4527
// // Config.swift // Amazeballs // // Created by Daniel Flax on 5/18/15. // Copyright (c) 2015 Daniel Flax. All rights reserved. // // The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation import UIKit //UI Constants let ScreenWidth = UIScreen.mainScreen().bounds.size.width let ScreenHeight = UIScreen.mainScreen().bounds.size.height let ScreenCenter = CGPoint(x: ScreenWidth / 2.0, y: ScreenHeight / 2.0) let ScreenSize = CGSize(width: ScreenWidth, height: ScreenHeight) let ScreenRect = CGRect(x: 0.0, y: 0.0, width: ScreenWidth, height: ScreenHeight) // Device type - true if iPad or iPad Simulator let isPad: Bool = { if (UIDevice.currentDevice().userInterfaceIdiom == .Pad) { return true } else { return false } }() // Calculate the right size for the settingsViewController ball images var settingsBallSize: CGFloat { return ((ScreenWidth - 50) / 8) } //Random Integer generator func randomNumber(#minX:UInt32, #maxX:UInt32) -> Int { let result = (arc4random() % (maxX - minX + 1)) + minX return Int(result) } // Collision categories struct CollisionCategories{ static let Ball : UInt32 = 0x1 << 0 static let Floor : UInt32 = 0x1 << 1 static let EdgeBody: UInt32 = 0x1 << 2 } // Extensions to enable CGFloat casting extension Int { var cf: CGFloat { return CGFloat(self) } var f: Float { return Float(self) } } extension Float { var cf: CGFloat { return CGFloat(self) } var f: Float { return self } } extension Double { var cf: CGFloat { return CGFloat(self) } var f: Float { return Float(self) } } // Determine the device type private let DeviceList = [ /* iPod 5 */ "iPod5,1": "iPod Touch 5", /* iPhone 4 */ "iPhone3,1": "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4", /* iPhone 4S */ "iPhone4,1": "iPhone 4S", /* iPhone 5 */ "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5", /* iPhone 5C */ "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C", /* iPhone 5S */ "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S", /* iPhone 6 */ "iPhone7,2": "iPhone 6", /* iPhone 6 Plus */ "iPhone7,1": "iPhone 6 Plus", /* iPad 2 */ "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2", /* iPad 3 */ "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3": "iPad 3", /* iPad 4 */ "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4", /* iPad Air */ "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air", /* iPad Air 2 */ "iPad5,1": "iPad Air 2", "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2", /* iPad Mini */ "iPad2,5": "iPad Mini", "iPad2,6": "iPad Mini", "iPad2,7": "iPad Mini", /* iPad Mini 2 */ "iPad4,4": "iPad Mini", "iPad4,5": "iPad Mini", "iPad4,6": "iPad Mini", /* iPad Mini 3 */ "iPad4,7": "iPad Mini", "iPad4,8": "iPad Mini", "iPad4,9": "iPad Mini", /* Simulator */ "x86_64": "Simulator", "i386": "Simulator" ] // Extension to UIDevice. Usage: let modelName = UIDevice.currentDevice().modelName public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machine = systemInfo.machine let mirror = reflect(machine) var identifier = "" for i in 0..<mirror.count { if let value = mirror[i].1.value as? Int8 where value != 0 { identifier.append(UnicodeScalar(UInt8(value))) } } return DeviceList[identifier] ?? identifier } }
mit
019f464e27a272979cad48d2b076ff7f
37.364407
106
0.652971
3.299563
false
false
false
false
liuchuo/Calculator_Swift
Calculator_Swift/CalcLogic.swift
1
2885
// // CalcLogic.swift // Calculator_Swift // // Created by 欣 陈 on 15/9/10. // Copyright (c) 2015年 欣 陈. All rights reserved. // import Foundation enum Operator : Int { case Plus = 200, Minus, Multiply, Divide case Default = 0 } class CalcLogic { //保存上一次的值 var lastRetainValue : Double //最近一次选择的操作符(加、减、乘、除) var opr : Operator //临时保存MainLabel内容,为true时,输入数字MainLabel内容被清为0 var isMainLabelTextTemporary : Bool //构造器 init () { println("CalcLogic init") lastRetainValue = 0.0 isMainLabelTextTemporary = false opr = .Default } //析构器 deinit { println("CalcLogic deinit") } //更新主标签内容 func updateMainLabelStringByNumberTag(tag : Int,withMainLabelString mainLabelString : String) -> String { var string = mainLabelString if(isMainLabelTextTemporary) { string = "0" isMainLabelTextTemporary = false } let optNumber = tag - 100 //把String转为double var mainLabelDouble = (string as NSString).doubleValue if mainLabelDouble == 0 && doesStringContainDecimal(string) == false { return String(optNumber) } let resultString = string + String(optNumber) return resultString } //判断字符串中是否包含小数点 func doesStringContainDecimal(string : String) -> Bool { for ch in string { if ch == "." { return true } } return false } func calculateByTag(tag : Int,withMainLabelString mainLabelString : String) -> String { var currentValue = (mainLabelString as NSString).doubleValue switch opr { case .Plus: lastRetainValue += currentValue case .Minus: lastRetainValue -= currentValue case .Multiply: lastRetainValue *= currentValue case .Divide: if currentValue != 0 { lastRetainValue /= currentValue } else { opr = .Default isMainLabelTextTemporary = true return "错误" } default: lastRetainValue = currentValue } //记录当前操作符,下次计算时使用 opr = Operator(rawValue : tag)! let resultString = NSString(format : "%g",lastRetainValue) isMainLabelTextTemporary = true return resultString as String } func clear() { lastRetainValue = 0.0 isMainLabelTextTemporary = false opr = .Default } }
gpl-2.0
d4bcee82e4599f70d30b8d61868e4e4a
22.622807
109
0.54586
5.052533
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Services/PostService+Likes.swift
1
5510
extension PostService { /** Fetches a list of users from remote that liked the post with the given IDs. @param postID The ID of the post to fetch likes for @param siteID The ID of the site that contains the post @param count Number of records to retrieve. Optional. Defaults to the endpoint max of 90. @param before Filter results to likes before this date/time. Optional. @param excludingIDs An array of user IDs to exclude from the returned results. Optional. @param purgeExisting Indicates if existing Likes for the given post and site should be purged before new ones are created. Defaults to true. @param success A success block returning: - Array of LikeUser - Total number of likes for the given post - Number of likes per fetch @param failure A failure block */ func getLikesFor(postID: NSNumber, siteID: NSNumber, count: Int = 90, before: String? = nil, excludingIDs: [NSNumber]? = nil, purgeExisting: Bool = true, success: @escaping (([LikeUser], Int, Int) -> Void), failure: @escaping ((Error?) -> Void)) { guard let remote = postServiceRemoteFactory.restRemoteFor(siteID: siteID, context: managedObjectContext) else { DDLogError("Unable to create a REST remote for posts.") failure(nil) return } remote.getLikesForPostID(postID, count: NSNumber(value: count), before: before, excludeUserIDs: excludingIDs, success: { remoteLikeUsers, totalLikes in self.createNewUsers(from: remoteLikeUsers, postID: postID, siteID: siteID, purgeExisting: purgeExisting) { let users = self.likeUsersFor(postID: postID, siteID: siteID) success(users, totalLikes.intValue, count) LikeUserHelper.purgeStaleLikes() } }, failure: { error in DDLogError(String(describing: error)) failure(error) }) } /** Fetches a list of users from Core Data that liked the post with the given IDs. @param postID The ID of the post to fetch likes for. @param siteID The ID of the site that contains the post. @param after Filter results to likes after this Date. */ func likeUsersFor(postID: NSNumber, siteID: NSNumber, after: Date? = nil) -> [LikeUser] { let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser> request.predicate = { if let after = after { // The date comparison is 'less than' because Likes are in descending order. return NSPredicate(format: "likedSiteID = %@ AND likedPostID = %@ AND dateLiked < %@", siteID, postID, after as CVarArg) } return NSPredicate(format: "likedSiteID = %@ AND likedPostID = %@", siteID, postID) }() request.sortDescriptors = [NSSortDescriptor(key: "dateLiked", ascending: false)] if let users = try? managedObjectContext.fetch(request) { return users } return [LikeUser]() } } private extension PostService { func createNewUsers(from remoteLikeUsers: [RemoteLikeUser]?, postID: NSNumber, siteID: NSNumber, purgeExisting: Bool, onComplete: @escaping (() -> Void)) { guard let remoteLikeUsers = remoteLikeUsers, !remoteLikeUsers.isEmpty else { onComplete() return } let derivedContext = ContextManager.shared.newDerivedContext() derivedContext.perform { let likers = remoteLikeUsers.map { remoteUser in LikeUserHelper.createOrUpdateFrom(remoteUser: remoteUser, context: derivedContext) } if purgeExisting { self.deleteExistingUsersFor(postID: postID, siteID: siteID, from: derivedContext, likesToKeep: likers) } ContextManager.shared.save(derivedContext) { DispatchQueue.main.async { onComplete() } } } } func deleteExistingUsersFor(postID: NSNumber, siteID: NSNumber, from context: NSManagedObjectContext, likesToKeep: [LikeUser]) { let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser> request.predicate = NSPredicate(format: "likedSiteID = %@ AND likedPostID = %@ AND NOT (self IN %@)", siteID, postID, likesToKeep) do { let users = try context.fetch(request) users.forEach { context.delete($0) } } catch { DDLogError("Error fetching post Like Users: \(error)") } } }
gpl-2.0
5ad30c64b59dea4cab852434cbf7a5c2
41.713178
138
0.530853
5.824524
false
false
false
false
wayfindrltd/wayfindr-demo-ios
Wayfindr Demo/Classes/Controller/ModeSelectionTabBarController.swift
1
4410
// // ModeSelectionTabViewController.swift // Wayfindr Demo // // Created by Wayfindr on 11/11/2015. // Copyright (c) 2016 Wayfindr (http://www.wayfindr.net) // // 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 /// Tab bar to select between modes of the app. final class ModeSelectionTabViewController: UITabBarController { // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() tabBar.isTranslucent = false setupTabs() } // MARK: - Setup fileprivate func setupTabs() { // Setup Modes let userMode = setupUserMode() let maintainerMode = setupMaintainerMode() let developerMode = setupDeveloperMode() // Add Controllers to TabBar setViewControllers([userMode, maintainerMode, developerMode], animated: false) } fileprivate func setupUserMode() -> UIViewController { let userController = UserActionTableViewController() let userNavigationController = UINavigationController(rootViewController: userController) userNavigationController.navigationBar.barTintColor = WAYConstants.WAYColors.WayfindrMainColor userNavigationController.navigationBar.tintColor = WAYConstants.WAYColors.NavigationText userNavigationController.navigationBar.isTranslucent = false let userTabBarItem = UITabBarItem(title: WAYStrings.ModeSelection.User, image: UIImage(assetIdentifier: .User), tag: 1) userTabBarItem.accessibilityIdentifier = WAYAccessibilityIdentifier.ModeSelection.UserTabBarItem userNavigationController.tabBarItem = userTabBarItem return userNavigationController } fileprivate func setupMaintainerMode() -> UIViewController { let maintainerController = MaintainerActionSelectionTableView() let maintainerNavigationController = UINavigationController(rootViewController: maintainerController) maintainerNavigationController.navigationBar.barTintColor = WAYConstants.WAYColors.Maintainer maintainerNavigationController.navigationBar.isTranslucent = false let maintainerTabBarItem = UITabBarItem(title: WAYStrings.CommonStrings.Maintainer, image: UIImage(assetIdentifier: .Maintenance), tag: 1) maintainerTabBarItem.accessibilityIdentifier = WAYAccessibilityIdentifier.ModeSelection.MaintainerTabBarItem maintainerNavigationController.tabBarItem = maintainerTabBarItem return maintainerNavigationController } fileprivate func setupDeveloperMode() -> UIViewController { let viewController = DeveloperActionSelectionTableView() let navigationController = UINavigationController(rootViewController: viewController) navigationController.navigationBar.barTintColor = WAYConstants.WAYColors.Developer navigationController.navigationBar.isTranslucent = false let tabBarItem = UITabBarItem(title: WAYStrings.CommonStrings.Developer, image: UIImage(assetIdentifier: .Developer), tag: 1) tabBarItem.accessibilityIdentifier = WAYAccessibilityIdentifier.ModeSelection.DeveloperTabBarItem navigationController.tabBarItem = tabBarItem return navigationController } }
mit
3ca7c2ce194104d5f952bfeff531fd81
42.663366
146
0.733787
5.73472
false
false
false
false
MichaelRow/MusicPlayer
Sources/Player/iTunes/iTunes.swift
1
3524
// // iTunes.swift // MusicPlayer // // Created by Michael Row on 2017/8/31. // import Foundation import ScriptingBridge import iTunesBridge class iTunes { var iTunesPlayer: iTunesApplication var currentTrack: MusicTrack? weak var delegate: MusicPlayerDelegate? var rememberedTrackStateDate = Date() fileprivate(set) var hashValue: Int required init?() { guard let player = SBApplication(bundleIdentifier: MusicPlayerName.iTunes.bundleID) else { return nil } iTunesPlayer = player hashValue = Int(arc4random()) } deinit { stopPlayerTracking() } // MARK: - Player Event Handle func pauseEvent() { // Rewind and fast forward would send pause notification. guard playbackState == .paused else { return } delegate?.player(self, playbackStateChanged: .paused, atPosition: playerPosition) startRunningObserving() } func stoppedEvent() { delegate?.player(self, playbackStateChanged: .stopped, atPosition: playerPosition) startRunningObserving() } func playingEvent() { musicTrackCheckEvent() delegate?.player(self, playbackStateChanged: .playing, atPosition: playerPosition) startPeriodTimerObserving() } func runningCheckEvent() { if !isRunning { delegate?.playerDidQuit(self) } } // MARK: - Notification Event @objc func playerInfoChanged(_ notification: Notification) { guard let userInfo = notification.userInfo, let playerState = userInfo["Player State"] as? String else { return } switch playerState { case "Paused": pauseEvent() case "Stopped": stoppedEvent() case "Playing": playingEvent() default: break } if let location = userInfo["Location"] as? String { currentTrack?.url = URL(fileURLWithPath: location) } } // MARK: - Timer Actions func startPeriodTimerObserving() { // start timer let event = PlayerTimer.Event(kind: .Infinite, precision: MusicPlayerConfig.TimerInterval) { time in self.repositionCheckEvent() } PlayerTimer.shared.register(self, event: event) // write down the track start time rememberedTrackStateDate = trackStartDate } func startRunningObserving() { // stop date let date = Date(timeIntervalSinceNow: 1.5) let event = PlayerTimer.Event(kind: .Period(date), precision: MusicPlayerConfig.TimerInterval) { time in self.runningCheckEvent() } PlayerTimer.shared.register(self, event: event) } } // MARK: - Track extension iTunesTrack { var musicTrack: MusicTrack? { guard mediaKind == .music, let id = id?(), let name = name, let duration = duration else { return nil } var artwork: NSImage? = nil if let artworks = artworks?(), artworks.count > 0, let iTunesArtwork = artworks[0] as? iTunesArtwork { artwork = iTunesArtwork.data } return MusicTrack(id: String(id), title: name, album: album, artist: artist, duration: duration, artwork: artwork, lyrics: lyrics, url: nil, originalTrack: self as? SBObject) } }
gpl-3.0
f056628b0edfd9d679d2c09a0a9f4565
26.53125
182
0.59563
5.092486
false
false
false
false
powerytg/Accented
Accented/UI/Common/Utils/ImageUtils.swift
1
4114
// // ImageUtils.swift // Accented // // Image utilities // // Created by Tiangong You on 6/4/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import GPUImage class ImageUtils: NSObject { static func correctedImageOrientation(image : UIImage) -> ImageOrientation { var orientation : ImageOrientation = .portrait if image.imageOrientation == .right { orientation = .landscapeRight } else if image.imageOrientation == .up { orientation = .portrait } else if image.imageOrientation == .down { orientation = .portraitUpsideDown } else if image.imageOrientation == .left { orientation = .landscapeLeft } return orientation } // https://stackoverflow.com/a/33260568 static func fixOrientation(_ input : UIImage, width : CGFloat, height : CGFloat) -> UIImage? { guard let cgImage = input.cgImage else { return nil } if input.imageOrientation == UIImageOrientation.up { return input } var transform = CGAffineTransform.identity switch input.imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: width, y: height) transform = transform.rotated(by: CGFloat.pi) case .left, .leftMirrored: transform = transform.translatedBy(x: width, y: 0) transform = transform.rotated(by: 0.5*CGFloat.pi) case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: height) transform = transform.rotated(by: -0.5*CGFloat.pi) case .up, .upMirrored: break } switch input.imageOrientation { case .upMirrored, .downMirrored: transform = transform.translatedBy(x: width, y: 0) transform = transform.scaledBy(x: -1, y: 1) case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: height, y: 0) transform = transform.scaledBy(x: -1, y: 1) default: break; } // Now we draw the underlying CGImage into a new context, applying the transform // calculated above. guard let colorSpace = cgImage.colorSpace else { return nil } guard let context = CGContext( data: nil, width: Int(width), height: Int(height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: cgImage.bytesPerRow, space: colorSpace, bitmapInfo: UInt32(cgImage.bitmapInfo.rawValue) ) else { return nil } context.concatenate(transform); switch input.imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: // Grr... context.draw(cgImage, in: CGRect(x: 0, y: 0, width: height, height: width)) default: context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height)) } // And now we just create a new UIImage from the drawing context guard let newCGImg = context.makeImage() else { return nil } let img = UIImage(cgImage: newCGImg) return img; } // https://stackoverflow.com/a/43536102 static func flipImage(_ image: UIImage) -> UIImage { UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: image.size.width, y: image.size.height) context.scaleBy(x: -image.scale, y: -image.scale) context.draw(image.cgImage!, in: CGRect(origin:CGPoint.zero, size: image.size)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
mit
fa4120b8ddbb86a6be1cfc3e3e975823
32.169355
98
0.572088
4.979419
false
false
false
false
SandcastleApps/partyup
Pods/Instructions/Sources/Managers/SkipViewDisplayManager.swift
1
4948
// SkipViewDisplayManager.swift // // Copyright (c) 2015, 2016 Frédéric Maquin <[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 /// This class deals with the layout of the "skip" view. internal class SkipViewDisplayManager { //mark: Internal properties /// Datasource providing the constraints to use. weak var dataSource: CoachMarksControllerProxyDataSource! //mark: Private properties /// Constraints defining the position of the "Skip" view private var skipViewConstraints: [NSLayoutConstraint] = [] //mark: Internal methods /// Hide the given Skip View with a fading effect. /// /// - Parameter skipView: the skip view to hide. /// - Parameter duration: the duration of the fade. func hideSkipView(skipView: CoachMarkSkipView, duration: NSTimeInterval = 0) { if duration == 0 { skipView.asView?.alpha = 0.0 } else { UIView.animateWithDuration(duration) { () -> Void in skipView.asView?.alpha = 0.0 } } } /// Show the given Skip View with a fading effect. /// /// - Parameter skipView: the skip view to show. /// - Parameter duration: the duration of the fade. func showSkipView(skipView: CoachMarkSkipView, duration: NSTimeInterval = 0) { guard let parentView = skipView.asView?.superview else { print("The Skip View has no parent, aborting.") return } let constraints = self.dataSource.constraintsForSkipView(skipView.asView!, inParentView: parentView) updateSkipView(skipView, withConstraints: constraints) skipView.asView?.superview?.bringSubviewToFront(skipView.asView!) if duration == 0 { skipView.asView?.alpha = 1.0 } else { UIView.animateWithDuration(duration) { () -> Void in skipView.asView?.alpha = 1.0 } } } /// Update the constraints defining the location of given s view. /// /// - Parameter skipView: the skip view to position. /// - Parameter constraints: the constraints to use. internal func updateSkipView(skipView: CoachMarkSkipView, withConstraints constraints: [NSLayoutConstraint]?) { guard let parentView = skipView.asView?.superview else { print("The Skip View has no parent, aborting.") return } skipView.asView?.translatesAutoresizingMaskIntoConstraints = false parentView.removeConstraints(self.skipViewConstraints) self.skipViewConstraints = [] if let constraints = constraints { self.skipViewConstraints = constraints } else { self.skipViewConstraints = defaultConstraints(for: skipView, in: parentView) } parentView.addConstraints(self.skipViewConstraints) } private func defaultConstraints(for skipView: CoachMarkSkipView, in parentView: UIView) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() constraints.append(NSLayoutConstraint( item: skipView, attribute: .Trailing, relatedBy: .Equal, toItem: parentView, attribute: .Trailing, multiplier: 1, constant: -10 )) var topConstant: CGFloat = 0.0 #if !INSTRUCTIONS_APP_EXTENSIONS if !UIApplication.sharedApplication().statusBarHidden { topConstant = UIApplication.sharedApplication().statusBarFrame.size.height } #endif topConstant += 2 constraints.append(NSLayoutConstraint( item: skipView, attribute: .Top, relatedBy: .Equal, toItem: parentView, attribute: .Top, multiplier: 1, constant: topConstant )) return constraints } }
mit
c82de838fdacf754379e5e831e4476d1
37.046154
91
0.655277
5.244963
false
false
false
false
manfengjun/KYMart
Section/Home/Controller/KYHomeViewController.swift
1
19414
// // HomeViewController.swift // KYMart // // Created by Jun on 2017/6/4. // Copyright © 2017年 JUN. All rights reserved. // import UIKit import MJRefresh import PYSearch fileprivate let KYHomeMenuIdentifier = "kYHomeMenuCVCell" fileprivate let KYHomeMenuPageCVCellIdentifier = "kYHomeMenuPageCVCell" fileprivate let KYHomeAdCVCellIdentifier = "kYHomeAdCVCell" fileprivate let KYProductScrollIdentifier = "kYProductScrollCVCell" fileprivate let KYHomeHeadViewIdentifier = "kYHomeHeadView" fileprivate let KYHomeFootViewIdentifier = "kYHomeFootView" fileprivate let KYHomeSallHeadViewIdentifier = "kYHomeSallHeadView" fileprivate let KYPoductIdentifier = "kYProductCVCell" fileprivate let KYPoductHeadViewIdentifier = "kYProductHeadView" private let headerIdentifier = "header" class KYHomeViewController: BaseViewController { let menuTitles:[String] = ["家用电器","手机数码","家居生活","潮流服饰","鞋靴箱包","礼品首饰","食品生鲜","母婴专区","美妆个护","运动户外","汽车用品","生活出行","店铺街","品牌街","我的订单","限时优惠"] let menuIDs:[String] = ["1","2","4","5","6","7","8","9","10","11","12","399"] var sectionCount:Int = 0 var scrollSectionTitles:[String] = [] var scrollSectionData:NSMutableArray = NSMutableArray() var productArray:[Good] = [] var homepagemodel:KYHomeModel? { didSet { if let array = self.homepagemodel?.promotion_goods { if array.count > 0 { self.sectionCount += 1 self.scrollSectionTitles.append("促销商品") self.scrollSectionData.add(array) } } if let array = self.homepagemodel?.high_quality_goods { if array.count > 0 { self.sectionCount += 1 self.scrollSectionTitles.append("精品推荐") self.scrollSectionData.add(array) } } if let array = self.homepagemodel?.flash_sale_goods { if array.count > 0 { self.sectionCount += 1 self.scrollSectionTitles.append("抢购") self.scrollSectionData.add(array) } } if let array = self.homepagemodel?.new_goods { if array.count > 0 { self.sectionCount += 1 self.scrollSectionTitles.append("新品上市") self.scrollSectionData.add(array) } } if let array = self.homepagemodel?.hot_goods { if array.count > 0 { self.sectionCount += 1 self.scrollSectionTitles.append("热销商品") self.scrollSectionData.add(array) } } self.sectionCount += 2 } } var titleArray:[String] = ["店铺街","品牌街","我的订单","个人中心"] //刷新页数 var page = 1 /// 列表 fileprivate lazy var collectionView : UICollectionView = { let homeLayout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 64), collectionViewLayout: homeLayout) collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = UIColor.hexStringColor(hex: "#F2F2F2") collectionView.register(UINib(nibName:"KYHomeMenuCVCell", bundle:Bundle.main), forCellWithReuseIdentifier: KYHomeMenuIdentifier) collectionView.register(UINib(nibName:"KYHomeMenuPageCVCell", bundle:Bundle.main), forCellWithReuseIdentifier: KYHomeMenuPageCVCellIdentifier) collectionView.register(UINib(nibName:"KYHomeAdCVCell", bundle:Bundle.main), forCellWithReuseIdentifier: KYHomeAdCVCellIdentifier) collectionView.register(UINib(nibName:"KYProductScrollCVCell", bundle:Bundle.main), forCellWithReuseIdentifier: KYProductScrollIdentifier) collectionView.register(UINib(nibName:"KYProductCVCell", bundle:Bundle.main), forCellWithReuseIdentifier: KYPoductIdentifier) collectionView.register(KYHomeHeadView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KYHomeHeadViewIdentifier) collectionView.register(KYHomeFootView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: KYHomeFootViewIdentifier) collectionView.register(KYHomeSallHeadView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KYHomeSallHeadViewIdentifier) collectionView.register(KYProductHeadView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KYPoductHeadViewIdentifier) return collectionView }() /// 上拉加载 fileprivate lazy var footer:MJRefreshAutoNormalFooter = { let footer = MJRefreshAutoNormalFooter() footer.setRefreshingTarget(self, refreshingAction: #selector(KYHomeViewController.footerRefresh)) return footer }() override func viewDidLoad() { super.viewDidLoad() setupUI() // Do any additional setup after loading the view. } /// 初始化UI func setupUI() { setRightButtonInNav(imageUrl: "home_news.png", action: #selector(newsAction)); navigationController?.navigationBar.barTintColor = HOME_BAR_TINTCOLOR automaticallyAdjustsScrollViewInsets = true view.addSubview(collectionView) collectionView.mj_footer = footer dataHomeRequest() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - 数据请求 extension KYHomeViewController { /// 促销、热门、推荐、轮播等 func dataHomeRequest() { SJBRequestModel.pull_fetchHomePageData { (response, status) in if status == 1{ self.dataProductRequest() self.homepagemodel = response as? KYHomeModel } } } /// 猜我喜欢 func dataProductRequest() { SJBRequestModel.pull_fetchFavoriteProductData(page: self.page) { (response, status) in self.collectionView.mj_footer.endRefreshing() if status == 1{ // var currentArray = NSMutableArray() // currentArray = self.productArray as! NSMutableArray if response.count == 0 { XHToast.showBottomWithText("没有更多数据") self.page -= 1 return } if self.productArray.count > 0 { //去重 for item in response as! Array<Good> { let predicate = NSPredicate(format: "goods_id = %@", String(item.goods_id)) let array = self.productArray as! NSMutableArray let result = array.filtered(using: predicate) if result.count <= 0{ self.productArray.append(item) } } } else{ self.productArray = response as! [Good] } self.collectionView.reloadData() } } } /// 上拉加载 func footerRefresh() { page += 1 dataProductRequest() } /// 消息列表 func newsAction() { self.performSegue(withIdentifier: "H_newsmenu_SegueID", sender: nil) } } // MARK: ------ 轮播图片、响应事件 extension KYHomeViewController:SDCycleScrollViewDelegate{ /// 搜索 /// /// - Parameter sender: sender description func searchAction(sender:UITapGestureRecognizer) { let searchVC = PYSearchViewController() let listVC = KYSearchProductListViewController() searchVC.didSearchBlock = { (searchViewController,searchBar,searchText) in if let text = searchText { listVC.backResult { self.tabBarController?.tabBar.isHidden = false } searchViewController?.navigationController?.pushViewController(listVC, animated: true) listVC.q = text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) listVC.navTitle = text } } let nav = BaseNavViewController(rootViewController: searchVC) self.present(nav, animated: true, completion: nil) } } // MARK: - 数据列表 extension KYHomeViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return sectionCount } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return 1 } if section == 1 { if let array = homepagemodel?.zone_obj { return array.count } return 0 } else if section == sectionCount - 1 { return productArray.count } return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 0 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KYHomeMenuPageCVCellIdentifier, for: indexPath) as! KYHomeMenuPageCVCell cell.menuTitles = menuTitles cell.menuIDs = menuIDs cell.callBackOne({ (index) in let row = index as! Int if row < 12 { SingleManager.instance.selectId = Int(self.menuIDs[row])! NotificationCenter.default.post(name:SectionIDSelectedNotification, object: nil) self.tabBarController?.selectedIndex = 1 } else if row == 14{ if SingleManager.instance.isLogin { self.tabBarController?.selectedIndex = 3 let nav = self.tabBarController?.selectedViewController as! BaseNavViewController nav.viewControllers[0].performSegue(withIdentifier: "M_orderList_SegudID", sender: nil) } else{ let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) let loginNav = storyboard.instantiateViewController(withIdentifier: "loginNav") as! BaseNavViewController let loginVC = loginNav.viewControllers[0] as! SJBLoginViewController loginVC.loginResult({ (isLogin) in if isLogin { self.tabBarController?.selectedIndex = 3 let nav = self.tabBarController?.selectedViewController as! BaseNavViewController nav.viewControllers[0].performSegue(withIdentifier: "M_orderList_SegudID", sender: nil) } }) loginVC.hidesBottomBarWhenPushed = true self.present(loginNav, animated: true, completion: nil) } } else { let noneVC = NoneViewController() self.navigationController?.pushViewController(noneVC, animated: true) switch indexPath.row { case 12: noneVC.navTitle = "店铺街" break case 13: noneVC.navTitle = "品牌街" break case 15: noneVC.navTitle = "限时优惠" break default: break } } }) return cell } else if indexPath.section == 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KYHomeAdCVCellIdentifier, for: indexPath) as! KYHomeAdCVCell if let array = homepagemodel?.zone_obj { let zoneObj = array[indexPath.row] if let text = zoneObj.img_url { cell.adIV.sd_setImage(with: URL(string: imgPath + "/\(text)")) } } return cell } else if indexPath.section == sectionCount - 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KYPoductIdentifier, for: indexPath) as! KYProductCVCell cell.good = productArray[indexPath.row] return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KYProductScrollIdentifier, for: indexPath) as! KYProductScrollCVCell let models = scrollSectionData[indexPath.section - 1] as? [Good] cell.models = models cell.selectResult({ (index) in let detailVC = KYProductDetailViewController() let model = models?[index] detailVC.id = model?.goods_id self.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(detailVC, animated: true) self.hidesBottomBarWhenPushed = false }) return cell } } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { var resableview = UICollectionReusableView() if kind == UICollectionElementKindSectionHeader { if indexPath.section == 0 { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KYHomeHeadViewIdentifier, for: indexPath) as! KYHomeHeadView if let images = homepagemodel?.ad { view.images = images } let searchTap = UITapGestureRecognizer(target: self, action: #selector(searchAction(sender:))) view.searchView.addGestureRecognizer(searchTap) resableview = view } else if indexPath.section == 1 { } else if indexPath.section == sectionCount - 1 { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KYPoductHeadViewIdentifier, for: indexPath) as! KYProductHeadView resableview = view } else { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KYHomeSallHeadViewIdentifier, for: indexPath) as! KYHomeSallHeadView view.titleL.text = scrollSectionTitles[indexPath.section - 1] resableview = view } } else { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: KYHomeFootViewIdentifier, for: indexPath) as! KYHomeFootView resableview = view } return resableview } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 0 { return CGSize(width: SCREEN_WIDTH, height: (SCREEN_WIDTH/4 - 20 + 30)*2 + 20) } if indexPath.section == 1 { return CGSize(width: SCREEN_WIDTH, height: SCREEN_WIDTH*2/9) } else if indexPath.section == sectionCount - 1 { return CGSize(width: (SCREEN_WIDTH - 10) / 2, height: (SCREEN_WIDTH - 10)/2 + 80) } return CGSize(width: SCREEN_WIDTH, height: SCREEN_WIDTH/3 + 100) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { if section == 0 { return CGSize(width: SCREEN_WIDTH, height: SCREEN_WIDTH*20/49 + 50) } else if section == 1 { return CGSize(width: SCREEN_WIDTH, height: 0) } else if section == sectionCount - 1 { return CGSize(width: SCREEN_WIDTH, height: 40) } else { return CGSize(width: SCREEN_WIDTH, height: 60) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { if section == sectionCount - 1 { return 10 } return 0.01 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0.01 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSize(width: SCREEN_WIDTH, height: 11) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.section == 1 { if let array = homepagemodel?.zone_obj { let zoneObj = array[indexPath.row] if let text = zoneObj.api_url { let productlistVC = KYProduceSectionListViewController() productlistVC.url = text if let title = zoneObj.title { productlistVC.navTitle = title } else { productlistVC.navTitle = "商品列表" } self.navigationController?.pushViewController(productlistVC, animated: true) productlistVC.backResult { self.tabBarController?.tabBar.isHidden = false } } } } else if indexPath.section == sectionCount - 1 { let detailVC = KYProductDetailViewController() let model = productArray[indexPath.row] detailVC.id = model.goods_id self.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(detailVC, animated: true) self.hidesBottomBarWhenPushed = false } // let detailVC = KYProductDetailViewController() // let model = dataArray[indexPath.row] as? Goods_list // detailVC.id = model?.goods_id // self.navigationController?.pushViewController(detailVC, animated: true) } }
mit
33883d5467900d836d0bab0bf49ed737
43.238979
210
0.597682
5.698446
false
false
false
false
pksprojects/ElasticSwift
Sources/ElasticSwift/Requests/UpdateByQueryRequest.swift
1
5739
// // UpdateByQueryRequest.swift // ElasticSwift // // Created by Prafull Kumar Soni on 7/30/19. // import ElasticSwiftCore import ElasticSwiftQueryDSL import Foundation import NIOHTTP1 // MARK: - Update By Query Request Builder public class UpdateByQueryRequestBuilder: RequestBuilder { public typealias RequestType = UpdateByQueryRequest private var _index: String? private var _type: String? private var _script: Script? private var _query: Query? public init() {} @discardableResult public func set(index: String) -> Self { _index = index return self } @discardableResult @available(*, deprecated, message: "Elasticsearch has deprecated use of custom types and will be remove in 7.0") public func set(type: String) -> Self { _type = type return self } @discardableResult public func set(query: Query) -> Self { _query = query return self } @discardableResult public func set(script: Script) -> Self { _script = script return self } public var index: String? { return _index } public var type: String? { return _type } public var script: Script? { return _script } public var query: Query? { return _query } public func build() throws -> UpdateByQueryRequest { return try UpdateByQueryRequest(withBuilder: self) } } // MARK: - Update By Query Request public struct UpdateByQueryRequest: Request { public var headers = HTTPHeaders() public let index: String public let type: String? public let script: Script? public let query: Query? public var refresh: IndexRefresh? public var conflicts: ConflictStrategy? public var routing: String? public var scrollSize: Int? public var from: Int? public var size: Int? public init(index: String, type: String? = nil, script: Script?, query: Query?) { self.index = index self.type = type self.script = script self.query = query } internal init(withBuilder builder: UpdateByQueryRequestBuilder) throws { guard builder.index != nil else { throw RequestBuilderError.missingRequiredField("index") } self.init(index: builder.index!, type: builder.type, script: builder.script, query: builder.query) } public var queryParams: [URLQueryItem] { var params = [URLQueryItem]() if let refresh = self.refresh { params.append(URLQueryItem(name: QueryParams.refresh.rawValue, value: refresh.rawValue)) } if let startegy = conflicts { params.append(URLQueryItem(name: QueryParams.conflicts.rawValue, value: startegy.rawValue)) } if let routing = self.routing { params.append(URLQueryItem(name: QueryParams.routing.rawValue, value: routing)) } if let scrollSize = self.scrollSize { params.append(URLQueryItem(name: QueryParams.scrollSize.rawValue, value: String(scrollSize))) } if let from = self.from { params.append(URLQueryItem(name: QueryParams.from.rawValue, value: String(from))) } if let size = self.size { params.append(URLQueryItem(name: QueryParams.size.rawValue, value: String(size))) } return params } public var method: HTTPMethod { return .POST } public var endPoint: String { var _endPoint = index if let type = self.type { _endPoint += "/" + type } return _endPoint + "/" + "_update_by_query" } public func makeBody(_ serializer: Serializer) -> Result<Data, MakeBodyError> { if query == nil, script == nil { return .failure(.noBodyForRequest) } let body = Body(query: query, script: script) return serializer.encode(body).mapError { error -> MakeBodyError in MakeBodyError.wrapped(error) } } struct Body: Codable { public let query: Query? public let script: Script? init(query: Query?, script: Script?) { self.query = query self.script = script } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) query = try container.decodeQueryIfPresent(forKey: .query) script = try container.decode(Script.self, forKey: .script) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(query, forKey: .query) try container.encodeIfPresent(script, forKey: .script) } enum CodingKeys: String, CodingKey { case query case script } } } extension UpdateByQueryRequest: Equatable { public static func == (lhs: UpdateByQueryRequest, rhs: UpdateByQueryRequest) -> Bool { return lhs.index == rhs.index && lhs.type == rhs.type && lhs.script == rhs.script && lhs.refresh == rhs.refresh && lhs.conflicts == rhs.conflicts && lhs.routing == rhs.routing && lhs.scrollSize == rhs.scrollSize && lhs.from == rhs.from && lhs.size == rhs.size && matchQueries(lhs.query, rhs.query) } private static func matchQueries(_ lhs: Query?, _ rhs: Query?) -> Bool { if lhs == nil, rhs == nil { return true } if let lhs = lhs, let rhs = rhs { return lhs.isEqualTo(rhs) } return false } }
mit
52042d17902597a31ce240394150ed24
27.984848
116
0.604112
4.635703
false
false
false
false
quran/quran-ios
Sources/QuranAudioKit/Downloads/AyahsAudioDownloader.swift
1
2952
// // AyahsAudioDownloader.swift // Quran // // Created by Mohamed Afifi on 4/21/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import BatchDownloader import Foundation import PromiseKit import QuranKit public struct AyahsAudioDownloader { let downloader: DownloadManager let fileListFactory: ReciterAudioFileListRetrievalFactory init(downloader: DownloadManager, fileListFactory: ReciterAudioFileListRetrievalFactory) { self.downloader = downloader self.fileListFactory = fileListFactory } public init(baseURL: URL, downloader: DownloadManager) { self.downloader = downloader fileListFactory = DefaultReciterAudioFileListRetrievalFactory(quran: Quran.madani, baseURL: baseURL) } public func download(from start: AyahNumber, to end: AyahNumber, reciter: Reciter) -> Promise<DownloadBatchResponse> { DispatchQueue.global() .async(.guarantee) { () -> DownloadBatchRequest in let retriever = self.fileListFactory.fileListRetrievalForReciter(reciter) // get downloads let files = retriever .get(for: reciter, from: start, to: end) .filter { !FileManager.documentsURL.appendingPathComponent($0.local).isReachable } .map { DownloadRequest(url: $0.remote, destinationPath: $0.local) } return DownloadBatchRequest(requests: files) } .then { // create downloads self.downloader.download($0) } } public func downloadingAudios(_ reciters: [Reciter]) -> Guarantee<[Reciter: DownloadBatchResponse]> { downloader.getOnGoingDownloads() .map { self.audioResponses(reciters, downloads: $0) } } private func audioResponses(_ reciters: [Reciter], downloads: [DownloadBatchResponse]) -> [Reciter: DownloadBatchResponse] { var paths: [String: DownloadBatchResponse] = [:] for batch in downloads { if let download = batch.requests.first, batch.isAudio { paths[download.destinationPath.stringByDeletingLastPathComponent] = batch } } var responses: [Reciter: DownloadBatchResponse] = [:] for reciter in reciters { responses[reciter] = paths[reciter.path] } return responses } }
apache-2.0
e05a99550bace89dc0bb8b2fe38e49db
37.842105
128
0.66565
4.969697
false
false
false
false
silt-lang/silt
Sources/Lithosphere/RawSyntax.swift
1
9838
//===------------------ RawSyntax.swift - Raw Syntax nodes ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// // // This file contains modifications from the Silt Langauge project. These // modifications are released under the MIT license, a copy of which is // available in the repository. // //===----------------------------------------------------------------------===// /// Box a value type into a reference type class Box<T> { let value: T init(_ value: T) { self.value = value } } /// The data that is specific to a tree or token node enum RawSyntaxData { /// A tree node with a kind and an array of children case node(kind: SyntaxKind, layout: [RawSyntax?]) /// A token with a token kind, leading trivia, and trailing trivia case token(kind: TokenKind, leadingTrivia: Trivia, trailingTrivia: Trivia) } /// Represents the raw tree structure underlying the syntax tree. These nodes /// have no notion of identity and only provide structure to the tree. They /// are immutable and can be freely shared between syntax nodes. final class RawSyntax { let data: RawSyntaxData let totalLength: SourceLength let presence: SourcePresence init(kind: SyntaxKind, layout: [RawSyntax?], length: SourceLength, presence: SourcePresence) { self.data = .node(kind: kind, layout: layout) self.totalLength = length self.presence = presence } init(kind: TokenKind, leadingTrivia: Trivia, trailingTrivia: Trivia, length: SourceLength, presence: SourcePresence) { self.data = .token(kind: kind, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia) self.totalLength = length self.presence = presence } /// The syntax kind of this raw syntax. var kind: SyntaxKind { switch data { case .node(let kind, _): return kind case .token(_, _, _): return .token } } var tokenKind: TokenKind? { switch data { case .node(_, _): return nil case .token(let kind, _, _): return kind } } /// The layout of the children of this Raw syntax node. var layout: [RawSyntax?] { switch data { case .node(_, let layout): return layout case .token(_, _, _): return [] } } /// Whether or not this node is a token one. var isToken: Bool { return tokenKind != nil } /// Whether this node is present in the original source. var isPresent: Bool { return presence == .present } /// Whether this node is missing from the original source. var isMissing: Bool { return presence == .missing } /// Creates a RawSyntax node that's marked missing in the source with the /// provided kind and layout. /// - Parameters: /// - kind: The syntax kind underlying this node. /// - layout: The children of this node. /// - Returns: A new RawSyntax `.node` with the provided kind and layout, with /// `.missing` source presence. static func missing(_ kind: SyntaxKind) -> RawSyntax { return RawSyntax(kind: kind, layout: [], length: SourceLength.zero, presence: .missing) } /// Creates a RawSyntax token that's marked missing in the source with the /// provided kind and no leading/trailing trivia. /// - Parameter kind: The token kind. /// - Returns: A new RawSyntax `.token` with the provided kind, no /// leading/trailing trivia, and `.missing` source presence. static func missingToken(_ kind: TokenKind) -> RawSyntax { return RawSyntax(kind: kind, leadingTrivia: [], trailingTrivia: [], length: SourceLength.zero, presence: .missing) } /// Returns a new RawSyntax node with the provided layout instead of the /// existing layout. /// - Note: This function does nothing with `.token` nodes --- the same token /// is returned. /// - Parameter newLayout: The children of the new node you're creating. func replacingLayout(_ newLayout: [RawSyntax?]) -> RawSyntax { switch data { case let .node(kind, _): return .createAndCalcLength(kind: kind, layout: newLayout, presence: presence) case .token(_, _, _): return self } } /// Creates a new RawSyntax with the provided child appended to its layout. /// - Parameter child: The child to append /// - Note: This function does nothing with `.token` nodes --- the same token /// is returned. /// - Return: A new RawSyntax node with the provided child at the end. func appending(_ child: RawSyntax) -> RawSyntax { var newLayout = layout newLayout.append(child) return replacingLayout(newLayout) } /// Returns the child at the provided cursor in the layout. /// - Parameter index: The index of the child you're accessing. /// - Returns: The child at the provided index. subscript<CursorType: RawRepresentable>(_ index: CursorType) -> RawSyntax? where CursorType.RawValue == Int { return layout[index.rawValue] } /// Replaces the child at the provided index in this node with the provided /// child. /// - Parameters: /// - index: The index of the child to replace. /// - newChild: The new child that should occupy that index in the node. func replacingChild(_ index: Int, with newChild: RawSyntax?) -> RawSyntax { precondition(index < layout.count, "Cursor \(index) reached past layout") var newLayout = layout newLayout[index] = newChild return replacingLayout(newLayout) } } extension RawSyntax: TextOutputStreamable { /// Prints the RawSyntax node, and all of its children, to the provided /// stream. This implementation must be source-accurate. /// - Parameter stream: The stream on which to output this node. func write<Target>(to target: inout Target) where Target: TextOutputStream { switch data { case .node(_, let layout): for child in layout { guard let child = child else { continue } child.write(to: &target) } case let .token(kind, leadingTrivia, trailingTrivia): guard isPresent else { return } for piece in leadingTrivia { piece.writeSourceText(to: &target) } target.write(kind.text) for piece in trailingTrivia { piece.writeSourceText(to: &target) } } } } extension RawSyntax { var leadingTrivia: Trivia? { switch data { case .node(_, let layout): for child in layout { guard let child = child else { continue } guard let result = child.leadingTrivia else { break } return result } return nil case let .token(_, leadingTrivia, _): return leadingTrivia } } var trailingTrivia: Trivia? { switch data { case .node(_, let layout): for child in layout.reversed() { guard let child = child else { continue } guard let result = child.trailingTrivia else { break } return result } return nil case let .token(_, _, trailingTrivia): return trailingTrivia } } } extension RawSyntax { var leadingTriviaLength: SourceLength { return leadingTrivia?.sourceLength ?? .zero } var trailingTriviaLength: SourceLength { return trailingTrivia?.sourceLength ?? .zero } /// The length of this node excluding its leading and trailing trivia. var contentLength: SourceLength { return totalLength - (leadingTriviaLength + trailingTriviaLength) } /// Convenience function to create a RawSyntax when its byte length is not /// known in advance, e.g. it is programmatically constructed instead of /// created by the parser. /// /// This is a separate function than in the initializer to make it more /// explicit and visible in the code for the instances where we don't have /// the length of the raw node already available. static func createAndCalcLength(kind: SyntaxKind, layout: [RawSyntax?], presence: SourcePresence) -> RawSyntax { let length: SourceLength switch presence { case .missing, .implicit: length = SourceLength.zero case .present: var totalen = SourceLength.zero for child in layout { totalen += child?.totalLength ?? .zero } length = totalen } return .init(kind: kind, layout: layout, length: length, presence: presence) } /// Convenience function to create a RawSyntax when its byte length is not /// known in advance, e.g. it is programmatically constructed instead of /// created by the parser. /// /// This is a separate function than in the initializer to make it more /// explicit and visible in the code for the instances where we don't have /// the length of the raw node already available. static func createAndCalcLength(kind: TokenKind, leadingTrivia: Trivia, trailingTrivia: Trivia, presence: SourcePresence) -> RawSyntax { let length: SourceLength switch presence { case .missing, .implicit: length = SourceLength.zero case .present: length = kind.sourceLength + leadingTrivia.sourceLength + trailingTrivia.sourceLength } return .init(kind: kind, leadingTrivia: leadingTrivia, trailingTrivia: trailingTrivia, length: length, presence: presence) } } // This is needed purely to have a self assignment initializer for // RawSyntax.init(from:Decoder) so we can reuse omitted nodes, instead of // copying them. private protocol _RawSyntaxFactory {} extension _RawSyntaxFactory { init(_instance: Self) { self = _instance } }
mit
c7c4e2de6be82dbc2faa458596494284
33.159722
80
0.659585
4.627469
false
false
false
false
silt-lang/silt
Sources/Moho/ScopeCheck.swift
1
37561
/// ScopeCheck.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Lithosphere import Foundation extension NameBinding { /// Checks that a module, its parameters, and its child declarations are /// well-scoped. In the process, `NameBinding` will quantify all non-local /// names and return a simplified well-scoped (but not yet type-correct) /// AST as output. /// /// Should scope check detect inconsistencies, it will diagnose terms and /// often drop them from its consideration - but not before binding their /// names into scope to aid recovery. /// /// This pass does not fail thus it is crucial that the diagnostic /// engine be checked before continuing on to the semantic passes. public func scopeCheckModule(_ module: ModuleDeclSyntax, topLevel: Bool = false) -> DeclaredModule { let moduleName = QualifiedName(ast: module.moduleIdentifier) let params = module.typedParameterList.map(self.scopeCheckParameter) let qmodName: QualifiedName if topLevel { qmodName = moduleName } else { qmodName = self.activeScope.qualify(name: moduleName.name) } let noteScope = walkNotations(module, qmodName) let moduleCheck: (Scope) -> DeclaredModule = { _ in return DeclaredModule( moduleName: self.activeScope.nameSpace.module, params: params, namespace: self.activeScope.nameSpace, decls: self.reparseDecls(module.declList)) } if topLevel { self.activeScope = noteScope return moduleCheck(noteScope) } else { return self.withScope(walkNotations(module, qmodName), moduleCheck) } } /// Scope check a declaration that may be found directly under a module. private func scopeCheckDecl(_ syntax: DeclSyntax) -> [Decl] { precondition(!(syntax is FunctionDeclSyntax || syntax is FunctionClauseDeclSyntax)) switch syntax { case let syntax as LetBindingDeclSyntax: return self.scopeCheckLetBinding(syntax) case let syntax as ModuleDeclSyntax: return [.module(self.scopeCheckModule(syntax))] case let syntax as DataDeclSyntax: return self.scopeCheckDataDecl(syntax) case let syntax as EmptyDataDeclSyntax: return self.scopeCheckEmptyDataDecl(syntax) case let syntax as RecordDeclSyntax: return self.scopeCheckRecordDecl(syntax) case let syntax as RecordConstructorDeclSyntax: return self.scopeCheckRecordConstructorDecl(syntax) case let syntax as FieldDeclSyntax: return self.scopeCheckFieldDecl(syntax) case let syntax as FixityDeclSyntax: return self.scopeCheckFixityDecl(syntax) case let syntax as ImportDeclSyntax: return self.scopeCheckImportDecl(syntax) case let syntax as OpenImportDeclSyntax: return self.scopeCheckOpenImportDecl(syntax) default: fatalError("scope checking for \(type(of: syntax)) is unimplemented") } } private func formCompleteApply( _ n: FullyQualifiedName, _ argBuf: [Expr]) -> Expr { let head: ApplyHead var args = [Expr]() args.reserveCapacity(argBuf.count) guard let resolution = self.resolveQualifiedName(n) else { // If it's not a definition or a local variable, it's undefined. // Recover by introducing a local variable binding anyways. self.engine.diagnose(.undeclaredIdentifier(n), node: n.node) head = .variable(n.name) args.append(contentsOf: argBuf) return .apply(head, args.map(Elimination.apply)) } switch resolution { case let .variable(h): head = .variable(h) args.append(contentsOf: argBuf) case let .nameInfo(fqn, info): switch info { case let .definition(plicity): head = .definition(fqn) let (result, _) = self.consumeArguments(argBuf, plicity, Expr.meta, { [$0] }, allowExtraneous: true) args.append(contentsOf: result) case let .constructor(set): args.append(contentsOf: argBuf) return .constructor(n, set.map { $0.0 }, args) default: head = .definition(fqn) args.append(contentsOf: argBuf) } } return .apply(head, args.map(Elimination.apply)) } /// Scope check and validate an expression. private func scopeCheckExpr(_ syntax: ExprSyntax) -> Expr { switch syntax { case let syntax as NamedBasicExprSyntax: let n = QualifiedName(ast: syntax.name) return self.formCompleteApply(n, []) case _ as TypeBasicExprSyntax: return .type case _ as UnderscoreExprSyntax: return .meta case let syntax as ParenthesizedExprSyntax: return self.underScope { _ in return self.scopeCheckExpr(syntax.expr) } case let syntax as LambdaExprSyntax: return self.underScope { _ in let bindings = self.scopeCheckBindingList(syntax.bindingList) let ee = self.scopeCheckExpr(syntax.bodyExpr) return bindings.reversed().reduce(ee) { (acc, next) -> Expr in let boundNames: [Name] = next.names let paramAsc: Expr = next.ascription return boundNames.reduce(acc) { (acc, nm) -> Expr in return Expr.lambda((nm, paramAsc), acc) } } } case let syntax as ReparsedApplicationExprSyntax: guard syntax.exprs.count >= 1 else { return self.scopeCheckExpr(syntax.head) } let headExpr = syntax.head let n = QualifiedName(ast: headExpr.name) guard n.string != NewNotation.arrowNotation.name.string else { assert(syntax.exprs.count == 2) if let piParams = syntax.exprs[0] as? TypedParameterGroupExprSyntax { return rollPi(piParams.parameters.map(self.scopeCheckParameter), self.scopeCheckExpr(syntax.exprs[1])).0 } return .function(self.scopeCheckExpr(syntax.exprs[0]), self.scopeCheckExpr(syntax.exprs[1])) } var args = [Expr]() for e in syntax.exprs { let elim = self.scopeCheckExpr(e) args.append(elim) } return self.formCompleteApply(n, args) case let syntax as ApplicationExprSyntax: guard syntax.exprs.count > 1 else { return self.scopeCheckExpr(syntax.exprs[0]) } switch syntax.exprs[0] { case let headExpr as NamedBasicExprSyntax: let n = QualifiedName(ast: headExpr.name) guard n.string != NewNotation.arrowNotation.name.string else { assert(syntax.exprs.count == 3) if let piParams = syntax.exprs[1] as? TypedParameterGroupExprSyntax { return rollPi(piParams.parameters.map(self.scopeCheckParameter), self.scopeCheckExpr(syntax.exprs[2])).0 } return .function(self.scopeCheckExpr(syntax.exprs[1]), self.scopeCheckExpr(syntax.exprs[2])) } var args = [Expr]() for e in syntax.exprs.dropFirst() { let elim = self.scopeCheckExpr(e) args.append(elim) } return self.formCompleteApply(n, args) default: fatalError("Cannot yet handle this case") } case let syntax as QuantifiedExprSyntax: return self.underScope { _ in let telescope = syntax.bindingList.map(self.scopeCheckParameter) return self.rollPi(telescope, self.scopeCheckExpr(syntax.outputExpr)).0 } case let syntax as TypedParameterGroupExprSyntax: let telescope = syntax.parameters.map(self.scopeCheckParameter) return self.rollPi1(telescope) case let syntax as LetExprSyntax: return self.underScope { _ in let reparsedDecls = self.reparseDecls(syntax.declList, allowOmittingSignatures: true) let output = self.scopeCheckExpr(syntax.outputExpr) return Expr.let(reparsedDecls, output) } default: fatalError("scope checking for \(type(of: syntax)) is unimplemented") } } // swiftlint:disable large_tuple private func rollPi( _ telescope: [DeclaredParameter], _ cap: Expr ) -> (Expr, [Name], [ArgumentPlicity]) { var type = cap var piNames = [Name]() var plicities = [ArgumentPlicity]() for param in telescope.reversed() { for name in param.names.reversed() { type = Expr.pi(name, param.ascription, type) piNames.append(name) plicities.append(param.plicity) } } return (type, piNames.reversed(), plicities.reversed()) } private func rollPi1(_ telescope: [DeclaredParameter]) -> Expr { precondition(!telescope.isEmpty) guard let first = telescope.last else { fatalError() } var type = first.ascription for name in first.names.dropLast().reversed() { type = Expr.pi(name, first.ascription, type) } for param in telescope.dropLast().reversed() { for name in param.names.reversed() { type = Expr.pi(name, param.ascription, type) } } return type } private func scopeCheckBindingList( _ syntax: BindingListSyntax) -> [DeclaredParameter] { var bs = [DeclaredParameter]() for binding in syntax { switch binding { case let binding as NamedBindingSyntax: let name = QualifiedName(ast: binding.name).name guard let bindName = self.bindVariable(named: name) else { // If this declaration is trying to bind with a reserved name, // ignore it. continue } bs.append(DeclaredParameter([bindName], .meta, .explicit)) case let binding as TypedBindingSyntax: bs.append(self.scopeCheckParameter(binding.parameter)) case _ as AnonymousBindingSyntax: bs.append(DeclaredParameter([ Name(name: SyntaxFactory.makeUnderscore()) ], .meta, .explicit)) default: fatalError() } } return bs } private func scopeCheckReparsedFunctionClauseDecl( _ syntax: ReparsedFunctionClause, _ boundExpr: ExprSyntax ) -> [Decl] { typealias ScopeCheckType = (QualifiedName, Expr, [ArgumentPlicity], [DeclaredPattern]) let (qualName, body, plicity, patterns) = self.underScope { _ -> ScopeCheckType in let plicity = Array(repeating: ArgumentPlicity.explicit, count: syntax.lhs.exprs.count) let patterns = self.scopeCheckPattern(syntax.lhs.name.syntax, syntax.lhs.exprs, plicity) let reparsedRHS = self.reparseExpr(boundExpr) let body = self.scopeCheckExpr(reparsedRHS) let qualName = QualifiedName(name: syntax.lhs.name) return (qualName, body, plicity, patterns) } guard let name = self.bindDefinition(named: qualName.name, plicity) else { engine.diagnose(.nameShadows(qualName.name), node: syntax.lhs.name.syntax) { $0.highlight(syntax.lhs.name.syntax) } return [] } let clause = DeclaredClause(patterns: patterns, body: .body(body, [])) return [Decl.letBinding(name, clause)] } private func scopeCheckLetBinding(_ syntax: LetBindingDeclSyntax) -> [Decl] { typealias ScopeCheckType = (QualifiedName, Expr, [ArgumentPlicity], [DeclaredPattern]) let (qualName, body, plicity, patterns) = self.underScope { _ -> ScopeCheckType in let plicity = Array(repeating: ArgumentPlicity.explicit, count: syntax.basicExprList.count) let patterns = self.scopeCheckPattern(syntax, syntax.basicExprList, plicity) let reparsedRHS = self.reparseExpr(syntax.boundExpr) let body = self.scopeCheckExpr(reparsedRHS) let qualName = QualifiedName(ast: syntax.head.name) return (qualName, body, plicity, patterns) } guard let name = self.bindDefinition(named: qualName.name, plicity) else { engine.diagnose(.nameShadows(qualName.name), node: syntax.head) { $0.highlight(syntax.head) } return [] } let clause = DeclaredClause(patterns: patterns, body: .body(body, [])) return [Decl.letBinding(name, clause)] } private func scopeCheckParameter( _ syntax: TypedParameterSyntax) -> DeclaredParameter { switch syntax { case let syntax as ExplicitTypedParameterSyntax: let tyExpr = self.scopeCheckExpr( self.reparseExpr(syntax.ascription.typeExpr)) var names = [Name]() for synName in syntax.ascription.boundNames { let name = Name(name: synName) guard !self.isBoundVariable(name) else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(name), node: syntax.ascription) { $0.highlight(syntax.ascription) } continue } guard let bindName = self.bindVariable(named: name) else { // If this declaration is trying to bind with a reserved name, // ignore it. continue } names.append(bindName) } return DeclaredParameter(names, tyExpr, .explicit) case let syntax as ImplicitTypedParameterSyntax: let tyExpr = self.scopeCheckExpr( self.reparseExpr(syntax.ascription.typeExpr)) var names = [Name]() for synName in syntax.ascription.boundNames { let name = Name(name: synName) guard !self.isBoundVariable(name) else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(name), node: syntax.ascription) { $0.highlight(syntax.ascription) } continue } guard let bindName = self.bindVariable(named: name) else { // If this declaration is trying to bind with a reserved name, // ignore it. continue } names.append(bindName) } return DeclaredParameter(names, tyExpr, .implicit) default: fatalError("scope checking for \(type(of: syntax)) is unimplemented") } } private func scopeCheckWhereClause( _ syntax: FunctionWhereClauseDeclSyntax?) -> [Decl] { guard let syntax = syntax else { return [] } return self.reparseDecls(syntax.declList) } private func scopeCheckPattern<Patterns: Collection>( _ parent: Syntax, _ syntax: Patterns, _ plicity: [ArgumentPlicity], expectAbsurd: Bool = false ) -> [DeclaredPattern] where Patterns.Element == BasicExprSyntax, Patterns.Index == Int { let (pats, maybeError) = self.consumeArguments(syntax, plicity, DeclaredPattern.wild, self.exprToDeclPattern) if let err = maybeError { switch err { case let .extraneousArguments(expected, have, implicit, leftoverStart): let diag: Diagnostic.Message = .tooManyPatternsInLHS(expected, have, implicit) self.engine.diagnose(diag, node: parent) { for i in leftoverStart..<syntax.count { $0.note(.ignoringExcessPattern, node: syntax[i]) } } } } func openPatternVarsIntoScope(_ p: DeclaredPattern) -> Bool { switch p { case .wild, .absurd: return true case .variable(let name): guard self.isBoundVariable(name) else { _ = self.bindVariable(named: name) return true } return false case let .constructor(_, pats): return pats.allSatisfy { openPatternVarsIntoScope($0) } } } var validPatterns = [DeclaredPattern]() validPatterns.reserveCapacity(pats.count) for pat in pats { guard openPatternVarsIntoScope(pat) else { continue } validPatterns.append(pat) } return validPatterns } private func scopeCheckEmptyDataDecl( _ syntax: EmptyDataDeclSyntax) -> [Decl] { typealias ScopeCheckType = (Expr, [ArgumentPlicity]) let (type, plicity) = self.underScope { (_) -> ScopeCheckType in let params = syntax.typedParameterList.map(self.scopeCheckParameter) let rebindExpr = self.reparseExpr(syntax.typeIndices.indexExpr) let (type, _, plicity) = self.rollPi(params, self.scopeCheckExpr(rebindExpr)) return (type, plicity) } let dataName = Name(name: syntax.dataIdentifier) guard let boundDataName = self.bindDefinition(named: dataName, plicity) else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(dataName), node: syntax) return [] } return [Decl.dataSignature(TypeSignature(name: boundDataName, type: type, plicity: plicity))] } private func scopeCheckDataDecl(_ syntax: DataDeclSyntax) -> [Decl] { return self.underScope { (parentScope) -> [Decl] in let params = syntax.typedParameterList.map(self.scopeCheckParameter) let rebindExpr = self.reparseExpr(syntax.typeIndices.indexExpr) let (type, names, plicity) = self.rollPi(params, self.scopeCheckExpr(rebindExpr)) let dataName = Name(name: syntax.dataIdentifier) guard let boundDataName = self.bindDefinition(named: dataName, in: parentScope, plicity) else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(dataName), node: syntax) return [] } let asc = Decl.dataSignature(TypeSignature(name: boundDataName, type: type, plicity: plicity)) let cs = self.underScope(named: boundDataName) { _ in return syntax.constructorList.flatMap(self.scopeCheckConstructor) } for constr in cs { guard self.bindConstructor(named: constr.name, in: parentScope, plicity) != nil else { fatalError("Constructor names should be unique by now!") } } return [ asc, Decl.data(boundDataName, names, cs) ] } } private func scopeCheckRecordConstructorDecl( _ syntax: RecordConstructorDeclSyntax) -> [Decl] { let recName = QualifiedName(name: Name(name: syntax.constructorName)) // Just return a bogus record signature. We'll fill this in later. return [ Decl.recordSignature(TypeSignature(name: recName, type: .meta, plicity: []), recName) ] } private func scopeCheckRecordDecl(_ syntax: RecordDeclSyntax) -> [Decl] { let recName = Name(name: syntax.recordName) // FIXME: Compute plicity guard let boundDataName = self.bindDefinition(named: recName, []) else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(recName), node: syntax) return [] } typealias ScopeCheckType = (TypeSignature, Name, [DeclaredField], [Name], [Decl], [ArgumentPlicity]) let checkedData = self.underScope {_ -> ScopeCheckType? in let params = syntax.parameterList.map(self.scopeCheckParameter) let indices = self.reparseExpr(syntax.typeIndices.indexExpr) let checkedIndices = self.scopeCheckExpr(indices) var preSigs = [DeclaredField]() var decls = [Decl]() var constr: Name? for re in self.reparseDecls(syntax.recordElementList) { switch re { case let .ascription(sig): preSigs.append(DeclaredField(signature: sig)) case .function(_, _): decls.append(re) case let .recordSignature(_, name): constr = name.name default: fatalError("\(re)") } } guard let recConstr = constr else { self.engine.diagnose(.recordMissingConstructor(boundDataName), node: syntax) return nil } let (ty, names, plicity) = self.rollPi(params, checkedIndices) let recordSignature = TypeSignature(name: boundDataName, type: ty, plicity: plicity) return (recordSignature, recConstr, preSigs, names, decls, plicity) } guard let (sig, recConstr, declFields, paramNames, decls, plicity) = checkedData else { return [] } // Open the record projections into the current scope. var sigs = [TypeSignature]() for declField in declFields { let fieldBaseName = declField.signature.name.name guard let bindName = self.bindProjection(named: fieldBaseName) else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(fieldBaseName), node: fieldBaseName.syntax) continue } sigs.append(TypeSignature(name: bindName, type: declField.signature.type, plicity: declField.signature.plicity)) } let fqn = self.activeScope.qualify(name: recConstr) guard let bindName = self.bindConstructor(named: fqn, plicity) else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(recConstr), node: recConstr.syntax) return [] } let asc = Decl.recordSignature(sig, bindName) let recordDecl: Decl = .record(boundDataName, paramNames, bindName, sigs) return [asc, recordDecl] + decls } private func scopeCheckFieldDecl( _ syntax: FieldDeclSyntax) -> [Decl] { assert(syntax.ascription.boundNames.count == 1) let (ascExpr, plicity) = self.underScope { _ -> (Expr, [ArgumentPlicity]) in let rebindExpr = self.reparseExpr(syntax.ascription.typeExpr) let plicity = self.computePlicity(rebindExpr) let ascExpr = self.scopeCheckExpr(rebindExpr) return (ascExpr, plicity) } let name = Name(name: syntax.ascription.boundNames[0]) guard self.bindVariable(named: name) != nil else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(name), node: syntax.ascription) return [] } return [ .ascription(TypeSignature(name: QualifiedName(name: name), type: ascExpr, plicity: plicity)) ] } private func scopeCheckConstructor( _ syntax: ConstructorDeclSyntax) -> [TypeSignature] { var result = [TypeSignature]() result.reserveCapacity(syntax.ascription.boundNames.count) for synName in syntax.ascription.boundNames { let name = Name(name: synName) let rebindExpr = self.reparseExpr(syntax.ascription.typeExpr) let ascExpr = self.scopeCheckExpr(rebindExpr) let plicity = self.computePlicity(rebindExpr) let fqn = self.activeScope.qualify(name: name) guard let bindName = self.bindConstructor(named: fqn, plicity) else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(name), node: syntax.ascription) continue } result.append(TypeSignature(name: bindName, type: ascExpr, plicity: plicity)) } return result } private func scopeCheckFunctionDecl( _ syntax: ReparsedFunctionDecl) -> [Decl] { let rebindExpr = self.reparseExpr(syntax.ascription.typeExpr) let ascExpr = self.underScope { _ in return self.scopeCheckExpr(rebindExpr) } let plicity = self.computePlicity(rebindExpr) let name = Name(name: syntax.name) guard let functionName = self.bindDefinition(named: name, plicity) else { fatalError("Should have unique function names by now") } let ascription = TypeSignature(name: functionName, type: ascExpr, plicity: plicity) let clauses = syntax.clauseList.map({ (clause, reparse) in return self.scopeCheckFunctionClause(clause, reparse, plicity) }) let fn = Decl.function(functionName, clauses) return [Decl.ascription(ascription), fn] } private func computePlicity(_ syntax: ExprSyntax) -> [ArgumentPlicity] { var plicities = [ArgumentPlicity]() func go(_ syntax: ExprSyntax) { switch syntax { case let syntax as ReparsedApplicationExprSyntax: let headExpr = syntax.head let n = QualifiedName(ast: headExpr.name) guard n.string == NewNotation.arrowNotation.name.string else { return } assert(syntax.exprs.count == 2) if let piParams = syntax.exprs[0] as? TypedParameterGroupExprSyntax { for param in piParams.parameters { switch param { case let itps as ImplicitTypedParameterSyntax: for _ in itps.ascription.boundNames { plicities.append(.implicit) } case let etps as ExplicitTypedParameterSyntax: for _ in etps.ascription.boundNames { plicities.append(.explicit) } default: fatalError() } } } else { plicities.append(.explicit) } go(syntax.exprs[1]) case let paren as ParenthesizedExprSyntax: go(paren.expr) default: return } } _ = go(syntax) return plicities } private func scopeCheckFunctionClause( _ syntax: FunctionClauseDeclSyntax, _ reparse: ReparsedFunctionClause, _ plicity: [ArgumentPlicity] ) -> DeclaredClause { switch syntax { case let syntax as NormalFunctionClauseDeclSyntax: return self.underScope { _ in let pattern = self.scopeCheckPattern(syntax, reparse.lhs.exprs, plicity) return self.underScope { _ in let wheres = self.scopeCheckWhereClause(syntax.whereClause) let reparsedRHS = self.reparseExpr(syntax.rhsExpr) let body = self.scopeCheckExpr(reparsedRHS) return DeclaredClause(patterns: pattern, body: .body(body, wheres)) } } case let syntax as WithRuleFunctionClauseDeclSyntax: return self.underScope { _ in let pattern = self.scopeCheckPattern(syntax, reparse.lhs.exprs, plicity) return self.underScope { _ in let wheres = self.scopeCheckWhereClause(syntax.whereClause) let body = self.scopeCheckExpr(syntax.rhsExpr) // FIXME: Introduce the with variables binding too. return DeclaredClause(patterns: pattern, body: .body(body, wheres)) } } case let syntax as AbsurdFunctionClauseDeclSyntax: return self.underScope { _ in let pattern = self.scopeCheckPattern(syntax, reparse.lhs.exprs, plicity, expectAbsurd: true) return DeclaredClause(patterns: pattern, body: .empty) } default: fatalError("Non-exhaustive match of function clause decl syntax?") } } private func exprToDeclPattern(_ syntax: ExprSyntax) -> [DeclaredPattern] { switch syntax { case let syntax as NamedBasicExprSyntax where syntax.name.count == 1 && syntax.name[0].name.tokenKind == .underscore: return [.wild] case let syntax as AbsurdExprSyntax: return [.absurd(syntax)] case let syntax as NamedBasicExprSyntax: let headName = QualifiedName(ast: syntax.name).name let localName = self.lookupLocalName(headName) guard case let .some((_, .constructor(overloadSet))) = localName else { return [.variable(headName)] } return [.constructor(overloadSet.map { $0.0 }, [])] case let syntax as ApplicationExprSyntax: guard let firstExpr = syntax.exprs.first, let head = firstExpr as? NamedBasicExprSyntax else { fatalError("Can't handle this kind of pattern") } let argsExpr = syntax.exprs.dropFirst().flatMap(self.exprToDeclPattern) let headName = QualifiedName(ast: head.name).name let localName = self.lookupLocalName(headName) guard case let .some((_, .constructor(overloadSet))) = localName else { fatalError() } return [.constructor(overloadSet.map { $0.0 }, argsExpr)] case let syntax as ReparsedApplicationExprSyntax: let name = QualifiedName(ast: syntax.head.name).name let lookupResult = self.lookupLocalName(name) guard case let .some(_, .constructor(overloadSet)) = lookupResult else { return self.exprToDeclPattern(syntax.head) + syntax.exprs.flatMap(self.exprToDeclPattern) } return [.constructor(overloadSet.map { $0.0 }, syntax.exprs.flatMap(self.exprToDeclPattern))] case let syntax as ParenthesizedExprSyntax: return self.exprToDeclPattern(syntax.expr) case _ as UnderscoreExprSyntax: return [.wild] default: fatalError("scope checking for \(type(of: syntax)) is unimplemented") } } } extension NameBinding { func reparseDecls(_ ds: DeclListSyntax, allowOmittingSignatures: Bool = false) -> [Decl] { var decls = [Decl]() var funcMap = [Name: FunctionDeclSyntax]() var clauseMap = [Name: [(FunctionClauseDeclSyntax, ReparsedFunctionClause)]]() var nameList = [Name]() for decl in ds { switch decl { case let funcDecl as FunctionDeclSyntax: for synName in funcDecl.ascription.boundNames { let name = Name(name: synName) guard clauseMap[name] == nil else { // If this declaration does not have a unique name, diagnose it and // recover by ignoring it. self.engine.diagnose(.nameShadows(name), node: funcDecl.ascription) { $0.note(.shadowsOriginal(name), node: funcMap[name]!) } continue } funcMap[name] = funcDecl clauseMap[name] = [] nameList.append(name) } case let funcDecl as NormalFunctionClauseDeclSyntax: let reparsedLHS = self.reparseLHS(funcDecl.basicExprList) let reparsedDecl = ReparsedFunctionClause(lhs: reparsedLHS) if clauseMap[reparsedLHS.name] == nil { if allowOmittingSignatures { decls.append(contentsOf: self.scopeCheckReparsedFunctionClauseDecl(reparsedDecl, funcDecl.rhsExpr)) continue } else { self.engine.diagnose(.bodyBeforeSignature(reparsedLHS.name), node: funcDecl) continue } } clauseMap[reparsedLHS.name]!.append((funcDecl, reparsedDecl)) case let funcDecl as AbsurdFunctionClauseDeclSyntax: let reparsedLHS = self.reparseLHS(funcDecl.basicExprList) let reparsedDecl = ReparsedFunctionClause(lhs: reparsedLHS) guard clauseMap[reparsedLHS.name] != nil else { self.engine.diagnose(.bodyBeforeSignature(reparsedLHS.name), node: funcDecl) continue } clauseMap[reparsedLHS.name]!.append((funcDecl, reparsedDecl)) case let fieldDecl as FieldDeclSyntax: for synName in fieldDecl.ascription.boundNames { let singleAscript = fieldDecl.ascription .withBoundNames(SyntaxFactory.makeIdentifierListSyntax([synName])) let newField = fieldDecl.withAscription(singleAscript) decls.append(contentsOf: self.scopeCheckDecl(newField)) } default: decls.append(contentsOf: self.scopeCheckDecl(decl)) } } for k in nameList { let function = funcMap[k]! let clauses = clauseMap[k]! decls.append(contentsOf: self.scopeCheckFunctionDecl(ReparsedFunctionDecl( name: k.syntax, ascription: function.ascription, trailingSemicolon: function.trailingSemicolon, clauseList: clauses))) } return decls } private func scopeCheckFixityDecl(_ syntax: FixityDeclSyntax) -> [Decl] { _ = fixityFromSyntax(syntax, diagnose: true) return [] } } extension NameBinding { fileprivate enum ArgumentConsumptionError { case extraneousArguments(expected: Int, have: Int, implicit: Int, leftoverStart: Int) } /// Consumes arguments of a given plicity and returns an array of all valid /// arguments. /// /// This function may be used to validate both the LHS and RHS of a /// declaration. /// /// Matching parameters is an iterative process that tries to drag as many /// implicit arguments into scope as possible as long as they are anchored by /// a named argument. For example, given the declaration: /// /// ``` /// f : {A B : Type} -> A -> B -> {C : Type} -> C -> A /// f x y c = x /// ``` /// /// The parameters `A, B` are dragged into scope by the introduction of `x`, /// and `c` drags `C` into scope. Items implicitly dragged into scope are /// represented by the value in the `implicit` parameter; either a wildcard /// pattern for LHSes or metavariables for RHSes. fileprivate func consumeArguments<C, T>( _ syntax: C, _ plicity: [ArgumentPlicity], _ implicit: T, _ valuesFn: (C.Element) -> [T], allowExtraneous: Bool = false ) -> ([T], ArgumentConsumptionError?) where C: Collection, C.Indices.Index == Int { var arguments = [T]() var lastExplicit = -1 var syntaxIdx = 0 var implicitCount = 0 for i in 0..<plicity.count { guard syntaxIdx < syntax.count else { for trailingImplIdx in i..<plicity.count { guard case .implicit = plicity[trailingImplIdx] else { break } arguments.append(implicit) } break } guard case .explicit = plicity[i] else { implicitCount += 1 continue } if i - lastExplicit - 1 > 0 || (lastExplicit == -1 && i > 0) { let extra = (lastExplicit == -1) ? i : (i - lastExplicit - 1) let wildCards = repeatElement(implicit, count: extra) arguments.append(contentsOf: wildCards) } let val = valuesFn(syntax[syntaxIdx]) arguments.append(contentsOf: val) syntaxIdx += 1 lastExplicit = i } guard syntaxIdx >= syntax.count || allowExtraneous else { let err = ArgumentConsumptionError .extraneousArguments(expected: arguments.count, have: syntax.count, implicit: implicitCount, leftoverStart: syntaxIdx) return (arguments, err) } if allowExtraneous && syntaxIdx < syntax.count { for i in syntaxIdx..<syntax.count { arguments.append(contentsOf: valuesFn(syntax[i])) } } return (arguments, nil) } } extension NameBinding { private func scopeCheckImportDecl(_ syntax: ImportDeclSyntax) -> [Decl] { let name = QualifiedName(ast: syntax.importIdentifier) guard let dependentURL = self.validateImportName(name) else { self.engine.diagnose(.incorrectModuleName(name), node: name.node) return [] } guard let importedDecls = self.processImportedFile(dependentURL) else { fatalError() } guard self.importModule(name, importedDecls) else { fatalError() } return [] } private func scopeCheckOpenImportDecl( _ syntax: OpenImportDeclSyntax ) -> [Decl] { let name = QualifiedName(ast: syntax.importIdentifier) guard let dependentURL = self.validateImportName(name) else { self.engine.diagnose(.incorrectModuleName(name), node: name.node) return [] } guard let importedDecls = self.processImportedFile(dependentURL) else { fatalError() } guard self.importModule(name, importedDecls) else { fatalError() } self.bindOpenNames(importedDecls, from: name) return [] } } private struct ReparsedFunctionDecl { let name: TokenSyntax let ascription: AscriptionSyntax let trailingSemicolon: TokenSyntax let clauseList: [(FunctionClauseDeclSyntax, ReparsedFunctionClause)] init( name: TokenSyntax, ascription: AscriptionSyntax, trailingSemicolon: TokenSyntax, clauseList: [(FunctionClauseDeclSyntax, ReparsedFunctionClause)] ) { self.name = name self.ascription = ascription self.trailingSemicolon = trailingSemicolon self.clauseList = clauseList } } private struct ReparsedFunctionClause { let lhs: ReparsedBasicExprList init( lhs: ReparsedBasicExprList ) { self.lhs = lhs } }
mit
38dd9dada3ef5959db9a7274fdac49e2
36.299901
80
0.628604
4.696886
false
false
false
false
PANDA-Guide/PandaGuideApp
PandaGuide/CurrentUser.swift
1
3085
// // CurrentUser.swift // PandaGuide // // Created by Arnaud Lenglet on 24/04/2017. // Copyright © 2017 ESTHESIX. All rights reserved. // import UIKit import os.log class CurrentUser: NSObject, NSCoding { // MARK: - Properties var id: Int var last_name: String var first_name: String var username: String var auth_token: String var email: String // MARK: API interface struct apiProperty { static let id = "id" static let last_name = "last_name" static let first_name = "first_name" static let username = "username" static let auth_token = "auth_token" static let email = "email" } // MARK: - Initialization init(id: Int, last_name: String, first_name: String, username: String, auth_token: String, email: String) { self.id = id self.last_name = last_name self.first_name = first_name self.username = username self.auth_token = auth_token self.email = email } // MARK: - Archiving Paths private static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! private static let ArchiveURL = DocumentsDirectory.appendingPathComponent("currentUser") // MARK: - Class methods static func get() -> Any? { return NSKeyedUnarchiver.unarchiveObject(withFile: ArchiveURL.path) as? CurrentUser ?? nil } static func set(to currentUser: CurrentUser) { NSKeyedArchiver.archiveRootObject(currentUser, toFile: ArchiveURL.path) os_log("Current User set to %@", log: .default, type: .debug, currentUser.username) } static func delete() { NSKeyedArchiver.archiveRootObject("", toFile: ArchiveURL.path) } // MARK: - NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: apiProperty.id) aCoder.encode(last_name, forKey: apiProperty.last_name) aCoder.encode(first_name, forKey: apiProperty.first_name) aCoder.encode(username, forKey: apiProperty.username) aCoder.encode(auth_token, forKey: apiProperty.auth_token) aCoder.encode(email, forKey: apiProperty.email) } required convenience init?(coder aDecoder: NSCoder) { let id = aDecoder.decodeInteger(forKey: apiProperty.id) let last_name = aDecoder.decodeObject(forKey: apiProperty.last_name) as! String let first_name = aDecoder.decodeObject(forKey: apiProperty.first_name) as! String let username = aDecoder.decodeObject(forKey: apiProperty.username) as! String let auth_token = aDecoder.decodeObject(forKey: apiProperty.auth_token) as! String let email = aDecoder.decodeObject(forKey: apiProperty.email) as! String self.init(id: id, last_name: last_name, first_name: first_name, username: username, auth_token: auth_token, email: email) } }
gpl-3.0
d2fc271eca91b954890bc9516dd1e012
32.89011
129
0.628405
4.343662
false
false
false
false
swift-lang/swift-k
tests/stress/internals/x_append_iter.swift
2
763
/* Iterate loops with variable number of loops to be called with cmdline arg -loops=<Number> todo : Fails to compile on 0.94 ? check Compiles on 0.93 (Regression noted) perhaps this isn't a very scalable test :( stats: 1K -> 2.458s real 10K -> Java heap space ? exec failed 100K -> ? 1M -> java.langOutOfMemoryError thrown 10M -> ? #NIGHTLY 1000 #WEEKLY 1000 10000 */ int limit = @toint(@arg("loops")); string result[]; result[0] = "banana"; iterate current { result[current+1] = @strcat(result[current], "banana"); // tracef("result[current] = %s \n", result[current]); } until ( current > limit ); tracef("Result[0] = %s \n", result[0]); tracef("Result[%i] = %s \n", limit, result[limit]);
apache-2.0
8192beadba82d914109fd4c8f6ac294a
27.296296
56
0.61599
3.179167
false
false
true
false
glaurent/MessagesHistoryBrowser
MessagesHistoryBrowser/ViewControllers/ChatTableViewController.swift
1
24368
// // ChatTableViewController.swift // MessagesHistoryBrowser // // Created by Guillaume Laurent on 25/10/15. // Copyright © 2015 Guillaume Laurent. All rights reserved. // import Cocoa import Contacts let CountryPhonePrefixUserDefaultsKey = "CountryPhonePrefix" let ShowDetailedSenderUserDefaultsKey = "ShowDetailedSender" let ShowTerseTimeUserDefaultsKey = "ShowTerseTime" extension String { func standardizingPath() -> String { return self.replacingOccurrences(of: "~", with: "/Users/" + NSUserName()) } } class ChatTableViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate { @IBOutlet weak var tableView: NSTableView! @IBOutlet weak var searchField: NSSearchField! @IBOutlet weak var afterDatePicker: NSDatePicker! @IBOutlet weak var beforeDatePicker: NSDatePicker! @IBOutlet weak var dbPopulateProgressIndicator: NSProgressIndicator! @IBOutlet weak var progressReportView: NSView! @objc dynamic var progress:Progress! var messagesListViewController:MessagesListViewController? var allKnownContacts = [ChatContact]() var allUnknownContacts = [ChatContact]() var messageFormatter = MessageFormatter() var showChatsFromUnknown = false var contactAccessChecked = false var searchTerm:String? var searchedContacts:[ChatContact]? var searchedMessages:[ChatMessage]? var searchTermHasChanged = false let dbPathBookmarkFileName = "DBPathBookmarkData" lazy var bookmarkDataFileURL:URL = { let appSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] let bookmarkDataFileURL = URL(fileURLWithPath: dbPathBookmarkFileName, relativeTo: appSupportURL) return bookmarkDataFileURL }() var dbPathBookmarkData: NSData? var setupDBSucceeded = false var messagesFolderURL:URL? @objc dynamic var beforeDateEnabled = false @objc dynamic var afterDateEnabled = false @objc dynamic var beforeDate = Date().addingTimeInterval(3600 * 24 * -7) // a week ago @objc dynamic var afterDate = Date().addingTimeInterval(3600 * 24 * -30) // a month ago var hasChatSelected:Bool { get { return tableView != nil && tableView.selectedRow >= 0 } } var showDetailedSenderUserDefault:Bool { return UserDefaults.standard.bool(forKey: ShowDetailedSenderUserDefaultsKey) } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. // first connect to the Messages.app chats DB, and terminate if we can't // setupDBSucceeded = setupChatDatabase() let moc = MOCController.sharedInstance.managedObjectContext let appDelegate = NSApp.delegate as! AppDelegate appDelegate.chatTableViewController = self if let parentSplitViewController = parent as? NSSplitViewController { let secondSplitViewItem = parentSplitViewController.splitViewItems[1] messagesListViewController = secondSplitViewItem.viewController as? MessagesListViewController } NotificationCenter.default.addObserver(self, selector: #selector(ChatTableViewController.showUnknownContactsChanged(_:)), name: NSNotification.Name(rawValue: AppDelegate.ShowChatsFromUnknownNotification), object: nil) // NSNotificationCenter.defaultCenter().addObserver(self, selector: "phonePrefixChanged:", name: NSUserDefaultsDidChangeNotification, object: nil) UserDefaults.standard.addObserver(self, forKeyPath: CountryPhonePrefixUserDefaultsKey, options: .new, context: nil) UserDefaults.standard.addObserver(self, forKeyPath: ShowDetailedSenderUserDefaultsKey, options: .new, context: nil) UserDefaults.standard.addObserver(self, forKeyPath: ShowTerseTimeUserDefaultsKey, options: .new, context: nil) if Chat.numberOfChatsInContext(moc) == 0 { importMessagesFromOSXApp() } else if appDelegate.needDBReload { // CoreData DB load failed, rebuild the whole thing refreshChatHistory() } else { progressReportView.isHidden = true tableView.isHidden = false messagesListViewController?.view.isHidden = false allKnownContacts = ChatContact.allKnownContacts(moc) allUnknownContacts = ChatContact.allUnknownContacts(moc) tableView.reloadData() } ChatItemsFetcher.sharedInstance.completion = displayChats } override func viewDidAppear() { // Check contacts authorization // if !contactAccessChecked { let contactStore = CNContactStore() contactStore.requestAccess(for: .contacts) { (authorized, error) in NSLog("ContactStore requestAccess result : \(authorized) - \(String(describing: error))") if !authorized { DispatchQueue.main.async { if let appDelegate = NSApp.delegate as? AppDelegate { appDelegate.showChatsFromUnknown = true } let alert = NSAlert() alert.messageText = NSLocalizedString("No access to contacts", comment: "") alert.informativeText = "access to contacts is denied - chat list will be displayed with phone numbers instead of contact names" alert.alertStyle = .warning alert.addButton(withTitle: NSLocalizedString("OK", comment: "")) let _ = alert.runModal() } } } contactAccessChecked = true } if !setupDBSucceeded { // First, ask user to open the ~/Library/Messages folder // let panel = NSOpenPanel() panel.canChooseFiles = false panel.canChooseDirectories = true panel.allowsMultipleSelection = false panel.message = NSLocalizedString("Please allow access to your Messages archive", comment: "") panel.directoryURL = URL(fileURLWithPath: String("~/Library/Messages/").standardizingPath(), isDirectory: true) panel.begin() { (response:NSApplication.ModalResponse) in if response == NSApplication.ModalResponse.OK { NSLog("Access granted") // create bookmark to selected folder // do { if let bookmarkData = try panel.url?.bookmarkData(options: URL.BookmarkCreationOptions.withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil) { let appSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] let bookmarkDataFileURL = URL(fileURLWithPath: self.dbPathBookmarkFileName, relativeTo: appSupportURL) try bookmarkData.write(to: bookmarkDataFileURL) } } catch (let error) { NSLog("Couldn't write bookmark data : \(error)") } self.setupDBSucceeded = self.setupChatDatabase() if !self.setupDBSucceeded { self.showPrivilegesDialogAndQuit() } } else { self.showPrivilegesDialogAndQuit() } } } } override func viewWillDisappear() { messagesFolderURL?.stopAccessingSecurityScopedResource() } private func showPrivilegesDialogAndQuit() { // if #available(OSX 10.14, *) { // // let showAppPrivilegesSetupWindowController = NSStoryboard.main?.instantiateController(withIdentifier: "AccessPrivilegesDialog") as! NSWindowController // // NSApp.mainWindow?.beginSheet(showAppPrivilegesSetupWindowController.window!, completionHandler: { (_) in // NSApp.terminate(nil) // }) // // } else { let appDelegate = NSApp.delegate as! AppDelegate let chatsDBPath = appDelegate.chatsDBPath let alert = NSAlert() alert.messageText = String(format:NSLocalizedString("Couldn't open Messages.app database in\n%@", comment: ""), chatsDBPath) alert.informativeText = NSLocalizedString("Application can't run. Check if the database is accessible", comment: "") alert.alertStyle = .critical alert.addButton(withTitle: NSLocalizedString("Quit", comment: "")) let _ = alert.runModal() NSApp.terminate(nil) // } } @objc func showUnknownContactsChanged(_ notification:Notification) { let appDelegate = NSApp.delegate as! AppDelegate showChatsFromUnknown = appDelegate.showChatsFromUnknown tableView.reloadData() } func contactForRow(_ row:Int) -> ChatContact? { guard (searchTerm != nil && row < searchedContacts!.count) || (showChatsFromUnknown && row < allKnownContacts.count + allUnknownContacts.count) || row < allKnownContacts.count else { return nil } var contact:ChatContact if searchTerm != nil { contact = searchedContacts![row] } else { if showChatsFromUnknown && row >= allKnownContacts.count { contact = allUnknownContacts[row - allKnownContacts.count] } else { contact = allKnownContacts[row] } } // print("\(__FUNCTION__) : row \(row) - contact \(contact.name)") return contact } // MARK: NSTableView datasource & delegate func numberOfRows(in tableView: NSTableView) -> Int { if searchTerm != nil { return searchedContacts?.count ?? 0 } if showChatsFromUnknown { return allKnownContacts.count + allUnknownContacts.count } return allKnownContacts.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { guard let tableColumn = tableColumn else { return nil } let cellView = tableView.makeView(withIdentifier: tableColumn.identifier, owner: self) as! ContactTableCellView if let contact = contactForRow(row) { cellView.textField?.stringValue = contact.name if let cellImageView = cellView.imageView { let (thumbnailImage, initialsPair) = ContactsMap.sharedInstance.contactImage(contact.identifier) if let thumbnailImage = thumbnailImage { let roundedThumbnailImage = roundCorners(thumbnailImage) DispatchQueue.main.async { cellImageView.image = roundedThumbnailImage cellView.showImage() } } else if let initialsPair = initialsPair { // contact unknown for this cell, use initials to generate an image let initials = "\(initialsPair.0)\(initialsPair.1)" DispatchQueue.main.async { cellView.contactInitialsLabel.stringValue = initials // cellView.createCircleLayer() cellView.showLabel() } } else { DispatchQueue.main.async { cellImageView.image = nil cellView.showImage() } } } } else { // no contact for this row ? shouldn't happen NSLog("WARNING : no contact found for row \(row)") cellView.textField?.stringValue = "unknown" cellView.imageView?.image = nil cellView.contactInitialsLabel.stringValue = "" cellView.showLabel() } return cellView } func tableViewSelectionDidChange(_ notification: Notification) { guard let index = tableView.selectedRowIndexes.first else { return } // no multiple selection if let selectedContact = contactForRow(index) { displayMessageListForContact(selectedContact) } else { // no contact selected, clean up if let searchTerm = searchTerm { // there is a search set, go back to full list of matching messages ChatItemsFetcher.sharedInstance.restoreSearchToAllContacts() messagesListViewController?.showMessages(ChatItemsFetcher.sharedInstance.matchingItems, withHighlightTerm: searchTerm) } else { // no search, clear all messagesListViewController?.clearAttachments() messagesListViewController?.clearMessages() } } } func displayMessageListForContact(_ contact:ChatContact) { // chatsDatabase.collectMessagesForContact(contact) ChatItemsFetcher.sharedInstance.contact = contact ChatItemsFetcher.sharedInstance.searchWithCompletionBlock() } func orderedMessagesForSelectedRow() -> (ChatContact, [ChatMessage])? { guard tableView.selectedRow >= 0 else { return nil } let index = tableView.selectedRow guard let selectedContact = contactForRow(index) else { return nil } let allContactChats = selectedContact.chats.allObjects as! [Chat] // get all messages from this contact // let allContactMessageArrays = allContactChats.compactMap { (chat) -> [ChatMessage]? in return chat.messages.allObjects as? [ChatMessage] } // let allContactMessages = allContactMessageArrays.reduce([ChatMessage]()) { (result, messageArray) -> [ChatMessage] in // return result + messageArray // } let allContactMessages = allContactMessageArrays.reduce([ChatMessage](), +) let allContactSortedMessages = allContactMessages.sorted { (messageA, messageB) -> Bool in return messageA.date < messageB.date } return (selectedContact, allContactSortedMessages) } func orderedChatItemsForSelectedRow() -> (ChatContact, [ChatItem])? { guard tableView.selectedRow >= 0 else { return nil } let index = tableView.selectedRow guard let selectedContact = contactForRow(index) else { return nil } let allContactChats = selectedContact.chats.allObjects as! [Chat] // get all chat items for this contact // let allContactChatItemArrays = allContactChats.compactMap { (chat) -> [ChatItem]? in return (chat.messages.allObjects + chat.attachments.allObjects) as? [ChatItem] } let allContactChatItems = allContactChatItemArrays.reduce([ChatItem](), +) let allContactSortedChatItems = allContactChatItems.sorted { (itemA, itemB) -> Bool in return itemA.date < itemB.date } return (selectedContact, allContactSortedChatItems) } // MARK: actions @IBAction func search(_ sender: NSSearchField) { NSLog("search for '\(sender.stringValue)'") searchTermHasChanged = true ChatItemsFetcher.sharedInstance.contact = nil if sender.stringValue == "" { searchTerm = nil searchedContacts = nil ChatItemsFetcher.sharedInstance.clearSearch() messagesListViewController?.showDetailedSender = showDetailedSenderUserDefault messagesListViewController?.clearMessages() messagesListViewController?.clearAttachments() tableView.reloadData() } else if sender.stringValue.count >= 3 && sender.stringValue != searchTerm { searchTerm = sender.stringValue ChatItemsFetcher.sharedInstance.searchTerm = sender.stringValue ChatItemsFetcher.sharedInstance.searchWithCompletionBlock() } } // restart a search once one of the date pickers has been changed // @IBAction func redoSearch(_ sender: NSObject) { if sender == afterDatePicker { afterDateEnabled = true } else if sender == beforeDatePicker { beforeDateEnabled = true } ChatItemsFetcher.sharedInstance.afterDate = afterDateEnabled ? afterDatePicker.dateValue : nil ChatItemsFetcher.sharedInstance.beforeDate = beforeDateEnabled ? beforeDatePicker.dateValue : nil ChatItemsFetcher.sharedInstance.searchWithCompletionBlock() } // override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { // print("\(__FUNCTION__) : \(change)") // if keyPath == "fractionCompleted" { // let newValue = change!["new"] as! NSNumber // dbPopulateProgressIndicator.doubleValue = newValue.doubleValue // } // } // MARK: file save enum SaveError : Error { case dataConversionFailed } func saveContactChats(_ contact:ChatContact, atURL url:URL) { do { let sortedMessages = contact.messages.sorted(by: ChatItemsFetcher.sharedInstance.messageEnumIteratorDateSort) let messages = sortedMessages as! [ChatMessage] let reducer = { (currentValue:String, message:ChatMessage) -> String in return currentValue + "\n" + self.messageFormatter.formatMessageAsString(message) } let allMessagesAsString = messages.reduce("", reducer) let tmpNSString = NSString(string: allMessagesAsString) if let data = tmpNSString.data(using: String.Encoding.utf8.rawValue) { FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil) } else { throw SaveError.dataConversionFailed } } catch { NSLog("save failed") } } @IBAction func saveChat(_ sender:AnyObject) { guard let window = view.window else { return } guard let selectedContact = contactForRow(tableView.selectedRow) else { return } let savePanel = NSSavePanel() savePanel.nameFieldStringValue = selectedContact.name savePanel.beginSheetModal(for: window) { (modalResponse) -> Void in NSLog("do save at URL \(String(describing: savePanel.url))") guard let saveURL = savePanel.url else { return } self.saveContactChats(selectedContact, atURL: saveURL) } } // used as a completion block by ChatItemsFetcher // func displayChats(_ messages:[ChatItem], attachments:[ChatAttachment], matchedContacts:[ChatContact]?) { // print(__FUNCTION__) messagesListViewController?.hideAttachmentDisplayWindow() messagesListViewController?.attachmentsToDisplay = attachments messagesListViewController?.attachmentsCollectionView.reloadData() if searchTerm != nil { // Force showing detailed sender in messages list if there's a search term messagesListViewController?.showDetailedSender = true } else { messagesListViewController?.showDetailedSender = showDetailedSenderUserDefault } if messages.count > 0 { messagesListViewController?.showMessages(messages, withHighlightTerm: searchTerm) } else { messagesListViewController?.clearMessages() messagesListViewController?.clearAttachments() } if searchTermHasChanged { searchedContacts = matchedContacts?.sorted{ $0.name < $1.name } searchTermHasChanged = false tableView.reloadData() } } // recreate CoreData DB from original chats history DB // func refreshChatHistory() { let appDelegate = NSApp.delegate as! AppDelegate appDelegate.isRefreshingHistory = true setupProgressBeforeImport() guard let chatsDatabase = appDelegate.chatsDatabase else { // appDelegate.isRefreshingHistory = false return } MOCController.sharedInstance.clearAllCoreData() chatsDatabase.populate(progress, completion:{ () -> Void in self.completeImport() // MOCController.sharedInstance.save() appDelegate.isRefreshingHistory = false }) } // MARK: - progress view // hide normal UI, show progress report // func setupProgressBeforeImport() { tableView.isHidden = true messagesListViewController?.view.isHidden = true progress = Progress(totalUnitCount: 10) progressReportView.isHidden = false } // hide progress report, restore normal UI // func completeImport() { DispatchQueue.main.async { if let currentProgress = Progress.current() { currentProgress.resignCurrent() } self.progressReportView.isHidden = true self.tableView.isHidden = false self.messagesListViewController?.view.isHidden = false self.allKnownContacts = ChatContact.allKnownContacts(MOCController.sharedInstance.managedObjectContext) self.allUnknownContacts = ChatContact.allUnknownContacts(MOCController.sharedInstance.managedObjectContext) self.tableView.reloadData() } } func importMessagesFromOSXApp() { let appDelegate = NSApp.delegate as! AppDelegate appDelegate.isRefreshingHistory = true guard let chatsDatabase = appDelegate.chatsDatabase else { appDelegate.isRefreshingHistory = false return } setupProgressBeforeImport() chatsDatabase.populate(progress, completion:{ () -> Void in self.completeImport() // MOCController.sharedInstance.save() appDelegate.isRefreshingHistory = false }) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // if let newValue = change?["new"] { // print("keyPath : \(keyPath) - new value : \(newValue)") // } else { // print("observeValueForKeyPath on NSUserDefaults : no new value found") // } // probably not a good idea from a usability point of view to trigger a re-import on pref change // // refreshChatHistory() guard let newValue = change?[NSKeyValueChangeKey.newKey] as? Bool else { return } if keyPath == ShowDetailedSenderUserDefaultsKey { messagesListViewController?.showDetailedSender = newValue } else if keyPath == ShowTerseTimeUserDefaultsKey { messagesListViewController?.showTerseTime = newValue } } func setupChatDatabase() -> Bool { let appDelegate = NSApp.delegate as! AppDelegate NSLog("bookmarkDataFileURL : \(bookmarkDataFileURL)") if let urlData = try? Data(contentsOf: bookmarkDataFileURL) { var isStale = false messagesFolderURL = try? URL(resolvingBookmarkData:urlData, options:.withSecurityScope, bookmarkDataIsStale:&isStale) if let messagesFolderURL = messagesFolderURL { if messagesFolderURL.startAccessingSecurityScopedResource() { let chatDBURL = messagesFolderURL.appendingPathComponent("chat.db") do { try appDelegate.chatsDatabase = ChatsDatabase(chatsDBPath:chatDBURL.path) return true } catch let error { NSLog("DB init error : \(error)") return false } } else { NSLog("No access to \(messagesFolderURL)") return false } } else { NSLog("Couldn't resolve bookmark data") return false } } else { NSLog("No bookmarkedURL data file") return false } } }
gpl-3.0
1ba2f6d42d29d45d222c08687fbe5b26
34.468705
225
0.62876
5.816901
false
false
false
false
openbuild-sheffield/jolt
Sources/RouteAuth/class.installer.swift
1
1093
import Foundation import OpenbuildExtensionCore import OpenbuildExtensionPerfect import OpenbuildMysql import OpenbuildRepository import OpenbuildRouteRegistry import OpenbuildSingleton public class Installer: OpenbuildRouteRegistry.FactoryInstaller { override public func install() -> Bool? { print("Has Installer") do{ let repositoryAuth = try RepositoryAuth() let repositoryAuthInstall = try repositoryAuth.install() print("repositoryAuthInstall: \(repositoryAuthInstall)") let repositoryRole = try RepositoryRole() let repositoryRoleInstall = try repositoryRole.install() print("repositoryRoleInstall: \(repositoryRoleInstall)") let repositoryUserLinkRole = try RepositoryUserLinkRole() let repositoryUserLinkRoleInstall = try repositoryUserLinkRole.install() print("repositoryUserLinkRoleInstall: \(repositoryUserLinkRoleInstall)") } catch { print("ERROR: \(error)") //exit(0) } return true } }
gpl-2.0
42f7953c73e77b4dee28c84e2e8c7b2a
25.682927
84
0.684355
5.876344
false
false
false
false
AckeeCZ/ACKategories
ACKategories-iOS/ReusableView.swift
1
4626
import UIKit // swiftlint:disable force_cast extension UITableViewCell: Reusable { } extension UITableViewHeaderFooterView: Reusable { } extension UICollectionReusableView: Reusable { } private enum Keys { static var prototypeCellStorage = UInt8(0) static var prototypeSupplementaryViewsStorage = UInt8(1) } extension UITableView { /// Storage for prototype cells private var prototypeCells: [String: UITableViewCell] { get { objc_getAssociatedObject(self, &Keys.prototypeCellStorage) as? [String: UITableViewCell] ?? [:] } set { objc_setAssociatedObject(self, &Keys.prototypeCellStorage, newValue, .OBJC_ASSOCIATION_RETAIN) } } /// Dequeues `UITableViewCell` generically according to expression result type /// /// Cell doesn't need to be registered as this method registers it before use. public func dequeueCell<T>(for indexPath: IndexPath, type: T.Type = T.self) -> T where T: UITableViewCell { register(T.classForCoder(), forCellReuseIdentifier: T.reuseIdentifier) return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T } /// Get prototype cell of given type public func prototypeCell<T>(type: T.Type = T.self) -> T where T: UITableViewCell { if let prototype = prototypeCells[T.reuseIdentifier] as? T { return prototype } let prototype = T() prototypeCells[T.reuseIdentifier] = prototype return prototype } /// Dequeues `UITableViewHeaderFooterView` generically according to expression result type /// /// View doesn't need to be registered as this method registers it before use. public func dequeueHeaderFooterView<T>(type: T.Type = T.self) -> T where T: UITableViewHeaderFooterView { register(T.classForCoder(), forHeaderFooterViewReuseIdentifier: T.reuseIdentifier) return dequeueReusableHeaderFooterView(withIdentifier: T.reuseIdentifier) as! T } } extension UICollectionView { /// Storage for prototype cells private var prototypeCells: [String: UICollectionViewCell] { get { objc_getAssociatedObject(self, &Keys.prototypeCellStorage) as? [String: UICollectionViewCell] ?? [:] } set { objc_setAssociatedObject(self, &Keys.prototypeCellStorage, newValue, .OBJC_ASSOCIATION_RETAIN) } } private var prototypeSupplementaryViews: [String: UICollectionReusableView] { get { objc_getAssociatedObject(self, &Keys.prototypeSupplementaryViewsStorage) as? [String: UICollectionReusableView] ?? [:] } set { objc_setAssociatedObject(self, &Keys.prototypeSupplementaryViewsStorage, newValue, .OBJC_ASSOCIATION_RETAIN) } } /// Dequeues `UICollectionViewCell` generically according to expression result type /// /// Cell doesn't need to be registered as this method registers it before use. public func dequeueCell<T>(for indexPath: IndexPath, type: T.Type = T.self) -> T where T: UICollectionViewCell { register(T.classForCoder(), forCellWithReuseIdentifier: T.reuseIdentifier) return dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as! T } /// Get prototype cell of given type public func prototypeCell<T>(type: T.Type = T.self) -> T where T: UICollectionViewCell { if let prototype = prototypeCells[T.reuseIdentifier] as? T { return prototype } let prototype = T() prototypeCells[T.reuseIdentifier] = prototype return prototype } /// Dequeues `UICollectionReusableView` generically according to expression result type /// /// View doesn't need to be registered as this method registers it before use. public func dequeueSupplementaryView<T>(ofKind kind: String, for indexPath: IndexPath, type: T.Type = T.self) -> T where T: UICollectionReusableView { register(T.classForCoder(), forSupplementaryViewOfKind: kind, withReuseIdentifier: T.reuseIdentifier) return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: T.reuseIdentifier, for: indexPath) as! T } public func prototypeSupplementaryView<T>(ofKind kind: String, type: T.Type = T.self) -> T where T: UICollectionReusableView { let key = kind + "-" + T.reuseIdentifier if let prototype = prototypeSupplementaryViews[key] as? T { return prototype } let prototype = T() prototypeSupplementaryViews[key] = prototype return prototype } }
mit
956b222e7045f4294fe2591a555099d8
40.675676
154
0.692391
5.180291
false
false
false
false
russbishop/swift
test/expr/unary/keypath/keypath.swift
1
4510
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -parse-as-library %s -verify import ObjectiveC import Foundation // REQUIRES: objc_interop @objc class A : NSObject { @objc var propB: B = B() @objc var propString: String = "" // expected-note {{did you mean 'propString'}} @objc var propArray: [String] = [] @objc var propDict: [String: B] = [:] @objc var propSet: Set<String> = [] @objc var propNSString: NSString? @objc var propNSArray: NSArray? @objc var propNSDict: NSDictionary? @objc var propNSSet: NSSet? @objc var propAnyObject: AnyObject? @objc var ambiguous: String? // expected-note{{'ambiguous' declared here}} @objc func someMethod() { } @objc var `repeat`: String? } @objc class B : NSObject { @objc var propA: A? @objc var ambiguous: String? // expected-note{{'ambiguous' declared here}} } class C { var nonObjC: String? // expected-note{{add '@objc' to expose this var to Objective-C}}{{3-3=@objc }} } func testKeyPath(a: A, b: B) { // Property let _: String = #keyPath(A.propB) // Chained property let _: String = #keyPath(A.propB.propA) // Optional property let _: String = #keyPath(A.propB.propA.propB) // String property let _: String = #keyPath(A.propString) // Property of String property (which looks on NSString) let _: String = #keyPath(A.propString.URLsInText) // Array property (make sure we look at the array element). let _: String = #keyPath(A.propArray) let _: String = #keyPath(A.propArray.URLsInText) // Dictionary property (make sure we look at the value type). let _: String = #keyPath(A.propDict.anyKeyName) let _: String = #keyPath(A.propDict.anyKeyName.propA) // Set property (make sure we look at the set element). let _: String = #keyPath(A.propSet) let _: String = #keyPath(A.propSet.URLsInText) // AnyObject property let _: String = #keyPath(A.propAnyObject.URLsInText) let _: String = #keyPath(A.propAnyObject.propA) let _: String = #keyPath(A.propAnyObject.propB) let _: String = #keyPath(A.propAnyObject.description) // NSString property let _: String = #keyPath(A.propNSString.URLsInText) // NSArray property (AnyObject array element). let _: String = #keyPath(A.propNSArray) let _: String = #keyPath(A.propNSArray.URLsInText) // NSDictionary property (AnyObject value type). let _: String = #keyPath(A.propNSDict.anyKeyName) let _: String = #keyPath(A.propNSDict.anyKeyName.propA) // NSSet property (AnyObject set element). let _: String = #keyPath(A.propNSSet) let _: String = #keyPath(A.propNSSet.URLsInText) // Property with keyword name. let _: String = #keyPath(A.repeat) } func testAsStaticString() { let _: StaticString = #keyPath(A.propB) } func testSemanticErrors() { let _: String = #keyPath(A.blarg) // expected-error{{type 'A' has no member 'blarg'}} let _: String = #keyPath(blarg) // expected-error{{use of unresolved identifier 'blarg'}} let _: String = #keyPath(AnyObject.ambiguous) // expected-error{{ambiguous reference to member 'ambiguous'}} let _: String = #keyPath(C.nonObjC) // expected-error{{argument of '#keyPath' refers to non-'@objc' property 'nonObjC'}} let _: String = #keyPath(A.propArray.UTF8View) // expected-error{{type 'String' has no member 'UTF8View'}} let _: String = #keyPath(A.someMethod) // expected-error{{'#keyPath' cannot refer to instance method 'someMethod()'}} let _: String = #keyPath(A) // expected-error{{empty '#keyPath' does not refer to a property}} let _: String = #keyPath(A.propDict.anyKeyName.unknown) // expected-error{{type 'B' has no member 'unknown'}} let _: String = #keyPath(A.propNSDict.anyKeyName.unknown) // expected-error{{type 'AnyObject' has no member 'unknown'}} } func testParseErrors() { let _: String = #keyPath; // expected-error{{expected '(' following '#keyPath'}} let _: String = #keyPath(123; // expected-error{{expected property or type name within '#keyPath(...)'}} let _: String = #keyPath(a.123; // expected-error{{expected property or type name within '#keyPath(...)'}} let _: String = #keyPath(A(b:c:d:).propSet); // expected-error{{cannot use compound name 'A(b:c:d:)' in '#keyPath' expression}} let _: String = #keyPath(A.propString; // expected-error{{expected ')' to complete '#keyPath' expression}} // expected-note@-1{{to match this opening '('}} } func testTypoCorrection() { let _: String = #keyPath(A.proString) // expected-error {{type 'A' has no member 'proString'}} }
apache-2.0
e24a876bb3fef7fe030e6aa8df80fde4
37.887931
129
0.680044
3.640032
false
false
false
false
JakeLin/IBAnimatable
Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationLineScalePulseOut.swift
2
1738
// // Created by Tom Baranes on 21/08/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationLineScalePulseOut: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 1 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let lineSize = size.width / 9 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let beginTime = layer.currentMediaTime let beginTimes = [0.4, 0.2, 0, 0.2, 0.4] let animation = defaultAnimation // Draw lines for i in 0 ..< 5 { let line = ActivityIndicatorShape.line.makeLayer(size: CGSize(width: lineSize, height: size.height), color: color) let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height) animation.beginTime = beginTime + beginTimes[i] line.frame = frame line.add(animation, forKey: "animation") layer.addSublayer(line) } } } // MARK: - Setup private extension ActivityIndicatorAnimationLineScalePulseOut { var defaultAnimation: CAKeyframeAnimation { let timingFunction = CAMediaTimingFunction(controlPoints: 0.85, 0.25, 0.37, 0.85) let animation = CAKeyframeAnimation(keyPath: .scaleY) animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.4, 1] animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } }
mit
7796f65b3a2b2002dedab18867bedb75
28.948276
120
0.668969
4.278325
false
false
false
false
OlafAndreas/SimpleNumpad
Classes/CustomPopoverViewController.swift
1
5653
// // CustomPopoverViewController.swift // SimpleNumpad // // Created by Olaf Øvrum on 07.06.2016. // Copyright © 2016 Viking Software Solutions. All rights reserved. // import UIKit open class CustomPopoverViewController: UIViewController, UIPopoverPresentationControllerDelegate { fileprivate var viewControllerContext: UIViewController! fileprivate var contentViewController: UIViewController? open var onPopoverDismissed: (() -> ())? /*** Returns true/false depending on if the popover is visible or not. - Returns: Bool */ open var isVisible: Bool { return self.isViewLoaded && self.view.window != nil } /*** Initiates a custom popover with the viewcontroller that will present the popover. - Parameter presentingViewController: The UIViewController that will present the popover. - parameter contentViewController: Optionally provide an UIViewController that will provide the popover content. */ public convenience init(presentingViewController: UIViewController, contentViewController: UIViewController? = nil) { self.init() self.viewControllerContext = presentingViewController self.contentViewController = contentViewController if let content = contentViewController { self.addChildViewController(content) self.preferredContentSize = content.preferredContentSize } } override open func viewDidLoad() { super.viewDidLoad() self.modalPresentationStyle = .popover } /// Use this to reset the popover controller settings to default. func prepareForReuse(){ guard let controller = self.popoverPresentationController else { return } controller.permittedArrowDirections = .any controller.passthroughViews = nil controller.sourceRect = CGRect.zero controller.sourceView = nil removeContentViewController() } fileprivate func removeContentViewController(){ if let content = self.contentViewController { content.dismiss(animated: true, completion: { content.removeFromParentViewController() self.contentViewController = nil }) } } /*** Present the popover based on the given parameters. - Note: If a contentViewController was used in the init(). The popoverContentView should be nil or unwanted behaviour may occur. - Parameter popoverContentView: An UIView to be used as the popover content. Pass nil if using a contentViewController. - Parameter source: An UIView where the popover should be presented within. Optional. - Parameter sourceRect: A CGRect where the popover should be presented from. - Parameter permittedArrowDirections: Defines the permitted arrow directions. Defaults to .Any. - Parameter passThroughViews: An UIView array which contains UIView's that should be interactable during popover presentation. Optional. */ open func presentPopover(_ popoverContentView: UIView? = nil, sourceView: UIView? = nil, sourceRect: CGRect, permittedArrowDirections: UIPopoverArrowDirection = .any, passThroughViews: [UIView]? = nil){ if let content = popoverContentView { self.view.addSubview(content) self.preferredContentSize = content.frame.size } else if let content = self.contentViewController { self.view.addSubview(content.view) self.preferredContentSize = content.preferredContentSize } else { print("Unable to get content for popover. If no contentViewController is defined, there should be a popoverContentView defined in the presentPopover() call. Aborting.") return } self.viewControllerContext.present(self, animated: true, completion: nil) let controller = self.popoverPresentationController! controller.delegate = self controller.permittedArrowDirections = permittedArrowDirections controller.passthroughViews = passThroughViews controller.sourceRect = sourceRect controller.sourceView = sourceView } /*** Manually dismiss the popover by calling this. - Parameter animated: Determine whether the dismissal should be animated or not not. Defaults to true. */ open func dismissPopover(_ animated: Bool = true){ self.dismiss(animated: animated, completion: { self.onPopoverDismissed?() self.removeContentViewController() }) } open func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) { } open func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { self.onPopoverDismissed?() self.removeContentViewController() } open func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool { return true } open func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) { } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.view.superview?.layer.cornerRadius = 0 } }
mit
fdad27e58cecda1989b7ed490875be18
38.795775
223
0.689612
6.285873
false
false
false
false
iachievedit/MQTT
Sources/MQTT.swift
1
15539
// // MQTT.swift // // Original source created by Feng Lee<[email protected]> on 14/8/3 and // Copyright (c) 2015 emqtt.io MIT License. // Copyright (c) 2016 iAchieved.it 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 Foundation import swiftlog /** * MQTT Delegate */ public protocol MQTTDelegate:class { func mqtt(mqtt: MQTT, didConnect host: String, port: Int) func mqtt(mqtt: MQTT, didConnectAck ack: MQTTConnAck) func mqtt(mqtt: MQTT, didPublishMessage message: MQTTMessage, id: UInt16) func mqtt(mqtt: MQTT, didPublishAck id: UInt16) func mqtt(mqtt: MQTT, didReceiveMessage message: MQTTMessage, id: UInt16 ) func mqtt(mqtt: MQTT, didSubscribeTopic topic: String) func mqtt(mqtt: MQTT, didUnsubscribeTopic topic: String) func mqttDidPing(mqtt: MQTT) func mqttDidReceivePong(mqtt: MQTT) func mqttDidDisconnect(mqtt: MQTT, withError err: NSError?) } /** * Blueprint of the MQTT client */ public protocol MQTTClient { var host: String { get set } var port: UInt16 { get set } var clientId: String { get } var username: String? {get set} var password: String? {get set} var secureMQTT: Bool {get set} var cleanSess: Bool {get set} var keepAlive: UInt16 {get set} var willMessage: MQTTWill? {get set} func connect() -> Bool func publish(topic: String, withString string: String, qos: MQTTQOS, retained: Bool, dup: Bool) -> UInt16 func publish(message: MQTTMessage) -> UInt16 func subscribe(topic: String, qos: MQTTQOS) -> UInt16 func unsubscribe(topic: String) -> UInt16 func ping() func disconnect() } public enum MQTTQOS: UInt8 { case QOS0 = 0 case QOS1 case QOS2 } /** * Connection State */ public enum MQTTConnState: UInt8 { case INIT = 0 case CONNECTING case CONNECTED case DISCONNECTED } /** * Conn Ack */ public enum MQTTConnAck: UInt8 { case ACCEPT = 0 case PROTO_VER case INVALID_ID case SERVER case CREDENTIALS case AUTH } /** * asyncsocket read tag */ enum MQTTReadTag: Int { case TAG_HEADER = 0 case TAG_LENGTH case TAG_PAYLOAD } /** * Main MQTT Class */ public class MQTT: NSObject, MQTTClient, MQTTReaderDelegate, AsyncSocketDelegate { public var host = "localhost" public var port: UInt16 = 1883 public var clientId: String public var username: String? public var password: String? public var secureMQTT: Bool = false public var backgroundOnSocket: Bool = false public var cleanSess: Bool = true //keep alive public var keepAlive: UInt16 = 60 var aliveTimer:Timer? //will message public var willMessage: MQTTWill? //delegate weak?? public weak var delegate: MQTTDelegate? //socket and connection public var connState = MQTTConnState.INIT var socket: AsyncSocket? var reader: MQTTReader? //global message id var gmid: UInt16 = 1 //subscribed topics var subscriptions = Dictionary<UInt16, String>() //published messages public var messages = Dictionary<UInt16, MQTTMessage>() public init(clientId: String, host: String = "localhost", port: UInt16 = 1883) { self.clientId = clientId self.host = host self.port = port } // API Functions public func connect() -> Bool { self.socket = AsyncSocket(host:self.host, port:self.port, delegate:self, secure:secureMQTT) reader = MQTTReader(socket: socket!, delegate: self) do { try socket!.connect() connState = MQTTConnState.CONNECTING return true } catch { SLogVerbose("MQTT: socket connect error") return false } } public func publish(topic: String, withString string: String, qos: MQTTQOS = .QOS1, retained: Bool = false, dup: Bool = false) -> UInt16 { let message = MQTTMessage(topic: topic, string: string, qos: qos, retained: retained, dup: dup) return publish(message:message) } public func publish(message: MQTTMessage) -> UInt16 { let msgId: UInt16 = _nextMessageId() let frame = MQTTFramePublish(msgid: msgId, topic: message.topic, payload: message.payload) frame.qos = message.qos.rawValue frame.retained = message.retained frame.dup = message.dup send(frame:frame, tag: Int(msgId)) if message.qos != MQTTQOS.QOS0 { messages[msgId] = message //cache } delegate?.mqtt(mqtt:self, didPublishMessage: message, id: msgId) return msgId } public func subscribe(topic: String, qos: MQTTQOS = .QOS1) -> UInt16 { let msgId = _nextMessageId() let frame = MQTTFrameSubscribe(msgid: msgId, topic: topic, reqos: qos.rawValue) send(frame:frame, tag: Int(msgId)) subscriptions[msgId] = topic //cache? return msgId } public func unsubscribe(topic: String) -> UInt16 { let msgId = _nextMessageId() let frame = MQTTFrameUnsubscribe(msgid: msgId, topic: topic) subscriptions[msgId] = topic //cache send(frame:frame, tag: Int(msgId)) return msgId } public func ping() { send(frame:MQTTFrame(type: MQTTFrameType.PINGREQ), tag: -0xC0) self.delegate?.mqttDidPing(mqtt:self) } public func disconnect() { send(frame:MQTTFrame(type: MQTTFrameType.DISCONNECT), tag: -0xE0) self.socket?.disconnect() } func send(frame: MQTTFrame, tag: Int = 0) { let data = frame.data() self.socket?.writeData(data:NSData(bytes: data, length: data.count), withTimeout: -1, tag: tag) } func sendConnectFrame() { let frame = MQTTFrameConnect(client: self) send(frame:frame) reader!.start() delegate?.mqtt(mqtt:self, didConnect: host, port: Int(port)) } //AsyncSocket Delegate public func socket(socket: AsyncSocket, didConnectToHost host: String, port: UInt16) { SLogVerbose("MQTT: connected to \(host) : \(port)") /* if secureMQTT { #if DEBUG sock.startTLS(["AsyncSocketManuallyEvaluateTrust": true, kCFStreamSSLPeerName: self.host]) #else sock.startTLS([kCFStreamSSLPeerName: self.host]) #endif } else { */ sendConnectFrame() } /* public func socket(sock: AsyncSocket!, didReceiveTrust trust: SecTrust!, completionHandler: ((Bool) -> Void)!) { #if DEBUG NSLog("MQTT: didReceiveTrust") #endif completionHandler(true) } */ /* public func socketDidSecure(sock: AsyncSocket!) { #if DEBUG NSLog("MQTT: socketDidSecure") #endif sendConnectFrame() } */ public func socket(socket: AsyncSocket, didWriteDataWithTag tag: Int) { SLogVerbose("MQTT: Socket write message with tag: \(tag)") } public func socket(socket: AsyncSocket, didReadData data: NSData!, withTag tag: Int) { let etag: MQTTReadTag = MQTTReadTag(rawValue: tag)! var bytes = [UInt8]([0]) switch etag { case MQTTReadTag.TAG_HEADER: data.getBytes(&bytes, length: 1) reader!.headerReady(header:bytes[0]) case MQTTReadTag.TAG_LENGTH: data.getBytes(&bytes, length: 1) reader!.lengthReady(byte:bytes[0]) case MQTTReadTag.TAG_PAYLOAD: reader!.payloadReady(data:data) } } public func socketDidDisconnect(socket:AsyncSocket, withError err: NSError!) { connState = MQTTConnState.DISCONNECTED delegate?.mqttDidDisconnect(mqtt:self, withError: err) } //MQTTReader Delegate public func didReceiveConnAck(reader: MQTTReader, connack: UInt8) { connState = MQTTConnState.CONNECTED SLogVerbose("MQTT: CONNACK Received: \(connack)") let ack = MQTTConnAck(rawValue: connack)! delegate?.mqtt(mqtt:self, didConnectAck: ack) if ack == MQTTConnAck.ACCEPT && keepAlive > 0 { SLogVerbose("MQTT: Set keepAlive for \(keepAlive) seconds") let keepAliveThread = Thread(){ SLogVerbose("MQTT: keepAlive thread started") self.aliveTimer = Timer.scheduledTimer(withTimeInterval:TimeInterval(self.keepAlive), repeats:true){ timer in SLogVerbose("MQTT: KeepAlive timer fired") if self.connState == MQTTConnState.CONNECTED { self.ping() } else { self.aliveTimer?.invalidate() } } SLogVerbose("MQTT: Adding timer to run loop") RunLoop.current().add(self.aliveTimer!, forMode:RunLoopMode.defaultRunLoopMode) RunLoop.current().run() } SLogVerbose("MQTT: Starting keepAlive thread") keepAliveThread.start() } } func didReceivePublish(reader: MQTTReader, message: MQTTMessage, id: UInt16) { SLogVerbose("MQTT: PUBLISH Received from \(message.topic)") delegate?.mqtt(mqtt:self, didReceiveMessage: message, id: id) if message.qos == MQTTQOS.QOS1 { _puback(type:MQTTFrameType.PUBACK, msgid: id) } else if message.qos == MQTTQOS.QOS2 { _puback(type:MQTTFrameType.PUBREC, msgid: id) } } func _puback(type: MQTTFrameType, msgid: UInt16) { var descr: String? switch type { case .PUBACK: descr = "PUBACK" case .PUBREC: descr = "PUBREC" case .PUBREL: descr = "PUBREL" case .PUBCOMP: descr = "PUBCOMP" default: assert(false) } if descr != nil { SLogVerbose("MQTT: Send \(descr!), msgid: \(msgid)") } send(frame:MQTTFramePubAck(type: type, msgid: msgid)) } func didReceivePubAck(reader: MQTTReader, msgid: UInt16) { SLogVerbose("MQTT: PUBACK Received: \(msgid)") messages.removeValue(forKey:msgid) delegate?.mqtt(mqtt:self, didPublishAck: msgid) } func didReceivePubRec(reader: MQTTReader, msgid: UInt16) { SLogVerbose("MQTT: PUBREC Received: \(msgid)") _puback(type:MQTTFrameType.PUBREL, msgid: msgid) } func didReceivePubRel(reader: MQTTReader, msgid: UInt16) { SLogVerbose("MQTT: PUBREL Received: \(msgid)") if let message = messages[msgid] { messages.removeValue(forKey:msgid) delegate?.mqtt(mqtt:self, didPublishMessage: message, id: msgid) } _puback(type:MQTTFrameType.PUBCOMP, msgid: msgid) } func didReceivePubComp(reader: MQTTReader, msgid: UInt16) { SLogVerbose("MQTT: PUBCOMP Received: \(msgid)") } func didReceiveSubAck(reader: MQTTReader, msgid: UInt16) { SLogVerbose("MQTT: SUBACK Received: \(msgid)") if let topic = subscriptions.removeValue(forKey:msgid) { delegate?.mqtt(mqtt:self, didSubscribeTopic: topic) } } func didReceiveUnsubAck(reader: MQTTReader, msgid: UInt16) { SLogVerbose("MQTT: UNSUBACK Received: \(msgid)") if let topic = subscriptions.removeValue(forKey:msgid) { delegate?.mqtt(mqtt:self, didUnsubscribeTopic: topic) } } func didReceivePong(reader: MQTTReader) { SLogVerbose("MQTT: PONG Received") delegate?.mqttDidReceivePong(mqtt:self) } func _nextMessageId() -> UInt16 { self.gmid += 1 let id = self.gmid if id >= UInt16.max { self.gmid = 1 } return id } } /** * MQTT Reader Delegate */ protocol MQTTReaderDelegate { func didReceiveConnAck(reader: MQTTReader, connack: UInt8) func didReceivePublish(reader: MQTTReader, message: MQTTMessage, id: UInt16) func didReceivePubAck(reader: MQTTReader, msgid: UInt16) func didReceivePubRec(reader: MQTTReader, msgid: UInt16) func didReceivePubRel(reader: MQTTReader, msgid: UInt16) func didReceivePubComp(reader: MQTTReader, msgid: UInt16) func didReceiveSubAck(reader: MQTTReader, msgid: UInt16) func didReceiveUnsubAck(reader: MQTTReader, msgid: UInt16) func didReceivePong(reader: MQTTReader) } public class MQTTReader { var socket: AsyncSocket var header: UInt8 = 0 var data: [UInt8] = [] var length: UInt = 0 var multiply: Int = 1 var delegate: MQTTReaderDelegate var timeout: Int = 30000 init(socket: AsyncSocket, delegate: MQTTReaderDelegate) { self.socket = socket self.delegate = delegate } func start() { readHeader() } func readHeader() { ENTRY_LOG() _reset(); socket.readDataToLength(length:1, withTimeout: -1, tag: MQTTReadTag.TAG_HEADER.rawValue) } func headerReady(header: UInt8) { SLogVerbose("MQTTReader: header ready: \(header) ") self.header = header readLength() } func readLength() { ENTRY_LOG() socket.readDataToLength(length:1, withTimeout:TimeInterval(timeout), tag: MQTTReadTag.TAG_LENGTH.rawValue) } func lengthReady(byte: UInt8) { length += (UInt)((Int)(byte & 127) * multiply) if byte & 0x80 == 0 { //done if length == 0 { frameReady() } else { readPayload() } } else { //more multiply *= 128 readLength() } } func readPayload() { ENTRY_LOG() socket.readDataToLength(length:length, withTimeout:TimeInterval(timeout), tag: MQTTReadTag.TAG_PAYLOAD.rawValue) } func payloadReady(data: NSData) { self.data = [UInt8](repeating:0, count: data.length) data.getBytes(&(self.data), length: data.length) frameReady() } func frameReady() { //handle frame let frameType = MQTTFrameType(rawValue: UInt8(header & 0xF0))! switch frameType { case .CONNACK: delegate.didReceiveConnAck(reader:self, connack: data[1]) case .PUBLISH: let (msgId, message) = unpackPublish() delegate.didReceivePublish(reader:self, message: message, id: msgId) case .PUBACK: delegate.didReceivePubAck(reader:self, msgid: _msgid(bytes:data)) case .PUBREC: delegate.didReceivePubRec(reader:self, msgid: _msgid(bytes:data)) case .PUBREL: delegate.didReceivePubRel(reader:self, msgid: _msgid(bytes:data)) case .PUBCOMP: delegate.didReceivePubComp(reader:self, msgid: _msgid(bytes:data)) case .SUBACK: delegate.didReceiveSubAck(reader:self, msgid: _msgid(bytes:data)) case .UNSUBACK: delegate.didReceiveUnsubAck(reader:self, msgid: _msgid(bytes:data)) case .PINGRESP: delegate.didReceivePong(reader:self) default: assert(false) } readHeader() } func unpackPublish() -> (UInt16, MQTTMessage) { let frame = MQTTFramePublish(header: header, data: data) frame.unpack() let msgId = frame.msgid! let qos = MQTTQOS(rawValue: frame.qos)! let message = MQTTMessage(topic: frame.topic!, payload: frame.payload, qos: qos, retained: frame.retained, dup: frame.dup) return (msgId, message) } func _msgid(bytes: [UInt8]) -> UInt16 { if bytes.count < 2 { return 0 } return UInt16(bytes[0]) << 8 + UInt16(bytes[1]) } func _reset() { length = 0; multiply = 1; header = 0; data = [] } }
mit
737f663a248a7ec81be191a4a655f7f0
28.598095
140
0.674303
3.958981
false
false
false
false
yanfeng0107/ios-charts
Charts/Classes/Renderers/ChartYAxisRendererHorizontalBarChart.swift
42
10944
// // ChartYAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/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 CoreGraphics import UIKit public class ChartYAxisRendererHorizontalBarChart: ChartYAxisRenderer { public override init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: transformer) } /// Computes the axis values. public override func computeAxis(var #yMin: Double, var yMax: Double) { // calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds) if (viewPortHandler.contentHeight > 10.0 && !viewPortHandler.isFullyZoomedOutX) { var p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) var p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) if (!_yAxis.isInverted) { yMin = Double(p1.x) yMax = Double(p2.x) } else { yMin = Double(p2.x) yMax = Double(p1.x) } } computeAxisValues(min: yMin, max: yMax) } /// draws the y-axis labels to the screen public override func renderAxisLabels(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.isDrawLabelsEnabled) { return } var positions = [CGPoint]() positions.reserveCapacity(_yAxis.entries.count) for (var i = 0; i < _yAxis.entries.count; i++) { positions.append(CGPoint(x: CGFloat(_yAxis.entries[i]), y: 0.0)) } transformer.pointValuesToPixel(&positions) var lineHeight = _yAxis.labelFont.lineHeight var baseYOffset: CGFloat = 2.5 var dependency = _yAxis.axisDependency var labelPosition = _yAxis.labelPosition var yPos: CGFloat = 0.0 if (dependency == .Left) { if (labelPosition == .OutsideChart) { yPos = viewPortHandler.contentTop - baseYOffset } else { yPos = viewPortHandler.contentTop - baseYOffset } } else { if (labelPosition == .OutsideChart) { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } else { yPos = viewPortHandler.contentBottom + lineHeight + baseYOffset } } // For compatibility with Android code, we keep above calculation the same, // And here we pull the line back up yPos -= lineHeight drawYLabels(context: context, fixedPosition: yPos, positions: positions, offset: _yAxis.yOffset) } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.drawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, _yAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, _yAxis.axisLineWidth) if (_yAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _yAxis.axisLineDashPhase, _yAxis.axisLineDashLengths, _yAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (_yAxis.axisDependency == .Left) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } else { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } /// draws the y-labels on the specified x-position internal func drawYLabels(#context: CGContext, fixedPosition: CGFloat, positions: [CGPoint], offset: CGFloat) { var labelFont = _yAxis.labelFont var labelTextColor = _yAxis.labelTextColor for (var i = 0; i < _yAxis.entryCount; i++) { var text = _yAxis.getFormattedLabel(i) if (!_yAxis.isDrawTopYLabelEntryEnabled && i >= _yAxis.entryCount - 1) { return } ChartUtils.drawText(context: context, text: text, point: CGPoint(x: positions[i].x, y: fixedPosition - offset), align: .Center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]) } } public override func renderGridLines(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.isDrawGridLinesEnabled) { return } CGContextSaveGState(context) // pre alloc var position = CGPoint() CGContextSetStrokeColorWithColor(context, _yAxis.gridColor.CGColor) CGContextSetLineWidth(context, _yAxis.gridLineWidth) if (_yAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _yAxis.gridLineDashPhase, _yAxis.gridLineDashLengths, _yAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } // draw the horizontal grid for (var i = 0; i < _yAxis.entryCount; i++) { position.x = CGFloat(_yAxis.entries[i]) position.y = 0.0 transformer.pointValueToPixel(&position) CGContextBeginPath(context) CGContextMoveToPoint(context, position.x, viewPortHandler.contentTop) CGContextAddLineToPoint(context, position.x, viewPortHandler.contentBottom) CGContextStrokePath(context) } CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderLimitLines(#context: CGContext) { var limitLines = _yAxis.limitLines if (limitLines.count <= 0) { return } CGContextSaveGState(context) var trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i] position.x = CGFloat(l.limit) position.y = 0.0 position = CGPointApplyAffineTransform(position, trans) _limitLineSegmentsBuffer[0].x = position.x _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop _limitLineSegmentsBuffer[1].x = position.x _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor) CGContextSetLineWidth(context, l.lineWidth) if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) var label = l.label // if drawing the limit-value label is enabled if (count(label) > 0) { var labelLineHeight = l.valueFont.lineHeight let add = CGFloat(4.0) var xOffset: CGFloat = l.lineWidth var yOffset: CGFloat = add / 2.0 if (l.labelPosition == .RightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .RightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else if (l.labelPosition == .LeftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentTop + yOffset), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]) } } } CGContextRestoreGState(context) } }
apache-2.0
468f4168d627aeb12efd4e583ca168a6
35.003289
233
0.556652
5.790476
false
false
false
false
HongliYu/DPSlideMenuKit-Swift
DPSlideMenuKitDemo/DPSlideMenuKit/Right/DPRightPageViewController.swift
1
5569
// // DPRightPageViewController.swift // DPSlideMenuKitDemo // // Created by Hongli Yu on 10/07/2017. // Copyright © 2017 Hongli Yu. All rights reserved. // import UIKit public class DPRightPageViewController: UIPageViewController { var transitionCompleted:((_ index: Int)->Void)? private(set) var rightContentViewControllers: [DPRightContentViewController]? public func setContentViewControllers(_ rightContentViewControllers: [DPRightContentViewController]) { self.rightContentViewControllers = rightContentViewControllers } override public func viewDidLoad() { super.viewDidLoad() self.basicUI() } private func basicUI() { guard let rightContentViewControllers = rightContentViewControllers, rightContentViewControllers.count > 0 else { return } delegate = self dataSource = self view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - kDPDrawerControllerDrawerWidthGapOffset, height: view.bounds.height) if rightContentViewControllers.count == 1 { for view in view.subviews { if let scrollView = view as? UIScrollView { scrollView.bounces = false } } } setViewControllers([rightContentViewControllers[0]], direction: .reverse, animated: false, completion: nil) } private func resetUI() { view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - kDPDrawerControllerDrawerWidthGapOffset, height: view.bounds.height) } public func scrollToViewController(index newIndex: Int) { guard let rightContentViewControllers = rightContentViewControllers, let firstViewController = viewControllers?.first as? DPRightContentViewController, let currentIndex = rightContentViewControllers.firstIndex(of: firstViewController) else { return } let direction: UIPageViewController.NavigationDirection = (newIndex >= currentIndex) ? .forward : .reverse let nextViewController = rightContentViewControllers[newIndex] scrollToViewController(nextViewController, direction: direction) } public func scrollToViewController(_ viewController: UIViewController, direction: UIPageViewController.NavigationDirection = .forward) { setViewControllers([viewController], direction: direction, animated: true, completion: { [weak self](finished) -> Void in guard let strongSelf = self else { return } guard let firstViewController = strongSelf.viewControllers?.first as? DPRightContentViewController, let rightContentViewControllers = strongSelf.rightContentViewControllers, let index = rightContentViewControllers.firstIndex(of: firstViewController) else { return } strongSelf.transitionCompleted?(index) }) } } extension DPRightPageViewController: UIPageViewControllerDataSource { public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let rightContentViewControllers = rightContentViewControllers, rightContentViewControllers.count >= 2, let viewController = viewController as? DPRightContentViewController, let firstIndex = rightContentViewControllers.firstIndex(of: viewController) else { return nil } let nextIndex = firstIndex + 1 let orderedViewControllersCount = rightContentViewControllers.count // User is on the last view controller and swiped right to loop to // the first view controller. guard orderedViewControllersCount != nextIndex else { return rightContentViewControllers.first } guard orderedViewControllersCount > nextIndex else { return nil } return rightContentViewControllers[nextIndex] } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let rightContentViewControllers = rightContentViewControllers, rightContentViewControllers.count >= 2, let viewController = viewController as? DPRightContentViewController, let firstIndex = rightContentViewControllers.firstIndex(of: viewController) else { return nil } let previousIndex = firstIndex - 1 // User is on the first view controller and swiped left to loop to // the last view controller. guard previousIndex >= 0 else { return rightContentViewControllers.last } guard rightContentViewControllers.count > previousIndex else { return nil } return rightContentViewControllers[previousIndex] } } extension DPRightPageViewController: UIPageViewControllerDelegate { public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if let pendingViewController = pageViewController.viewControllers?.first as? DPRightContentViewController, let rightContentViewControllers = rightContentViewControllers, let index = rightContentViewControllers.firstIndex(of: pendingViewController) { if completed { self.transitionCompleted?(index) } } } }
mit
01acd2abb10f142b618452d76501072d
38.771429
110
0.70546
6.341686
false
false
false
false
gontovnik/DGElasticPullToRefresh
DGElasticPullToRefreshExample/ViewController.swift
1
3243
// // ViewController.swift // DGElasticPullToRefreshExample // // Created by Danil Gontovnik on 10/2/15. // Copyright © 2015 Danil Gontovnik. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - // MARK: Vars fileprivate var tableView: UITableView! // MARK: - override func loadView() { super.loadView() navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.barTintColor = UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0) tableView = UITableView(frame: view.bounds, style: .plain) tableView.dataSource = self tableView.delegate = self tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.separatorColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 231/255.0, alpha: 1.0) tableView.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 251/255.0, alpha: 1.0) view.addSubview(tableView) let loadingView = DGElasticPullToRefreshLoadingViewCircle() loadingView.tintColor = UIColor(red: 78/255.0, green: 221/255.0, blue: 200/255.0, alpha: 1.0) tableView.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: { self?.tableView.dg_stopLoading() }) }, loadingView: loadingView) tableView.dg_setPullToRefreshFillColor(UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0)) tableView.dg_setPullToRefreshBackgroundColor(tableView.backgroundColor!) } deinit { tableView.dg_removePullToRefresh() } } // MARK: - // MARK: UITableView Data Source extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "cellIdentifier" var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier) cell!.contentView.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 251/255.0, alpha: 1.0) } if let cell = cell { cell.textLabel?.text = "\((indexPath as NSIndexPath).row)" return cell } return UITableViewCell() } } // MARK: - // MARK: UITableView Delegate extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
mit
f057660030612681df03abc2e91b1683
33.489362
149
0.649291
4.521618
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Profile/Controller/FishboneRechargeViewController.swift
1
4276
// // FishboneRechargeViewController.swift // DYZB // // Created by xiudou on 2017/7/4. // Copyright © 2017年 xiudo. All rights reserved. // import UIKit fileprivate let columns : CGFloat = 3 fileprivate let leftMargin : CGFloat = 15 fileprivate let rightMargin : CGFloat = leftMargin fileprivate let centerMargin : CGFloat = 20 fileprivate let FishboneRechargeCellIdentifier = "FishboneRechargeCellIdentifier" class FishboneRechargeViewController: UIViewController { fileprivate lazy var fishboneRechargeVM : FishboneRechargeVM = FishboneRechargeVM() fileprivate lazy var fishboneRechargBottomView : FishboneRechargBottomView = FishboneRechargBottomView() fileprivate lazy var collectionView : UICollectionView = { // 设置layout属性 let layout = UICollectionViewFlowLayout() let width = (sScreenW - leftMargin - rightMargin - (columns - 1 ) * centerMargin) / columns layout.itemSize = CGSize(width: width, height: width) layout.minimumInteritemSpacing = centerMargin layout.minimumLineSpacing = 20 // 创建UICollectionView let collectionView = UICollectionView(frame: CGRect(x: 0, y:sStatusBarH + sNavatationBarH + 40, width: sScreenW, height: sScreenH - (sStatusBarH + sNavatationBarH + 40)), collectionViewLayout: layout) collectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) // 设置数据源 collectionView.delegate = self collectionView.dataSource = self collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = UIColor(r: 231, g: 231, b: 231) // 注册cell collectionView.register(FishboneRechargeCell.self, forCellWithReuseIdentifier: FishboneRechargeCellIdentifier) return collectionView; }() override func viewDidLoad() { super.viewDidLoad() title = "鱼刺充值" view.backgroundColor = UIColor.white view.addSubview(collectionView) view.addSubview(fishboneRechargBottomView) fishboneRechargBottomView.frame = CGRect(x: 0, y: sScreenH - 100 - 20, width: sScreenW, height: 100) stupData() } } extension FishboneRechargeViewController { func stupData(){ fishboneRechargeVM.loadFishboneRechargeDatas({ self.collectionView.reloadData() }, { (message) in }) { } } } extension FishboneRechargeViewController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return fishboneRechargeVM.fishboneRechargeBigModel.fishboneRechargeModelArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FishboneRechargeCellIdentifier, for: indexPath) as! FishboneRechargeCell let fishboneRechargeModel = fishboneRechargeVM.fishboneRechargeBigModel.fishboneRechargeModelArray[indexPath.item] cell.fishboneRechargeModel = fishboneRechargeModel if fishboneRechargeModel.default_select == "1" { fishboneRechargBottomView.fishboneRechargeModel = fishboneRechargeModel } return cell } } extension FishboneRechargeViewController : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){ guard let cell = collectionView.cellForItem(at: indexPath) as? FishboneRechargeCell else { return } let cells = collectionView.visibleCells as! [FishboneRechargeCell] for cell in cells{ cell.boderView.isHidden = true } let fishboneRechargeModel = fishboneRechargeVM.fishboneRechargeBigModel.fishboneRechargeModelArray[indexPath.item] cell.didSelectedModelAction(fishboneRechargeModel) fishboneRechargBottomView.fishboneRechargeModel = fishboneRechargeModel } }
mit
8daf835752b6cbb1b39faa609cc1ef1b
37.536364
208
0.705591
5.895688
false
false
false
false
maxbritto/cours-ios11-swift4
Maitriser/Objectif Telechargement/Safety First/Safety First/Model/CredentialsManager.swift
2
1353
// // CredentialsManager.swift // Safety First // // Created by Maxime Britto on 05/09/2017. // Copyright © 2017 Maxime Britto. All rights reserved. // import Foundation import RealmSwift class CredentialsManager { private let _realm:Realm private let _credentialList:Results<Credentials> init() { _realm = try! Realm() _credentialList = _realm.objects(Credentials.self) } func addCredentials(title:String, login:String, password:String, url:String) -> Credentials { let newCredential = Credentials() newCredential.title = title newCredential.login = login newCredential.password = password newCredential.url = url try? _realm.write { _realm.add(newCredential) } return newCredential } func getCredentialCount() -> Int { return _credentialList.count } func getCredential(atIndex index:Int) -> Credentials? { guard index >= 0 && index < getCredentialCount() else { return nil } return _credentialList[index] } func deleteCredential(atIndex index:Int) { if let credToDelete = getCredential(atIndex: index) { try? _realm.write { _realm.delete(credToDelete) } } } }
apache-2.0
c8f1405e514feda7ae9f13fdf631c709
22.310345
97
0.597633
4.646048
false
false
false
false
benlangmuir/swift
test/IDE/complete_actorisolation.swift
9
7888
// REQUIRES: concurrency // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t -warn-concurrency class MyNonSendable {} struct MySendable {} actor MyActor { var property: Int func syncFunc() -> Int { 1 } func syncNonSendable(arg: MyNonSendable) -> Int { 1 } func syncSendable(arg: MySendable) -> Int { 1 } func asyncFunc() async -> Int { 1 } subscript(idx: Int) -> Int { get { 1 } set { } } } extension MyActor { func testSyncFunc(other: MyActor) { let _ = #^IN_SYNCFUNC^# // IN_SYNCFUNC: Begin completions // IN_SYNCFUNC-DAG: Decl[InstanceVar]/CurrNominal: property[#Int#]; // IN_SYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal: syncFunc()[#Int#]; // IN_SYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal: syncNonSendable({#arg: MyNonSendable#})[#Int#]; // IN_SYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal: syncSendable({#arg: MySendable#})[#Int#]; // IN_SYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: asyncFunc()[' async'][#Int#]; // IN_SYNCFUNC: End completions let _ = self.#^IN_SYNCFUNC_SELF_DOT^# // IN_SYNCFUNC_SELF_DOT: Begin completions // IN_SYNCFUNC_SELF_DOT-DAG: Decl[InstanceVar]/CurrNominal: property[#Int#]; // IN_SYNCFUNC_SELF_DOT-DAG: Decl[InstanceMethod]/CurrNominal: syncFunc()[#Int#]; // IN_SYNCFUNC_SELF_DOT-DAG: Decl[InstanceMethod]/CurrNominal: syncNonSendable({#arg: MyNonSendable#})[#Int#]; // IN_SYNCFUNC_SELF_DOT-DAG: Decl[InstanceMethod]/CurrNominal: syncSendable({#arg: MySendable#})[#Int#]; // IN_SYNCFUNC_SELF_DOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: asyncFunc()[' async'][#Int#]; // IN_SYNCFUNC_SELF_DOT-DAG: End completions let _ = self#^IN_SYNCFUNC_SELF_NODOT^# // IN_SYNCFUNC_SELF_NODOT: Begin completions // IN_SYNCFUNC_SELF_NODOT-DAG: Decl[InstanceVar]/CurrNominal: .property[#Int#]; // IN_SYNCFUNC_SELF_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .syncFunc()[#Int#]; // IN_SYNCFUNC_SELF_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .syncNonSendable({#arg: MyNonSendable#})[#Int#]; // IN_SYNCFUNC_SELF_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .syncSendable({#arg: MySendable#})[#Int#]; // IN_SYNCFUNC_SELF_NODOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: .asyncFunc()[' async'][#Int#]; // IN_SYNCFUNC_SELF_NODOT-DAG: Decl[Subscript]/CurrNominal: [{#(idx): Int#}][#Int#]; // IN_SYNCFUNC_SELF_NODOT-DAG: End completions let _ = other.#^IN_SYNCFUNC_OTHER_DOT^# // IN_SYNCFUNC_OTHER_DOT: Begin completions // IN_SYNCFUNC_OTHER_DOT-DAG: Decl[InstanceVar]/CurrNominal/NotRecommended: property[#Int#][' async']; // IN_SYNCFUNC_OTHER_DOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: syncFunc()[' async'][#Int#]; // IN_SYNCFUNC_OTHER_DOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: syncNonSendable({#arg: MyNonSendable#})[' async'][#Int#]; // IN_SYNCFUNC_OTHER_DOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: syncSendable({#arg: MySendable#})[' async'][#Int#]; // IN_SYNCFUNC_OTHER_DOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: asyncFunc()[' async'][#Int#]; // IN_SYNCFUNC_OTHER_DOT: End completions let _ = other#^IN_SYNCFUNC_OTHER_NODOT^# // IN_SYNCFUNC_OTHER_NODOT: Begin completions // IN_SYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceVar]/CurrNominal/NotRecommended: .property[#Int#][' async']; // IN_SYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: .syncFunc()[' async'][#Int#]; // IN_SYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: .syncNonSendable({#arg: MyNonSendable#})[' async'][#Int#]; // IN_SYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: .syncSendable({#arg: MySendable#})[' async'][#Int#]; // IN_SYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: .asyncFunc()[' async'][#Int#]; // IN_SYNCFUNC_OTHER_NODOT-DAG: Decl[Subscript]/CurrNominal/NotRecommended: [{#(idx): Int#}][' async'][#Int#]; // IN_SYNCFUNC_OTHER_NODOT: End completions } func testAsyncFunc(other: MyActor) async { let _ = #^IN_ASYNCFUNC^# // IN_ASYNCFUNC: Begin completions // IN_ASYNCFUNC-DAG: Decl[InstanceVar]/CurrNominal: property[#Int#]; // IN_ASYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal: syncFunc()[#Int#]; // IN_ASYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal: syncNonSendable({#arg: MyNonSendable#})[#Int#]; // IN_ASYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal: syncSendable({#arg: MySendable#})[#Int#]; // IN_ASYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal: asyncFunc()[' async'][#Int#]; // IN_ASYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal: testSyncFunc({#other: MyActor#})[#Void#]; // IN_ASYNCFUNC-DAG: Decl[InstanceMethod]/CurrNominal: testAsyncFunc({#other: MyActor#})[' async'][#Void#]; // IN_ASYNCFUNC: End completions let _ = self.#^IN_ASYNCFUNC_SELF_DOT^# // IN_ASYNCFUNC_SELF_DOT: Begin completions // IN_ASYNCFUNC_SELF_DOT-DAG: Decl[InstanceVar]/CurrNominal: property[#Int#]; // IN_ASYNCFUNC_SELF_DOT-DAG: Decl[InstanceMethod]/CurrNominal: syncFunc()[#Int#]; // IN_ASYNCFUNC_SELF_DOT-DAG: Decl[InstanceMethod]/CurrNominal: syncNonSendable({#arg: MyNonSendable#})[#Int#]; // IN_ASYNCFUNC_SELF_DOT-DAG: Decl[InstanceMethod]/CurrNominal: syncSendable({#arg: MySendable#})[#Int#]; // IN_ASYNCFUNC_SELF_DOT-DAG: Decl[InstanceMethod]/CurrNominal: asyncFunc()[' async'][#Int#]; // IN_ASYNCFUNC_SELF_DOT: End completions let _ = self#^IN_ASYNCFUNC_SELF_NODOT^# // IN_ASYNCFUNC_SELF_NODOT: Begin completions // IN_ASYNCFUNC_SELF_NODOT-DAG: Decl[InstanceVar]/CurrNominal: .property[#Int#]; // IN_ASYNCFUNC_SELF_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .syncFunc()[#Int#]; // IN_ASYNCFUNC_SELF_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .syncNonSendable({#arg: MyNonSendable#})[#Int#]; // IN_ASYNCFUNC_SELF_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .syncSendable({#arg: MySendable#})[#Int#]; // IN_ASYNCFUNC_SELF_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .asyncFunc()[' async'][#Int#]; // IN_ASYNCFUNC_SELF_NODOT-DAG: Decl[Subscript]/CurrNominal: [{#(idx): Int#}][#Int#]; // IN_ASYNCFUNC_SELF_NODOT-DAG: End completions let _ = other.#^IN_ASYNCFUNC_OTHER_DOT^# // IN_ASYNCFUNC_OTHER_DOT: Begin completions // IN_ASYNCFUNC_OTHER_DOT-DAG: Decl[InstanceVar]/CurrNominal: property[#Int#][' async']; // IN_ASYNCFUNC_OTHER_DOT-DAG: Decl[InstanceMethod]/CurrNominal: syncFunc()[' async'][#Int#]; // IN_ASYNCFUNC_OTHER_DOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: syncNonSendable({#arg: MyNonSendable#})[' async'][#Int#]; // IN_ASYNCFUNC_OTHER_DOT-DAG: Decl[InstanceMethod]/CurrNominal: syncSendable({#arg: MySendable#})[' async'][#Int#]; // IN_ASYNCFUNC_OTHER_DOT-DAG: Decl[InstanceMethod]/CurrNominal: asyncFunc()[' async'][#Int#]; // IN_ASYNCFUNC_OTHER_DOT: End completions let _ = other#^IN_ASYNCFUNC_OTHER_NODOT^# // IN_ASYNCFUNC_OTHER_NODOT: Begin completions // IN_ASYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceVar]/CurrNominal: .property[#Int#][' async']; // IN_ASYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .syncFunc()[' async'][#Int#]; // IN_ASYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: .syncNonSendable({#arg: MyNonSendable#})[' async'][#Int#]; // IN_ASYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .syncSendable({#arg: MySendable#})[' async'][#Int#]; // IN_ASYNCFUNC_OTHER_NODOT-DAG: Decl[InstanceMethod]/CurrNominal: .asyncFunc()[' async'][#Int#]; // IN_ASYNCFUNC_OTHER_NODOT-DAG: Decl[Subscript]/CurrNominal: [{#(idx): Int#}][' async'][#Int#]; // IN_ASYNCFUNC_OTHER_NODOT: End completions } func testActorKind() { let _ = #^GLOBAL^# // GLOBAL: Begin completions // GLOBAL: Decl[Actor]/CurrModule: MyActor[#MyActor#]; name=MyActor // GLOBAL: End completions } }
apache-2.0
bc3774a0d0a8ef8e3d1a0dfaf288636d
63.655738
143
0.703093
3.878073
false
false
false
false
bitjammer/swift
test/SILGen/ivar_destroyer.swift
14
3135
// RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | %FileCheck %s // Only derived classes with non-trivial ivars need an ivar destroyer. struct TrivialStruct {} class RootClassWithoutProperties {} class RootClassWithTrivialProperties { var x: Int = 0 var y: TrivialStruct = TrivialStruct() } class Canary {} class RootClassWithNonTrivialProperties { var x: Canary = Canary() } class DerivedClassWithTrivialProperties : RootClassWithoutProperties { var z: Int = 12 } class DerivedClassWithNonTrivialProperties : RootClassWithoutProperties { var z: Canary = Canary() } // CHECK-LABEL: sil hidden @_T014ivar_destroyer36DerivedClassWithNonTrivialPropertiesCfE // CHECK: bb0(%0 : $DerivedClassWithNonTrivialProperties): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: [[Z_ADDR:%.*]] = ref_element_addr %0 // CHECK-NEXT: destroy_addr [[Z_ADDR]] // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil_vtable RootClassWithoutProperties { // CHECK-NEXT: #RootClassWithoutProperties.init!initializer.1 // CHECK-NEXT: #RootClassWithoutProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable RootClassWithTrivialProperties { // CHECK-NEXT: #RootClassWithTrivialProperties.x!getter.1 // CHECK-NEXT: #RootClassWithTrivialProperties.x!setter.1 // CHECK-NEXT: #RootClassWithTrivialProperties.x!materializeForSet.1 // CHECK-NEXT: #RootClassWithTrivialProperties.y!getter.1 // CHECK-NEXT: #RootClassWithTrivialProperties.y!setter.1 // CHECK-NEXT: #RootClassWithTrivialProperties.y!materializeForSet.1 // CHECK-NEXT: #RootClassWithTrivialProperties.init!initializer.1 // CHECK-NEXT: #RootClassWithTrivialProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable RootClassWithNonTrivialProperties { // CHECK-NEXT: #RootClassWithNonTrivialProperties.x!getter.1 // CHECK-NEXT: #RootClassWithNonTrivialProperties.x!setter.1 // CHECK-NEXT: #RootClassWithNonTrivialProperties.x!materializeForSet.1 // CHECK-NEXT: #RootClassWithNonTrivialProperties.init!initializer.1 // CHECK-NEXT: #RootClassWithNonTrivialProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable DerivedClassWithTrivialProperties { // CHECK-NEXT: #RootClassWithoutProperties.init!initializer.1 // CHECK-NEXT: #DerivedClassWithTrivialProperties.z!getter.1 // CHECK-NEXT: #DerivedClassWithTrivialProperties.z!setter.1 // CHECK-NEXT: #DerivedClassWithTrivialProperties.z!materializeForSet.1 // CHECK-NEXT: #DerivedClassWithTrivialProperties.deinit!deallocator // CHECK-NEXT: } // CHECK-LABEL: sil_vtable DerivedClassWithNonTrivialProperties { // CHECK-NEXT: #RootClassWithoutProperties.init!initializer.1 // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!getter.1 // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!setter.1 // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.z!materializeForSet.1 // CHECK-NEXT: #DerivedClassWithNonTrivialProperties.deinit!deallocator // CHECK-NEXT: #DerivedClassWithNonTrivialProperties!ivardestroyer.1 // CHECK-NEXT: }
apache-2.0
e5ab83a8de478c273ade7fb225dbfe04
40.8
88
0.765869
4.360223
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/ConversationViewController+GuestBar.swift
1
3792
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import FormatterKit import WireDataModel extension ConversationViewController { typealias ConversationBanner = L10n.Localizable.Conversation.Banner /// The state that the guest bar should adopt in the current configuration. var currentGuestBarState: GuestsBarController.State { let state = conversation.externalParticipantsState if state.isEmpty { return .hidden } else { return .visible(labelKey: label(for: state), identifier: identifier(for: state)) } } func label(for state: ZMConversation.ExternalParticipantsState) -> String { var states: [String] = [] if conversation.externalParticipantsState.contains(.visibleRemotes) { states.append(ConversationBanner.remotes) } if conversation.externalParticipantsState.contains(.visibleExternals) { states.append(ConversationBanner.externals) } if conversation.externalParticipantsState.contains(.visibleGuests) { states.append(ConversationBanner.guests) } if conversation.externalParticipantsState.contains(.visibleServices) { states.append(ConversationBanner.services) } let head = states[0] let tail = states.dropFirst().map({ $0.localizedLowercase }) let list = ([head] + tail).joined(separator: ConversationBanner.separator) if state == .visibleServices { return ConversationBanner.areActive(list) } else { return ConversationBanner.arePresent(list) } } func identifier(for state: ZMConversation.ExternalParticipantsState) -> String { var identifiers: [String] = [] if conversation.externalParticipantsState.contains(.visibleRemotes) { identifiers.append("remotes") } if conversation.externalParticipantsState.contains(.visibleExternals) { identifiers.append("externals") } if conversation.externalParticipantsState.contains(.visibleGuests) { identifiers.append("guests") } if conversation.externalParticipantsState.contains(.visibleServices) { identifiers.append("services") } return "has\(identifiers.joined(separator: "and"))" } /// Updates the visibility of the guest bar. func updateGuestsBarVisibility() { let currentState = self.currentGuestBarState guestsBarController.state = currentState if case .hidden = currentState { conversationBarController.dismiss(bar: guestsBarController) } else { conversationBarController.present(bar: guestsBarController) } } func setGuestBarForceHidden(_ isGuestBarForceHidden: Bool) { if isGuestBarForceHidden { guestsBarController.setState(.hidden, animated: true) guestsBarController.shouldIgnoreUpdates = true } else { guestsBarController.shouldIgnoreUpdates = false updateGuestsBarVisibility() } } }
gpl-3.0
72cbf6a8a1eb0a6ecc3e44ead0355153
32.557522
92
0.676951
5.159184
false
false
false
false
zmeyc/telegram-bot-swift
Sources/TelegramBotSDK/Extensions/Scanner+Utils.swift
1
5873
import Foundation public extension Scanner { func skipping(_ characters: CharacterSet?, closure: () throws->()) rethrows { let previous = charactersToBeSkipped defer { charactersToBeSkipped = previous } charactersToBeSkipped = characters try closure() } @discardableResult func skipInt() -> Bool { return scanInt() != nil } @discardableResult func skipInt32() -> Bool { #if os(OSX) return scanInt32(nil) #else return scanInt() != nil #endif } @discardableResult func skipInt64() -> Bool { return scanInt64() != nil } @discardableResult func skipUInt64() -> Bool { return scanUInt64() != nil } @discardableResult func skipFloat() -> Bool { return scanFloat() != nil } @discardableResult func skipDouble() -> Bool { return scanDouble() != nil } @discardableResult func skipHexUInt32() -> Bool { return scanHexUInt32() != nil } @discardableResult func skipHexUInt64() -> Bool { return scanHexUInt64() != nil } @discardableResult func skipHexFloat() -> Bool { return scanHexFloat() != nil } @discardableResult func skipHexDouble() -> Bool { return scanHexDouble() != nil } @discardableResult func skipString(_ string: String) -> Bool { #if true return scanString(string) != nil #else let utf16 = self.string.utf16 let startOffset = skippingCharacters(startingAt: scanLocation, in: utf16) let toSkip = string.utf16 let toSkipCount = toSkip.count let fromIndex = utf16.index(utf16.startIndex, offsetBy: startOffset) if let toIndex = utf16.index(fromIndex, offsetBy: toSkipCount, limitedBy: utf16.endIndex), utf16[fromIndex..<toIndex].elementsEqual(toSkip) { scanLocation = toIndex.encodedOffset return true } return false #endif } @discardableResult func skipCharacters(from: CharacterSet) -> Bool { return scanCharacters(from: from) != nil } @discardableResult func skipUpTo(_ string: String) -> Bool { return scanUpTo(string) != nil } @discardableResult func skipUpToCharacters(from set: CharacterSet) -> Bool { return scanUpToCharacters(from: set) != nil } func peekUtf16CodeUnit() -> UTF16.CodeUnit? { let originalScanLocation = scanLocation defer { scanLocation = originalScanLocation } let originalCharactersToBeSkipped = charactersToBeSkipped defer { charactersToBeSkipped = originalCharactersToBeSkipped } if let characters = charactersToBeSkipped { charactersToBeSkipped = nil let _ = scanCharacters(from: characters) } guard scanLocation < string.utf16.count else { return nil } let index = string.utf16.index(string.utf16.startIndex, offsetBy: scanLocation) return string.utf16[index] } var scanLocationInCharacters: Int { let utf16 = string.utf16 guard let to16 = utf16.index(utf16.startIndex, offsetBy: scanLocation, limitedBy: utf16.endIndex), let to = String.Index(to16, within: string) else { return 0 } return string.distance(from: string.startIndex, to: to) } private var currentCharacterIndex: String.Index? { let utf16 = string.utf16 guard let to16 = utf16.index(utf16.startIndex, offsetBy: scanLocation, limitedBy: utf16.endIndex), let to = String.Index(to16, within: string) else { return nil } // to is a String.CharacterView.Index return to } var parsedText: Substring { guard let index = currentCharacterIndex else { return "" } return string[..<index] } var textToParse: Substring { guard let index = currentCharacterIndex else { return "" } return string[index...] } var lineBeingParsed: String { let targetLine = self.line() var currentLine = 1 var line = "" line.reserveCapacity(256) for character in string { if currentLine > targetLine { break } if character == "\n" || character == "\r\n" { currentLine += 1 continue } if currentLine == targetLine { line.append(character) } } return line } /// Very slow, do not in use in loops func line() -> Int { var newLinesCount = 0 parsedText.forEach { if $0 == "\n" || $0 == "\r\n" { newLinesCount += 1 } } return 1 + newLinesCount } /// Very slow, do not in use in loops func column() -> Int { let text = parsedText if let range = text.range(of: "\n", options: .backwards) { return text.distance(from: range.upperBound, to: text.endIndex) + 1 } return parsedText.count + 1 } #if fålse private func skippingCharacters(startingAt: Int, in utf16: String.UTF16View) -> Int { guard let charactersToBeSkipped = charactersToBeSkipped else { return startingAt } let fromIndex = utf16.index(utf16.startIndex, offsetBy: startingAt) var newLocation = startingAt for c in utf16[fromIndex...] { guard let scalar = UnicodeScalar(c) else { break } guard charactersToBeSkipped.contains(scalar) else { break } newLocation += 1 } return newLocation } #endif }
apache-2.0
9781c00d9180fc380ec8426b8a0e3e73
28.21393
106
0.576294
4.917923
false
false
false
false
danielsaidi/KeyboardKit
Tests/KeyboardKitTests/UIKit/Shadow/UIView+ShadowTests.swift
1
2202
// // UIView+ShadowTests.swift // KeyboardKit // // Created by Daniel Saidi on 2019-05-28. // Copyright © 2021 Daniel Saidi. All rights reserved. // import Quick import Nimble import KeyboardKit import UIKit class UIView_ShadowTests: QuickSpec { override func spec() { describe("applying shadow") { it("applies shadow properties") { let view = UIView() let shadow = UIShadow.test() let layer = view.layer view.applyShadow(shadow) expect(layer.shadowColor).to(equal(shadow.color.cgColor)) expect(layer.shadowOpacity).to(equal(shadow.alpha)) expect(layer.shadowOffset.width).to(equal(0)) expect(layer.shadowOffset.height).to(equal(0)) expect(layer.shadowRadius).to(equal(shadow.blur/2)) } it("applies behavior properties") { let view = UIView() let shadow = UIShadow.test() let layer = view.layer view.applyShadow(shadow) expect(layer.shouldRasterize).to(beTrue()) expect(layer.rasterizationScale).to(equal(UIScreen.main.scale)) } it("does not apply shadow path if spread is zero") { let view = UIView() let shadow = UIShadow.test(spread: 0) let layer = view.layer view.applyShadow(shadow) expect(layer.shadowPath).toNot(beNil()) } it("applies shadow path if spread is not zero") { let view = UIView() let shadow = UIShadow.test(spread: 0.5) let layer = view.layer view.applyShadow(shadow) expect(layer.shadowPath).toNot(beNil()) } } } } private extension UIShadow { static func test(spread: CGFloat = 0.8) -> UIShadow { return UIShadow( alpha: 0.75, blur: 0.123, color: .red, spread: spread, x: 100.1, y: 200.2) } }
mit
65ae1678354a426cb67bb115329035c3
30
79
0.511586
4.75378
false
true
false
false
asefnoor/IQKeyboardManager
IQKeybordManagerSwift/IQKeyboardManager.swift
1
49300
// // IQKeyboardManager.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-14 Iftekhar Qurashi. // // 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 CoreGraphics import UIKit /*! @author Iftekhar Qurashi @related [email protected] @class IQKeyboardManager @abstract Keyboard TextField/TextView Manager. A generic version of KeyboardManagement. https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html */ /* @const kIQDoneButtonToolbarTag Default tag for toolbar with Done button -1002. */ let kIQDoneButtonToolbarTag : NSInteger = -1002 /* @const kIQPreviousNextButtonToolbarTag Default tag for toolbar with Previous/Next buttons -1005. */ let kIQPreviousNextButtonToolbarTag : NSInteger = -1005 class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate { //UIKeyboard handling /*! @abstract enable/disable the keyboard manager. Default is YES(Enabled when class loads in `+(void)load` method. */ var enable: Bool = false { didSet{ //If not enable, enable it. if (enable == true && oldValue == false) { //If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard. if _kbShowNotification != nil { keyboardWillShow(_kbShowNotification) } } //If not disable, desable it. else if (enable == false && oldValue == true) { keyboardWillHide(nil) } } } /*! @abstract To set keyboard distance from textField. can't be less than zero. Default is 10.0. */ var keyboardDistanceFromTextField: CGFloat { set { _privateKeyboardDistanceFromTextField = max(0, newValue) } get { return _privateKeyboardDistanceFromTextField } } /*! @abstract Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES. */ var preventShowingBottomBlankSpace = true //IQToolbar handling /*! @abstract Automatic add the IQToolbar functionality. Default is YES. */ var enableAutoToolbar: Bool = true { didSet { enableAutoToolbar ?addToolbarIfRequired():removeToolbarIfRequired() } } /*! @abstract AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews. */ var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.BySubviews /*! @abstract If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO. */ var shouldToolbarUsesTextFieldTintColor = false /*! @abstract If YES, then it add the textField's placeholder text on IQToolbar. Default is YES. */ var shouldShowTextFieldPlaceholder = true /*! @abstract placeholder Font. Default is nil. */ var placeholderFont: UIFont? //TextView handling /*! @abstract Adjust textView's frame when it is too big in height. Default is NO. */ var canAdjustTextView = false //Keyboard appearance overriding /*! @abstract override the keyboardAppearance for all textField/textView. Default is NO. */ var overrideKeyboardAppearance = false /*! @abstract if overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property. */ var keyboardAppearance = UIKeyboardAppearance.Default //Resign handling /*! @abstract Resigns Keyboard on touching outside of UITextField/View. Default is NO. */ var shouldResignOnTouchOutside: Bool = false { didSet { _tapGesture.enabled = shouldResignOnTouchOutside } } //Sound handling /*! @abstract If YES, then it plays inputClick sound on next/previous/done click. */ var shouldPlayInputClicks = false //Animation handling /*! @abstract If YES, then uses keyboard default animation curve style to move view, otherwise uses UIViewAnimationOptionCurveEaseInOut animation style. Default is YES. @discussion Sometimes strange animations may be produced if uses default curve style animation in iOS 7 and changing the textFields very frequently. */ var shouldAdoptDefaultKeyboardAnimation = true //Private variables /*******************************************/ /*! To save UITextField/UITextView object voa textField/textView notifications. */ private weak var _textFieldView: UIView! /*! used with canAdjustTextView boolean. */ private var _textFieldViewIntialFrame: CGRect = CGRectZero /*! To save rootViewController.view.frame. */ private var _topViewBeginRect: CGRect = CGRectZero /*! used with canAdjustTextView to detect a textFieldView frame is changes or not. (Bug ID: #92)*/ private var _isTextFieldViewFrameChanged: Bool = false /*******************************************/ /*! Variable to save lastScrollView that was scrolled. */ private weak var _lastScrollView: UIScrollView? /*! LastScrollView's initial contentOffset. */ private var _startingContentOffset: CGPoint = CGPointZero /*******************************************/ /*! To save keyboardWillShowNotification. Needed for enable keyboard functionality. */ private var _kbShowNotification: NSNotification! /*! Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */ private var _isKeyboardShowing: Bool = false /*! To save keyboard size. */ private var _kbSize: CGSize! = CGSizeZero /*! To save keyboard animation duration. */ private var _animationDuration: NSTimeInterval = 0.25 /*! To mimic the keyboard animation */ private var _animationCurve: UIViewAnimationOptions = UIViewAnimationOptions.CurveEaseOut /*******************************************/ /*! TapGesture to resign keyboard on view's touch. */ private var _tapGesture: UITapGestureRecognizer! /*! @abstract Save keyWindow object for reuse. @discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */ private var _keyWindow: UIWindow! /*******************************************/ /*! To use with keyboardDistanceFromTextField. */ private var _privateKeyboardDistanceFromTextField: CGFloat = 10.0 /*******************************************/ override init() { super.init() // Registering for keyboard notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHide:", name: UIKeyboardDidHideNotification, object: nil) // Registering for textField notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextFieldTextDidBeginEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextFieldTextDidEndEditingNotification, object: nil) // Registering for textView notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextViewTextDidBeginEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextViewTextDidEndEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidChange:", name: UITextViewTextDidChangeNotification, object: nil) // Registering for orientation changes notification NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeStatusBarOrientation:", name: UIApplicationWillChangeStatusBarOrientationNotification, object: nil) //Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14) _tapGesture = UITapGestureRecognizer(target: self, action: "tapRecognized:") _tapGesture.delegate = self _tapGesture.enabled = shouldResignOnTouchOutside } override class func load() { super.load() IQKeyboardManager.sharedManager().enable = true } deinit { enable = false NSNotificationCenter.defaultCenter().removeObserver(self) } class func sharedManager() -> IQKeyboardManager { struct Static { static let kbManager : IQKeyboardManager = IQKeyboardManager() } /*! @return Returns the default singleton instance. */ return Static.kbManager } /*! Getting keyWindow. */ private func keyWindow() -> UIWindow { /* (Bug ID: #23, #25, #73) */ let originalKeyWindow : UIWindow? = UIApplication.sharedApplication().keyWindow //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow. if originalKeyWindow != nil && _keyWindow != originalKeyWindow { _keyWindow = originalKeyWindow } //Return KeyWindow return _keyWindow } /* Helper function to manipulate RootViewController's frame with animation. */ private func setRootViewFrame(var frame: CGRect) { // Getting topMost ViewController. var controller: UIViewController! = keyWindow().topMostController() //frame size needs to be adjusted on iOS8 due to orientation structure changes. if (IQ_IS_IOS8_OR_GREATER) { frame.size = controller.view.size } // If can't get rootViewController then printing warning to user. if (controller == nil) { println("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager") } //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in // Setting it's new frame controller.view.frame = frame }) { (animated:Bool) -> Void in} } /* Adjusting RootViewController's frame according to device orientation. */ private func adjustFrame() { // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) if (_textFieldView == nil) { return } // Boolean to know keyboard is showing/hiding _isKeyboardShowing = true // Getting KeyWindow object. var window = keyWindow() // Getting RootViewController. (Bug ID: #1, #4) var rootController = keyWindow().topMostController() //If it's iOS8 then we should do calculations according to portrait orientations. // (Bug ID: #64, #66) var interfaceOrientation = (IQ_IS_IOS8_OR_GREATER) ? UIInterfaceOrientation.Portrait : rootController.interfaceOrientation // Converting Rectangle according to window bounds. var textFieldViewRect : CGRect? = _textFieldView.superview?.convertRect(_textFieldView.frame, toView: window) // Getting RootViewRect. var rootViewRect = rootController.view.frame //Getting statusBarFrame var statusBarFrame = UIApplication.sharedApplication().statusBarFrame var move : CGFloat = 0 // Move positive = textField is hidden. // Move negative = textField is showing. // Calculating move position. Common for both normal and special cases. switch (interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft: move = min((textFieldViewRect?.x)! - (statusBarFrame.width+5), (textFieldViewRect?.right)!-(window.width-_kbSize.width)) case UIInterfaceOrientation.LandscapeRight: move = min(window.width - (textFieldViewRect?.right)! - (statusBarFrame.width+5), _kbSize.width - (textFieldViewRect?.x)!) case UIInterfaceOrientation.Portrait: move = min((textFieldViewRect?.y)! - (statusBarFrame.height+5), (textFieldViewRect?.bottom)! - (window.height-_kbSize.height)) case UIInterfaceOrientation.PortraitUpsideDown: move = min(window.height - (textFieldViewRect?.bottom)! - (statusBarFrame.height+5), _kbSize.height - (textFieldViewRect?.y)!) default: break } // Getting it's superScrollView. // (Enhancement ID: #21, #24) var superScrollView : UIScrollView? = _textFieldView.superScrollView() //If there was a lastScrollView. // (Bug ID: #34) if (_lastScrollView != nil) { //If we can't find current superScrollView, then setting lastScrollView to it's original form. if (superScrollView == nil) { _lastScrollView?.setContentOffset(_startingContentOffset, animated: true) _lastScrollView = nil _startingContentOffset = CGPointZero } //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView. else if (superScrollView != _lastScrollView) { _lastScrollView?.setContentOffset(_startingContentOffset, animated: true) _lastScrollView = superScrollView _startingContentOffset = (superScrollView?.contentOffset)! } //Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead } //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView. else if((superScrollView) != nil) { _lastScrollView = superScrollView _startingContentOffset = (superScrollView?.contentOffset)! } // Special case for ScrollView. // If we found lastScrollView then setting it's contentOffset to show textField. if (_lastScrollView != nil) { //Saving var lastView = _textFieldView var superScrollView : UIScrollView! = _lastScrollView //Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object. while (superScrollView != nil && move>0) { //Getting lastViewRect. var lastViewRect : CGRect! = lastView.superview?.convertRect(lastView.frame, toView: superScrollView) //Calculating the expected Y offset from move and scrollView's contentOffset. var shouldOffsetY = superScrollView.contentOffset.y - min(superScrollView.contentOffset.y,-move) //Rearranging the expected Y offset according to the view. shouldOffsetY = min(shouldOffsetY, lastViewRect.y /*-5*/) //-5 is for good UI.//Commenting -5 Bug ID #69 //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. move -= (shouldOffsetY-superScrollView.contentOffset.y) //Getting problem while using `setContentOffset:animated:`, So I used animation API. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in superScrollView.contentOffset = CGPointMake(superScrollView.contentOffset.x, shouldOffsetY) }) { (animated:Bool) -> Void in } // Getting next lastView & superScrollView. lastView = superScrollView superScrollView = lastView.superScrollView() } } //Going ahead. No else if. //Special case for UITextView(Readjusting the move variable when textView hight is too big to fit on screen). //If we have permission to adjust the textView, then let's do it on behalf of user. (Enhancement ID: #15) //Added _isTextFieldViewFrameChanged. (Bug ID: #92) if ((canAdjustTextView == true) && (_textFieldView.isKindOfClass(UITextView) == true) && (_isTextFieldViewFrameChanged == false)) { var textViewHeight: CGFloat = _textFieldView.height switch (interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight: textViewHeight = min(textViewHeight, (window.width-_kbSize.width-(statusBarFrame.width+5))) case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown: textViewHeight = min(textViewHeight, (window.height-_kbSize.height-(statusBarFrame.height+5))) default: break } UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve|UIViewAnimationOptions.BeginFromCurrentState), animations: { () -> Void in self._textFieldView.height = textViewHeight self._isTextFieldViewFrameChanged = true }, completion: { (finished) -> Void in }) } // Special case for iPad modalPresentationStyle. if (rootController.modalPresentationStyle == UIModalPresentationStyle.FormSheet || rootController.modalPresentationStyle == UIModalPresentationStyle.PageSheet) { // Positive or zero. if (move>=0) { // We should only manipulate y. rootViewRect.y -= move // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if (preventShowingBottomBlankSpace == true) { var minimumY: CGFloat = 0 switch (interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight: minimumY = window.width-rootViewRect.height-statusBarFrame.width-(_kbSize.width-keyboardDistanceFromTextField) case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown: minimumY = (window.height-rootViewRect.height-statusBarFrame.height)/2-(_kbSize.height-keyboardDistanceFromTextField) default: break } rootViewRect.y = max(rootViewRect.y, minimumY) } self.setRootViewFrame(rootViewRect) } // Negative else { // Calculating disturbed distance. Pull Request #3 var disturbDistance = rootViewRect.y - _topViewBeginRect.y // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if(disturbDistance<0) { // We should only manipulate y. rootViewRect.y -= max(move, disturbDistance) self.setRootViewFrame(rootViewRect) } } } //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case) else { // Positive or zero. if (move>=0) { switch (interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft: rootViewRect.x -= move case UIInterfaceOrientation.LandscapeRight: rootViewRect.x += move case UIInterfaceOrientation.Portrait: rootViewRect.y -= move case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.y += move default : break } // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if (preventShowingBottomBlankSpace == true) { switch (interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft: rootViewRect.x = max(rootViewRect.x, -_kbSize.width+keyboardDistanceFromTextField) case UIInterfaceOrientation.LandscapeRight: rootViewRect.x = min(rootViewRect.x, +_kbSize.width-keyboardDistanceFromTextField) case UIInterfaceOrientation.Portrait: rootViewRect.y = max(rootViewRect.y, -_kbSize.height+keyboardDistanceFromTextField) case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.y = min(rootViewRect.y, +_kbSize.height-keyboardDistanceFromTextField) default: break } } // Setting adjusted rootViewRect self.setRootViewFrame(rootViewRect) } // Negative else { var disturbDistance : CGFloat = 0 switch (interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft: disturbDistance = rootViewRect.left - _topViewBeginRect.left case UIInterfaceOrientation.LandscapeRight: disturbDistance = _topViewBeginRect.left - rootViewRect.left case UIInterfaceOrientation.Portrait: disturbDistance = rootViewRect.top - _topViewBeginRect.top case UIInterfaceOrientation.PortraitUpsideDown: disturbDistance = _topViewBeginRect.top - rootViewRect.top default : break } // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if(disturbDistance<0) { switch (interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft: rootViewRect.x -= max(move, disturbDistance) case UIInterfaceOrientation.LandscapeRight: rootViewRect.x += max(move, disturbDistance) case UIInterfaceOrientation.Portrait: rootViewRect.y -= max(move, disturbDistance) case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.y += max(move, disturbDistance) default : break } // Setting adjusted rootViewRect self.setRootViewFrame(rootViewRect) } } } } /* UIKeyboardWillShowNotification. */ func keyboardWillShow(notification:NSNotification) -> Void { _kbShowNotification = notification var info : NSDictionary = notification.userInfo! if (enable == false) { return } //Due to orientation callback we need to resave it's original frame. // (Bug ID: #46) //Added _isTextFieldViewFrameChanged check. Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed. (Bug ID: #92) if (_isTextFieldViewFrameChanged == false && _textFieldView != nil) { _textFieldViewIntialFrame = _textFieldView.frame } if (CGRectEqualToRect(_topViewBeginRect, CGRectZero)) // (Bug ID: #5) { // keyboard is not showing(At the beginning only). We should save rootViewRect. var rootController = keyWindow().topMostController() _topViewBeginRect = rootController.view.frame } if (shouldAdoptDefaultKeyboardAnimation) { // Getting keyboard animation. var curve = info.objectForKey(UIKeyboardAnimationDurationUserInfoKey)?.unsignedLongValue /* If you are running below Xcode 6.1 then please add `-DIQ_IS_XCODE_BELOW_6_1` flag in 'other swift flag' to fix compiler errors. http://stackoverflow.com/questions/24369272/swift-ios-deployment-target-command-line-flag */ #if IQ_IS_XCODE_BELOW_6_1 _animationCurve = UIViewAnimationOptions.fromRaw(curve!)! #else _animationCurve = UIViewAnimationOptions(rawValue: curve!) #endif } else { _animationCurve = UIViewAnimationOptions.CurveEaseOut } // Getting keyboard animation duration var duration = info.objectForKey(UIKeyboardAnimationDurationUserInfoKey)?.doubleValue //Saving animation duration if (duration != 0.0) { _animationDuration = duration! } var oldKBSize = _kbSize // Getting UIKeyboardSize. _kbSize = info.objectForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue().size //If it's iOS8 then we should do calculations according to portrait orientations. // (Bug ID: #64, #66) var interfaceOrientation = (IQ_IS_IOS8_OR_GREATER) ? UIInterfaceOrientation.Portrait : self.keyWindow().topMostController().interfaceOrientation // Adding Keyboard distance from textField. switch (interfaceOrientation) { case UIInterfaceOrientation.LandscapeLeft: _kbSize.width += keyboardDistanceFromTextField case UIInterfaceOrientation.LandscapeRight: _kbSize.width += keyboardDistanceFromTextField case UIInterfaceOrientation.Portrait: _kbSize.height += keyboardDistanceFromTextField case UIInterfaceOrientation.PortraitUpsideDown: _kbSize.height += keyboardDistanceFromTextField default : break } //If last restored keyboard size is different(any orientation accure), then refresh. otherwise not. if (!CGSizeEqualToSize(_kbSize, oldKBSize)) { //If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _textFieldView != nil && _textFieldView.viewController()?.isKindOfClass(UITableViewController) == false && _textFieldView.isAlertViewTextField() == false { adjustFrame() } } } /* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */ func keyboardWillHide(notification:NSNotification?) -> Void { //If it's not a fake notification generated by [self setEnable:NO]. if (notification != nil) { _kbShowNotification = nil } //If not enabled then do nothing. if (enable == false) { return } //Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56) // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) // if (_textFieldView == nil) return // Boolean to know keyboard is showing/hiding _isKeyboardShowing = false var info :NSDictionary? = notification?.userInfo! // Getting keyboard animation duration var duration = info?.objectForKey(UIKeyboardAnimationDurationUserInfoKey)?.doubleValue if (duration != 0) { // Setitng keyboard animation duration _animationDuration = duration! } //Restoring the contentOffset of the lastScrollView if (_lastScrollView != nil) { UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in self._lastScrollView?.contentOffset = self._startingContentOffset // TODO: This is temporary solution. Have to implement the save and restore scrollView state var superscrollView : UIScrollView? = self._lastScrollView superscrollView = superscrollView?.superScrollView() while (superscrollView != nil) { var superScrollView : UIScrollView! = superscrollView var contentSize = CGSizeMake(max(superScrollView.contentSize.width, superScrollView.width), max(superScrollView.contentSize.height, superScrollView.height)) var minimumY = contentSize.height-superScrollView.height if (minimumY < superScrollView.contentOffset.y) { superScrollView.contentOffset = CGPointMake(superScrollView.contentOffset.x, minimumY) } superscrollView = superScrollView.superScrollView() } }) { (finished) -> Void in } } // Setting rootViewController frame to it's original position. // (Bug ID: #18) if (!CGRectEqualToRect(_topViewBeginRect, CGRectZero)) { setRootViewFrame(_topViewBeginRect) } //Reset all values _lastScrollView = nil _kbSize = CGSizeZero _startingContentOffset = CGPointZero } func keyboardDidHide(notification:NSNotification) { _topViewBeginRect = CGRectZero } /*! UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */ func textFieldViewDidBeginEditing(notification:NSNotification) { // Getting object _textFieldView = notification.object as UIView if (overrideKeyboardAppearance == true) { if (_textFieldView.isKindOfClass(UITextField) == true) { (_textFieldView as UITextField).keyboardAppearance = keyboardAppearance } else if (_textFieldView.isKindOfClass(UITextView) == true) { (_textFieldView as UITextView).keyboardAppearance = keyboardAppearance } } // Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed. //Added _isTextFieldViewFrameChanged check. (Bug ID: #92) if (_isTextFieldViewFrameChanged == false) { _textFieldViewIntialFrame = _textFieldView.frame } //If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required. if (enableAutoToolbar) { //UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it. if ((_textFieldView.isKindOfClass(UITextView) == true) && _textFieldView.inputAccessoryView == nil) { UIView.animateWithDuration(0.00001, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in self.addToolbarIfRequired() }, completion: { (finished) -> Void in var textFieldRetain = self._textFieldView textFieldRetain.resignFirstResponder() textFieldRetain.becomeFirstResponder() }) } else { addToolbarIfRequired() } } if (enable == false) { return } _textFieldView.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14) if _isKeyboardShowing == false { // (Bug ID: #5) // keyboard is not showing(At the beginning only). We should save rootViewRect. var rootController = self.keyWindow().topMostController() _topViewBeginRect = rootController.view.frame } //If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37, #74, #76) //See notes:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _textFieldView != nil && _textFieldView.viewController()?.isKindOfClass(UITableViewController) == false && _textFieldView.isAlertViewTextField() == false { adjustFrame() } } /*! UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */ func textFieldViewDidEndEditing(notification:NSNotification) { _textFieldView.window?.removeGestureRecognizer(_tapGesture) // (Enhancement ID: #14) // We check if there's a change in original frame or not. if(_isTextFieldViewFrameChanged == true) { UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in self._isTextFieldViewFrameChanged = false self._textFieldView.frame = self._textFieldViewIntialFrame }, completion: { (finished) -> Void in }) } //Setting object to nil _textFieldView = nil } /* UITextViewTextDidChangeNotificationBug, fix for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string */ func textFieldViewDidChange(notification:NSNotification) { // (Bug ID: #18) var textView : UITextView = notification.object as UITextView var line = textView .caretRectForPosition(textView.selectedTextRange?.start) var overflow = CGRectGetMaxY(line) - (textView.contentOffset.y + CGRectGetHeight(textView.bounds) - textView.contentInset.bottom - textView.contentInset.top) //Added overflow conditions (Bug ID: 95) if ( overflow > 0.0 && overflow < CGFloat(FLT_MAX)) { // We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it) // Scroll caret to visible area var offset = textView.contentOffset offset.y += overflow + 7 // leave 7 pixels margin // Cannot animate with setContentOffset:animated: or caret will not appear UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState|_animationCurve, animations: { () -> Void in textView.contentOffset = offset }, completion: { (finished) -> Void in }) } } /*! UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/ func willChangeStatusBarOrientation(notification:NSNotification) { //If textFieldViewInitialRect is saved then restore it.(UITextView case @canAdjustTextView) if (_isTextFieldViewFrameChanged == true) { //Due to orientation callback we need to set it's original position. UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve|UIViewAnimationOptions.BeginFromCurrentState), animations: { () -> Void in self._textFieldView.frame = self._textFieldViewIntialFrame self._isTextFieldViewFrameChanged = false }, completion: { (finished) -> Void in }) } } /*! Resigning on tap gesture. */ func tapRecognized(gesture: UITapGestureRecognizer) { if (gesture.state == UIGestureRecognizerState.Ended) { gesture.view?.endEditing(true) } } /*! Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */ func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } /*! Resigning textField. */ func resignFirstResponder() { if (_textFieldView != nil) { // Retaining textFieldView var textFieldRetain = _textFieldView //Resigning first responder var isResignFirstResponder = _textFieldView.resignFirstResponder() // If it refuses then becoming it as first responder again. (Bug ID: #96) if (isResignFirstResponder == false) { //If it refuses to resign then becoming it first responder again for getting notifications callback. textFieldRetain.becomeFirstResponder() println("IQKeyboardManager: Refuses to Resign first responder: \(_textFieldView) ") } } } /*! Get all UITextField/UITextView siblings of textFieldView. */ func responderViews()-> NSArray { var tableView : UIView? = _textFieldView.superTableView() if(tableView == nil) { tableView = tableView?.superCollectionView() } var textFields : NSArray! //If there is a tableView in view's hierarchy, then fetching all it's subview that responds. if (tableView != nil) { // (Enhancement ID: #22) textFields = tableView?.deepResponderViews() } //Otherwise fetching all the siblings else { textFields = _textFieldView.responderSiblings() } //Sorting textFields according to behaviour switch (toolbarManageBehaviour) { //If autoToolbar behaviour is bySubviews, then returning it. case IQAutoToolbarManageBehaviour.BySubviews: return textFields //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.ByTag: return textFields.sortedArrayByTag() //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.ByPosition: return textFields.sortedArrayByPosition() } } /*! previousAction. */ func previousAction (segmentedControl : AnyObject!) { if (shouldPlayInputClicks == true) { UIDevice.currentDevice().playInputClick() } //Getting all responder view's. var textFields = responderViews() if (textFields.containsObject(_textFieldView) == true) { //Getting index of current textField. var index = textFields.indexOfObject(_textFieldView) //If it is not first textField. then it's previous object becomeFirstResponder. if index > 0 { var nextTextField = textFields[index-1] as UIView // Retaining textFieldView var textFieldRetain = _textFieldView var isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if (isAcceptAsFirstResponder == false) { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() println("IQKeyboardManager: Refuses to become first responder: \(nextTextField)") } } } } /*! nextAction. */ func nextAction (segmentedControl : AnyObject!) { if (shouldPlayInputClicks == true) { UIDevice.currentDevice().playInputClick() } //Getting all responder view's. var textFields = responderViews() if (textFields.containsObject(_textFieldView) == true) { //Getting index of current textField. var index = textFields.indexOfObject(_textFieldView) //If it is not last textField. then it's next object becomeFirstResponder. if index < textFields.count-1 { var nextTextField = textFields[index+1] as UIView // Retaining textFieldView var textFieldRetain = _textFieldView var isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if (isAcceptAsFirstResponder == false) { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() println("IQKeyboardManager: Refuses to become first responder: \(nextTextField)") } } } } /*! doneAction. Resigning current textField. */ func doneAction (barButton : IQBarButtonItem!) { if (shouldPlayInputClicks == true) { UIDevice.currentDevice().playInputClick() } resignFirstResponder() } /*! Add toolbar if it is required to add on textFields and it's siblings. */ private func addToolbarIfRequired() { // Getting all the sibling textFields. var siblings : NSArray? = responderViews() // If only one object is found, then adding only Done button. if (siblings?.count == 1) { var textField : UIView = siblings?.firstObject as UIView //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar). if (textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == kIQPreviousNextButtonToolbarTag) { textField.addDoneOnKeyboardWithTarget(self, action: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder) textField.inputAccessoryView?.tag = kIQDoneButtonToolbarTag // (Bug ID: #78) //Setting toolbar tintColor. // (Enhancement ID: #30) if shouldToolbarUsesTextFieldTintColor == true { textField.inputAccessoryView?.tintColor = textField.tintColor } //Setting toolbar title font. // (Enhancement ID: #30) if (shouldShowTextFieldPlaceholder == true && placeholderFont != nil) { (textField.inputAccessoryView as IQToolbar).titleFont = placeholderFont! } } } else if siblings?.count != 0 { // If more than 1 textField is found. then adding previous/next/done buttons on it. for textField in siblings as Array<UIView> { if (textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == kIQDoneButtonToolbarTag) { textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: "previousAction:", nextAction: "nextAction:", doneAction: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder) textField.inputAccessoryView?.tag = kIQPreviousNextButtonToolbarTag // (Bug ID: #78) //Setting toolbar tintColor // (Enhancement ID: #30) if shouldToolbarUsesTextFieldTintColor == true { textField.inputAccessoryView?.tintColor = textField.tintColor } //Setting toolbar title font. // (Enhancement ID: #30) if (shouldShowTextFieldPlaceholder == true && placeholderFont != nil) { (textField.inputAccessoryView as IQToolbar).titleFont = placeholderFont! } } //If the toolbar is added by IQKeyboardManager then automatically enabling/disabling the previous/next button. if (textField.inputAccessoryView?.tag == kIQPreviousNextButtonToolbarTag) { //In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56) // If firstTextField, then previous should not be enabled. if (siblings?.objectAtIndex(0) as UIView == textField) { textField.setEnablePrevious(false, isNextEnabled: true) } // If lastTextField then next should not be enaled. else if (siblings?.lastObject as UIView == textField) { textField.setEnablePrevious(true, isNextEnabled: false) } else { textField.setEnablePrevious(true, isNextEnabled: true) } } } } } /*! Remove any toolbar if it is IQToolbar. */ private func removeToolbarIfRequired() { // (Bug ID: #18) // Getting all the sibling textFields. var siblings : NSArray? = responderViews() for view in siblings as Array<UIView> { var toolbar = view.inputAccessoryView? if view.inputAccessoryView is IQToolbar && ( toolbar != nil && (toolbar?.tag == kIQDoneButtonToolbarTag || toolbar?.tag == kIQPreviousNextButtonToolbarTag)) { if (view.isKindOfClass(UITextField) == true) { var textField : UITextField = view as UITextField textField.inputAccessoryView = nil } else if (view.isKindOfClass(UITextView) == true) { var textView : UITextView = view as UITextView textView.inputAccessoryView = nil } } } } }
mit
4813c618c3a46a2d12ba259f1dd77876
46.177033
365
0.615984
6.229467
false
false
false
false
cuba/NetworkKit
Source/Errors/BaseNetworkError.swift
1
1520
// // BaseNetworkError.swift // NetworkKit iOS // // Created by Jacob Sikorski on 2017-12-23. // Copyright © 2017 Jacob Sikorski. All rights reserved. // import Foundation public protocol BaseNetworkError: LocalizedError, CustomNSError { var errorKey: String { get } } extension BaseNetworkError { public var errorDescription: String? { var parts: [String] = [] if let failureReason = failureReason { parts.append(failureReason) } if let recoverySuggestion = recoverySuggestion { parts.append(recoverySuggestion) } if parts.count > 0 { return parts.joined(separator: " ") } else { return "ErrorReason.UnknownNetworkError".localized() } } public var errorUserInfo: [String : Any] { var userInfo: [String: Any] = [ NSDebugDescriptionErrorKey: errorKey ] var tempUserInfo: [String: Any?] = [ NSLocalizedDescriptionKey: errorDescription, NSLocalizedFailureReasonErrorKey: failureReason, NSLocalizedRecoverySuggestionErrorKey: recoverySuggestion ] if #available(iOS 11.0, *) { tempUserInfo[NSLocalizedFailureErrorKey] = errorDescription } for (key, value) in tempUserInfo { guard let value = value else { continue } userInfo[key] = value } return userInfo } }
mit
9a26fe36024599301a23bb729a1a553e
26.125
71
0.58657
5.329825
false
false
false
false
lennet/proNotes
app/proNotes/AppDelegate.swift
1
2152
// // AppDelegate.swift // proNotes // // Created by Leo Thomas on 26/11/15. // Copyright © 2015 leonardthomas. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { if Preferences.isFirstRun { Preferences.setUpDefaults() } let args = ProcessInfo.processInfo.arguments if args.contains("UITEST") { Preferences.showWelcomeScreen = false Preferences.iCloudActive = false } return true } func applicationWillTerminate(_ application: UIApplication) { DocumentInstance.sharedInstance.save { (success) -> Void in DocumentInstance.sharedInstance.document?.close(completionHandler: nil) } } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> ()) { let overViewController = moveToOverViewIfNeeded(false) overViewController?.createNewDocument() completionHandler(true) } /// Pops all ViewControllers on the ViewControllers-Stack until the DocumentOverViewController is visible /// /// - parameter animated: defines whether poping the current ViewController should be animated or not /// /// - returns: the instance of the visible DocumentOverViewController private func moveToOverViewIfNeeded(_ animated: Bool) -> DocumentOverviewViewController? { if let navViewController = self.window?.rootViewController as? UINavigationController { if navViewController.visibleViewController is DocumentViewController { navViewController.popViewController(animated: animated) DocumentInstance.sharedInstance.removeAllDelegates() } return navViewController.viewControllers.first as? DocumentOverviewViewController } return nil } }
mit
b502b6c0b9b574c7a80df65a7684d8b8
36.086207
153
0.693631
5.909341
false
false
false
false
wordpress-mobile/WordPress-Shared-iOS
WordPressShared/Core/Utility/String+Helpers.swift
1
6202
import Foundation extension String { public func stringByDecodingXMLCharacters() -> String { return NSString.decodeXMLCharacters(in: self) } public func stringByEncodingXMLCharacters() -> String { return NSString.encodeXMLCharacters(in: self) } public func trim() -> String { return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } /// Returns `self` if not empty, or `nil` otherwise /// public func nonEmptyString() -> String? { return isEmpty ? nil : self } /// Returns a string without the character at the specified index. /// This is a non-mutating version of `String.remove(at:)`. public func removing(at index: Index) -> String { var copy = self copy.remove(at: index) return copy } /// Returns a count of valid text characters. /// - Note : This implementation is influenced by `-wordCount` in `NSString+Helpers`. public var characterCount: Int { var charCount = 0 if isEmpty == false { let textRange = startIndex..<endIndex enumerateSubstrings(in: textRange, options: [.byWords, .localized]) { word, _, _, _ in let wordLength = word?.count ?? 0 charCount += wordLength } } return charCount } } // MARK: - Prefix removal public extension String { /// Removes the given prefix from the string, if exists. /// /// Calling this method might invalidate any existing indices for use with this string. /// /// - Parameters: /// - prefix: A possible prefix to remove from this string. /// mutating func removePrefix(_ prefix: String) { if let prefixRange = range(of: prefix), prefixRange.lowerBound == startIndex { removeSubrange(prefixRange) } } /// Returns a string with the given prefix removed, if it exists. /// /// - Parameters: /// - prefix: A possible prefix to remove from this string. /// func removingPrefix(_ prefix: String) -> String { var copy = self copy.removePrefix(prefix) return copy } /// Removes the prefix from the string that matches the given pattern, if any. /// /// Calling this method might invalidate any existing indices for use with this string. /// /// - Parameters: /// - pattern: The regular expression pattern to search for. Avoid using `^`. /// - options: The options applied to the regular expression during matching. /// /// - Throws: an error if it the pattern is not a valid regular expression. /// mutating func removePrefix(pattern: String, options: NSRegularExpression.Options = []) throws { let regexp = try NSRegularExpression(pattern: "^\(pattern)", options: options) let fullRange = NSRange(location: 0, length: (self as NSString).length) if let match = regexp.firstMatch(in: self, options: [], range: fullRange) { let matchRange = match.range self = (self as NSString).replacingCharacters(in: matchRange, with: "") } } /// Returns a string without the prefix that matches the given pattern, if it exists. /// /// - Parameters: /// - pattern: The regular expression pattern to search for. Avoid using `^`. /// - options: The options applied to the regular expression during matching. /// /// - Throws: an error if it the pattern is not a valid regular expression. /// func removingPrefix(pattern: String, options: NSRegularExpression.Options = []) throws -> String { var copy = self try copy.removePrefix(pattern: pattern, options: options) return copy } } // MARK: - Suffix removal public extension String { /// Removes the given suffix from the string, if exists. /// /// Calling this method might invalidate any existing indices for use with this string. /// /// - Parameters: /// - suffix: A possible suffix to remove from this string. /// mutating func removeSuffix(_ suffix: String) { if let suffixRange = range(of: suffix, options: [.backwards]), suffixRange.upperBound == endIndex { removeSubrange(suffixRange) } } /// Returns a string with the given suffix removed, if it exists. /// /// - Parameters: /// - suffix: A possible suffix to remove from this string. /// func removingSuffix(_ suffix: String) -> String { var copy = self copy.removeSuffix(suffix) return copy } /// Removes the suffix from the string that matches the given pattern, if any. /// /// Calling this method might invalidate any existing indices for use with this string. /// /// - Parameters: /// - pattern: The regular expression pattern to search for. Avoid using `$`. /// - options: The options applied to the regular expression during matching. /// /// - Throws: an error if it the pattern is not a valid regular expression. /// mutating func removeSuffix(pattern: String, options: NSRegularExpression.Options = []) throws { let regexp = try NSRegularExpression(pattern: "\(pattern)$", options: options) let fullRange = NSRange(location: 0, length: (self as NSString).length) if let match = regexp.firstMatch(in: self, options: [], range: fullRange) { let matchRange = match.range self = (self as NSString).replacingCharacters(in: matchRange, with: "") } } /// Returns a string without the suffix that matches the given pattern, if it exists. /// /// - Parameters: /// - pattern: The regular expression pattern to search for. Avoid using `$`. /// - options: The options applied to the regular expression during matching. /// /// - Throws: an error if it the pattern is not a valid regular expression. /// func removingSuffix(pattern: String, options: NSRegularExpression.Options = []) throws -> String { var copy = self try copy.removeSuffix(pattern: pattern, options: options) return copy } }
gpl-2.0
4d2e71e013751e08038ae5bbc48bdcf7
36.137725
107
0.626572
4.804028
false
false
false
false
zzw19880707/shadow
Sources/Routes/Register/control/RegisterRoutes.swift
1
1552
// // RegisterRo.swift // PerfectTemplate // // Created by zhengzw on 2016/11/24. // // import PerfectLib import PerfectHTTP import PerfectHTTPServer import Foundation class RegisterRoutes { class func create() -> Routes { var routes = Routes(baseUri: "register") routes.add(method: .post , uri: "", handler: { request, response in //设置编码集 response.setHeader(.contentType, value: "text/html; charset=UTF-8") //接收参数 let username = request.param(name: "username") let password = request.param(name: "password")?.md5() if let u = username, let p = password { print("username :" + u + "password :" + p) let user = UserModel(userId: 0, username: u, password: p, createTime: "\(NSDate())" ) let result = LoginDBManager().insert(user: user) if result { response.setBody(string:try! ["msg":"成功","code":code.success.rawValue].jsonEncodedString()) }else { response.setBody(string: try! ["msg":"用户名重复","code":code.用户名重复.rawValue].jsonEncodedString()) } }else{ Log.warning(message: "用户名密码未输入 ") response.setBody(string: try! ["msg":"用户名密码为空","code":code.用户名密码为空.rawValue].jsonEncodedString()) } response.completed() }) return routes } }
apache-2.0
ce0a328d5b89f9d81894210ae455e800
34.756098
115
0.548431
4.350148
false
false
false
false
evgenykarev/MapKit-and-UIKit-Examples
MapPoints/MapPointFirebaseManager.swift
1
5330
// // MapPointFirebaseManager.swift // MapPoints // // Created by Evgeny Karev on 06.06.17. // Copyright © 2017 Evgeny Karev. All rights reserved. // import FirebaseDatabase import GeoFire protocol FirebaseManagerDelegate: class { // creating points func firebaseManager(_ manager: FirebaseManager, didCreate mapPoint: MapPoint, error: Error?) func firebaseManager(_ manager: FirebaseManager, willCreate mapPoint: MapPoint) // removing points func firebaseManager(_ manager: FirebaseManager, didRemove mapPoint: MapPoint, error: Error?) // load points from Firebase func firebaseManager(_ manager: FirebaseManager, didLoad mapPoint: MapPoint) func firebaseManager(_ manager: FirebaseManager, didRemove mapPointId: String) } class FirebaseManager { static let instance = FirebaseManager() private let refPoints: DatabaseReference private let refPointLocations: DatabaseReference private let geoFirePoints: GeoFire weak var delegate: FirebaseManagerDelegate? init() { Database.database().isPersistenceEnabled = true refPoints = Database.database().reference(withPath: "points") refPointLocations = Database.database().reference(withPath: "pointLocations") geoFirePoints = GeoFire(firebaseRef: refPointLocations) } func createMapPoint(for annotation: MKPointAnnotationIcon) { let id = refPoints.childByAutoId().key let mapPoint = MapPoint(id: id, annotation: annotation) delegate?.firebaseManager(self, willCreate: mapPoint) let point = mapPoint.firebaseDict refPoints.updateChildValues([id: point]) { (error, _) in guard error == nil else { self.delegate?.firebaseManager(self, didCreate: mapPoint, error: error) return } } geoFirePoints.setLocation(for: mapPoint.coordinate, for: id) { (error: Error?) in guard error == nil else { self.delegate?.firebaseManager(self, didCreate: mapPoint, error: error) return } self.delegate?.firebaseManager(self, didCreate: mapPoint, error: nil) } } func removeMapPoint(_ mapPoint: MapPoint) { refPointLocations.child(mapPoint.id).removeValue { (error: Error?, _: DatabaseReference) in guard error == nil else { self.delegate?.firebaseManager(self, didRemove: mapPoint, error: error!) return } } refPoints.child(mapPoint.id).removeValue(completionBlock: { (error: Error?, _: DatabaseReference) in // if error recieved ignore it, because point location was deleted self.delegate?.firebaseManager(self, didRemove: mapPoint, error: nil) }) } private var pointsQuery: GFCircleQuery? private func setupListeners() { guard let query = pointsQuery else { return } query.observe(.keyEntered) { (id: String?, location: CLLocation?) in guard let pointId = id else { return } guard let pointLocation = location else { return } self.refPoints.child(pointId).observeSingleEvent(of: .value, with: { (snapshot) in guard let pointDictionary = snapshot.value as? NSDictionary else { print("error load \(pointId)-\(pointLocation)") return } guard let pointTitle = pointDictionary["title"] as? String else { print("error load \(pointId)-\(pointLocation)") return } let mapPoint = MapPoint(id: pointId, coordinate: pointLocation.coordinate, title: pointTitle) self.delegate?.firebaseManager(self, didLoad: mapPoint) }) } query.observe(.keyExited) { (id: String?, _: CLLocation?) in guard let pointId = id else { return } self.delegate?.firebaseManager(self, didRemove: pointId) } } var isListening: Bool = false { didSet { guard oldValue != isListening else { return } if isListening { setupListeners() } else { pointsQuery?.removeAllObservers() } } } func updateListening(for mapView: MKMapView) { let centerMap = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude) let mapRadius = mapView.mapRadiusMeters/1000 let minRadius = 1.0 let maxRadius = 100.0 var radius = mapRadius * 10 radius = max(radius, minRadius) radius = min(radius, maxRadius) if let query = pointsQuery { query.center = centerMap query.radius = radius } else { if isListening { pointsQuery = self.geoFirePoints.query(at: centerMap, withRadius: radius) setupListeners() } } } }
mit
5f08e7a52d6eda859fc3cb5f76297fe5
32.099379
126
0.584537
5.41565
false
false
false
false
rahul-apple/XMPP-Zom_iOS
Zom/Zom/Classes/View Controllers/Onboarding/ZomCongratsViewController.swift
1
4335
// // ZomCongratsViewController.swift // Zom // // Created by N-Pex on 2017-01-24. // // import UIKit import MobileCoreServices public class ZomCongratsViewController: UIViewController { @IBOutlet weak var avatarImageView:UIButton! public var account:OTRAccount? { didSet { guard let acct = account else { return; } self.viewHandler?.keyCollectionObserver.observe(acct.uniqueId, collection: OTRAccount.collection()) } } private var avatarPicker:OTRAttachmentPicker? private var viewHandler:OTRYapViewHandler? public override func viewDidLoad() { super.viewDidLoad() if let connection = OTRDatabaseManager.sharedInstance().longLivedReadOnlyConnection { self.viewHandler = OTRYapViewHandler(databaseConnection: connection, databaseChangeNotificationName: DatabaseNotificationName.LongLivedTransactionChanges) if let accountKey = account?.uniqueId { self.viewHandler?.keyCollectionObserver.observe(accountKey, collection: OTRAccount.collection()) } self.viewHandler?.delegate = self } } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.avatarImageView.layer.cornerRadius = CGRectGetWidth(self.avatarImageView.frame)/2; self.avatarImageView.userInteractionEnabled = true self.avatarImageView.clipsToBounds = true; } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.refreshAvatarImage(self.account) } func refreshAvatarImage(account:OTRAccount?) { if let account = self.account, let data = account.avatarData where data.length > 0 { self.avatarImageView.setImage(account.avatarImage(), forState: .Normal) } else { self.avatarImageView.setImage(UIImage(named: "onboarding_avatar", inBundle: OTRAssets.resourcesBundle(), compatibleWithTraitCollection: nil), forState: .Normal) } } @IBAction func avatarButtonPressed(sender: AnyObject) { let picker = OTRAttachmentPicker(parentViewController: self, delegate: self) self.avatarPicker = picker picker.showAlertControllerWithCompletion(nil) } /** Uses the global readOnlyDatabaseConnection to refetch the account object and refresh the avatar image view with that new object*/ private func refreshViews() { guard let key = self.account?.uniqueId else { self.refreshAvatarImage(nil) return } var account:OTRAccount? = nil OTRDatabaseManager.sharedInstance().longLivedReadOnlyConnection?.asyncReadWithBlock({ (transaction) in account = OTRAccount .fetchObjectWithUniqueID(key, transaction: transaction) }, completionQueue: dispatch_get_main_queue()) { self.account = account self.refreshAvatarImage(self.account) } } } extension ZomCongratsViewController: OTRYapViewHandlerDelegateProtocol { public func didReceiveChanges(handler: OTRYapViewHandler, key: String, collection: String) { if key == self.account?.uniqueId { self.refreshViews() } } } extension ZomCongratsViewController:OTRAttachmentPickerDelegate { public func attachmentPicker(attachmentPicker: OTRAttachmentPicker!, gotVideoURL videoURL: NSURL!) { } public func attachmentPicker(attachmentPicker: OTRAttachmentPicker!, gotPhoto photo: UIImage!, withInfo info: [NSObject : AnyObject]!) { guard let account = self.account else { return } if (OTRProtocolManager.sharedInstance().protocolForAccount(account) != nil) { if let xmppManager = OTRProtocolManager.sharedInstance().protocolForAccount(account) as? OTRXMPPManager { xmppManager.setAvatar(photo, completion: { (success) in //We updated the avatar }) } } } public func attachmentPicker(attachmentPicker: OTRAttachmentPicker!, preferredMediaTypesForSource source: UIImagePickerControllerSourceType) -> [String]! { return [kUTTypeImage as String] } }
mpl-2.0
d3828248d8c7ce389bea15229acac97f
37.362832
172
0.671742
5.579151
false
false
false
false
mrlegowatch/JSON-to-Swift-Converter
JSON to Swift ConverterTests/JSONPropertyTests.swift
1
11275
// // JSONPropertyTests.swift // JSON to Swift Converter // // Created by Brian Arnold on 2/25/17. // Copyright © 2018 Brian Arnold. All rights reserved. // import XCTest class JSONPropertyTests: XCTestCase { var appSettings: AppSettings! override func setUp() { super.setUp() // Use an isolated version of app settings appSettings = AppSettings(UserDefaults(suiteName: "JSON-to-Swift-tests-properties")!) appSettings.reset() } func testNumberValueType() { do { let bool = NSNumber(value: true) let (type, defaultValue) = bool.valueType XCTAssertEqual(type, "Bool", "NSNumber Bool type") XCTAssertEqual(defaultValue, "false", "NSNumber Bool default value") } do { let int = NSNumber(value: 31) let (type, defaultValue) = int.valueType XCTAssertEqual(type, "Int", "NSNumber Int type") XCTAssertEqual(defaultValue, "0", "NSNumber Int default value") } do { let double = NSNumber(value: -78.234) let (type, defaultValue) = double.valueType XCTAssertEqual(type, "Double", "NSNumber Double type") XCTAssertEqual(defaultValue, "0.0", "NSNumber Double default value") } } func testStringTojsonObject() { // Empty string do { let string = "" let object = string.jsonObject XCTAssertNil(object, "empty string should produce nil") } // Simple string do { let string = "\"name\"" let object = string.jsonObject XCTAssertNil(object, "simple string should produce nil dictionary") } // Simple dictionary do { let string = "{ \"name\": \"Frodo\" }" let dictionary = string.jsonObject as? [String: Any] XCTAssertNotNil(dictionary, "simple dictionary should be non-nil") XCTAssertEqual(dictionary?["name"] as? String, "Frodo", "simple dictionary should have an item") } // Negative test, badly constructed dictionary do { let string = "{ \"name\": }" let dictionary = string.jsonObject XCTAssertNil(dictionary, "simple dictionary should be non-nil") } } func testSimpleProperty() { /// Test a simple property do { let property = JSONProperty("key", name: "name", dictionary: [:], appSettings: appSettings) XCTAssertEqual(property.key, "key", "property key") XCTAssertEqual(property.name, "name", "property name") XCTAssertTrue(property.dictionary.isEmpty, "property dictionary") } /// Test an invalid string do { let property = JSONProperty(from: "\"hello\"", appSettings: appSettings) XCTAssertNil(property, "simple string should return nil property") } } func testDictionaryProperty() { /// Test a slightly non-trival dictionary with child dictionaries, arrays of ints, and arrays of dictionaries let string = "{ \"name\": \"Bilbo\", \"info\": [ { \"age\": 111 }, { \"weight\": 25.8 } ], \"attributes\": { \"strength\": 12 }, \"miscellaneous scores\": [2, 3] }" let property = JSONProperty(from: string, appSettings: appSettings) XCTAssertNotNil(property, "property should be non-nil") let indent = LineIndent(useTabs: false, indentationWidth: 4) // Note: we are going to mess with app settings shared instance, which affects state across unit test sessions. do { // NB, this is a white box test, allKeys shouldn't be called directly let keys = property!.allKeys print("keys = \(keys)") // TODO: see comment in JSONProperty regarding [Any] children // the parsing via makeRootProperty misses the second array dictionary "weight" key XCTAssertEqual(keys.count, 6 /*7*/, "property should have 7 unique keys") // Test propertyKeys output let propertyKeys = property?.propertyKeys(indent: indent) print("propertyKeys = \n\(propertyKeys ?? "")") XCTAssertTrue(propertyKeys?.hasPrefix("\nprivate enum CodingKeys: String, CodingKey {\n") ?? false, "prefix for property keys") XCTAssertTrue(propertyKeys?.contains(" case ") ?? false, "declarations for property keys") XCTAssertTrue(propertyKeys?.contains(" miscellaneousScores = ") ?? false, "a specific key declaration") XCTAssertTrue(propertyKeys?.contains("\"miscellaneous scores\"") ?? false, "a specific key value") XCTAssertTrue(propertyKeys?.hasSuffix("\n}\n") ?? false, "suffix for property keys") } // Test typeContent output do { let typeContent = property?.typeContent(indent: indent) XCTAssertFalse(typeContent?.isEmpty ?? true, "typeContent should be non-empty") print("typeContent = \n\(typeContent ?? "")") XCTAssertTrue(typeContent?.contains("struct <#InfoType#>: Codable {") ?? false, "a specific type declaration") XCTAssertTrue(typeContent?.contains("struct <#AttributesType#>: Codable {") ?? false, "a specific type declaration") } // Test propertyContent output do { let propertyContent = property?.propertyContent(indent: indent) XCTAssertFalse(propertyContent?.isEmpty ?? true, "typeContent should be non-empty") print("propertyContent (default) = \n\(propertyContent ?? "")") XCTAssertTrue(propertyContent?.contains("let info: [<#InfoType#>]!") ?? false, "a specific type declaration") XCTAssertTrue(propertyContent?.contains("let name: String!") ?? false, "a specific type declaration") XCTAssertTrue(propertyContent?.contains("let attributes: <#AttributesType#>!") ?? false, "a specific type declaration") XCTAssertTrue(propertyContent?.contains("let miscellaneousScores: [Int]!") ?? false, "a specific type declaration") } do { // Change the defaults and check the new output appSettings.declaration = .useVar appSettings.typeUnwrapping = .optional appSettings.addDefaultValue = true let propertyContent = property?.propertyContent(indent: indent) print("propertyContent (non-default) = \n\(propertyContent ?? "")") XCTAssertTrue(propertyContent?.contains("var info: [<#InfoType#>]? = []") ?? false, "a specific type declaration") XCTAssertTrue(propertyContent?.contains("var name: String? = \"\"") ?? false, "a specific type declaration") XCTAssertTrue(propertyContent?.contains("var attributes: <#AttributesType#>? = [:]") ?? false, "a specific type declaration") XCTAssertTrue(propertyContent?.contains("var miscellaneousScores: [Int]? = []") ?? false, "a specific type declaration") } } func testAddInitAndDictionary() { let string = "{ \"name\": \"Bilbo\", \"info\": [ { \"age\": 111 }, { \"weight\": 25.8 } ], \"attributes\": { \"strength\": 12 }, \"miscellaneous scores\": [2, 3] }" let property = JSONProperty(from: string, appSettings: appSettings) XCTAssertNotNil(property, "property should be non-nil") let indent = LineIndent(useTabs: false, indentationWidth: 4) // Note: we are going to mess with app settings shared instance, which affects state across unit test sessions. appSettings.addDefaultValue = true appSettings.supportCodable = true // var with optional will set default values in the declarations do { appSettings.declaration = .useVar appSettings.typeUnwrapping = .optional let propertyContent = property?.propertyContent(indent: indent) print("init with var and optional = \n\(propertyContent ?? "")") } // let with optional will set default values in the init method do { appSettings.declaration = .useLet appSettings.typeUnwrapping = .optional let propertyContent = property?.propertyContent(indent: indent) print("init with let and optional = \n\(propertyContent ?? "")") } // let with explicit will use guard do { appSettings.declaration = .useLet appSettings.typeUnwrapping = .explicit let propertyContent = property?.propertyContent(indent: indent) print("init with let and explicit = \n\(propertyContent ?? "")") } } func testJSONArray() { let string = "[\"name\", \"age\"]" let property = JSONProperty(from: string, appSettings: appSettings) XCTAssertNotNil(property, "property should be non-nil") let indent = LineIndent(useTabs: false, indentationWidth: 4) do { let propertyContent = property?.propertyContent(indent: indent) print("propertyContent (array) = \n\(propertyContent ?? "")") } } func testJSONPropertyOutput() { guard let testClassesFile = Bundle(for: JSONPropertyTests.self).url(forResource: "TestClasses", withExtension: "json") else { XCTFail("TestClasses.json is missing") return } guard let testClasses = try? String(contentsOf: testClassesFile) else { XCTFail("TestClasses.json could not be converted to string.") return } guard let property = JSONProperty(from: testClasses, appSettings: appSettings) else { XCTFail("JSONProperty could not be parsed.") return } let lineIndent = LineIndent(useTabs: false, indentationWidth: 4, level: 1) let propertyKeys = property.propertyKeys(indent: lineIndent) print("propertyKeys = \n\(propertyKeys)") let typeContent = property.typeContent(indent: lineIndent) print("typeContent = \n\(typeContent)") let propertyContent = property.propertyContent(indent: lineIndent) print("propertyContent = \n\(propertyContent)") } func testJSONPropertyPerformance() { let testClassesFile = Bundle(for: JSONPropertyTests.self).url(forResource: "TestClasses", withExtension: "json")! let testClasses = try! String(contentsOf: testClassesFile, encoding: .utf8) let property = JSONProperty(from: testClasses, appSettings: appSettings)! self.measure { let lineIndent = LineIndent(useTabs: false, indentationWidth: 4, level: 1) let _ = property.propertyKeys(indent: lineIndent) let _ = property.typeContent(indent: lineIndent) let _ = property.propertyContent(indent: lineIndent) } } }
mit
3893455230e680953883e261d38419ba
41.86692
172
0.597836
5.355819
false
true
false
false
iWeslie/Ant
Ant/Ant/Main/NewsComment.swift
2
1021
// // NewsComment.swift // Ant // // Created by LiuXinQiang on 2017/8/15. // Copyright © 2017年 LiuXinQiang. All rights reserved. // import UIKit class NewsComment: NSObject { var id : NSNumber? var msg_id : NSNumber? var time : String? var height : CGFloat? var content : String? { didSet { self.height = self.getLabHeight(labelStr: content!, font: UIFont.italicSystemFont(ofSize: 14), width: width - 90) + CGFloat(110) } } var user_info : NewsUserInfoModel? func getLabHeight(labelStr: String, font: UIFont, width: CGFloat) -> CGFloat { let statusLabelText = labelStr let size = CGSize(width: width, height: 900) let dic = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying) let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context: nil).size return strSize.height } }
apache-2.0
666cfc81b5e1f3946afa5a7ea2ad941d
27.277778
157
0.636542
4.072
false
false
false
false
adauguet/ClusterMapView
ClusterMapView/Node.swift
1
5919
import Foundation import MapKit public class Node: NSObject, MKAnnotation { public enum NodeType { case root(children: [Node]) case node(parent: Node, children: [Node]) case leaf(parent: Node, annotation: MKAnnotation) } private var annotation: MKAnnotation? var mapRect: MKMapRect private var mapPoint: MKMapPoint public dynamic var coordinate: CLLocationCoordinate2D private var parent: Node? private var children: [Node] = [] private var depth: Int public var type: NodeType { switch (parent, children) { case (nil, let children): return .root(children: children) case (let parent?, let children) where children.isEmpty: return .leaf(parent: parent, annotation: annotation!) case (let parent?, let children): return .node(parent: parent, children: children) } } public var annotations: [MKAnnotation] { switch type { case .leaf(_, let annotation): return [annotation] case .root(let children), .node(_, let children): return children.flatMap { $0.annotations } } } public convenience init(annotations: [MKAnnotation]) { let markers = annotations.map { Marker(annotation: $0) } self.init(markers: markers) } init(markers: [Marker], depth: Int = 0) { self.depth = depth if markers.count == 1, let marker = markers.first { self.annotation = marker.annotation self.mapPoint = marker.mapPoint self.coordinate = MKCoordinateForMapPoint(mapPoint) self.mapRect = MKMapRect(origin: marker.mapPoint, size: .zero) super.init() } else { let (mapPoint, mapRect, children) = Marker.divide(markers: markers) self.mapPoint = mapPoint self.coordinate = MKCoordinateForMapPoint(mapPoint) self.mapRect = mapRect self.children = children.map { Node(markers: $0, depth: depth + 1) } super.init() // reference parent after self init self.children.forEach { $0.parent = self } } } func isParent(node: Node) -> Bool { guard let parent = node.parent else { return false } if parent == self { return true } else { return isParent(node: parent) } } func depthAndNodes(mapRect: MKMapRect, maximum: Int) -> (depth: Int, insideNodes: [Node], outsideNodes: [Node]) { var insideNodes: [Node] = [self] var outsideNodes = [Node]() var previousInside = [Node]() var previousOutside = [Node]() var nextInsideNodes = [Node]() var nextOutsideNodes = [Node]() // init depth to its node's var depth = self.depth // keep track of root/node nodes left var areNodesLeft = true // compute next level nodes while (insideNodes.count <= maximum && !insideNodes.isEmpty && areNodesLeft) { depth += 1 // Save previous state previousInside = insideNodes previousOutside = outsideNodes nextInsideNodes = [] nextOutsideNodes = [] areNodesLeft = false for insideNode in insideNodes { switch insideNode.type { case .leaf: // since this method is always called on a root/node node, // only leaf nodes contained in the desired mapRect can be present in nodes // so it is not necessary to check it here nextInsideNodes.append(insideNode) case .node(_, let children), .root(let children): for child in children { switch child.type { case .root, .node: // if the root/node node intersects with the current mapRect // then keep it as inside, toggle the flag // else keep it as outside if MKMapRectIntersectsRect(mapRect, child.mapRect) { nextInsideNodes.append(child) areNodesLeft = true } else { nextOutsideNodes.append(child) } case .leaf: // if the child node is contained in current mapRect // then keep it as inside // else keep it as outside if MKMapRectContainsPoint(mapRect, child.mapPoint) { nextInsideNodes.append(child) } else { nextOutsideNodes.append(child) } } } } } for outsideNode in outsideNodes { switch outsideNode.type { case .leaf: nextOutsideNodes.append(outsideNode) case .node(_, let children), .root(let children): nextOutsideNodes += children } } insideNodes = nextInsideNodes outsideNodes = nextOutsideNodes } if insideNodes.count > maximum { insideNodes = previousInside outsideNodes = previousOutside if depth > 0 { depth -= 1 } } return (depth, insideNodes, outsideNodes) } }
mit
a412d0c41b8c807d65b66f386f98e89c
34.656627
117
0.501267
5.702312
false
false
false
false
Fenrikur/ef-app_ios
Domain Model/EurofurenceModel/Public/Server Client/Response/EventCharacteristics.swift
1
1790
import Foundation public struct EventCharacteristics: Equatable, Identifyable { public var identifier: String public var roomIdentifier: String public var trackIdentifier: String public var dayIdentifier: String public var startDateTime: Date public var endDateTime: Date public var title: String public var subtitle: String public var abstract: String public var panelHosts: String public var eventDescription: String public var posterImageId: String? public var bannerImageId: String? public var tags: [String]? public var isAcceptingFeedback: Bool public init(identifier: String, roomIdentifier: String, trackIdentifier: String, dayIdentifier: String, startDateTime: Date, endDateTime: Date, title: String, subtitle: String, abstract: String, panelHosts: String, eventDescription: String, posterImageId: String?, bannerImageId: String?, tags: [String]?, isAcceptingFeedback: Bool) { self.identifier = identifier self.roomIdentifier = roomIdentifier self.trackIdentifier = trackIdentifier self.dayIdentifier = dayIdentifier self.startDateTime = startDateTime self.endDateTime = endDateTime self.title = title self.subtitle = subtitle self.abstract = abstract self.panelHosts = panelHosts self.eventDescription = eventDescription self.posterImageId = posterImageId self.bannerImageId = bannerImageId self.tags = tags self.isAcceptingFeedback = isAcceptingFeedback } }
mit
31a31c12354045d2376b05e24b488fa3
32.148148
61
0.631285
5.628931
false
false
false
false
KevinYangGit/DYTV
DYZB/DYZB/Classes/Tools/NetworkTools.swift
1
937
// // NetworkTools.swift // DYZB // // Created by boxfishedu on 2016/10/17. // Copyright © 2016年 杨琦. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools: NSObject { class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) { //获取类型 let method = type == .get ? HTTPMethod.get : HTTPMethod.post //发送网络请求 Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in //获取结果 guard let result = response.result.value else { print(response.result.error) return } //通过回调返回结果 finishedCallback(result) } } }
mit
7782f3791495f909115d2e6254f1cb77
22.945946
158
0.564334
4.56701
false
false
false
false
gribozavr/swift
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_generic_use.swift
1
1725
// RUN: %swift -target %module-target-future -emit-ir -prespecialize-generic-metadata %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios struct Outer<First> { let first: First } struct Inner<First> { let first: First } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // TODO: Once prespecialization is done for generic arguments which are // themselves generic (Outer<Inner<Int>>, here), a direct reference to // the prespecialized metadata should be emitted here. // CHECK: [[TYPE:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s4main5OuterVyAA5InnerVySiGGMD") // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* [[TYPE]]) // CHECK: } func doit() { consume( Outer(first: Inner(first: 13)) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5OuterVMa"([[INT]], %swift.type*) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* undef, i8* undef, %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8 }>* @"$s4main5OuterVMn" to %swift.type_descriptor*)) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
d4e8c8386d8d121b2ec9f9844583d14c
43.230769
335
0.65971
3.165138
false
false
false
false
adolfrank/Swift_practise
25-day/25-day/FifthViewController.swift
1
1847
// // FifthViewController.swift // 25-day // // Created by Hongbo Yu on 16/5/19. // Copyright © 2016年 Frank. All rights reserved. // import UIKit class FifthViewController: UIViewController { @IBOutlet weak var trump1: UIImageView! @IBOutlet weak var trump2: UIImageView! @IBOutlet weak var trump3: UIImageView! @IBOutlet weak var trump4: UIImageView! @IBOutlet weak var trump5: UIImageView! @IBOutlet weak var trump6: UIImageView! @IBOutlet weak var trump7: UIImageView! @IBOutlet weak var trump8: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func spin() { UIView.animateWithDuration(0.8, delay: 0, options: .CurveLinear, animations: { self.trump1.transform = CGAffineTransformRotate(self.trump1.transform, CGFloat(M_PI)) self.trump2.transform = CGAffineTransformRotate(self.trump2.transform, CGFloat(M_PI)) self.trump3.transform = CGAffineTransformRotate(self.trump3.transform, CGFloat(M_PI)) self.trump4.transform = CGAffineTransformRotate(self.trump4.transform, CGFloat(M_PI)) self.trump5.transform = CGAffineTransformRotate(self.trump5.transform, CGFloat(M_PI)) self.trump6.transform = CGAffineTransformRotate(self.trump6.transform, CGFloat(M_PI)) self.trump7.transform = CGAffineTransformRotate(self.trump7.transform, CGFloat(M_PI)) self.trump8.transform = CGAffineTransformRotate(self.trump8.transform, CGFloat(M_PI)) }) { (finished) -> Void in self.spin() } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.spin() } }
mit
11cb6e82dcfa47cb4bd0ca4a84b5d5aa
30.793103
97
0.652928
4.400955
false
false
false
false
harenbrs/swix
swix/swix/swix/matrix/m-image.swift
1
5592
// // twoD-image.swift // swix // // Created by Scott Sievert on 7/30/14. // Copyright (c) 2014 com.scott. All rights reserved. // /* * some other useful tips that need an iOS app to use: * 1. UIImage to raw array[0]: * 2. raw array to UIImage[1]: * * for a working implementation, see[2] (to be published shortly) * * [0]:http://stackoverflow.com/a/1262893/1141256 * [1]:http://stackoverflow.com/a/12868860/1141256 * [2]:https://github.com/scottsievert/saliency/blob/master/AVCam/AVCam/saliency/imageToRawArray.m * * */ import Foundation func rgb2hsv_pixel(R:Double, G:Double, B:Double)->(Double, Double, Double){ // tested against wikipedia/HSL_and_HSV. returns (H, S_hsv, V) let M = max(array(R, G, B)) let m = min(array(R, G, B)) let C = M - m var Hp:Double = 0 if M==R {Hp = ((G-B)/C) % 6} else if M==G {Hp = ((B-R)/C) + 2} else if M==B {Hp = ((R-G)/C) + 4} let H = 60 * Hp let V = M var S = 0.0 if !(V==0) {S = C/V} return (H, S, V) } func rgb2hsv(r:matrix, g:matrix, b:matrix)->(matrix, matrix, matrix){ assert(r.shape.0 == g.shape.0) assert(b.shape.0 == g.shape.0) assert(r.shape.1 == g.shape.1) assert(b.shape.1 == g.shape.1) var h = zeros_like(r) var s = zeros_like(g) var v = zeros_like(b) for i in 0..<r.shape.0{ for j in 0..<r.shape.1{ let (h_p, s_p, v_p) = rgb2hsv_pixel(r[i,j], G: g[i,j], B: b[i,j]) h[i,j] = h_p s[i,j] = s_p v[i,j] = v_p } } return (h, s, v) } func rgb2_hsv_vplane(r:matrix, g:matrix, b:matrix)->matrix{ return max(max(r, y: g), y: b) } func savefig(x:matrix, filename:String, save:Bool=true, show:Bool=false){ // assumes Python is on your $PATH and pylab/etc are installed // prefix should point to the swix folder! // prefix is defined in numbers.swift // assumes python is on your path write_csv(x, filename:"swix/temp.csv") system("cd "+S2_PREFIX+"; "+PYTHON_PATH + " imshow.py \(filename) \(save) \(show)") system("rm "+S2_PREFIX+"temp.csv") } func imshow(x: matrix){ savefig(x, filename: "junk", save:false, show:true) } //func UIImageToRGBA(image:UIImage)->(matrix, matrix, matrix, matrix){ // // returns red, green, blue and alpha channels // // // init'ing // var imageRef = image.CGImage // var width = CGImageGetWidth(imageRef) // var height = CGImageGetHeight(imageRef) // var colorSpace = CGColorSpaceCreateDeviceRGB() // var bytesPerPixel = 4 // var bytesPerRow:UInt = UInt(bytesPerPixel) * UInt(width) // var bitsPerComponent:UInt = 8 // var pix = Int(width) * Int(height) // var count:Int = 4*Int(pix) // // // pulling the color out of the image // var rawData:[CUnsignedChar] = Array(count:count, repeatedValue:0) // var bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedLast.toRaw())! // var context = CGBitmapContextCreate(&rawData, UInt(width), UInt(height), bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo) // CGContextDrawImage(context, CGRectMake(0,0,CGFloat(width), CGFloat(height)), imageRef) // // // // unsigned char to double conversion // var rawDataArray = zeros(count)-1 // vDSP_vfltu8D(&rawData, 1, &rawDataArray.grid, 1, count.length) // // // pulling the RGBA channels out of the color // var i = arange(pix) // var r = zeros((Int(height), Int(width)))-1; // r.flat = rawDataArray[4*i+0] // // var g = zeros((Int(height), Int(width))); // g.flat = rawDataArray[4*i+1] // // var b = zeros((Int(height), Int(width))); // b.flat = rawDataArray[4*i+2] // // var a = zeros((Int(height), Int(width))); // a.flat = rawDataArray[4*i+3] // return (r, g, b, a) //} //func RGBAToUIImage(r:matrix, g:matrix, b:matrix, a:matrix)->UIImage{ // // setup // var height = r.shape.0 // var width = r.shape.1 // var area = height * width // var componentsPerPixel = 4 // rgba // var compressedPixelData = zeros(4*area) // var N = width * height // // // double to unsigned int // var i = arange(N) // compressedPixelData[4*i+0] = r.flat // compressedPixelData[4*i+1] = g.flat // compressedPixelData[4*i+2] = b.flat // compressedPixelData[4*i+3] = a.flat // var pixelData:[CUnsignedChar] = Array(count:area*componentsPerPixel, repeatedValue:0) // vDSP_vfixu8D(&compressedPixelData.grid, 1, &pixelData, 1, vDSP_Length(componentsPerPixel*area)) // // // creating the bitmap context // var colorSpace = CGColorSpaceCreateDeviceRGB() // var bitsPerComponent = 8 // var bytesPerRow = ((bitsPerComponent * width) / 8) * componentsPerPixel // var bitmapInfo = CGBitmapInfo.fromRaw(CGImageAlphaInfo.PremultipliedLast.toRaw())! // var context = CGBitmapContextCreate(&pixelData, UInt(width), UInt(height), UInt(bitsPerComponent), UInt(bytesPerRow), colorSpace, bitmapInfo) // // // creating the image // var toCGImage = CGBitmapContextCreateImage(context) // var image:UIImage = UIImage.init(CGImage:toCGImage) // return image //} //func resizeImage(image:UIImage, shape:(Int, Int)) -> UIImage{ // // nice variables // var (height, width) = shape // var cgSize = CGSizeMake(width, height) // // // draw on new CGSize // UIGraphicsBeginImageContextWithOptions(cgSize, false, 0.0) // image.drawInRect(CGRectMake(0, 0, width, height)) // var newImage = UIGraphicsGetImageFromCurrentImageContext() // UIGraphicsEndImageContext() // return newImage //}
mit
efe24fa5880eb73e517512a05fbb637e
33.95
147
0.623033
3.139809
false
false
false
false
marko628/Playground
Answers.playgroundbook/Contents/Sources/PlaygroundInternal/AnswersViewController.swift
1
20876
// AnswersViewController.swift import UIKit import PlaygroundSupport class AnswersViewController: UITableViewController, PlaygroundLiveViewMessageHandler, InputCellDelegate { private var items: [TranscriptItem] = [] private var textHeightCache = NSCache<NSString, NSNumber>() private var previousLayoutSize: CGSize = CGSize() private var hasPopoverContentInset = false private var hasKeyboardContentInset = false private var pendingPopoverCell: PopoverInputCell? = nil static let insertAnimationDuration: Double = 0.4 private static let popoverInsetAnimationDuration: Double = 0.25 private static let defaultBottomContentInset: CGFloat = 72.0 override func viewDidLoad() { super.viewDidLoad() view.translatesAutoresizingMaskIntoConstraints = false let placeholderView = UIView() let titleLabel = UILabel() titleLabel.text = NSLocalizedString("com.apple.playgroundbook.template.Answers.no-output-title", value: "No output to show", comment: "Title lablel when there is no output from the answers template") titleLabel.textColor = UIColor.black titleLabel.font = UIFont.systemFont(ofSize: 25.0, weight: UIFontWeightLight) titleLabel.translatesAutoresizingMaskIntoConstraints = false placeholderView.addSubview(titleLabel) let messageLabel = UILabel() messageLabel.text = NSLocalizedString("com.apple.playgroundbook.template.Answers.no-output-content", value: "Run your code to see your show() and ask() commands here", comment: "Content lablel when there is no output from the answers template") messageLabel.textColor = UIColor(white: 0.0, alpha: 0.5) messageLabel.font = UIFont.systemFont(ofSize: 17.0, weight: UIFontWeightLight) messageLabel.numberOfLines = 0 messageLabel.textAlignment = .center messageLabel.translatesAutoresizingMaskIntoConstraints = false placeholderView.addSubview(messageLabel) let topConstraint = NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: placeholderView, attribute: .bottom, multiplier: 0.24, constant: 0.0) NSLayoutConstraint.activate([ topConstraint, titleLabel.centerXAnchor.constraint(equalTo: placeholderView.centerXAnchor), messageLabel.centerXAnchor.constraint(equalTo: placeholderView.centerXAnchor), messageLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 20.0), messageLabel.widthAnchor.constraint(equalToConstant: 300.0) ]) tableView.backgroundView = placeholderView tableView.backgroundColor = UIColor(white: 1.0, alpha: 0.02) tableView.separatorStyle = .none tableView.keyboardDismissMode = .interactive tableView.cellLayoutMarginsFollowReadableWidth = false tableView.contentInset.bottom = AnswersViewController.defaultBottomContentInset tableView.allowsSelection = false tableView.register(MessageCell.self, forCellReuseIdentifier: MessageCell.reuseIdentifier) tableView.register(InputCell.self, forCellReuseIdentifier: InputCell.reuseIdentifier) tableView.register(NumberInputCell.self, forCellReuseIdentifier: NumberInputCell.reuseIdentifier) tableView.register(DateInputCell.self, forCellReuseIdentifier: DateInputCell.reuseIdentifier) tableView.register(ChoiceInputCell.self, forCellReuseIdentifier: ChoiceInputCell.reuseIdentifier) NotificationCenter.default.addObserver(self, selector: #selector(AnswersViewController.keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(AnswersViewController.keyboardDidShow(_:)), name: .UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(AnswersViewController.keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(AnswersViewController.keyboardDidHide(_:)), name: .UIKeyboardDidHide, object: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if view.bounds.width != previousLayoutSize.width || view.bounds.height != previousLayoutSize.height { if view.bounds.width != previousLayoutSize.width { textHeightCache.removeAllObjects() tableView.beginUpdates() tableView.endUpdates() } updateContentInsetsWithSize(view.bounds.size) previousLayoutSize = view.bounds.size if let lastItem = items.last, lastItem.isUserEntered { tableView.scrollToRow(at: IndexPath(row: items.count - 1, section: 0), at: .bottom, animated: false) tableView.beginUpdates() tableView.endUpdates() } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) for (index, item) in items.enumerated() { if item.isEditing { let indexPath = IndexPath(row: index, section: 0) if let cell = tableView.cellForRow(at: indexPath) as? InputCell { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) { cell.textEntryView.becomeFirstResponder() cell.textEntryView.becomeFirstResponder() } return } } } } // MARK: Internal Methods func show(_ string: String) { append(item: TranscriptItem(text: string), animated: true) } func ask(forType valueType: AnswersValueType, placeholder: String) { append(item: TranscriptItem(userEnteredText: "", valueType: valueType, placeholder: placeholder, isEditing: true), animated: true) } func clear() { items.removeAll() textHeightCache.removeAllObjects() tableView.reloadData() } // MARK: Private Methods private func updateContentInsetsWithSize(_ size: CGSize) { let screen = view.window?.screen ?? UIScreen.main // Add inset for top toolbar (when live view is not side-by-side) tableView.contentInset.top = size.width == screen.bounds.width / 2.0 || size.width == screen.bounds.height / 2.0 || size.width == 490.5 ? 20.0 : 72.0 } private func append(item: TranscriptItem, animated: Bool) { let insertedItemIndexPath = IndexPath(row: items.count, section: 0) let contentBottomMargin = tableView.contentOffset.y + tableView.frame.size.height - tableView.contentInset.bottom - tableView.contentSize.height items.append(item) tableView.beginUpdates() tableView.insertRows(at: [insertedItemIndexPath], with: .none) tableView.endUpdates() if animated { if contentBottomMargin.distance(to: 0.0) <= tableView.rectForRow(at: insertedItemIndexPath).height { scrollToInsertedCell(at: insertedItemIndexPath) } if let cell = tableView.cellForRow(at: insertedItemIndexPath) { let finalCellCenter = cell.center cell.center.y += 20 cell.alpha = 0.0 UIView.animate(withDuration: AnswersViewController.insertAnimationDuration, delay: 0.0, options: .curveEaseOut, animations: { cell.center = finalCellCenter cell.alpha = 1.0 }, completion: { (_) in if item.isEditing { (cell as! InputCell).textEntryView.becomeFirstResponder() (cell as! InputCell).textEntryView.becomeFirstResponder() } UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, cell) }) } } } private func scrollToInsertedCell(at indexPath: IndexPath) { let insertedCell = tableView.cellForRow(at: indexPath) if let popoverCell = insertedCell as? PopoverInputCell { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(AnswersViewController.resetContentInset), object: nil) if hasKeyboardContentInset { pendingPopoverCell = popoverCell UIView.animate(withDuration: AnswersViewController.insertAnimationDuration, delay: 0.0, options: [.beginFromCurrentState, .curveEaseOut], animations: { self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) }) } else { UIView.animate(withDuration: AnswersViewController.insertAnimationDuration, delay: 0.0, options: [.beginFromCurrentState, .curveEaseOut], animations: { self.tableView.contentInset.bottom = AnswersViewController.defaultBottomContentInset - self.tableView.contentInset.top + popoverCell.popoverContentSize.height + 40.0 self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) }) } hasPopoverContentInset = false } else { UIView.animate(withDuration: AnswersViewController.insertAnimationDuration, delay: 0.0, options: [.beginFromCurrentState, .allowUserInteraction], animations: { self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) }) } } @objc private func resetContentInset() { hasPopoverContentInset = false NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(AnswersViewController.resetContentInset), object: nil) UIView.animate(withDuration: AnswersViewController.popoverInsetAnimationDuration, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.tableView.contentInset.bottom = AnswersViewController.defaultBottomContentInset }) } @objc private func updateContentInset(forCell cell: PopoverInputCell) { guard let indexPath = cell.indexPath else { return } hasKeyboardContentInset = false UIView.animate(withDuration: AnswersViewController.popoverInsetAnimationDuration, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.tableView.contentInset.bottom = AnswersViewController.defaultBottomContentInset - self.tableView.contentInset.top + cell.popoverContentSize.height + 40.0 self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) }, completion: { (_) in cell.textEntryView.becomeFirstResponder() }) } @objc func keyboardWillShow(_ note: NSNotification) { if hasPopoverContentInset { resetContentInset() } } @objc func keyboardDidShow(_ note: NSNotification) { hasKeyboardContentInset = true } @objc func keyboardWillHide(_ note: NSNotification) { if let cell = pendingPopoverCell { pendingPopoverCell = nil perform(#selector(AnswersViewController.updateContentInset(forCell:)), with: cell, afterDelay: 0.01) } } @objc func keyboardDidHide(_ note: NSNotification) { hasKeyboardContentInset = false } // MARK: UITableViewDataSource Methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = items[indexPath.row] var cell: MessageCell if item.isUserEntered { let valueType = item.valueType ?? .string var cellReuseIdentifier: String switch valueType { case .number, .decimal: cellReuseIdentifier = NumberInputCell.reuseIdentifier case .date: cellReuseIdentifier = DateInputCell.reuseIdentifier case .choice(_): cellReuseIdentifier = ChoiceInputCell.reuseIdentifier default: cellReuseIdentifier = InputCell.reuseIdentifier } let inputCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! InputCell inputCell.delegate = self inputCell.indexPath = indexPath inputCell.messageText = item.text inputCell.valueType = valueType inputCell.placeholderText = item.placeholder inputCell.setInputEnabled(item.isEditing, animated: false) cell = inputCell } else { cell = tableView.dequeueReusableCell(withIdentifier: MessageCell.reuseIdentifier, for: indexPath) as! MessageCell cell.messageText = item.text cell.layoutMargins.right = InputCell.submitButtonWidthPlusSpacing + InputCell.defaultLayoutMargins.right } return cell } // MARK: UITableViewDelegate Methods override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let item = items[indexPath.row] var textHeight: Double? = textHeightCache.object(forKey: item.text as NSString)?.doubleValue if textHeight == nil { let font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body) let boundingSize = CGSize(width: tableView.bounds.width - InputCell.defaultLayoutMargins.left - InputCell.submitButtonWidthPlusSpacing - InputCell.defaultLayoutMargins.right, height: CGFloat.greatestFiniteMagnitude) let textSize = (item.text as NSString).boundingRect(with: boundingSize, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil).size textHeight = Double(max(textSize.height, font.lineHeight)) if !item.isEditing || item.text.characters.count == 0 { textHeightCache.setObject(NSNumber(value: textHeight!), forKey: item.text as NSString) } } let screen = view.window?.screen ?? UIScreen.main let padding: CGFloat = (screen.bounds.width >= 1366.0 || screen.bounds.height >= 1366.0) && tableView.bounds.height >= 916.0 ? 16.0 : 8.0 return CGFloat(floor(textHeight!)) + InputCell.defaultLayoutMargins.top + InputCell.defaultLayoutMargins.bottom + padding } override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool { let item = items[indexPath.row] return !item.isEditing } override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return action == #selector(copy(_:)) } override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) { let item = items[indexPath.row] UIPasteboard.general.string = item.text } @objc(tableView:calloutTargetRectForCell:forRowAtIndexPath:) func tableView(tableView: UITableView, calloutTargetRectForCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) -> CGRect { if let messageCell = cell as? MessageCell { return messageCell.selectionRect } else { return cell.bounds } } // MARK: PlaygroundLiveViewMessageHandler Methods func liveViewMessageConnectionOpened() { tableView.backgroundView = nil clear() } func liveViewMessageConnectionClosed() { if presentedViewController != nil { dismiss(animated: true, completion: nil) } for (index, item) in items.enumerated() { if item.isEditing { let indexPath = IndexPath(row: index, section: 0) if let cell = tableView.cellForRow(at: indexPath) as? InputCell { cell.setInputEnabled(false, animated: false) } items.replaceSubrange(index...index, with: [TranscriptItem(userEnteredText: item.text)]) } } } func receive(_ message: PlaygroundValue) { guard let command = AnswersCommand(message) else { return } switch command { case .show(let string): show(string) case .ask(let valueType, let placeholder): ask(forType: valueType, placeholder: placeholder) case .clear: clear() default: break } } // MARK: InputCellDelegate Methods func cellTextDidChange(_ cell: InputCell) { guard let indexPath = cell.indexPath else { return } items.replaceSubrange(indexPath.row...indexPath.row, with: [TranscriptItem(userEnteredText: cell.messageText, valueType: cell.valueType, placeholder: cell.placeholderText, isEditing: true)]) if (tableView.indexPathsForVisibleRows ?? []).contains(indexPath) { let contentBottomMargin = tableView.contentOffset.y + tableView.frame.size.height - tableView.contentInset.bottom - tableView.contentSize.height // Force cell heights to recalculate tableView.beginUpdates() tableView.endUpdates() if contentBottomMargin >= 0.0 { tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) } } } func cell(_ cell: InputCell, didSubmitText text: String) { guard let indexPath = cell.indexPath else { return } items.replaceSubrange(indexPath.row...indexPath.row, with: [TranscriptItem(userEnteredText: text)]) send(AnswersCommand.submit(text)) } func cellShouldPresentPopover(_ cell: InputCell) -> Bool { return !hasKeyboardContentInset } func presentPopover(_ popoverViewController: UIViewController, for cell: InputCell) { guard let indexPath = cell.indexPath else { return } let popoverBottomInset = AnswersViewController.defaultBottomContentInset - self.tableView.contentInset.top + popoverViewController.preferredContentSize.height + 40.0 UIView.animate(withDuration: AnswersViewController.popoverInsetAnimationDuration, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.tableView.contentInset.bottom = popoverBottomInset self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false) }, completion: { (_) in self.tableView.contentInset.bottom = popoverBottomInset self.present(popoverViewController, animated: true, completion: nil) }) } func dismissPopover(_ popoverViewController: UIViewController, for cell: InputCell) { dismiss(animated: true, completion: nil) hasPopoverContentInset = true perform(#selector(AnswersViewController.resetContentInset), with: nil, afterDelay: 1.0) } func cell(_ cell: InputCell, willDismissPopover popoverViewController: UIViewController) { UIView.animate(withDuration: AnswersViewController.popoverInsetAnimationDuration, delay: 0.0, options: [.beginFromCurrentState, .curveEaseInOut], animations: { self.tableView.contentInset.bottom = AnswersViewController.defaultBottomContentInset }) } } private struct TranscriptItem { let text: String let valueType: AnswersValueType? let placeholder: String? let isUserEntered: Bool let isEditing: Bool init(text: String) { valueType = nil placeholder = nil isUserEntered = false isEditing = false self.text = text } init(userEnteredText text: String, valueType: AnswersValueType? = nil, placeholder: String? = nil, isEditing: Bool = false) { isUserEntered = true self.text = text self.valueType = valueType self.placeholder = placeholder self.isEditing = isEditing } }
mit
b8132ee4e163f68856bb2cf4e5141e12
45.185841
252
0.647873
5.691385
false
false
false
false
micolous/metrodroid
native/metrodroid/metrodroid/SupportedCardsViewCell.swift
1
2843
// // SupportedCardsViewCell.swift // // Copyright 2019 Google // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // import UIKit import metrolib class SupportedCardsViewCell: UICollectionViewCell { @IBOutlet weak var cardName: UILabel! @IBOutlet weak var cardImage: UIImageView! @IBOutlet weak var cardLocation: UILabel! @IBOutlet weak var cardNotice: UILabel! func getCardInfoDrawable(ci: CardInfo) -> UIImage? { guard let imageId = ci.imageId else { return nil } guard let image = UIImage(named: imageId.id) else { return nil } guard let imageAlphaId = ci.imageAlphaId else { return image } guard let imageAlpha = UIImage(named: imageAlphaId.id) else { return image } print("Masked bitmap \(imageId.id) / \(imageAlphaId.id)") if (image.size != imageAlpha.size) { print("Source image (\(image.size)) and mask (\(imageAlpha.size)) are not the same size -- returning image without alpha") return image } UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) image.draw(at: CGPoint.zero) imageAlpha.draw(at: CGPoint.zero, blendMode: .destinationIn, alpha: 1.0) return UIGraphicsGetImageFromCurrentImageContext() } func getNoteText(_ ci: CardInfo) -> String? { var notes = "" if let li = ci.iOSExtraNote { notes += Utils.localizeString(li) } else if let li = ci.resourceExtraNote { notes += Utils.localizeString(li) } if (ci.preview) { notes += " " + Utils.localizeString(RKt.R.string.card_preview_reader) } if notes == "" { return nil } return notes } func setCardInfo(_ ci: CardInfo) { cardName.text = ci.name if let li = ci.locationId { cardLocation.text = Utils.localizeString(li) cardLocation.isHidden = false } else { cardLocation.isHidden = true } cardNotice.text = getNoteText(ci) cardImage.image = getCardInfoDrawable(ci: ci) layer.cornerRadius = 8.0 } }
gpl-3.0
e50c5ebaeb2eadae9ae0dc6d901faaab
33.253012
134
0.627858
4.394127
false
false
false
false
AaronMT/firefox-ios
Client/Frontend/AuthenticationManager/SetupPasscodeViewController.swift
12
2309
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import SwiftKeychainWrapper /// Displayed to the user when setting up a passcode. class SetupPasscodeViewController: PagingPasscodeViewController, PasscodeInputViewDelegate { fileprivate var confirmCode: String? override init() { super.init() self.title = AuthenticationStrings.setPasscode self.panes = [ PasscodePane(title: AuthenticationStrings.enterAPasscode, passcodeSize: 6), PasscodePane(title: AuthenticationStrings.reenterPasscode, passcodeSize: 6), ] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) panes.forEach { $0.codeInputView.delegate = self } // Don't show the keyboard or allow typing if we're locked out. Also display the error. if authenticationInfo?.isLocked() ?? false { displayLockoutError() panes.first?.codeInputView.isUserInteractionEnabled = false } else { panes.first?.codeInputView.becomeFirstResponder() } } func passcodeInputView(_ inputView: PasscodeInputView, didFinishEnteringCode code: String) { switch currentPaneIndex { case 0: confirmCode = code scrollToNextAndSelect() case 1: // Constraint: The first and confirmation codes must match. if confirmCode != code { failMismatchPasscode() resetAllInputFields() scrollToPreviousAndSelect() confirmCode = nil return } createPasscodeWithCode(code) dismissAnimated() default: break } } fileprivate func createPasscodeWithCode(_ code: String) { KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(AuthenticationKeychainInfo(passcode: code)) NotificationCenter.default.post(name: .PasscodeDidCreate, object: nil) } }
mpl-2.0
f72cfce6e0011686cecd18cfb1defec4
33.984848
116
0.650498
5.420188
false
false
false
false
regexident/Gestalt
GestaltDemo/Themes/Theme.swift
1
1647
// // Theme.swift // Gestalt // // Created by Vincent Esche on 7/3/17. // Copyright © 2017 Vincent Esche. All rights reserved. // import UIKit import Gestalt struct NativeTheme: Theme { let navigationBar: NavigationBarTheme let textfield: TextFieldTheme let segmentedControl: SegmentedControlTheme let activityIndicator: ActivityIndicatorViewTheme let stepper: StepperTheme let `switch`: SwitchTheme let slider: SliderTheme let button: ButtonTheme init(palette: Palette) { self.navigationBar = .init(palette: palette) self.textfield = .init(palette: palette) self.segmentedControl = .init(palette: palette) self.activityIndicator = .init(palette: palette) self.stepper = .init(palette: palette) self.switch = .init(palette: palette) self.slider = .init(palette: palette) self.button = .init(palette: palette) } } struct CustomTheme: Theme { let stageDesign: StageDesignViewTheme let demo: DemoViewTheme init(palette: Palette) { self.stageDesign = .init(palette: palette) self.demo = .init(palette: palette) } } struct ApplicationTheme: Theme { let native: NativeTheme let custom: CustomTheme static var `default`: ApplicationTheme { return .light } static let light: ApplicationTheme = .init(palette: .light) static let dark: ApplicationTheme = .init(palette: .dark) static let debug: ApplicationTheme = .init(palette: .debug) init(palette: Palette) { self.native = .init(palette: palette) self.custom = .init(palette: palette) } }
mpl-2.0
82a23eddd7f672e0d1796798fcd52a0f
25.983607
63
0.672539
4.209719
false
false
false
false
MattLewin/Interview-Prep
Data Structures.playground/Pages/LRU Cache - Doubly Linked List.xcplaygroundpage/Sources/Doubly Linked List Cache.swift
1
2527
import Foundation typealias DoublyLinkedListNode<T> = DoublyLinkedList<T>.Node<T> class DoublyLinkedList<T> { class Node<T> { var value: T var previous: Node<T>? var next: Node<T>? init(value: T) { self.value = value } } private(set) var count = 0 private var head: Node<T>? private var tail: Node<T>? func addHead(_ value: T) -> Node<T> { let node = Node(value: value) defer { head = node count += 1 } guard let head = self.head else { tail = node return node } head.previous = node node.previous = nil node.next = head return node } func moveToHead(_ node: Node<T>) { guard node !== head else { return } let previous = node.previous let next = node.next next?.previous = previous previous?.next = next node.next = head node.previous = nil head?.previous = node if node === tail { tail = previous } head = node } func removeLast() -> Node<T>? { guard let tail = self.tail else { return nil } let previous = tail.previous previous?.next = nil self.tail = previous count -= 1 if count == 0 { head = nil } return tail } } public class LRUCache<Key: Hashable, Value> { private struct CachePayload { let key: Key let value: Value } private let list = DoublyLinkedList<CachePayload>() private var nodesDict = [Key: DoublyLinkedListNode<CachePayload>]() private let capacity: Int public init(capacity: Int) { self.capacity = max(0, capacity) } public func setValue(_ value: Value, for key: Key) { let payload = CachePayload(key: key, value: value) if let node = nodesDict[key] { node.value = payload list.moveToHead(node) } else { let node = list.addHead(payload) nodesDict[key] = node } if list.count > capacity { let nodeRemoved = list.removeLast() if let key = nodeRemoved?.value.key { nodesDict[key] = nil } } } public func getValue(for key: Key) -> Value? { guard let node = nodesDict[key] else { return nil } list.moveToHead(node) return node.value.value } }
unlicense
07a940cd1d748f4523d1935e82e27039
20.784483
71
0.522359
4.334477
false
false
false
false
grokify/ringcentral-swift
src/Platform/Platform.swift
1
9596
// // Platform.swift // src // // Created by Anil Kumar BP on 11/17/15. // Copyright (c) 2015 Anil Kumar BP. All rights reserved. // import Foundation /// Platform used to call HTTP request methods. public class Platform { // platform Constants public let ACCESS_TOKEN_TTL = "3600"; // 60 minutes public let REFRESH_TOKEN_TTL = "604800"; // 1 week public let TOKEN_ENDPOINT = "/restapi/oauth/token"; public let REVOKE_ENDPOINT = "/restapi/oauth/revoke"; public let API_VERSION = "v1.0"; public let URL_PREFIX = "/restapi"; // Platform credentials internal var auth: Auth internal var client: Client internal let server: String internal let appKey: String internal let appSecret: String internal var appName: String internal var appVersion: String /// Constructor for the platform of the SDK /// /// :param: appKey The appKey of your app /// :param: appSecet The appSecret of your app /// :param: server Choice of PRODUCTION or SANDBOX public init(client: Client, appKey: String, appSecret: String, server: String, appName: String = "", appVersion: String = "") { self.appKey = appKey self.appName = appName != "" ? appName : "Unnamed" self.appVersion = appVersion != "" ? appVersion : "0.0.0" self.appSecret = appSecret self.server = server self.auth = Auth() self.client = client } // Returns the auth object /// public func returnAuth() -> Auth { return self.auth } /// func createUrl /// /// @param: path The username of the RingCentral account /// @param: options The password of the RingCentral account /// @response: ApiResponse The password of the RingCentral account public func createUrl(path: String, options: [String: AnyObject]) -> String { var builtUrl = "" if(options["skipAuthCheck"] === true){ builtUrl = builtUrl + self.server + path return builtUrl } builtUrl = builtUrl + self.server + self.URL_PREFIX + "/" + self.API_VERSION + path return builtUrl } /// Authenticates the user with the correct credentials /// /// :param: username The username of the RingCentral account /// :param: password The password of the RingCentral account public func login(username: String, ext: String, password: String) -> ApiResponse { let response = requestToken(self.TOKEN_ENDPOINT,body: [ "grant_type": "password", "username": username, "extension": ext, "password": password, "access_token_ttl": self.ACCESS_TOKEN_TTL, "refresh_token_ttl": self.REFRESH_TOKEN_TTL ]) self.auth.setData(response.getDict()) return response } /// Refreshes the Auth object so that the accessToken and refreshToken are updated. /// /// **Caution**: Refreshing an accessToken will deplete it's current time, and will /// not be appended to following accessToken. public func refresh() -> ApiResponse { if(!self.auth.refreshTokenValid()){ NSException(name: "Refresh token has expired", reason: "reason", userInfo: nil).raise() } let response = requestToken(self.TOKEN_ENDPOINT,body: [ "refresh_token": self.auth.refreshToken(), "grant_type": "refresh_token", "access_token_ttl": self.ACCESS_TOKEN_TTL, "refresh_token_ttl": self.REFRESH_TOKEN_TTL ]) self.auth.setData(response.getDict()) return response } /// func inflateRequest () /// /// @param: request NSMutableURLRequest /// @param: options list of options /// @response: NSMutableURLRequest public func inflateRequest(request: NSMutableURLRequest, options: [String: AnyObject]) -> NSMutableURLRequest { if options["skipAuthCheck"] == nil { ensureAuthentication() let authHeader = self.auth.tokenType() + " " + self.auth.accessToken() request.setValue(authHeader, forHTTPHeaderField: "Authorization") } return request } /// func sendRequest () /// /// @param: request NSMutableURLRequest /// @param: options list of options /// @response: ApiResponse Callback public func sendRequest(request: NSMutableURLRequest, options: [String: AnyObject]!, completion: (apiresponse: ApiResponse) -> Void) { client.send(inflateRequest(request, options: options)) { (t) in completion(apiresponse: t) } } /// func sendRequest () - without Completetion handler /// /// @param: request NSMutableURLRequest /// @param: options list of options /// @response: ApiResponse public func sendRequest(request: NSMutableURLRequest, options: [String: AnyObject]!) -> ApiResponse { return client.send(inflateRequest(request, options: options)) } /// func requestToken () /// /// @param: path The token endpoint /// @param: array The body /// @return ApiResponse func requestToken(path: String, body: [String:AnyObject]) -> ApiResponse { let authHeader = "Basic" + " " + self.apiKey() var headers: [String: String] = [:] headers["Authorization"] = authHeader headers["Content-type"] = "application/x-www-form-urlencoded;charset=UTF-8" var options: [String: AnyObject] = [:] options["skipAuthCheck"] = true let urlCreated = createUrl(path,options: options) let request = self.client.createRequest("POST", url: urlCreated, query: nil, body: body, headers: headers) return self.sendRequest(request, options: options) } /// Base 64 encoding func apiKey() -> String { let plainData = (self.appKey + ":" + self.appSecret as NSString).dataUsingEncoding(NSUTF8StringEncoding) let base64String = plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) return base64String } /// Logs the user out of the current account. /// /// Kills the current accessToken and refreshToken. public func logout() -> ApiResponse { let response = requestToken(self.TOKEN_ENDPOINT,body: [ "token": self.auth.accessToken() ]) self.auth.reset() return response } /// Check if the accessToken is valid func ensureAuthentication() { if (!self.auth.accessTokenValid()) { refresh() } } // Generic Method calls ( HTTP ) GET /// /// @param: url token endpoint /// @param: query body /// @return ApiResponse Callback public func get(url: String, query: [String: String]?=["":""], body: [String: AnyObject]?=nil, headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (response: ApiResponse) -> Void) { let urlCreated = createUrl(url,options: options!) sendRequest(self.client.createRequest("GET", url: urlCreated, query: query, body: body, headers: headers!), options: options) { (r) in completion(response: r) } } // Generic Method calls ( HTTP ) POST /// /// @param: url token endpoint /// @param: body body /// @return ApiResponse Callback public func post(url: String, query: [String: String]?=["":""], body: [String: AnyObject] = ["":""], headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse) -> Void) { let urlCreated = createUrl(url,options: options!) sendRequest(self.client.createRequest("POST", url: urlCreated, query: query, body: body, headers: headers!), options: options) { (r) in completion(apiresponse: r) } } // Generic Method calls ( HTTP ) PUT /// /// @param: url token endpoint /// @param: body body /// @return ApiResponse Callback public func put(url: String, query: [String: String]?=["":""], body: [String: AnyObject] = ["":""], headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse) -> Void) { let urlCreated = createUrl(url,options: options!) sendRequest(self.client.createRequest("PUT", url: urlCreated, query: query, body: body, headers: headers!), options: options) { (r) in completion(apiresponse: r) } } // Generic Method calls ( HTTP ) DELETE /// /// @param: url token endpoint /// @param: query body /// @return ApiResponse Callback public func delete(url: String, query: [String: String] = ["":""], body: [String: AnyObject]?=nil, headers: [String: String]?=["":""], options: [String: AnyObject]?=["":""], completion: (apiresponse: ApiResponse) -> Void) { let urlCreated = createUrl(url,options: options!) sendRequest(self.client.createRequest("DELETE", url: urlCreated, query: query, body: body, headers: headers!), options: options) { (r) in completion(apiresponse: r) } } }
mit
4f08727e2383f288cc4fefb2e64f7949
37.231076
229
0.588474
4.755203
false
false
false
false
KrishMunot/swift
test/SILGen/init_ref_delegation.swift
5
8209
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s struct X { } // Initializer delegation within a struct. struct S { // CHECK-LABEL: sil hidden @_TFV19init_ref_delegation1SC{{.*}} : $@convention(method) (@thin S.Type) -> S { init() { // CHECK: bb0([[SELF_META:%[0-9]+]] : $@thin S.Type): // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box $S // CHECK-NEXT: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S // CHECK: [[S_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1SC{{.*}} : $@convention(method) (X, @thin S.Type) -> S // CHECK: [[X_CTOR:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X // CHECK-NEXT: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK-NEXT: [[X:%[0-9]+]] = apply [[X_CTOR]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK-NEXT: [[REPLACEMENT_SELF:%[0-9]+]] = apply [[S_DELEG_INIT]]([[X]], [[SELF_META]]) : $@convention(method) (X, @thin S.Type) -> S self.init(x: X()) // CHECK-NEXT: assign [[REPLACEMENT_SELF]] to [[SELF]] : $*S // CHECK-NEXT: [[SELF_BOX1:%[0-9]+]] = load [[SELF]] : $*S // CHECK-NEXT: strong_release [[SELF_BOX]] : $@box S // CHECK-NEXT: return [[SELF_BOX1]] : $S } init(x: X) { } } // Initializer delegation within an enum enum E { // CHECK-LABEL: sil hidden @_TFO19init_ref_delegation1EC{{.*}} : $@convention(method) (@thin E.Type) -> E init() { // CHECK: bb0([[E_META:%[0-9]+]] : $@thin E.Type): // CHECK: [[E_BOX:%[0-9]+]] = alloc_box $E // CHECK: [[PB:%.*]] = project_box [[E_BOX]] // CHECK: [[E_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*E // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFO19init_ref_delegation1EC{{.*}} : $@convention(method) (X, @thin E.Type) -> E // CHECK: [[E_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[E_DELEG_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[S:%[0-9]+]] = apply [[X_INIT]]([[X]], [[E_META]]) : $@convention(method) (X, @thin E.Type) -> E // CHECK: assign [[S:%[0-9]+]] to [[E_SELF]] : $*E // CHECK: [[E_BOX1:%[0-9]+]] = load [[E_SELF]] : $*E self.init(x: X()) // CHECK: strong_release [[E_BOX]] : $@box E // CHECK: return [[E_BOX1:%[0-9]+]] : $E } init(x: X) { } } // Initializer delegation to a generic initializer struct S2 { // CHECK-LABEL: sil hidden @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(method) (@thin S2.Type) -> S2 init() { // CHECK: bb0([[S2_META:%[0-9]+]] : $@thin S2.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $S2 // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*S2 // CHECK: [[S2_DELEG_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation2S2C{{.*}} : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFV19init_ref_delegation1XC{{.*}} : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type // CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X // CHECK: [[X_BOX:%[0-9]+]] = alloc_stack $X // CHECK: store [[X]] to [[X_BOX]] : $*X // CHECK: [[SELF_BOX1:%[0-9]+]] = apply [[S2_DELEG_INIT]]<X>([[X_BOX]], [[S2_META]]) : $@convention(method) <τ_0_0> (@in τ_0_0, @thin S2.Type) -> S2 // CHECK: assign [[SELF_BOX1]] to [[SELF]] : $*S2 // CHECK: dealloc_stack [[X_BOX]] : $*X // CHECK: [[SELF_BOX4:%[0-9]+]] = load [[SELF]] : $*S2 self.init(t: X()) // CHECK: strong_release [[SELF_BOX]] : $@box S2 // CHECK: return [[SELF_BOX4]] : $S2 } init<T>(t: T) { } } class C1 { var ivar: X // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C1c{{.*}} : $@convention(method) (X, @owned C1) -> @owned C1 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C1): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $C1 // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C1 // CHECK: store [[ORIG_SELF]] to [[SELF]] : $*C1 // CHECK: [[SELF_FROM_BOX:%[0-9]+]] = load [[SELF]] : $*C1 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF_FROM_BOX]] : $C1, #C1.init!initializer.1 : C1.Type -> (x1: X, x2: X) -> C1 , $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: [[SELFP:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF_FROM_BOX]]) : $@convention(method) (X, X, @owned C1) -> @owned C1 // CHECK: store [[SELFP]] to [[SELF]] : $*C1 // CHECK: [[SELFP:%[0-9]+]] = load [[SELF]] : $*C1 // CHECK: strong_retain [[SELFP]] : $C1 // CHECK: strong_release [[SELF_BOX]] : $@box C1 // CHECK: return [[SELFP]] : $C1 self.init(x1: x, x2: x) } init(x1: X, x2: X) { ivar = x1 } } @objc class C2 { var ivar: X // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2c{{.*}} : $@convention(method) (X, @owned C2) -> @owned C2 convenience init(x: X) { // CHECK: bb0([[X:%[0-9]+]] : $X, [[ORIG_SELF:%[0-9]+]] : $C2): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $C2 // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*C2 // CHECK: store [[ORIG_SELF]] to [[UNINIT_SELF]] : $*C2 // CHECK: [[SELF:%[0-9]+]] = load [[UNINIT_SELF]] : $*C2 // CHECK: [[DELEG_INIT:%[0-9]+]] = class_method [[SELF]] : $C2, #C2.init!initializer.1 : C2.Type -> (x1: X, x2: X) -> C2 , $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: [[REPLACE_SELF:%[0-9]+]] = apply [[DELEG_INIT]]([[X]], [[X]], [[SELF]]) : $@convention(method) (X, X, @owned C2) -> @owned C2 // CHECK: store [[REPLACE_SELF]] to [[UNINIT_SELF]] : $*C2 // CHECK: [[VAR_15:%[0-9]+]] = load [[UNINIT_SELF]] : $*C2 // CHECK: strong_retain [[VAR_15]] : $C2 // CHECK: strong_release [[SELF_BOX]] : $@box C2 // CHECK: return [[VAR_15]] : $C2 self.init(x1: x, x2: x) // CHECK-NOT: sil hidden @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, @owned C2) -> @owned C2 { } // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C2C{{.*}} : $@convention(method) (X, X, @thick C2.Type) -> @owned C2 { // CHECK-NOT: sil @_TToFC19init_ref_delegation2C2c{{.*}} : $@convention(objc_method) (X, X, @owned C2) -> @owned C2 { init(x1: X, x2: X) { ivar = x1 } } var x: X = X() class C3 { var i: Int = 5 // CHECK-LABEL: sil hidden @_TFC19init_ref_delegation2C3c{{.*}} : $@convention(method) (@owned C3) -> @owned C3 convenience init() { // CHECK: mark_uninitialized [delegatingself] // CHECK-NOT: integer_literal // CHECK: class_method [[SELF:%[0-9]+]] : $C3, #C3.init!initializer.1 : C3.Type -> (x: X) -> C3 , $@convention(method) (X, @owned C3) -> @owned C3 // CHECK-NOT: integer_literal // CHECK: return self.init(x: x) } init(x: X) { } } // Initializer delegation from a constructor defined in an extension. class C4 { } extension C4 { convenience init(x1: X) { self.init() } // CHECK: sil hidden @_TFC19init_ref_delegation2C4c{{.*}} // CHECK: [[PEER:%[0-9]+]] = function_ref @_TFC19init_ref_delegation2C4c{{.*}} // CHECK: apply [[PEER]]([[X:%[0-9]+]], [[OBJ:%[0-9]+]]) convenience init(x2: X) { self.init(x1: x2) } } // Initializer delegation to a constructor defined in a protocol extension. protocol Pb { init() } extension Pb { init(d: Int) { } } class Sn : Pb { required init() { } convenience init(d3: Int) { self.init(d: d3) } } // Same as above but for a value type. struct Cs : Pb { init() { } init(d3: Int) { self.init(d: d3) } }
apache-2.0
a45c28cfd9b4067b3e39d777eeb3c55c
40.439394
189
0.532724
2.789867
false
false
false
false
KrishMunot/swift
test/DebugInfo/inlinedAt.swift
2
1883
// RUN: %target-swift-frontend %s -O -I %t -emit-sil -emit-verbose-sil -o - \ // RUN: | FileCheck %s --check-prefix=CHECK-SIL // RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o - | FileCheck %s #sourceLocation(file: "abc.swift", line: 100) @inline(__always) func h(_ k : Int) -> Int { // 101 return k // 102 } #sourceLocation(file: "abc.swift", line: 200) @inline(__always) func g(_ j : Int) -> Int { // 201 return h(j) // 202 } #sourceLocation(file: "abc.swift", line: 301) public func f(_ i : Int) -> Int { // 301 return g(i) // 302 } // CHECK-SIL: sil {{.*}}@_TF9inlinedAt1fFSiSi : // CHECK-SIL-NOT: return // CHECK-SIL: debug_value %0 : $Int, let, name "k", argno 1 // CHECK-SIL-SAME: line:101:10:in_prologue // CHECK-SIL-SAME: perf_inlined_at line:202:10 // CHECK-SIL-SAME: perf_inlined_at line:302:10 // CHECK: define {{.*}}@_TF9inlinedAt1fFSiSi // CHECK-NOT: ret // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value({{.*}}), !dbg ![[L1:.*]] // CHECK: ![[F:.*]] = distinct !DISubprogram(name: "f", // CHECK: ![[G:.*]] = distinct !DISubprogram(name: "g", // CHECK: ![[H:.*]] = distinct !DISubprogram(name: "h", // CHECK: ![[L3:.*]] = !DILocation(line: 302, column: 13, // CHECK-SAME: scope: ![[F_SCOPE:.*]]) // CHECK: ![[F_SCOPE]] = distinct !DILexicalBlock(scope: ![[F]], // CHECK-SAME: line: 301, column: 33) // CHECK: ![[L1]] = !DILocation(line: 101, column: 8, scope: ![[H]], // CHECK-SAME: inlinedAt: ![[L2:.*]]) // CHECK: ![[L2]] = !DILocation(line: 202, column: 13, scope: ![[G_SCOPE:.*]], // CHECK-SAME: inlinedAt: ![[L3]]) // CHECK: ![[G_SCOPE]] = distinct !DILexicalBlock(scope: ![[G]], // CHECK-SAME: line: 201, column: 26)
apache-2.0
e5f5bcdb8245a35afe5b0de8aad703a0
38.229167
78
0.531067
3.061789
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Appflow/Appflow_Paginator.swift
1
11928
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension Appflow { /// Returns a list of connector-profile details matching the provided connector-profile names and connector-types. Both input lists are optional, and you can use them to filter the result. If no names or connector-types are provided, returns all connector profiles in a paginated form. If there is no match, this operation returns an empty list. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func describeConnectorProfilesPaginator<Result>( _ input: DescribeConnectorProfilesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, DescribeConnectorProfilesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: describeConnectorProfiles, tokenKey: \DescribeConnectorProfilesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func describeConnectorProfilesPaginator( _ input: DescribeConnectorProfilesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (DescribeConnectorProfilesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeConnectorProfiles, tokenKey: \DescribeConnectorProfilesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Describes the connectors vended by Amazon AppFlow for specified connector types. If you don't specify a connector type, this operation describes all connectors vended by Amazon AppFlow. If there are more connectors than can be returned in one page, the response contains a nextToken object, which can be be passed in to the next call to the DescribeConnectors API operation to retrieve the next page. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func describeConnectorsPaginator<Result>( _ input: DescribeConnectorsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, DescribeConnectorsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: describeConnectors, tokenKey: \DescribeConnectorsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func describeConnectorsPaginator( _ input: DescribeConnectorsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (DescribeConnectorsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeConnectors, tokenKey: \DescribeConnectorsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Fetches the execution history of the flow. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func describeFlowExecutionRecordsPaginator<Result>( _ input: DescribeFlowExecutionRecordsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, DescribeFlowExecutionRecordsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: describeFlowExecutionRecords, tokenKey: \DescribeFlowExecutionRecordsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func describeFlowExecutionRecordsPaginator( _ input: DescribeFlowExecutionRecordsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (DescribeFlowExecutionRecordsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: describeFlowExecutionRecords, tokenKey: \DescribeFlowExecutionRecordsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists all of the flows associated with your account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listFlowsPaginator<Result>( _ input: ListFlowsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListFlowsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listFlows, tokenKey: \ListFlowsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listFlowsPaginator( _ input: ListFlowsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListFlowsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listFlows, tokenKey: \ListFlowsResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension Appflow.DescribeConnectorProfilesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Appflow.DescribeConnectorProfilesRequest { return .init( connectorProfileNames: self.connectorProfileNames, connectorType: self.connectorType, maxResults: self.maxResults, nextToken: token ) } } extension Appflow.DescribeConnectorsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Appflow.DescribeConnectorsRequest { return .init( connectorTypes: self.connectorTypes, nextToken: token ) } } extension Appflow.DescribeFlowExecutionRecordsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Appflow.DescribeFlowExecutionRecordsRequest { return .init( flowName: self.flowName, maxResults: self.maxResults, nextToken: token ) } } extension Appflow.ListFlowsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Appflow.ListFlowsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } }
apache-2.0
e2ed7ad54f06a889fdd6950ec63062e1
44.181818
410
0.654007
5.325
false
false
false
false
phanthanhhai/DayseeNetwork
DayseeNetwork/Configs/BFConstants.swift
1
5831
// // BFConstants.swift // Benlly // // Created by haipt on 9/8/15. // Copyright (c) 2015 Curations. All rights reserved. // import Foundation import CoreLocation public let GoogleApiKey = "AIzaSyDuJ2Oi7wKAX4qbOAORozyIrdrNR2zbkPE" let BFApi_GGMapsSearchPlace = "https://maps.googleapis.com/maps/api/place/textsearch/json?language=ja&query=" let BFApi_GGMapsGetPlaceDetail = "https://maps.googleapis.com/maps/api/geocode/json?language=ja&latlng=" //----------key of header token----- public let BFTokenHeaderKey = "X-Benlly-Api-Token" public let BFVersionHeaderKey = "X-Benlly-Api-Version" public let BFDeviceHeaderKey = "X-Benlly-Device-Type" public let BFDeviceName = "iOS" public let BFDeviceUniqueId = "device_unique_id" public let BFAppVersion = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as! String //----------Timeout afnetworking----------- public let BFApi_Timeout : Double = 30 //----------key of response----------- public let BFAPIKey_ResultCode = "result_code" public let BFAPIKey_Msg = "msg" public let BFAPIKey_Success = "success" public let BFAPIKey_LoginOauth = "oauth" public let BFAPIKey_AccessToken = "token" public let BFApiTitleError = "エラー" public let BFApiBtnRetry = "リトライ" public let BFApiBtn_Cancel = "キャンセル" public let BFApiBtn_OK = "OK" public let BFApiBtn_Appstore = "AppStoreへ" public let BFApiMsgCommonError = "システムが混雑しています。\r\nしばらくしてから再度お試しください。" public let BFApiMsgNetworkErrorWithRetry = "ネットワークエラーが発生しました。\r\nリトライしますか?" public let BFAlertConfirm_Title = "" //----------error code response----------- //http status public let BFErrCode_200 = 200 //OK public let BFErrCode_400 = 400 public let BFErrCode_401 = 401 public let BFErrCode_409 = 409 public let BFErrCode_500 = 500 //Internal Server Error public let BFErrCode_503 = 503 //Maintainance public let BFErrCode_404 = 404 //http status = 400 : error code public let BFErrCode_4010 = 4014 //api token invalid public let BFErrCode_4014 = 4014 //Recipe key invalid public let BFErrCode_4015 = 4015 //Recipe limit public let BFErrCode_4016 = 4016 //FB token expired public let BFErrCode_4019 = 4019 //item of recipe requirement public let BFErrCode_4020 = 4020 //item of recipe: selection invalid public let BFErrCode_4021 = 4021 //item of recipe: url invalid public let BFErrCode_4022 = 4022 //item of recipe: time invalid public let BFErrCode_4023 = 4023 //channel not authorization public let BFErrCode_4024 = 4024 //file download key invalid public let BFErrCode_4025 = 4025 //evernote error //http status = 401 : error code public let BFErrCode_4026 = 4026 //device type not found public let BFErrCode_4011 = 4026 //api token invalid //http status = 409 : error code public let BFErrCode_14010 = 14010 //uuid duplicated public let BFErrCode_14020 = 14020 //email existing public let BFErrCode_14030 = 14030 //email not exsit public let BFErrCode_14040 = 14040 //email disable //http status = 500 : error code public let BFErrCode_4001 = 4001 //Parameter invalid public let BFErrCode_4012 = 4012 //api version not found public let BFErrCode_4013 = 4013 //update requirement public let BFErrCode_4017 = 4017 //FB server error //----------Image Upload----------- public let BFMaxSizeImageUpload : Int = 400000 public let BFMaxWidthImageUpload : String = "750" public typealias BFLocationModel = (coordinate: CLLocationCoordinate2D, name: String, radius: CGFloat) public typealias LocationTrackerModel = (coordinate: CLLocationCoordinate2D, radius: CGFloat, triggerId: Int, ideaId: Int) public let LocationDefault: BFLocationModel = (CLLocationCoordinate2DMake(35.817813, 139.910202), "Tokyo", 300) //default is tokyo public typealias FailHandler = (NSError?) -> Void public typealias RequestSuccessHandler = (AnyObject?) -> Void public typealias RequestFailHandler = (NSError?) -> Void public enum TriggerIdIOS : Int { case NewImage = 1000 case AnyNewImage = 18 case NewVideo = 1001 case AnyNewVideo = 1002 case LocationEnter = 19 case LocationExit = 20 case LocationVisit = 21 } public enum HTTPMethod { case POST case POST_FORMDATA case GET case PUT case PUT_FORMDATA case DELETE } public enum UploadingCase : Int { case UploadImage = 0 case UploadVideo = 1 }
mit
c522329ae3cb46dc90ae866d2b6d099b
46.823529
131
0.557371
4.541899
false
false
false
false
garygriswold/Bible.js
Plugins/Utility/src/ios/OBSOLETE/Utility.swift
2
6167
// // Utility.swift // Utility // // Created by Gary Griswold on 1/9/18. // Copyright © 2018 ShortSands. All rights reserved. // import Foundation import UIKit /* platform, modelType, modelName, deviceSize */ @objc(Utility) class Utility : CDVPlugin { @objc(locale:) func locale(command: CDVInvokedUrlCommand) { let loc = Locale.current let message: [String?] = [ loc.identifier, loc.languageCode, loc.scriptCode, loc.regionCode ] let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message) self.commandDelegate!.send(result, callbackId: command.callbackId) } @objc(platform:) func platform(command: CDVInvokedUrlCommand) { let message = "iOS" let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message) self.commandDelegate!.send(result, callbackId: command.callbackId) } @objc(modelType:) func modelType(command: CDVInvokedUrlCommand) { let message = UIDevice.current.model let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message) self.commandDelegate!.send(result, callbackId: command.callbackId) } @objc(modelName:) func modelName(command: CDVInvokedUrlCommand) { let message = DeviceSettings.modelName() let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message) self.commandDelegate!.send(result, callbackId: command.callbackId) } @objc(deviceSize:) func deviceSize(command: CDVInvokedUrlCommand) { let message = DeviceSettings.deviceSize() let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message) self.commandDelegate!.send(result, callbackId: command.callbackId) } @objc(open:) func open(command: CDVInvokedUrlCommand) { DispatchQueue.global().sync { do { let database = try Sqlite3.openDB( dbname: command.arguments[0] as? String ?? "", copyIfAbsent: command.arguments[1] as? Bool ?? false) let result = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.send(result, callbackId: command.callbackId) } catch let err { self.returnError(error: err, command: command) } } } @objc(queryJS:) func queryJS(command: CDVInvokedUrlCommand) { DispatchQueue.global().sync { do { let database = try Sqlite3.findDB(dbname: command.arguments[0] as? String ?? "") let resultSet = try database.queryJS( sql: command.arguments[1] as? String ?? "", values: command.arguments[2] as? [Any?] ?? []) let json = String(data: resultSet, encoding: String.Encoding.utf8) let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: json) self.commandDelegate!.send(result, callbackId: command.callbackId) } catch let err { self.returnError(error: err, command: command) } } } @objc(executeJS:) func executeJS(command: CDVInvokedUrlCommand) { DispatchQueue.global().sync { do { let database = try Sqlite3.findDB(dbname: command.arguments[0] as? String ?? "") let rowCount = try database.executeV1( sql: command.arguments[1] as? String ?? "", values: command.arguments[2] as? [Any?] ?? []) let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: rowCount) self.commandDelegate!.send(result, callbackId: command.callbackId) } catch let err { self.returnError(error: err, command: command) } } } @objc(bulkExecuteJS:) func bulkExecuteJS(command: CDVInvokedUrlCommand) { DispatchQueue.global().sync { do { let database = try Sqlite3.findDB(dbname: command.arguments[0] as? String ?? "") let rowCount = try database.bulkExecuteV1( sql: command.arguments[1] as? String ?? "", values: command.arguments[2] as? [[Any?]] ?? [[]]) let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: rowCount) self.commandDelegate!.send(result, callbackId: command.callbackId) } catch let err { self.returnError(error: err, command: command) } } } @objc(close:) func close(command: CDVInvokedUrlCommand) { DispatchQueue.global().sync { Sqlite3.closeDB(dbname: command.arguments[0] as? String ?? "") let result = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.send(result, callbackId: command.callbackId) } } @objc(listDB:) func listDB(command: CDVInvokedUrlCommand) { do { let files = try Sqlite3.listDB() let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: files) self.commandDelegate!.send(result, callbackId: command.callbackId) } catch let err { self.returnError(error: err, command: command) } } @objc(deleteDB:) func deleteDB(command: CDVInvokedUrlCommand) { do { try Sqlite3.deleteDB(dbname: command.arguments[0] as? String ?? "") let result = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.send(result, callbackId: command.callbackId) } catch let err { self.returnError(error: err, command: command) } } @objc(hideKeyboard:) func hideKeyboard(command: CDVInvokedUrlCommand) { do { let hidden = self.webView.endEditing(true) let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: hidden) self.commandDelegate!.send(result, callbackId: command.callbackId) } catch let err { self.returnError(error: err, command: command) } } private func returnError(error: Error, command: CDVInvokedUrlCommand) { let message = Sqlite3.errorDescription(error: error) let result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: message) self.commandDelegate!.send(result, callbackId: command.callbackId) } }
mit
29f8a6bf387c97d840d81c84cdd2a14c
39.565789
101
0.646286
4.416905
false
false
false
false
GeekSpeak/GeekSpeak-Show-Timer
GeekSpeak Show Timer/BreakCount-3/TimerViewController.swift
2
15094
import UIKit import AngleGear import TimerViewsGear enum TimerLabelDisplay: String, CustomStringConvertible { case Remaining = "Remaining" case Elapsed = "Elapsed" var description: String { return self.rawValue } } final class TimerViewController: UIViewController { var timer: Timer? var timerViews: TimerViews? var timerLabelDisplay: TimerLabelDisplay = .Remaining { didSet { updateTimerLabels() } } fileprivate var layoutSize: CGSize { return view.frame.size } fileprivate var layoutIsVertical: Bool { return self.layoutSize.width < self.layoutSize.height } fileprivate var layoutIsHorizontal: Bool { return self.layoutSize.width < self.layoutSize.height } // Required on load @IBOutlet weak var timerCirclesView: UIView! @IBOutlet weak var totalTimeLabel: UILabel! @IBOutlet weak var sectionTimeLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var segmentLabel: UILabel! @IBOutlet weak var flashImageView: UIImageView! @IBOutlet weak var backButton: BackButton! @IBOutlet weak var backView: BackView! @IBOutlet weak var startPauseButton: StartPauseButton! @IBOutlet weak var nextButton: NextButton! @IBOutlet weak var nextButtonTimerOverlay: NextButton! @IBOutlet weak var containerStackView: UIStackView! @IBOutlet weak var controlsStackView: UIStackView! @IBOutlet weak var activityView: ActivityView! fileprivate var controlsInOrder: [UIButton] = [] override func viewDidLoad() { super.viewDidLoad() controlsInOrder = [startPauseButton, nextButton] activityView.fillColor = Appearance.Constants.GeekSpeakBlueColor addSwipeGesture() setupBackButton() setupStartPauseButton() setupNextButton() } // MARK: - // MARK: Setup func setupBackButton() { backButton.backView = backView backView.unhighlight() } func setupNextButton() { let geekSpeakBlueColor = Appearance.Constants.GeekSpeakBlueColor let nextView = NextView() nextView.highlightColor = geekSpeakBlueColor nextView.tintColor = geekSpeakBlueColor view.insertSubview( nextView, belowSubview: containerStackView) centerView( nextView, ToView: nextButton, WithContraintParent: view) nextButton.nextView = nextView nextButtonTimerOverlay.nextView = nextView } func setupStartPauseButton() { let geekSpeakBlueColor = Appearance.Constants.GeekSpeakBlueColor let startPauseView = StartPauseView() startPauseView.highlightColor = geekSpeakBlueColor startPauseView.tintColor = geekSpeakBlueColor view.insertSubview( startPauseView, belowSubview: containerStackView) centerView( startPauseView, ToView: startPauseButton, WithContraintParent: view) startPauseButton.startPauseView = startPauseView } override func viewWillAppear(_ animated: Bool) { if let timer = timer { setupButtonLayout(timer) } setupTimeLabelContraints(totalTimeLabel) setupTimeLabelContraints(sectionTimeLabel) setupDescriptionLabelContraints(totalLabel) setupDescriptionLabelContraints(segmentLabel) let breakView = BreakView() breakView.fillColor = Appearance.Constants.BreakColor timerCirclesView.addSubview(breakView) let ring1bg = configureBGRing( RingView(), withColor: Appearance .Constants.GeekSpeakBlueInactiveColor) let ring1fg = configureFGRing( RingView(), withColor: Appearance.Constants.GeekSpeakBlueColor) let ring2bg = configureBGRing( RingView(), withColor: Appearance .Constants.GeekSpeakBlueInactiveColor) let ring2fg = configureFGRing( RingView(), withColor: Appearance.Constants.GeekSpeakBlueColor) let ring3bg = configureBGRing( RingView(), withColor: Appearance .Constants.GeekSpeakBlueInactiveColor) let ring3fg = configureFGRing( RingView(), withColor: Appearance.Constants.GeekSpeakBlueColor) ring3bg.fillScale = 0.95 ring3fg.fillScale = 0.95 ring2bg.fillScale = 0.64 ring2fg.fillScale = 0.64 ring1bg.fillScale = 0.33 ring1fg.fillScale = 0.33 timerViews = TimerViews( ring1bg: ring1bg, ring1fg: ring1fg, ring2bg: ring2bg, ring2fg: ring2fg, ring3bg: ring3bg, ring3fg: ring3fg, breakView: breakView) registerForTimerNotifications() displayAllTime() timerUpdatedTime() timerChangedCountingStatus() timerDurationChanged() layoutViewsForSize(layoutSize) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewDidDisappear(_ animated: Bool) { unregisterForTimerNotifications() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) let duration = coordinator.transitionDuration layoutViewsForSize(size, animateWithDuration: duration) } // MARK: - // MARK: ViewController override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - // MARK: Actions @IBAction func backButtonPressed(_ sender: AnyObject) { if let primaryViewController = parent as? PrimaryViewController { primaryViewController.presentMenuViewController() } } @IBAction func nextButtonPressed(_ sender: NextButton) { timer?.next() } @IBAction func startPauseButtonPressed(_ sender: StartPauseButton) { if let timer = timer { switch timer.state { case .Ready, .Paused, .PausedAfterComplete: timer.start() case .Counting, .CountingAfterComplete: timer.pause() } } } func setupButtonLayout(_ timer: Timer) { switch timer.state { case .Ready, .Paused, .PausedAfterComplete: startPauseButton.startPauseView?.label.text = "Start Timer" startPauseButton.startPauseView?.currentButton = .start startPauseButton.startPauseView?.unhighlight() case .Counting, .CountingAfterComplete: startPauseButton.startPauseView?.label.text = "Pause Timer" startPauseButton.startPauseView?.currentButton = .pause startPauseButton.startPauseView?.unhighlight() } setNextButtonState(timer) } func updateButtonLayout(_ timer: Timer) { // StartPause Button switch timer.state { case .Ready, .Paused, .PausedAfterComplete: startPauseButton.startPauseView?.label.text = "Start Timer" case .Counting, .CountingAfterComplete: startPauseButton.startPauseView?.label.text = "Pause Timer" } if timer.state == .Ready { startPauseButton.startPauseView?.currentButton = .start startPauseButton.startPauseView?.unhighlight() } setNextButtonState(timer) } func setNextButtonState(_ timer: Timer) { // Next Button switch timer.state { case .Ready, .PausedAfterComplete, .CountingAfterComplete: disableNextButton() case .Counting, .Paused: enableNextButton() } } func disableNextButton() { let inactiveColor = Appearance.Constants.GeekSpeakBlueInactiveColor nextButton.isEnabled = false nextButtonTimerOverlay.isEnabled = false nextButton.nextView?.tintColor = inactiveColor nextButton.nextView?.highlightColor = inactiveColor nextButton.nextView?.label.textColor = inactiveColor nextButton.nextView?.highlight() } func enableNextButton() { let activeColor = Appearance.Constants.GeekSpeakBlueColor nextButton.isEnabled = true nextButtonTimerOverlay.isEnabled = true nextButton.nextView?.tintColor = activeColor nextButton.nextView?.highlightColor = activeColor nextButton.nextView?.label.textColor = activeColor nextButton.nextView?.unhighlight() } // MARK: - // MARK: View Layout func layoutViewsForSize( _ size: CGSize) { layoutViewsForSize(size, animateWithDuration: 0.0) } func layoutViewsForSize( _ size: CGSize, animateWithDuration duration: TimeInterval) { if size.width < size.height { self.setContraintsForVerticalLayout() } else { self.setContraintsForHorizontalLayout() } } func setContraintsForVerticalLayout() { containerStackView.axis = .vertical controlsStackView.axis = .horizontal flipControlViews(controlsInOrder) } func setContraintsForHorizontalLayout() { containerStackView.axis = .horizontal controlsStackView.axis = .vertical flipControlViews(controlsInOrder.reversed()) } func flipControlViews(_ controls : [UIButton]) { let arrangedViews = controlsStackView.arrangedSubviews.reversed() arrangedViews.forEach {controlsStackView.removeArrangedSubview($0)} controls.forEach {controlsStackView.addArrangedSubview($0)} } func centerView(_ view: UIView, ToView toView: UIView, WithContraintParent parent: UIView) { let y = NSLayoutConstraint(item: view, attribute: .centerY, relatedBy: .equal, toItem: toView, attribute: .centerY, multiplier: 1.0, constant: 0.0) let x = NSLayoutConstraint(item: view, attribute: .centerX, relatedBy: .equal, toItem: toView, attribute: .centerX, multiplier: 1.0, constant: 0.0) parent.addConstraints([x,y]) } // MARK: - // MARK: Gestures func addSwipeGesture() { let gesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(TimerViewController.panGestureRecognized(_:))) gesture.edges = .left view.addGestureRecognizer(gesture) } func panGestureRecognized(_ sender: UIPanGestureRecognizer) { guard let primaryViewController = UIApplication.shared .keyWindow?.rootViewController as? PrimaryViewController else { assertionFailure("Could not find PrimaryViewController as root View controller") return } primaryViewController.panGestureRecognized(sender) } // MARK: - // MARK: Warning Animation var warningDuration = TimeInterval(0.75) fileprivate var warningStartTime = Date().timeIntervalSince1970 fileprivate var warningAnimationInProgress = false func animateWarning() { if !warningAnimationInProgress { warningStartTime = Date().timeIntervalSince1970 warningAnimationInProgress = true flashImageView.alpha = 0.0 animateBlackToWhite() } } func animateBlackToWhite() { UIView.animate( withDuration: 0.05, delay: 0.0, options: [], animations: { self.flashImageView.alpha = 1.0 self.view.backgroundColor = Appearance.Constants.BreakColor }, completion: { completed in if (self.warningStartTime + self.warningDuration) > Date().timeIntervalSince1970 { self.animateWhiteToBlack() } else { self.warningAnimationInProgress = false self.view.backgroundColor = UIColor.black self.flashImageView.alpha = 0.0 } }) } func animateWhiteToBlack() { UIView.animate( withDuration: 0.05, delay: 0.0, options: [], animations: { self.flashImageView.alpha = 0.0 self.view.backgroundColor = UIColor.black }, completion: { completed in if (self.warningStartTime + self.warningDuration) > Date().timeIntervalSince1970 { self.animateBlackToWhite() } else { self.warningAnimationInProgress = false self.view.backgroundColor = UIColor.black self.flashImageView.alpha = 0.0 } }) } // MARK: - // MARK: Setup func configureFGRing(_ ringView: RingView, withColor color: UIColor) -> RingView { ringView.color = color ringView.startAngle = TauAngle(degrees: 0) ringView.endAngle = TauAngle(degrees: 0) ringView.ringStyle = .rounded configureRing(ringView) return ringView } func configureBGRing(_ ringView: RingView, withColor color: UIColor) -> RingView { let darkenBy = Appearance.Constants.RingDarkeningFactor ringView.color = color.darkenColorWithMultiplier(darkenBy) ringView.startAngle = TauAngle(degrees: 0) ringView.endAngle = TauAngle(degrees: 360) ringView.ringStyle = .sharp configureRing(ringView) return ringView } func configureRing(_ ringView: RingView) { ringView.ringWidth = Appearance.Constants.RingWidth timerCirclesView.addSubview(ringView) ringView.isOpaque = false } func setupTimeLabelContraints(_ label: UILabel) { let width = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: label.superview, attribute: .width, multiplier: 160 / 736, constant: 0.0) width.priority = 1000 label.superview?.addConstraint(width) } func setupDescriptionLabelContraints(_ label: UILabel) { if let labelSuperView = label.superview { let height = NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: labelSuperView, attribute: .height, multiplier: 20 / 736, constant: 0.0) height.priority = 1000 labelSuperView.addConstraint(height) } } }
mit
bb887d0d2197c42a0cb3375d74d53554
28.251938
112
0.616669
5.447131
false
false
false
false
taqun/HBR
HBRTests/Tests/Parser/AtomFeedParserTest.swift
1
1627
// // AtomFeedParserTest.swift // HBR // // Created by taqun on 2015/07/30. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit import XCTest class AtomFeedParserTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } /* * Tests */ func testCreateInstanace() { let parser = AtomFeedParser() XCTAssertNotNil(parser) } private var callbackException: XCTestExpectation! func testParse() { let parser = AtomFeedParser() let path = NSBundle(forClass: self.dynamicType).pathForResource("atom", ofType: "xml") let data = NSData(contentsOfFile: path!)! callbackException = self.expectationWithDescription("Callback method is called") parser.parse(data, onComplete: self.testComplete) self.waitForExpectationsWithTimeout(0.5, handler: { (error) -> Void in }) } private func testComplete(parser: AtomFeedParser) { XCTAssertEqual(parser.itemDatas.count, 3) let item1 = parser.itemDatas[0] let title1 = item1["title"]! XCTAssertEqual(title1, "エントリー1") let item2 = parser.itemDatas[1] let link2 = item2["link"]! XCTAssertEqual(link2, "http://example.jp/bar") let item3 = parser.itemDatas[2] let issued3 = item3["issued"]! XCTAssertEqual(issued3, "2015-06-26T09:36:06") callbackException.fulfill() } }
mit
16d62181f116e3651807d9419bbce87c
23.439394
94
0.587725
4.468144
false
true
false
false
squaremeals/squaremeals-ios-app
SquareMeals/Model/CloudKit/CKService.swift
1
4129
// // CloudKitService.swift // SquareMeals // // Created by Zachary Shakked on 10/11/17. // Copyright © 2017 Shakd, LLC. All rights reserved. // import Foundation import CloudKit public final class CloudKitService { public let user: User fileprivate init(user: User) { self.user = user } static func create(completion: @escaping (Bool, AlertableError?, CloudKitService?) -> ()) { CKContainer.default().accountStatus { (status, error) in guard error == nil else { completion(false, CKError(error: error), nil) return } CKContainer.default().fetchUserRecordID { (userRecordID, error) in guard let userRecordID = userRecordID, error == nil else { completion(false, CKError(error: error), nil) return } CKContainer.default().publicCloudDatabase.fetch(withRecordID: userRecordID) { (record, error) in guard let userRecord = record, error == nil else { completion(false, CKError(error: error), nil) return } let user = User(record: userRecord) let cloudKitService = CloudKitService(user: user) print("User: \(user)") completion(true, nil, cloudKitService) } } } } public func saveUserInfo(_ userInfo: UserInfo, completion: @escaping (Bool, AlertableError?, User?) -> ()) -> Operation { let record: CKRecord = user.record if let firstName = userInfo.firstName { record[User.Fields.firstName] = firstName as CKRecordValue } if let lastName = userInfo.lastName { record[User.Fields.lastName] = lastName as CKRecordValue } if let birthday = userInfo.birthday { record[User.Fields.birthday] = birthday as CKRecordValue } if let weight = userInfo.weight { record[User.Fields.weight] = weight as CKRecordValue } if let height = userInfo.height { record[User.Fields.height] = height as CKRecordValue } if let measuringSystem = userInfo.measuringSystem { record[User.Fields.measuringSystem] = measuringSystem as CKRecordValue } return saveRecord(record: record, completion: completion) } public func saveRecord<T: CKWrapper>(record: CKRecord, completion: @escaping (Bool, AlertableError?, T?) -> ()) -> Operation { let saveOperation = CKModifyRecordsOperation(recordsToSave: [record], recordIDsToDelete: nil) saveOperation.qualityOfService = .userInitiated saveOperation.modifyRecordsCompletionBlock = { records, _, error in guard let record = records?.first, error == nil else { completion(false, CKError(error: error), nil) return } completion(true, nil, T(record: record)) } CKContainer.default().publicCloudDatabase.add(saveOperation) return saveOperation } public func saveRecords<T: CKWrapper>(records: [CKRecord], completion: @escaping (Bool, AlertableError?, [T]?) -> ()) -> Operation { let saveOperation = CKModifyRecordsOperation(recordsToSave: records, recordIDsToDelete: nil) saveOperation.qualityOfService = .userInitiated saveOperation.modifyRecordsCompletionBlock = { records, _, error in guard let records = records, error == nil else { completion(false, CKError(error: error), nil) return } completion(true, nil, records.map(T.init)) } CKContainer.default().publicCloudDatabase.add(saveOperation) return saveOperation } }
mit
e8f96dc7894efcf6272a71812fd5792b
34.895652
136
0.561773
5.496671
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_096_Unique_Binary_Search_Trees.swift
1
999
/* https://leetcode.com/problems/unique-binary-search-trees/ #96 Unique Binary Search Trees Level: medium Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 Inspired by @liaison at https://leetcode.com/discuss/24282/dp-solution-in-6-lines-with-explanation-f-i-n-g-i-1-g-n-i */ import Foundation class Medium_096_Unique_Binary_Search_Trees { // t=O(N^2), s=O(N) class func numTrees(_ n: Int) -> Int { var ret: [Int] = Array<Int>(repeating: 0, count: n+1) ret[0] = 1 ret[1] = 1 if 2 <= n { for i in 2 ... n { for j in 0 ..< i { ret[i] += ret[j] * ret[i-1-j] } } } return ret[n] } }
mit
9f5c9c498c0a611629347d0a01824e99
23.365854
116
0.472472
3.102484
false
false
false
false
jdevuyst/ruminant
Sources/chunkediterator.swift
1
1178
// // Created by Jonas De Vuyst on 18/02/15. // Copyright (c) 2015 Jonas De Vuyst. All rights reserved. // // chunkediterator.swift // n.b. ChunkedIterator copies can be advanced independently when backed by a persistent data structure // https://www.uraimo.com/2015/11/12/experimenting-with-swift-2-sequencetype-generatortype/ public class ChunkedIterator<T>: IteratorProtocol { public typealias Element = T public typealias ChunkFunction = (Int) -> (chunk: [T], offset: Int) public let f: ChunkFunction private let end: Int private var i: Int private var j = 0 private var chunk: [T] init(f: @escaping ChunkFunction, start: Int, end: Int) { assert(end >= start) self.f = f self.i = start self.end = end (chunk: self.chunk, offset: self.j) = end - start == 0 ? ([], 0) : f(start) } public func next() -> T? { guard i < end else { return nil } if j == chunk.count { (chunk: chunk, offset: j) = f(i) } i += 1 defer { j += 1 } return chunk[j] } }
epl-1.0
b37c0bae17d0f633c76319acda2001b5
24.608696
103
0.555178
3.69279
false
false
false
false
jhaigler94/cs4720-iOS
Pensieve/Pensieve/CreateMemPtViewController.swift
1
19695
// // CreateMemPtViewController.swift // Pensieve // // Created by Jennifer Ruth Haigler on 10/26/15. // Copyright © 2015 University of Virginia. All rights reserved. // import UIKit import CoreData import GoogleMaps import CoreLocation class CreateMemPtViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, CLLocationManagerDelegate, UITextFieldDelegate { let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext // Mark: Properties var memDate: String! var memTime: String! @IBOutlet weak var memNameLabel: UILabel! @IBOutlet var imageView: UIImageView! @IBOutlet weak var memptDateTextField: UITextField! @IBOutlet weak var memptTimeTextField: UITextField! var placePicker: GMSPlacePicker? var locationManager: CLLocationManager? var lat:String! = "38.031432" var lon:String! = "-78.510798" @IBOutlet weak var memptLocNameLabel: UILabel! @IBOutlet weak var memptLocAddLabel: UILabel! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var noteTextField: UITextField! var imageData: NSData! var passFromMemName:String! override func viewDidLoad() { super.viewDidLoad() memNameLabel.text = passFromMemName var stackFrame = stackView.frame stackFrame.size.width = UIScreen.mainScreen().bounds.width stackView.frame = stackFrame imageData = UIImagePNGRepresentation(UIImage(named: "defaultImage")!) noteTextField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { /* Are location services available on this device? */ if CLLocationManager.locationServicesEnabled(){ /* Do we have authorization to access location services? */ switch CLLocationManager.authorizationStatus(){ case .AuthorizedAlways: /* Yes, always */ createLocationManager(startImmediately: true) case .AuthorizedWhenInUse: /* Yes, only when our app is in use */ createLocationManager(startImmediately: true) case .Denied: /* No */ displayAlertWithTitle("Not Determined", message: "Location services are not allowed for this app") case .NotDetermined: /* We don't know yet, we have to ask */ createLocationManager(startImmediately: false) if let manager = self.locationManager{ manager.requestWhenInUseAuthorization() } case .Restricted: /* Restrictions have been applied, we have no access to location services */ displayAlertWithTitle("Restricted", message: "Location services are not allowed for this app") } } else { /* Location services are not enabled. Take appropriate action: for instance, prompt the user to enable the location services */ print("Location services are not enabled") } } // MARK: Actions @IBAction func takePhotoButton(sender: UIBarButtonItem) { if (UIImagePickerController.isSourceTypeAvailable(.Camera)) { if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil { let imagePickerController = UIImagePickerController() imagePickerController.sourceType = .Camera imagePickerController.delegate = self presentViewController(imagePickerController, animated: true, completion: nil) } else { var alert = UIAlertController(title: "Rear camera doesn't exist", message: "Application cannot access the camera.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) print("Application cannot access the camera.") //postAlert("Rear camera doesn't exist", message: "Application cannot access the camera.") } } else { var alert = UIAlertController(title: "Camera Inaccessable", message: "Application cannot access the camera.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } print("Camera inaccessable.") //postAlert("Camera inaccessable", message: "Application cannot access the camera.") } @IBAction func takePhoto(sender: UIButton) { if (UIImagePickerController.isSourceTypeAvailable(.Camera)) { if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil { let imagePickerController = UIImagePickerController() imagePickerController.sourceType = .Camera imagePickerController.delegate = self presentViewController(imagePickerController, animated: true, completion: nil) } else { var alert = UIAlertController(title: "Rear camera doesn't exist", message: "Application cannot access the camera.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) print("Application cannot access the camera.") //postAlert("Rear camera doesn't exist", message: "Application cannot access the camera.") } } else { var alert = UIAlertController(title: "Camera Inaccessable", message: "Application cannot access the camera.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } //print("Camera inaccessable.") //postAlert("Camera inaccessable", message: "Application cannot access the camera.") } @IBAction func pickPhotoFromLibrary(sender: UIButton) { if (UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary)) { let imagePickerController = UIImagePickerController() imagePickerController.sourceType = .PhotoLibrary imagePickerController.delegate = self presentViewController(imagePickerController, animated: true, completion: nil) } else { var alert = UIAlertController(title: "Photo Library Inaccessable", message: "Application cannot access the photo library.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } //print("Photo Library inaccessable.") //postAlert("Camera inaccessable", message: "Application cannot access the camera.") } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage imageView.image = selectedImage imageData = UIImagePNGRepresentation(selectedImage) dismissViewControllerAnimated(true, completion: nil) } @IBAction func saveMemPt(sender: UIBarButtonItem) { print("Bar Button Pressed") dismissViewControllerAnimated(true, completion: nil) } @IBAction func SaveMemPoint(sender: AnyObject) { print("Non Bar Button Pressed") var locName = memptLocNameLabel.text if memptLocNameLabel.text == "Location Name" { locName = "" } print("ImageData = \(_stdlib_getDemangledTypeName(imageData))") createNewMemory(memNameLabel.text!, date: memptDateTextField.text!, time: memptTimeTextField.text!, loc: locName!) } func createNewMemory(name: String, date: String, time: String, loc: String) -> Bool{ var i = 0 let fetchRequest = NSFetchRequest(entityName: "Memory") do { let mems = try managedObjectContext.executeFetchRequest(fetchRequest) for memory in mems{ if((memory.valueForKey("memname")as? String!)==(name)){ if ((memory.valueForKey("pointid")as? String!)==("0")) { memDate = (memory.valueForKey("memdate")as? String!) memTime = (memory.valueForKey("memtime")as? String!) } i++ } } } catch let error as NSError{ print(error) } print("Begininng") let newMem = NSEntityDescription.insertNewObjectForEntityForName("Memory", inManagedObjectContext: managedObjectContext) //as! Pensieve.Memory print("HERE?") newMem.setValue(name, forKey: "memname") print("Name Saved") newMem.setValue(time, forKey: "memtime") newMem.setValue(date, forKey: "memdate") newMem.setValue(loc, forKey: "memloc") newMem.setValue(String(i), forKey:"pointid") newMem.setValue(imageData, forKey: "picfileloc") newMem.setValue(noteTextField.text, forKey:"note") print("All the Rest Saved") print("Note:" + noteTextField.text!) //print("PICFILELOC: " + String(imageData)) do{ try managedObjectContext.save() } catch let error as NSError{ print("Failed to save the new person. Error = \(error)") } return false } //DatePicker @IBAction func pickDate(sender: UITextField) { print("pickdate button pressed") let inputView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 240)) var datePickerView : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 40, 0, 0)) datePickerView.datePickerMode = UIDatePickerMode.Date inputView.addSubview(datePickerView) // add date picker to UIView let doneButton = UIButton(frame: CGRectMake((self.view.frame.size.width/2) - (100/2), 0, 100, 50)) doneButton.setTitle("Done", forState: UIControlState.Normal) doneButton.setTitle("Done", forState: UIControlState.Highlighted) doneButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) doneButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted) inputView.addSubview(doneButton) // add Button to UIView doneButton.addTarget(self, action: "doneDatePicker:", forControlEvents: UIControlEvents.TouchUpInside) // set button click event sender.inputView = inputView datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged) handleDatePicker(datePickerView) // Set the date on start. } @IBAction func doneDatePicker(sender: UITextField) { memptDateTextField.resignFirstResponder() } func handleDatePicker(sender: UIDatePicker) { var dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .LongStyle dateFormatter.timeStyle = .NoStyle memptDateTextField.text = dateFormatter.stringFromDate(sender.date) } //TimePicker @IBAction func pickTime(sender: UITextField) { print("timepicker button pressed") let inputView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 240)) var timePickerView : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 40, 0, 0)) timePickerView.datePickerMode = UIDatePickerMode.Time inputView.addSubview(timePickerView) // add date picker to UIView let doneButton = UIButton(frame: CGRectMake((self.view.frame.size.width/2) - (100/2), 0, 100, 50)) doneButton.setTitle("Done", forState: UIControlState.Normal) doneButton.setTitle("Done", forState: UIControlState.Highlighted) doneButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) doneButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted) inputView.addSubview(doneButton) // add Button to UIView doneButton.addTarget(self, action: "doneTimePicker:", forControlEvents: UIControlEvents.TouchUpInside) // set button click event sender.inputView = inputView timePickerView.addTarget(self, action: Selector("handleTimePicker:"), forControlEvents: UIControlEvents.ValueChanged) handleTimePicker(timePickerView) // Set the date on start. } @IBAction func doneTimePicker(sender: UITextField) { memptTimeTextField.resignFirstResponder() } func handleTimePicker(sender: UIDatePicker) { var timeFormatter = NSDateFormatter() timeFormatter.dateStyle = .NoStyle timeFormatter.timeStyle = .ShortStyle memptTimeTextField.text = timeFormatter.stringFromDate(sender.date) } //LocationPicker @IBAction func getLocation(sender: UIButton) { if CLLocationManager.locationServicesEnabled() { let mylat = Double(lat) let mylon = Double(lon) let center = CLLocationCoordinate2DMake(mylat!, mylon!) let northEast = CLLocationCoordinate2DMake(center.latitude + 0.001, center.longitude + 0.001) let southWest = CLLocationCoordinate2DMake(center.latitude - 0.001, center.longitude - 0.001) let viewport = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest) let config = GMSPlacePickerConfig(viewport: viewport) placePicker = GMSPlacePicker(config: config) placePicker?.pickPlaceWithCallback({ (place: GMSPlace?, error: NSError?) -> Void in if let error = error { print("Pick Place error: \(error.localizedDescription)") return } if let place = place { self.memptLocNameLabel.text = place.name if (place.formattedAddress != nil) { self.memptLocAddLabel.text = place.formattedAddress.componentsSeparatedByString(", ").joinWithSeparator("\n") } } else { self.memptLocNameLabel.text = "No Place Selected" self.memptLocAddLabel.text = "" } }) } else { var alert = UIAlertController(title: "Alert", message: "Location Services disabled for this application.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } // MARK: Location func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if locations.count == 0{ //handle error here return } let newLocation = locations[0] print("Latitude = \(newLocation.coordinate.latitude)") print("Longitude = \(newLocation.coordinate.longitude)") lat = String(newLocation.coordinate.latitude) lon = String(newLocation.coordinate.longitude) } func locationManager(manager: CLLocationManager, didFailWithError error: NSError){ print("Location manager failed with error = \(error)") } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus){ print("The authorization status of location services is changed to: ", terminator: "") switch CLLocationManager.authorizationStatus(){ case .AuthorizedAlways: print("Authorized") case .AuthorizedWhenInUse: print("Authorized when in use") case .Denied: print("Denied") case .NotDetermined: print("Not determined") case .Restricted: print("Restricted") } } func createLocationManager(startImmediately startImmediately: Bool){ locationManager = CLLocationManager() if let manager = locationManager{ print("Successfully created the location manager") manager.delegate = self if startImmediately{ manager.startUpdatingLocation() } } } func displayAlertWithTitle(title: String, message: String){ let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert) controller.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(controller, animated: true, completion: nil) } // MARK: Segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "ToMemFromSave") { var SmemVC = segue.destinationViewController as! MemoryViewController SmemVC.passName = memNameLabel.text SmemVC.passDate = memDate SmemVC.passTime = memTime } } // MARK: TEXT VIEW func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let currentCharacterCount = textField.text?.characters.count ?? 0 if (range.length + range.location > currentCharacterCount){ return false } let newLength = currentCharacterCount + string.characters.count - range.length return newLength <= 30 } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
f4ca8d49368b51f87e57c0a68e49fe7e
40.902128
181
0.628161
5.761849
false
false
false
false
csjlengxiang/ObjectMapper
ObjectMapperTests/ObjectMapperTests.swift
7
20495
// // ObjectMapperTests.swift // ObjectMapperTests // // Created by Tristan Himmelman on 2014-10-16. // Copyright (c) 2014 hearst. All rights reserved. // import Foundation import XCTest import ObjectMapper import Nimble class ObjectMapperTests: XCTestCase { let userMapper = Mapper<User>() 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 testBasicParsing() { let username = "John Doe" let identifier = "user8723" let photoCount = 13 let age = 1227 let weight = 123.23 let float: Float = 123.231 let drinker = true let smoker = false let sex: Sex = .Female let subUserJSON = "{\"identifier\" : \"user8723\", \"drinker\" : true, \"age\": 17, \"username\" : \"sub user\" }" let userJSONString = "{\"username\":\"\(username)\",\"identifier\":\"\(identifier)\",\"photoCount\":\(photoCount),\"age\":\(age),\"drinker\":\(drinker),\"smoker\":\(smoker), \"sex\":\"\(sex.rawValue)\", \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"arrOpt\":[ \"bla\", true, 42 ], \"dictOpt\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"weight\": \(weight), \"float\": \(float), \"friend\": \(subUserJSON), \"friendDictionary\":{ \"bestFriend\": \(subUserJSON)}}" let user = userMapper.map(userJSONString)! expect(user).notTo(beNil()) expect(username).to(equal(user.username)) expect(identifier).to(equal(user.identifier)) expect(photoCount).to(equal(user.photoCount)) expect(age).to(equal(user.age)) expect(weight).to(equal(user.weight)) expect(float).to(equal(user.float)) expect(drinker).to(equal(user.drinker)) expect(smoker).to(equal(user.smoker)) expect(sex).to(equal(user.sex)) //print(Mapper().toJSONString(user, prettyPrint: true)) } func testInstanceParsing() { let username = "John Doe" let identifier = "user8723" let photoCount = 13 let age = 1227 let weight = 123.23 let float: Float = 123.231 let drinker = true let smoker = false let sex: Sex = .Female let subUserJSON = "{\"identifier\" : \"user8723\", \"drinker\" : true, \"age\": 17, \"username\" : \"sub user\" }" let userJSONString = "{\"username\":\"\(username)\",\"identifier\":\"\(identifier)\",\"photoCount\":\(photoCount),\"age\":\(age),\"drinker\":\(drinker),\"smoker\":\(smoker), \"sex\":\"\(sex.rawValue)\", \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"arrOpt\":[ \"bla\", true, 42 ], \"dictOpt\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 },\"weight\": \(weight), \"float\": \(float), \"friend\": \(subUserJSON), \"friendDictionary\":{ \"bestFriend\": \(subUserJSON)}}" let user = Mapper().map(userJSONString, toObject: User()) expect(username).to(equal(user.username)) expect(identifier).to(equal(user.identifier)) expect(photoCount).to(equal(user.photoCount)) expect(age).to(equal(user.age)) expect(weight).to(equal(user.weight)) expect(float).to(equal(user.float)) expect(drinker).to(equal(user.drinker)) expect(smoker).to(equal(user.smoker)) expect(sex).to(equal(user.sex)) //print(Mapper().toJSONString(user, prettyPrint: true)) } func testDictionaryParsing() { let name: String = "Genghis khan" let UUID: String = "12345" let major: Int = 99 let minor: Int = 1 let json: [String: AnyObject] = ["name": name, "UUID": UUID, "major": major] //test that the sematics of value types works as expected. the resulting maped student //should have the correct minor property set even thoug it's not mapped var s = Student() s.minor = minor let student = Mapper().map(json, toObject: s) expect(student.name).to(equal(name)) expect(student.UUID).to(equal(UUID)) expect(student.major).to(equal(major)) expect(student.minor).to(equal(minor)) //Test that mapping a reference type works as expected while not relying on the return value let username: String = "Barack Obama" let identifier: String = "Political" let photoCount: Int = 1000000000 let json2: [String: AnyObject] = ["username": username, "identifier": identifier, "photoCount": photoCount] let user = User() Mapper().map(json2, toObject: user) expect(user.username).to(equal(username)) expect(user.identifier).to(equal(identifier)) expect(user.photoCount).to(equal(photoCount)) } func testNullObject() { let JSONString = "{\"username\":\"bob\"}" let user = userMapper.map(JSONString) expect(user).notTo(beNil()) expect(user?.age).to(beNil()) } func testToObjectFromString() { let username = "bob" let JSONString = "{\"username\":\"\(username)\"}" let user = User() user.username = "Tristan" Mapper().map(JSONString, toObject: user) expect(user.username).to(equal(username)) } func testToObjectFromJSON() { let username = "bob" let JSON = ["username": username] let user = User() user.username = "Tristan" Mapper().map(JSON, toObject: user) expect(user.username).to(equal(username)) } func testToObjectFromAnyObject() { let username = "bob" let userJSON = ["username": username] let user = User() user.username = "Tristan" Mapper().map(userJSON as AnyObject?, toObject: user) expect(user.username).to(equal(username)) } func testToJSONAndBack(){ let user = User() user.username = "tristan_him" user.identifier = "tristan_him_identifier" user.photoCount = 0 user.age = 28 user.weight = 150 user.drinker = true user.smoker = false user.sex = .Female user.arr = ["cheese", 11234] let JSONString = Mapper().toJSONString(user, prettyPrint: true) //print(JSONString) let parsedUser = userMapper.map(JSONString!)! expect(parsedUser).notTo(beNil()) expect(user.identifier).to(equal(parsedUser.identifier)) expect(user.photoCount).to(equal(parsedUser.photoCount)) expect(user.age).to(equal(parsedUser.age)) expect(user.weight).to(equal(parsedUser.weight)) expect(user.drinker).to(equal(parsedUser.drinker)) expect(user.smoker).to(equal(parsedUser.smoker)) expect(user.sex).to(equal(parsedUser.sex)) } func testUnknownPropertiesIgnored() { let JSONString = "{\"username\":\"bob\",\"identifier\":\"bob1987\", \"foo\" : \"bar\", \"fooArr\" : [ 1, 2, 3], \"fooObj\" : { \"baz\" : \"qux\" } }" let user = userMapper.map(JSONString) expect(user).notTo(beNil()) } func testInvalidJsonResultsInNilObject() { let JSONString = "{\"username\":\"bob\",\"identifier\":\"bob1987\"" // missing ending brace let user = userMapper.map(JSONString) expect(user).to(beNil()) } func testMapArrayJSON(){ let name1 = "Bob" let name2 = "Jane" let JSONString = "[{\"name\": \"\(name1)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC875\", \"major\": 541, \"minor\": 123},{ \"name\": \"\(name2)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC876\", \"major\": 54321,\"minor\": 13 }]" let students = Mapper<Student>().mapArray(JSONString) expect(students).notTo(beEmpty()) expect(students.count).to(equal(2)) expect(students[0].name).to(equal(name1)) expect(students[1].name).to(equal(name2)) } // test mapArray() with JSON string that is not an array form // should return a collection with one item func testMapArrayJSONWithNoArray(){ let name1 = "Bob" let JSONString = "{\"name\": \"\(name1)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC875\", \"major\": 541, \"minor\": 123}" let students = Mapper<Student>().mapArray(JSONString) expect(students).notTo(beEmpty()) expect(students.count).to(equal(1)) expect(students[0].name).to(equal(name1)) } func testArrayOfCustomObjects(){ let percentage1: Double = 0.1 let percentage2: Double = 1792.41 let JSONString = "{ \"tasks\": [{\"taskId\":103,\"percentage\":\(percentage1)},{\"taskId\":108,\"percentage\":\(percentage2)}] }" let plan = Mapper<Plan>().map(JSONString) let tasks = plan?.tasks expect(tasks).notTo(beNil()) expect(tasks?[0].percentage).to(equal(percentage1)) expect(tasks?[1].percentage).to(equal(percentage2)) } func testDictionaryOfArrayOfCustomObjects(){ let percentage1: Double = 0.1 let percentage2: Double = 1792.41 let JSONString = "{ \"dictionaryOfTasks\": { \"mondayTasks\" :[{\"taskId\":103,\"percentage\":\(percentage1)},{\"taskId\":108,\"percentage\":\(percentage2)}] } }" let plan = Mapper<Plan>().map(JSONString) let dictionaryOfTasks = plan?.dictionaryOfTasks expect(dictionaryOfTasks).notTo(beNil()) expect(dictionaryOfTasks?["mondayTasks"]?[0].percentage).to(equal(percentage1)) expect(dictionaryOfTasks?["mondayTasks"]?[1].percentage).to(equal(percentage2)) let planToJSON = Mapper().toJSONString(plan!, prettyPrint: false) //print(planToJSON) let planFromJSON = Mapper<Plan>().map(planToJSON!) let dictionaryOfTasks2 = planFromJSON?.dictionaryOfTasks expect(dictionaryOfTasks2).notTo(beNil()) expect(dictionaryOfTasks2?["mondayTasks"]?[0].percentage).to(equal(percentage1)) expect(dictionaryOfTasks2?["mondayTasks"]?[1].percentage).to(equal(percentage2)) } func testArrayOfEnumObjects(){ let a: ExampleEnum = .A let b: ExampleEnum = .B let c: ExampleEnum = .C let JSONString = "{ \"enums\": [\(a.rawValue), \(b.rawValue), \(c.rawValue)] }" let enumArray = Mapper<ExampleEnumArray>().map(JSONString) let enums = enumArray?.enums expect(enums).notTo(beNil()) expect(enums?.count).to(equal(3)) expect(enums?[0]).to(equal(a)) expect(enums?[1]).to(equal(b)) expect(enums?[2]).to(equal(c)) } func testDictionaryOfCustomObjects(){ let percentage1: Double = 0.1 let percentage2: Double = 1792.41 let JSONString = "{\"tasks\": { \"task1\": {\"taskId\":103,\"percentage\":\(percentage1)}, \"task2\": {\"taskId\":108,\"percentage\":\(percentage2)}}}" let taskDict = Mapper<TaskDictionary>().map(JSONString) let task = taskDict?.tasks?["task1"] expect(task).notTo(beNil()) expect(task?.percentage).to(equal(percentage1)) } func testDictionryOfEnumObjects(){ let a: ExampleEnum = .A let b: ExampleEnum = .B let c: ExampleEnum = .C let JSONString = "{ \"enums\": {\"A\": \(a.rawValue), \"B\": \(b.rawValue), \"C\": \(c.rawValue)} }" let enumDict = Mapper<ExampleEnumDictionary>().map(JSONString) let enums = enumDict?.enums expect(enums).notTo(beNil()) expect(enums?.count).to(equal(3)) } func testDoubleParsing(){ let percentage1: Double = 1792.41 let JSONString = "{\"taskId\":103,\"percentage\":\(percentage1)}" let task = Mapper<Task>().map(JSONString) expect(task).notTo(beNil()) expect(task?.percentage).to(equal(percentage1)) } func testMappingAGenericObject(){ let code: Int = 22 let JSONString = "{\"result\":{\"code\":\(code)}}" let response = Mapper<Response<Status>>().map(JSONString) let status = response?.result?.status expect(status).notTo(beNil()) expect(status).to(equal(code)) } func testToJSONArray(){ let task1 = Task() task1.taskId = 1 task1.percentage = 11.1 let task2 = Task() task2.taskId = 2 task2.percentage = 22.2 let task3 = Task() task3.taskId = 3 task3.percentage = 33.3 let taskArray = [task1, task2, task3] let JSONArray = Mapper().toJSONArray(taskArray) let taskId1 = JSONArray[0]["taskId"] as? Int let percentage1 = JSONArray[0]["percentage"] as? Double expect(taskId1).to(equal(task1.taskId)) expect(percentage1).to(equal(task1.percentage)) let taskId2 = JSONArray[1]["taskId"] as? Int let percentage2 = JSONArray[1]["percentage"] as? Double expect(taskId2).to(equal(task2.taskId)) expect(percentage2).to(equal(task2.percentage)) let taskId3 = JSONArray[2]["taskId"] as? Int let percentage3 = JSONArray[2]["percentage"] as? Double expect(taskId3).to(equal(task3.taskId)) expect(percentage3).to(equal(task3.percentage)) } func testSubclass() { let object = Subclass() object.base = "base var" object.sub = "sub var" let json = Mapper().toJSON(object) let parsedObject = Mapper<Subclass>().map(json) expect(object.base).to(equal(parsedObject?.base)) expect(object.sub).to(equal(parsedObject?.sub)) } func testGenericSubclass() { let object = GenericSubclass<String>() object.base = "base var" object.sub = "sub var" let json = Mapper().toJSON(object) let parsedObject = Mapper<GenericSubclass<String>>().map(json) expect(object.base).to(equal(parsedObject?.base)) expect(object.sub).to(equal(parsedObject?.sub)) } func testSubclassWithGenericArrayInSuperclass() { let JSONString = "{\"genericItems\":[{\"value\":\"value0\"}, {\"value\":\"value1\"}]}" let parsedObject = Mapper<SubclassWithGenericArrayInSuperclass<AnyObject>>().map(JSONString) let genericItems = parsedObject?.genericItems expect(genericItems).notTo(beNil()) expect(genericItems?[0].value).to(equal("value0")) expect(genericItems?[1].value).to(equal("value1")) } func testImmutableMappable() { let mapper = Mapper<Immutable>() let JSON = ["prop1": "Immutable!", "prop2": 255, "prop3": true ] let immutable: Immutable! = mapper.map(JSON) expect(immutable).notTo(beNil()) expect(immutable?.prop1).to(equal("Immutable!")) expect(immutable?.prop2).to(equal(255)) expect(immutable?.prop3).to(equal(true)) expect(immutable?.prop4).to(equal(DBL_MAX)) let JSON2 = [ "prop1": "prop1", "prop2": NSNull() ] let immutable2 = mapper.map(JSON2) expect(immutable2).to(beNil()) let JSONFromObject = mapper.toJSON(immutable) expect(mapper.map(JSONFromObject)).to(equal(immutable)) } func testArrayOfArrayOfMappable() { let base1 = "1" let base2 = "2" let base3 = "3" let base4 = "4" let array1 = [["base": base1], ["base": base2], ["base": base3]] let array2 = [["base": base4]] let JSON = ["twoDimensionalArray":[array1, array2]] let arrayTest = Mapper<ArrayTest>().map(JSON) expect(arrayTest).notTo(beNil()) expect(arrayTest?.twoDimensionalArray?[0][0].base).to(equal(base1)) expect(arrayTest?.twoDimensionalArray?[0][1].base).to(equal(base2)) expect(arrayTest?.twoDimensionalArray?[0][2].base).to(equal(base3)) expect(arrayTest?.twoDimensionalArray?[1][0].base).to(equal(base4)) expect(arrayTest?.twoDimensionalArray?[0].count).to(equal(array1.count)) expect(arrayTest?.twoDimensionalArray?[1].count).to(equal(array2.count)) let backToJSON = Mapper<ArrayTest>().toJSON(arrayTest!) expect(backToJSON).notTo(beNil()) let arrayTest2 = Mapper<ArrayTest>().map(backToJSON) expect(arrayTest2).notTo(beNil()) expect(arrayTest2?.twoDimensionalArray?[0][0].base).to(equal(arrayTest?.twoDimensionalArray?[0][0].base)) expect(arrayTest2?.twoDimensionalArray?[0][1].base).to(equal(arrayTest?.twoDimensionalArray?[0][1].base)) } } class Response<T: Mappable>: Mappable { var result: T? required init?(_ map: Map){ } func mapping(map: Map) { result <- map["result"] } } class Status: Mappable { var status: Int? required init?(_ map: Map){ } func mapping(map: Map) { status <- map["code"] } } class Plan: Mappable { var tasks: [Task]? var dictionaryOfTasks: [String: [Task]]? required init?(_ map: Map){ } func mapping(map: Map) { tasks <- map["tasks"] dictionaryOfTasks <- map["dictionaryOfTasks"] } } class Task: Mappable { var taskId: Int? var percentage: Double? init(){ } required init?(_ map: Map){ } func mapping(map: Map) { taskId <- map["taskId"] percentage <- map["percentage"] } } class TaskDictionary: Mappable { var test: String? var tasks: [String : Task]? required init?(_ map: Map){ } func mapping(map: Map) { test <- map["test"] tasks <- map["tasks"] } } // Confirm that struct can conform to `Mappable` struct Student: Mappable { var name: String? var UUID: String? var major: Int? var minor: Int? init(){ } init?(_ map: Map){ } mutating func mapping(map: Map) { name <- map["name"] UUID <- map["UUID"] major <- map["major"] minor <- map["minor"] } } enum Sex: String { case Male = "Male" case Female = "Female" } class User: Mappable { var username: String = "" var identifier: String? var photoCount: Int = 0 var age: Int? var weight: Double? var float: Float? var drinker: Bool = false var smoker: Bool? var sex: Sex? var arr: [AnyObject] = [] var arrOptional: [AnyObject]? var dict: [String : AnyObject] = [:] var dictOptional: [String : AnyObject]? var dictString: [String : String]? var friendDictionary: [String : User]? var friend: User? var friends: [User]? = [] init(){ } required init?(_ map: Map){ } func mapping(map: Map) { username <- map["username"] identifier <- map["identifier"] photoCount <- map["photoCount"] age <- map["age"] weight <- map["weight"] float <- map["float"] drinker <- map["drinker"] smoker <- map["smoker"] sex <- map["sex"] arr <- map["arr"] arrOptional <- map["arrOpt"] dict <- map["dict"] dictOptional <- map["dictOpt"] friend <- map["friend"] friends <- map["friends"] friendDictionary <- map["friendDictionary"] dictString <- map["dictString"] } } class Base: Mappable { var base: String? init(){ } required init?(_ map: Map){ } func mapping(map: Map) { base <- map["base"] } } class Subclass: Base { var sub: String? override init(){ super.init() } required init?(_ map: Map){ super.init(map) } override func mapping(map: Map) { super.mapping(map) sub <- map["sub"] } } class GenericSubclass<T>: Base { var sub: String? override init(){ super.init() } required init?(_ map: Map){ super.init(map) } override func mapping(map: Map) { super.mapping(map) sub <- map["sub"] } } class WithGenericArray<T: Mappable>: Mappable { var genericItems: [T]? required init?(_ map: Map){ } func mapping(map: Map) { genericItems <- map["genericItems"] } } class ConcreteItem: Mappable { var value: String? required init?(_ map: Map){ } func mapping(map: Map) { value <- map["value"] } } class SubclassWithGenericArrayInSuperclass<Unused>: WithGenericArray<ConcreteItem> { required init?(_ map: Map){ super.init(map) } } enum ExampleEnum: Int { case A case B case C } class ExampleEnumArray: Mappable { var enums: [ExampleEnum] = [] required init?(_ map: Map){ } func mapping(map: Map) { enums <- map["enums"] } } class ExampleEnumDictionary: Mappable { var enums: [String: ExampleEnum] = [:] required init?(_ map: Map){ } func mapping(map: Map) { enums <- map["enums"] } } class ArrayTest: Mappable { var twoDimensionalArray: Array<Array<Base>>? required init?(_ map: Map){} func mapping(map: Map) { twoDimensionalArray <- map["twoDimensionalArray"] } } struct Immutable: Equatable { let prop1: String let prop2: Int let prop3: Bool let prop4: Double } extension Immutable: Mappable { init?(_ map: Map) { prop1 = map["prop1"].valueOrFail() prop2 = map["prop2"].valueOrFail() prop3 = map["prop3"].valueOrFail() prop4 = map["prop4"].valueOr(DBL_MAX) if !map.isValid { return nil } } mutating func mapping(map: Map) { switch map.mappingType { case .FromJSON: if let x = Immutable(map) { self = x } case .ToJSON: var prop1 = self.prop1 var prop2 = self.prop2 var prop3 = self.prop3 var prop4 = self.prop4 prop1 <- map["prop1"] prop2 <- map["prop2"] prop3 <- map["prop3"] prop4 <- map["prop4"] } } } func ==(lhs: Immutable, rhs: Immutable) -> Bool { return lhs.prop1 == rhs.prop1 && lhs.prop2 == rhs.prop2 && lhs.prop3 == rhs.prop3 && lhs.prop4 == rhs.prop4 }
mit
45cbf7f44207308c657430a311a3c08c
25.616883
547
0.636497
3.461409
false
true
false
false
feliperuzg/CleanExample
Pods/URITemplate/Sources/URITemplate.swift
3
19435
// // URITemplate.swift // URITemplate // // Created by Kyle Fuller on 25/11/2014. // Copyright (c) 2014 Kyle Fuller. All rights reserved. // import Foundation // MARK: URITemplate /// A data structure to represent an RFC6570 URI template. public struct URITemplate : CustomStringConvertible, Equatable, Hashable, ExpressibleByStringLiteral, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByUnicodeScalarLiteral { /// The underlying URI template public let template:String var regex:NSRegularExpression { let expression: NSRegularExpression? do { expression = try NSRegularExpression(pattern: "\\{([^\\}]+)\\}", options: NSRegularExpression.Options(rawValue: 0)) } catch let error as NSError { fatalError("Invalid Regex \(error)") } return expression! } var operators:[Operator] { return [ StringExpansion(), ReservedExpansion(), FragmentExpansion(), LabelExpansion(), PathSegmentExpansion(), PathStyleParameterExpansion(), FormStyleQueryExpansion(), FormStyleQueryContinuation(), ] } /// Initialize a URITemplate with the given template public init(template:String) { self.template = template } public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { template = value } public typealias UnicodeScalarLiteralType = StringLiteralType public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { template = value } public init(stringLiteral value: StringLiteralType) { template = value } /// Returns a description of the URITemplate public var description: String { return template } public var hashValue: Int { return template.hashValue } /// Returns the set of keywords in the URI Template public var variables: [String] { let expressions = regex.matches(template).map { expression -> String in // Removes the { and } from the expression #if swift(>=4.0) return String(expression[expression.characters.index(after: expression.startIndex)..<expression.characters.index(before: expression.endIndex)]) #else return expression.substring(with: expression.characters.index(after: expression.startIndex)..<expression.characters.index(before: expression.endIndex)) #endif } return expressions.map { expression -> [String] in var expression = expression for op in self.operators { if let op = op.op { if expression.hasPrefix(op) { #if swift(>=4.0) expression = String(expression[expression.characters.index(after: expression.startIndex)...]) #else expression = expression.substring(from: expression.characters.index(after: expression.startIndex)) #endif break } } } return expression.components(separatedBy: ",").map { component in if component.hasSuffix("*") { #if swift(>=4.0) return String(component[..<component.characters.index(before: component.endIndex)]) #else return component.substring(to: component.characters.index(before: component.endIndex)) #endif } else { return component } } }.reduce([], +) } /// Expand template as a URI Template using the given variables public func expand(_ variables: [String: Any]) -> String { return regex.substitute(template) { string in #if swift(>=4.0) var expression = String(string[string.characters.index(after: string.startIndex)..<string.characters.index(before: string.endIndex)]) let firstCharacter = String(expression[..<expression.characters.index(after: expression.startIndex)]) #else var expression = string.substring(with: string.characters.index(after: string.startIndex)..<string.characters.index(before: string.endIndex)) let firstCharacter = expression.substring(to: expression.characters.index(after: expression.startIndex)) #endif var op = self.operators.filter { if let op = $0.op { return op == firstCharacter } return false }.first if (op != nil) { #if swift(>=4.0) expression = String(expression[expression.characters.index(after: expression.startIndex)...]) #else expression = expression.substring(from: expression.characters.index(after: expression.startIndex)) #endif } else { op = self.operators.first } let rawExpansions = expression.components(separatedBy: ",").map { vari -> String? in var variable = vari var prefix:Int? if let range = variable.range(of: ":") { #if swift(>=4.0) prefix = Int(String(variable[range.upperBound...])) variable = String(variable[..<range.lowerBound]) #else prefix = Int(variable.substring(from: range.upperBound)) variable = variable.substring(to: range.lowerBound) #endif } let explode = variable.hasSuffix("*") if explode { #if swift(>=4.0) variable = String(variable[..<variable.characters.index(before: variable.endIndex)]) #else variable = variable.substring(to: variable.characters.index(before: variable.endIndex)) #endif } if let value: Any = variables[variable] { return op!.expand(variable, value: value, explode: explode, prefix:prefix) } return op!.expand(variable, value:nil, explode:false, prefix:prefix) } let expansions = rawExpansions.reduce([], { (accumulator, expansion) -> [String] in if let expansion = expansion { return accumulator + [expansion] } return accumulator }) if expansions.count > 0 { return op!.prefix + expansions.joined(separator: op!.joiner) } return "" } } func regexForVariable(_ variable:String, op:Operator?) -> String { if op != nil { return "(.*)" } else { return "([A-z0-9%_\\-]+)" } } func regexForExpression(_ expression:String) -> String { var expression = expression let op = operators.filter { $0.op != nil && expression.hasPrefix($0.op!) }.first if op != nil { #if swift(>=4.0) expression = String(expression[expression.characters.index(after: expression.startIndex)..<expression.endIndex]) #else expression = expression.substring(with: expression.characters.index(after: expression.startIndex)..<expression.endIndex) #endif } let regexes = expression.components(separatedBy: ",").map { variable -> String in return self.regexForVariable(variable, op: op) } return regexes.joined(separator: (op ?? StringExpansion()).joiner) } var extractionRegex:NSRegularExpression? { let regex = try! NSRegularExpression(pattern: "(\\{([^\\}]+)\\})|[^(.*)]", options: NSRegularExpression.Options(rawValue: 0)) let pattern = regex.substitute(self.template) { expression in if expression.hasPrefix("{") && expression.hasSuffix("}") { let startIndex = expression.characters.index(after: expression.startIndex) let endIndex = expression.characters.index(before: expression.endIndex) #if swift(>=4.0) return self.regexForExpression(String(expression[startIndex..<endIndex])) #else return self.regexForExpression(expression.substring(with: startIndex..<endIndex)) #endif } else { return NSRegularExpression.escapedPattern(for: expression) } } do { return try NSRegularExpression(pattern: "^\(pattern)$", options: NSRegularExpression.Options(rawValue: 0)) } catch _ { return nil } } /// Extract the variables used in a given URL public func extract(_ url:String) -> [String:String]? { if let expression = extractionRegex { let input = url as NSString let range = NSRange(location: 0, length: input.length) let results = expression.matches(in: url, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range) if let result = results.first { var extractedVariables:[String: String] = [:] for (index, variable) in variables.enumerated() { #if swift(>=4.0) let range = result.range(at: index + 1) #else let range = result.rangeAt(index + 1) #endif let value = NSString(string: input.substring(with: range)).removingPercentEncoding extractedVariables[variable] = value } return extractedVariables } } return nil } } /// Determine if two URITemplate's are equivalent public func ==(lhs:URITemplate, rhs:URITemplate) -> Bool { return lhs.template == rhs.template } // MARK: Extensions extension NSRegularExpression { func substitute(_ string:String, block:((String) -> (String))) -> String { let oldString = string as NSString let range = NSRange(location: 0, length: oldString.length) var newString = string as NSString let matches = self.matches(in: string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range) for match in Array(matches.reversed()) { let expression = oldString.substring(with: match.range) let replacement = block(expression) newString = newString.replacingCharacters(in: match.range, with: replacement) as NSString } return newString as String } func matches(_ string:String) -> [String] { let input = string as NSString let range = NSRange(location: 0, length: input.length) let results = self.matches(in: string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range) return results.map { result -> String in return input.substring(with: result.range) } } } extension String { func percentEncoded() -> String { return addingPercentEncoding(withAllowedCharacters: CharacterSet.URITemplate.unreserved)! } } // MARK: Operators protocol Operator { /// Operator var op:String? { get } /// Prefix for the expanded string var prefix:String { get } /// Character to use to join expanded components var joiner:String { get } func expand(_ variable:String, value: Any?, explode:Bool, prefix:Int?) -> String? } class BaseOperator { var joiner:String { return "," } func expand(_ variable:String, value: Any?, explode:Bool, prefix:Int?) -> String? { if let value = value { if let values = value as? [String: Any] { return expand(variable:variable, value: values, explode: explode) } else if let values = value as? [Any] { return expand(variable:variable, value: values, explode: explode) } else if let _ = value as? NSNull { return expand(variable:variable) } else { return expand(variable:variable, value:"\(value)", prefix:prefix) } } return expand(variable:variable) } // Point to overide to expand a value (i.e, perform encoding) func expand(value:String) -> String { return value } // Point to overide to expanding a string func expand(variable:String, value:String, prefix:Int?) -> String { if let prefix = prefix { if value.characters.count > prefix { let index = value.characters.index(value.startIndex, offsetBy: prefix, limitedBy: value.endIndex) #if swift(>=4.0) return expand(value: String(value[..<index!])) #else return expand(value: value.substring(to: index!)) #endif } } return expand(value: value) } // Point to overide to expanding an array func expand(variable:String, value:[Any], explode:Bool) -> String? { let joiner = explode ? self.joiner : "," return value.map { self.expand(value: "\($0)") }.joined(separator: joiner) } // Point to overide to expanding a dictionary func expand(variable: String, value: [String: Any], explode: Bool) -> String? { let joiner = explode ? self.joiner : "," let keyValueJoiner = explode ? "=" : "," let elements = value.map({ (key, value) -> String in let expandedKey = self.expand(value: key) let expandedValue = self.expand(value: "\(value)") return "\(expandedKey)\(keyValueJoiner)\(expandedValue)" }) return elements.joined(separator: joiner) } // Point to overide when value not found func expand(variable: String) -> String? { return nil } } /// RFC6570 (3.2.2) Simple String Expansion: {var} class StringExpansion : BaseOperator, Operator { var op:String? { return nil } var prefix:String { return "" } override var joiner:String { return "," } override func expand(value:String) -> String { return value.percentEncoded() } } /// RFC6570 (3.2.3) Reserved Expansion: {+var} class ReservedExpansion : BaseOperator, Operator { var op:String? { return "+" } var prefix:String { return "" } override var joiner:String { return "," } override func expand(value:String) -> String { return value.addingPercentEncoding(withAllowedCharacters: CharacterSet.uriTemplateReservedAllowed)! } } /// RFC6570 (3.2.4) Fragment Expansion {#var} class FragmentExpansion : BaseOperator, Operator { var op:String? { return "#" } var prefix:String { return "#" } override var joiner:String { return "," } override func expand(value:String) -> String { return value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)! } } /// RFC6570 (3.2.5) Label Expansion with Dot-Prefix: {.var} class LabelExpansion : BaseOperator, Operator { var op:String? { return "." } var prefix:String { return "." } override var joiner:String { return "." } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:[Any], explode:Bool) -> String? { if value.count > 0 { return super.expand(variable: variable, value: value, explode: explode) } return nil } } /// RFC6570 (3.2.6) Path Segment Expansion: {/var} class PathSegmentExpansion : BaseOperator, Operator { var op:String? { return "/" } var prefix:String { return "/" } override var joiner:String { return "/" } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:[Any], explode:Bool) -> String? { if value.count > 0 { return super.expand(variable: variable, value: value, explode: explode) } return nil } } /// RFC6570 (3.2.7) Path-Style Parameter Expansion: {;var} class PathStyleParameterExpansion : BaseOperator, Operator { var op:String? { return ";" } var prefix:String { return ";" } override var joiner:String { return ";" } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:String, prefix:Int?) -> String { if value.characters.count > 0 { let expandedValue = super.expand(variable: variable, value: value, prefix: prefix) return "\(variable)=\(expandedValue)" } return variable } override func expand(variable:String, value:[Any], explode:Bool) -> String? { let joiner = explode ? self.joiner : "," let expandedValue = value.map { let expandedValue = self.expand(value: "\($0)") if explode { return "\(variable)=\(expandedValue)" } return expandedValue }.joined(separator: joiner) if !explode { return "\(variable)=\(expandedValue)" } return expandedValue } override func expand(variable: String, value: [String: Any], explode: Bool) -> String? { let expandedValue = super.expand(variable: variable, value: value, explode: explode) if let expandedValue = expandedValue { if (!explode) { return "\(variable)=\(expandedValue)" } } return expandedValue } } /// RFC6570 (3.2.8) Form-Style Query Expansion: {?var} class FormStyleQueryExpansion : BaseOperator, Operator { var op:String? { return "?" } var prefix:String { return "?" } override var joiner:String { return "&" } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:String, prefix:Int?) -> String { let expandedValue = super.expand(variable: variable, value: value, prefix: prefix) return "\(variable)=\(expandedValue)" } override func expand(variable: String, value: [Any], explode: Bool) -> String? { if value.count > 0 { let joiner = explode ? self.joiner : "," let expandedValue = value.map { let expandedValue = self.expand(value: "\($0)") if explode { return "\(variable)=\(expandedValue)" } return expandedValue }.joined(separator: joiner) if !explode { return "\(variable)=\(expandedValue)" } return expandedValue } return nil } override func expand(variable: String, value: [String: Any], explode: Bool) -> String? { if value.count > 0 { let expandedVariable = self.expand(value: variable) let expandedValue = super.expand(variable: variable, value: value, explode: explode) if let expandedValue = expandedValue { if (!explode) { return "\(expandedVariable)=\(expandedValue)" } } return expandedValue } return nil } } /// RFC6570 (3.2.9) Form-Style Query Continuation: {&var} class FormStyleQueryContinuation : BaseOperator, Operator { var op:String? { return "&" } var prefix:String { return "&" } override var joiner:String { return "&" } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:String, prefix:Int?) -> String { let expandedValue = super.expand(variable: variable, value: value, prefix: prefix) return "\(variable)=\(expandedValue)" } override func expand(variable: String, value: [Any], explode: Bool) -> String? { let joiner = explode ? self.joiner : "," let expandedValue = value.map { let expandedValue = self.expand(value: "\($0)") if explode { return "\(variable)=\(expandedValue)" } return expandedValue }.joined(separator: joiner) if !explode { return "\(variable)=\(expandedValue)" } return expandedValue } override func expand(variable: String, value: [String: Any], explode: Bool) -> String? { let expandedValue = super.expand(variable: variable, value: value, explode: explode) if let expandedValue = expandedValue { if (!explode) { return "\(variable)=\(expandedValue)" } } return expandedValue } } private extension CharacterSet { struct URITemplate { static let digits = CharacterSet(charactersIn: "0"..."9") static let genDelims = CharacterSet(charactersIn: ":/?#[]@") static let subDelims = CharacterSet(charactersIn: "!$&'()*+,;=") static let unreservedSymbols = CharacterSet(charactersIn: "-._~") static let unreserved = { return alpha.union(digits).union(unreservedSymbols) }() static let reserved = { return genDelims.union(subDelims) }() static let alpha = { () -> CharacterSet in let upperAlpha = CharacterSet(charactersIn: "A"..."Z") let lowerAlpha = CharacterSet(charactersIn: "a"..."z") return upperAlpha.union(lowerAlpha) }() } static let uriTemplateReservedAllowed = { return URITemplate.unreserved.union(URITemplate.reserved) }() }
mit
874a959c9fbaff60b98c91ea37a479e3
29.462382
182
0.661538
4.384164
false
false
false
false
lokinfey/MyPerfectframework
Examples/Authenticator/Authenticator Client/LoginViewController.swift
1
3041
// // LoginViewController.swift // Authenticator // // Created by Kyle Jessup on 2015-11-12. // Copyright © 2015 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import UIKit let LOGIN_SEGUE_ID = "loginSegue" class LoginViewController: UIViewController, NSURLSessionDelegate, UITextFieldDelegate { @IBOutlet var emailAddressText: UITextField? @IBOutlet var passwordText: UITextField? var message = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.emailAddressText?.delegate = self self.passwordText?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { if identifier == LOGIN_SEGUE_ID { // start login process tryLogin() return false } return true } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let dest = segue.destinationViewController as? ResultViewController { dest.message = self.message } } func tryLogin() { let urlSessionDelegate = URLSessionDelegate(username: self.emailAddressText!.text!, password: self.passwordText!.text!) { (d:NSData?, res:NSURLResponse?, e:NSError?) -> Void in if let _ = e { self.message = "Failed with error \(e!)" } else if let httpRes = res as? NSHTTPURLResponse where httpRes.statusCode != 200 { self.message = "Failed with HTTP code \(httpRes.statusCode)" } else { let deserialized = try! NSJSONSerialization.JSONObjectWithData(d!, options: NSJSONReadingOptions.AllowFragments) self.message = "Logged in \(deserialized["firstName"]!!) \(deserialized["lastName"]!!)" } dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier(LOGIN_SEGUE_ID, sender: nil) } } let sessionConfig = NSURLSession.sharedSession().configuration let session = NSURLSession(configuration: sessionConfig, delegate: urlSessionDelegate, delegateQueue: nil) let req = NSMutableURLRequest(URL: NSURL(string: END_POINT + "login")!) req.addValue("application/json", forHTTPHeaderField: "Accept") let task = session.dataTaskWithRequest(req) task.resume() } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
apache-2.0
64480722ff82d3c278fdc358b3f046cc
30.340206
123
0.66875
4.684129
false
false
false
false
larryhou/swift
ByteArray/ByteArray/ByteArray.swift
1
12081
// // ByteArray.swift // ByteArray // // Created by larryhou on 5/20/15. // Copyright (c) 2015 larryhou. All rights reserved. // import Foundation class ByteArray { enum Endian: Int { case LITTLE_ENDIAN = 1 // NS_LittleEndian case BIG_ENDIAN = 2 // NS_BigEndian } var endian: Endian var data: NSMutableData var position: Int private var range: NSRange var length: Int {return data.length } var bytesAvailable: Bool {return position < length} init() { data = NSMutableData() endian = Endian.LITTLE_ENDIAN range = NSRange(location: 0, length: 0) position = 0 } convenience init(data: NSData) { self.init() self.data.appendData(data) } // MARK: subscript subscript(index: Int) -> UInt8 { var value: UInt8 = 0 data.getBytes(&value, range: NSRange(location: index, length: 1)) return value } // MARK: clear func clear() { data = NSMutableData() position = 0 } // MARK: ByteArray read func readBoolean() -> Bool { range.location = position range.length = 1 var flag = false data.getBytes(&flag, range: range) position += range.length return flag } func readDouble() -> Double { range.location = position range.length = 8 var value: Double = 0.0 if endian == Endian.BIG_ENDIAN { var bytes = [UInt8](count: range.length, repeatedValue: 0) data.getBytes(&bytes, range: range) bytes = bytes.reverse() value = UnsafePointer<Double>(bytes).memory } else { data.getBytes(&value, range: range) } position += range.length return value } func readFloat() -> Float32 { range.location = position range.length = 4 var value: Float32 = 0.0 if endian == Endian.BIG_ENDIAN { var bytes = [UInt8](count: range.length, repeatedValue: 0) data.getBytes(&bytes, range: range) bytes = bytes.reverse() value = UnsafePointer<Float32>(bytes).memory } else { data.getBytes(&value, range: range) } position += range.length return value } func readInt8() -> Int8 { range.location = position range.length = 1 var value: Int8 = 0 data.getBytes(&value, range: range) position += range.length return value } func readInt16() -> Int16 { range.location = position range.length = 2 var value: Int16 = 0 data.getBytes(&value, range: range) position += range.length return endian == Endian.BIG_ENDIAN ? value.bigEndian : value } func readInt32() -> Int32 { range.location = position range.length = 4 var value: Int32 = 0 data.getBytes(&value, range: range) position += range.length return endian == Endian.BIG_ENDIAN ? value.bigEndian : value } func readInt64() -> Int { range.location = position range.length = 8 var value: Int = 0 data.getBytes(&value, range: range) position += range.length return endian == Endian.BIG_ENDIAN ? value.bigEndian : value } func readUInt8() -> UInt8 { range.location = position range.length = 1 var value: UInt8 = 0 data.getBytes(&value, range: range) position += range.length return value } func readUInt16() -> UInt16 { range.location = position range.length = 2 var value: UInt16 = 0 data.getBytes(&value, range: range) position += data.length return endian == Endian.BIG_ENDIAN ? value.bigEndian : value } func readUInt32() -> UInt32 { range.location = position range.length = 4 var value: UInt32 = 0 data.getBytes(&value, range: range) position += data.length return endian == Endian.BIG_ENDIAN ? value.bigEndian : value } func readUInt64() -> UInt { range.location = position range.length = 8 var value: UInt = 0 data.getBytes(&value, range: range) position += data.length return endian == Endian.BIG_ENDIAN ? value.bigEndian : value } func readBytes(bytes: ByteArray, offset: Int = 0, var length: Int = 0) { let remain = max(0, self.length - self.position) length = length == 0 ? remain : min(length, remain) if length <= 0 { return } range.location = position range.length = length var list = [UInt8](count: range.length, repeatedValue: 0) data.getBytes(&list, range: range) position += range.length var bin = bytes.data if offset > bytes.length { var zeros = [UInt8](count: offset - bytes.length, repeatedValue: 0) bin.replaceBytesInRange(NSRange(location: bytes.length, length: zeros.count), withBytes: &zeros) } bin.replaceBytesInRange(NSRange(location: offset, length: length), withBytes: &list) } func readUTF() -> String { return readUTFBytes(Int(readInt16())) } func readUTFBytes(length: Int) -> String { range.location = position range.length = length let value = NSString(data: data.subdataWithRange(range), encoding: NSUTF8StringEncoding) as! String position += range.length return value } func readMultiByte(length: Int, encoding: CFStringEncoding) -> String { range.location = position range.length = length let charset = CFStringConvertEncodingToNSStringEncoding(encoding) let value = NSString(data: data.subdataWithRange(range), encoding: charset) as! String position += range.length return value } // MARK: class tools class func dump<T>(var target: T) -> [UInt8] { return withUnsafePointer(&target) { let bufpt = UnsafeBufferPointer(start: UnsafePointer<UInt8>($0), count: sizeof(T)) return Array(bufpt) } } class func dump<T>(pointer: UnsafePointer<T>) -> [UInt8] { let bufpt = UnsafeBufferPointer(start: UnsafePointer<UInt8>(pointer), count: sizeof(T)) return Array(bufpt) } class func hexe(bytes: ByteArray, var range: NSRange, column: Int = 4) -> String { if range.location + range.length > bytes.length { range.length = bytes.length - range.location } var list = [UInt8](count: range.length, repeatedValue: 0) bytes.data.getBytes(&list, range: range) var result = "" var data = list.map({String(format: "%02x", $0).uppercaseString}) for i in 0..<data.count { result += data[i] + " " if (i + 1) % 4 == 0 { result += " " if (i + 1) % (4 * column) == 0 { result += "\n" } } } return result } // MARK: ByteArray write func writeBoolean(var value: Bool) { range.location = position range.length = 1 data.replaceBytesInRange(range, withBytes: &value) position += range.length } func writeDouble(var value: Double) { range.location = position range.length = 8 if endian == Endian.BIG_ENDIAN { var bytes = ByteArray.dump(value) bytes = bytes.reverse() data.replaceBytesInRange(range, withBytes: &bytes) } else { data.replaceBytesInRange(range, withBytes: &value) } position += range.length } func writeFloat(var value: Float32) { range.location = position range.length = 4 if endian == Endian.BIG_ENDIAN { var bytes = ByteArray.dump(value) bytes = bytes.reverse() data.replaceBytesInRange(range, withBytes: &bytes) } else { data.replaceBytesInRange(range, withBytes: &value) } position += range.length } func writeInt8(var value: Int8) { range.location = position range.length = 1 data.replaceBytesInRange(range, withBytes: &value) position += range.length } func writeInt16(var value: Int16) { if endian == Endian.BIG_ENDIAN { value = value.bigEndian } range.location = position range.length = 2 data.replaceBytesInRange(range, withBytes: &value) position += range.length } func writeInt32(var value: Int32) { if endian == Endian.BIG_ENDIAN { value = value.bigEndian } range.location = position range.length = 4 data.replaceBytesInRange(range, withBytes: &value) position += range.length } func writeInt64(var value: Int) { if endian == Endian.BIG_ENDIAN { value = value.bigEndian } range.location = position range.length = 8 data.replaceBytesInRange(range, withBytes: &value) position += range.length } func writeUInt8(var value: UInt8) { range.location = position range.length = 1 data.replaceBytesInRange(range, withBytes: &value) position += range.length } func writeUInt16(var value: UInt16) { if endian == Endian.BIG_ENDIAN { value = value.bigEndian } range.location = position range.length = 2 data.replaceBytesInRange(range, withBytes: &value) position += range.length } func writeUInt32(var value: UInt32) { if endian == Endian.BIG_ENDIAN { value = value.bigEndian } range.location = position range.length = 4 data.replaceBytesInRange(range, withBytes: &value) position += range.length } func writeUInt64(var value: UInt) { if endian == Endian.BIG_ENDIAN { value = value.bigEndian } range.location = position range.length = 8 data.replaceBytesInRange(range, withBytes: &value) position += range.length } func writeUTF(var value: String) { var num = UInt16(count(value.utf8)) if endian == Endian.BIG_ENDIAN { num = num.bigEndian } range.location = position range.length = 2 data.replaceBytesInRange(range, withBytes: &num) position += range.length writeUTFBytes(value) } func writeUTFBytes(var value: String) { var bytes = [UInt8](value.utf8) range.location = position range.length = bytes.count data.replaceBytesInRange(range, withBytes: &bytes) position += range.length } func writeMultiBytes(var value: String, encoding: CFStringEncoding) { let chatset = CFStringConvertEncodingToNSStringEncoding(encoding) let bin = NSString(string: value).dataUsingEncoding(chatset)! var bytes = [UInt8](count: bin.length, repeatedValue: 0) bin.getBytes(&bytes, length: bytes.count) range.location = position range.length = bin.length data.replaceBytesInRange(range, withBytes: &bytes) position += range.length } func writeBytes(bytes: ByteArray, offset: Int = 0, var length: Int = 0) { let remain = max(0, bytes.length - offset) length = length == 0 ? remain : min(length, remain) if length > 0 { let bin = bytes.data.subdataWithRange(NSRange(location: offset, length: length)) var bytes = [UInt8](count: bin.length, repeatedValue: 0) bin.getBytes(&bytes, length: bytes.count) range.location = position range.length = bin.length data.replaceBytesInRange(range, withBytes: &bytes) position += range.length } } }
mit
081c835f7c04c19a798fae40ffcbd01f
25.846667
108
0.574621
4.423654
false
false
false
false
yeziahehe/Gank
Gank/ViewControllers/Category/CategoryViewController.swift
1
2561
// // CategoryViewController.swift // Gank // // Created by 叶帆 on 2016/10/27. // Copyright © 2016年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved. // import UIKit final class CategoryViewController: BaseViewController { var categoryArray: [String] = [] @IBOutlet weak var categoryCollectionView: UICollectionView! { didSet { categoryCollectionView.registerNibOf(CategoryCollectionCell.self) } } deinit { categoryCollectionView?.delegate = nil gankLog.debug("deinit CategoryViewController") } override func viewDidLoad() { super.viewDidLoad() categoryArray = GankUserDefaults.version.value! ? ["all", "iOS", "Android", "前端", "瞎推荐", "拓展资源", "App", "休息视频", "福利"] : ["all", "iOS", "前端", "瞎推荐", "拓展资源", "App", "休息视频", "福利"] // 审核,禁止 Android } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else { return } switch identifier { case "showArticle": let vc = segue.destination as! ArticleViewController let categoryString = sender as! String vc.category = categoryString default: break } } @IBAction func showSearch(_ sender: Any) { self.performSegue(withIdentifier: "showSearch", sender: nil) } } extension CategoryViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return categoryArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: CategoryCollectionCell = collectionView.dequeueReusableCell(forIndexPath: indexPath) cell.configure(categoryArray[indexPath.row]) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) if categoryArray[indexPath.row] == "福利" { self.performSegue(withIdentifier: "showMeizi", sender: nil) } else { self.performSegue(withIdentifier: "showArticle", sender: categoryArray[indexPath.row]) } } }
gpl-3.0
920b41b1927de4ac346b8807e49dadb6
32.513514
201
0.647177
5.071575
false
false
false
false
arvedviehweger/swift
stdlib/public/core/String.swift
1
29637
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // FIXME: complexity documentation for most of methods on String is ought to be // qualified with "amortized" at least, as Characters are variable-length. /// A Unicode string value. /// /// A string is a series of characters, such as `"Swift"`. Strings in Swift are /// Unicode correct, locale insensitive, and designed to be efficient. The /// `String` type bridges with the Objective-C class `NSString` and offers /// interoperability with C functions that works with strings. /// /// You can create new strings using string literals or string interpolations. /// A string literal is a series of characters enclosed in quotes. /// /// let greeting = "Welcome!" /// /// String interpolations are string literals that evaluate any included /// expressions and convert the results to string form. String interpolations /// are an easy way to build a string from multiple pieces. Wrap each /// expression in a string interpolation in parentheses, prefixed by a /// backslash. /// /// let name = "Rosa" /// let personalizedGreeting = "Welcome, \(name)!" /// /// let price = 2 /// let number = 3 /// let cookiePrice = "\(number) cookies: $\(price * number)." /// /// Combine strings using the concatenation operator (`+`). /// /// let longerGreeting = greeting + " We're glad you're here!" /// print(longerGreeting) /// // Prints "Welcome! We're glad you're here!" /// /// Modifying and Comparing Strings /// =============================== /// /// Strings always have value semantics. Modifying a copy of a string leaves /// the original unaffected. /// /// var otherGreeting = greeting /// otherGreeting += " Have a nice time!" /// print(otherGreeting) /// // Prints "Welcome! Have a nice time!" /// /// print(greeting) /// // Prints "Welcome!" /// /// Comparing strings for equality using the equal-to operator (`==`) or a /// relational operator (like `<` and `>=`) is always performed using the /// Unicode canonical representation. This means that different /// representations of a string compare as being equal. /// /// let cafe1 = "Cafe\u{301}" /// let cafe2 = "Café" /// print(cafe1 == cafe2) /// // Prints "true" /// /// The Unicode code point `"\u{301}"` modifies the preceding character to /// include an accent, so `"e\u{301}"` has the same canonical representation /// as the single Unicode code point `"é"`. /// /// Basic string operations are not sensitive to locale settings. This ensures /// that string comparisons and other operations always have a single, stable /// result, allowing strings to be used as keys in `Dictionary` instances and /// for other purposes. /// /// Representing Strings: Views /// =========================== /// /// A string is not itself a collection. Instead, it has properties that /// present its contents as meaningful collections. Each of these collections /// is a particular type of *view* of the string's visible and data /// representation. /// /// To demonstrate the different views available for every string, the /// following examples use this `String` instance: /// /// let cafe = "Cafe\u{301} du 🌍" /// print(cafe) /// // Prints "Café du 🌍" /// /// Character View /// -------------- /// /// A string's `characters` property is a collection of *extended grapheme /// clusters*, which approximate human-readable characters. Many individual /// characters, such as "é", "김", and "🇮🇳", can be made up of multiple Unicode /// code points. These code points are combined by Unicode's boundary /// algorithms into extended grapheme clusters, represented by Swift's /// `Character` type. Each element of the `characters` view is represented by /// a `Character` instance. /// /// print(cafe.characters.count) /// // Prints "9" /// print(Array(cafe.characters)) /// // Prints "["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]" /// /// Each visible character in the `cafe` string is a separate element of the /// `characters` view. /// /// Unicode Scalar View /// ------------------- /// /// A string's `unicodeScalars` property is a collection of Unicode scalar /// values, the 21-bit codes that are the basic unit of Unicode. Each scalar /// value is represented by a `UnicodeScalar` instance and is equivalent to a /// UTF-32 code unit. /// /// print(cafe.unicodeScalars.count) /// // Prints "10" /// print(Array(cafe.unicodeScalars)) /// // Prints "["C", "a", "f", "e", "\u{0301}", " ", "d", "u", " ", "\u{0001F30D}"]" /// print(cafe.unicodeScalars.map { $0.value }) /// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 127757]" /// /// The `unicodeScalars` view's elements comprise each Unicode scalar value in /// the `cafe` string. In particular, because `cafe` was declared using the /// decomposed form of the `"é"` character, `unicodeScalars` contains the code /// points for both the letter `"e"` (101) and the accent character `"´"` /// (769). /// /// UTF-16 View /// ----------- /// /// A string's `utf16` property is a collection of UTF-16 code units, the /// 16-bit encoding form of the string's Unicode scalar values. Each code unit /// is stored as a `UInt16` instance. /// /// print(cafe.utf16.count) /// // Prints "11" /// print(Array(cafe.utf16)) /// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]" /// /// The elements of the `utf16` view are the code units for the string when /// encoded in UTF-16. /// /// The elements of this collection match those accessed through indexed /// `NSString` APIs. /// /// let nscafe = cafe as NSString /// print(nscafe.length) /// // Prints "11" /// print(nscafe.character(at: 3)) /// // Prints "101" /// /// UTF-8 View /// ---------- /// /// A string's `utf8` property is a collection of UTF-8 code units, the 8-bit /// encoding form of the string's Unicode scalar values. Each code unit is /// stored as a `UInt8` instance. /// /// print(cafe.utf8.count) /// // Prints "14" /// print(Array(cafe.utf8)) /// // Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]" /// /// The elements of the `utf8` view are the code units for the string when /// encoded in UTF-8. This representation matches the one used when `String` /// instances are passed to C APIs. /// /// let cLength = strlen(cafe) /// print(cLength) /// // Prints "14" /// /// Counting the Length of a String /// =============================== /// /// When you need to know the length of a string, you must first consider what /// you'll use the length for. Are you measuring the number of characters that /// will be displayed on the screen, or are you measuring the amount of /// storage needed for the string in a particular encoding? A single string /// can have greatly differing lengths when measured by its different views. /// /// For example, an ASCII character like the capital letter *A* is represented /// by a single element in each of its four views. The Unicode scalar value of /// *A* is `65`, which is small enough to fit in a single code unit in both /// UTF-16 and UTF-8. /// /// let capitalA = "A" /// print(capitalA.characters.count) /// // Prints "1" /// print(capitalA.unicodeScalars.count) /// // Prints "1" /// print(capitalA.utf16.count) /// // Prints "1" /// print(capitalA.utf8.count) /// // Prints "1" /// /// On the other hand, an emoji flag character is constructed from a pair of /// Unicode scalars values, like `"\u{1F1F5}"` and `"\u{1F1F7}"`. Each of /// these scalar values, in turn, is too large to fit into a single UTF-16 or /// UTF-8 code unit. As a result, each view of the string `"🇵🇷"` reports a /// different length. /// /// let flag = "🇵🇷" /// print(flag.characters.count) /// // Prints "1" /// print(flag.unicodeScalars.count) /// // Prints "2" /// print(flag.utf16.count) /// // Prints "4" /// print(flag.utf8.count) /// // Prints "8" /// /// To check whether a string is empty, use its `isEmpty` property instead /// of comparing the length of one of the views to `0`. Unlike `isEmpty`, /// calculating a view's `count` property requires iterating through the /// elements of the string. /// /// Accessing String View Elements /// ============================== /// /// To find individual elements of a string, use the appropriate view for your /// task. For example, to retrieve the first word of a longer string, you can /// search the `characters` view for a space and then create a new string from /// a prefix of the `characters` view up to that point. /// /// let name = "Marie Curie" /// let firstSpace = name.characters.index(of: " ")! /// let firstName = String(name.characters.prefix(upTo: firstSpace)) /// print(firstName) /// // Prints "Marie" /// /// You can convert an index into one of a string's views to an index into /// another view. /// /// let firstSpaceUTF8 = firstSpace.samePosition(in: name.utf8) /// print(Array(name.utf8.prefix(upTo: firstSpaceUTF8))) /// // Prints "[77, 97, 114, 105, 101]" /// /// Performance Optimizations /// ========================= /// /// Although strings in Swift have value semantics, strings use a copy-on-write /// strategy to store their data in a buffer. This buffer can then be shared /// by different copies of a string. A string's data is only copied lazily, /// upon mutation, when more than one string instance is using the same /// buffer. Therefore, the first in any sequence of mutating operations may /// cost O(*n*) time and space. /// /// When a string's contiguous storage fills up, a new buffer must be allocated /// and data must be moved to the new storage. String buffers use an /// exponential growth strategy that makes appending to a string a constant /// time operation when averaged over many append operations. /// /// Bridging between String and NSString /// ==================================== /// /// Any `String` instance can be bridged to `NSString` using the type-cast /// operator (`as`), and any `String` instance that originates in Objective-C /// may use an `NSString` instance as its storage. Because any arbitrary /// subclass of `NSString` can become a `String` instance, there are no /// guarantees about representation or efficiency when a `String` instance is /// backed by `NSString` storage. Because `NSString` is immutable, it is just /// as though the storage was shared by a copy: The first in any sequence of /// mutating operations causes elements to be copied into unique, contiguous /// storage which may cost O(*n*) time and space, where *n* is the length of /// the string's encoded representation (or more, if the underlying `NSString` /// has unusual performance characteristics). /// /// For more information about the Unicode terms used in this discussion, see /// the [Unicode.org glossary][glossary]. In particular, this discussion /// mentions [extended grapheme clusters][clusters], /// [Unicode scalar values][scalars], and [canonical equivalence][equivalence]. /// /// [glossary]: http://www.unicode.org/glossary/ /// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster /// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value /// [equivalence]: http://www.unicode.org/glossary/#canonical_equivalent /// /// - SeeAlso: `String.CharacterView`, `String.UnicodeScalarView`, /// `String.UTF16View`, `String.UTF8View` @_fixed_layout public struct String { /// Creates an empty string. public init() { _core = _StringCore() } public // @testable init(_ _core: _StringCore) { self._core = _core } public // @testable var _core: _StringCore } extension String { public // @testable static func _fromWellFormedCodeUnitSequence<Encoding, Input>( _ encoding: Encoding.Type, input: Input ) -> String where Encoding: UnicodeCodec, Input: Collection, Input.Iterator.Element == Encoding.CodeUnit { return String._fromCodeUnitSequence(encoding, input: input)! } public // @testable static func _fromCodeUnitSequence<Encoding, Input>( _ encoding: Encoding.Type, input: Input ) -> String? where Encoding: UnicodeCodec, Input: Collection, Input.Iterator.Element == Encoding.CodeUnit { let (stringBufferOptional, _) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: false) return stringBufferOptional.map { String(_storage: $0) } } public // @testable static func _fromCodeUnitSequenceWithRepair<Encoding, Input>( _ encoding: Encoding.Type, input: Input ) -> (String, hadError: Bool) where Encoding: UnicodeCodec, Input: Collection, Input.Iterator.Element == Encoding.CodeUnit { let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits(input, encoding: encoding, repairIllFormedSequences: true) return (String(_storage: stringBuffer!), hadError) } } extension String : _ExpressibleByBuiltinUnicodeScalarLiteral { @effects(readonly) public // @testable init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value))) } } extension String : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral { @_inlineable @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } extension String : _ExpressibleByBuiltinUTF16StringLiteral { @_inlineable @effects(readonly) @_semantics("string.makeUTF16") public init( _builtinUTF16StringLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { self = String( _StringCore( baseAddress: UnsafeMutableRawPointer(start), count: Int(utf16CodeUnitCount), elementShift: 1, hasCocoaBuffer: false, owner: nil)) } } extension String : _ExpressibleByBuiltinStringLiteral { @_inlineable @effects(readonly) @_semantics("string.makeUTF8") public init( _builtinStringLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1) { if Bool(isASCII) { self = String( _StringCore( baseAddress: UnsafeMutableRawPointer(start), count: Int(utf8CodeUnitCount), elementShift: 0, hasCocoaBuffer: false, owner: nil)) } else { self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount))) } } } extension String : ExpressibleByStringLiteral { /// Creates an instance initialized to the given string value. /// /// Do not call this initializer directly. It is used by the compiler when you /// initialize a string using a string literal. For example: /// /// let nextStop = "Clark & Lake" /// /// This assignment to the `nextStop` constant calls this string literal /// initializer behind the scenes. public init(stringLiteral value: String) { self = value } } extension String : CustomDebugStringConvertible { /// A representation of the string that is suitable for debugging. public var debugDescription: String { var result = "\"" for us in self.unicodeScalars { result += us.escaped(asASCII: false) } result += "\"" return result } } extension String { /// Returns the number of code units occupied by this string /// in the given encoding. func _encodedLength< Encoding: UnicodeCodec >(_ encoding: Encoding.Type) -> Int { var codeUnitCount = 0 self._encode(encoding, into: { _ in codeUnitCount += 1 }) return codeUnitCount } // FIXME: this function does not handle the case when a wrapped NSString // contains unpaired surrogates. Fix this before exposing this function as a // public API. But it is unclear if it is valid to have such an NSString in // the first place. If it is not, we should not be crashing in an obscure // way -- add a test for that. // Related: <rdar://problem/17340917> Please document how NSString interacts // with unpaired surrogates func _encode< Encoding: UnicodeCodec >( _ encoding: Encoding.Type, into processCodeUnit: (Encoding.CodeUnit) -> Void ) { return _core.encode(encoding, into: processCodeUnit) } } // Support for copy-on-write extension String { /// Appends the given string to this string. /// /// The following example builds a customized greeting by using the /// `append(_:)` method: /// /// var greeting = "Hello, " /// if let name = getUserName() { /// greeting.append(name) /// } else { /// greeting.append("friend") /// } /// print(greeting) /// // Prints "Hello, friend" /// /// - Parameter other: Another string. public mutating func append(_ other: String) { _core.append(other._core) } /// Appends the given Unicode scalar to the string. /// /// - Parameter x: A Unicode scalar value. /// /// - Complexity: Appending a Unicode scalar to a string averages to O(1) /// over many additions. @available(*, unavailable, message: "Replaced by append(_: String)") public mutating func append(_ x: UnicodeScalar) { Builtin.unreachable() } public // SPI(Foundation) init(_storage: _StringBuffer) { _core = _StringCore(_storage) } } extension String { @effects(readonly) @_semantics("string.concat") public static func + (lhs: String, rhs: String) -> String { if lhs.isEmpty { return rhs } var lhs = lhs lhs._core.append(rhs._core) return lhs } // String append public static func += (lhs: inout String, rhs: String) { if lhs.isEmpty { lhs = rhs } else { lhs._core.append(rhs._core) } } /// Constructs a `String` in `resultStorage` containing the given UTF-8. /// /// Low-level construction interface used by introspection /// implementation in the runtime library. @_inlineable @_silgen_name("swift_stringFromUTF8InRawMemory") public // COMPILER_INTRINSIC static func _fromUTF8InRawMemory( _ resultStorage: UnsafeMutablePointer<String>, start: UnsafeMutablePointer<UTF8.CodeUnit>, utf8CodeUnitCount: Int ) { resultStorage.initialize(to: String._fromWellFormedCodeUnitSequence( UTF8.self, input: UnsafeBufferPointer(start: start, count: utf8CodeUnitCount))) } } extension Sequence where Iterator.Element == String { /// Returns a new string by concatenating the elements of the sequence, /// adding the given separator between each element. /// /// The following example shows how an array of strings can be joined to a /// single, comma-separated string: /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let list = cast.joined(separator: ", ") /// print(list) /// // Prints "Vivien, Marlon, Kim, Karl" /// /// - Parameter separator: A string to insert between each of the elements /// in this sequence. The default separator is an empty string. /// - Returns: A single, concatenated string. public func joined(separator: String = "") -> String { var result = "" // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. let separatorSize = separator.utf16.count let reservation = self._preprocessingPass { () -> Int in var r = 0 for chunk in self { // FIXME(performance): this code assumes UTF-16 in-memory representation. // It should be switched to low-level APIs. r += separatorSize + chunk.utf16.count } return r - separatorSize } if let n = reservation { result.reserveCapacity(n) } if separatorSize == 0 { for x in self { result.append(x) } return result } var iter = makeIterator() if let first = iter.next() { result.append(first) while let next = iter.next() { result.append(separator) result.append(next) } } return result } } #if _runtime(_ObjC) @_silgen_name("swift_stdlib_NSStringLowercaseString") func _stdlib_NSStringLowercaseString(_ str: AnyObject) -> _CocoaString @_silgen_name("swift_stdlib_NSStringUppercaseString") func _stdlib_NSStringUppercaseString(_ str: AnyObject) -> _CocoaString #else internal func _nativeUnicodeLowercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Allocation of a StringBuffer requires binding the memory to the correct // encoding type. let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) // Try to write it out to the same length. let z = _swift_stdlib_unicode_strToLower( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) _swift_stdlib_unicode_strToLower( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } internal func _nativeUnicodeUppercaseString(_ str: String) -> String { var buffer = _StringBuffer( capacity: str._core.count, initialSize: str._core.count, elementWidth: 2) // Allocation of a StringBuffer requires binding the memory to the correct // encoding type. let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) // Try to write it out to the same length. let z = _swift_stdlib_unicode_strToUpper( dest, Int32(str._core.count), str._core.startUTF16, Int32(str._core.count)) let correctSize = Int(z) // If more space is needed, do it again with the correct buffer size. if correctSize != str._core.count { buffer = _StringBuffer( capacity: correctSize, initialSize: correctSize, elementWidth: 2) let dest = buffer.start.bindMemory( to: UTF16.CodeUnit.self, capacity: str._core.count) _swift_stdlib_unicode_strToUpper( dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count)) } return String(_storage: buffer) } #endif // Unicode algorithms extension String { // FIXME: implement case folding without relying on Foundation. // <rdar://problem/17550602> [unicode] Implement case folding /// A "table" for which ASCII characters need to be upper cased. /// To determine which bit corresponds to which ASCII character, subtract 1 /// from the ASCII value of that character and divide by 2. The bit is set iff /// that character is a lower case character. internal var _asciiLowerCaseTable: UInt64 { @inline(__always) get { return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000 } } /// The same table for upper case characters. internal var _asciiUpperCaseTable: UInt64 { @inline(__always) get { return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000 } } /// Returns a lowercase version of the string. /// /// Here's an example of transforming a string to all lowercase letters. /// /// let cafe = "Café 🍵" /// print(cafe.lowercased()) /// // Prints "café 🍵" /// /// - Returns: A lowercase copy of the string. /// /// - Complexity: O(*n*) public func lowercased() -> String { if let asciiBuffer = self._core.asciiBuffer { let count = asciiBuffer.count let source = asciiBuffer.baseAddress! let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = buffer.start for i in 0..<count { // For each character in the string, we lookup if it should be shifted // in our ascii table, then we return 0x20 if it should, 0x0 if not. // This code is equivalent to: // switch source[i] { // case let x where (x >= 0x41 && x <= 0x5a): // dest[i] = x &+ 0x20 // case let x: // dest[i] = x // } let value = source[i] let isUpper = _asciiUpperCaseTable &>> UInt64(((value &- 1) & 0b0111_1111) &>> 1) let add = (isUpper & 0x1) &<< 5 // Since we are left with either 0x0 or 0x20, we can safely truncate to // a UInt8 and add to our ASCII value (this will not overflow numbers in // the ASCII range). dest.storeBytes(of: value &+ UInt8(extendingOrTruncating: add), toByteOffset: i, as: UInt8.self) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeLowercaseString(self) #endif } /// Returns an uppercase version of the string. /// /// The following example transforms a string to uppercase letters: /// /// let cafe = "Café 🍵" /// print(cafe.uppercased()) /// // Prints "CAFÉ 🍵" /// /// - Returns: An uppercase copy of the string. /// /// - Complexity: O(*n*) public func uppercased() -> String { if let asciiBuffer = self._core.asciiBuffer { let count = asciiBuffer.count let source = asciiBuffer.baseAddress! let buffer = _StringBuffer( capacity: count, initialSize: count, elementWidth: 1) let dest = buffer.start for i in 0..<count { // See the comment above in lowercaseString. let value = source[i] let isLower = _asciiLowerCaseTable &>> UInt64(((value &- 1) & 0b0111_1111) &>> 1) let add = (isLower & 0x1) &<< 5 dest.storeBytes(of: value &- UInt8(extendingOrTruncating: add), toByteOffset: i, as: UInt8.self) } return String(_storage: buffer) } #if _runtime(_ObjC) return _cocoaStringToSwiftString_NonASCII( _stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl())) #else return _nativeUnicodeUppercaseString(self) #endif } /// Creates an instance from the description of a given /// `LosslessStringConvertible` instance. public init<T : LosslessStringConvertible>(_ value: T) { self = value.description } } extension String : CustomStringConvertible { public var description: String { return self } } extension String : LosslessStringConvertible { public init?(_ description: String) { self = description } } extension String { @available(*, unavailable, renamed: "append(_:)") public mutating func appendContentsOf(_ other: String) { Builtin.unreachable() } @available(*, unavailable, renamed: "append(contentsOf:)") public mutating func appendContentsOf<S : Sequence>(_ newElements: S) where S.Iterator.Element == Character { Builtin.unreachable() } @available(*, unavailable, renamed: "insert(contentsOf:at:)") public mutating func insertContentsOf<S : Collection>( _ newElements: S, at i: Index ) where S.Iterator.Element == Character { Builtin.unreachable() } @available(*, unavailable, renamed: "replaceSubrange") public mutating func replaceRange<C : Collection>( _ subRange: Range<Index>, with newElements: C ) where C.Iterator.Element == Character { Builtin.unreachable() } @available(*, unavailable, renamed: "replaceSubrange") public mutating func replaceRange( _ subRange: Range<Index>, with newElements: String ) { Builtin.unreachable() } @available(*, unavailable, renamed: "remove(at:)") public mutating func removeAtIndex(_ i: Index) -> Character { Builtin.unreachable() } @available(*, unavailable, renamed: "removeSubrange") public mutating func removeRange(_ subRange: Range<Index>) { Builtin.unreachable() } @available(*, unavailable, renamed: "lowercased()") public var lowercaseString: String { Builtin.unreachable() } @available(*, unavailable, renamed: "uppercased()") public var uppercaseString: String { Builtin.unreachable() } @available(*, unavailable, renamed: "init(describing:)") public init<T>(_: T) { Builtin.unreachable() } } extension Sequence where Iterator.Element == String { @available(*, unavailable, renamed: "joined(separator:)") public func joinWithSeparator(_ separator: String) -> String { Builtin.unreachable() } }
apache-2.0
ad6e945a82849af8565782b8963e596f
33.005747
94
0.655974
4.137184
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Views/ImageOverlayView.swift
1
1886
// // ImageOverlayView.swift // Habitica // // Created by Phillip Thelen on 13.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation class ImageOverlayView: HabiticaAlertController { private var imageView = NetworkImageView() private var imageHeightConstraint: NSLayoutConstraint? var imageName: String? { didSet { if let imageName = imageName { imageView.setImagewith(name: imageName) } } } var imageHeight: CGFloat? { get { return imageHeightConstraint?.constant } set { imageHeightConstraint?.constant = newValue ?? 0 } } init(imageName: String, title: String?, message: String?) { super.init() self.title = title self.message = message self.imageName = imageName setupImageView() imageView.setImagewith(name: imageName) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupImageView() } private func setupImageView() { contentView = imageView imageView.contentMode = .center imageHeightConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100) if let constraint = imageHeightConstraint { imageView.addConstraint(constraint) } } }
gpl-3.0
1c3f735014ac298b5f4d35a9ee904704
29.901639
106
0.531034
6.304348
false
false
false
false
garyshirk/ThriftStoreLocator1
ThriftStoreLocator/NetworkLayer.swift
1
16820
// // NetworkLayer.swift // ThriftStoreLocator // // Created by Gary Shirk on 2/28/17. // Copyright © 2017 Gary Shirk. All rights reserved. // import Foundation import Alamofire import SwiftyJSON import FirebaseDatabase private let firebaseThriftStoreBaseURL = "https://thrift-store-locator.firebaseio.com/thriftstores/<QUERY>.json?auth=Llvl7BLMTOMPVWjtMCtj8QM9vX9A1UVuHOyvFu56" private let firebaseFavoritesBaseURL = "https://thrift-store-locator.firebaseio.com/favorites/<QUERY>.json?auth=Llvl7BLMTOMPVWjtMCtj8QM9vX9A1UVuHOyvFu56" private let locationInfoBaseURL = "http://maps.googleapis.com/maps/api/geocode/json?address=<location>&sensor=false" class NetworkLayer { var dbFavoritesRef: DatabaseReference? var rootRef = Database.database().reference() var favoritesArrayOfDicts = [[String: Any]]() var storesArrayOfDicts = [[String: Any]]() var atLeastOneFoundFavSuccessfullyLoaded: Bool? func removeFavorite(store: Store, forUser user: String, networkLayerRemoveFavUpdater: @escaping (ErrorType) -> Void) { var errorType: ErrorType = .none dbFavoritesRef = Database.database().reference(withPath: "favorites") let userRef = dbFavoritesRef!.child(user) if let stateStr = store.state { let stateRef = userRef.child(stateStr) if let countyStr = store.county { let countyRef = stateRef.child(countyStr.lowercased()) let storeIdStr = (store.storeId?.stringValue)! let storeIdRef = countyRef.child(storeIdStr) storeIdRef.removeValue() { (error, ref) -> Void in if error != nil { errorType = .serverFavDelete(error!.localizedDescription) } networkLayerRemoveFavUpdater(errorType) } } else { errorType = .serverFavDelete(DebugErrorMessage.firebaseDbAccessError) networkLayerRemoveFavUpdater(errorType) } } else { errorType = .serverFavDelete(DebugErrorMessage.firebaseDbAccessError) networkLayerRemoveFavUpdater(errorType) } } func postFavorite(store: Store, forUser user: String, networkLayerPostFavUpdater: @escaping (ErrorType) -> Void) { var errorType: ErrorType = .none dbFavoritesRef = Database.database().reference(withPath: "favorites") // Set json user uid key let userRef = dbFavoritesRef!.child(user) // Set state key if let storeState = store.state { let storeStateRef = userRef.child(storeState) // Set county key if let storeCounty = store.county { let storeCountyStr = storeCounty.lowercased() let storeCountyRef = storeStateRef.child(storeCountyStr) // Set store id key if let storeId = store.storeId { let storeIdRef = storeCountyRef.child(storeId.stringValue) storeIdRef.setValue(storeId) { (error, ref) -> Void in if error != nil { errorType = .serverFavPost(error!.localizedDescription) } // DEBUG networkLayerPostFavUpdater(.none) //networkLayerPostFavUpdater(.serverFavPost("test fav post error")) } } else { errorType = .serverFavPost(DebugErrorMessage.firebaseDbAccessError) networkLayerPostFavUpdater(errorType) } } else { errorType = .serverFavPost(DebugErrorMessage.firebaseDbAccessError) networkLayerPostFavUpdater(errorType) } } else { errorType = .serverFavPost(DebugErrorMessage.firebaseDbAccessError) networkLayerPostFavUpdater(errorType) } } func loadFavoritesFromServer(forUser user: String, networkLayerLoadFavoritesUpdater: @escaping ([[String: Any]], ErrorType) -> Void) { dbFavoritesRef = Database.database().reference(withPath: "favorites") self.favoritesArrayOfDicts.removeAll() let urlString = firebaseFavoritesBaseURL.replacingOccurrences(of: "<QUERY>", with: user) var errorType: ErrorType = .none // First: Do a rest GET to get storeId references to all user favorites Alamofire.request(urlString, method: .get).validate() .responseJSON(completionHandler: { [weak self] response in guard let strongSelf = self else { return } switch response.result { case .success(let value): let json = JSON(value) for (state, subJson):(String, JSON) in json { for (county, subSubJson):(String, JSON) in subJson { for (storeId, _):(String, JSON) in subSubJson { var itemDict = [String: String]() itemDict["state"] = state itemDict["county"] = county itemDict["storeId"] = storeId strongSelf.favoritesArrayOfDicts.append(itemDict as [String: Any]) } } } // Next: Use firebase event observer to load favorite stores based on references above and pass back to model manager strongSelf.storesArrayOfDicts.removeAll() let dbStoresRef = Database.database().reference(withPath: "thriftstores") var favoritesCount = strongSelf.favoritesArrayOfDicts.count if favoritesCount <= 0 { // No favorites, return networkLayerLoadFavoritesUpdater(strongSelf.storesArrayOfDicts, ErrorType.none) return } else { strongSelf.atLeastOneFoundFavSuccessfullyLoaded = false } for favorite in strongSelf.favoritesArrayOfDicts { if let state = favorite["state"] { let stateRef = dbStoresRef.child(state as! String) if let county = favorite["county"] { let countyStr = (county as! String).lowercased() let countyRef = stateRef.child(countyStr) if let storeId = favorite["storeId"] { let storeIdRef = countyRef.child(storeId as! String) storeIdRef.observeSingleEvent(of: .value, with: { (snapshot) in if let value = snapshot.value as? NSDictionary { var itemDict = [String: String]() itemDict["name"] = value["bizName"] as? String itemDict["storeId"] = String(describing: value["bizID"] as! Int64) itemDict["categoryMain"] = value["bizCat"] as? String itemDict["categorySub"] = value["bizCatSub"] as? String itemDict["address"] = value["bizAddr"] as? String itemDict["city"] = value["bizCity"] as? String itemDict["state"] = value["bizState"] as? String itemDict["zip"] = value["bizZip"] as? String itemDict["phone"] = value["bizPhone"] as? String itemDict["email"] = value["bizEmail"] as? String itemDict["website"] = value["bizURL"] as? String itemDict["locLat"] = String(describing: value["locLat"] as! Double) itemDict["locLong"] = String(describing: value["locLong"] as! Double) itemDict["county"] = value["locCounty"] as? String strongSelf.storesArrayOfDicts.append(itemDict as [String: Any]) favoritesCount -= 1 strongSelf.atLeastOneFoundFavSuccessfullyLoaded = true if favoritesCount <= 0 { networkLayerLoadFavoritesUpdater(strongSelf.storesArrayOfDicts, ErrorType.none) strongSelf.storesArrayOfDicts.removeAll() strongSelf.favoritesArrayOfDicts.removeAll() } } }) { (error) in errorType = ErrorType.serverError(error.localizedDescription) networkLayerLoadFavoritesUpdater(strongSelf.storesArrayOfDicts, errorType) } } } } } if strongSelf.atLeastOneFoundFavSuccessfullyLoaded == false { networkLayerLoadFavoritesUpdater(strongSelf.storesArrayOfDicts, ErrorType.none) } case .failure(let error): errorType = ErrorType.serverError(error.localizedDescription) networkLayerLoadFavoritesUpdater(strongSelf.storesArrayOfDicts, errorType) } }) } func loadStoresFromServer(forQuery query: String, networkLayerStoreUpdater: @escaping ([[String: Any]], ErrorType) -> Void) { self.storesArrayOfDicts.removeAll() var isLoadingByState = false if query.range(of: "/") == nil { isLoadingByState = true } let urlString = firebaseThriftStoreBaseURL.replacingOccurrences(of: "<QUERY>", with: query) // Load stores by county if isLoadingByState == false { var errorType: ErrorType = .none Alamofire.request(urlString, method: .get).validate() .responseJSON(completionHandler: { [weak self] response in guard let strongSelf = self else { return } switch response.result { case .success(let value): let json = JSON(value) for (_, subJson):(String, JSON) in json { var itemDict = [String: String]() itemDict["name"] = subJson["bizName"].stringValue itemDict["storeId"] = subJson["bizID"].stringValue itemDict["categoryMain"] = subJson["bizCat"].stringValue itemDict["categorySub"] = subJson["bizCatSub"].stringValue itemDict["address"] = subJson["bizAddr"].stringValue itemDict["city"] = subJson["bizCity"].stringValue itemDict["state"] = subJson["bizState"].stringValue itemDict["zip"] = subJson["bizZip"].stringValue itemDict["phone"] = subJson["bizPhone"].stringValue itemDict["email"] = subJson["bizEmail"].stringValue itemDict["website"] = subJson["bizURL"].stringValue itemDict["locLat"] = subJson["locLat"].stringValue itemDict["locLong"] = subJson["locLong"].stringValue itemDict["county"] = subJson["locCounty"].stringValue strongSelf.storesArrayOfDicts.append(itemDict as [String: Any]) } networkLayerStoreUpdater(strongSelf.storesArrayOfDicts, ErrorType.none) strongSelf.storesArrayOfDicts.removeAll() case .failure(let error): errorType = ErrorType.serverError(error.localizedDescription) networkLayerStoreUpdater(strongSelf.storesArrayOfDicts, errorType) } }) } else { // Load stores by state var errorType: ErrorType = .none Alamofire.request(urlString, method: .get).validate() .responseJSON(completionHandler: { [weak self] response in guard let strongSelf = self else { return } switch response.result { case .success(let value): let json = JSON(value) for (_, countyJson):(String, JSON) in json { for (_, storeJson):(String, JSON) in countyJson { var itemDict = [String: String]() itemDict["name"] = storeJson["bizName"].stringValue itemDict["storeId"] = storeJson["bizID"].stringValue itemDict["categoryMain"] = storeJson["bizCat"].stringValue itemDict["categorySub"] = storeJson["bizCatSub"].stringValue itemDict["address"] = storeJson["bizAddr"].stringValue itemDict["city"] = storeJson["bizCity"].stringValue itemDict["state"] = storeJson["bizState"].stringValue itemDict["zip"] = storeJson["bizZip"].stringValue itemDict["phone"] = storeJson["bizPhone"].stringValue itemDict["email"] = storeJson["bizEmail"].stringValue itemDict["website"] = storeJson["bizURL"].stringValue itemDict["locLat"] = storeJson["locLat"].stringValue itemDict["locLong"] = storeJson["locLong"].stringValue itemDict["county"] = storeJson["locCounty"].stringValue strongSelf.storesArrayOfDicts.append(itemDict as [String: Any]) } } networkLayerStoreUpdater(strongSelf.storesArrayOfDicts, ErrorType.none) strongSelf.storesArrayOfDicts.removeAll() case .failure(let error): errorType = ErrorType.serverError(error.localizedDescription) networkLayerStoreUpdater(strongSelf.storesArrayOfDicts, errorType) } }) } } }
mit
02eff3fedfe4f5efe1a7ce1515db5bbd
49.966667
158
0.463404
6.999168
false
false
false
false
gvsucis/mobile-app-dev-book
iOS/ch13/TraxyApp/TraxyApp/TraxyLoginTextField.swift
8
832
// // TraxyLoginTextField.swift // TraxyApp // // Created by Jonathan Engelsma on 2/21/17. // Copyright © 2017 Jonathan Engelsma. All rights reserved. // import UIKit class TraxyLoginTextField: UITextField { override func awakeFromNib() { self.tintColor = THEME_COLOR3 self.layer.borderWidth = 1.0 self.layer.borderColor = THEME_COLOR3.cgColor self.layer.cornerRadius = 5.0 self.textColor = THEME_COLOR3 self.backgroundColor = UIColor.clear self.borderStyle = .roundedRect guard let ph = self.placeholder else { return } self.attributedPlaceholder = NSAttributedString(string: ph, attributes: [NSAttributedString.Key.foregroundColor : THEME_COLOR3]) } }
gpl-3.0
05e381b200556ee68326595751f6fc01
24.181818
96
0.614922
4.616667
false
false
false
false
dpfannenstiel/RoshamSpock
RoshamSpock/RoshamSpock/MultipeerController.swift
1
4397
// // MultipeerController.swift // RoshamSpock // // Created by Dustin Pfannenstiel on 11/19/14. // Copyright (c) 2014 Dustin Pfannenstiel. All rights reserved. // import UIKit import MultipeerConnectivity let ServiceId = "roshambo-srv" enum MessageType: String { case RequestConnection = "RequestConnection" case EndConnection = "EndConnection" case UserSelection = "UserSelection" case Results = "Results" } class MultipeerController: NSObject, MCNearbyServiceAdvertiserDelegate, MCSessionDelegate, MCNearbyServiceBrowserDelegate, UITableViewDataSource { var me: MCPeerID? var advertiser: MCNearbyServiceAdvertiser? var opponent: MCPeerID? var availablePeers: NSMutableArray var session: MCSession? var browser: MCNearbyServiceBrowser? override init() { self.availablePeers = NSMutableArray() super.init() } func beginSharingPeer(displayName: NSString) { self.me = MCPeerID(displayName: displayName) self.advertiser = MCNearbyServiceAdvertiser(peer: self.me, discoveryInfo: nil, serviceType: ServiceId) self.browser = MCNearbyServiceBrowser(peer: me, serviceType: ServiceId) self.session = MCSession(peer: me) self.session?.delegate = self self.advertiser?.delegate = self self.browser?.delegate = self self.advertiser?.startAdvertisingPeer() self.browser?.startBrowsingForPeers() } func endSharing() { browser?.stopBrowsingForPeers() advertiser?.stopAdvertisingPeer() advertiser?.delegate = nil session?.delegate = nil browser?.delegate = nil self.browser = nil self.session = nil self.advertiser = nil self.me = nil } func processMessage(_ :NSDictionary, communicationType:NSString) { } // MARK: - MCNearbyServiceAdvertiserDelegate func advertiser(advertiser: MCNearbyServiceAdvertiser!, didNotStartAdvertisingPeer error: NSError!) { } func advertiser(advertiser: MCNearbyServiceAdvertiser!, didReceiveInvitationFromPeer peerID: MCPeerID!, withContext context: NSData!, invitationHandler: ((Bool, MCSession!) -> Void)!) { } // MARK: - MCSessionDelegate func session(session: MCSession!, didFinishReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, atURL localURL: NSURL!, withError error: NSError!) { } func session(session: MCSession!, didReceiveCertificate certificate: [AnyObject]!, fromPeer peerID: MCPeerID!, certificateHandler: ((Bool) -> Void)!) { } func session(session: MCSession!, didReceiveData data: NSData!, fromPeer peerID: MCPeerID!) { let dictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary if let communicationString = dictionary["communicationType"] as? NSString { self.processMessage(dictionary, communicationType: communicationString as NSString) } } func session(session: MCSession!, didReceiveStream stream: NSInputStream!, withName streamName: String!, fromPeer peerID: MCPeerID!) { } func session(session: MCSession!, didStartReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, withProgress progress: NSProgress!) { } func session(session: MCSession!, peer peerID: MCPeerID!, didChangeState state: MCSessionState) { } // MARK: - MCNearbyServiceBrowserDelegate func browser(browser: MCNearbyServiceBrowser!, didNotStartBrowsingForPeers error: NSError!) { } func browser(browser: MCNearbyServiceBrowser!, foundPeer peerID: MCPeerID!, withDiscoveryInfo info: [NSObject : AnyObject]!) { if availablePeers.containsObject(peerID) == false { availablePeers.addObject(peerID) } } func browser(browser: MCNearbyServiceBrowser!, lostPeer peerID: MCPeerID!) { if availablePeers.containsObject(peerID) == false { availablePeers.removeObject(peerID) } } // MARK: - UITableViewDataSource func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(PeerSelectionTableViewCellReuseId, forIndexPath: indexPath) as UITableViewCell let peer = availablePeers.objectAtIndex(indexPath.row) as MCPeerID cell.textLabel.text = peer.displayName return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return availablePeers.count } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } }
mit
59ab37541537280df363e6bc89114450
27.367742
186
0.759154
4.628421
false
false
false
false
boqian2000/swift-algorithm-club
DiningPhilosophers/Sources/main.swift
1
2675
// // Swift Dining philosophers problem Algorithm // https://en.wikipedia.org/wiki/Dining_philosophers_problem // // Created by Jacopo Mangiavacchi on 11/02/16. // // import Foundation import Dispatch let numberOfPhilosophers = 4 struct ForkPair { static let forksSemaphore:[DispatchSemaphore] = Array(repeating: DispatchSemaphore(value: 1), count: numberOfPhilosophers) let leftFork: DispatchSemaphore let rightFork: DispatchSemaphore init(leftIndex: Int, rightIndex: Int) { //Order forks by index to prevent deadlock if leftIndex > rightIndex { leftFork = ForkPair.forksSemaphore[leftIndex] rightFork = ForkPair.forksSemaphore[rightIndex] } else { leftFork = ForkPair.forksSemaphore[rightIndex] rightFork = ForkPair.forksSemaphore[leftIndex] } } func pickUp() { //Acquire by starting with the lower index leftFork.wait() rightFork.wait() } func putDown() { //The order does not matter here leftFork.signal() rightFork.signal() } } struct Philosophers { let forkPair: ForkPair let philosopherIndex: Int var leftIndex = -1 var rightIndex = -1 init(philosopherIndex: Int) { leftIndex = philosopherIndex rightIndex = philosopherIndex - 1 if rightIndex < 0 { rightIndex += numberOfPhilosophers } self.forkPair = ForkPair(leftIndex: leftIndex, rightIndex: rightIndex) self.philosopherIndex = philosopherIndex print("Philosopher: \(philosopherIndex) left: \(leftIndex) right: \(rightIndex)") } func run() { while true { print("Acquiring lock for Philosofer: \(philosopherIndex) Left:\(leftIndex) Right:\(rightIndex)") forkPair.pickUp() print("Start Eating Philosopher: \(philosopherIndex)") //sleep(1000) print("Releasing lock for Philosofer: \(philosopherIndex) Left:\(leftIndex) Right:\(rightIndex)") forkPair.putDown() } } } // Layout of the table (P = philosopher, f = fork) for 4 Philosopher // P0 // f3 f0 // P3 P1 // f2 f1 // P2 let globalSem = DispatchSemaphore(value: 0) for i in 0..<numberOfPhilosophers { DispatchQueue.global(qos: .background).async { let p = Philosophers(philosopherIndex: i) p.run() } } //start the thread signaling the semaphore for i in 0..<numberOfPhilosophers { ForkPair.forksSemaphore[i].signal() } //wait forever globalSem.wait()
mit
6e0425f94faf383652e1aa3f3d25f5ec
24
126
0.617196
4.57265
false
false
false
false
DarrenKong/firefox-ios
ThirdParty/SQLite.swift/Sources/SQLite/Typed/Query.swift
2
36358
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public protocol QueryType : Expressible { var clauses: QueryClauses { get set } init(_ name: String, database: String?) } public protocol SchemaType : QueryType { static var identifier: String { get } } extension SchemaType { /// Builds a copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let email = Expression<String>("email") /// /// users.select(id, email) /// // SELECT "id", "email" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select(_ column1: Expressible, _ more: Expressible...) -> Self { return select(false, [column1] + more) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: email) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter columns: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct column1: Expressible, _ more: Expressible...) -> Self { return select(true, [column1] + more) } /// Builds a copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let email = Expression<String>("email") /// /// users.select([id, email]) /// // SELECT "id", "email" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select(_ all: [Expressible]) -> Self { return select(false, all) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: [email]) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter columns: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct columns: [Expressible]) -> Self { return select(true, columns) } /// Builds a copy of the query with the `SELECT *` clause applied. /// /// let users = Table("users") /// /// users.select(*) /// // SELECT * FROM "users" /// /// - Parameter star: A star literal. /// /// - Returns: A query with the given `SELECT *` clause applied. public func select(_ star: Star) -> Self { return select([star(nil, nil)]) } /// Builds a copy of the query with the `SELECT DISTINCT *` clause applied. /// /// let users = Table("users") /// /// users.select(distinct: *) /// // SELECT DISTINCT * FROM "users" /// /// - Parameter star: A star literal. /// /// - Returns: A query with the given `SELECT DISTINCT *` clause applied. public func select(distinct star: Star) -> Self { return select(distinct: [star(nil, nil)]) } /// Builds a scalar copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// /// users.select(id) /// // SELECT "id" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select<V : Value>(_ column: Expression<V>) -> ScalarQuery<V> { return select(false, [column]) } public func select<V : Value>(_ column: Expression<V?>) -> ScalarQuery<V?> { return select(false, [column]) } /// Builds a scalar copy of the query with the `SELECT DISTINCT` clause /// applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: email) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter column: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select<V : Value>(distinct column: Expression<V>) -> ScalarQuery<V> { return select(true, [column]) } public func select<V : Value>(distinct column: Expression<V?>) -> ScalarQuery<V?> { return select(true, [column]) } public var count: ScalarQuery<Int> { return select(Expression.count(*)) } } extension QueryType { fileprivate func select<Q : QueryType>(_ distinct: Bool, _ columns: [Expressible]) -> Q { var query = Q.init(clauses.from.name, database: clauses.from.database) query.clauses = clauses query.clauses.select = (distinct, columns) return query } // MARK: JOIN /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64>("user_id") /// /// users.join(posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ table: QueryType, on condition: Expression<Bool>) -> Self { return join(table, on: Expression<Bool?>(condition)) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64?>("user_id") /// /// users.join(posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ table: QueryType, on condition: Expression<Bool?>) -> Self { return join(.inner, table, on: condition) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64>("user_id") /// /// users.join(.LeftOuter, posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - type: The `JOIN` operator. /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool>) -> Self { return join(type, table, on: Expression<Bool?>(condition)) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64?>("user_id") /// /// users.join(.LeftOuter, posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - type: The `JOIN` operator. /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(_ type: JoinType, _ table: QueryType, on condition: Expression<Bool?>) -> Self { var query = self query.clauses.join.append((type: type, query: table, condition: table.clauses.filters.map { condition && $0 } ?? condition as Expressible)) return query } // MARK: WHERE /// Adds a condition to the query’s `WHERE` clause. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// /// users.filter(id == 1) /// // SELECT * FROM "users" WHERE ("id" = 1) /// /// - Parameter condition: A boolean expression to filter on. /// /// - Returns: A query with the given `WHERE` clause applied. public func filter(_ predicate: Expression<Bool>) -> Self { return filter(Expression<Bool?>(predicate)) } /// Adds a condition to the query’s `WHERE` clause. /// /// let users = Table("users") /// let age = Expression<Int?>("age") /// /// users.filter(age >= 35) /// // SELECT * FROM "users" WHERE ("age" >= 35) /// /// - Parameter condition: A boolean expression to filter on. /// /// - Returns: A query with the given `WHERE` clause applied. public func filter(_ predicate: Expression<Bool?>) -> Self { var query = self query.clauses.filters = query.clauses.filters.map { $0 && predicate } ?? predicate return query } /// Adds a condition to the query’s `WHERE` clause. /// This is an alias for `filter(predicate)` public func `where`(_ predicate: Expression<Bool>) -> Self { return `where`(Expression<Bool?>(predicate)) } /// Adds a condition to the query’s `WHERE` clause. /// This is an alias for `filter(predicate)` public func `where`(_ predicate: Expression<Bool?>) -> Self { return filter(predicate) } // MARK: GROUP BY /// Sets a `GROUP BY` clause on the query. /// /// - Parameter by: A list of columns to group by. /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(_ by: Expressible...) -> Self { return group(by) } /// Sets a `GROUP BY` clause on the query. /// /// - Parameter by: A list of columns to group by. /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(_ by: [Expressible]) -> Self { return group(by, nil) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A column to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: Expressible, having: Expression<Bool>) -> Self { return group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A column to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: Expressible, having: Expression<Bool?>) -> Self { return group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A list of columns to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: [Expressible], having: Expression<Bool>) -> Self { return group(by, Expression<Bool?>(having)) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A list of columns to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(_ by: [Expressible], having: Expression<Bool?>) -> Self { return group(by, having) } fileprivate func group(_ by: [Expressible], _ having: Expression<Bool?>?) -> Self { var query = self query.clauses.group = (by, having) return query } // MARK: ORDER BY /// Sets an `ORDER BY` clause on the query. /// /// let users = Table("users") /// let email = Expression<String>("email") /// let name = Expression<String?>("name") /// /// users.order(email.desc, name.asc) /// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC /// /// - Parameter by: An ordered list of columns and directions to sort by. /// /// - Returns: A query with the given `ORDER BY` clause applied. public func order(_ by: Expressible...) -> Self { return order(by) } /// Sets an `ORDER BY` clause on the query. /// /// let users = Table("users") /// let email = Expression<String>("email") /// let name = Expression<String?>("name") /// /// users.order([email.desc, name.asc]) /// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC /// /// - Parameter by: An ordered list of columns and directions to sort by. /// /// - Returns: A query with the given `ORDER BY` clause applied. public func order(_ by: [Expressible]) -> Self { var query = self query.clauses.order = by return query } // MARK: LIMIT/OFFSET /// Sets the LIMIT clause (and resets any OFFSET clause) on the query. /// /// let users = Table("users") /// /// users.limit(20) /// // SELECT * FROM "users" LIMIT 20 /// /// - Parameter length: The maximum number of rows to return (or `nil` to /// return unlimited rows). /// /// - Returns: A query with the given LIMIT clause applied. public func limit(_ length: Int?) -> Self { return limit(length, nil) } /// Sets LIMIT and OFFSET clauses on the query. /// /// let users = Table("users") /// /// users.limit(20, offset: 20) /// // SELECT * FROM "users" LIMIT 20 OFFSET 20 /// /// - Parameters: /// /// - length: The maximum number of rows to return. /// /// - offset: The number of rows to skip. /// /// - Returns: A query with the given LIMIT and OFFSET clauses applied. public func limit(_ length: Int, offset: Int) -> Self { return limit(length, offset) } // prevents limit(nil, offset: 5) fileprivate func limit(_ length: Int?, _ offset: Int?) -> Self { var query = self query.clauses.limit = length.map { ($0, offset) } return query } // MARK: - Clauses // // MARK: SELECT // MARK: - fileprivate var selectClause: Expressible { return " ".join([ Expression<Void>(literal: clauses.select.distinct ? "SELECT DISTINCT" : "SELECT"), ", ".join(clauses.select.columns), Expression<Void>(literal: "FROM"), tableName(alias: true) ]) } fileprivate var joinClause: Expressible? { guard !clauses.join.isEmpty else { return nil } return " ".join(clauses.join.map { type, query, condition in " ".join([ Expression<Void>(literal: "\(type.rawValue) JOIN"), query.tableName(alias: true), Expression<Void>(literal: "ON"), condition ]) }) } fileprivate var whereClause: Expressible? { guard let filters = clauses.filters else { return nil } return " ".join([ Expression<Void>(literal: "WHERE"), filters ]) } fileprivate var groupByClause: Expressible? { guard let group = clauses.group else { return nil } let groupByClause = " ".join([ Expression<Void>(literal: "GROUP BY"), ", ".join(group.by) ]) guard let having = group.having else { return groupByClause } return " ".join([ groupByClause, " ".join([ Expression<Void>(literal: "HAVING"), having ]) ]) } fileprivate var orderClause: Expressible? { guard !clauses.order.isEmpty else { return nil } return " ".join([ Expression<Void>(literal: "ORDER BY"), ", ".join(clauses.order) ]) } fileprivate var limitOffsetClause: Expressible? { guard let limit = clauses.limit else { return nil } let limitClause = Expression<Void>(literal: "LIMIT \(limit.length)") guard let offset = limit.offset else { return limitClause } return " ".join([ limitClause, Expression<Void>(literal: "OFFSET \(offset)") ]) } // MARK: - public func alias(_ aliasName: String) -> Self { var query = self query.clauses.from = (clauses.from.name, aliasName, clauses.from.database) return query } // MARK: - Operations // // MARK: INSERT public func insert(_ value: Setter, _ more: Setter...) -> Insert { return insert([value] + more) } public func insert(_ values: [Setter]) -> Insert { return insert(nil, values) } public func insert(or onConflict: OnConflict, _ values: Setter...) -> Insert { return insert(or: onConflict, values) } public func insert(or onConflict: OnConflict, _ values: [Setter]) -> Insert { return insert(onConflict, values) } fileprivate func insert(_ or: OnConflict?, _ values: [Setter]) -> Insert { let insert = values.reduce((columns: [Expressible](), values: [Expressible]())) { insert, setter in (insert.columns + [setter.column], insert.values + [setter.value]) } let clauses: [Expressible?] = [ Expression<Void>(literal: "INSERT"), or.map { Expression<Void>(literal: "OR \($0.rawValue)") }, Expression<Void>(literal: "INTO"), tableName(), "".wrap(insert.columns) as Expression<Void>, Expression<Void>(literal: "VALUES"), "".wrap(insert.values) as Expression<Void>, whereClause ] return Insert(" ".join(clauses.flatMap { $0 }).expression) } /// Runs an `INSERT` statement against the query with `DEFAULT VALUES`. public func insert() -> Insert { return Insert(" ".join([ Expression<Void>(literal: "INSERT INTO"), tableName(), Expression<Void>(literal: "DEFAULT VALUES") ]).expression) } /// Runs an `INSERT` statement against the query with the results of another /// query. /// /// - Parameter query: A query to `SELECT` results from. /// /// - Returns: The number of updated rows and statement. public func insert(_ query: QueryType) -> Update { return Update(" ".join([ Expression<Void>(literal: "INSERT INTO"), tableName(), query.expression ]).expression) } // MARK: UPDATE public func update(_ values: Setter...) -> Update { return update(values) } public func update(_ values: [Setter]) -> Update { let clauses: [Expressible?] = [ Expression<Void>(literal: "UPDATE"), tableName(), Expression<Void>(literal: "SET"), ", ".join(values.map { " = ".join([$0.column, $0.value]) }), whereClause ] return Update(" ".join(clauses.flatMap { $0 }).expression) } // MARK: DELETE public func delete() -> Delete { let clauses: [Expressible?] = [ Expression<Void>(literal: "DELETE FROM"), tableName(), whereClause ] return Delete(" ".join(clauses.flatMap { $0 }).expression) } // MARK: EXISTS public var exists: Select<Bool> { return Select(" ".join([ Expression<Void>(literal: "SELECT EXISTS"), "".wrap(expression) as Expression<Void> ]).expression) } // MARK: - /// Prefixes a column expression with the query’s table name or alias. /// /// - Parameter column: A column expression. /// /// - Returns: A column expression namespaced with the query’s table name or /// alias. public func namespace<V>(_ column: Expression<V>) -> Expression<V> { return Expression(".".join([tableName(), column]).expression) } // FIXME: rdar://problem/18673897 // subscript<T>… public subscript(column: Expression<Blob>) -> Expression<Blob> { return namespace(column) } public subscript(column: Expression<Blob?>) -> Expression<Blob?> { return namespace(column) } public subscript(column: Expression<Bool>) -> Expression<Bool> { return namespace(column) } public subscript(column: Expression<Bool?>) -> Expression<Bool?> { return namespace(column) } public subscript(column: Expression<Double>) -> Expression<Double> { return namespace(column) } public subscript(column: Expression<Double?>) -> Expression<Double?> { return namespace(column) } public subscript(column: Expression<Int>) -> Expression<Int> { return namespace(column) } public subscript(column: Expression<Int?>) -> Expression<Int?> { return namespace(column) } public subscript(column: Expression<Int64>) -> Expression<Int64> { return namespace(column) } public subscript(column: Expression<Int64?>) -> Expression<Int64?> { return namespace(column) } public subscript(column: Expression<String>) -> Expression<String> { return namespace(column) } public subscript(column: Expression<String?>) -> Expression<String?> { return namespace(column) } /// Prefixes a star with the query’s table name or alias. /// /// - Parameter star: A literal `*`. /// /// - Returns: A `*` expression namespaced with the query’s table name or /// alias. public subscript(star: Star) -> Expression<Void> { return namespace(star(nil, nil)) } // MARK: - // TODO: alias support func tableName(alias aliased: Bool = false) -> Expressible { guard let alias = clauses.from.alias , aliased else { return database(namespace: clauses.from.alias ?? clauses.from.name) } return " ".join([ database(namespace: clauses.from.name), Expression<Void>(literal: "AS"), Expression<Void>(alias) ]) } func tableName(qualified: Bool) -> Expressible { if qualified { return tableName() } return Expression<Void>(clauses.from.alias ?? clauses.from.name) } func database(namespace name: String) -> Expressible { let name = Expression<Void>(name) guard let database = clauses.from.database else { return name } return ".".join([Expression<Void>(database), name]) } public var expression: Expression<Void> { let clauses: [Expressible?] = [ selectClause, joinClause, whereClause, groupByClause, orderClause, limitOffsetClause ] return " ".join(clauses.flatMap { $0 }).expression } } // TODO: decide: simplify the below with a boxed type instead /// Queries a collection of chainable helper functions and expressions to build /// executable SQL statements. public struct Table : SchemaType { public static let identifier = "TABLE" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } public struct View : SchemaType { public static let identifier = "VIEW" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } public struct VirtualTable : SchemaType { public static let identifier = "VIRTUAL TABLE" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } // TODO: make `ScalarQuery` work in `QueryType.select()`, `.filter()`, etc. public struct ScalarQuery<V> : QueryType { public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } // TODO: decide: simplify the below with a boxed type instead public struct Select<T> : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Insert : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Update : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Delete : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } extension Connection { public func prepare(_ query: QueryType) throws -> AnySequence<Row> { let expression = query.expression let statement = try prepare(expression.template, expression.bindings) let columnNames: [String: Int] = try { var (columnNames, idx) = ([String: Int](), 0) column: for each in query.clauses.select.columns { var names = each.expression.template.split { $0 == "." }.map(String.init) let column = names.removeLast() let namespace = names.joined(separator: ".") func expandGlob(_ namespace: Bool) -> ((QueryType) throws -> Void) { return { (query: QueryType) throws -> (Void) in var q = type(of: query).init(query.clauses.from.name, database: query.clauses.from.database) q.clauses.select = query.clauses.select let e = q.expression var names = try self.prepare(e.template, e.bindings).columnNames.map { $0.quote() } if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } } for name in names { columnNames[name] = idx; idx += 1 } } } if column == "*" { var select = query select.clauses.select = (false, [Expression<Void>(literal: "*") as Expressible]) let queries = [select] + query.clauses.join.map { $0.query } if !namespace.isEmpty { for q in queries { if q.tableName().expression.template == namespace { try expandGlob(true)(q) continue column } } fatalError("no such table: \(namespace)") } for q in queries { try expandGlob(query.clauses.join.count > 0)(q) } continue } columnNames[each.expression.template] = idx idx += 1 } return columnNames }() return AnySequence { AnyIterator { statement.next().map { Row(columnNames, $0) } } } } public func scalar<V : Value>(_ query: ScalarQuery<V>) throws -> V { let expression = query.expression return value(try scalar(expression.template, expression.bindings)) } public func scalar<V : Value>(_ query: ScalarQuery<V?>) throws -> V.ValueType? { let expression = query.expression guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } public func scalar<V : Value>(_ query: Select<V>) throws -> V { let expression = query.expression return value(try scalar(expression.template, expression.bindings)) } public func scalar<V : Value>(_ query: Select<V?>) throws -> V.ValueType? { let expression = query.expression guard let value = try scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } public func pluck(_ query: QueryType) throws -> Row? { return try prepare(query.limit(1, query.clauses.limit?.offset)).makeIterator().next() } /// Runs an `Insert` query. /// /// - SeeAlso: `QueryType.insert(value:_:)` /// - SeeAlso: `QueryType.insert(values:)` /// - SeeAlso: `QueryType.insert(or:_:)` /// - SeeAlso: `QueryType.insert()` /// /// - Parameter query: An insert query. /// /// - Returns: The insert’s rowid. @discardableResult public func run(_ query: Insert) throws -> Int64 { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.lastInsertRowid } } /// Runs an `Update` query. /// /// - SeeAlso: `QueryType.insert(query:)` /// - SeeAlso: `QueryType.update(values:)` /// /// - Parameter query: An update query. /// /// - Returns: The number of updated rows. @discardableResult public func run(_ query: Update) throws -> Int { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.changes } } /// Runs a `Delete` query. /// /// - SeeAlso: `QueryType.delete()` /// /// - Parameter query: A delete query. /// /// - Returns: The number of deleted rows. @discardableResult public func run(_ query: Delete) throws -> Int { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.changes } } } public struct Row { fileprivate let columnNames: [String: Int] fileprivate let values: [Binding?] fileprivate init(_ columnNames: [String: Int], _ values: [Binding?]) { self.columnNames = columnNames self.values = values } /// Returns a row’s value for the given column. /// /// - Parameter column: An expression representing a column selected in a Query. /// /// - Returns: The value for the given column. public func get<V: Value>(_ column: Expression<V>) -> V { return get(Expression<V?>(column))! } public func get<V: Value>(_ column: Expression<V?>) -> V? { func valueAtIndex(_ idx: Int) -> V? { guard let value = values[idx] as? V.Datatype else { return nil } return (V.fromDatatypeValue(value) as? V)! } guard let idx = columnNames[column.template] else { let similar = Array(columnNames.keys).filter { $0.hasSuffix(".\(column.template)") } switch similar.count { case 0: fatalError("no such column '\(column.template)' in columns: \(columnNames.keys.sorted())") case 1: return valueAtIndex(columnNames[similar[0]]!) default: fatalError("ambiguous column '\(column.template)' (please disambiguate: \(similar))") } } return valueAtIndex(idx) } // FIXME: rdar://problem/18673897 // subscript<T>… public subscript(column: Expression<Blob>) -> Blob { return get(column) } public subscript(column: Expression<Blob?>) -> Blob? { return get(column) } public subscript(column: Expression<Bool>) -> Bool { return get(column) } public subscript(column: Expression<Bool?>) -> Bool? { return get(column) } public subscript(column: Expression<Double>) -> Double { return get(column) } public subscript(column: Expression<Double?>) -> Double? { return get(column) } public subscript(column: Expression<Int>) -> Int { return get(column) } public subscript(column: Expression<Int?>) -> Int? { return get(column) } public subscript(column: Expression<Int64>) -> Int64 { return get(column) } public subscript(column: Expression<Int64?>) -> Int64? { return get(column) } public subscript(column: Expression<String>) -> String { return get(column) } public subscript(column: Expression<String?>) -> String? { return get(column) } } /// Determines the join operator for a query’s `JOIN` clause. public enum JoinType : String { /// A `CROSS` join. case cross = "CROSS" /// An `INNER` join. case inner = "INNER" /// A `LEFT OUTER` join. case leftOuter = "LEFT OUTER" } /// ON CONFLICT resolutions. public enum OnConflict: String { case replace = "REPLACE" case rollback = "ROLLBACK" case abort = "ABORT" case fail = "FAIL" case ignore = "IGNORE" } // MARK: - Private public struct QueryClauses { var select = (distinct: false, columns: [Expression<Void>(literal: "*") as Expressible]) var from: (name: String, alias: String?, database: String?) var join = [(type: JoinType, query: QueryType, condition: Expressible)]() var filters: Expression<Bool?>? var group: (by: [Expressible], having: Expression<Bool?>?)? var order = [Expressible]() var limit: (length: Int, offset: Int?)? fileprivate init(_ name: String, alias: String?, database: String?) { self.from = (name, alias, database) } }
mpl-2.0
2a1f226052b2e222433a45db9100c460
30.259036
147
0.571759
4.341221
false
false
false
false
andrea-prearo/SwiftExamples
TaskList/TaskList/TasksDataSource.swift
1
3869
// // TasksDataSource.swift // TaskList // // Created by Andrea Prearo on 5/1/17. // Copyright © 2017 Andrea Prearo. All rights reserved. // import UIKit struct TasksDataSource { var tasks: [Task]? = nil { didSet { if oldValue == nil { viewModels = initializeViewModels() } } } fileprivate var viewModels: [[TaskViewModel]] = [[]] fileprivate var headerViewModels: [TaskHeaderViewModel] = Priority.allValues().map { return TaskHeaderViewModel(sectionText: $0.asString) } public var isGrouped = false { didSet { viewModels = rearrangeTasks(isGrouped: isGrouped) } } // MARK: - Public Methods func numberOfSections() -> Int { return viewModels.count } func numberOfItems(inSection section: Int) -> Int { return viewModels[section].count } func header(for section: Int) -> TaskHeaderViewModel? { return headerViewModels[section] } func item(at indexPath: IndexPath) -> TaskViewModel? { return viewModels[indexPath.section][indexPath.row] } mutating func updateItem(at indexPath: IndexPath, checked: Bool) { guard let updateTask = updateTask(at: indexPath, checked: checked) else { return } updateTaskViewModel(at: indexPath, task: updateTask, checked: checked) } @discardableResult mutating func updateTask(at indexPath: IndexPath, checked: Bool) -> Task? { let viewModel = viewModels[indexPath.section][indexPath.row] let originalTask = viewModel.task let taskIndex: Int? if isGrouped { taskIndex = tasks?.firstIndex { return $0 == originalTask } } else { taskIndex = indexPath.row } guard let index = taskIndex else { return nil } let updatedTask = Task(name: originalTask.name, priority: originalTask.priority, completed: checked) tasks?[index] = updatedTask return updatedTask } @discardableResult mutating func updateTaskViewModel(at indexPath: IndexPath, task: Task, checked: Bool) -> TaskViewModel? { let updatedViewModel = TaskViewModel(task: task) viewModels[indexPath.section][indexPath.row] = updatedViewModel return updatedViewModel } } // MARK: - Private Methods fileprivate extension TasksDataSource { func initializeViewModels() -> [[TaskViewModel]] { guard let tasks = tasks else { return [[]] } return [tasks.map { return TaskViewModel(task: $0) }] } func rearrangeTasks(isGrouped: Bool) -> [[TaskViewModel]] { guard let tasks = tasks else { return [[]] } let viewModels: [[TaskViewModel]] if isGrouped { var unknownPriorities = [TaskViewModel]() var highPriorities = [TaskViewModel]() var mediumPriorities = [TaskViewModel]() var lowPriorities = [TaskViewModel]() for task in tasks { switch task.priority { case .unknown: unknownPriorities.append(TaskViewModel(task: task)) case .high: highPriorities.append(TaskViewModel(task: task)) case .medium: mediumPriorities.append(TaskViewModel(task: task)) case .low: lowPriorities.append(TaskViewModel(task: task)) } } viewModels = [ unknownPriorities, highPriorities, mediumPriorities, lowPriorities ] } else { viewModels = initializeViewModels() } return viewModels } }
mit
3abca265e52b4264d80a87cb66eb1b19
29.456693
109
0.577818
5.212938
false
false
false
false
vbudhram/firefox-ios
Client/Frontend/Reader/ReaderModeUtils.swift
4
1663
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation struct ReaderModeUtils { static let DomainPrefixesToSimplify = ["www.", "mobile.", "m.", "blog."] static func simplifyDomain(_ domain: String) -> String { return DomainPrefixesToSimplify.first { domain.hasPrefix($0) }.map { $0.substring(from: $0.index($0.startIndex, offsetBy: $0.count)) } ?? domain } static func generateReaderContent(_ readabilityResult: ReadabilityResult, initialStyle: ReaderModeStyle) -> String? { guard let stylePath = Bundle.main.path(forResource: "Reader", ofType: "css"), let css = try? String(contentsOfFile: stylePath, encoding: .utf8), let tmplPath = Bundle.main.path(forResource: "Reader", ofType: "html"), let tmpl = try? String(contentsOfFile: tmplPath, encoding: .utf8) else { return nil } return tmpl.replacingOccurrences(of: "%READER-CSS%", with: css) .replacingOccurrences(of: "%READER-STYLE%", with: initialStyle.encode()) .replacingOccurrences(of: "%READER-DOMAIN%", with: simplifyDomain(readabilityResult.domain)) .replacingOccurrences(of: "%READER-URL%", with: readabilityResult.url) .replacingOccurrences(of: "%READER-TITLE%", with: readabilityResult.title) .replacingOccurrences(of: "%READER-CREDITS%", with: readabilityResult.credits) .replacingOccurrences(of: "%READER-CONTENT%", with: readabilityResult.content) } }
mpl-2.0
2166550a57b95f1d7f01b4f93ef1ace3
50.96875
121
0.669874
4.48248
false
false
false
false
adamnemecek/AudioKit
Sources/AudioKit/Nodes/NodeParameter.swift
1
8792
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation /// Definition or specification of a node parameter public struct NodeParameterDef { /// Unique ID public var identifier: String /// Name public var name: String /// Address public var address: AUParameterAddress /// Starting value if not set in initializer public var defaultValue: AUValue = 0.0 /// Value Range public var range: ClosedRange<AUValue> /// Physical Units public var unit: AudioUnitParameterUnit /// Options public var flags: AudioUnitParameterOptions /// Initialize node parameter definition with all data /// - Parameters: /// - identifier: Unique ID /// - name: Name /// - address: Address /// - defaultValue: Starting value /// - range: Value range /// - unit: Physical units /// - flags: Audio Unit Parameter options public init(identifier: String, name: String, address: AUParameterAddress, defaultValue: AUValue, range: ClosedRange<AUValue>, unit: AudioUnitParameterUnit, flags: AudioUnitParameterOptions = .default) { self.identifier = identifier self.name = name self.address = address self.defaultValue = defaultValue self.range = range self.unit = unit self.flags = flags } } /// NodeParameter wraps AUParameter in a user-friendly interface and adds some AudioKit-specific functionality. /// New version for use with Parameter property wrapper. public class NodeParameter { public private(set) var avAudioNode: AVAudioNode! /// AU Parameter that this wraps public private(set) var parameter: AUParameter! /// Definition. public var def: NodeParameterDef // MARK: Parameter properties /// Value of the parameter public var value: AUValue { get { parameter.value } set { if let avAudioUnit = avAudioNode as? AVAudioUnit { AudioUnitSetParameter(avAudioUnit.audioUnit, param: AudioUnitParameterID(def.address), to: newValue.clamped(to: range)) } parameter.value = newValue.clamped(to: range) } } /// Boolean values for parameters public var boolValue: Bool { get { value > 0.5 } set { value = newValue ? 1.0 : 0.0 } } /// Minimum value public var minValue: AUValue { parameter.minValue } /// Maximum value public var maxValue: AUValue { parameter.maxValue } /// Value range public var range: ClosedRange<AUValue> { (parameter.minValue ... parameter.maxValue) } /// Initial with definition /// - Parameter def: Node parameter definition public init(_ def: NodeParameterDef) { self.def = def } // MARK: Automation public var renderObserverToken: Int? /// Automate to a new value using a ramp. public func ramp(to value: AUValue, duration: Float, delay: Float = 0) { var delaySamples = AUAudioFrameCount(delay * Float(Settings.sampleRate)) if delaySamples > 4096 { print("Warning: delay longer than 4096, setting to to 4096") delaySamples = 4096 } if !parameter.flags.contains(.flag_CanRamp) { print("Error: can't ramp parameter \(parameter.displayName)") return } assert(delaySamples < 4096) let paramBlock = avAudioNode.auAudioUnit.scheduleParameterBlock paramBlock(AUEventSampleTimeImmediate + Int64(delaySamples), AUAudioFrameCount(duration * Float(Settings.sampleRate)), parameter.address, value.clamped(to: range)) } private var parameterObserverToken: AUParameterObserverToken? /// Records automation for this parameter. /// - Parameter callback: Called on the main queue for each parameter event. public func recordAutomation(callback: @escaping (AUParameterAutomationEvent) -> Void) { parameterObserverToken = parameter.token(byAddingParameterAutomationObserver: { numberEvents, events in for index in 0 ..< numberEvents { let event = events[index] // Dispatching to main thread avoids the restrictions // required of parameter automation observers. DispatchQueue.main.async { callback(event) } } }) } /// Stop calling the function passed to `recordAutomation` public func stopRecording() { if let token = parameterObserverToken { parameter.removeParameterObserver(token) } } // MARK: Lifecycle /// Helper function to attach the parameter to the appropriate tree /// - Parameters: /// - avAudioNode: AVAudioUnit to associate with public func associate(with avAudioNode: AVAudioNode) { self.avAudioNode = avAudioNode guard let tree = avAudioNode.auAudioUnit.parameterTree else { fatalError("No parameter tree.") } parameter = tree.parameter(withAddress: def.address) assert(parameter != nil) } /// Helper function to attach the parameter to the appropriate tree /// - Parameters: /// - avAudioNode: AVAudioUnit to associate with /// - parameter: Parameter to associate public func associate(with avAudioNode: AVAudioNode, parameter: AUParameter) { self.avAudioNode = avAudioNode self.parameter = parameter } /// Sends a .touch event to the parameter automation observer, beginning automation recording if /// enabled in ParameterAutomation. /// A value may be passed as the initial automation value. The current value is used if none is passed. /// - Parameter value: Initial value public func beginTouch(value: AUValue? = nil) { guard let value = value ?? parameter?.value else { return } parameter?.setValue(value, originator: nil, atHostTime: 0, eventType: .touch) } /// Sends a .release event to the parameter observation observer, ending any automation recording. /// A value may be passed as the final automation value. The current value is used if none is passed. /// - Parameter value: Final value public func endTouch(value: AUValue? = nil) { guard let value = value ?? parameter?.value else { return } parameter?.setValue(value, originator: nil, atHostTime: 0, eventType: .release) } } /// Base protocol for any type supported by @Parameter public protocol NodeParameterType { /// Get the float value func toAUValue() -> AUValue /// Initialize with a floating point number /// - Parameter value: initial value init(_ value: AUValue) } extension Bool: NodeParameterType { /// Convert a Boolean to a floating point number /// - Returns: An AUValue public func toAUValue() -> AUValue { self ? 1.0 : 0.0 } /// Initialize with a value /// - Parameter value: Initial value public init(_ value: AUValue) { self = value > 0.5 } } extension AUValue: NodeParameterType { /// Conver to AUValue /// - Returns: Value of type AUValue public func toAUValue() -> AUValue { self } } /// Used internally so we can iterate over parameters using reflection. protocol ParameterBase { var projectedValue: NodeParameter { get } } /// Wraps NodeParameter so we can easily assign values to it. /// /// Instead of`osc.frequency.value = 440`, we have `osc.frequency = 440` /// /// Use the $ operator to access the underlying NodeParameter. For example: /// `osc.$frequency.maxValue` /// /// When writing a Node, use: /// ``` /// @Parameter(myParameterDef) var myParameterName: AUValue /// ``` /// This syntax gives us additional flexibility for how parameters are implemented internally. /// /// Note that we don't allow initialization of Parameters to values /// because we don't yet have an underlying AUParameter. @propertyWrapper public struct Parameter<Value: NodeParameterType>: ParameterBase { var param: NodeParameter /// Create a parameter given a definition public init(_ def: NodeParameterDef) { param = NodeParameter(def) } /// Get the wrapped value public var wrappedValue: Value { get { Value(param.value) } set { param.value = newValue.toAUValue() } } /// Get the projected value public var projectedValue: NodeParameter { get { param } set { param = newValue } } }
mit
41d83fae7ea157bf31ca62df189e65cf
32.557252
111
0.638421
5.003984
false
false
false
false
ashfurrow/eidolon
Kiosk/Auction Listings/ListingsViewModel.swift
2
13520
import Foundation import RxSwift typealias ShowDetailsClosure = (SaleArtwork) -> Void typealias PresentModalClosure = (SaleArtwork) -> Void protocol ListingsViewModelType { var auctionID: String { get } var syncInterval: TimeInterval { get } var pageSize: Int { get } var logSync: (Date) -> Void { get } var numberOfSaleArtworks: Int { get } var showSpinner: Observable<Bool>! { get } var gridSelected: Observable<Bool>! { get } var updatedContents: Observable<NSDate> { get } var scheduleOnBackground: (_ observable: Observable<Any>) -> Observable<Any> { get } var scheduleOnForeground: (_ observable: Observable<[SaleArtwork]>) -> Observable<[SaleArtwork]> { get } func saleArtworkViewModel(atIndexPath indexPath: IndexPath) -> SaleArtworkViewModel func showDetailsForSaleArtwork(atIndexPath indexPath: IndexPath) func presentModalForSaleArtwork(atIndexPath indexPath: IndexPath) func imageAspectRatioForSaleArtwork(atIndexPath indexPath: IndexPath) -> CGFloat? func hasEstimateForSaleArtwork(atIndexPath indexPath: IndexPath) -> Bool } // Cheating here, should be in the instance but there's only ever one instance, so ¯\_(ツ)_/¯ private let backgroundScheduler = SerialDispatchQueueScheduler(qos: .default) class ListingsViewModel: NSObject, ListingsViewModelType { // These are private to the view model – should not be accessed directly fileprivate var saleArtworks = Variable(Array<SaleArtwork>()) fileprivate var sortedSaleArtworks = Variable<Array<SaleArtwork>>([]) let auctionID: String let pageSize: Int let syncInterval: TimeInterval let logSync: (Date) -> Void var scheduleOnBackground: (_ observable: Observable<Any>) -> Observable<Any> var scheduleOnForeground: (_ observable: Observable<[SaleArtwork]>) -> Observable<[SaleArtwork]> var numberOfSaleArtworks: Int { return sortedSaleArtworks.value.count } var showSpinner: Observable<Bool>! var gridSelected: Observable<Bool>! var updatedContents: Observable<NSDate> { return sortedSaleArtworks .asObservable() .map { $0.count > 0 } .ignore(value: false) .map { _ in NSDate() } } let showDetails: ShowDetailsClosure let presentModal: PresentModalClosure let provider: Networking init(provider: Networking, selectedIndex: Observable<Int>, showDetails: @escaping ShowDetailsClosure, presentModal: @escaping PresentModalClosure, pageSize: Int = 10, syncInterval: TimeInterval = SyncInterval, logSync:@escaping (Date) -> Void = ListingsViewModel.DefaultLogging, scheduleOnBackground: @escaping (_ observable: Observable<Any>) -> Observable<Any> = ListingsViewModel.DefaultScheduler(onBackground: true), scheduleOnForeground: @escaping (_ observable: Observable<[SaleArtwork]>) -> Observable<[SaleArtwork]> = ListingsViewModel.DefaultScheduler(onBackground: false), auctionID: String = AppSetup.sharedState.auctionID) { self.provider = provider self.auctionID = auctionID self.showDetails = showDetails self.presentModal = presentModal self.pageSize = pageSize self.syncInterval = syncInterval self.logSync = logSync self.scheduleOnBackground = scheduleOnBackground self.scheduleOnForeground = scheduleOnForeground super.init() setup(selectedIndex) } // MARK: Private Methods fileprivate func setup(_ selectedIndex: Observable<Int>) { recurringListingsRequest() .takeUntil(rx.deallocated) .bind(to: saleArtworks) .disposed(by: rx.disposeBag) showSpinner = sortedSaleArtworks.asObservable().map { sortedSaleArtworks in return sortedSaleArtworks.count == 0 } gridSelected = selectedIndex.map { ListingsViewModel.SwitchValues(rawValue: $0) == .some(.grid) } let distinctSaleArtworks = saleArtworks .asObservable() .distinctUntilChanged { (lhs, rhs) -> Bool in return lhs == rhs } .mapReplace(with: 0) // To use in combineLatest, we must have an array of identically-typed observables. Observable.combineLatest([selectedIndex, distinctSaleArtworks]) { ints in // We use distinctSaleArtworks to trigger an update, but ints[1] is unused. return ints[0] } .startWith(0) .map { selectedIndex in return ListingsViewModel.SwitchValues(rawValue: selectedIndex) } .filterNil() .map { [weak self] switchValue -> [SaleArtwork] in guard let me = self else { return [] } return switchValue.sortSaleArtworks(me.saleArtworks.value) } .bind(to: sortedSaleArtworks) .disposed(by: rx.disposeBag) } fileprivate func listingsRequest(forPage page: Int) -> Observable<Any> { return provider.request(.auctionListings(id: auctionID, page: page, pageSize: self.pageSize)).filterSuccessfulStatusCodes().mapJSON() } // Repeatedly calls itself with page+1 until the count of the returned array is < pageSize. fileprivate func retrieveAllListingsRequest(_ page: Int) -> Observable<Any> { return Observable.create { [weak self] observer in guard let me = self else { return Disposables.create() } return me.listingsRequest(forPage: page).subscribe(onNext: { object in guard let array = object as? Array<AnyObject> else { return } guard let me = self else { return } // This'll either be the next page request or .empty. let nextPage: Observable<Any> // We must have more results to retrieve if array.count >= me.pageSize { nextPage = me.retrieveAllListingsRequest(page+1) } else { nextPage = .empty() } // TODO: Anything with this disposable? _ = Observable<Any>.just(object) .concat(nextPage) .subscribe(observer) }) } } // Fetches all pages of the auction fileprivate func allListingsRequest() -> Observable<[SaleArtwork]> { let backgroundJSONParsing = scheduleOnBackground(retrieveAllListingsRequest(1)).reduce([Any]()) { (memo, object) in guard let array = object as? Array<Any> else { return memo } return memo + array } .mapTo(arrayOf: SaleArtwork.self) .logServerError(message: "Sale artworks failed to retrieve+parse") .catchErrorJustReturn([]) return scheduleOnForeground(backgroundJSONParsing) } fileprivate func recurringListingsRequest() -> Observable<Array<SaleArtwork>> { let recurring = Observable<Int>.interval(syncInterval, scheduler: MainScheduler.instance) .map { _ in Date() } .startWith(Date()) .takeUntil(rx.deallocated) return recurring .do(onNext: logSync) .flatMap { [weak self] _ in return self?.allListingsRequest() ?? .empty() } .map { [weak self] newSaleArtworks -> [SaleArtwork] in guard let me = self else { return [] } let currentSaleArtworks = me.saleArtworks.value // So we want to do here is pretty simple – if the existing and new arrays are of the same length, // then update the individual values in the current array and return the existing value. // If the array's length has changed, then we pass through the new array if newSaleArtworks.count == currentSaleArtworks.count { if update(currentSaleArtworks, newSaleArtworks: newSaleArtworks) { return currentSaleArtworks } } return newSaleArtworks } } // MARK: Private class methods fileprivate class func DefaultLogging(_ date: Date) { #if (arch(i386) || arch(x86_64)) && os(iOS) logger.log("Syncing on \(date)") #endif } fileprivate class func DefaultScheduler<T>(onBackground background: Bool) -> (_ observable: Observable<T>) -> Observable<T> { return { observable in if background { return observable.observeOn(backgroundScheduler) } else { return observable.observeOn(MainScheduler.instance) } } } // MARK: Public methods func saleArtworkViewModel(atIndexPath indexPath: IndexPath) -> SaleArtworkViewModel { return sortedSaleArtworks.value[indexPath.item].viewModel } func imageAspectRatioForSaleArtwork(atIndexPath indexPath: IndexPath) -> CGFloat? { return sortedSaleArtworks.value[indexPath.item].artwork.defaultImage?.aspectRatio } func hasEstimateForSaleArtwork(atIndexPath indexPath: IndexPath) -> Bool { let saleArtwork = sortedSaleArtworks.value[indexPath.item] switch (saleArtwork.estimateCents, saleArtwork.lowEstimateCents, saleArtwork.highEstimateCents) { case (.some, _, _): return true case (_, .some, .some): return true default: return false } } func showDetailsForSaleArtwork(atIndexPath indexPath: IndexPath) { showDetails(sortedSaleArtworks.value[indexPath.item]) } func presentModalForSaleArtwork(atIndexPath indexPath: IndexPath) { presentModal(sortedSaleArtworks.value[indexPath.item]) } // MARK: - Switch Values enum SwitchValues: Int { case grid = 0 case leastBids case mostBids case highestCurrentBid case lowestCurrentBid case alphabetical var name: String { switch self { case .grid: return "Grid" case .leastBids: return "Least Bids" case .mostBids: return "Most Bids" case .highestCurrentBid: return "Highest Bid" case .lowestCurrentBid: return "Lowest Bid" case .alphabetical: return "A–Z" } } func sortSaleArtworks(_ saleArtworks: [SaleArtwork]) -> [SaleArtwork] { switch self { case .grid: return saleArtworks case .leastBids: return saleArtworks.sorted(by: leastBidsSort) case .mostBids: return saleArtworks.sorted(by: mostBidsSort) case .highestCurrentBid: return saleArtworks.sorted(by: highestCurrentBidSort) case .lowestCurrentBid: return saleArtworks.sorted(by: lowestCurrentBidSort) case .alphabetical: return saleArtworks.sorted(by: alphabeticalSort) } } static func allSwitchValues() -> [SwitchValues] { return [grid, leastBids, mostBids, highestCurrentBid, lowestCurrentBid, alphabetical] } static func allSwitchValueNames() -> [String] { return allSwitchValues().map{$0.name.uppercased()} } } } // MARK: - Sorting Functions protocol IntOrZeroable { var intOrZero: Int { get } } extension NSNumber: IntOrZeroable { var intOrZero: Int { return (self as? Int) ?? 0 } } extension Optional where Wrapped: IntOrZeroable { var intOrZero: Int { return self.value?.intOrZero ?? 0 } } func leastBidsSort(_ lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return (lhs.bidCount.intOrZero) < (rhs.bidCount.intOrZero) } func mostBidsSort(_ lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return !leastBidsSort(lhs, rhs) } func lowestCurrentBidSort(_ lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return (lhs.highestBidCents.intOrZero) < (rhs.highestBidCents.intOrZero) } func highestCurrentBidSort(_ lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return !lowestCurrentBidSort(lhs, rhs) } func alphabeticalSort(_ lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return lhs.artwork.sortableArtistID().caseInsensitiveCompare(rhs.artwork.sortableArtistID()) == .orderedAscending } func sortById(_ lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return lhs.id.caseInsensitiveCompare(rhs.id) == .orderedAscending } private func update(_ currentSaleArtworks: [SaleArtwork], newSaleArtworks: [SaleArtwork]) -> Bool { assert(currentSaleArtworks.count == newSaleArtworks.count, "Arrays' counts must be equal.") // Updating the currentSaleArtworks is easy. Both are already sorted as they came from the API (by lot #). // Because we assume that their length is the same, we just do a linear scan through and // copy values from the new to the existing. let saleArtworksCount = currentSaleArtworks.count for i in 0 ..< saleArtworksCount { if currentSaleArtworks[i].id == newSaleArtworks[i].id { currentSaleArtworks[i].updateWithValues(newSaleArtworks[i]) } else { // Failure: the list was the same size but had different artworks. return false } } return true }
mit
7d2cc8e88c5175a765dde822edb14980
36.217631
170
0.634197
5.254765
false
false
false
false
900116/GodEyeClear
Classes/Model/CrashRecordModel.swift
1
2908
// // CrashRecordModel.swift // Pods // // Created by zixun on 16/12/28. // // import Foundation import CrashEye import RealmSwift import Realm final class CrashRecordModel: Object { dynamic open var type: String? dynamic open var name: String? dynamic open var reason: String? dynamic open var appinfo: String? dynamic open var callStack: String? init(model:CrashModel) { super.init() self.type = "\(model.type)" self.name = model.name self.reason = model.reason self.appinfo = model.appinfo self.callStack = model.callStack } init(type:CrashModelType, name:String, reason:String, appinfo:String,callStack:String) { super.init() self.type = "\(type)" self.name = name self.reason = reason self.appinfo = appinfo self.callStack = callStack } required init() { super.init() } required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm:realm,schema:schema) } required init(value: Any, schema: RLMSchema) { super.init(value:value,schema:schema) } } extension CrashRecordModel: RecordORMProtocol{ static var type: RecordType { return RecordType.crash } func attributeString() -> NSAttributedString { let result = NSMutableAttributedString() result.append(self.headerString()) result.append(self.nameString()) result.append(self.reasonString()) result.append(self.appinfoString()) result.append(self.callStackString()) return result } private func headerString() -> NSAttributedString { let type = self.type == "\(CrashModelType.exception.rawValue)" ? "Exception" : "SIGNAL" return self.headerString(with: "CRASH", content: type, color: UIColor(hex: 0xDF1921)) } private func nameString() -> NSAttributedString { return self.contentString(with: "NAME", content: self.name) } private func reasonString() -> NSAttributedString { return self.contentString(with: "REASON", content: self.reason) } private func appinfoString() -> NSAttributedString { return self.contentString(with: "APPINFO", content: self.appinfo) } private func callStackString() -> NSAttributedString { let result = NSMutableAttributedString(attributedString: self.contentString(with: "CALL STACK", content: self.callStack)) let range = result.string.NS.range(of: self.callStack!) if range.location != NSNotFound { let att = [NSFontAttributeName:UIFont(name: "Courier", size: 6)!, NSForegroundColorAttributeName:UIColor.white] as [String : Any] result.setAttributes(att, range: range) } return result } }
mit
658acbcdd75b5b47ba12f37c20e89c73
28.373737
129
0.628267
4.565149
false
false
false
false
terflogag/BadgeSegmentControl
Sources/BadgeSegmentControlAppearance.swift
1
2053
// // SegmentAppearance.swift // BadgeSegmentControl // // Created by terflogag on 03/02/2017. // Copyright (c) 2017 terflogag. All rights reserved. // import UIKit open class BadgeSegmentControlAppearance { // MARK: - Var open var segmentOnSelectionColour: UIColor open var segmentOffSelectionColour: UIColor open var segmentTouchDownColour: UIColor open var titleOnSelectionColour: UIColor open var titleOffSelectionColour: UIColor open var titleOnSelectionFont: UIFont open var titleOffSelectionFont: UIFont open var contentVerticalMargin: CGFloat open var dividerWidth: CGFloat open var dividerColour: UIColor open var cornerRadius: CGFloat open var borderWidth: CGFloat open var borderColor: UIColor open var backgroundColor: UIColor open var selectionBarColor: UIColor open var showSelectionBar: Bool open var selectionBarHeight: CGFloat // MARK: - Lifecycle /// Default init for appearance public init() { // Segment style initialization self.segmentOnSelectionColour = UIColor.darkGray self.segmentOffSelectionColour = UIColor.gray self.segmentTouchDownColour = UIColor.white.withAlphaComponent(0.4) // Title style initialization self.titleOnSelectionColour = UIColor.white self.titleOffSelectionColour = UIColor.darkGray self.titleOnSelectionFont = UIFont.systemFont(ofSize: 17.0) self.titleOffSelectionFont = UIFont.systemFont(ofSize: 17.0) // Margin initialization self.contentVerticalMargin = 5.0 // Divider self.dividerWidth = 1.0 self.dividerColour = UIColor.black // Border self.cornerRadius = 3.0 self.borderWidth = 2.0 self.borderColor = UIColor.black // Background self.backgroundColor = UIColor.clear // Selection bar self.selectionBarColor = UIColor.darkGray self.selectionBarHeight = 8.0 self.showSelectionBar = false } }
mit
6cf7fca6ee9c88f84333e3d28bdad6ee
26.373333
75
0.694106
5.05665
false
false
false
false