repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mojio/mojio-ios-sdk
refs/heads/master
MojioSDK/Models/Mojio.swift
mit
1
// // Mojio.swift // MojioSDK // // Created by Ashish Agarwal on 2016-02-10. // Copyright © 2016 Mojio. All rights reserved. // import UIKit import ObjectMapper public class Mojio: Mappable { public dynamic var Id : String? = nil public dynamic var Name : String? = nil public dynamic var IMEI : String? = nil public dynamic var LastContactTime : String? = nil public dynamic var GatewayTime : String? = nil public dynamic var VehicleId : String? = nil public var MojioLocation : Location? = nil public var Tags : [String] = [] public var Wifi : WifiRadio? = nil public var ConnectedState : BooleanState? = nil public dynamic var CreatedOn : String? = nil public dynamic var LastModified : String? = nil public dynamic var Deleted : Bool = false public required convenience init?(_ map: Map) { self.init() } public required init() { } public static func primaryKey() -> String? { return "Id" } public func json () -> String? { let dictionary : NSMutableDictionary = NSMutableDictionary() if self.Name != nil { dictionary.setObject(self.Name!, forKey: "Name") } if self.IMEI != nil { dictionary.setObject(self.IMEI!, forKey: "IMEI") } let data = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.PrettyPrinted) return NSString(data: data, encoding: NSUTF8StringEncoding)! as String } public func mapping(map: Map) { Id <- map["Id"] Name <- map["Name"] IMEI <- map["IMEI"] LastContactTime <- map["LastContactTime"] Wifi <- map["WifiRadio"] GatewayTime <- map["GatewayTime"] VehicleId <- map["VehicleId"] MojioLocation <- map["Location"] ConnectedState <- map["ConnectedState"] CreatedOn <- map["CreatedOn"] LastModified <- map["LastModified"] Tags <- map["Tags"] Deleted <- map["Deleted"] } }
2d502e665d10b8cf6fd647a6837fa704
28.714286
120
0.603846
false
false
false
false
tedrog36/HealthKitApp-Swift
refs/heads/master
HealthKitApp/AppDelegate.swift
mit
1
// // AppDelegate.swift // HealthKitApp // // Created by Ted Rogers on 6/10/14. // Copyright (c) 2014 Ted Rogers Consulting, LLC. All rights reserved. // import UIKit import HealthKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // the app main window var window: UIWindow? // the health store - can be null if we don't get permission var healthStore: HKHealthStore? // optional func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool { // dispatch immediately after current block DispatchQueue.main.async { self.requestHealthKitSharing() } return true } func requestHealthKitSharing() { // make sure HealthKit is available on this device if !HKHealthStore.isHealthDataAvailable() { return } // get our types to read and write for sharing permissions let typesToWrite = dataTypesToWrite() let typesToRead = dataTypesToRead() // create our health store let myHealthStore = HKHealthStore() print("requesting authorization to share health data types") // illustrate a few ways of handling the closure // start with class trailing closure myHealthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead) { (success, error) in if success { self.handleAuthorizationSuccess(healthStore: myHealthStore) } else { self.handleAuthorizationFailure(error: error) } } // // maximum verbosity // // request permissions to share health data with HealthKit // myHealthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead, completion: { // (success: Bool, error: Error?) -> Void in // if success { // self.handleAuthorizationSuccess(healthStore: myHealthStore) // } else { // self.handleAuthorizationFailure(error: error) // } // }) // // drop parameter types // myHealthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead, completion: { // (success, error) -> Void in // if success { // self.handleAuthorizationSuccess(healthStore: myHealthStore) // } else { // self.handleAuthorizationFailure(error: error) // } // }) // // drop return // myHealthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead, completion: { // (success, error) in // if success { // self.handleAuthorizationSuccess(healthStore: myHealthStore) // } else { // self.handleAuthorizationFailure(error: error) // } // }) // // switch to trailing closure - you can do this if the last param is a closure // myHealthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead) { (success: Bool, error: Error?) -> Void in // if success { // self.handleAuthorizationSuccess(healthStore: myHealthStore) // } else { // self.handleAuthorizationFailure(error: error) // } // } // // trailing closue with no return type and no param types // myHealthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead) { (success, error) in // if success { // self.handleAuthorizationSuccess(healthStore: myHealthStore) // } else { // self.handleAuthorizationFailure(error: error) // } // } // // trailing closue with no return type and no params // myHealthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead) { // if $0 { // self.handleAuthorizationSuccess(healthStore: myHealthStore) // } else { // self.handleAuthorizationFailure(error: $1) // } // } // // create a variable to hold the closure // let completion = { // (success: Bool, error: Error?) -> Void in // if success { // self.handleAuthorizationSuccess(healthStore: myHealthStore) // } else { // self.handleAuthorizationFailure(error: error) // } // } // myHealthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead, completion: completion) } func handleAuthorizationSuccess(healthStore: HKHealthStore) { print("successfully registered to share types") // all is good, so save our HealthStore and do some initialization DispatchQueue.main.async { self.healthStore = healthStore NotificationCenter.default.post(name: NSNotification.Name(rawValue: Constants.kHealthKitInitialized), object: self) } } func handleAuthorizationFailure(error: Error?) { if let theError = error { print("error regisering shared types = \(theError)") } } func dataTypesToWrite() -> Set<HKQuantityType> { let heartRateType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) let bloodGlucoseType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose) let types: Set = [heartRateType!, bloodGlucoseType!]; return types; } func dataTypesToRead() -> Set<HKQuantityType> { let heartRateType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) let bloodGlucoseType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose) let types: Set = [heartRateType!, bloodGlucoseType!]; return types; } }
09efc5e0562bf4d760c0c0fc60253abc
40.48951
145
0.620934
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGraphics/DrawableContext/Gradient.swift
mit
1
// // Gradient.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public enum GradientSpreadMode: CaseIterable { case none case pad case reflect case `repeat` } @frozen public struct GradientStop<Color: ColorProtocol>: Hashable { public var offset: Double public var color: Color @inlinable @inline(__always) public init(offset: Double, color: Color) { self.offset = offset self.color = color } } extension GradientStop where Color == AnyColor { @inlinable @inline(__always) public init<M>(_ stop: GradientStop<DoggieGraphics.Color<M>>) { self.init(offset: stop.offset, color: AnyColor(stop.color)) } @inlinable @inline(__always) public init<M>(offset: Double, color: DoggieGraphics.Color<M>) { self.init(offset: offset, color: AnyColor(color)) } } extension GradientStop { @inlinable @inline(__always) public func convert<Model>(to colorSpace: ColorSpace<Model>, intent: RenderingIntent = .default) -> GradientStop<DoggieGraphics.Color<Model>> { return GradientStop<DoggieGraphics.Color<Model>>(offset: offset, color: color.convert(to: colorSpace, intent: intent)) } @inlinable @inline(__always) public func convert(to colorSpace: AnyColorSpace, intent: RenderingIntent = .default) -> GradientStop<AnyColor> { return GradientStop<AnyColor>(offset: offset, color: color.convert(to: colorSpace, intent: intent)) } } public enum GradientType: CaseIterable { case linear case radial } @frozen public struct Gradient<Color: ColorProtocol>: Hashable { public var type: GradientType public var start: Point public var end: Point @inlinable @inline(__always) var rawCenter: Point { switch type { case .linear: return 0.5 * (start + end) case .radial: return end } } @inlinable @inline(__always) public var center: Point { get { return rawCenter * transform } set { let _center = center if _center != newValue { let offset = newValue - rawCenter * transform transform *= SDTransform.translate(x: offset.x, y: offset.y) } } } public var transform: SDTransform = .identity public var opacity: Double = 1 public var stops: [GradientStop<Color>] public var startSpread: GradientSpreadMode = .pad public var endSpread: GradientSpreadMode = .pad @inlinable @inline(__always) public init(type: GradientType, start: Point, end: Point, stops: [GradientStop<Color>]) { self.type = type self.start = start self.end = end self.stops = stops } } extension Gradient where Color == AnyColor { @inlinable @inline(__always) public init<M>(_ gradient: Gradient<DoggieGraphics.Color<M>>) { self.init(type: gradient.type, start: gradient.start, end: gradient.end, stops: gradient.stops.map(GradientStop<AnyColor>.init)) self.transform = gradient.transform self.opacity = gradient.opacity self.startSpread = gradient.startSpread self.endSpread = gradient.endSpread } } extension Gradient { @inlinable @inline(__always) public func convert<Model>(to colorSpace: ColorSpace<Model>, intent: RenderingIntent = .default) -> Gradient<DoggieGraphics.Color<Model>> { var result = Gradient<DoggieGraphics.Color<Model>>(type: self.type, start: self.start, end: self.end, stops: self.stops.map { $0.convert(to: colorSpace, intent: intent) }) result.transform = self.transform result.opacity = self.opacity result.startSpread = self.startSpread result.endSpread = self.endSpread return result } @inlinable @inline(__always) public func convert(to colorSpace: AnyColorSpace, intent: RenderingIntent = .default) -> Gradient<AnyColor> { var result = Gradient<AnyColor>(type: self.type, start: self.start, end: self.end, stops: self.stops.map { $0.convert(to: colorSpace, intent: intent) }) result.transform = self.transform result.opacity = self.opacity result.startSpread = self.startSpread result.endSpread = self.endSpread return result } } extension Gradient { @inlinable @inline(__always) public mutating func rotate(_ angle: Double) { let center = self.center self.transform *= SDTransform.translate(x: -center.x, y: -center.y) * SDTransform.rotate(angle) * SDTransform.translate(x: center.x, y: center.y) } @inlinable @inline(__always) public mutating func skewX(_ angle: Double) { let center = self.center self.transform *= SDTransform.translate(x: -center.x, y: -center.y) * SDTransform.skewX(angle) * SDTransform.translate(x: center.x, y: center.y) } @inlinable @inline(__always) public mutating func skewY(_ angle: Double) { let center = self.center self.transform *= SDTransform.translate(x: -center.x, y: -center.y) * SDTransform.skewY(angle) * SDTransform.translate(x: center.x, y: center.y) } @inlinable @inline(__always) public mutating func scale(_ scale: Double) { let center = self.center self.transform *= SDTransform.translate(x: -center.x, y: -center.y) * SDTransform.scale(scale) * SDTransform.translate(x: center.x, y: center.y) } @inlinable @inline(__always) public mutating func scale(x: Double = 1, y: Double = 1) { let center = self.center self.transform *= SDTransform.translate(x: -center.x, y: -center.y) * SDTransform.scale(x: x, y: y) * SDTransform.translate(x: center.x, y: center.y) } @inlinable @inline(__always) public mutating func translate(x: Double = 0, y: Double = 0) { self.transform *= SDTransform.translate(x: x, y: y) } @inlinable @inline(__always) public mutating func reflectX() { self.transform *= SDTransform.reflectX(self.center.x) } @inlinable @inline(__always) public mutating func reflectY() { self.transform *= SDTransform.reflectY(self.center.y) } @inlinable @inline(__always) public mutating func reflectX(_ x: Double) { self.transform *= SDTransform.reflectX(x) } @inlinable @inline(__always) public mutating func reflectY(_ y: Double) { self.transform *= SDTransform.reflectY(y) } }
2f4845afe30196fee0630f09e021b66b
30.739837
179
0.645748
false
false
false
false
vanshg/MacAssistant
refs/heads/master
Pods/Magnet/Lib/Magnet/HotKey.swift
mit
1
// // HotKey.swift // Magnet // // Created by 古林俊佑 on 2016/03/09. // Copyright © 2016年 Shunsuke Furubayashi. All rights reserved. // import Cocoa import Carbon public final class HotKey: NSObject { // MARK: - Properties public let identifier: String public let keyCombo: KeyCombo public let callback: ((HotKey) -> Void)? public let target: AnyObject? public let action: Selector? public let actionQueue: ActionQueue var hotKeyId: UInt32? var hotKeyRef: EventHotKeyRef? // MARK: - Enum Value public enum ActionQueue { case main case session public func execute(closure: @escaping () -> Void) { switch self { case .main: DispatchQueue.main.async { closure() } case .session: closure() } } } // MARK: - Initialize public init(identifier: String, keyCombo: KeyCombo, target: AnyObject, action: Selector, actionQueue: ActionQueue = .main) { self.identifier = identifier self.keyCombo = keyCombo self.callback = nil self.target = target self.action = action self.actionQueue = actionQueue super.init() } public init(identifier: String, keyCombo: KeyCombo, actionQueue: ActionQueue = .main, handler: @escaping ((HotKey) -> Void)) { self.identifier = identifier self.keyCombo = keyCombo self.callback = handler self.target = nil self.action = nil self.actionQueue = actionQueue super.init() } } // MARK: - Invoke public extension HotKey { public func invoke() { guard let callback = self.callback else { guard let target = self.target as? NSObject, let selector = self.action else { return } guard target.responds(to: selector) else { return } actionQueue.execute { [weak self] in guard let wSelf = self else { return } target.perform(selector, with: wSelf) } return } actionQueue.execute { [weak self] in guard let wSelf = self else { return } callback(wSelf) } } } // MARK: - Register & UnRegister public extension HotKey { @discardableResult public func register() -> Bool { return HotKeyCenter.shared.register(with: self) } public func unregister() { return HotKeyCenter.shared.unregister(with: self) } } // MARK: - override isEqual public extension HotKey { public override func isEqual(_ object: Any?) -> Bool { guard let hotKey = object as? HotKey else { return false } return self.identifier == hotKey.identifier && self.keyCombo == hotKey.keyCombo && self.hotKeyId == hotKey.hotKeyId && self.hotKeyRef == hotKey.hotKeyRef } }
08ea2b3b7e67a9dcb1012fdb75d222f3
27.339623
130
0.574567
false
false
false
false
infobip/mobile-messaging-sdk-ios
refs/heads/master
Classes/Core/Operations/AppOperations/FetchInstanceOperation.swift
apache-2.0
1
// // FetchInstanceOperation.swift // MobileMessaging // // Created by Andrey Kadochnikov on 09/11/2018. // import Foundation class FetchInstanceOperation : MMOperation { let mmContext: MobileMessaging let currentInstallation: MMInstallation let finishBlock: ((NSError?) -> Void) let pushRegistrationId: String init?(userInitiated: Bool, currentInstallation: MMInstallation, mmContext: MobileMessaging, finishBlock: @escaping ((NSError?) -> Void)) { self.currentInstallation = currentInstallation self.mmContext = mmContext self.finishBlock = finishBlock if let pushRegistrationId = currentInstallation.pushRegistrationId { self.pushRegistrationId = pushRegistrationId } else { Self.logDebug("There is no registration. Abortin...") return nil } super.init(isUserInitiated: userInitiated) self.addCondition(HealthyRegistrationCondition(mmContext: mmContext)) } override func execute() { guard !isCancelled else { logDebug("cancelled...") finish() return } logDebug("started...") performRequest() } private func performRequest() { mmContext.remoteApiProvider.getInstance(applicationCode: mmContext.applicationCode, pushRegistrationId: pushRegistrationId, queue: underlyingQueue) { (result) in self.handleResult(result) self.finishWithError(result.error) } } private func handleResult(_ result: FetchInstanceDataResult) { assert(!Thread.isMainThread) guard !isCancelled else { logDebug("cancelled.") return } switch result { case .Success(let responseInstallation): if fetchedInstallationMayBeSaved(fetchedInstallation: responseInstallation) { responseInstallation.archiveAll() } logDebug("successfully synced") case .Failure(let error): logError("sync request failed with error: \(error.orNil)") case .Cancel: logWarn("sync request cancelled.") } } private func fetchedInstallationMayBeSaved(fetchedInstallation: MMInstallation) -> Bool { return fetchedInstallation.pushRegistrationId == mmContext.dirtyInstallation().pushRegistrationId } override func finished(_ errors: [NSError]) { assert(userInitiated == Thread.isMainThread) logDebug("finished with errors: \(errors)") finishBlock(errors.first) //check what to do with errors/ } }
fa3d8d4ea37b0718a879e92dd9de711f
29.144737
169
0.747708
false
false
false
false
crazypoo/PTools
refs/heads/master
Pods/InAppViewDebugger/InAppViewDebugger/ViewControllerUtils.swift
mit
1
// // ViewUtils.swift // InAppViewDebugger // // Created by Indragie Karunaratne on 4/4/19. // Copyright © 2019 Indragie Karunaratne. All rights reserved. // import UIKit func getNearestAncestorViewController(responder: UIResponder) -> UIViewController? { if let viewController = responder as? UIViewController { return viewController } else if let nextResponder = responder.next { return getNearestAncestorViewController(responder: nextResponder) } return nil } func topViewController(rootViewController: UIViewController?) -> UIViewController? { guard let rootViewController = rootViewController else { return nil } guard let presentedViewController = rootViewController.presentedViewController else { return rootViewController } if let navigationController = presentedViewController as? UINavigationController { return topViewController(rootViewController: navigationController.viewControllers.last) } else if let tabBarController = presentedViewController as? UITabBarController { return topViewController(rootViewController: tabBarController.selectedViewController) } else { return topViewController(rootViewController: presentedViewController) } }
ab05f1f73c7340c2817165987ec99101
35.285714
95
0.75748
false
false
false
false
proversity-org/edx-app-ios
refs/heads/master
Source/Deep Linking/DeepLinkManager.swift
apache-2.0
1
// // DeepLinkManager.swift // edX // // Created by Salman on 02/10/2018. // Copyright © 2018 edX. All rights reserved. // import UIKit typealias DismissCompletion = () -> Void @objc class DeepLinkManager: NSObject { @objc static let sharedInstance = DeepLinkManager() typealias Environment = OEXSessionProvider & OEXRouterProvider & OEXConfigProvider var environment: Environment? private var topMostViewController: UIViewController? { return UIApplication.shared.topMostController() } private override init() { super.init() } @objc func processDeepLink(with params: [String: Any], environment: Environment) { self.environment = environment let deepLink = DeepLink(dictionary: params) let deepLinkType = deepLink.type guard deepLinkType != .none else { return } navigateToDeepLink(with: deepLinkType, link: deepLink) } private func showLoginScreen() { guard let topViewController = topMostViewController, !(topViewController is OEXLoginViewController) else { return } dismiss() { [weak self] in self?.environment?.router?.showLoginScreen(from: nil, completion: nil) } } private func isUserLoggedin() -> Bool { return environment?.session.currentUser != nil } private func linkType(for controller: UIViewController) -> DeepLinkType { if let courseOutlineViewController = controller as? CourseOutlineViewController { return courseOutlineViewController.courseOutlineMode == .full ? .courseDashboard : .courseVideos } else if controller is OEXCourseInfoViewController { return .courseDetail } else if let discoveryViewController = controller as? DiscoveryViewController { let segmentType = discoveryViewController.segmentType(of: discoveryViewController.segmentedControl.selectedSegmentIndex) if segmentType == SegmentOption.program.rawValue { return .programDiscovery } else if segmentType == SegmentOption.course.rawValue { return .courseDiscovery } else if segmentType == SegmentOption.degree.rawValue { return .degreeDiscovery } } else if controller is OEXFindCoursesViewController { return .courseDiscovery } else if let programsDiscoveryViewController = controller as? ProgramsDiscoveryViewController { if programsDiscoveryViewController.viewType == .program { return programsDiscoveryViewController.pathId == nil ? .programDiscovery : .programDiscoveryDetail } else if programsDiscoveryViewController.viewType == .degree { return programsDiscoveryViewController.pathId == nil ? .degreeDiscovery : .degreeDiscoveryDetail } } else if controller is ProgramsViewController { return .program } else if controller is DiscussionTopicsViewController { return .discussions } else if controller is AccountViewController { return .account } else if controller is UserProfileViewController { return .profile } return .none } private func showCourseDashboardViewController(with link: DeepLink) { guard let topViewController = topMostViewController else { return } if let courseDashboardView = topViewController.parent as? CourseDashboardViewController, courseDashboardView.courseID == link.courseId { if !controllerAlreadyDisplayed(for: link.type) { courseDashboardView.switchTab(with: link.type) } } dismiss() { [weak self] in if let topController = self?.topMostViewController { self?.environment?.router?.showCourse(with: link, courseID: link.courseId ?? "", from: topController) } } } private func showDiscovery(with link: DeepLink) { guard !controllerAlreadyDisplayed(for: link.type) else { // Course discovery detail if already loaded if let courseInfoController = topMostViewController as? OEXCourseInfoViewController, let pathId = link.courseId { courseInfoController.loadCourseInfo(with: pathId, forceLoad: false) } // Program discovery detail if already loaded if let programDiscoveryViewController = topMostViewController as? ProgramsDiscoveryViewController, let pathId = link.pathID { if pathId != programDiscoveryViewController.pathId { programDiscoveryViewController.loadProgramDetails(with: pathId) } } return } switch link.type { case .courseDetail: guard environment?.config.discovery.course.isEnabled ?? false, let courseId = link.courseId else { return } if let discoveryViewController = topMostViewController as? DiscoveryViewController { discoveryViewController.switchSegment(with: .courseDiscovery) environment?.router?.showDiscoveryDetail(from: discoveryViewController, type: .courseDetail, pathID: courseId, bottomBar: discoveryViewController.bottomBar) return } else if let findCoursesViewController = topMostViewController as? OEXFindCoursesViewController { environment?.router?.showDiscoveryDetail(from: findCoursesViewController, type: .courseDetail, pathID: courseId, bottomBar: findCoursesViewController.bottomBar) return } break case .programDiscoveryDetail: guard environment?.config.discovery.program.isEnabled ?? false, let pathId = link.pathID else { return } if let discoveryViewController = topMostViewController as? DiscoveryViewController { discoveryViewController.switchSegment(with: .programDiscovery) environment?.router?.showDiscoveryDetail(from: discoveryViewController, type: .programDiscoveryDetail, pathID: pathId, bottomBar: discoveryViewController.bottomBar) return } else if let programsDiscoveryViewController = topMostViewController as? ProgramsDiscoveryViewController { environment?.router?.showDiscoveryDetail(from: programsDiscoveryViewController, type: .programDiscoveryDetail, pathID: pathId, bottomBar: programsDiscoveryViewController.bottomBar) return } break case .programDiscovery: guard environment?.config.discovery.program.isEnabled ?? false else { return } if let discoveryViewController = topMostViewController as? DiscoveryViewController { discoveryViewController.switchSegment(with: link.type) return } break case .courseDiscovery: guard environment?.config.discovery.course.isEnabled ?? false else { return } if let discoveryViewController = topMostViewController as? DiscoveryViewController { discoveryViewController.switchSegment(with: link.type) return } break case .degreeDiscovery: guard environment?.config.discovery.degree.isEnabled ?? false else { return } if let discoveryViewController = topMostViewController as? DiscoveryViewController { discoveryViewController.switchSegment(with: link.type) return } break case .degreeDiscoveryDetail: guard environment?.config.discovery.degree.isEnabled ?? false, let pathId = link.pathID else { return } if let discoveryViewController = topMostViewController as? DiscoveryViewController { discoveryViewController.switchSegment(with: .degreeDiscoveryDetail) environment?.router?.showDiscoveryDetail(from: discoveryViewController, type: .degreeDiscoveryDetail, pathID: pathId, bottomBar: discoveryViewController.bottomBar) return } break default: break } guard let topController = topMostViewController else { return } let pathId = link.type == .courseDetail ? link.courseId : link.pathID if isUserLoggedin() { dismiss() { [weak self] in if let topController = self?.topMostViewController { self?.environment?.router?.showDiscoveryController(from: topController, type: link.type, isUserLoggedIn: true , pathID: pathId) } } } else { if !(topController is DiscoveryViewController), topController.isModal() { topController.dismiss(animated: true) { [weak self] in if let topController = self?.topMostViewController { self?.environment?.router?.showDiscoveryController(from: topController, type: link.type, isUserLoggedIn: false , pathID: pathId) } } } else { environment?.router?.showDiscoveryController(from: topController, type: link.type, isUserLoggedIn: false , pathID: pathId) } } } private func showPrograms(with link: DeepLink) { if let topController = topMostViewController, let controller = topController as? ProgramsViewController, controller.type == .detail { topController.navigationController?.popViewController(animated: true) } else if !controllerAlreadyDisplayed(for: link.type) { dismiss() { [weak self] in if let topController = self?.topMostViewController { self?.environment?.router?.showProgram(with: link.type, from: topController) } } } } private func showProgramDetail(with link: DeepLink) { guard !controllerAlreadyDisplayed(for: link.type), let myProgramDetailURL = environment?.config.programConfig.programDetailURLTemplate, let pathID = link.pathID, let url = URL(string: myProgramDetailURL.replacingOccurrences(of: URIString.pathPlaceHolder.rawValue, with: pathID)) else { return} if let topController = topMostViewController, let controller = topController as? ProgramsViewController { if controller.type == .base { environment?.router?.showProgramDetails(with: url, from: topController) } else if controller.type == .detail && controller.programsURL != url { controller.loadPrograms(with: url) } } else { dismiss() { [weak self] in if let topController = self?.topMostViewController { self?.environment?.router?.showProgram(with: link.type, url: url, from: topController) } } } } private func showAccountViewController(with link: DeepLink) { guard !controllerAlreadyDisplayed(for: link.type) else { return} dismiss() { [weak self] in if let topViewController = self?.topMostViewController { self?.environment?.router?.showAccount(controller:topViewController, modalTransitionStylePresent: true) } } } private func showProfile(with link: DeepLink) { guard let topViewController = topMostViewController, let username = environment?.session.currentUser?.username else { return } func showView(modal: Bool) { environment?.router?.showProfileForUsername(controller: topMostViewController, username: username, editable: false, modal: modal) } if topViewController is AccountViewController { showView(modal: false) } else if topViewController is UserProfileEditViewController || topViewController is JSONFormViewController<String> || topViewController is JSONFormBuilderTextEditorViewController { if let viewController = topViewController.navigationController?.viewControllers.first(where: {$0 is UserProfileViewController}) { topViewController.navigationController?.popToViewController(viewController, animated: true) } } else if !controllerAlreadyDisplayed(for: link.type) { dismiss() { showView(modal: true) } } } private func showDiscussionTopic(with link: DeepLink) { guard let courseId = link.courseId, let topicID = link.topicID, let topController = topMostViewController else { return } var isControllerAlreadyDisplayed : Bool { guard let postController = topMostViewController as? PostsViewController else { return false } return postController.topicID == link.topicID } func showDiscussionPosts() { if let topController = topMostViewController { environment?.router?.showDiscussionPosts(from: topController, courseID: courseId, topicID: topicID) } } if let postController = topController as? PostsViewController, postController.topicID != link.topicID { postController.navigationController?.popViewController(animated: true) showDiscussionPosts() } else { dismiss() { [weak self] in guard let topController = self?.topMostViewController, !isControllerAlreadyDisplayed else { return } if let courseDashboardController = topController as? CourseDashboardViewController, courseDashboardController.courseID == link.courseId { courseDashboardController.switchTab(with: link.type) } else { self?.showCourseDashboardViewController(with: link) } showDiscussionPosts() } } } private func showDiscussionResponses(with link: DeepLink, completion: (() -> Void)? = nil) { guard let courseId = link.courseId, let threadID = link.threadID, let topController = topMostViewController else { return } var isControllerAlreadyDisplayed: Bool { guard let discussionResponseController = topMostViewController as? DiscussionResponsesViewController else { return false } return discussionResponseController.threadID == link.threadID } func showResponses() { if let topController = topMostViewController { environment?.router?.showDiscussionResponses(from: topController, courseID: courseId, threadID: threadID, isDiscussionBlackedOut: false, completion: completion) } } if let discussionResponseController = topController as? DiscussionResponsesViewController, discussionResponseController.threadID != link.threadID { discussionResponseController.navigationController?.popViewController(animated: true) showResponses() } else { dismiss() { [weak self] in guard let topController = self?.topMostViewController, !isControllerAlreadyDisplayed else { return } if let courseDashboardController = topController as? CourseDashboardViewController, courseDashboardController.courseID == link.courseId { courseDashboardController.switchTab(with: link.type) } else if let postViewController = topController as? PostsViewController, postViewController.topicID != link.topicID { postViewController.navigationController?.popViewController(animated: true) } self?.showDiscussionTopic(with: link) showResponses() } } } private func showdiscussionComments(with link: DeepLink) { guard let courseID = link.courseId, let commentID = link.commentID, let threadID = link.threadID, let topController = topMostViewController else { return } var isControllerAlreadyDisplayed: Bool { guard let discussionCommentViewController = topMostViewController as? DiscussionCommentsViewController else { return false} return discussionCommentViewController.commentID == commentID } var isResponseControllerDisplayed: Bool { guard let discussionResponseController = topMostViewController as? DiscussionResponsesViewController else { return false } return discussionResponseController.threadID == link.threadID } func showComment() { if let topController = topMostViewController, let discussionResponseController = topController as? DiscussionResponsesViewController { environment?.router?.showDiscussionComments(from: discussionResponseController, courseID: courseID, commentID: commentID, threadID:threadID) discussionResponseController.navigationController?.delegate = nil } } if let discussionCommentController = topController as? DiscussionCommentsViewController, discussionCommentController.commentID != commentID { discussionCommentController.navigationController?.popViewController(animated: true) showComment() } else { dismiss() { [weak self] in guard !isControllerAlreadyDisplayed else { return } if isResponseControllerDisplayed { showComment() } else { self?.showDiscussionResponses(with: link) { showComment() } } } } } private func showCourseHandout(with link: DeepLink) { var controllerAlreadyDisplayed: Bool { if let topController = topMostViewController, let courseHandoutController = topController as? CourseHandoutsViewController, courseHandoutController.courseID == link.courseId { return true } return false } func showHandout() { if let topController = topMostViewController { environment?.router?.showHandoutsFromController(controller: topController, courseID: link.courseId ?? "") } } guard !controllerAlreadyDisplayed else { return } dismiss() { [weak self] in if let topController = self?.topMostViewController { self?.environment?.router?.showCourse(with: link, courseID: link.courseId ?? "", from: topController) } showHandout() } } private func showCourseAnnouncement(with link: DeepLink) { var controllerAlreadyDisplayed: Bool { if let topController = topMostViewController, let courseAnnouncementsViewController = topController as? CourseAnnouncementsViewController, courseAnnouncementsViewController.courseID == link.courseId { return true } return false } func showAnnouncement() { if let topController = topMostViewController { environment?.router?.showAnnouncment(from: topController, courseID: link.courseId ?? "") } } guard !controllerAlreadyDisplayed else { return } dismiss() { [weak self] in if let topController = self?.topMostViewController { self?.environment?.router?.showCourse(with: link, courseID: link.courseId ?? "", from: topController) } showAnnouncement() } } private func controllerAlreadyDisplayed(for type: DeepLinkType) -> Bool { guard let topViewController = topMostViewController else { return false } return linkType(for: topViewController) == type } private func dismiss(completion: @escaping DismissCompletion) { if let rootController = UIApplication.shared.keyWindow?.rootViewController, rootController.presentedViewController != nil { rootController.dismiss(animated: false, completion: completion) } else { completion() } } private func isDiscovery(type: DeepLinkType) -> Bool { return (type == .courseDiscovery || type == .courseDetail || type == .programDiscovery || type == .programDiscoveryDetail || type == .degreeDiscovery || type == .degreeDiscoveryDetail) } private func navigateToDeepLink(with type: DeepLinkType, link: DeepLink) { if isDiscovery(type: type) { showDiscovery(with: link) } else if !isUserLoggedin() { showLoginScreen() return } switch type { case .courseDashboard, .courseVideos, .discussions, .courseDates: showCourseDashboardViewController(with: link) break case .program: guard environment?.config.programConfig.enabled ?? false else { return } showPrograms(with: link) break case .programDetail: guard environment?.config.programConfig.enabled ?? false else { return } showProgramDetail(with: link) break case .account: showAccountViewController(with: link) break case .profile: showProfile(with: link) break case .discussionTopic: showDiscussionTopic(with: link) break case .discussionPost: showDiscussionResponses(with: link) break case .discussionComment: showdiscussionComments(with: link) case .courseHandout: showCourseHandout(with: link) break case .courseAnnouncement: showCourseAnnouncement(with: link) break default: break } } }
cecf83e378d305c4d0e4957803b3f1dc
43.413725
212
0.624785
false
false
false
false
mykoma/NetworkingLib
refs/heads/master
Demo/NetworkingDemo/NetworkingDemo/RemoteServerTransaction.swift
mit
1
// // RemoteServerTransaction.swift // NetworkingDemo // // Created by Apple on 2017/8/17. // Copyright © 2017年 Goluk. All rights reserved. // import UIKit import Networking class RemoteServerTransaction: HttpTransaction { override func baseServerUrl() -> String { return "https://test2bservice.goluk.cn" } override func requestHeaders() -> [String: String] { var superHeaders = super.requestHeaders() superHeaders["xieyi"] = "100" superHeaders["commostag"] = "ios" superHeaders["commuid"] = "5baac280ea834a509873d86de4495c0a" superHeaders["commwifi"] = "1" // superHeaders["commlon"] = String(BMLocationService.sharedInstance.getPosition().longitude) // superHeaders["commlat"] = String(BMLocationService.sharedInstance.getPosition().latitude) superHeaders["commmid"] = "123" // superHeaders["commlocale"] = NSLocale.currentLocale().localeIdentifier superHeaders["commappversion"] = "1.0.0" // superHeaders["commdevmodel"] = UIDevice.currentDevice().model // superHeaders["commsysversion"] = UIDevice.currentDevice().systemVersion // superHeaders["commipcversion"] = AppSettings.sharedInstance()?.recentDeviceSoftVersion // superHeaders["commhdtype"] = AppSettings.sharedInstance()?.recentDeviceType // let dateFormatter = DateFormatter() dateFormatter.locale = NSLocale.system dateFormatter.dateFormat = "yyyyMMddHHmmssSSS" let timestamp = dateFormatter.string(from: Date.init()) superHeaders["commtimestamp"] = timestamp if let ticket = self.genTicket(timestamp: timestamp) { superHeaders["commticket"] = ticket } return superHeaders } private func genTicket(timestamp: String) -> String? { let uuid = "5baac280ea834a509873d86de4495c0a" guard let UUIDString = UIDevice.current.identifierForVendor?.uuidString else { return nil } let key = "7f5699a9892d44fa8bbc928d84cd3ffa" let value = "u=\(uuid)&m=\(UUIDString)&t=\(timestamp)" let result = CocoaSecurity.hmacSha256(value, hmacKey: key) return result?.hex } }
c4fe02d1ed6a43b1960533ca1d9130cf
38.122807
100
0.665919
false
false
false
false
pekoto/fightydot
refs/heads/master
FightyDot/FightyDot/Constants.swift
mit
1
// // Constants.swift // FightyDot // // Created by Graham McRobbie on 08/12/2016. // Copyright © 2016 Graham McRobbie. All rights reserved. // import UIKit struct Constants { struct AlertMessages { static let won = "won!" static let playAgain = "Tap Play Again to, well, you know..." static let errorTitle = "Oh no!" static let errorMsg = "I'm sorry to say this, but something went wrong. A developer has been notified. Meanwhile, let's count this as a win :)" } struct AnimationKeys { static let glowingShadow = "glowingShadow" static let locations = "locations" static let pop = "pop" } // The board looks like this: // // 0) 0---------1---------2 // | | | // 2) | 3------4------5 | // | | | | | // 3) | | 6--7--8 | | // | | | | | | // 4) 9--10--11 12--13-14 // | | | | | | // 5) | | 15-16-17 | | // | | | | | // 6) | 18-----19-----20 | // | | | // 7) 21--------22-------23 struct BoardSetup { static let nodeNeighbours = [ [1, 9], // Node 0 [0, 2, 4], // Node 1 [1, 14], // Node 2 [4, 10], // Node 3 [1, 3, 5, 7], // Node 4 [4, 13], // Node 5 [7, 11], // Node 6 [4, 6, 8], // Node 7 [7, 12], // Node 8 [0, 10, 21], // Node 9 [3, 9, 11, 18], // Node 10 [6, 10, 15], // Node 11 [8, 13, 17], // Node 12 [5, 12, 14, 20], // Node 13 [2, 13, 23], // Node 14 [11, 16], // Node 15 [15, 17, 19], // Node 16 [12, 16], // Node 17 [10, 19], // Node 18 [16, 18, 20, 22], // Node 19 [13, 19], // Node 20 [9, 22], // Node 21 [19, 21, 23], // Node 22 [14, 22] // Node 23 ] static let millNodes = [ // Horizontal mills, left to right [0, 1, 2], // Node 0 [3, 4, 5], // Node 1 [6, 7, 8], // Node 2 [9, 10, 11], // Node 3 [12, 13, 14], // Node 4 [15, 16, 17], // Node 5 [18, 19, 20], // Node 6 [21, 22, 23], // Node 7 // Vertical mills, top to bottom [0, 9, 21], // Node 8 [3, 10, 18], // Node 9 [6, 11, 15], // Node 10 [1, 4, 7], // Node 11 [16, 19, 22], // Node 12 [8, 12, 17], // Node 13 [5, 13, 20], // Node 14 [2, 14, 23] // Node 15 ] // These are arguably the best starting nodes static let intersections = [4, 10, 13, 19] } struct Colours { static let darkBlue = UIColor(red: 42.0/255.0, green: 106.0/255.0, blue: 185.0/255.0, alpha: 1.0) static let lightBlue = UIColor(red: 83.0/255.0, green: 161.0/255.0, blue: 221.0/255.0, alpha: 1.0) static let defaultGlowColour = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.7) static let emptyMillColour = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.3) static let greenMillColour = UIColor(red: 112.0/255.0, green: 183.0/255.0, blue: 95.0/255.0, alpha: 1.0) static let redMillColour = UIColor(red: 222.0/255.0, green: 104.0/255.0, blue: 104.0/255.0, alpha: 1.0) } struct Constraints { static let activeMillThickness = CGFloat(2.0) static let defaultMillThickness = CGFloat(1.0) static let heightId = "height" static let widthId = "width" } struct ErrorCodes { static let invalidNodeId = "A00001" static let invalidState = "A00002" static let missingNodeTag = "A00003" static let nodeCastFailed = "A00004" static let unknown = "Z99999" } struct FirebaseEvents { static let boardState = "board_state" static let engineState = "engine_state" static let gameComplete = "game_complete" static let playerOneState = "player_1_state" static let playerTwoState = "player_2_state" static let soundToggled = "sound_toggled" } struct FontNames { static let light = "Lato-Light" static let regular = "Lato-Regular" static let bold = "Lato-Bold" } struct GameplayNumbers { static let piecesInMill = 3 static let startingPieces = 9 //1 //9 // Use LHS comment values to test moving static let flyingThreshold = 3 //0 //3 static let loseThreshold = 2 //0 //2 static let numOfNodes = 24 static let verticalMillStartIndex = 8 } struct Help { static let aiTurn = "\(PlayerData.defaultAIName) is moving..." static let placePiece = "Tap an empty spot to place a piece" static let movePiece_Select = "Select a piece to move" static let movePiece_Selected = "Drag your piece to a glowing spot" static let movePiece_Selected_CanFly = "Drag your piece to a glowing spot" static let takePiece = "Choose one of your opponent's pieces to take" static let gameWon = "Game won!" static let errorState = "Oops!" } struct PieceDics { static let imgColours: [UIImage: UIColor] = [ #imageLiteral(resourceName: "empty-node"): Constants.Colours.emptyMillColour, #imageLiteral(resourceName: "green-piece"): Constants.Colours.greenMillColour, #imageLiteral(resourceName: "red-piece"): Constants.Colours.redMillColour ] static let nodeImgs: [PieceColour: UIImage] = [ PieceColour.none: #imageLiteral(resourceName: "empty-node"), PieceColour.green: #imageLiteral(resourceName: "green-piece"), PieceColour.red: #imageLiteral(resourceName: "red-piece") ] static let pieceColours: [PieceColour: UIColor] = [ PieceColour.none: Constants.Colours.emptyMillColour, PieceColour.green: Constants.Colours.greenMillColour, PieceColour.red: Constants.Colours.redMillColour ] } struct PlayerData { static let defaultAIName = "AI" static let defaultPvpP1Name = "Player 1" static let defaultPvpP2Name = "Player 2" } struct Settings { static let difficulty = "difficulty" static let muteSounds = "muteSounds" } struct Sfx { static let startGame = "start-game" static let placePiece = "place-piece" static let millFormed = "mill-formed" static let pieceLost = "lose-piece" static let dragStart = "drag-start" static let dragCancel = "drag-cancel" static let gameOver = "game-over" } struct Tips { static let makeMove = "Tip: Get 3 in a row to take your opponent's piece!" static let canFly = "Tip: When you only have 3 pieces left, you can move to anywhere on the board!" static let canTakePiece = "Tip: You can't take pieces in a row until all other pieces have been taken first." static let restart = "Tap the X in the upper-right to play again." static let apology = "I'm terribly sorry about this, but something went wrong.\n\(restart)." } struct View { static let alertOverlayAlpha = CGFloat(0.6) static let alertVCStoryboardId = "AlertVC" static let cornerRadius = CGFloat(10.0) static let tapGestureRecognizerIndex = 0 static let dragGestureRecognizerIndex = 1 } // To ensure MiniMax/NegaMax algorithms choose at least 1 move when all possible moves are winning moves, // we make the winning scores slighty less than Int.max/Int.min. // redWin is +2 to make the scores more "symmetrical", and to stop issues when swapping // alpha/beta during negamax pruning. (In Swift 3, Int.max != Int.min * -1) struct WinScores { static let greenWin = Int.max-1 static let redWin = Int.min+2 } }
9eaed844a26f26b2a41b0c25c9b15dc7
37.474886
151
0.525042
false
false
false
false
QuarkX/Quark
refs/heads/master
Sources/Quark/Core/Data/Data.swift
mit
1
@_exported import struct Foundation.Data public typealias Byte = UInt8 public protocol DataInitializable { init(data: Data) throws } public protocol DataRepresentable { var data: Data { get } } extension Data : DataRepresentable { public var data: Data { return self } } public protocol DataConvertible : DataInitializable, DataRepresentable {} #if os(Linux) extension Data : RangeReplaceableCollection { public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element { // Calculate this once, it may not be O(1) let replacementCount : Int = numericCast(newElements.count) let currentCount = self.count let subrangeCount = subrange.count if currentCount < subrange.lowerBound + subrangeCount { if subrangeCount == 0 { preconditionFailure("location \(subrange.lowerBound) exceeds data count \(currentCount)") } else { preconditionFailure("range \(subrange) exceeds data count \(currentCount)") } } let resultCount = currentCount - subrangeCount + replacementCount if resultCount != currentCount { // This may realloc. // In the future, if we keep the malloced pointer and count inside this struct/ref instead of deferring to NSData, we may be able to do this more efficiently. self.count = resultCount } let shift = resultCount - currentCount let start = subrange.lowerBound self.withUnsafeMutableBytes { (bytes : UnsafeMutablePointer<UInt8>) -> () in if shift != 0 { let destination = bytes + start + replacementCount let source = bytes + start + subrangeCount memmove(destination, source, currentCount - start - subrangeCount) } if replacementCount != 0 { newElements._copyContents(initializing: bytes + start) } } } } #endif extension Data { public init(_ string: String) { self = Data(string.utf8) } } extension String : DataConvertible { public init(data: Data) throws { guard let string = String(data: data, encoding: String.Encoding.utf8) else { throw StringError.invalidString } self = string } public var data: Data { return Data(self) } } extension Data { public func hexadecimalString(inGroupsOf characterCount: Int = 0) -> String { var string = "" for (index, value) in self.enumerated() { if characterCount != 0 && index > 0 && index % characterCount == 0 { string += " " } string += (value < 16 ? "0" : "") + String(value, radix: 16) } return string } public var hexadecimalDescription: String { return hexadecimalString(inGroupsOf: 2) } }
de59c44ed140651a171f03242823d835
30.572917
194
0.617948
false
false
false
false
CodaFi/swift
refs/heads/master
stdlib/public/Darwin/Dispatch/Block.swift
apache-2.0
9
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_implementationOnly import _SwiftDispatchOverlayShims public struct DispatchWorkItemFlags : OptionSet, RawRepresentable { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let barrier = DispatchWorkItemFlags(rawValue: 0x1) @available(macOS 10.10, iOS 8.0, *) public static let detached = DispatchWorkItemFlags(rawValue: 0x2) @available(macOS 10.10, iOS 8.0, *) public static let assignCurrentContext = DispatchWorkItemFlags(rawValue: 0x4) @available(macOS 10.10, iOS 8.0, *) public static let noQoS = DispatchWorkItemFlags(rawValue: 0x8) @available(macOS 10.10, iOS 8.0, *) public static let inheritQoS = DispatchWorkItemFlags(rawValue: 0x10) @available(macOS 10.10, iOS 8.0, *) public static let enforceQoS = DispatchWorkItemFlags(rawValue: 0x20) } // NOTE: older overlays had Dispatch.DispatchWorkItem as the ObjC name. // The two must coexist, so it was renamed. The old name must not be // used in the new runtime. _TtC8Dispatch17_DispatchWorkItem is the // mangled name for Dispatch._DispatchWorkItem. @available(macOS 10.10, iOS 8.0, *) @_objcRuntimeName(_TtC8Dispatch17_DispatchWorkItem) public class DispatchWorkItem { internal var _block: _DispatchBlock public init(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], block: @escaping @convention(block) () -> Void) { _block = _swift_dispatch_block_create_with_qos_class( __dispatch_block_flags_t(rawValue: flags.rawValue), qos.qosClass.rawValue, Int32(qos.relativePriority), block) } // Used by DispatchQueue.synchronously<T> to provide a path through // dispatch_block_t, as we know the lifetime of the block in question. internal init(flags: DispatchWorkItemFlags = [], noescapeBlock: () -> Void) { _block = _swift_dispatch_block_create_noescape( __dispatch_block_flags_t(rawValue: flags.rawValue), noescapeBlock) } public func perform() { _block() } public func wait() { _ = _swift_dispatch_block_wait(_block, DispatchTime.distantFuture.rawValue) } public func wait(timeout: DispatchTime) -> DispatchTimeoutResult { return _swift_dispatch_block_wait(_block, timeout.rawValue) == 0 ? .success : .timedOut } public func wait(wallTimeout: DispatchWallTime) -> DispatchTimeoutResult { return _swift_dispatch_block_wait(_block, wallTimeout.rawValue) == 0 ? .success : .timedOut } public func notify( qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], queue: DispatchQueue, execute: @escaping @convention(block) () -> Void) { if qos != .unspecified || !flags.isEmpty { let item = DispatchWorkItem(qos: qos, flags: flags, block: execute) _swift_dispatch_block_notify(_block, queue, item._block) } else { _swift_dispatch_block_notify(_block, queue, execute) } } public func notify(queue: DispatchQueue, execute: DispatchWorkItem) { _swift_dispatch_block_notify(_block, queue, execute._block) } public func cancel() { _swift_dispatch_block_cancel(_block) } public var isCancelled: Bool { return _swift_dispatch_block_testcancel(_block) != 0 } } /// The dispatch_block_t typealias is different from usual closures in that it /// uses @convention(block). This is to avoid unnecessary bridging between /// C blocks and Swift closures, which interferes with dispatch APIs that depend /// on the referential identity of a block. Particularly, dispatch_block_create. internal typealias _DispatchBlock = @convention(block) () -> Void
e89e02311b3aa3643e7e0b59d01b07d3
36.327103
130
0.708563
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
其他功能/MGImagePickerControllerTest/MGImagePickerControllerTest/ImagePickerController/MGPhotosPreviewController.swift
mit
1
// // MGPhotosPreviewController.swift // MGImagePickerControllerDemo // // Created by newunion on 2019/7/8. // Copyright © 2019 MG. All rights reserved. // import UIKit import Photos class MGPhotosPreviewController: UIViewController { /// 当前显示的资源对象 var showAsset: PHAsset = PHAsset() /// 展示图片的视图 lazy fileprivate var imageView: UIImageView = { let imageView = UIImageView() imageView.backgroundColor = .white imageView.contentMode = .scaleToFill imageView.layer.cornerRadius = 8.0 return imageView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //获得资源的宽度与高度的比例 let scale = CGFloat(showAsset.pixelHeight) * 1.0 / CGFloat(showAsset.pixelWidth) preferredContentSize = CGSize(width: view.bounds.width, height: view.bounds.width * scale) //添加 view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true imageView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true imageView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true imageView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true //约束布局 // imageView.snp.makeConstraints { (make) in // make.edges.equalToSuperview() // } //获取图片对象 MGPhotoHandleManager.asset(representionIn: showAsset, size: preferredContentSize) { (image, _) in self.imageView.image = image } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { print("\(self.self)deinit") } }
8137a098a1b536000febea68fced16bb
30.709677
105
0.646999
false
false
false
false
jamesjmtaylor/weg-ios
refs/heads/master
weg-ios/Models/Air.swift
mit
1
// // Air.swift // weg-ios // // Created by Taylor, James on 4/24/18. // Copyright © 2018 James JM Taylor. All rights reserved. // import Foundation import CoreData @objc(Air) class Air : NSManagedObject, Equipment { var type = EquipmentType.AIR enum CodingKeys: String, CodingKey { case id case name case desc = "description" case groupIconUrl case individualIconUrl case photoUrl case gun case agm case aam case asm case speed case auto case ceiling case weight } required convenience init(from decoder: Decoder) throws { guard let context = decoder.userInfo[CodingUserInfoKey.context!] as? NSManagedObjectContext else { fatalError() } guard let entity = NSEntityDescription.entity(forEntityName: "Air", in: context) else { fatalError() } self.init(entity: entity, insertInto: context) let container = try! decoder.container(keyedBy: CodingKeys.self) self.id = try container.decode(Int64.self, forKey: .id) self.name = try container.decodeIfPresent(String.self, forKey: .name) self.desc = try container.decodeIfPresent(String.self, forKey: .desc) self.groupIconUrl = try container.decodeIfPresent(String.self, forKey: .groupIconUrl) self.individualIconUrl = try container.decodeIfPresent(String.self, forKey: .individualIconUrl) self.photoUrl = try container.decodeIfPresent(String.self, forKey: .photoUrl) self.gun = try container.decodeIfPresent(Gun.self, forKey: .gun) self.agm = try container.decodeIfPresent(Gun.self, forKey: .agm) self.aam = try container.decodeIfPresent(Gun.self, forKey: .aam) self.asm = try container.decodeIfPresent(Gun.self, forKey: .asm) self.speed = try container.decode(Int64.self, forKey: .speed) self.auto = try container.decode(Int64.self, forKey: .auto) self.ceiling = try container.decode(Int64.self, forKey: .ceiling) self.weight = try container.decode(Int64.self, forKey: .weight) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(name, forKey: .name) try container.encode(desc, forKey: .desc) try container.encode(groupIconUrl, forKey: .groupIconUrl) try container.encode(individualIconUrl, forKey: .individualIconUrl) try container.encode(photoUrl, forKey: .photoUrl) try container.encode(gun, forKey: .gun) try container.encode(agm, forKey: .agm) try container.encode(aam, forKey: .aam) try container.encode(asm, forKey: .asm) try container.encode(speed, forKey: .speed) try container.encode(auto, forKey: .auto) try container.encode(ceiling, forKey: .ceiling) try container.encode(weight, forKey: .weight) } }
998bad941b35fab1d33fec5e9af61aa2
40.506849
121
0.660726
false
false
false
false
DylanModesitt/Verb
refs/heads/master
Verb/Verb/Community.swift
apache-2.0
1
// // Community.swift // Verb // // Created by dcm on 12/10/15. // Copyright © 2015 Verb. All rights reserved. // import Foundation import Parse /* @brief Create a new community given the desired name @init This method begins creates a new community object @param name The name of the community to be created @return The Community PFObject created */ class Community { /* note that a community does not create anything other than its community. It is the job of lower classes to create the relations with their parents. As in, verb must update the community, but community does not spur any update with the verb. This continues down the cascade. */ let community = PFObject(className: "Community") var name: String var communityDescription: String var numberOfMembers: Int var numberOfVerbs: Int var isPrivate: Bool init(givenName: String, isPrivate: Bool, givenDescription: String) throws { self.name = givenName self.communityDescription = givenDescription self.numberOfMembers = 1 self.numberOfVerbs = 0 self.isPrivate = isPrivate // Initialize the properties of the object community["name"] = name if let _ = PFUser.currentUser()?.objectId! { let relation = community.relationForKey("users") relation.addObject(PFUser.currentUser()!) let relation2 = PFUser.currentUser()?.relationForKey("communities") relation2?.addObject(community) } else { if(UserAPI().isLoggedIn() == false) { throw errors.failureToGetUser } else { throw errors.failureToSaveData } } community["description"] = communityDescription community["numberOfMembers"] = numberOfMembers community["numberOfVerbs"] = numberOfVerbs community["isPrivate"] = isPrivate // Attempt to save directly. If not, save the object to the server eventually do { try community.save() try PFUser.currentUser()!.save() } catch { community.saveEventually() PFUser.currentUser()!.saveEventually() throw errors.failureToSaveData } } // @returns The community PFObject func getCommunity() -> PFObject { return community } // @returns the community's objectId func getCommunityObjectID() -> String? { if let _ = community.objectId { return community.objectId! } else { return nil } } }
c83a5b109ddceb7668e5fab700939cfb
27.168421
114
0.613976
false
false
false
false
darwin/textyourmom
refs/heads/master
TextYourMom/Brain.swift
mit
1
import UIKit protocol BrainDelegate { func remindCallMomFromAirport(city:String, _ airportName:String) } class Brain { var delegate: BrainDelegate? var state = AirportsVisitorState() init() { } func reportAirportVisit(airportId: AirportId) { if let airport = masterController.airportsProvider.lookupAirport(airportId) { model.lastReportedAirport = airport.name delegate?.remindCallMomFromAirport(airport.city, airport.name) } else { log("unable to lookup airport #\(airportId)") } } } // MARK: AirportsWatcherDelegate extension Brain : AirportsWatcherDelegate { func visitorPotentialChangeInState(newState: AirportsVisitorState) { let diff = AirportsVisitorStateDiff(oldState:state, newState:newState) if diff.empty { return } log("brain: state changed \(diff)") state = newState // new state should be stored in the model model.visitorState = state.serialize() if supressNextStateChangeReport { log("supressNextStateChangeReport active => bail out") supressNextStateChangeReport = false return } // we are only interested in airports where user was suddenly teleported in // in other words: the airport state changed from .None to .Inner var candidates = [AirportId]() for (id, change) in diff.diff { if change.before == .None && change.after == .Inner { candidates.append(id) } } if candidates.count == 0 { log(" no teleportations detected => bail out") return } // in case we got multiple simultaneous teleportations // report only airport with lowest id candidates.sort({$0 < $1}) log(" got candidates \(candidates), reporting the first one") reportAirportVisit(candidates[0]) } }
350193d814dfe4a176bc113680458493
28.542857
85
0.59381
false
false
false
false
ParsePlatform/Parse-SDK-iOS-OSX
refs/heads/master
ParseUI/ParseUIDemo/Swift/CustomViewControllers/QueryCollectionViewController/DeletionCollectionViewController.swift
bsd-3-clause
1
// // DeletionCollectionViewController.swift // ParseUIDemo // // Created by Richard Ross III on 5/14/15. // Copyright (c) 2015 Parse Inc. All rights reserved. // import UIKit import Parse import ParseUI import Bolts.BFTask class DeletionCollectionViewController: PFQueryCollectionViewController, UIAlertViewDelegate { convenience init(className: String?) { let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsetsMake(0.0, 10.0, 0.0, 10.0) layout.minimumInteritemSpacing = 5.0 self.init(collectionViewLayout: layout, className: className) title = "Deletion Collection" pullToRefreshEnabled = true objectsPerPage = 10 paginationEnabled = true collectionView?.allowsMultipleSelection = true navigationItem.rightBarButtonItems = [ editButtonItem, UIBarButtonItem(barButtonSystemItem: .add, target: self, action:#selector(addTodo)) ] } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let layout = collectionViewLayout as? UICollectionViewFlowLayout { let bounds = UIEdgeInsetsInsetRect(view.bounds, layout.sectionInset) let sideLength = min(bounds.width, bounds.height) / 2.0 - layout.minimumInteritemSpacing layout.itemSize = CGSize(width: sideLength, height: sideLength) } } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if (editing) { navigationItem.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .trash, target: self, action: #selector(deleteSelectedItems) ) } else { navigationItem.leftBarButtonItem = navigationItem.backBarButtonItem } } @objc func addTodo() { if #available(iOS 8.0, *) { let alertDialog = UIAlertController(title: "Add Todo", message: nil, preferredStyle: .alert) var titleTextField : UITextField? = nil alertDialog.addTextField(configurationHandler: { titleTextField = $0 }) alertDialog.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alertDialog.addAction(UIAlertAction(title: "Save", style: .default) { action in if let title = titleTextField?.text { let object = PFObject(className: self.parseClassName!, dictionary: [ "title": title ]) object.saveEventually().continueOnSuccessWith { _ -> AnyObject! in return self.loadObjects() } } }) present(alertDialog, animated: true, completion: nil) } else { let alertView = UIAlertView( title: "Add Todo", message: "", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Save" ) alertView.alertViewStyle = .plainTextInput alertView.textField(at: 0)?.placeholder = "Name" alertView.show() } } @objc func deleteSelectedItems() { guard let paths = collectionView?.indexPathsForSelectedItems else { return } removeObjects(at: paths) } // MARK - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath, object: PFObject?) -> PFCollectionViewCell? { let cell = super.collectionView(collectionView, cellForItemAt: indexPath, object: object) cell?.textLabel.textAlignment = .center cell?.textLabel.text = object?["title"] as? String cell?.contentView.layer.borderWidth = 1.0 cell?.contentView.layer.borderColor = UIColor.lightGray.cgColor return cell } // MARK - UIAlertViewDelegate @objc func alertView(_ alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if (buttonIndex == alertView.cancelButtonIndex) { return } if let title = alertView.textField(at: 0)?.text { let object = PFObject( className: self.parseClassName!, dictionary: [ "title": title ] ) object.saveEventually().continueOnSuccessWith { _ -> AnyObject! in return self.loadObjects() } } } }
1e6d7ea20297c66462bcf18867958f37
32.588235
150
0.610552
false
false
false
false
Ben21hao/edx-app-ios-new
refs/heads/master
Source/DiscussionNewPostViewController.swift
apache-2.0
1
// // DiscussionNewPostViewController.swift // edX // // Created by Tang, Jeff on 6/1/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit struct DiscussionNewThread { let courseID: String let topicID: String let type: DiscussionThreadType let title: String let rawBody: String } protocol DiscussionNewPostViewControllerDelegate : class { func newPostController(controller : DiscussionNewPostViewController, addedPost post: DiscussionThread) } public class DiscussionNewPostViewController: UIViewController, UITextViewDelegate, MenuOptionsViewControllerDelegate, InterfaceOrientationOverriding { public typealias Environment = protocol<DataManagerProvider, NetworkManagerProvider, OEXRouterProvider, OEXAnalyticsProvider> private let minBodyTextHeight : CGFloat = 66 // height for 3 lines of text private let environment: Environment private let growingTextController = GrowingTextViewController() private let insetsController = ContentInsetsController() @IBOutlet private var scrollView: UIScrollView! @IBOutlet private var backgroundView: UIView! @IBOutlet private var contentTextView: OEXPlaceholderTextView! @IBOutlet private var titleTextField: UITextField! @IBOutlet private var discussionQuestionSegmentedControl: UISegmentedControl! @IBOutlet private var bodyTextViewHeightConstraint: NSLayoutConstraint! @IBOutlet private var topicButton: UIButton! @IBOutlet private var postButton: SpinnerButton! @IBOutlet weak var contentTitleLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! private let loadController = LoadStateViewController() private let courseID: String private let topics = BackedStream<[DiscussionTopic]>() private var selectedTopic: DiscussionTopic? private var optionsViewController: MenuOptionsViewController? weak var delegate: DiscussionNewPostViewControllerDelegate? private let tapButton = UIButton() var titleTextStyle : OEXTextStyle{ return OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) } private var selectedThreadType: DiscussionThreadType = .Discussion { didSet { switch selectedThreadType { case .Discussion: self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout([titleTextStyle.attributedStringWithText(Strings.courseDashboardDiscussion), titleTextStyle.attributedStringWithText(Strings.asteric)]) postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle,withTitle: Strings.postDiscussion) contentTextView.accessibilityLabel = Strings.courseDashboardDiscussion case .Question: self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout([titleTextStyle.attributedStringWithText(Strings.question), titleTextStyle.attributedStringWithText(Strings.asteric)]) postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle, withTitle: Strings.postQuestion) contentTextView.accessibilityLabel = Strings.question } } } public init(environment: Environment, courseID: String, selectedTopic : DiscussionTopic?) { self.environment = environment self.courseID = courseID super.init(nibName: "DiscussionNewPostViewController", bundle: nil) let stream = environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID).topics topics.backWithStream(stream.map { return DiscussionTopic.linearizeTopics($0) } ) self.selectedTopic = selectedTopic } private var firstSelectableTopic : DiscussionTopic? { let selectablePredicate = { (topic : DiscussionTopic) -> Bool in topic.isSelectable } guard let topics = self.topics.value, selectableTopicIndex = topics.firstIndexMatching(selectablePredicate) else { return nil } return topics[selectableTopicIndex] } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func postTapped(sender: AnyObject) { postButton.enabled = false postButton.showProgress = true // create new thread (post) if let topic = selectedTopic, topicID = topic.id { let newThread = DiscussionNewThread(courseID: courseID, topicID: topicID, type: selectedThreadType ?? .Discussion, title: titleTextField.text ?? "", rawBody: contentTextView.text) let apiRequest = DiscussionAPI.createNewThread(newThread) environment.networkManager.taskForRequest(apiRequest) {[weak self] result in self?.postButton.enabled = true self?.postButton.showProgress = false if let post = result.data { self?.delegate?.newPostController(self!, addedPost: post) self?.dismissViewControllerAnimated(true, completion: nil) } else { DiscussionHelper.showErrorMessage(self, error: result.error) } } } } override public func viewDidLoad() { super.viewDidLoad() self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor(), NSFontAttributeName : UIFont(name: "OpenSans", size: 18.0)!] self.navigationItem.title = Strings.post let cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: nil, action: nil) cancelItem.oex_setAction { [weak self]() -> Void in self?.dismissViewControllerAnimated(true, completion: nil) } self.navigationItem.leftBarButtonItem = cancelItem contentTitleLabel.isAccessibilityElement = false titleLabel.isAccessibilityElement = false titleLabel.attributedText = NSAttributedString.joinInNaturalLayout([titleTextStyle.attributedStringWithText(Strings.title), titleTextStyle.attributedStringWithText(Strings.asteric)]) contentTextView.textContainer.lineFragmentPadding = 0 contentTextView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets contentTextView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes contentTextView.placeholderTextColor = OEXStyles.sharedStyles().neutralLight() contentTextView.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle) contentTextView.delegate = self titleTextField.accessibilityLabel = Strings.title self.view.backgroundColor = OEXStyles.sharedStyles().baseColor5() configureSegmentControl() titleTextField.defaultTextAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes setTopicsButtonTitle() let insets = OEXStyles.sharedStyles().standardTextViewInsets topicButton.titleEdgeInsets = UIEdgeInsetsMake(0, insets.left, 0, insets.right) topicButton.accessibilityHint = Strings.accessibilityShowsDropdownHint topicButton.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle) topicButton.localizedHorizontalContentAlignment = .Leading let dropdownLabel = UILabel() dropdownLabel.attributedText = Icon.Dropdown.attributedTextWithStyle(titleTextStyle) topicButton.addSubview(dropdownLabel) dropdownLabel.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(topicButton).offset(-insets.right) make.top.equalTo(topicButton).offset(topicButton.frame.size.height / 2.0 - 5.0) } topicButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in self?.showTopicPicker() }, forEvents: UIControlEvents.TouchUpInside) postButton.enabled = false titleTextField.oex_addAction({[weak self] _ in self?.validatePostButton() }, forEvents: .EditingChanged) self.growingTextController.setupWithScrollView(scrollView, textView: contentTextView, bottomView: postButton) self.insetsController.setupInController(self, scrollView: scrollView) // Force setting it to call didSet which is only called out of initialization context self.selectedThreadType = .Question loadController.setupInController(self, contentView: self.scrollView) topics.listen(self, success : {[weak self]_ in self?.loadedData() }, failure : {[weak self] error in self?.loadController.state = LoadState.failed(error) }) backgroundView.addSubview(tapButton) backgroundView.sendSubviewToBack(tapButton) tapButton.backgroundColor = UIColor.clearColor() tapButton.frame = CGRectMake(0, 0, backgroundView.frame.size.width, backgroundView.frame.size.height) tapButton.isAccessibilityElement = false tapButton.accessibilityLabel = Strings.accessibilityHideKeyboard tapButton.oex_addAction({[weak self] (sender) in self?.view.endEditing(true) }, forEvents: .TouchUpInside) } private func configureSegmentControl() { discussionQuestionSegmentedControl.removeAllSegments() let questionIcon = Icon.Question.attributedTextWithStyle(titleTextStyle) let questionTitle = NSAttributedString.joinInNaturalLayout([questionIcon, titleTextStyle.attributedStringWithText(Strings.question)]) let discussionIcon = Icon.Comments.attributedTextWithStyle(titleTextStyle) let discussionTitle = NSAttributedString.joinInNaturalLayout([discussionIcon, titleTextStyle.attributedStringWithText(Strings.discussion)]) let segmentOptions : [(title : NSAttributedString, value : DiscussionThreadType)] = [ (title : questionTitle, value : .Question), (title : discussionTitle, value : .Discussion), ] for i in 0..<segmentOptions.count { discussionQuestionSegmentedControl.insertSegmentWithAttributedTitle(segmentOptions[i].title, index: i, animated: false) discussionQuestionSegmentedControl.subviews[i].accessibilityLabel = segmentOptions[i].title.string } discussionQuestionSegmentedControl.oex_addAction({ [weak self] (control:AnyObject) -> Void in if let segmentedControl = control as? UISegmentedControl { let index = segmentedControl.selectedSegmentIndex let threadType = segmentOptions[index].value self?.selectedThreadType = threadType self?.updateSelectedTabColor() } else { assert(true, "Invalid Segment ID, Remove this segment index OR handle it in the ThreadType enum") } }, forEvents: UIControlEvents.ValueChanged) discussionQuestionSegmentedControl.tintColor = OEXStyles.sharedStyles().neutralDark() discussionQuestionSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName: OEXStyles.sharedStyles().neutralWhite()], forState: UIControlState.Selected) discussionQuestionSegmentedControl.selectedSegmentIndex = 0 updateSelectedTabColor() } private func updateSelectedTabColor() { // //UIsegmentControl don't Multiple tint color so updating tint color of subviews to match desired behaviour let subViews:NSArray = discussionQuestionSegmentedControl.subviews for i in 0..<subViews.count { if subViews.objectAtIndex(i).isSelected ?? false { let view = subViews.objectAtIndex(i) as! UIView view.tintColor = OEXStyles.sharedStyles().primaryBaseColor() } else { let view = subViews.objectAtIndex(i) as! UIView view.tintColor = OEXStyles.sharedStyles().neutralDark() } } } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.environment.analytics.trackDiscussionScreenWithName(OEXAnalyticsScreenCreateTopicThread, courseId: self.courseID, value: selectedTopic?.name, threadId: nil, topicId: selectedTopic?.id, responseID: nil) } override public func shouldAutorotate() -> Bool { return true } override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .AllButUpsideDown } private func loadedData() { loadController.state = topics.value?.count == 0 ? LoadState.empty(icon: .NoTopics, message : Strings.unableToLoadCourseContent) : .Loaded if selectedTopic == nil { selectedTopic = firstSelectableTopic } setTopicsButtonTitle() } private func setTopicsButtonTitle() { if let topic = selectedTopic, name = topic.name { let title = Strings.topic(topic: name) topicButton.setAttributedTitle(OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()).attributedStringWithText(title), forState: .Normal) } } func showTopicPicker() { if self.optionsViewController != nil { return } view.endEditing(true) self.optionsViewController = MenuOptionsViewController() self.optionsViewController?.delegate = self guard let courseTopics = topics.value else { //Don't need to configure an empty state here because it's handled in viewDidLoad() return } self.optionsViewController?.options = courseTopics.map { return MenuOptionsViewController.MenuOption(depth : $0.depth, label : $0.name ?? "") } self.optionsViewController?.selectedOptionIndex = self.selectedTopicIndex() self.view.addSubview(self.optionsViewController!.view) self.optionsViewController!.view.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(self.topicButton) make.leading.equalTo(self.topicButton) make.top.equalTo(self.topicButton.snp_bottom).offset(-3) // make.bottom.equalTo(self.view.snp_bottom) make.height.equalTo((self.optionsViewController?.options.count)! * 30) } self.optionsViewController?.view.alpha = 0.0 UIView.animateWithDuration(0.3) { self.optionsViewController?.view.alpha = 1.0 } } private func selectedTopicIndex() -> Int? { guard let selected = selectedTopic else { return 0 } return self.topics.value?.firstIndexMatching { return $0.id == selected.id } } public func textViewDidChange(textView: UITextView) { validatePostButton() growingTextController.handleTextChange() } public func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index : Int) -> Bool { return self.topics.value?[index].isSelectable ?? false } private func validatePostButton() { self.postButton.enabled = !(titleTextField.text ?? "").isEmpty && !contentTextView.text.isEmpty && self.selectedTopic != nil } func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int) { selectedTopic = self.topics.value?[index] if let topic = selectedTopic where topic.id != nil { setTopicsButtonTitle() UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, titleTextField); UIView.animateWithDuration(0.3, animations: { self.optionsViewController?.view.alpha = 0.0 }, completion: {[weak self](finished: Bool) in self?.optionsViewController?.view.removeFromSuperview() self?.optionsViewController = nil }) } } public override func viewDidLayoutSubviews() { self.insetsController.updateInsets() growingTextController.scrollToVisible() } func textFieldDidBeginEditing(textField: UITextField) { tapButton.isAccessibilityElement = true } func textFieldDidEndEditing(textField: UITextField) { tapButton.isAccessibilityElement = false } public func textViewDidBeginEditing(textView: UITextView) { tapButton.isAccessibilityElement = true } public func textViewDidEndEditing(textView: UITextView) { tapButton.isAccessibilityElement = false } } extension UISegmentedControl { //UIsegmentControl didn't support attributedTitle by default func insertSegmentWithAttributedTitle(title: NSAttributedString, index: NSInteger, animated: Bool) { let segmentLabel = UILabel() segmentLabel.backgroundColor = UIColor.clearColor() segmentLabel.textAlignment = .Center segmentLabel.attributedText = title segmentLabel.sizeToFit() self.insertSegmentWithImage(segmentLabel.toImage(), atIndex: 1, animated: false) } } extension UILabel { func toImage()-> UIImage? { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) self.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); return image; } } // For use in testing only extension DiscussionNewPostViewController { public func t_topicsLoaded() -> Stream<[DiscussionTopic]> { return topics } }
0341bcdd4e372b498ba0495a7e4b2cf9
43.102439
230
0.681506
false
false
false
false
optimizely/swift-sdk
refs/heads/master
Sources/Optimizely/OptimizelyError.swift
apache-2.0
1
// // Copyright 2019-2021, Optimizely, Inc. and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public enum OptimizelyError: Error { case generic // MARK: - Decision errors case sdkNotReady case featureKeyInvalid(_ key: String) case variableValueInvalid(_ key: String) case invalidJSONVariable // MARK: - Experiment case experimentKeyInvalid(_ key: String) case experimentIdInvalid(_ id: String) case experimentHasNoTrafficAllocation(_ key: String) case variationKeyInvalid(_ expKey: String, _ varKey: String) case variationIdInvalid(_ expKey: String, _ varKey: String) case variationUnknown(_ userId: String, _ key: String) case variableKeyInvalid(_ varKey: String, _ feature: String) case eventKeyInvalid(_ key: String) case eventBuildFailure(_ key: String) case eventTagsFormatInvalid case attributesKeyInvalid(_ key: String) case attributeValueInvalid(_ key: String) case attributeFormatInvalid case groupIdInvalid(_ id: String) case groupHasNoTrafficAllocation(_ key: String) case rolloutIdInvalid(_ id: String, _ feature: String) // MARK: - Audience Evaluation case conditionNoMatchingAudience(_ id: String) case conditionInvalidFormat(_ hint: String) case conditionCannotBeEvaluated(_ hint: String) case evaluateAttributeInvalidCondition(_ condition: String) case evaluateAttributeInvalidType(_ condition: String, _ value: Any, _ key: String) case evaluateAttributeValueOutOfRange(_ condition: String, _ key: String) case evaluateAttributeInvalidFormat(_ hint: String) case userAttributeInvalidType(_ condition: String) case userAttributeInvalidMatch(_ condition: String) case userAttributeNilValue(_ condition: String) case userAttributeInvalidName(_ condition: String) case nilAttributeValue(_ condition: String, _ key: String) case missingAttributeValue(_ condition: String, _ key: String) // MARK: - Bucketing case userIdInvalid case bucketingIdInvalid(_ id: UInt64) case userProfileInvalid // MARK: - Datafile Errors case datafileDownloadFailed(_ hint: String) case dataFileInvalid case dataFileVersionInvalid(_ version: String) case datafileSavingFailed(_ hint: String) case datafileLoadingFailed(_ hint: String) // MARK: - EventDispatcher Errors case eventDispatchFailed(_ reason: String) case eventDispatcherConfigError(_ reason: String) // MARK: - AudienceSegements Errors case invalidSegmentIdentifier case fetchSegmentsFailed(_ hint: String) case odpEventFailed(_ hint: String, _ canRetry: Bool) case odpNotIntegrated case odpNotEnabled case odpInvalidData } // MARK: - CustomStringConvertible extension OptimizelyError: CustomStringConvertible, ReasonProtocol { public var description: String { return "[Optimizely][Error] " + self.reason } public var localizedDescription: String { return description } var reason: String { var message: String switch self { case .generic: message = "Unknown reason." // DO NOT CHANGE these critical error messages - FSC will validate exact-wordings of these messages. case .sdkNotReady: message = "Optimizely SDK not configured properly yet." case .featureKeyInvalid(let key): message = "No flag was found for key \"\(key)\"." case .variableValueInvalid(let key): message = "Variable value for key \"\(key)\" is invalid or wrong type." case .invalidJSONVariable: message = "Invalid variables for OptimizelyJSON." // These error messages not validated by FSC case .experimentKeyInvalid(let key): message = "Experiment key (\(key)) is not in datafile. It is either invalid, paused, or archived." case .experimentIdInvalid(let id): message = "Experiment ID (\(id)) is not in datafile." case .experimentHasNoTrafficAllocation(let key): message = "No traffic allocation rules are defined for experiment (\(key))." case .variationKeyInvalid(let expKey, let varKey): message = "No variation key (\(varKey)) defined in datafile for experiment (\(expKey))." case .variationIdInvalid(let expKey, let varId): message = "No variation ID (\(varId)) defined in datafile for experiment (\(expKey))." case .variationUnknown(let userId, let key): message = "User (\(userId)) does not meet conditions to be in experiment/feature (\(key))." case .variableKeyInvalid(let varKey, let feature): message = "Variable with key (\(varKey)) associated with feature with key (\(feature)) is not in datafile." case .eventKeyInvalid(let key): message = "Event key (\(key)) is not in datafile." case .eventBuildFailure(let key): message = "Failed to create a dispatch event (\(key))" case .eventTagsFormatInvalid: message = "Provided event tags are in an invalid format." case .attributesKeyInvalid(let key): message = "Attribute key (\(key)) is not in datafile." case .attributeValueInvalid(let key): message = "Attribute value for (\(key)) is invalid." case .attributeFormatInvalid: message = "Provided attributes are in an invalid format." case .groupIdInvalid(let id): message = "Group ID (\(id)) is not in datafile." case .groupHasNoTrafficAllocation(let id): message = "No traffic allocation rules are defined for group (\(id))." case .rolloutIdInvalid(let id, let feature): message = "Invalid rollout ID (\(id)) attached to feature (\(feature))." case .conditionNoMatchingAudience(let id): message = "Audience (\(id)) is not in datafile." case .conditionInvalidFormat(let hint): message = "Condition has an invalid format (\(hint))." case .conditionCannotBeEvaluated(let hint): message = "Condition cannot be evaluated (\(hint))." case .evaluateAttributeInvalidCondition(let condition): message = "Audience condition (\(condition)) has an unsupported condition value. You may need to upgrade to a newer release of the Optimizely SDK." case .evaluateAttributeInvalidType(let condition, let value, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because a value of type (\(value)) was passed for user attribute (\(key))." case .evaluateAttributeValueOutOfRange(let condition, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because the number value for user attribute (\(key)) is not in the range [-2^53, +2^53]." case .evaluateAttributeInvalidFormat(let hint): message = "Evaluation attribute has an invalid format (\(hint))." case .userAttributeInvalidType(let condition): message = "Audience condition (\(condition)) uses an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK." case .userAttributeInvalidMatch(let condition): message = "Audience condition (\(condition)) uses an unknown match type. You may need to upgrade to a newer release of the Optimizely SDK." case .userAttributeNilValue(let condition): message = "Audience condition (\(condition)) evaluated to UNKNOWN because of null value." case .userAttributeInvalidName(let condition): message = "Audience condition (\(condition)) evaluated to UNKNOWN because of invalid attribute name." case .nilAttributeValue(let condition, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because a null value was passed for user attribute (\(key))." case .missingAttributeValue(let condition, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because no value was passed for user attribute (\(key))." case .userIdInvalid: message = "Provided user ID is in an invalid format." case .bucketingIdInvalid(let id): message = "Invalid bucketing ID (\(id))." case .userProfileInvalid: message = "Provided user profile object is invalid." case .datafileDownloadFailed(let hint): message = "Datafile download failed (\(hint))." case .dataFileInvalid: message = "Provided datafile is in an invalid format." case .dataFileVersionInvalid(let version): message = "Provided datafile version (\(version)) is not supported." case .datafileSavingFailed(let hint): message = "Datafile save failed (\(hint))." case .datafileLoadingFailed(let hint): message = "Datafile load failed (\(hint))." case .eventDispatchFailed(let hint): message = "Event dispatch failed (\(hint))." case .eventDispatcherConfigError(let hint): message = "EventDispatcher config error (\(hint))." case .invalidSegmentIdentifier: message = "Audience segments fetch failed (invalid identifier)" case .fetchSegmentsFailed(let hint): message = "Audience segments fetch failed (\(hint))." case .odpEventFailed(let hint, _): message = "ODP event send failed (\(hint))." case .odpNotIntegrated: message = "ODP is not integrated." case .odpNotEnabled: message = "ODP is not enabled." case .odpInvalidData: message = "ODP data is not valid." } return message } } // MARK: - LocalizedError (ObjC NSError) extension OptimizelyError: LocalizedError { public var errorDescription: String? { return self.reason } }
91db27c2c871e8655a1b1ccca69eeab7
59.207865
229
0.65606
false
false
false
false
jdkelley/Udacity-OnTheMap-ExampleApps
refs/heads/master
TheMovieManager-v1/TheMovieManager/TMDBAuthViewController.swift
mit
1
// // TMDBAuthViewController.swift // TheMovieManager // // Created by Jarrod Parkes on 2/11/15. // Copyright (c) 2015 Jarrod Parkes. All rights reserved. // import UIKit // MARK: - TMDBAuthViewController: UIViewController class TMDBAuthViewController: UIViewController { // MARK: Properties var urlRequest: NSURLRequest? = nil var requestToken: String? = nil var completionHandlerForView: ((success: Bool, errorString: String?) -> Void)? = nil // MARK: Outlets @IBOutlet weak var webView: UIWebView! // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() webView.delegate = self navigationItem.title = "TheMovieDB Auth" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(cancelAuth)) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) auth() } func auth() { if let urlRequest = urlRequest { webView.loadRequest(urlRequest) } } // MARK: Cancel Auth Flow func cancelAuth() { dismissViewControllerAnimated(true, completion: nil) } } // MARK: - TMDBAuthViewController: UIWebViewDelegate extension TMDBAuthViewController: UIWebViewDelegate { func webViewDidFinishLoad(webView: UIWebView) { if webView.request?.URL!.absoluteString == "\(TMDBClient.Constants.AuthorizationURL)\(requestToken!)\(TMDBClient.Methods.Allow)" { print("Authorized") dismissViewControllerAnimated(true) { self.completionHandlerForView?(success: true, errorString: nil) } } if webView.request!.URL!.absoluteString.containsString("https://www.themoviedb.org/account/") { auth() } } }
4e344089d1540536df3dd444573ad653
26.128571
138
0.634879
false
false
false
false
VicFrolov/Markit
refs/heads/master
iOS/Markit/Markit/NewListingTableViewController.swift
apache-2.0
1
// // NewListingTableViewController.swift // Markit // // Created by Victor Frolov on 9/25/16. // Copyright © 2016 Victor Frolov. All rights reserved. // import UIKit import Firebase class NewListingTableViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { let imagePicker: UIImagePickerController! = UIImagePickerController() var priceSelected = false var titleSelected = false var photoSelected = false var tagSelected = false var hubSelected = false var descriptionSelected = false var databaseRef: FIRDatabaseReference! var tagRef: FIRDatabaseReference! var hubRef: FIRDatabaseReference! var tagList: [String] = [String]() var hubList: [String] = [String]() @IBOutlet weak var price: UIButton! @IBOutlet weak var itemImage: UIImageView! @IBOutlet weak var itemTitle: UIButton! @IBOutlet weak var itemDescription: UIButton! @IBOutlet weak var tags: UIButton! @IBOutlet weak var hubs: UIButton! @IBOutlet weak var postButton: UIButton! @IBAction func takePicture(sender: UIButton) { if (UIImagePickerController.isSourceTypeAvailable(.camera)) { if (UIImagePickerController.isCameraDeviceAvailable(.rear)) { imagePicker.sourceType = .camera imagePicker.cameraCaptureMode = .photo present(imagePicker, animated: true, completion: {}) } } else { imagePicker.allowsEditing = true imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) photoSelected = true } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { var selectedImageFromPicker: UIImage? if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage { selectedImageFromPicker = editedImage } else if let originalImage: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage { selectedImageFromPicker = originalImage } if let selectedImage = selectedImageFromPicker { itemImage.contentMode = .scaleAspectFill itemImage.image = selectedImage itemImage.layer.zPosition = 1 photoSelected = true if (!priceSelected) { price.layer.zPosition = 2 } } imagePicker.dismiss(animated: true, completion: {}) if photoSelected && priceSelected { price.layer.zPosition = 2 itemImage.layer.zPosition = 1 } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func getTags () { tagRef.observe(.childAdded, with: { (snapshot) -> Void in if snapshot.value is Int { if (snapshot.value as! Int?)! > 7 { self.tagList.append(snapshot.key.trim()) } } }) } func getHubs () { hubRef.observe(.childAdded, with: { (snapshot) -> Void in if snapshot.value! is Int { self.hubList.append(snapshot.key.trim()) } }) } @IBAction func unwindPrice(segue: UIStoryboardSegue) { let priceVC = segue.source as? AddPriceViewController var userPrice = (priceVC?.priceLabel.text)! if (userPrice != "...") { userPrice = "$" + userPrice let blingedOutUserPrice = NSMutableAttributedString(string: userPrice as String) blingedOutUserPrice.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 255, green: 218, blue: 0, alpha: 0.7), range: NSRange(location:0,length:1)) price.setAttributedTitle(blingedOutUserPrice, for: .normal) price.backgroundColor = UIColor(red: 100/255, green: 100/255, blue: 100/255, alpha: 0.5) priceSelected = true } } @IBAction func unwindAddTitle(segue: UIStoryboardSegue) { let titleVC = segue.source as? AddTitleViewController let userTitle = titleVC?.itemTitle.text! if userTitle != "" { itemTitle.setAttributedTitle(NSMutableAttributedString(string: userTitle! as String), for: .normal) titleSelected = true } print("it's running! and here's the title: \(userTitle!)") } @IBAction func unwindDescription(segue: UIStoryboardSegue) { let descVC = segue.source as? AddDescriptionViewController let userDescription = descVC?.itemDescription.text if userDescription != "" { itemDescription.setAttributedTitle(NSMutableAttributedString(string: userDescription! as String), for: .normal) descriptionSelected = true } print("description accepted: \(userDescription!)") } @IBAction func unwindTag(segue: UIStoryboardSegue) { let tagVC = segue.source as? AddTagsViewController let userTags = tagVC?.tagsField.text?.lowercased() if userTags != "" { tags.setAttributedTitle(NSMutableAttributedString(string: userTags! as String), for: .normal) tagSelected = true } print("tags accepted: \(userTags!)") } @IBAction func unwindAddHubs(segue: UIStoryboardSegue) { let hubVC = segue.source as? AddHubViewController let userHubs = hubVC?.hubsField.text if userHubs != "" { hubs.setAttributedTitle(NSMutableAttributedString(string: userHubs! as String), for: .normal) hubSelected = true } print("hubs accepted: \(userHubs!)") } override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self postButton.isUserInteractionEnabled = false postButton.alpha = 0.1 postButton.layer.cornerRadius = 10 databaseRef = FIRDatabase.database().reference() tagRef = databaseRef.child("tags") hubRef = databaseRef.child("hubs") getTags() getHubs() } override func viewDidAppear(_ animated: Bool) { if priceSelected && titleSelected && photoSelected && tagSelected && hubSelected && descriptionSelected { postButton.isUserInteractionEnabled = true postButton.alpha = 1.0 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "addTagSegue" { let addTagVC = segue.destination as! AddTagsViewController addTagVC.tagList = self.tagList } else if segue.identifier == "addHubSegue" { let addHubVC = segue.destination as! AddHubViewController addHubVC.hubList = self.hubList } } @IBAction func cancelToNewListings(segue: UIStoryboardSegue) {} }
896c6c1bb41abac3340f3b5e676f87e3
34.728155
172
0.61087
false
false
false
false
JaySonGD/SwiftDayToDay
refs/heads/master
Swift - 闭包/Swift - 闭包/ViewController.swift
mit
1
// // ViewController.swift // Swift - 闭包 // // Created by czljcb on 16/2/26. // Copyright © 2016年 czljcb. All rights reserved. // import UIKit class ViewController: UIViewController { var tool : HTTPTool? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let tool = HTTPTool() self.tool = tool // MARK: - 闭包格式 (参数类型) -> (返回值类型) // var myBlock : ( (String) -> () )? // MARK: - 常用写法 // tool.load { (data : String) -> () in // // print(data) // } // // MARK: - 方式2 // tool.load ({ (data : String) -> () in // // print("888\(data)") // }) // MARK: - 方式3 // tool.load (){ (data : String) -> () in // print("9999\(data)") // self.view.backgroundColor = UIColor.orangeColor() // } // MARK: - 最直接方式 // weak var weakSelf : ViewController? = self // // // tool.load (){ (data : String) -> () in // print("9999\(data)") // weakSelf!.view.backgroundColor = UIColor.orangeColor() // } // MARK: - 最直接方式(简写) // tool.load (){[weak self] (data : String) -> () in // print("9999\(data)") // self!.view.backgroundColor = UIColor.orangeColor() // } // MARK: - 不安全方式(viewController delloc 时 指针不清空,永远指着那一块地址) tool.load (){[unowned self] (data : String) -> () in print("9999\(data)") self.view.backgroundColor = UIColor.orangeColor() } } // MARK: - 相当于OC delloc deinit{ print("delloc") } }
ff86a25a782c53f232d1e472ded11acf
23.682353
80
0.396568
false
false
false
false
iOS-mamu/SS
refs/heads/master
P/PotatsoModel/Rule.swift
mit
1
// // Rule.swift // Potatso // // Created by LEI on 4/6/16. // Copyright © 2016 TouchingApp. All rights reserved. // import RealmSwift import PotatsoBase private let ruleValueKey = "value"; private let ruleActionKey = "action"; public enum RuleType: String { case URLMatch = "URL-MATCH" case URL = "URL" case Domain = "DOMAIN" case DomainMatch = "DOMAIN-MATCH" case DomainSuffix = "DOMAIN-SUFFIX" case GeoIP = "GEOIP" case IPCIDR = "IP-CIDR" } extension RuleType { public static func fromInt(_ intValue: Int) -> RuleType? { switch intValue { case 1: return .Domain case 2: return .DomainSuffix case 3: return .DomainMatch case 4: return .URL case 5: return .URLMatch case 6: return .GeoIP case 7: return .IPCIDR default: return nil } } } extension RuleType: CustomStringConvertible { public var description: String { return rawValue } } public enum RuleAction: String { case Direct = "DIRECT" case Reject = "REJECT" case Proxy = "PROXY" } extension RuleAction { public static func fromInt(_ intValue: Int) -> RuleAction? { switch intValue { case 1: return .Direct case 2: return .Reject case 3: return .Proxy default: return nil } } } extension RuleAction: CustomStringConvertible { public var description: String { return rawValue } } public enum RuleError: Error { case invalidRule(String) } //extension RuleError: CustomStringConvertible { // // public var description: String { // switch self { // case .InvalidRule(let rule): // return "Invalid rule - \(rule)" // } // } // //} // //public final class Rule: BaseModel { // // public dynamic var typeRaw = "" // public dynamic var content = "" // public dynamic var order = 0 // public let rulesets = LinkingObjects(fromType: RuleSet.self, property: "rules") // //} // //extension Rule { // // public var type : RuleType { // get { // return RuleType(rawValue: typeRaw) ?? .DomainSuffix // } // set(v) { // typeRaw = v.rawValue // } // } // // public var action : RuleAction { // let json = content.jsonDictionary() // if let raw = json?[ruleActionKey] as? String { // return RuleAction(rawValue: raw) ?? .Proxy // } // return .Proxy // } // // public var value : String { // let json = content.jsonDictionary() // return json?[ruleValueKey] as? String ?? "" // } // //} // public final class Rule { public var type: RuleType public var value: String public var action: RuleAction public convenience init(str: String) throws { var ruleStr = str.replacingOccurrences(of: "\t", with: "") ruleStr = ruleStr.replacingOccurrences(of: " ", with: "") let parts = ruleStr.components(separatedBy: ",") guard parts.count >= 3 else { throw RuleError.invalidRule(str) } let actionStr = parts[2].uppercased() let typeStr = parts[0].uppercased() let value = parts[1] guard let type = RuleType(rawValue: typeStr), let action = RuleAction(rawValue: actionStr), value.characters.count > 0 else { throw RuleError.invalidRule(str) } self.init(type: type, action: action, value: value) } public init(type: RuleType, action: RuleAction, value: String) { self.type = type self.value = value self.action = action } public convenience init?(json: [String: AnyObject]) { guard let typeRaw = json["type"] as? String, let type = RuleType(rawValue: typeRaw) else { return nil } guard let actionRaw = json["action"] as? String, let action = RuleAction(rawValue: actionRaw) else { return nil } guard let value = json["value"] as? String else { return nil } self.init(type: type, action: action, value: value) } public var description: String { return "\(type), \(value), \(action)" } public var json: [String: AnyObject] { return ["type": type.rawValue as AnyObject, "value": value as AnyObject, "action": action.rawValue as AnyObject] } } // // //public func ==(lhs: Rule, rhs: Rule) -> Bool { // return lhs.uuid == rhs.uuid //}
6898005a5f50f4f4e877c64c80f181a4
23.375
133
0.563248
false
false
false
false
gerardogrisolini/Webretail
refs/heads/master
Sources/Webretail/Models/Category.swift
apache-2.0
1
// // Category.swift // Webretail // // Created by Gerardo Grisolini on 17/02/17. // // import Foundation import StORM import mwsWebretail class Category: PostgresSqlORM, Codable { public var categoryId : Int = 0 public var categoryIsPrimary : Bool = false public var categoryName : String = "" public var categoryDescription: [Translation] = [Translation]() public var categoryMedia: Media = Media() public var categorySeo : Seo = Seo() public var categoryCreated : Int = Int.now() public var categoryUpdated : Int = Int.now() private enum CodingKeys: String, CodingKey { case categoryId case categoryIsPrimary case categoryName case categoryDescription = "translations" case categoryMedia = "media" case categorySeo = "seo" } open override func table() -> String { return "categories" } open override func tableIndexes() -> [String] { return ["categoryName"] } open override func to(_ this: StORMRow) { categoryId = this.data["categoryid"] as? Int ?? 0 categoryIsPrimary = this.data["categoryisprimary"] as? Bool ?? true categoryName = this.data["categoryname"] as? String ?? "" let decoder = JSONDecoder() var jsonData: Data if let translates = this.data["categorydescription"] { jsonData = try! JSONSerialization.data(withJSONObject: translates, options: []) categoryDescription = try! decoder.decode([Translation].self, from: jsonData) } if let media = this.data["categorymedia"] { jsonData = try! JSONSerialization.data(withJSONObject: media, options: []) categoryMedia = try! decoder.decode(Media.self, from: jsonData) } if let seo = this.data["categoryseo"] { jsonData = try! JSONSerialization.data(withJSONObject: seo, options: []) categorySeo = try! decoder.decode(Seo.self, from: jsonData) } categoryCreated = this.data["categorycreated"] as? Int ?? 0 categoryUpdated = this.data["categoryupdated"] as? Int ?? 0 } func rows() -> [Category] { var rows = [Category]() for i in 0..<self.results.rows.count { let row = Category() row.to(self.results.rows[i]) rows.append(row) } return rows } override init() { super.init() } required init(from decoder: Decoder) throws { super.init() let container = try decoder.container(keyedBy: CodingKeys.self) categoryId = try container.decode(Int.self, forKey: .categoryId) categoryIsPrimary = try container.decode(Bool.self, forKey: .categoryIsPrimary) categoryName = try container.decode(String.self, forKey: .categoryName) categoryDescription = try container.decodeIfPresent([Translation].self, forKey: .categoryDescription) ?? [Translation]() categoryMedia = try container.decodeIfPresent(Media.self, forKey: .categoryMedia) ?? Media() categorySeo = try container.decodeIfPresent(Seo.self, forKey: .categorySeo) ?? Seo() } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(categoryId, forKey: .categoryId) try container.encode(categoryIsPrimary, forKey: .categoryIsPrimary) try container.encode(categoryName, forKey: .categoryName) try container.encode(categoryDescription, forKey: .categoryDescription) try container.encode(categoryMedia, forKey: .categoryMedia) try container.encode(categorySeo, forKey: .categorySeo) } fileprivate func addCategory(name: String, description: String, isPrimary: Bool) throws { let translation = Translation() translation.country = "EN" translation.value = description let item = Category() item.categoryName = name item.categoryIsPrimary = isPrimary item.categoryDescription.append(translation) item.categorySeo.permalink = item.categoryName.permalink() item.categoryCreated = Int.now() item.categoryUpdated = Int.now() try item.save() } func setupMarketplace() throws { try query(cursor: StORMCursor(limit: 1, offset: 0)) if results.rows.count == 0 { for item in ClothingType.cases() { if item != .jewelry { try addCategory(name: item.rawValue, description: "Clothing: \(item.rawValue)", isPrimary: true) } } } } }
44d02e640aed389fb97d0cd16932442f
37.363636
128
0.636148
false
false
false
false
Fitbit/thrift
refs/heads/master
lib/swift/Sources/TProtocolError.swift
apache-2.0
21
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Foundation public struct TProtocolError : TError { public init() { } public enum Code : TErrorCode { case unknown case invalidData case negativeSize case sizeLimit(limit: Int, got: Int) case badVersion(expected: String, got: String) case notImplemented case depthLimit public var thriftErrorCode: Int { switch self { case .unknown: return 0 case .invalidData: return 1 case .negativeSize: return 2 case .sizeLimit: return 3 case .badVersion: return 4 case .notImplemented: return 5 case .depthLimit: return 6 } } public var description: String { switch self { case .unknown: return "Unknown TProtocolError" case .invalidData: return "Invalid Data" case .negativeSize: return "Negative Size" case .sizeLimit(let limit, let got): return "Message exceeds size limit of \(limit) (received: \(got)" case .badVersion(let expected, let got): return "Bad Version. (Expected: \(expected), Got: \(got)" case .notImplemented: return "Not Implemented" case .depthLimit: return "Depth Limit" } } } public enum ExtendedErrorCode : TErrorCode { case unknown case missingRequiredField(fieldName: String) case unexpectedType(type: TType) case mismatchedProtocol(expected: String, got: String) public var thriftErrorCode: Int { switch self { case .unknown: return 1000 case .missingRequiredField: return 1001 case .unexpectedType: return 1002 case .mismatchedProtocol: return 1003 } } public var description: String { switch self { case .unknown: return "Unknown TProtocolExtendedError" case .missingRequiredField(let fieldName): return "Missing Required Field: \(fieldName)" case .unexpectedType(let type): return "Unexpected Type \(type.self)" case .mismatchedProtocol(let expected, let got): return "Mismatched Protocol. (Expected: \(expected), got \(got))" } } } public var extendedError: ExtendedErrorCode? = nil public init(error: Code = .unknown, message: String? = nil, extendedError: ExtendedErrorCode? = nil) { self.error = error self.message = message self.extendedError = extendedError } /// Mark: TError public var error: Code = .unknown public var message: String? = nil public static var defaultCase: Code { return .unknown } public var description: String { var out = "\(TProtocolError.self): (\(error.thriftErrorCode) \(error.description)\n" if let extendedError = extendedError { out += "TProtocolExtendedError (\(extendedError.thriftErrorCode)): \(extendedError.description)" } if let message = message { out += "Message: \(message)" } return out } } /// Wrapper for Transport errors in Protocols. Inspired by Thrift-Cocoa PROTOCOL_TRANSPORT_ERROR /// macro. Modified to be more Swift-y. Catches any TError thrown within the block and /// rethrows a given TProtocolError, the original error's description is appended to the new /// TProtocolError's message. sourceFile, sourceLine, sourceMethod are auto-populated and should /// be ignored when calling. /// /// - parameter error: TProtocolError to throw if the block throws /// - parameter sourceFile: throwing file, autopopulated /// - parameter sourceLine: throwing line, autopopulated /// - parameter sourceMethod: throwing method, autopopulated /// - parameter block: throwing block /// /// - throws: TProtocolError Default is TProtocolError.ErrorCode.unknown. Underlying /// error's description appended to TProtocolError.message func ProtocolTransportTry(error: TProtocolError = TProtocolError(), sourceFile: String = #file, sourceLine: Int = #line, sourceMethod: String = #function, block: () throws -> ()) throws { // Need mutable copy var error = error do { try block() } catch let err as TError { var message = error.message ?? "" message += "\nFile: \(sourceFile)\n" message += "Line: \(sourceLine)\n" message += "Method: \(sourceMethod)" message += "\nOriginal Error:\n" + err.description error.message = message throw error } }
340c58a2a2a3ded1b359228177ebbe07
35.287671
122
0.65855
false
false
false
false
scotteg/LayerPlayer
refs/heads/master
LayerPlayer/TrackBall.swift
mit
1
// // TrackBall.swift // LayerPlayer // // Created by Scott Gardner on 11/20/14. // Copyright (c) 2014 Scott Gardner. All rights reserved. // import UIKit postfix operator ** postfix func ** (value: CGFloat) -> CGFloat { return value * value } class TrackBall { let tolerance = 0.001 var baseTransform = CATransform3DIdentity let trackBallRadius: CGFloat let trackBallCenter: CGPoint var trackBallStartPoint = (x: CGFloat(0.0), y: CGFloat(0.0), z: CGFloat(0.0)) init(location: CGPoint, inRect bounds: CGRect) { if bounds.width > bounds.height { trackBallRadius = bounds.height * 0.5 } else { trackBallRadius = bounds.width * 0.5 } trackBallCenter = CGPoint(x: bounds.midX, y: bounds.midY) setStartPointFromLocation(location) } func setStartPointFromLocation(_ location: CGPoint) { trackBallStartPoint.x = location.x - trackBallCenter.x trackBallStartPoint.y = location.y - trackBallCenter.y let distance = trackBallStartPoint.x** + trackBallStartPoint.y** trackBallStartPoint.z = distance > trackBallRadius** ? CGFloat(0.0) : sqrt(trackBallRadius** - distance) } func finalizeTrackBallForLocation(_ location: CGPoint) { baseTransform = rotationTransformForLocation(location) } func rotationTransformForLocation(_ location: CGPoint) -> CATransform3D { var trackBallCurrentPoint = (x: location.x - trackBallCenter.x, y: location.y - trackBallCenter.y, z: CGFloat(0.0)) let withinTolerance = fabs(Double(trackBallCurrentPoint.x - trackBallStartPoint.x)) < tolerance && fabs(Double(trackBallCurrentPoint.y - trackBallStartPoint.y)) < tolerance if withinTolerance { return CATransform3DIdentity } let distance = trackBallCurrentPoint.x** + trackBallCurrentPoint.y** if distance > trackBallRadius** { trackBallCurrentPoint.z = 0.0 } else { trackBallCurrentPoint.z = sqrt(trackBallRadius** - distance) } let startPoint = trackBallStartPoint let currentPoint = trackBallCurrentPoint let x = startPoint.y * currentPoint.z - startPoint.z * currentPoint.y let y = -startPoint.x * currentPoint.z + trackBallStartPoint.z * currentPoint.x let z = startPoint.x * currentPoint.y - startPoint.y * currentPoint.x var rotationVector = (x: x, y: y, z: z) let startLength = sqrt(Double(startPoint.x** + startPoint.y** + startPoint.z**)) let currentLength = sqrt(Double(currentPoint.x** + currentPoint.y** + currentPoint.z**)) let startDotCurrent = Double(startPoint.x * currentPoint.x + startPoint.y + currentPoint.y + startPoint.z + currentPoint.z) let rotationLength = sqrt(Double(rotationVector.x** + rotationVector.y** + rotationVector.z**)) let angle = CGFloat(atan2(rotationLength / (startLength * currentLength), startDotCurrent / (startLength * currentLength))) let normalizer = CGFloat(rotationLength) rotationVector.x /= normalizer rotationVector.y /= normalizer rotationVector.z /= normalizer let rotationTransform = CATransform3DMakeRotation(angle, rotationVector.x, rotationVector.y, rotationVector.z) return CATransform3DConcat(baseTransform, rotationTransform) } }
bbb9278f5033ff6ebf07835dc026e93d
36.941176
176
0.709147
false
false
false
false
dduan/swift
refs/heads/master
benchmark/single-source/ArrayAppend.swift
apache-2.0
2
//===--- ArrayAppend.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks the performance of appending to an array. import TestsUtils @inline(never) public func run_ArrayAppend(N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<40000 { nums.append(1) } } } } @inline(never) public func run_ArrayAppendReserved(N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() nums.reserveCapacity(40000) for _ in 0..<40000 { nums.append(1) } } } }
475d74f17185f9fa9e7d6bdb054f4a96
24.75
80
0.532039
false
false
false
false
easyui/Alamofire
refs/heads/master
Source/Protected.swift
mit
1
// // Protected.swift // // Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) // // 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 private protocol Lock { func lock() func unlock() } extension Lock { /// Executes a closure returning a value while acquiring the lock. /// /// - Parameter closure: The closure to run. /// /// - Returns: The value the closure generated. func around<T>(_ closure: () -> T) -> T { lock(); defer { unlock() } return closure() } /// Execute a closure while acquiring the lock. /// /// - Parameter closure: The closure to run. func around(_ closure: () -> Void) { lock(); defer { unlock() } closure() } } #if os(Linux) || os(Windows) extension NSLock: Lock {} #endif #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) /// An `os_unfair_lock` wrapper. final class UnfairLock: Lock { private let unfairLock: os_unfair_lock_t init() { unfairLock = .allocate(capacity: 1) unfairLock.initialize(to: os_unfair_lock()) } deinit { unfairLock.deinitialize(count: 1) unfairLock.deallocate() } fileprivate func lock() { os_unfair_lock_lock(unfairLock) } fileprivate func unlock() { os_unfair_lock_unlock(unfairLock) } } #endif /// A thread-safe wrapper around a value. @propertyWrapper @dynamicMemberLookup final class Protected<T> { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) private let lock = UnfairLock() #elseif os(Linux) || os(Windows) private let lock = NSLock() #endif private var value: T init(_ value: T) { self.value = value } /// The contained value. Unsafe for anything more than direct read or write. var wrappedValue: T { get { lock.around { value } } set { lock.around { value = newValue } } } var projectedValue: Protected<T> { self } init(wrappedValue: T) { value = wrappedValue } /// Synchronously read or transform the contained value. /// /// - Parameter closure: The closure to execute. /// /// - Returns: The return value of the closure passed. func read<U>(_ closure: (T) -> U) -> U { lock.around { closure(self.value) } } /// Synchronously modify the protected value. /// /// - Parameter closure: The closure to execute. /// /// - Returns: The modified value. @discardableResult func write<U>(_ closure: (inout T) -> U) -> U { lock.around { closure(&self.value) } } subscript<Property>(dynamicMember keyPath: WritableKeyPath<T, Property>) -> Property { get { lock.around { value[keyPath: keyPath] } } set { lock.around { value[keyPath: keyPath] = newValue } } } } extension Protected where T: RangeReplaceableCollection { /// Adds a new element to the end of this protected collection. /// /// - Parameter newElement: The `Element` to append. func append(_ newElement: T.Element) { write { (ward: inout T) in ward.append(newElement) } } /// Adds the elements of a sequence to the end of this protected collection. /// /// - Parameter newElements: The `Sequence` to append. func append<S: Sequence>(contentsOf newElements: S) where S.Element == T.Element { write { (ward: inout T) in ward.append(contentsOf: newElements) } } /// Add the elements of a collection to the end of the protected collection. /// /// - Parameter newElements: The `Collection` to append. func append<C: Collection>(contentsOf newElements: C) where C.Element == T.Element { write { (ward: inout T) in ward.append(contentsOf: newElements) } } } extension Protected where T == Data? { /// Adds the contents of a `Data` value to the end of the protected `Data`. /// /// - Parameter data: The `Data` to be appended. func append(_ data: Data) { write { (ward: inout T) in ward?.append(data) } } } extension Protected where T == Request.MutableState { /// Attempts to transition to the passed `State`. /// /// - Parameter state: The `State` to attempt transition to. /// /// - Returns: Whether the transition occurred. func attemptToTransitionTo(_ state: Request.State) -> Bool { lock.around { guard value.state.canTransitionTo(state) else { return false } value.state = state return true } } /// Perform a closure while locked with the provided `Request.State`. /// /// - Parameter perform: The closure to perform while locked. func withState(perform: (Request.State) -> Void) { lock.around { perform(value.state) } } }
2f6fa727fbb3ad17131da5c679e27532
29.213198
90
0.624328
false
false
false
false
calkinssean/woodshopBMX
refs/heads/master
WoodshopBMX/WoodshopBMX/ItemDetailViewController.swift
apache-2.0
1
// // ItemDetailViewController.swift // M3rch // // Created by Sean Calkins on 4/4/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import UIKit import Charts class ItemDetailViewController: UIViewController, ChartViewDelegate { //MARK: - Outlets @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var itemPriceLabel: UILabel! @IBOutlet weak var itemQuantityLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet var colorButtons: [UIButton]! @IBOutlet var sizeButtons: [UIButton]! @IBOutlet weak var currentSizeLabel: UILabel! @IBOutlet weak var currentColorView: UIView! @IBOutlet weak var pickColorLabel: UILabel! @IBOutlet weak var whiteLabel: UILabel! //MARK: - Properties var currentEvent: Event? var currentItem: Item? var currentSubItem: SubItem? var currentColor: String? var currentSize: String? var formatter = NSDateFormatter() var timeInterval: Double = 3600 var arrayOfSubItems = [SubItem]() var sizeStrings = [String]() var numFormatter = NSNumberFormatter() //MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = self.currentItem?.name numFormatter.minimumFractionDigits = 2 numFormatter.maximumFractionDigits = 2 self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit Item", style: .Plain, target: self, action: #selector(self.editItemTapped)) formatter.dateFormat = "h:mm a" formatter.AMSymbol = "AM" formatter.PMSymbol = "PM" } override func viewWillAppear(animated: Bool) { if let event = self.currentEvent { if event.name == "WoodShop" { self.backgroundImageView.image = UIImage(named: "wood copy") } } //Grab subitems for current item from data store let fetchedSubItems = DataController.sharedInstance.fetchSubItems() self.arrayOfSubItems.removeAll() for subItem in fetchedSubItems { if subItem.item == self.currentItem { self.arrayOfSubItems.append(subItem) } } self.updateUI() self.changeSizeButtonTitles() self.updateColorButtons() self.updateSizeButtons() } //MARK: - Color button tapped @IBAction func colorButtons(sender: UIButton) { var stock: Int = 0 if let color = sender.backgroundColor { //Changed current color on tap to button's background color self.currentColor = "\(color)" if self.currentColor == "UIDeviceRGBColorSpace 1 1 1 1" { self.whiteLabel.hidden = false } else { self.whiteLabel.hidden = true } self.currentColorView.backgroundColor = color self.pickColorLabel.text = "Pick a Size" } for item in arrayOfSubItems { //If sub item with current color exists, update quantity label and show sizes for that color if item.color == self.currentColor { if let quan = item.quantity { stock = stock + Int(quan) } } } self.itemQuantityLabel.text = "\(stock) left" self.updateSizeButtons() } //MARK: - Size button tapped @IBAction func sizeButtons(sender: UIButton) { //Changes current size on button tap var quantityTotal: Int = 0 if let size = sender.titleLabel?.text { self.currentSize = size self.currentSizeLabel.text = size self.pickColorLabel.text = "" } for item in arrayOfSubItems { //If sub item with selected color and size exists, update current quantity label if item.color == self.currentColor && item.size == self.currentSize { if let quantity = item.quantity { quantityTotal = quantityTotal + Int(quantity) if Int(quantity) > 0 { self.currentSubItem = item } } } } self.itemQuantityLabel.text = "\(quantityTotal) left" } //MARK: - Sell item tapped @IBAction func sellItemTapped() { if self.currentColor != nil && self.currentSize != nil { if let quan = self.currentSubItem?.quantity { if Double(quan) > 0 { self.saleTypeAlert() } else { self.presentAlert("Item is sold out") } } else { self.presentAlert("Please select a size and color") } } else { self.presentAlert("Please select a size and color") } } //Alert if item is sold out func presentAlert(message: String) { let alert = UIAlertController(title: "\(message)", message: nil, preferredStyle: .Alert) let ok = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(ok) presentViewController(alert, animated: true, completion: nil) self.updateColorButtons() self.updateSizeButtons() } //Choose type of sale func saleTypeAlert() { let alert = UIAlertController(title: "Sell Item", message: "Choose Type Of Sale", preferredStyle: .Alert) //If cash sale, create sale object with "Cash" as type let cashAction = UIAlertAction(title: "Cash", style: .Default) { (action: UIAlertAction) -> Void in if let quan = self.currentSubItem?.quantity { if Double(quan) > 0 { var newAmount = Double(quan) newAmount = newAmount - Double(1) //update quantity on sale self.currentSubItem?.setValue(newAmount, forKey: "quantity") dataControllerSave() let date = NSDate() if let price = self.currentItem?.price { let priceDouble = Double(price) if let event = self.currentItem?.event { if let item = self.currentItem { if let currentSubItem = self.currentSubItem { if let initialCost = self.currentItem?.purchasedPrice { DataController.sharedInstance.seedSale(date, type: "Cash", amount: priceDouble, initialCost: Double(initialCost), event: event, item: item, subItem: currentSubItem) self.updateColorButtons() self.updateSizeButtons() self.updateUI() } } } } } } else { self.presentAlert("Item is sold out") } } } //If cash sale, create sale object with "Card" as type let cardAction = UIAlertAction(title: "Card", style: .Default) { (action: UIAlertAction) -> Void in if let quan = self.currentSubItem?.quantity { if Double(quan) > 0 { var newAmount = Double(quan) newAmount = newAmount - Double(1) //update quantity on sale self.currentSubItem?.setValue(newAmount, forKey: "quantity") dataControllerSave() let date = NSDate() if let price = self.currentItem?.price { let priceDouble = Double(price) if let event = self.currentItem?.event { if let item = self.currentItem { if let currentSubItem = self.currentSubItem { if let initialCost = self.currentItem?.purchasedPrice { DataController.sharedInstance.seedSale(date, type: "Card", amount: priceDouble, initialCost: Double(initialCost), event: event, item: item, subItem: currentSubItem) self.updateColorButtons() self.updateSizeButtons() self.updateUI() } } } } } } else { self.presentAlert("Item is sold out") } } self.updateUI() } let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction) -> Void in } alert.addAction(cashAction) alert.addAction(cardAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } //MARK: - Helper Methods func updateUI() { if let price = self.currentItem?.price { if let formattedString = numFormatter.stringFromNumber(price) { self.itemPriceLabel.text = "$\(formattedString)" } } let qty = Int(self.getCurrentStock(self.currentItem!)) self.itemQuantityLabel.text = "\(qty) left" if let imageName = currentItem?.imageName { if let image = loadImageFromUrl(imageName) { self.imageView.image = image } } self.currentSize = nil self.currentColor = nil self.currentSizeLabel.text = "" self.currentColorView.backgroundColor = UIColor.clearColor() self.pickColorLabel.text = "Pick a Color" } //MARK: - Change size button titles func changeSizeButtonTitles() { self.sizeStrings = [] for item in arrayOfSubItems { if !self.sizeStrings.contains(item.size!) { self.sizeStrings.append(item.size!) } } //loop through buttons array and change button titles to size strings as needed then unhide the button for (index, size) in self.sizeStrings.enumerate() { let button = self.sizeButtons[index] button.setTitle(size, forState: .Normal) button.hidden = false } } //MARK: - Edit Item Tapped func editItemTapped() { performSegueWithIdentifier("editItemSegue", sender: self) } //MARK: - Prepare for segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "editItemSegue" { let controller = segue.destinationViewController as! ColorsAndSizesViewController controller.currentItem = self.currentItem controller.currentEvent = self.currentEvent } } //MARK: - Update Color Buttons func updateColorButtons() { for button in colorButtons { button.hidden = true } for sItem in arrayOfSubItems { if let quan = sItem.quantity { if Double(quan) > 0 { for button in colorButtons { //Unhides the color button if the current item has a sub item of that color if let color = button.backgroundColor { if "\(color)" == sItem.color { button.hidden = false } } } } } } } //MARK: - Update size buttons func updateSizeButtons() { for button in sizeButtons { button.hidden = true } for sItem in arrayOfSubItems { if let quan = sItem.quantity { if Double(quan) > 0 { for button in sizeButtons { if let color = sItem.color { if let size = button.titleLabel!.text { //Unhides size button if current item has sub item of that size and current color if size == sItem.size && color == self.currentColor { button.hidden = false } } } } } } } } //MARK: - Unwind Segue @IBAction func unwindSegue (segue: UIStoryboardSegue) {} //Add the quantities of all sub items to get a quantity of current item func getCurrentStock(item: Item) -> Double { let fetchedSubItems = DataController.sharedInstance.fetchSubItems() var stockTotal: Double = 0 for subItem in fetchedSubItems { if subItem.item == item { if let quantity = subItem.quantity { stockTotal = stockTotal + Double(quantity) } } } return stockTotal } }
1fb9c85b2893c1b2f7399394a45fe1d3
31.786448
204
0.440158
false
false
false
false
dathtcheapgo/Jira-Demo
refs/heads/master
Driver/Extension/UIViewExtension.swift
mit
1
// // UIViewExtension.swift // drivers // // Created by Đinh Anh Huy on 10/10/16. // Copyright © 2016 Đinh Anh Huy. All rights reserved. // import UIKit extension UIView { //MARK: Layer func makeRoundedConner(radius: CGFloat = 10) { self.layer.cornerRadius = radius self.clipsToBounds = true } func copyView() -> UIView { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! UIView } } //MARK: Indicator extension UIView { func showIndicator(indicatorStyle: UIActivityIndicatorViewStyle, blockColor: UIColor, alpha: CGFloat) { OperationQueue.main.addOperation { for currentView in self.subviews { if currentView.tag == 9999 { return } } let viewBlock = UIView() viewBlock.tag = 9999 viewBlock.backgroundColor = blockColor viewBlock.alpha = alpha viewBlock.translatesAutoresizingMaskIntoConstraints = false self.addSubview(viewBlock) _ = viewBlock.addConstraintFillInView(view: self, commenParrentView: self) let indicator = UIActivityIndicatorView(activityIndicatorStyle: indicatorStyle) indicator.frame = CGRect( x: self.frame.width/2-25, y: self.frame.height/2-25, width: 50, height: 50) viewBlock.addSubview(indicator) indicator.startAnimating() } } func showIndicator() { OperationQueue.main.addOperation { for currentView in self.subviews { if currentView.tag == 9999 { return } } let viewBlock = UIView() viewBlock.tag = 9999 viewBlock.backgroundColor = UIColor.black viewBlock.alpha = 0.3 viewBlock.layer.cornerRadius = self.layer.cornerRadius let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white) viewBlock.translatesAutoresizingMaskIntoConstraints = false self.addSubview(viewBlock) _ = viewBlock.addConstraintFillInView(view: self, commenParrentView: self) indicator.translatesAutoresizingMaskIntoConstraints = false viewBlock.addSubview(indicator) _ = indicator.addConstraintCenterXToView(view: self, commonParrentView: self) _ = indicator.addConstraintCenterYToView(view: self, commonParrentView: self) indicator.startAnimating() } } func showIndicator(frame: CGRect, blackStyle: Bool = false) { let viewBlock = UIView() viewBlock.tag = 9999 viewBlock.backgroundColor = UIColor.white viewBlock.frame = frame let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) indicator.frame = CGRect( x: self.frame.width/2-25, y: self.frame.height/2-25, width: 50, height: 50) viewBlock.addSubview(indicator) self.addSubview(viewBlock) indicator.startAnimating() } func hideIndicator() { let indicatorView = self.viewWithTag(9999) indicatorView?.removeFromSuperview() for currentView in self.subviews { if currentView.tag == 9999 { let _view = currentView OperationQueue.main.addOperation { _view.removeFromSuperview() } } } } } //MARK: Animation extension UIView { func moveToFrameWithAnimation(newFrame: CGRect, delay: TimeInterval, time: TimeInterval) { UIView.animate(withDuration: time, delay: delay, options: .curveEaseOut, animations: { self.frame = newFrame }, completion:nil) } func fadeOut(time: TimeInterval, delay: TimeInterval) { self.isUserInteractionEnabled = false UIView.animate(withDuration: time, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: { self.alpha = 0.0 }, completion: { (finished: Bool) -> Void in if finished == true { self.isHidden = true } }) } func fadeIn(time: TimeInterval, delay: TimeInterval) { self.isUserInteractionEnabled = true self.alpha = 0 self.isHidden = false UIView.animate(withDuration: time, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: { self.alpha = 1.0 }, completion: { (finished: Bool) -> Void in if finished == true { } }) } } //MARK: Add constraint extension UIView { func leadingMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func trailingMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintTopToBot(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintBotToTop(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintBotMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintTopMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { // self.setTranslatesAutoresizingMaskIntoConstraints(false) let constraint = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintWidth(parrentView: UIView, width: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: width) parrentView.addConstraint(constraint) return constraint } func addConstraintHeight(parrentView: UIView, height: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: height) parrentView.addConstraint(constraint) return constraint } func addConstraintLeftToRight(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.right, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintRightToLeft(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintCenterYToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintCenterXToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: margin) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintEqualHeightToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.height, multiplier: 1, constant: margin) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintEqualWidthToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: margin) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintFillInView(view: UIView, commenParrentView: UIView, margins: [CGFloat]? = nil) -> (top: NSLayoutConstraint, bot: NSLayoutConstraint, lead: NSLayoutConstraint, trail: NSLayoutConstraint) { var mutableMargins = margins if mutableMargins == nil { mutableMargins = [0, 0, 0, 0] } let top = addConstraintTopMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![0]) let trail = trailingMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![1]) let bot = addConstraintBotMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![2]) let lead = leadingMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![3]) return (top, bot, lead, trail) } } //MARK: Get constraint from superview extension UIView { func constraintTop() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isTopConstraint() else { continue } return constraint } return nil } func constraintBot() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isBotConstraint() else { continue } return constraint } return nil } func constraintLead() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isLeadConstraint() else { continue } return constraint } return nil } func constraintTrail() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isTrailConstraint() else { continue } return constraint } return nil } }
94da2428a15f7e7af789cf06c87d5419
41.064599
123
0.532834
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Graphic Equalizer.xcplaygroundpage/Contents.swift
mit
1
//: ## Graphic Equalizer //: This playground builds a graphic equalizer from a set of equalizer filters import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true let filterBand2 = AKEqualizerFilter(player, centerFrequency: 32, bandwidth: 44.7, gain: 1.0) let filterBand3 = AKEqualizerFilter(filterBand2, centerFrequency: 64, bandwidth: 70.8, gain: 1.0) let filterBand4 = AKEqualizerFilter(filterBand3, centerFrequency: 125, bandwidth: 141, gain: 1.0) let filterBand5 = AKEqualizerFilter(filterBand4, centerFrequency: 250, bandwidth: 282, gain: 1.0) let filterBand6 = AKEqualizerFilter(filterBand5, centerFrequency: 500, bandwidth: 562, gain: 1.0) let filterBand7 = AKEqualizerFilter(filterBand6, centerFrequency: 1_000, bandwidth: 1_112, gain: 1.0) AudioKit.output = filterBand7 AudioKit.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Graphic Equalizer") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addLabel("Equalizer Gains") addView(AKSlider(property: "32Hz", value: filterBand2.gain, range: 0 ... 2) { sliderValue in filterBand2.gain = sliderValue }) addView(AKSlider(property: "64Hz", value: filterBand3.gain, range: 0 ... 2) { sliderValue in filterBand3.gain = sliderValue }) addView(AKSlider(property: "125Hz", value: filterBand4.gain, range: 0 ... 2) { sliderValue in filterBand4.gain = sliderValue }) addView(AKSlider(property: "250Hz", value: filterBand5.gain, range: 0 ... 2) { sliderValue in filterBand5.gain = sliderValue }) addView(AKSlider(property: "500Hz", value: filterBand6.gain, range: 0 ... 2) { sliderValue in filterBand6.gain = sliderValue }) addView(AKSlider(property: "1000Hz", value: filterBand7.gain, range: 0 ... 2) { sliderValue in filterBand7.gain = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
ed3fc124d408f52a4a2d110f54bd9977
36.064516
102
0.704526
false
false
false
false
seuzl/iHerald
refs/heads/master
Herald/AcademicViewController.swift
mit
1
// // AcademicViewController.swift // 先声 // // Created by Wangshuo on 14-9-2. // Copyright (c) 2014年 WangShuo. All rights reserved. // import UIKit class AcademicViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,APIGetter { @IBOutlet var upSegmentControl: UISegmentedControl! @IBOutlet var downSegmentControl: UISegmentedControl! @IBOutlet var tableView: UITableView! var allInfoList:NSMutableArray = []//All information in a list with all JWC info.Should be initialized before use var contentDictionary:NSDictionary?//All information in a dictionary with 5 type of JWC info var currentList:NSMutableArray = [] var segmentedControlLastPressedIndex:NSNumber = 0 var firstLoad = true var API = HeraldAPI() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "教务信息" self.view.backgroundColor = UIColor(red: 180/255, green: 230/255, blue: 230/255, alpha: 1) self.tableView.backgroundColor = UIColor(red: 180/255, green: 230/255, blue: 230/255, alpha: 1) self.upSegmentControl.addTarget(self, action: Selector("upSegmentedControlPressed"), forControlEvents: UIControlEvents.ValueChanged) self.downSegmentControl.addTarget(self, action: Selector("downSegmentedControlPressed"), forControlEvents: UIControlEvents.ValueChanged) //设置默认选择项索引 self.upSegmentControl.selectedSegmentIndex = 0 self.downSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment //设置表格刷新 self.tableView.addFooterWithTarget(self, action: Selector("footerRefreshing")) let initResult = Tool.initNavigationAPI(self) if initResult{ Tool.showProgressHUD("正在查询教务信息") self.API.delegate = self API.sendAPI("jwc") } } override func viewWillDisappear(animated: Bool) { Tool.dismissHUD() API.cancelAllRequest() } func getResult(APIName: String, results: JSON) { Tool.showSuccessHUD("获取成功") contentDictionary = results["content"].dictionaryObject getAllInformation() if firstLoad{ upSegmentedControlPressed() firstLoad = false } } func getError(APIName: String, statusCode: Int) { Tool.showErrorHUD("获取数据失败") } func upSegmentedControlPressed() { let selectedIndex = self.upSegmentControl.selectedSegmentIndex if contentDictionary == nil{ Tool.showErrorHUD("没有数据哦") return } switch selectedIndex { case 0: if allInfoList.count != 0{ self.downSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = allInfoList self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } case 1: if let segmentedContent:NSMutableArray = contentDictionary!["最新动态"] as? NSMutableArray{ self.downSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } case 2: if let segmentedContent:NSMutableArray = contentDictionary!["教务信息"] as? NSMutableArray{ self.downSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } default: break } } func downSegmentedControlPressed() { let selectedIndex = self.downSegmentControl.selectedSegmentIndex switch selectedIndex { case 0: if let segmentedContent:NSMutableArray = contentDictionary!["合作办学"] as? NSMutableArray{ self.upSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } case 1: if let segmentedContent:NSMutableArray = contentDictionary!["学籍管理"] as? NSMutableArray{ self.upSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } case 2: if let segmentedContent:NSMutableArray = contentDictionary!["实践教学"] as? NSMutableArray{ self.upSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } default: break } } //获取教务信息中的全部信息,而非某个信息,供第一个SegmentedControl显示 func getAllInformation(){ allInfoList = []//清空 if let allContent = contentDictionary{ for (_,infoArray) in allContent{ allInfoList.addObjectsFromArray(infoArray as! Array<AnyObject>) } } } func footerRefreshing() { Tool.showProgressHUD("正在加载更多数据") API.sendAPI("jwc") self.tableView.footerEndRefreshing() } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 110 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.currentList.count == 0 { return 0 } else { return self.currentList.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier:String = "AcademicTableViewCell" var cell: AcademicTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? AcademicTableViewCell if nil == cell { let nibArray:NSArray = NSBundle.mainBundle().loadNibNamed("AcademicTableViewCell", owner: self, options: nil) cell = nibArray.objectAtIndex(0) as? AcademicTableViewCell } cell?.backgroundColor = UIColor(red: 180/255, green: 230/255, blue: 230/255, alpha: 1) let row = indexPath.row cell?.headLineLabel.text = self.currentList[row]["title"] as? String cell?.dateLabel.text = self.currentList[row]["date"] as? String cell?.headLineLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping cell?.headLineLabel.numberOfLines = 0 cell?.dateLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping cell?.dateLabel.numberOfLines = 0 return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ tableView.deselectRowAtIndexPath(indexPath, animated: true) let row = indexPath.row self.tableView.deselectRowAtIndexPath(indexPath, animated: true) let academicDetailVC = AcademicDetailViewController() academicDetailVC.initWebView(self.currentList[row]["href"] as! NSString as String) self.navigationController!.pushViewController(academicDetailVC, animated: true) } //现在API只返回网页形式的教务信息,没有文字信息 }
0fa5cc5b5b484bf46c897659b88367cf
34.877273
144
0.643988
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/MailPagePresenter.swift
lgpl-2.1
2
// // MailPagePresenter.swift // Neocom // // Created by Artem Shimanski on 11/2/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData import TreeController import EVEAPI class MailPagePresenter: TreePresenter { typealias View = MailPageViewController typealias Interactor = MailPageInteractor typealias Presentation = [Tree.Item.DateSection<Tree.Item.MailRow>] weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) var content: Interactor.Content? var presentation: Presentation? var loading: Future<Presentation>? var lastMailID: Int64? required init(view: View) { self.view = view } func configure() { view?.tableView.register([Prototype.TreeSectionCell.default, Prototype.MailCell.default]) interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } } private var applicationWillEnterForegroundObserver: NotificationObserver? func presentation(for content: Interactor.Content) -> Future<Presentation> { guard let input = view?.input else {return .init(.failure(NCError.invalidInput(type: type(of: self))))} guard !content.value.headers.isEmpty else {return .init(.failure(NCError.noResults))} guard let characterID = Services.storage.viewContext.currentAccount?.characterID else {return .init(.failure(NCError.authenticationRequired))} let treeController = view?.treeController let old = self.presentation ?? [] let api = interactor.api return DispatchQueue.global(qos: .utility).async { () -> (Presentation, Int?) in let calendar = Calendar(identifier: .gregorian) let headers = content.value.headers.filter{$0.mailID != nil && $0.timestamp != nil}.sorted{$0.mailID! > $1.mailID!}.map { header -> Tree.Item.MailRow in var ids = Set(header.recipients?.map{Int64($0.recipientID)} ?? []) if let from = header.from { ids.insert(Int64(from)) } return Tree.Item.MailRow(header, contacts: content.value.contacts.filter {ids.contains($0.key)}, label: input, characterID: characterID, api: api) } let sections = Dictionary(grouping: headers, by: { (i) -> Date in let components = calendar.dateComponents([.year, .month, .day], from: i.content.timestamp!) return calendar.date(from: components) ?? i.content.timestamp! }).sorted {$0.key > $1.key} .map{Tree.Item.DateSection(date: $0.key, diffIdentifier: $0.key, treeController: treeController, children: $0.value)} return (sections, headers.last?.content.mailID) }.then(on: .main) { [weak self] (new, lastMailID) -> Presentation in self?.lastMailID = lastMailID.map{Int64($0)} var result = old for i in new { if let j = old.upperBound(where: {$0.date <= i.date}).first, j.date == i.date { let mailIDs = Set(j.children?.compactMap {$0.content.mailID} ?? []) j.children?.append(contentsOf: i.children?.filter {$0.content.mailID != nil && !mailIDs.contains($0.content.mailID!)} ?? []) } else { result.append(i) } } return result } } func prepareForReload() { self.presentation = nil self.lastMailID = nil self.isEndReached = false } private var isEndReached = false @discardableResult func fetchIfNeeded() -> Future<Presentation> { guard !isEndReached else {return .init(.failure(NCError.isEndReached))} guard let lastMailID = lastMailID, self.loading == nil else {return .init(.failure(NCError.reloadInProgress))} view?.activityIndicator.startAnimating() let loading = interactor.load(from: lastMailID, cachePolicy: .useProtocolCachePolicy).then(on: .main) { [weak self] content -> Future<Presentation> in guard let strongSelf = self else {throw NCError.cancelled(type: type(of: self), function: #function)} return strongSelf.presentation(for: content).then(on: .main) { [weak self] presentation -> Presentation in self?.presentation = presentation self?.view?.present(presentation, animated: false) self?.loading = nil return presentation } }.catch(on: .main) { [weak self] error in self?.loading = nil self?.isEndReached = true }.finally(on: .main) { [weak self] in self?.view?.activityIndicator.stopAnimating() } if case .pending = loading.state { self.loading = loading } return loading } func canEdit<T: TreeItem>(_ item: T) -> Bool { return item is Tree.Item.MailRow } func editingStyle<T: TreeItem>(for item: T) -> UITableViewCell.EditingStyle { return item is Tree.Item.MailRow ? .delete : .none } func editActions<T: TreeItem>(for item: T) -> [UITableViewRowAction]? { guard let item = item as? Tree.Item.MailRow else {return nil} return [UITableViewRowAction(style: .destructive, title: NSLocalizedString("Delete", comment: "")) { [weak self] (_, _) in self?.interactor.delete(item.content).then(on: .main) { guard let bound = self?.presentation?.upperBound(where: {$0.date <= item.content.timestamp!}) else {return} guard let section = bound.first else {return} guard let i = section.children?.firstIndex(of: item) else {return} section.children?.remove(at: i) if section.children?.isEmpty == true { self?.presentation?.remove(at: bound.indices.first!) if let presentation = self?.presentation { _ = self?.view?.treeController.reloadData(presentation, with: .fade) } } else { self?.view?.treeController.update(contentsOf: section, with: .fade) } if let n = self?.view?.input?.unreadCount, item.content.isRead != true && n > 0 { self?.view?.input?.unreadCount = n - 1 self?.view?.updateTitle() } }.catch(on: .main) { [weak self] error in self?.view?.present(UIAlertController(error: error), animated: true, completion: nil) } }] } func didSelect<T: TreeItem>(item: T) -> Void { guard let view = view else {return} guard let item = item as? Tree.Item.MailRow else {return} if item.content.isRead != true { item.content.isRead = true interactor.markRead(item.content) if let n = view.input?.unreadCount, n > 0 { view.input?.unreadCount = n - 1 view.updateTitle() } if let cell = view.treeController.cell(for: item) { item.configure(cell: cell, treeController: view.treeController) } else { view.treeController.reloadRow(for: item, with: .none) } } Router.Mail.mailBody(item.content).perform(from: view) } } extension Tree.Item { class DateSection<Element: TreeItem>: Section<Tree.Content.Section, Element> { let date: Date init<T: Hashable>(date: Date, doesRelativeDateFormatting: Bool = true, diffIdentifier: T, expandIdentifier: CustomStringConvertible? = nil, treeController: TreeController?, children: [Element]? = nil) { self.date = date let formatter = DateFormatter() formatter.doesRelativeDateFormatting = doesRelativeDateFormatting formatter.timeStyle = .none formatter.dateStyle = .medium let title = formatter.string(from: date).uppercased() super.init(Tree.Content.Section(prototype: Prototype.TreeSectionCell.default, title: title), isExpanded: true, diffIdentifier: diffIdentifier, expandIdentifier: expandIdentifier, treeController: treeController, children: children) } } }
b9c06ffc1a5657254b3794c67817b486
34.688679
204
0.690986
false
false
false
false
FsThatOne/FSOAuth2.0Test
refs/heads/master
FSOAuth2.0Test/FSOAuth2.0Test/NetworkTools.swift
mit
1
// // NetworkTools.swift // // // Created by FS小一 on 15/11/22. // // import UIKit import AFNetworking /// HTTP 请求方法枚举 enum FSRequestMethod: String { case GET = "GET" case POST = "POST" } // MARK: - 网络工具 class NetworkTools: AFHTTPSessionManager { private let testOAuthLoginUrl = "https://api.weibo.com/oauth2/authorize?client_id=3353833785&redirect_uri=https://github.com/FsThatOne" // 单例 static let sharedTools: NetworkTools = { let tools = NetworkTools(baseURL: nil) // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set tools.responseSerializer.acceptableContentTypes?.insert("text/html") return tools }() } extension NetworkTools{ func oauthUrl() -> NSURL { let url = NSURL(string: testOAuthLoginUrl) return url! } } // MARK: - 封装 AFN 网络方法 extension NetworkTools { /// 网络请求 /// /// - parameter method: GET / POST /// - parameter URLString: URLString /// - parameter parameters: 参数字典 /// - parameter finished: 完成回调 func request(method: FSRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: (result: AnyObject?, error: NSError?)->()) { // 定义成功回调 let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in finished(result: result, error: nil) } // 定义失败回调 let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in // 在开发网络应用的时候,错误不要提示给用户,但是错误一定要输出! print(error) finished(result: nil, error: error) } if method == FSRequestMethod.GET { GET(URLString, parameters: parameters, success: success, failure: failure) } else { POST(URLString, parameters: parameters, success: success, failure: failure) } } }
09a8d773f6c3ed1b169b3268a78a9be3
24.90411
149
0.59651
false
false
false
false
thomashocking/SimpleGeo
refs/heads/master
Constants.swift
gpl-3.0
1
// // Constants.swift // LSGeo // // Created by Thomas Hocking on 11/18/16. // Copyright © 2016 Thomas Hocking. All rights reserved. // import Foundation let NamesResultsKey : String = "NamesResultsKey" let TotalResultsCountKey : String = "TotalResultsCountKey" let AdminCode1Key : String = "AdminCode1Key" let AdminCode2Key : String = "AdminCode2Key" let AdminCode3Key : String = "AdminCode3Key" let AdminName1Key : String = "AdminName1Key" let AdminName2Key : String = "AdminName2Key" let AdminName3Key : String = "AdminName3Key" let AdminName4Key : String = "AdminName4Key" let NameKey : String = "NameKey" let ToponymNameKey : String = "ToponymNameKey" let ContinentCodeKey : String = "ContinentCodeKey" let CountryCodeKey : String = "CountryCodeKey" let CountryNameKey : String = "CountryNameKey" let PopulationKey : String = "PopulationKey" //used for wikipedia requests. let WikiTitleKey : String = "WikiTitleKey" let WikiSummaryKey : String = "WikiSummaryKey" let WikiURLKey : String = "WikiURLKey" let WikiFeatureKey : String = "WikiFeatureKey" let AlternateNamesKey : String = "AlternateNamesKey" let AlternateNameKey : String = "AlternateNameKey" let AlternateLanguageKey : String = "AlternateLanguageKey" let IDKey : String = "IDKey" let FeatureClassKey : String = "FeatureClassKey" let FeatureCodeKey : String = "FeatureCodeKey" let FeatureClassNameKey : String = "FeatureClassNameKey" let FeatureNameKey : String = "FeatureNameKey" let NamesScoreKey : String = "NamesScoreKey" let LatitudeKey : String = "LatitudeKey" let LongitudeKey : String = "LongitudeKey" let DistanceKey : String = "DistanceKey" let ElevationKey : String = "ElevationKey" let LanguageKey : String = "LanguageKey" //Wiki let RankKey : String = "RankKey" //Wiki let TimeZoneInfoKey : String = "TimeZoneInfoKey" let TimeZoneDSTOffsetKey : String = "TimeZoneDSTOffsetKey" let TimeZoneGMTOffsetKey : String = "TimeZoneGMTOffsetKey" let TimeZoneIDKey : String = "TimeZoneIDKey" let ErrorResponseKey : String = "ErrorResponseKey" let ErrorMessageKey : String = "ErrorMessageKey" let ErrorCodeKey : String = "ErrorCodeKey"
38a33950c986ae8c0375d0add92bf373
30.235294
58
0.768832
false
false
false
false
gosick/calculator
refs/heads/master
calculator/calculator/AppDelegate.swift
mit
1
// // AppDelegate.swift // calculator // // Created by gosick on 2015/10/8. // Copyright © 2015年 gosick. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.gosick.calculator" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("calculator", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
2260686215920774913eafbf77b42bc5
53.846847
291
0.719612
false
false
false
false
iadmir/Signal-iOS
refs/heads/master
Signal/src/call/CallAudioService.swift
gpl-3.0
1
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import AVFoundation public let CallAudioServiceSessionChanged = Notification.Name("CallAudioServiceSessionChanged") struct AudioSource: Hashable { let image: UIImage let localizedName: String let portDescription: AVAudioSessionPortDescription? // The built-in loud speaker / aka speakerphone let isBuiltInSpeaker: Bool // The built-in quiet speaker, aka the normal phone handset receiver earpiece let isBuiltInEarPiece: Bool init(localizedName: String, image: UIImage, isBuiltInSpeaker: Bool, isBuiltInEarPiece: Bool, portDescription: AVAudioSessionPortDescription? = nil) { self.localizedName = localizedName self.image = image self.isBuiltInSpeaker = isBuiltInSpeaker self.isBuiltInEarPiece = isBuiltInEarPiece self.portDescription = portDescription } init(portDescription: AVAudioSessionPortDescription) { let isBuiltInEarPiece = portDescription.portType == AVAudioSessionPortBuiltInMic // portDescription.portName works well for BT linked devices, but if we are using // the built in mic, we have "iPhone Microphone" which is a little awkward. // In that case, instead we prefer just the model name e.g. "iPhone" or "iPad" let localizedName = isBuiltInEarPiece ? UIDevice.current.localizedModel : portDescription.portName self.init(localizedName: localizedName, image:#imageLiteral(resourceName: "button_phone_white"), // TODO isBuiltInSpeaker: false, isBuiltInEarPiece: isBuiltInEarPiece, portDescription: portDescription) } // Speakerphone is handled separately from the other audio routes as it doesn't appear as an "input" static var builtInSpeaker: AudioSource { return self.init(localizedName: NSLocalizedString("AUDIO_ROUTE_BUILT_IN_SPEAKER", comment: "action sheet button title to enable built in speaker during a call"), image: #imageLiteral(resourceName: "button_phone_white"), //TODO isBuiltInSpeaker: true, isBuiltInEarPiece: false) } // MARK: Hashable static func ==(lhs: AudioSource, rhs: AudioSource) -> Bool { // Simply comparing the `portDescription` vs the `portDescription.uid` // caused multiple instances of the built in mic to turn up in a set. if lhs.isBuiltInSpeaker && rhs.isBuiltInSpeaker { return true } if lhs.isBuiltInSpeaker || rhs.isBuiltInSpeaker { return false } guard let lhsPortDescription = lhs.portDescription else { owsFail("only the built in speaker should lack a port description") return false } guard let rhsPortDescription = rhs.portDescription else { owsFail("only the built in speaker should lack a port description") return false } return lhsPortDescription.uid == rhsPortDescription.uid } var hashValue: Int { guard let portDescription = self.portDescription else { assert(self.isBuiltInSpeaker) return "Built In Speaker".hashValue } return portDescription.uid.hash } } @objc class CallAudioService: NSObject, CallObserver { private let TAG = "[CallAudioService]" private var vibrateTimer: Timer? private let audioPlayer = AVAudioPlayer() private let handleRinging: Bool class Sound { let TAG = "[Sound]" static let incomingRing = Sound(filePath: "r", fileExtension: "caf", loop: true) static let outgoingRing = Sound(filePath: "outring", fileExtension: "mp3", loop: true) static let dialing = Sound(filePath: "sonarping", fileExtension: "mp3", loop: true) static let busy = Sound(filePath: "busy", fileExtension: "mp3", loop: false) static let failure = Sound(filePath: "failure", fileExtension: "mp3", loop: false) let filePath: String let fileExtension: String let url: URL let loop: Bool init(filePath: String, fileExtension: String, loop: Bool) { self.filePath = filePath self.fileExtension = fileExtension self.url = Bundle.main.url(forResource: self.filePath, withExtension: self.fileExtension)! self.loop = loop } lazy var player: AVAudioPlayer? = { let newPlayer: AVAudioPlayer? do { try newPlayer = AVAudioPlayer(contentsOf: self.url, fileTypeHint: nil) if self.loop { newPlayer?.numberOfLoops = -1 } } catch { owsFail("\(self.TAG) failed to build audio player with error: \(error)") newPlayer = nil } return newPlayer }() } // MARK: Vibration config private let vibrateRepeatDuration = 1.6 // Our ring buzz is a pair of vibrations. // `pulseDuration` is the small pause between the two vibrations in the pair. private let pulseDuration = 0.2 // MARK: - Initializers init(handleRinging: Bool) { self.handleRinging = handleRinging } // MARK: - CallObserver internal func stateDidChange(call: SignalCall, state: CallState) { AssertIsOnMainThread() self.handleState(call:call) } internal func muteDidChange(call: SignalCall, isMuted: Bool) { AssertIsOnMainThread() Logger.verbose("\(TAG) in \(#function) is no-op") } internal func audioSourceDidChange(call: SignalCall, audioSource: AudioSource?) { AssertIsOnMainThread() ensureProperAudioSession(call: call) } internal func hasLocalVideoDidChange(call: SignalCall, hasLocalVideo: Bool) { AssertIsOnMainThread() ensureProperAudioSession(call: call) } private func ensureProperAudioSession(call: SignalCall?) { AssertIsOnMainThread() guard let call = call else { setAudioSession(category: AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault) return } // Disallow bluetooth while (and only while) the user has explicitly chosen the built in receiver. // // NOTE: I'm actually not sure why this is required - it seems like we should just be able // to setPreferredInput to call.audioSource.portDescription in this case, // but in practice I'm seeing the call revert to the bluetooth headset. // Presumably something else (in WebRTC?) is touching our shared AudioSession. - mjk let options: AVAudioSessionCategoryOptions = call.audioSource?.isBuiltInEarPiece == true ? [] : [.allowBluetooth] if call.state == .localRinging { // SoloAmbient plays through speaker, but respects silent switch setAudioSession(category: AVAudioSessionCategorySoloAmbient, mode: AVAudioSessionModeDefault) } else if call.hasLocalVideo { // Apple Docs say that setting mode to AVAudioSessionModeVideoChat has the // side effect of setting options: .allowBluetooth, when I remove the (seemingly unnecessary) // option, and inspect AVAudioSession.sharedInstance.categoryOptions == 0. And availableInputs // does not include my linked bluetooth device setAudioSession(category: AVAudioSessionCategoryPlayAndRecord, mode: AVAudioSessionModeVideoChat, options: options) } else { // Apple Docs say that setting mode to AVAudioSessionModeVoiceChat has the // side effect of setting options: .allowBluetooth, when I remove the (seemingly unnecessary) // option, and inspect AVAudioSession.sharedInstance.categoryOptions == 0. And availableInputs // does not include my linked bluetooth device setAudioSession(category: AVAudioSessionCategoryPlayAndRecord, mode: AVAudioSessionModeVoiceChat, options: options) } let session = AVAudioSession.sharedInstance() do { // It's important to set preferred input *after* ensuring properAudioSession // because some sources are only valid for certain category/option combinations. let existingPreferredInput = session.preferredInput if existingPreferredInput != call.audioSource?.portDescription { Logger.info("\(TAG) changing preferred input: \(String(describing: existingPreferredInput)) -> \(String(describing: call.audioSource?.portDescription))") try session.setPreferredInput(call.audioSource?.portDescription) } if call.isSpeakerphoneEnabled { try session.overrideOutputAudioPort(.speaker) } else { try session.overrideOutputAudioPort(.none) } } catch { owsFail("\(TAG) failed setting audio source with error: \(error) isSpeakerPhoneEnabled: \(call.isSpeakerphoneEnabled)") } } // MARK: - Service action handlers public func didUpdateVideoTracks(call: SignalCall?) { Logger.verbose("\(TAG) in \(#function)") self.ensureProperAudioSession(call: call) } public func handleState(call: SignalCall) { assert(Thread.isMainThread) Logger.verbose("\(TAG) in \(#function) new state: \(call.state)") // Stop playing sounds while switching audio session so we don't // get any blips across a temporary unintended route. stopPlayingAnySounds() self.ensureProperAudioSession(call: call) switch call.state { case .idle: handleIdle(call: call) case .dialing: handleDialing(call: call) case .answering: handleAnswering(call: call) case .remoteRinging: handleRemoteRinging(call: call) case .localRinging: handleLocalRinging(call: call) case .connected: handleConnected(call: call) case .localFailure: handleLocalFailure(call: call) case .localHangup: handleLocalHangup(call: call) case .remoteHangup: handleRemoteHangup(call: call) case .remoteBusy: handleBusy(call: call) } } private func handleIdle(call: SignalCall) { Logger.debug("\(TAG) \(#function)") } private func handleDialing(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() // HACK: Without this async, dialing sound only plays once. I don't really understand why. Does the audioSession // need some time to settle? Is somethign else interrupting our session? DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { self.play(sound: Sound.dialing) } } private func handleAnswering(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() } private func handleRemoteRinging(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() // FIXME if you toggled speakerphone before this point, the outgoing ring does not play through speaker. Why? self.play(sound: Sound.outgoingRing) } private func handleLocalRinging(call: SignalCall) { Logger.debug("\(TAG) in \(#function)") AssertIsOnMainThread() startRinging(call: call) } private func handleConnected(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() } private func handleLocalFailure(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() play(sound: Sound.failure) } private func handleLocalHangup(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() handleCallEnded(call: call) } private func handleRemoteHangup(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() vibrate() handleCallEnded(call:call) } private func handleBusy(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() play(sound: Sound.busy) // Let the busy sound play for 4 seconds. The full file is longer than necessary DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 4.0) { self.handleCallEnded(call: call) } } private func handleCallEnded(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() // Stop solo audio, revert to default. setAudioSession(category: AVAudioSessionCategoryAmbient) } // MARK: Playing Sounds var currentPlayer: AVAudioPlayer? private func stopPlayingAnySounds() { currentPlayer?.stop() stopAnyRingingVibration() } private func play(sound: Sound) { guard let newPlayer = sound.player else { owsFail("\(self.TAG) unable to build player") return } Logger.info("\(self.TAG) playing sound: \(sound.filePath)") // It's important to stop the current player **before** starting the new player. In the case that // we're playing the same sound, since the player is memoized on the sound instance, we'd otherwise // stop the sound we just started. self.currentPlayer?.stop() newPlayer.play() self.currentPlayer = newPlayer } // MARK: - Ringing private func startRinging(call: SignalCall) { guard handleRinging else { Logger.debug("\(TAG) ignoring \(#function) since CallKit handles it's own ringing state") return } vibrateTimer = WeakTimer.scheduledTimer(timeInterval: vibrateRepeatDuration, target: self, userInfo: nil, repeats: true) {[weak self] _ in self?.ringVibration() } vibrateTimer?.fire() play(sound: Sound.incomingRing) } private func stopAnyRingingVibration() { guard handleRinging else { Logger.debug("\(TAG) ignoring \(#function) since CallKit handles it's own ringing state") return } Logger.debug("\(TAG) in \(#function)") // Stop vibrating vibrateTimer?.invalidate() vibrateTimer = nil } // public so it can be called by timer via selector public func ringVibration() { // Since a call notification is more urgent than a message notifaction, we // vibrate twice, like a pulse, to differentiate from a normal notification vibration. vibrate() DispatchQueue.default.asyncAfter(deadline: DispatchTime.now() + pulseDuration) { self.vibrate() } } func vibrate() { // TODO implement HapticAdapter for iPhone7 and up AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } // MARK - AudioSession MGMT // TODO move this to CallAudioSession? // Note this method is sensitive to the current audio session configuration. // Specifically if you call it while speakerphone is enabled you won't see // any connected bluetooth routes. var availableInputs: [AudioSource] { let session = AVAudioSession.sharedInstance() guard let availableInputs = session.availableInputs else { // I'm not sure why this would happen, but it may indicate an error. // In practice, I haven't seen it on iOS9+. // // I *have* seen it on iOS8, but it doesn't seem to cause any problems, // so we do *not* trigger the assert on that platform. if #available(iOS 9.0, *) { owsFail("No available inputs or inputs not ready") } return [AudioSource.builtInSpeaker] } Logger.info("\(TAG) in \(#function) availableInputs: \(availableInputs)") return [AudioSource.builtInSpeaker] + availableInputs.map { portDescription in return AudioSource(portDescription: portDescription) } } func currentAudioSource(call: SignalCall) -> AudioSource? { if let audioSource = call.audioSource { return audioSource } // Before the user has specified an audio source on the call, we rely on the existing // system state to determine the current audio source. // If a bluetooth is connected, this will be bluetooth, otherwise // this will be the receiver. let session = AVAudioSession.sharedInstance() guard let portDescription = session.currentRoute.inputs.first else { return nil } return AudioSource(portDescription: portDescription) } private func setAudioSession(category: String, mode: String? = nil, options: AVAudioSessionCategoryOptions = AVAudioSessionCategoryOptions(rawValue: 0)) { AssertIsOnMainThread() let session = AVAudioSession.sharedInstance() var audioSessionChanged = false do { if #available(iOS 10.0, *), let mode = mode { let oldCategory = session.category let oldMode = session.mode let oldOptions = session.categoryOptions guard oldCategory != category || oldMode != mode || oldOptions != options else { return } audioSessionChanged = true if oldCategory != category { Logger.debug("\(self.TAG) audio session changed category: \(oldCategory) -> \(category) ") } if oldMode != mode { Logger.debug("\(self.TAG) audio session changed mode: \(oldMode) -> \(mode) ") } if oldOptions != options { Logger.debug("\(self.TAG) audio session changed options: \(oldOptions) -> \(options) ") } try session.setCategory(category, mode: mode, options: options) } else { let oldCategory = session.category let oldOptions = session.categoryOptions guard session.category != category || session.categoryOptions != options else { return } audioSessionChanged = true if oldCategory != category { Logger.debug("\(self.TAG) audio session changed category: \(oldCategory) -> \(category) ") } if oldOptions != options { Logger.debug("\(self.TAG) audio session changed options: \(oldOptions) -> \(options) ") } try session.setCategory(category, with: options) } } catch { let message = "\(self.TAG) in \(#function) failed to set category: \(category) mode: \(String(describing: mode)), options: \(options) with error: \(error)" owsFail(message) } if audioSessionChanged { Logger.info("\(TAG) in \(#function)") // Update call view synchronously; already on main thread. NotificationCenter.default.post(name:CallAudioServiceSessionChanged, object: nil) } } }
be5c605eed0735817af02505309e0674
37.040777
169
0.625236
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Views/Shepard Tab/Settings/Game Row/GameRow.swift
mit
1
// // GameRow.swift // MEGameTracker // // Created by Emily Ivie on 8/12/15. // Copyright © 2015 urdnot. All rights reserved. // import UIKit final class GameRow: UITableViewCell { // MARK: Types // MARK: Constants private let dateMessage = "Last Played: %@" // MARK: Outlets @IBOutlet private weak var photoImageView: UIImageView? @IBOutlet private weak var nameLabel: UILabel? @IBOutlet private weak var titleLabel: UILabel? @IBOutlet private weak var dateLabel: UILabel? // MARK: Properties internal fileprivate(set) var shepard: Shepard? // MARK: Change Listeners And Change Status Flags private var isDefined = false // MARK: Lifecycle Events public override func layoutSubviews() { if !isDefined { clearRow() } super.layoutSubviews() } // MARK: Initialization /// Sets up the row - expects to be in main/UI dispatch queue. /// Also, table layout needs to wait for this, /// so don't run it asynchronously or the layout will be wrong. public func define(shepard: Shepard?) { isDefined = true self.shepard = shepard setup() } // MARK: Populate Data private func setup() { guard photoImageView != nil else { return } if !UIWindow.isInterfaceBuilder { Photo.addPhoto(from: shepard, toView: photoImageView, placeholder: UIImage.placeholder()) } nameLabel?.text = shepard?.fullName ?? "" titleLabel?.text = shepard?.title dateLabel?.text = String(format: dateMessage, shepard?.modifiedDate.format(.typical) ?? "") } /// Resets all text in the cases where row UI loads before data/setup. /// (I prefer to use sample UI data in nib, so I need it to disappear before UI displays.) private func clearRow() { photoImageView?.image = nil nameLabel?.text = "" titleLabel?.text = "" dateLabel?.text = "" } }
a1d4b766bf2fa705125c1aaf106c2675
25.924242
93
0.705684
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Card/Controller/CardTableViewController.swift
mit
2
// // CardTableViewController.swift // DereGuide // // Created by zzk on 16/6/5. // Copyright © 2016 zzk. All rights reserved. // import UIKit class CardTableViewController: BaseCardTableViewController { override func viewDidLoad() { super.viewDidLoad() print(NSHomeDirectory()) print(Locale.preferredLanguages.first ?? "") if UserDefaults.standard.value(forKey: "DownloadAtStart") as? Bool ?? true { check(.all) } registerForPreviewing(with: self, sourceView: view) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { searchBar.resignFirstResponder() let card = cardList[indexPath.row] let vc = CDTabViewController(card: card) vc.hidesBottomBarWhenPushed = true navigationController?.pushViewController(vc, animated: true) } } @available(iOS 9.0, *) extension CardTableViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { viewControllerToCommit.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewControllerToCommit, animated: true) } func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) else { return nil } let card = cardList[indexPath.row] let vc = CDTabViewController(card: card) vc.preferredContentSize = CGSize(width: view.shortSide, height: CGSSGlobal.spreadImageHeight * view.shortSide / CGSSGlobal.spreadImageWidth + 68) previewingContext.sourceRect = cell.frame return vc } }
fca204f87c086389b9b705e8614bc31a
33.649123
153
0.687089
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
refs/heads/master
source/Core/Classes/Audio/RSAudioPlayer.swift
apache-2.0
1
// // RSAudioPlayer.swift // ResearchSuiteExtensions // // Created by James Kizer on 4/4/18. // import UIKit import AVFoundation open class RSAudioPlayer: UIStackView, AVAudioPlayerDelegate { public enum RSAudioPlayerError: Error { case NotSupported } var audioPlayer: AVAudioPlayer! var audioInterruptedObserver: NSObjectProtocol! var playPauseButton: RSLabelButton! var resetButton: RSLabelButton! var isReset: Bool { return self.audioPlayer.currentTime == 0.0 } var isPlaying: Bool { return self.audioPlayer.isPlaying } private func setupAudioSession() throws { if #available(iOS 10.0, *) { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: [.defaultToSpeaker]) self.audioInterruptedObserver = NotificationCenter.default.addObserver(forName: AVAudioSession.interruptionNotification, object: nil, queue: nil, using: { [weak self](notification) in self?.audioPlayer.pause() }) } else { throw RSAudioPlayerError.NotSupported } } public convenience init?(fileURL: URL) { guard let audioPlayer = try? AVAudioPlayer(contentsOf: fileURL) else { return nil } self.init(arrangedSubviews: []) self.axis = .horizontal self.distribution = .fillEqually self.spacing = 16.0 self.audioPlayer = audioPlayer self.audioPlayer.delegate = self if self.audioPlayer.prepareToPlay() == false { return nil } do { try self.setupAudioSession() } catch { return nil } self.playPauseButton = RSLabelButton(frame: CGRect()) self.playPauseButton.addTarget(self, action: #selector(playPauseButtonTapped), for: .touchUpInside) self.playPauseButton.configuredColor = self.tintColor self.addArrangedSubview(self.playPauseButton) self.resetButton = RSLabelButton(frame: CGRect()) self.resetButton.addTarget(self, action: #selector(resetButtonTapped), for: .touchUpInside) self.resetButton.configuredColor = self.tintColor self.addArrangedSubview(self.resetButton) self.updateUI() } deinit { NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil) } private func reset() { self.audioPlayer.stop() self.audioPlayer.currentTime = 0.0 self.audioPlayer.prepareToPlay() self.updateUI() } @objc func playPauseButtonTapped() { if self.isPlaying { self.audioPlayer.pause() } else { self.audioPlayer.play() } self.updateUI() } @objc func resetButtonTapped() { self.reset() } public func updateUI() { self.playPauseButton.setTitle(self.isPlaying ? "Pause Audio" : "Play Audio", for: .normal) self.resetButton.setTitle("Reset Audio", for: .normal) self.resetButton.isEnabled = !self.isReset } public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { if flag { self.reset() } } public func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { // debugPrint(player) // debugPrint(error) } }
4992838c08447e70c9e0280f28779b91
25.791367
195
0.594791
false
false
false
false
cuappdev/DiningStack
refs/heads/master
DiningStack/DataManager.swift
mit
1
// // DataManager.swift // Eatery // // Created by Eric Appel on 10/8/14. // Copyright (c) 2014 CUAppDev. All rights reserved. // import Foundation import Alamofire import SwiftyJSON let separator = ":------------------------------------------" /** Router Endpoints enum */ internal enum Router: URLConvertible { /// Returns a URL that conforms to RFC 2396 or throws an `Error`. /// /// - throws: An `Error` if the type cannot be converted to a `URL`. /// /// - returns: A URL or throws an `Error`. public func asURL() throws -> URL { let path: String = { switch self { case .root: return "/" case .eateries: return "/eateries.json" } }() if let url = URL(string: Router.baseURLString + path) { return url } else { throw AFError.invalidURL(url: self) } } static let baseURLString = "https://now.dining.cornell.edu/api/1.0/dining" case root case eateries } /** Keys for Cornell API These will be in the response dictionary */ public enum APIKey : String { // Top Level case status = "status" case data = "data" case meta = "meta" case message = "message" // Data case eateries = "eateries" // Eatery case identifier = "id" case slug = "slug" case name = "name" case nameShort = "nameshort" case eateryTypes = "eateryTypes" case aboutShort = "aboutshort" case latitude = "latitude" case longitude = "longitude" case hours = "operatingHours" case payment = "payMethods" case phoneNumber = "contactPhone" case campusArea = "campusArea" case address = "location" case diningItems = "diningItems" // Hours case date = "date" case events = "events" // Events case startTime = "startTimestamp" case endTime = "endTimestamp" case startFormat = "start" case endFormat = "end" case menu = "menu" case summary = "calSummary" // Events/Payment/CampusArea/EateryTypes case description = "descr" case shortDescription = "descrshort" // Menu case items = "items" case category = "category" case item = "item" case healthy = "healthy" // Meta case copyright = "copyright" case timestamp = "responseDttm" // External case weekday = "weekday" case external = "external" } /** Enumerated Server Response - Success: String for the status if the request was a success. */ enum Status: String { case success = "success" } /** Error Types - ServerError: An error arose from the server-side of things */ enum DataError: Error { case serverError } public enum DayOfTheWeek: Int { case sunday = 1 case monday case tuesday case wednesday case thursday case friday case saturday init?(string: String) { switch string.lowercased() { case "sunday": self = .sunday case "monday": self = .monday case "tuesday": self = .tuesday case "wednesday": self = .wednesday case "thursday": self = .thursday case "friday": self = .friday case "saturday": self = .saturday default: return nil } } static func ofDateSpan(_ string: String) -> [DayOfTheWeek]? { let partition = string.lowercased().split { $0 == "-" } .map(String.init) switch partition.count { case 2: guard let start = DayOfTheWeek(string: partition[0]) else { return nil } guard let end = DayOfTheWeek(string: partition[1]) else { return nil } var result: [DayOfTheWeek] = [] let endValue = start.rawValue <= end.rawValue ? end.rawValue : end.rawValue + 7 for dayValue in start.rawValue...endValue { guard let day = DayOfTheWeek(rawValue: dayValue % 7) else { return nil } result.append(day) } return result case 1: guard let start = DayOfTheWeek(string: partition[0]) else { return nil } return [start] default: return nil } } func getDate() -> Date { let startOfToday = Calendar.current.startOfDay(for: Date()) let weekDay = Calendar.current.component(.weekday, from: Date()) let daysAway = (rawValue - weekDay + 7) % 7 let endDate = Calendar.current.date(byAdding: .weekday, value: daysAway, to: startOfToday) ?? Date() return endDate } func getDateString() -> String { let date = getDate() let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter.string(from: date) } func getTimeStamp(_ timeString: String) -> Date { let endDate = getDate() let formatter = DateFormatter() formatter.dateFormat = "h:mma" let timeIntoEndDate = formatter.date(from: timeString) ?? Date() let components = Calendar.current.dateComponents([.hour, .minute], from: timeIntoEndDate) return Calendar.current.date(byAdding: components, to: endDate) ?? Date() } } /// Top-level class to communicate with Cornell Dining public class DataManager: NSObject { /// Gives a shared instance of `DataManager` public static let sharedInstance = DataManager() /// List of all the Dining Locations with parsed events and menus private (set) public var eateries: [Eatery] = [] /** Sends a GET request to the Cornell API to get the events for all eateries and stores them in user documents. - parameter force: Boolean indicating that the data should be refreshed even if the cache is invalid. - parameter completion: Completion block called upon successful receipt and parsing of the data or with an error if there was one. Use `-eateries` to get the parsed response. */ public func fetchEateries(_ force: Bool, completion: ((Error?) -> Void)?) { if eateries.count > 0 && !force { completion?(nil) return } let req = Alamofire.request(Router.eateries) func processData (_ data: Data) { let json = JSON(data) if (json[APIKey.status.rawValue].stringValue != Status.success.rawValue) { completion?(DataError.serverError) // do something is message return } let eateryList = json["data"]["eateries"] self.eateries = eateryList.map { Eatery(json: $0.1) } let externalEateryList = kExternalEateries["eateries"]! let externalEateries = externalEateryList.map { Eatery(json: $0.1) } //don't add duplicate external eateries //Uncomment after CU Dining Pushes Eatery with marketing for external in externalEateries { if !eateries.contains(where: { $0.slug == external.slug }) { eateries.append(external) } } completion?(nil) } if let request = req.request, !force { let cached = URLCache.shared.cachedResponse(for: request) if let info = cached?.userInfo { // This is hacky because the server doesn't support caching really // and even if it did it is too slow to respond to make it worthwhile // so I'm going to try to screw with the cache policy depending // upon the age of the entry in the cache if let date = info["date"] as? Double { let maxAge: Double = 24 * 60 * 60 let now = Date().timeIntervalSince1970 if now - date <= maxAge { processData(cached!.data) return } } } } req.responseData { (resp) -> Void in let data = resp.result let request = resp.request let response = resp.response if let data = data.value, let response = response, let request = request { let cached = CachedURLResponse(response: response, data: data, userInfo: ["date": NSDate().timeIntervalSince1970], storagePolicy: .allowed) URLCache.shared.storeCachedResponse(cached, for: request) } if let jsonData = data.value { processData(jsonData) } else { completion?(data.error) } } } }
5584e5f8d55a0d0c2b4904523a75c483
29.230508
159
0.559879
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Reader/Select Interests/ReaderInterestsStyleGuide.swift
gpl-2.0
2
import Foundation import WordPressShared class ReaderInterestsStyleGuide { // MARK: - View Styles public class func applyTitleLabelStyles(label: UILabel) { label.font = WPStyleGuide.serifFontForTextStyle(.largeTitle, fontWeight: .medium) label.textColor = .text } public class func applySubtitleLabelStyles(label: UILabel) { label.font = WPStyleGuide.fontForTextStyle(.body) label.textColor = .text } // MARK: - Collection View Cell Styles public class var cellLabelTitleFont: UIFont { return WPStyleGuide.fontForTextStyle(.body) } public class func applyCellLabelStyle(label: UILabel, isSelected: Bool) { label.font = WPStyleGuide.fontForTextStyle(.body) label.textColor = isSelected ? .white : .text label.backgroundColor = isSelected ? .muriel(color: .primary, .shade40) : .quaternaryBackground } // MARK: - Compact Collection View Cell Styles public class var compactCellLabelTitleFont: UIFont { return WPStyleGuide.fontForTextStyle(.footnote) } public class func applyCompactCellLabelStyle(label: UILabel) { label.font = Self.compactCellLabelTitleFont label.textColor = .text label.backgroundColor = .quaternaryBackground } // MARK: - Next Button public class var buttonContainerViewBackgroundColor: UIColor { if #available(iOS 13, *) { return .tertiarySystemBackground } return .white } public class func applyNextButtonStyle(button: FancyButton) { let disabledBackgroundColor: UIColor let titleColor: UIColor disabledBackgroundColor = UIColor(light: .systemGray4, dark: .systemGray3) titleColor = .textTertiary button.disabledTitleColor = titleColor button.disabledBorderColor = disabledBackgroundColor button.disabledBackgroundColor = disabledBackgroundColor } // MARK: - Loading public class func applyLoadingLabelStyles(label: UILabel) { label.font = WPStyleGuide.fontForTextStyle(.body) label.textColor = .textSubtle } public class func applyActivityIndicatorStyles(indicator: UIActivityIndicatorView) { indicator.color = UIColor(light: .black, dark: .white) } } class ReaderSuggestedTopicsStyleGuide { /// The array of colors from the designs /// Note: I am explictly using the MurielColor names instead of using the semantic ones /// since these are explicit and not semantic colors. static let colors: [TopicStyle] = [ // Green .init(textColor: .init(colorName: .green, section: .text), backgroundColor: .init(colorName: .green, section: .background), borderColor: .init(colorName: .green, section: .border)), // Purple .init(textColor: .init(colorName: .purple, section: .text), backgroundColor: .init(colorName: .purple, section: .background), borderColor: .init(colorName: .purple, section: .border)), // Yellow .init(textColor: .init(colorName: .yellow, section: .text), backgroundColor: .init(colorName: .yellow, section: .background), borderColor: .init(colorName: .yellow, section: .border)), // Orange .init(textColor: .init(colorName: .orange, section: .text), backgroundColor: .init(colorName: .orange, section: .background), borderColor: .init(colorName: .orange, section: .border)), ] private class func topicStyle(for index: Int) -> TopicStyle { let colorCount = Self.colors.count // Safety feature if for some reason the count of returned topics ever increases past 4 we will // loop through the list colors again. return Self.colors[index % colorCount] } public static var topicFont: UIFont = WPStyleGuide.fontForTextStyle(.footnote) public class func applySuggestedTopicStyle(label: UILabel, with index: Int) { let style = Self.topicStyle(for: index) label.font = Self.topicFont label.textColor = style.textColor.color() label.layer.borderColor = style.borderColor.color().cgColor label.layer.borderWidth = .hairlineBorderWidth label.layer.backgroundColor = style.backgroundColor.color().cgColor } // MARK: - Color Representation struct TopicStyle { let textColor: TopicColor let backgroundColor: TopicColor let borderColor: TopicColor struct TopicColor { enum StyleSection { case text, background, border } let colorName: MurielColorName let section: StyleSection func color() -> UIColor { let lightShade: MurielColorShade let darkShade: MurielColorShade switch section { case .text: lightShade = .shade50 darkShade = .shade40 case .border: lightShade = .shade5 darkShade = .shade100 case .background: lightShade = .shade0 darkShade = .shade90 } return UIColor(light: .muriel(color: MurielColor(name: colorName, shade: lightShade)), dark: .muriel(color: MurielColor(name: colorName, shade: darkShade))) } } } }
19f447b6ab3328ed6a871f8eeab2f36d
34.767742
103
0.630051
false
false
false
false
fcanas/Compass
refs/heads/master
Compass/ChevronPathRenderer.swift
mit
1
// // ChevronPathRenderer.swift // Compass // // Created by Fabian Canas on 5/27/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import MapKit #if os(OSX) public typealias CMPSColor = NSColor #else public typealias CMPSColor = UIColor #endif public class ChevronPathRenderer: MKOverlayRenderer { public var color: CMPSColor = CMPSColor(red: 0xff/255.0, green: 0x85/255.0, blue: 0x1b/255.0, alpha: 1) public var chevronColor: CMPSColor = CMPSColor(red: 0xff/255.0, green: 0x41/255.0, blue: 0x36/255.0, alpha: 1) public let polyline: MKPolyline public var lineWidth: CGFloat = 12 public init(polyline: MKPolyline) { self.polyline = polyline super.init(overlay: polyline) setNeedsDisplayInMapRect(polyline.boundingMapRect) } public override func drawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale, inContext context: CGContext!) { if !MKMapRectIntersectsRect(mapRect, MKMapRectInset(polyline.boundingMapRect, -20, -20)) { return } let path = CGPathCreateMutable() let chevronPath = CGPathCreateMutable() let firstPoint = pointForMapPoint(polyline.points()[0]) let ctxLineWidth = CGContextConvertSizeToUserSpace(context, CGSizeMake(lineWidth, lineWidth)).width * contentScaleFactor let ctxPixelWidth = CGContextConvertSizeToUserSpace(context, CGSizeMake(1, 1)).width * contentScaleFactor CGPathMoveToPoint(path, nil, firstPoint.x, firstPoint.y) CGPathMoveToPoint(chevronPath, nil, firstPoint.x, firstPoint.y) var offset: CGFloat = 0.0 for idx in 1...(polyline.pointCount - 1) { let nextPoint = pointForMapPoint(polyline.points()[idx]) CGPathAddLineToPoint(path, nil, nextPoint.x, nextPoint.y) let lastPoint = CGPathGetCurrentPoint(path) offset = chevronToPoint(chevronPath, point: nextPoint, size: ctxLineWidth, offset: offset) } CGContextSetLineJoin(context, kCGLineJoinRound) CGContextSetLineCap(context, kCGLineCapRound) CGContextAddPath(context, path) CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetLineWidth(context, ctxLineWidth) CGContextStrokePath(context) CGContextSetLineJoin(context, kCGLineJoinMiter) CGContextSetLineCap(context, kCGLineCapSquare) CGContextAddPath(context, chevronPath) CGContextSetFillColorWithColor(context, chevronColor.CGColor) CGContextSetLineWidth(context, ctxPixelWidth) CGContextFillPath(context) } private func pointDist(point1: CGPoint!, point2: CGPoint!) -> CGFloat { return sqrt(pow(point1.x - point2.x, 2.0) + pow(point1.y - point2.y, 2.0)) } private func chevronToPoint(path: CGMutablePathRef!, point: CGPoint, size: CGFloat!, offset: CGFloat) -> CGFloat { let startingPoint = CGPathGetCurrentPoint(path) let dx = point.x - startingPoint.x let dy = point.y - startingPoint.y let w: CGFloat = size / 2 let h: CGFloat = size / 3 let count = Int( (pointDist(startingPoint, point2: point) - offset) / (2.0 * h) ) * 2 / 3 // Create Transform for Chevron var t = CGAffineTransformMakeTranslation(startingPoint.x, startingPoint.y) t = CGAffineTransformRotate(t, -atan2(dx, dy)) t = CGAffineTransformTranslate(t, 0, offset) var overshoot = offset while overshoot < pointDist(startingPoint, point2: point) { CGPathMoveToPoint (path, &t, 0, 0) CGPathAddLineToPoint(path, &t, w, -h) CGPathAddLineToPoint(path, &t, w, 0) CGPathAddLineToPoint(path, &t, 0, h) CGPathAddLineToPoint(path, &t, -w, 0) CGPathAddLineToPoint(path, &t, -w, -h) CGPathAddLineToPoint(path, &t, 0, 0) t = CGAffineTransformTranslate(t, 0, 3 * h) overshoot += 3 * h } overshoot -= pointDist(startingPoint, point2: point) CGPathMoveToPoint(path, nil, point.x, point.y) return overshoot } }
249d3dbfd81e4c0f6cb27dca94737ab3
38.2
128
0.639295
false
false
false
false
Scorocode/scorocode-SDK-swift
refs/heads/master
todolist/SCLib/Model/SCScript.swift
mit
1
// // SCScript.swift // SC // // Created by Alexey Kuznetsov on 27/12/2016. // Copyright © 2016 Prof-IT Group OOO. All rights reserved. // import Foundation public enum ScriptJobType : String { case custom = "custom" case daily = "daily" case monthly = "monthly" case once = "once" } public struct RepeatTimer { fileprivate let kRepeatTimerCustomName = "custom" fileprivate let kRepeatTimerDailyName = "daily" fileprivate let kRepeatTimerMonthlyName = "monthly" public var custom = _custom() public var daily = _daily() public var monthly = _monthly() public struct _custom { public var days = 0 public var hours = 0 public var minutes = 0 func toDict() -> [String: Any] { return ["days": self.days, "hours": self.hours, "minutes": self.minutes] } } public struct _daily { public var on = [Int]() public var hours = 0 public var minutes = 0 func toDict() -> [String: Any] { return ["on": self.on, "hours": self.hours, "minutes": self.minutes] } } public struct _monthly { public var on = [Int]() public var days = [Int]() public var lastDate = false public var hours = 0 public var minutes = 0 func toDict() -> [String: Any] { return ["on": self.on, "days": self.days, "lastDate": self.lastDate, "hours": self.hours, "minutes": self.minutes] } } public func toDict() -> [String: Any] { var dict = [String: Any]() dict.updateValue(self.custom.toDict(), forKey: kRepeatTimerCustomName) dict.updateValue(self.daily.toDict(), forKey: kRepeatTimerDailyName) dict.updateValue(self.monthly.toDict(), forKey: kRepeatTimerMonthlyName) return dict } } public class SCScript { public var id: String? public var path: String? public var name = "" public var description = "" public var code = "" public var jobStartAt = SCDate(Date()) public var isActiveJob = false public var jobType = ScriptJobType.once public var ACL = [String]() public var repeatTimer = RepeatTimer() public init(id: String) { self.id = id } public init(path: String) { self.path = path } // Запуск скрипта public func run(pool: [String: Any], debug: Bool, callback: @escaping (Bool, SCError?) -> Void) { guard self.id != nil || self.path != nil else { callback(false, SCError.system("Укажите id скрипта или путь к скрипту.")) return } SCAPI.sharedInstance.runScript(scriptId: self.id, scriptPath: self.path, pool: pool, debug: debug, callback: callback) } // Получение скрипта public func load(callback: @escaping (Bool, SCError?, [String: Any]?) -> Void) { guard self.id != nil else { callback(false, SCError.system("id скрипта не задан."), nil) return } SCAPI.sharedInstance.getScript(scriptId: self.id!) { (success, error, result, script) in if script != nil { self.path = script?.path ?? "" self.name = script?.name ?? "" self.description = script?.description ?? "" self.code = script?.code ?? "" self.jobStartAt = script?.jobStartAt ?? SCDate(Date()) self.isActiveJob = script?.isActiveJob ?? false self.jobType = script?.jobType ?? ScriptJobType.once self.ACL = script?.ACL ?? [String]() self.repeatTimer = script?.repeatTimer ?? RepeatTimer() } callback(success, error, result) } } // Создание нового скрипта public func create(callback: @escaping (Bool, SCError?, [String: Any]?) -> Void) { guard self.path != nil else { callback(false, SCError.system("путь скрипта не задан."), nil) return } SCAPI.sharedInstance.createScript(script: self, callback: callback) } // Изменение скрипта public func save(callback: @escaping (Bool, SCError?, [String: Any]?) -> Void) { guard self.id != nil else { callback(false, SCError.system("id скрипта не задан."), nil) return } SCAPI.sharedInstance.saveScript(script: self, callback: callback) } // Удаление скрипта public func delete(callback: @escaping (Bool, SCError?, [String: Any]?) -> Void) { guard self.id != nil else { callback(false, SCError.system("id скрипта не задан."), nil) return } SCAPI.sharedInstance.deleteScript(scriptId: self.id!, callback: callback) } }
b3b5d15776b674e83d15739df53cd381
31.635135
126
0.574327
false
false
false
false
aatalyk/swift-algorithm-club
refs/heads/master
Radix Sort/radixSort.swift
mit
2
/* Sorting Algorithm that sorts an input array of integers digit by digit. */ // NOTE: This implementation does not handle negative numbers func radixSort(_ array: inout [Int] ) { let radix = 10 //Here we define our radix to be 10 var done = false var index: Int var digit = 1 //Which digit are we on? while !done { //While our sorting is not completed done = true //Assume it is done for now var buckets: [[Int]] = [] //Our sorting subroutine is bucket sort, so let us predefine our buckets for _ in 1...radix { buckets.append([]) } for number in array { index = number / digit //Which bucket will we access? buckets[index % radix].append(number) if done && index > 0 { //If we arent done, continue to finish, otherwise we are done done = false } } var i = 0 for j in 0..<radix { let bucket = buckets[j] for number in bucket { array[i] = number i += 1 } } digit *= radix //Move to the next digit } }
eed4948fc94e7cef1fb62431847bc66b
22.5
103
0.579093
false
false
false
false
rain2540/RGAppTools
refs/heads/master
Sources/Extensions/Basic/Int+RGAppTools.swift
mpl-2.0
1
// // Int+RGAppTools.swift // RGAppTools // // Created by RAIN on 16/2/2. // Copyright © 2016-2017 Smartech. All rights reserved. // import UIKit extension Int { public var rat: IntExtension { return IntExtension(int: self) } public static var rat: IntExtension.Type { return IntExtension.self } } // MARK: - public struct IntExtension { private var int: Int fileprivate init(int: Int) { self.int = int } } // MARK: - Farmatted Output extension IntExtension { /// 格式化输出字符串 /// - Parameter format: 以字符串形式表示的输出格式 /// - Returns: 格式化输出结果 public func string(format: String) -> String { return String(format: "%\(format)d", int) } /// 格式化输出 /// - Parameter fmt: 以字符串形式表示的输出格式 /// - Returns: 格式化输出结果 @available(*, deprecated, renamed: "string(format:)") public func format(_ fmt: String) -> String { return String(format: "%\(fmt)d", int) } } // MARK: - Transfer extension IntExtension { /// 转换为对应的 CGFloat 值 public var cgFloatValue: CGFloat { return CGFloat(int) } } // MARK: - Random Number extension IntExtension { /// 创建 lower - upper 之间的一个随机数 /// - Parameter lower: 范围下限,默认为 0 /// - Parameter upper: 范围上限,默认为 UInt32.max /// - Returns: 获取到的随机数 public static func randomNumber( lower: Int = 0, upper: Int = Int(UInt32.max)) -> Int { return lower + Int(arc4random_uniform(UInt32(upper - lower))) } /// 创建 range 范围内的一个随机数 /// - Parameter range: 产生随机数的范围 /// - Returns: 获取到的随机数 public static func randomNumber(range: Range<Int>) -> Int { return randomNumber(lower: range.lowerBound, upper: range.upperBound) } /// 创建 lower - upper 之间的若干个随机数 /// - Parameters: /// - lower: 范围下限,默认为 0 /// - upper: 范围上限,默认为 UInt32.max /// - size: 随机数个数。默认为 10 /// - Returns: 获取到的随机数数组 public static func randomNumbers( lower: Int = 0, upper: Int = Int(UInt32.max), size: Int = 10) -> [Int] { var res: [Int] = [] for _ in 0 ..< size { res.append(randomNumber(lower: lower, upper: upper)) } return res } /// 创建 range 范围内的若干个随机数 /// - Parameters: /// - range: 产生随机数的范围 /// - size: 随机数个数,默认为 10 /// - Returns: 获取到的随机数数组 public static func randomNumbers( range: Range<Int>, size: Int = 10) -> [Int] { var res: [Int] = [] for _ in 0 ..< size { res.append(randomNumber(range: range)) } return res } }
2f6d0d03043b9ecb2d33a4ea17182f61
18.03937
73
0.609595
false
false
false
false
yasuoza/graphPON
refs/heads/master
graphPON iOS/ViewControllers/DailyChartViewController.swift
mit
1
import UIKit import GraphPONDataKit import JBChartFramework class DailyChartViewController: BaseChartViewController, JBBarChartViewDelegate, JBBarChartViewDataSource, HddServiceListTableViewControllerDelegate, DisplayPacketLogsSelectTableViewControllerDelegate { @IBOutlet weak var chartViewContainerView: ChartViewContainerView! let mode: Mode = .Daily private var chartData: [CGFloat]? private var chartHorizontalData: [String]? private var hdoService: HdoService? { didSet { self.serviceCode = hdoService?.hdoServiceCode } } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = self.mode.backgroundColor() self.chartViewContainerView.chartView.delegate = self self.chartViewContainerView.chartView.dataSource = self self.chartViewContainerView.chartView.headerPadding = kJBAreaChartViewControllerChartHeaderPadding self.chartViewContainerView.chartView.footerPadding = kJBAreaChartViewControllerChartFooterPadding self.chartViewContainerView.chartView.backgroundColor = self.mode.backgroundColor() let footerView = LineChartFooterView(frame: CGRectMake( self.chartViewContainerView.chartView.frame.origin.x, ceil(self.view.bounds.size.height * 0.5) - ceil(kJBLineChartViewControllerChartFooterHeight * 0.5), self.chartViewContainerView.chartView.bounds.width, kJBLineChartViewControllerChartFooterHeight + kJBLineChartViewControllerChartPadding )) footerView.backgroundColor = UIColor.clearColor() footerView.leftLabel.textColor = UIColor.whiteColor() footerView.rightLabel.textColor = UIColor.whiteColor() self.chartViewContainerView.chartView.footerView = footerView self.chartInformationView.setHidden(true, animated: false) if self.serviceCode == nil { if let hdoService = PacketInfoManager.sharedManager.hddServices.first?.hdoServices?.first { self.hdoService = hdoService } } self.reBuildChartData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.reloadChartView(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserverForName( PacketInfoManager.LatestPacketLogsDidFetchNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { _ in self.reBuildChartData() self.reloadChartView(true) }) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - Actions override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "HddServiceListFromDailyChartSegue" { let navigationController = segue.destinationViewController as! UINavigationController let hddServiceListViewController = navigationController.topViewController as! HddServiceListTableViewController hddServiceListViewController.delegate = self hddServiceListViewController.mode = .Daily hddServiceListViewController.selectedService = self.hdoService?.number ?? "" } else if segue.identifier == "DisplayPacketLogsSelectFromSummaryChartSegue" { let navigationController = segue.destinationViewController as! UINavigationController let displayPacketLogSelectViewController = navigationController.topViewController as! DisplayPacketLogsSelectTableViewController displayPacketLogSelectViewController.delegate = self displayPacketLogSelectViewController.selectedFilteringSegment = self.chartDataFilteringSegment } } @IBAction func chartSegmentedControlValueDidChanged(segmentedControl: UISegmentedControl) { self.chartDurationSegment = HdoService.Duration(rawValue: segmentedControl.selectedSegmentIndex)! self.reBuildChartData() self.reloadChartView(false) } func reloadChartView(animated: Bool) { if let hdoService = self.hdoService { self.navigationItem.title = "\(hdoService.nickName) (\(self.chartDataFilteringSegment.text()))" } if let chartData = self.chartData where chartData.count > 0 { self.chartViewContainerView.chartView.minimumValue = 0 self.chartViewContainerView.chartView.maximumValue = maxElement(chartData) } if let footerView = self.chartViewContainerView.chartView.footerView as? LineChartFooterView { footerView.leftLabel.text = self.hdoService?.packetLogs.first?.dateText() footerView.rightLabel.text = self.hdoService?.packetLogs.last?.dateText() footerView.sectionCount = self.chartData?.count ?? 0 footerView.hidden = footerView.sectionCount == 0 } self.displayLatestTotalChartInformation() self.chartViewContainerView.reloadChartData() self.chartViewContainerView.chartView.setState(JBChartViewState.Expanded, animated: animated) } func displayLatestTotalChartInformation() { if let packetLog = self.hdoService?.packetLogs.last { self.chartInformationView.setTitleText( String(format: NSLocalizedString("Used in %@", comment: "Chart information title text in daily chart"), packetLog.dateText()) ) self.chartInformationView.setHidden(false, animated: true) } else { self.chartInformationView.setHidden(true, animated: false) self.informationValueLabelSeparatorView.alpha = 0.0 self.valueLabel.alpha = 0.0 return } UIView.animateWithDuration(NSTimeInterval(kJBChartViewDefaultAnimationDuration) * 0.5, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.informationValueLabelSeparatorView.alpha = 1.0 self.valueLabel.text = PacketLog.stringForValue(self.chartData?.last) self.valueLabel.alpha = 1.0 }, completion: nil ) } // MARK: - Private methods func reBuildChartData() { if let hdoService = PacketInfoManager.sharedManager.hdoServiceForServiceCode(self.serviceCode) ?? PacketInfoManager.sharedManager.hddServices.first?.hdoServices?.first { self.hdoService = hdoService } else { return } self.chartData = self.hdoService?.summarizeServiceUsageInDuration( self.chartDurationSegment, couponSwitch: self.chartDataFilteringSegment ) self.chartHorizontalData = self.hdoService?.packetLogs.map { $0.dateText() } } // MARK: - JBLineChartViewDataSource func numberOfBarsInBarChartView(barChartView: JBBarChartView!) -> UInt { return UInt(self.chartData?.count ?? 0) } // MARK: - JBLineChartViewDelegate func barChartView(barChartView: JBBarChartView!, heightForBarViewAtIndex index: UInt) -> CGFloat { return self.chartData?[Int(index)] ?? 0.0 } func barChartView(barChartView: JBBarChartView!, didSelectBarAtIndex index: UInt, touchPoint: CGPoint) { let dateText = self.chartHorizontalData?[Int(index)] ?? "" self.chartInformationView.setTitleText( String(format: NSLocalizedString("Used in %@", comment: "Chart information title text in daily chart"), dateText) ) self.chartInformationView.setHidden(false, animated: true) UIView.animateWithDuration( NSTimeInterval(kJBChartViewDefaultAnimationDuration) * 0.5, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.valueLabel.text = PacketLog.stringForValue(self.chartData?[Int(index)]) self.valueLabel.alpha = 1.0 }, completion: nil ) } func didDeselectBarChartView(barChartView: JBBarChartView!) { self.chartInformationView.setHidden(true, animated: true) UIView.animateWithDuration( NSTimeInterval(kJBChartViewDefaultAnimationDuration) * 0.5, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.valueLabel.alpha = 0.0 }, completion: { [unowned self] finish in if finish { self.displayLatestTotalChartInformation() } } ) } func barChartView(barChartView: JBBarChartView!, colorForBarViewAtIndex index: UInt) -> UIColor! { return UIColor.whiteColor() } func barSelectionColorForBarChartView(barChartView: JBBarChartView!) -> UIColor! { return UIColor(red:0.392, green:0.392, blue:0.559, alpha:1.0) } // MARK: - HddServiceListTableViewControllerDelegate func serviceDidSelectedSection(section: Int, row: Int) { self.hdoService = PacketInfoManager.sharedManager.hddServices[section].hdoServices?[row] self.reBuildChartData() if self.traitCollection.horizontalSizeClass == .Regular { self.reloadChartView(true) } } // MARK: - DisplayPacketLogsSelectTableViewControllerDelegate func displayPacketLogSegmentDidSelected(segment: Int) { self.chartDataFilteringSegment = Coupon.Switch(rawValue: segment)! self.reBuildChartData() if self.traitCollection.horizontalSizeClass == .Regular { self.reloadChartView(true) } } }
c83757ef5a9da6f6f8de02c2733e8778
39.63786
202
0.680506
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
refs/heads/master
Libraries/SwiftyJSON/Source/SwiftyJSON.swift
apache-2.0
3
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // 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 // MARK: - Error ///Error domain public let ErrorDomain: String! = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: error The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) self.init(object) } catch let error1 as NSError { error.memory = error1 self.init(NSNull()) } } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /// Private object private var _object: AnyObject = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? /// Object in JSON public var object: AnyObject { get { return _object } set { _object = newValue switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } case _ as NSString: _type = .String case _ as NSNull: _type = .Null case _ as NSArray: _type = .Array case _ as NSDictionary: _type = .Dictionary default: _type = .Unknown _object = NSNull() _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json public static var nullJSON: JSON { get { return JSON(NSNull()) } } } // MARK: - SequenceType extension JSON : Swift.SequenceType { /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. public var isEmpty: Bool { get { switch self.type { case .Array: return (self.object as! [AnyObject]).isEmpty case .Dictionary: return (self.object as! [String : AnyObject]).isEmpty default: return false } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { get { switch self.type { case .Array: return self.arrayValue.count case .Dictionary: return self.dictionaryValue.count default: return 0 } } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of this *sequence*. */ public func generate() -> AnyGenerator<(String, JSON)> { switch self.type { case .Array: let array_ = object as! [AnyObject] var generate_ = array_.generate() var index_: Int = 0 return AnyGenerator { if let element_: AnyObject = generate_.next() { let result = ("\(index_)", JSON(element_)) index_ += 1 return result } else { return nil } } case .Dictionary: let dictionary_ = object as! [String : AnyObject] var generate_ = dictionary_.generate() return AnyGenerator { if let (key_, value_): (String, AnyObject) = generate_.next() { return (key_, JSON(value_)) } else { return nil } } default: return AnyGenerator { return nil } } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public protocol SubscriptType {} extension Int: SubscriptType {} extension String: SubscriptType {} extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { var errorResult_ = JSON.nullJSON errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return errorResult_ } let array_ = self.object as! [AnyObject] if index >= 0 && index < array_.count { return JSON(array_[index]) } var errorResult_ = JSON.nullJSON errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return errorResult_ } set { if self.type == .Array { var array_ = self.object as! [AnyObject] if array_.count > index { array_[index] = newValue.object self.object = array_ } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var returnJSON = JSON.nullJSON if self.type == .Dictionary { let dictionary_ = self.object as! NSDictionary if let object_: AnyObject = dictionary_[key] { returnJSON = JSON(object_) } else { returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return returnJSON } set { if self.type == .Dictionary { var dictionary_ = self.object as! [String : AnyObject] dictionary_[key] = newValue.object self.object = dictionary_ } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: SubscriptType) -> JSON { get { if sub is String { return self[key:sub as! String] } else { return self[index:sub as! Int] } } set { if sub is String { self[key:sub as! String] = newValue } else { self[index:sub as! Int] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [SubscriptType]) -> JSON { get { if path.count == 0 { return JSON.nullJSON } var next = self for sub in path { next = next[sub:sub] } return next } set { switch path.count { case 0: return case 1: self[sub:path[0]] = newValue default: var last = newValue var newPath = path newPath.removeLast() for sub in Array(path.reverse()) { var previousLast = self[newPath] previousLast[sub:sub] = last last = previousLast if newPath.count <= 1 { break } newPath.removeLast() } self[sub:newPath[0]] = last } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: SubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { var dictionary_ = [String : AnyObject]() for (key_, value) in elements { dictionary_[key_] = value } self.init(dictionary_) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: do { let data = try self.rawData(options: opt) return NSString(data: data, encoding: encoding) as? String } catch _ { return nil } case .String: return (self.object as! String) case .Number: return (self.object as! NSNumber).stringValue case .Bool: return (self.object as! Bool).description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return (self.object as! [AnyObject]).map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.object as? [AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableArray(array: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] { var result = [Key: NewValue](minimumCapacity:source.count) for (key,value) in source { result[key] = transform(value) } return result } //Optional [String : JSON] public var dictionary: [String : JSON]? { get { if self.type == .Dictionary { return _map(self.object as! [String : AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { get { return self.dictionary ?? [:] } } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.object as? [String : AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.object.boolValue default: return nil } } set { if newValue != nil { self.object = NSNumber(bool: newValue!) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if newValue != nil { self.object = NSString(string:newValue!) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as! String case .Number: return self.object.stringValue case .Bool: return (self.object as! Bool).description default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.object as? NSNumber default: return nil } } set { self.object = newValue?.copy() ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let scanner = NSScanner(string: self.object as! String) if scanner.scanDouble(nil){ if (scanner.atEnd) { return NSNumber(double:(self.object as! NSString).doubleValue) } } return NSNumber(double: 0.0) case .Number, .Bool: return self.object as! NSNumber default: return NSNumber(double: 0.0) } } set { self.object = newValue.copy() } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return NSNull() default: return nil } } set { self.object = NSNull() } } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if newValue != nil { self.object = NSNumber(double: newValue!) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if newValue != nil { self.object = NSNumber(float: newValue!) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if newValue != nil { self.object = NSNumber(integer: newValue!) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLong: newValue!) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if newValue != nil { self.object = NSNumber(char: newValue!) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if newValue != nil { self.object = NSNumber(unsignedChar: newValue!) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if newValue != nil { self.object = NSNumber(short: newValue!) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if newValue != nil { self.object = NSNumber(unsignedShort: newValue!) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if newValue != nil { self.object = NSNumber(int: newValue!) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if newValue != nil { self.object = NSNumber(unsignedInt: newValue!) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if newValue != nil { self.object = NSNumber(longLong: newValue!) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLongLong: newValue!) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON: Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) == (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) == (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) <= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) >= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) > (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) > (rhs.object as! String) default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) < (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) < (rhs.object as! String) default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber: Swift.Comparable { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } } //MARK:- Unavailable @available(*, unavailable, renamed="JSON") public typealias JSONValue = JSON extension JSON { @available(*, unavailable, message="use 'init(_ object:AnyObject)' instead") public init(object: AnyObject) { self = JSON(object) } @available(*, unavailable, renamed="dictionaryObject") public var dictionaryObjects: [String : AnyObject]? { get { return self.dictionaryObject } } @available(*, unavailable, renamed="arrayObject") public var arrayObjects: [AnyObject]? { get { return self.arrayObject } } @available(*, unavailable, renamed="int8") public var char: Int8? { get { return self.number?.charValue } } @available(*, unavailable, renamed="int8Value") public var charValue: Int8 { get { return self.numberValue.charValue } } @available(*, unavailable, renamed="uInt8") public var unsignedChar: UInt8? { get{ return self.number?.unsignedCharValue } } @available(*, unavailable, renamed="uInt8Value") public var unsignedCharValue: UInt8 { get{ return self.numberValue.unsignedCharValue } } @available(*, unavailable, renamed="int16") public var short: Int16? { get{ return self.number?.shortValue } } @available(*, unavailable, renamed="int16Value") public var shortValue: Int16 { get{ return self.numberValue.shortValue } } @available(*, unavailable, renamed="uInt16") public var unsignedShort: UInt16? { get{ return self.number?.unsignedShortValue } } @available(*, unavailable, renamed="uInt16Value") public var unsignedShortValue: UInt16 { get{ return self.numberValue.unsignedShortValue } } @available(*, unavailable, renamed="int") public var long: Int? { get{ return self.number?.longValue } } @available(*, unavailable, renamed="intValue") public var longValue: Int { get{ return self.numberValue.longValue } } @available(*, unavailable, renamed="uInt") public var unsignedLong: UInt? { get{ return self.number?.unsignedLongValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedLongValue: UInt { get{ return self.numberValue.unsignedLongValue } } @available(*, unavailable, renamed="int64") public var longLong: Int64? { get{ return self.number?.longLongValue } } @available(*, unavailable, renamed="int64Value") public var longLongValue: Int64 { get{ return self.numberValue.longLongValue } } @available(*, unavailable, renamed="uInt64") public var unsignedLongLong: UInt64? { get{ return self.number?.unsignedLongLongValue } } @available(*, unavailable, renamed="uInt64Value") public var unsignedLongLongValue: UInt64 { get{ return self.numberValue.unsignedLongLongValue } } @available(*, unavailable, renamed="int") public var integer: Int? { get { return self.number?.integerValue } } @available(*, unavailable, renamed="intValue") public var integerValue: Int { get { return self.numberValue.integerValue } } @available(*, unavailable, renamed="uInt") public var unsignedInteger: Int? { get { return self.number.flatMap{ Int($0) } } } @available(*, unavailable, renamed="uIntValue") public var unsignedIntegerValue: Int { get { return Int(self.numberValue.unsignedIntegerValue) } } }
8fd7afdf0229164a5de37989de5a93b4
25.476718
264
0.526505
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/TextBarButtonItem.swift
mit
1
import UIKit /// A Themeable UIBarButtonItem with title text only class TextBarButtonItem: UIBarButtonItem, Themeable { // MARK: - Properties private var theme: Theme? override var isEnabled: Bool { get { return super.isEnabled } set { super.isEnabled = newValue if let theme = theme { apply(theme: theme) } } } // MARK: - Lifecycle @objc convenience init(title: String, target: Any?, action: Selector?) { self.init(title: title, style: .plain, target: target, action: action) } // MARK: - Themeable public func apply(theme: Theme) { self.theme = theme if let customView = customView as? UIButton { customView.tintColor = isEnabled ? theme.colors.link : theme.colors.disabledLink } else { tintColor = isEnabled ? theme.colors.link : theme.colors.disabledLink } } }
af171da741078e091049b7bf60ccacee
23.794872
92
0.585315
false
false
false
false
NoManTeam/Hole
refs/heads/master
CryptoFramework/Crypto/Algorithm/AES_256_ECB/NSAESString.swift
unlicense
1
// // NSAESString.swift // 密语输入法 // // Created by macsjh on 15/10/17. // Copyright © 2015年 macsjh. All rights reserved. // import Foundation class NSAESString:NSObject { internal static func aes256_encrypt(PlainText:NSString, Key:NSString) -> NSString? { let cstr:UnsafePointer<Int8> = PlainText.cStringUsingEncoding(NSUTF8StringEncoding) let data = NSData(bytes: cstr, length:PlainText.length) //对数据进行加密 let result = data.aes256_encrypt(Key) if (result != nil && result!.length > 0 ) { return result!.toHexString() } return nil } internal static func aes256_decrypt(CipherText:String, key:NSString) -> NSString? { //转换为2进制Data guard let data = CipherText.hexStringToData() else {return nil} //对数据进行解密 let result = data.aes256_decrypt(key) if (result != nil && result!.length > 0) { return NSString(data:result!, encoding:NSUTF8StringEncoding) } return nil } }
8ce00b9b0062e786e1f1b0c07c7dc88f
24.942857
85
0.708931
false
false
false
false
aksskas/DouYuZB
refs/heads/master
DYZB/DYZB/Classes/Main/View/PageContentView.swift
mit
1
// // PageContentView.swift // DYZB // // Created by aksskas on 2017/9/19. // Copyright © 2017年 aksskas. All rights reserved. // import UIKit protocol PageContentViewDelegate: class { func pageContentView(contentView: PageContentView,progress: CGFloat, sourceIndex: Int, targetIndex: Int) } private let contentCellID = "contentCell" class PageContentView: UIView { //MARK:- 定义属性 private var childVcs: [UIViewController] private var startOffsetX: CGFloat = 0 weak var delegate: PageContentViewDelegate? private weak var parentViewController: UIViewController? //MARK:- 懒加载属性 private lazy var collectionView: UICollectionView = { [weak self] in let layout = UICollectionViewFlowLayout().then { $0.itemSize = self!.bounds.size $0.minimumLineSpacing = 0 $0.minimumInteritemSpacing = 0 $0.scrollDirection = .horizontal } let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout).then { $0.showsVerticalScrollIndicator = false $0.isPagingEnabled = true $0.bounces = false } //设置数据源相关 collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID) collectionView.dataSource = self collectionView.delegate = self return collectionView }() //MARK:- 自定义构造函数 init(frame: CGRect, childVcs: [UIViewController], parentController: UIViewController?) { self.childVcs = childVcs self.parentViewController = parentController super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:- 设置UI extension PageContentView { private func setupUI() { for childVc in childVcs { parentViewController?.addChildViewController(childVc) childVc.view.frame = bounds } addSubview(collectionView) collectionView.frame = bounds } } //MARK:- CollectionView 数据源 extension PageContentView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } cell.contentView.addSubview(childVcs[indexPath.item].view!) return cell } } //MARK:- Delegate extension PageContentView: UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { var progress: CGFloat = 0 var targetIndex: Int = 0 var sourceIndex: Int = 0 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { //左滑 progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) sourceIndex = Int(currentOffsetX / scrollViewW) targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { //右滑 progress = 1 - currentOffsetX / scrollViewW + floor(currentOffsetX / scrollViewW) targetIndex = Int(currentOffsetX / scrollViewW) sourceIndex = targetIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } } delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //MARK:- 对外暴露设置的方法 extension PageContentView { func setCurrentIndex(currentIndex index: Int) { let offsetX = CGFloat(index) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
3b75fdc8af65b4fbbd4a6646c95c01c7
30.386207
124
0.640299
false
false
false
false
toddkramer/Archiver
refs/heads/master
Sources/Archivable.swift
mit
1
// // Archivable.swift // // Copyright (c) 2016 Todd Kramer (http://www.tekramer.com) // // 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 public typealias Archive = [String: Any] public protocol Archivable: ArchiveRepresentable, UniquelyIdentifiable { static var archiver: Archiver { get } static var directoryName: String { get } init?(resourceID: String) func storeArchive() func deleteArchive() } extension Archivable { public static var archiver: Archiver { return .default } public static var directoryName: String { return String(describing: self) } static var directoryURL: URL? { return archiver.archiveDirectoryURL?.appendingPathComponent(directoryName) } var fileURL: URL? { return Self.directoryURL?.appendingPathComponent("\(id).plist") } public init?(resourceID: String) { let url = Self.directoryURL?.appendingPathComponent("\(resourceID).plist") guard let path = url?.path else { return nil } guard let archive = Self.archiver.archive(atPath: path) else { return nil } self.init(archive: archive) } public func storeArchive() { guard let directoryPath = Self.directoryURL?.path else { return } Self.archiver.createDirectoryIfNeeded(atPath: directoryPath) guard let path = fileURL?.path else { return } Self.archiver.store(archive: archiveValue, atPath: path) } public func deleteArchive() { guard let path = fileURL?.path else { return } Self.archiver.deleteArchive(atPath: path) } } extension Archivable { public static func unarchivedCollection(withIdentifiers identifiers: [String]) -> [Self] { return identifiers.flatMap { Self(resourceID: $0) } } } extension Array where Element: Archivable { public func storeArchives() { forEach { $0.storeArchive() } } }
88f79d7dd69f6c29b4f499d7558718e0
32.314607
94
0.703879
false
false
false
false
raulriera/Bike-Compass
refs/heads/master
App/Carthage/Checkouts/Alamofire/Source/ParameterEncoding.swift
mit
2
// // ParameterEncoding.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /** HTTP method definitions. See https://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } // MARK: ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. - `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. */ public enum ParameterEncoding { case url case urlEncodedInURL case json case propertyList(PropertyListSerialization.PropertyListFormat, PropertyListSerialization.WriteOptions) case custom((URLRequestConvertible, [String: AnyObject]?) -> (URLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. - parameter URLRequest: The request to have parameters applied. - parameter parameters: The parameters to apply. - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode( _ URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (Foundation.URLRequest, NSError?) { var urlRequest = URLRequest.urlRequest guard let parameters = parameters else { return (urlRequest, nil) } var encodingError: NSError? = nil switch self { case .url, .urlEncodedInURL: func query(_ parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(isOrderedBefore: <) { let value = parameters[key]! components += queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joined(separator: "&") } func encodesParametersInURL(_ method: Method) -> Bool { switch self { case .urlEncodedInURL: return true default: break } switch method { case .GET, .HEAD, .DELETE: return true default: return false } } if let method = Method(rawValue: urlRequest.httpMethod!) where encodesParametersInURL(method) { if var URLComponents = URLComponents(url: urlRequest.url!, resolvingAgainstBaseURL: false) where !parameters.isEmpty { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = URLComponents.url } } else { if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue( "application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type" ) } urlRequest.httpBody = query(parameters).data( using: String.Encoding.utf8, allowLossyConversion: false ) } case .json: do { let options = JSONSerialization.WritingOptions() let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { encodingError = error as NSError } case .propertyList(let format, let options): do { let data = try PropertyListSerialization.data( fromPropertyList: parameters, format: format, options: options ) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { encodingError = error as NSError } case .custom(let closure): (urlRequest, encodingError) = closure(urlRequest, parameters) } return (urlRequest, encodingError) } /** Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - parameter key: The key of the query component. - parameter value: The value of the query component. - returns: The percent-escaped, URL encoded query string components. */ public func queryComponents(_ key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.append((escape(key), escape("\(value)"))) } return components } /** Returns a percent-escaped string following RFC 3986 for a query string key or value. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent-escaped in the query string. - parameter string: The string to be percent-escaped. - returns: The percent-escaped string. */ public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" // rdar://26850776 // Crash in Xcode 8 Seed 1 when trying to mutate a CharacterSet with remove var allowedCharacterSet = NSMutableCharacterSet.urlQueryAllowed() allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, OSX 10.10, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) let range = startIndex..<(endIndex ?? string.endIndex) let substring = string.substring(with: range) escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring index = endIndex ?? string.endIndex } } return escaped } }
9a2a36e025c593c3416ff76a7e58ee6d
42.288973
124
0.58173
false
false
false
false
JiriTrecak/Warp
refs/heads/master
Source/WRPObject.swift
mit
1
// // WRPObject.swift // // Copyright (c) 2016 Jiri Trecak (http://jiritrecak.com/) // // 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. // // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Imports import Foundation // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Definitions // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Extension // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Protocols // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Implementation open class WRPObject: NSObject { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Properties // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Setup override public init() { super.init() // No initialization required - nothing to fill object with } convenience public init(fromJSON: String) { if let jsonData: Data = fromJSON.data(using: String.Encoding.utf8, allowLossyConversion: true) { do { let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? self.init(parameters: jsonObject as! NSDictionary) } catch let error as NSError { self.init(parameters: [:]) print ("Error while parsing a json object: \(error.domain)") } } else { self.init(parameters: NSDictionary()) } } convenience public init(fromDictionary: NSDictionary) { self.init(parameters: fromDictionary) } required public init(parameters: NSDictionary) { super.init() self.preInit() if self.debugInstantiate() { NSLog("Object type %@\nParsing using %@", self.self, parameters) } self.fillValues(parameters) self.processClosestRelationships(parameters) self.postInit() } required public init(parameters: NSDictionary, parentObject: WRPObject?) { super.init() self.preInit() if self.debugInstantiate() { NSLog("Object type %@\nParsing using %@", self.self, parameters) } self.fillValues(parameters) self.processClosestRelationships(parameters, parentObject: parentObject) self.postInit() } open static func fromArrayInJson<T: WRPObject>(_ fromJSON: String) -> [T] { if let jsonData: Data = fromJSON.data(using: String.Encoding.utf8, allowLossyConversion: true) { do { var buffer: [T] = [] let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? for jsonDictionary in jsonObject as! NSArray { let object = T(parameters: jsonDictionary as! NSDictionary) buffer.append(object) } return buffer } catch let error as NSError { print ("Error while parsing a json object: \(error.domain)") return [] } } else { return [] } } open static func fromArray<T: WRPObject>(_ object: NSArray) -> [T] { var buffer: [T] = [] for jsonDictionary in object { let object = T(parameters: jsonDictionary as! NSDictionary) buffer.append(object) } return buffer } open static func fromArrayInJson<T: WRPObject>(_ fromJSON: String, modelClassTypeKey : String, modelClassTransformer : ((String) -> WRPObject.Type?)) -> [T] { if let jsonData: Data = fromJSON.data(using: String.Encoding.utf8, allowLossyConversion: true) { do { var buffer: [WRPObject] = [] let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? for object: Any in jsonObject as! NSArray { if let jsonDictionary = object as? NSDictionary, let key = jsonDictionary[modelClassTypeKey] as? String { let type = modelClassTransformer(key) if let type = type { let object = type.init(parameters: jsonDictionary) buffer.append(object) } } } return buffer as! [T] } catch let error as NSError { print ("Error while parsing a json object: \(error.domain)") return [] } } else { return [] } } open static func fromArray<T: WRPObject>(_ object: NSArray, modelClassTypeKey : String, modelClassTransformer : ((String) -> WRPObject.Type?)) -> [T] { var buffer: [WRPObject] = [] for object: Any in object { if let jsonDictionary = object as? NSDictionary, let key = jsonDictionary[modelClassTypeKey] as? String { let type = modelClassTransformer(key) if let type = type { let object = type.init(parameters: jsonDictionary) buffer.append(object) } } } return buffer as! [T] } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - User overrides for data mapping open func propertyMap() -> [WRPProperty] { return [] } open func relationMap() -> [WRPRelation] { return [] } open func preInit() { } open func postInit() { } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Private fileprivate func fillValues(_ parameters: NSDictionary) { for element: WRPProperty in self.propertyMap() { // Dot convention self.assignValueForElement(element, parameters: parameters) } } fileprivate func processClosestRelationships(_ parameters: NSDictionary) { self.processClosestRelationships(parameters, parentObject: nil) } fileprivate func processClosestRelationships(_ parameters: NSDictionary, parentObject: WRPObject?) { for element in self.relationMap() { self.assignDataObjectForElement(element, parameters: parameters, parentObject: parentObject) } } fileprivate func assignValueForElement(_ element: WRPProperty, parameters: NSDictionary) { switch element.elementDataType { // Handle string data type case .string: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.stringFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle boolean data type case .bool: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.boolFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle double data type case .double: for elementRemoteName in element.remoteNames { if (self.setValue(.double, value: self.doubleFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle float data type case .float: for elementRemoteName in element.remoteNames { if (self.setValue(.float, value: self.floatFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle int data type case .int: for elementRemoteName in element.remoteNames { if (self.setValue(.int, value: self.intFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle int data type case .number: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.numberFromParameters(parameters, key: elementRemoteName), forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle date data type case .date: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.dateFromParameters(parameters, key: elementRemoteName, format: element.format) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle array data type case .array: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.arrayFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle dictionary data type case .dictionary: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.dictionaryFromParameters(parameters, key: elementRemoteName), forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } } } @discardableResult fileprivate func assignDataObjectForElement(_ element: WRPRelation, parameters: NSDictionary, parentObject: WRPObject?) -> WRPObject? { switch element.relationshipType { case .toOne: return self.handleToOneRelationshipWithElement(element, parameters: parameters, parentObject: parentObject) case .toMany: self.handleToManyRelationshipWithElement(element, parameters: parameters, parentObject: parentObject) } return nil } fileprivate func handleToOneRelationshipWithElement(_ element: WRPRelation, parameters: NSDictionary, parentObject: WRPObject?) -> WRPObject? { if let objectData: AnyObject? = parameters.value(forKeyPath: element.remoteName) as AnyObject?? { if objectData is NSDictionary { guard let classType = self.elementClassType(objectData as! NSDictionary, relationDescriptor: element) else { return nil } // Create object let dataObject = self.dataObjectFromParameters(objectData as! NSDictionary, objectType: classType, parentObject: parentObject) // Set child object to self.property self.setValue(.any, value: dataObject, forKey: element.localName, optional: element.optional, temporaryOptional: false) // Set inverse relationship if let inverseRelationshipType = element.inverseRelationshipType, let inverseKey = element.inverseName { if inverseRelationshipType == .toOne { dataObject.setValue(.any, value: self, forKey: inverseKey, optional: true, temporaryOptional: true) // If the relationship is to .ToMany, then create data pack for that } else if inverseRelationshipType == .toMany { var objects: [WRPObject]? = [WRPObject]() objects?.append(self) dataObject.setValue(.any, value: objects as AnyObject?, forKey: inverseKey, optional: true, temporaryOptional: true) } } return dataObject } else if objectData is NSNull { // Set empty object to self.property self.setValue(.any, value: nil, forKey: element.localName, optional: element.optional, temporaryOptional: false) return nil } } return nil } fileprivate func handleToManyRelationshipWithElement(_ element: WRPRelation, parameters: NSDictionary, parentObject: WRPObject?) { if let objectDataPack: AnyObject? = parameters.value(forKeyPath: element.remoteName) as AnyObject?? { // While the relationship is .ToMany, we can actually add it from single entry if objectDataPack is NSDictionary { // Always override local property, there is no inserting allowed var objects: [WRPObject]? = [WRPObject]() self.setValue(objects, forKey: element.localName) guard let classType = self.elementClassType(objectDataPack as! NSDictionary, relationDescriptor: element) else { return } // Create object let dataObject = self.dataObjectFromParameters(objectDataPack as! NSDictionary, objectType: classType, parentObject: parentObject) // Set inverse relationship if let inverseRelationshipType = element.inverseRelationshipType, let inverseKey = element.inverseName { if inverseRelationshipType == .toOne { dataObject.setValue(.any, value: self, forKey: inverseKey, optional: true, temporaryOptional: true) // If the relationship is to .ToMany, then create data pack for that } else if inverseRelationshipType == .toMany { var objects: [WRPObject]? = [WRPObject]() objects?.append(self) dataObject.setValue(.any, value: objects as AnyObject?, forKey: inverseKey, optional: true, temporaryOptional: true) } } // Append new data object to array objects!.append(dataObject) // Write new objects back self.setValue(objects, forKey: element.localName) // More objects in the same entry } else if objectDataPack is NSArray { // Always override local property, there is no inserting allowed var objects: [WRPObject]? = [WRPObject]() self.setValue(objects, forKey: element.localName) // Fill that property with data for objectData in (objectDataPack as! NSArray) { // Skip generation of this object, if the class does not exist guard let classType = self.elementClassType(objectData as! NSDictionary, relationDescriptor: element) else { continue } // Create object let dataObject = self.dataObjectFromParameters(objectData as! NSDictionary, objectType: classType, parentObject: parentObject) // Assign inverse relationship if let inverseRelationshipType = element.inverseRelationshipType, let inverseKey = element.inverseName { if inverseRelationshipType == .toOne { dataObject.setValue(.any, value: self, forKey: inverseKey, optional: true, temporaryOptional: true) // If the relationship is to .ToMany, then create data pack for that } else { var objects: [WRPObject]? = [WRPObject]() objects?.append(self) dataObject.setValue(.any, value: objects as AnyObject?, forKey: inverseKey, optional: true, temporaryOptional: true) } } // Append new data objects!.append(dataObject) } // Write new objects back self.setValue(objects, forKey: element.localName) // Null encountered, null the output } else if objectDataPack is NSNull { self.setValue(nil, forKey: element.localName) } } } fileprivate func elementClassType(_ element: NSDictionary, relationDescriptor: WRPRelation) -> WRPObject.Type? { // If there is only one class to pick from (no transform function), return the type if let type = relationDescriptor.modelClassType { return type // Otherwise use transformation function to get object type from string key } else if let transformer = relationDescriptor.modelClassTypeTransformer, let key = relationDescriptor.modelClassTypeKey { return transformer(element.object(forKey: key) as! String) } // Transformation failed // TODO: Better error handling return WRPObject.self } @discardableResult fileprivate func setValue(_ type: WRPPropertyAssignement, value: AnyObject?, forKey key: String, optional: Bool, temporaryOptional: Bool) -> Bool { if ((optional || temporaryOptional) && value == nil) { return false } if type == .any { self.setValue(value, forKey: key) } else if type == .double { if value is Double { self.setValue(value as! NSNumber, forKey: key) } else if value is NSNumber { self.setValue(value?.doubleValue, forKey: key) } else { self.setValue(nil, forKey: key) } } else if type == .int { if value is Int { self.setValue(value as! NSNumber, forKey: key) } else if value is NSNumber { self.setValue(Int32(value as! NSNumber), forKey: key) } else { self.setValue(nil, forKey: key) } } else if type == .float { if value is Float { self.setValue(value as! NSNumber, forKey: key) } else if value is NSNumber { self.setValue(value?.floatValue, forKey: key) } else { self.setValue(nil, forKey: key) } } return true } fileprivate func setDictionary(_ value: Dictionary<AnyKey, AnyKey>?, forKey: String, optional: Bool, temporaryOptional: Bool) -> Bool { if ((optional || temporaryOptional) && value == nil) { return false } self.setValue((value as AnyObject), forKey: forKey) return true } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Variable creation fileprivate func stringFromParameters(_ parameters: NSDictionary, key: String) -> String? { if let value: NSString = parameters.value(forKeyPath: key) as? NSString { return value as String } return nil } fileprivate func numberFromParameters(_ parameters: NSDictionary, key: String) -> NSNumber? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return value as NSNumber } return nil } fileprivate func intFromParameters(_ parameters: NSDictionary, key: String) -> Int? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return Int(value) } else if wrappedValue = parameters.value(forKeyPath: key) as? String, let value = Int(wrappedValue) { return value } return nil } fileprivate func doubleFromParameters(_ parameters: NSDictionary, key: String) -> Double? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return Double(value) } else if wrappedValue = parameters.value(forKeyPath: key) as? String, let value = Double(wrappedValue) { return value } return nil } fileprivate func floatFromParameters(_ parameters: NSDictionary, key: String) -> Float? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return Float(value) } else if wrappedValue = parameters.value(forKeyPath: key) as? String, let value = Float(wrappedValue) { return value } return nil } fileprivate func boolFromParameters(_ parameters: NSDictionary, key: String) -> Bool? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return Bool(value) } return nil } fileprivate func dateFromParameters(_ parameters: NSDictionary, key: String, format: String?) -> Date? { if let value: String = parameters.value(forKeyPath: key) as? String { // Create date formatter let dateFormatter: DateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: value) } return nil } fileprivate func arrayFromParameters(_ parameters: NSDictionary, key: String) -> Array<AnyObject>? { if let value: Array = parameters.value(forKeyPath: key) as? Array<AnyObject> { return value } return nil } fileprivate func dictionaryFromParameters(_ parameters: NSDictionary, key: String) -> NSDictionary? { if let value: NSDictionary = parameters.value(forKeyPath: key) as? NSDictionary { return value } return nil } fileprivate func dataObjectFromParameters(_ parameters: NSDictionary, objectType: WRPObject.Type, parentObject: WRPObject?) -> WRPObject { let dataObject: WRPObject = objectType.init(parameters: parameters, parentObject: parentObject) return dataObject } fileprivate func valueForKey(_ key: String, optional: Bool) -> AnyObject? { return nil } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Object serialization open func toDictionary() -> NSDictionary { return self.toDictionaryWithSerializationOption(.none, without: []) } open func toDictionaryWithout(_ exclude: [String]) -> NSDictionary { return self.toDictionaryWithSerializationOption(.none, without: exclude) } open func toDictionaryWithOnly(_ include: [String]) -> NSDictionary { print("toDictionaryWithOnly(:) is not yet supported. Expected version: 0.2") return NSDictionary() // return self.toDictionaryWithSerializationOption(.None, with: include) } open func toDictionaryWithSerializationOption(_ option: WRPSerializationOption) -> NSDictionary { return self.toDictionaryWithSerializationOption(option, without: []) } open func toDictionaryWithSerializationOption(_ option: WRPSerializationOption, without: [String]) -> NSDictionary { // Create output let outputParams: NSMutableDictionary = NSMutableDictionary() // Get mapping parameters, go through all of them and serialize them into output for element: WRPProperty in self.propertyMap() { // Skip element if it should be excluded if self.keyPathShouldBeExcluded(element.masterRemoteName, exclusionArray: without) { continue } // Get actual value of property let actualValue: AnyObject? = self.value(forKey: element.localName) as AnyObject? // Check for nil, if it is nil, we add <NSNull> object instead of value if (actualValue == nil) { if (option == WRPSerializationOption.includeNullProperties) { outputParams.setObject(NSNull(), forKeyPath: element.remoteNames.first!) } } else { // Otherwise add value itself outputParams.setObject(self.valueOfElement(element, value: actualValue!), forKeyPath: element.masterRemoteName) } } // Now get all relationships and call .toDictionary above all of them for element: WRPRelation in self.relationMap() { if self.keyPathShouldBeExcluded(element.remoteName, exclusionArray: without) { continue } if (element.relationshipType == .toMany) { // Get data pack if let actualValues = self.value(forKey: element.localName) as? [WRPObject] { // Create data pack if exists, get all values, serialize those, and assign all of them var outputArray = [NSDictionary]() for actualValue: WRPObject in actualValues { outputArray.append(actualValue.toDictionaryWithSerializationOption(option, without: self.keyPathForChildWithElement(element, parentRules: without))) } // Add all intros back outputParams.setObject(outputArray as AnyObject!, forKeyPath: element.remoteName) } else { // Add null value for relationship if needed if (option == WRPSerializationOption.includeNullProperties) { outputParams.setObject(NSNull(), forKey: element.remoteName as NSCopying) } } } else { // Get actual value of property let actualValue: WRPObject? = self.value(forKey: element.localName) as? WRPObject // Check for nil, if it is nil, we add <NSNull> object instead of value if (actualValue == nil) { if (option == WRPSerializationOption.includeNullProperties) { outputParams.setObject(NSNull(), forKey: element.remoteName as NSCopying) } } else { // Otherwise add value itself outputParams.setObject(actualValue!.toDictionaryWithSerializationOption(option, without: self.keyPathForChildWithElement(element, parentRules: without)), forKey: element.remoteName as NSCopying) } } } return outputParams } fileprivate func keyPathForChildWithElement(_ element: WRPRelation, parentRules: [String]) -> [String] { if (parentRules.count > 0) { var newExlusionRules = [String]() for parentRule: String in parentRules { let objcString: NSString = parentRule as NSString let range: NSRange = objcString.range(of: String(format: "%@.", element.remoteName)) if range.location != NSNotFound && range.location == 0 { let newPath = objcString.replacingCharacters(in: range, with: "") newExlusionRules.append(newPath as String) } } return newExlusionRules } else { return [] } } fileprivate func keyPathShouldBeExcluded(_ valueKeyPath: String, exclusionArray: [String]) -> Bool { let objcString: NSString = valueKeyPath as NSString for exclustionKeyPath: String in exclusionArray { let range: NSRange = objcString.range(of: exclustionKeyPath) if range.location != NSNotFound && range.location == 0 { return true } } return false } fileprivate func valueOfElement(_ element: WRPProperty, value: AnyObject) -> AnyObject { switch element.elementDataType { case .int: return NSNumber(value: value as! Int as Int) case .float: return NSNumber(value: value as! Float as Float) case .double: return NSNumber(value: value as! Double as Double) case .bool: return NSNumber(value: value as! Bool as Bool) case .date: let formatter: DateFormatter = DateFormatter() formatter.dateFormat = element.format! return formatter.string(from: value as! Date) as AnyObject default: return value } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Convenience open func updateWithJSONString(_ jsonString: String) -> Bool { // Try to parse json data if let jsonData: Data = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: true) { // If it worked, update data of current object (dictionary is expected on root level) do { let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? self.fillValues(jsonObject as! NSDictionary) self.processClosestRelationships(jsonObject as! NSDictionary) return true } catch let error as NSError { print ("Error while parsing a json object: \(error.domain)") } } // Could not process json string return false } open func updateWithDictionary(_ objectData: NSDictionary) -> Bool { // Update data of current object self.fillValues(objectData) self.processClosestRelationships(objectData) return true } open func excludeOnSerialization() -> [String] { return [] } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Debug open func debugInstantiate() -> Bool { return false } override open var debugDescription: String { return "Class: \(self.self)\nContent: \(self.toDictionary().debugDescription)" } }
9986641fc9c1b1080b3ea79f6f4269a1
38.365541
214
0.545527
false
false
false
false
codestergit/swift
refs/heads/master
test/SILGen/newtype.swift
apache-2.0
2
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-RAW // RUN: %target-swift-frontend -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-CANONICAL // REQUIRES: objc_interop import Newtype // CHECK-CANONICAL-LABEL: sil hidden @_T07newtype17createErrorDomain{{[_0-9a-zA-Z]*}}F // CHECK-CANONICAL: bb0([[STR:%[0-9]+]] : $String) func createErrorDomain(str: String) -> ErrorDomain { // CHECK-CANONICAL: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC // CHECK-CANONICAL-NEXT: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[STR]]) // CHECK-CANONICAL: struct $ErrorDomain ([[BRIDGED]] : $NSString) return ErrorDomain(rawValue: str) } // CHECK-RAW-LABEL: sil shared [transparent] [serializable] @_T0SC11ErrorDomainVABSS8rawValue_tcfC // CHECK-RAW: bb0([[STR:%[0-9]+]] : $String, // CHECK-RAW: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var ErrorDomain }, var, name "self" // CHECK-RAW: [[SELF:%[0-9]+]] = project_box [[SELF_BOX]] // CHECK-RAW: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF]] // CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC // CHECK-RAW: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK-RAW: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[BORROWED_STR]]) // CHECK-RAW: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK-RAW: [[RAWVALUE_ADDR:%[0-9]+]] = struct_element_addr [[UNINIT_SELF]] // CHECK-RAW: assign [[BRIDGED]] to [[RAWVALUE_ADDR]] func getRawValue(ed: ErrorDomain) -> String { return ed.rawValue } // CHECK-RAW-LABEL: sil shared [serializable] @_T0SC11ErrorDomainV8rawValueSSfg // CHECK-RAW: bb0([[SELF:%[0-9]+]] : $ErrorDomain): // CHECK-RAW: [[FORCE_BRIDGE:%[0-9]+]] = function_ref @_forceBridgeFromObjectiveC_bridgeable // CHECK-RAW: [[STRING_RESULT_ADDR:%[0-9]+]] = alloc_stack $String // CHECK-RAW: [[STORED_VALUE:%[0-9]+]] = struct_extract [[SELF]] : $ErrorDomain, #ErrorDomain._rawValue // CHECK-RAW: [[STORED_VALUE_COPY:%.*]] = copy_value [[STORED_VALUE]] // CHECK-RAW: [[STRING_META:%[0-9]+]] = metatype $@thick String.Type // CHECK-RAW: apply [[FORCE_BRIDGE]]<String>([[STRING_RESULT_ADDR]], [[STORED_VALUE_COPY]], [[STRING_META]]) // CHECK-RAW: [[STRING_RESULT:%[0-9]+]] = load [take] [[STRING_RESULT_ADDR]] // CHECK-RAW: return [[STRING_RESULT]] class ObjCTest { // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGF : $@convention(method) (@owned Optional<ErrorDomain>, @guaranteed ObjCTest) -> @owned Optional<ErrorDomain> { // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGFTo : $@convention(objc_method) (Optional<ErrorDomain>, ObjCTest) -> Optional<ErrorDomain> { @objc func optionalPassThrough(_ ed: ErrorDomain?) -> ErrorDomain? { return ed } // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFF : $@convention(method) (MyInt, @guaranteed ObjCTest) -> MyInt { // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFFTo : $@convention(objc_method) (MyInt, ObjCTest) -> MyInt { @objc func integerPassThrough(_ ed: MyInt) -> MyInt { return ed } }
ce0ed517500364c9de330ce022ff03a6
55.37931
207
0.679817
false
true
false
false
tinrobots/CoreDataPlus
refs/heads/master
Sources/NSManagedObjectContext+Utils.swift
mit
1
// CoreDataPlus import CoreData extension NSManagedObjectContext { /// The persistent stores associated with the receiver (if any). public final var persistentStores: [NSPersistentStore] { return persistentStoreCoordinator?.persistentStores ?? [] } /// Returns a dictionary that contains the metadata currently stored or to-be-stored in a given persistent store. public final func metaData(for store: NSPersistentStore) -> [String: Any] { guard let persistentStoreCoordinator = persistentStoreCoordinator else { preconditionFailure("\(self.description) doesn't have a Persistent Store Coordinator.") } return persistentStoreCoordinator.metadata(for: store) } /// Adds an `object` to the store's metadata and saves it **asynchronously**. /// /// - Parameters: /// - object: Object to be added to the medata dictionary. /// - key: Object key /// - store: NSPersistentStore where is stored the metadata. /// - handler: The completion handler called when the saving is completed. public final func setMetaDataObject(_ object: Any?, with key: String, for store: NSPersistentStore, completion handler: ( (Error?) -> Void )? = nil ) { performSave(after: { context in guard let persistentStoreCoordinator = context.persistentStoreCoordinator else { preconditionFailure("\(context.description) doesn't have a Persistent Store Coordinator.") } var metaData = persistentStoreCoordinator.metadata(for: store) metaData[key] = object persistentStoreCoordinator.setMetadata(metaData, for: store) }, completion: { error in handler?(error) }) } /// Returns the entity with the specified name (if any) from the managed object model associated with the specified managed object context’s persistent store coordinator. public final func entity(forEntityName name: String) -> NSEntityDescription? { guard let persistentStoreCoordinator = persistentStoreCoordinator else { preconditionFailure("\(self.description) doesn't have a Persistent Store Coordinator.") } let entity = persistentStoreCoordinator.managedObjectModel.entitiesByName[name] return entity } } // MARK: - Fetch extension NSManagedObjectContext { /// Returns an array of objects that meet the criteria specified by a given fetch request. /// - Note: When fetching data from Core Data, you don’t always know how many values you’ll be getting back. /// Core Data solves this problem by using a subclass of `NSArray` that will dynamically pull in data from the underlying store on demand. /// On the other hand, a Swift `Array` requires having every element in the array all at once, and bridging an `NSArray` to a Swift `Array` requires retrieving every single value. /// - Warning: **Batched requests** are supported only when returning a `NSArray`. /// - SeeAlso:https://developer.apple.com/forums/thread/651325) public final func fetchNSArray<T>(_ request: NSFetchRequest<T>) throws -> NSArray { // [...] Similarly for fetch requests with batching enabled, you do not want a Swift Array but instead an NSArray to avoid making an immediate copy of the future. // https://developer.apple.com/forums/thread/651325. // swiftlint:disable force_cast let protocolRequest = request as! NSFetchRequest<NSFetchRequestResult> let results = try fetch(protocolRequest) as NSArray return results } } // MARK: - Child Context extension NSManagedObjectContext { /// Returns a `new` background `NSManagedObjectContext`. /// - Parameters: /// - asChildContext: Specifies if this new context is a child context of the current context (default *false*). public final func newBackgroundContext(asChildContext isChildContext: Bool = false) -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) if isChildContext { context.parent = self } else { context.persistentStoreCoordinator = persistentStoreCoordinator } return context } /// Returns a `new` child `NSManagedObjectContext`. /// - Parameters: /// - concurrencyType: Specifies the concurrency pattern used by this child context (defaults to the parent type). public final func newChildContext(concurrencyType: NSManagedObjectContextConcurrencyType? = nil) -> NSManagedObjectContext { let type = concurrencyType ?? self.concurrencyType let context = NSManagedObjectContext(concurrencyType: type) context.parent = self return context } } // MARK: - Save extension NSManagedObjectContext { /// Returns the number of uncommitted changes (transient changes are included). public var changesCount: Int { guard hasChanges else { return 0 } return insertedObjects.count + deletedObjects.count + updatedObjects.count } /// Checks whether there are actually changes that will change the persistent store. /// - Note: The `hasChanges` method would return `true` for transient changes as well which can lead to false positives. public var hasPersistentChanges: Bool { guard hasChanges else { return false } return !insertedObjects.isEmpty || !deletedObjects.isEmpty || updatedObjects.first(where: { $0.hasPersistentChangedValues }) != nil } /// Returns the number of changes that will change the persistent store (transient changes are ignored). public var persistentChangesCount: Int { guard hasChanges else { return 0 } return insertedObjects.count + deletedObjects.count + updatedObjects.filter({ $0.hasPersistentChangedValues }).count } /// Asynchronously performs changes and then saves them. /// /// - Parameters: /// - changes: Changes to be applied in the current context before the saving operation. If they fail throwing an execption, the context will be reset. /// - completion: Block executed (on the context’s queue.) at the end of the saving operation. public final func performSave(after changes: @escaping (NSManagedObjectContext) throws -> Void, completion: ( (NSError?) -> Void )? = nil ) { // https://stackoverflow.com/questions/37837979/using-weak-strong-self-usage-in-block-core-data-swift // `perform` executes the block and then releases it. // In Swift terms it is @noescape (and in the future it may be marked that way and you won't need to use self. in noescape closures). // Until the block executes, self cannot be deallocated, but after the block executes, the cycle is immediately broken. perform { var internalError: NSError? do { try changes(self) // TODO // add an option flag to decide whether or not a context can be saved if only transient properties are changed // in that case hasPersistentChanges should be used instead of hasChanges if self.hasChanges { try self.save() } } catch { internalError = error as NSError } completion?(internalError) } } /// Synchronously performs changes and then saves them: if the changes fail throwing an execption, the context will be reset. /// /// - Throws: It throws an error in cases of failure (while applying changes or saving). public final func performSaveAndWait(after changes: (NSManagedObjectContext) throws -> Void) throws { // swiftlint:disable:next identifier_name try withoutActuallyEscaping(changes) { _changes in var internalError: NSError? performAndWait { do { try _changes(self) if hasChanges { try save() } } catch { internalError = error as NSError } } if let error = internalError { throw error } } } /// Saves the `NSManagedObjectContext` if changes are present or **rollbacks** if any error occurs. /// - Note: The rollback removes everything from the undo stack, discards all insertions and deletions, and restores updated objects to their last committed values. public final func saveOrRollBack() throws { guard hasChanges else { return } do { try save() } catch { rollback() // rolls back the pending changes throw error } } /// Saves the `NSManagedObjectContext` up to the last parent `NSManagedObjectContext`. internal final func performSaveUpToTheLastParentContextAndWait() throws { var parentContext: NSManagedObjectContext? = self while parentContext != nil { var saveError: Error? parentContext!.performAndWait { guard parentContext!.hasChanges else { return } do { try parentContext!.save() } catch { saveError = error } } parentContext = parentContext!.parent if let error = saveError { throw error } } } } // MARK: - Better PerformAndWait extension NSManagedObjectContext { /// Synchronously performs a given block on the context’s queue and returns the final result. /// - Throws: It throws an error in cases of failure. public func performAndWaitResult<T>(_ block: (NSManagedObjectContext) throws -> T) rethrows -> T { return try _performAndWait(function: performAndWait, execute: block, rescue: { throw $0 }) } /// Synchronously performs a given block on the context’s queue. /// - Throws: It throws an error in cases of failure. public func performAndWait(_ block: (NSManagedObjectContext) throws -> Void) rethrows { try _performAndWait(function: performAndWait, execute: block, rescue: { throw $0 }) } /// Helper function for convincing the type checker that the rethrows invariant holds for performAndWait. /// /// Source: https://oleb.net/blog/2018/02/performandwait/ /// Source: https://github.com/apple/swift/blob/bb157a070ec6534e4b534456d208b03adc07704b/stdlib/public/SDK/Dispatch/Queue.swift#L228-L249 private func _performAndWait<T>(function: (() -> Void) -> Void, execute work: (NSManagedObjectContext) throws -> T, rescue: ((Error) throws -> (T))) rethrows -> T { var result: T? var error: Error? // swiftlint:disable:next identifier_name withoutActuallyEscaping(work) { _work in function { do { result = try _work(self) } catch let catchedError { error = catchedError } } } if let error = error { return try rescue(error) } else { return result! } } }
4b6b5eed04b2c76a8c1748479310be00
41.772727
181
0.707275
false
false
false
false
dtop/SwiftValidate
refs/heads/master
validate/Validators/ValidatorNumeric.swift
mit
1
// // ValidatorNumeric.swift // validator // // Created by Danilo Topalovic on 19.12.15. // Copyright © 2015 Danilo Topalovic. All rights reserved. // import Foundation public class ValidatorNumeric: BaseValidator, ValidatorProtocol { /// nil is allowed public var allowNil: Bool = true /// Holds if the number can be a string representation public var allowString: Bool = true /// Holds if we accept floating point numbers public var allowFloatingPoint = true /// error message not numeric public var errorMessageNotNumeric = NSLocalizedString("Please enter avalid number", comment: "error message not numeric") /** inits - returns: the instance */ required public init( _ initializer: (ValidatorNumeric) -> () = { _ in }) { super.init() initializer(self) } /** Validates the value - parameter value: the value - parameter context: the context (if any) - throws: validation errors - returns: true on success */ override public func validate<T: Any>(_ value: T?, context: [String: Any?]?) throws -> Bool { self.emptyErrors() if self.allowNil && nil == value { return true } if let strVal: String = value as? String { if !self.allowString { return self.returnError(error: self.errorMessageNotNumeric) } if self.canBeInt(number: strVal) || (self.allowFloatingPoint && self.canBeFloat(number: strVal)) { return true } return self.returnError(error: self.errorMessageNotNumeric) } if let _ = value as? Int { return true } if self.allowFloatingPoint { if let _ = value as? Double { return true } } return self.returnError(error: self.errorMessageNotNumeric) } /** Tests if the number could be an int - parameter number: the number as string - returns: true if possible */ private func canBeInt(number: String) -> Bool { guard let _ = Int(number) else { return false } return true } /** Tests if the number could be a double - parameter number: the number as string - returns: true if possible */ private func canBeFloat(number: String) -> Bool { guard let _ = Double(number) else { return false } return true } }
7c8569c6a08a1abbcd7545de7a97507f
23.433628
125
0.534951
false
false
false
false
charmaex/poke-deck
refs/heads/master
PokeDeck/MainVC.swift
gpl-3.0
1
// // ViewController.swift // PokeDeck // // Created by Jan Dammshäuser on 24.02.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit class MainVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate { @IBOutlet weak var appView: AppView! @IBOutlet weak var collView: UICollectionView! @IBOutlet weak var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() collView.dataSource = self collView.delegate = self searchBar.delegate = self searchBar.returnKeyType = .Done NSNotificationCenter.defaultCenter().addObserver(self, selector: "showApp:", name: "introDone", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadData", name: "reloadCollView", object: nil) } func reloadData() { collView.reloadData() } func showApp(notif: NSNotification) { appView.show() } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return PokemonService.inst.dataList.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collView.dequeueReusableCellWithReuseIdentifier("PokemonCell", forIndexPath: indexPath) as! PokemonCell cell.initializeCell(PokemonService.inst.dataList[indexPath.row]) return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let pokemon = PokemonService.inst.dataList[indexPath.row] performSegueWithIdentifier("DetailVC", sender: pokemon) } func searchBarSearchButtonClicked(searchBar: UISearchBar) { view.endEditing(true) } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { PokemonService.inst.updateFilter(searchBar.text) if searchBar.text == nil || searchBar.text == "" { view.endEditing(false) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "DetailVC" { guard let vc = segue.destinationViewController as? DetailVC, let pokemon = sender as? Pokemon else { return } vc.pokemon = pokemon } } }
e8c6a2338300decd9068a59a70c086d4
30.879518
130
0.666289
false
false
false
false
lennet/bugreporter
refs/heads/master
Bugreporter/AppDelegate.swift
mit
1
// // AppDelegate.swift // Bugreporter // // Created by Leo Thomas on 12/07/16. // Copyright © 2016 Leonard Thomas. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var windowController: NSWindowController? let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) weak var menuController: MenuViewController? weak var menuPopover: NSPopover? override func awakeFromNib() { configureStatusItem() } func applicationDidFinishLaunching(_ aNotification: Notification) { UserPreferences.setup() DeviceObserver.shared.delegate = self NSUserNotificationCenter.default.delegate = self } func configureStatusItem() { guard let button = statusItem.button else { return } button.title = "Bugreporter" button.target = self button.action = #selector(statusItemClicked) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } func statusItemClicked(sender: NSButton) { guard let menuController = NSStoryboard(name: "Main", bundle: nil).instantiateController(withIdentifier: "MenuViewController") as? MenuViewController else { return } let popover = NSPopover() popover.behavior = .transient popover.contentViewController = menuController self.menuController = menuController popover.show(relativeTo: sender.frame, of: sender, preferredEdge: .minY) self.menuPopover = popover } func showDevice(name: String) { guard let selectedDevice = DeviceObserver.shared.device(withName: name) else { return } windowController = NSStoryboard(name: "Main", bundle: nil).instantiateController(withIdentifier: "DeviceWindowController") as? NSWindowController (windowController?.contentViewController as? RecordExternalDeviceViewController)?.device = selectedDevice windowController?.showWindow(self) } func showNotification(text: String) { let notification = NSUserNotification() notification.title = "Device detected" notification.informativeText = text notification.soundName = NSUserNotificationDefaultSoundName notification.hasActionButton = true NSUserNotificationCenter.default.deliver(notification) } } extension AppDelegate: DeviceObserverDelegate { func didRemoveDevice() { menuController?.reload() } func didAddDevice(name: String) { menuController?.reload() if UserPreferences.showNotifications { showNotification(text: name) } } } extension AppDelegate : NSUserNotificationCenterDelegate { func userNotificationCenter(_ center: NSUserNotificationCenter, didDeliver notification: NSUserNotification) { } func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) { guard let informativeText = notification.informativeText else { return } showDevice(name: informativeText) } }
46659b16806d0739bb03db6853daed75
31.346535
173
0.691154
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Library/ViewModels/ProjectEnvironmentalCommitmentCellViewModel.swift
apache-2.0
1
import KsApi import Prelude import ReactiveSwift public protocol ProjectEnvironmentalCommitmentCellViewModelInputs { /// Call to configure with a `ProjectEnvironmentalCommitment`. func configureWith(value: ProjectEnvironmentalCommitment) } public protocol ProjectEnvironmentalCommitmentCellViewModelOutputs { /// Emits a `String` of the category from the `ProjectEnvironmentalCommitment` object var categoryLabelText: Signal<String, Never> { get } /// Emits a `String` of the description from the `ProjectEnvironmentalCommitment` object var descriptionLabelText: Signal<String, Never> { get } } public protocol ProjectEnvironmentalCommitmentCellViewModelType { var inputs: ProjectEnvironmentalCommitmentCellViewModelInputs { get } var outputs: ProjectEnvironmentalCommitmentCellViewModelOutputs { get } } public final class ProjectEnvironmentalCommitmentCellViewModel: ProjectEnvironmentalCommitmentCellViewModelType, ProjectEnvironmentalCommitmentCellViewModelInputs, ProjectEnvironmentalCommitmentCellViewModelOutputs { public init() { let environmentalCommitment = self.configureWithProperty.signal .skipNil() self.categoryLabelText = environmentalCommitment .map(\.category) .map(internationalizedString) self.descriptionLabelText = environmentalCommitment.map(\.description) } fileprivate let configureWithProperty = MutableProperty<ProjectEnvironmentalCommitment?>(nil) public func configureWith(value: ProjectEnvironmentalCommitment) { self.configureWithProperty.value = value } public let categoryLabelText: Signal<String, Never> public let descriptionLabelText: Signal<String, Never> public var inputs: ProjectEnvironmentalCommitmentCellViewModelInputs { self } public var outputs: ProjectEnvironmentalCommitmentCellViewModelOutputs { self } } private func internationalizedString(for category: ProjectCommitmentCategory) -> String { switch category { case .longLastingDesign: return Strings.Long_lasting_design() case .sustainableMaterials: return Strings.Sustainable_materials() case .environmentallyFriendlyFactories: return Strings.Environmentally_friendly_factories() case .sustainableDistribution: return Strings.Sustainable_distribution() case .reusabilityAndRecyclability: return Strings.Reusability_and_recyclability() case .somethingElse: return Strings.Something_else() } }
e1535a6f2785b451befa0275ffafe9b5
36.765625
101
0.810509
false
true
false
false
lzpfmh/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers Support/AAViewController.swift
mit
1
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit import MobileCoreServices class AAViewController: UIViewController, UINavigationControllerDelegate { // MARK: - // MARK: Public vars var placeholder = BigPlaceholderView(topOffset: 0) var pendingPickClosure: ((image: UIImage) -> ())? var avatarHeight: CGFloat = DeviceType.IS_IPHONE_6P ? 336.0 : 256.0 var popover: UIPopoverController? // Content type for view tracking var content: ACPage? // Data for views var autoTrack: Bool = false { didSet { if self.autoTrack { if let u = self.uid { content = ACAllEvents_Profile_viewWithInt_(jint(u)) } if let g = self.gid { content = ACAllEvents_Group_viewWithInt_(jint(g)) } } } } var uid: Int! { didSet { if self.uid != nil { self.user = Actor.getUserWithUid(jint(self.uid)) self.isBot = user.isBot().boolValue } } } var user: ACUserVM! var isBot: Bool! var gid: Int! { didSet { if self.gid != nil { self.group = Actor.getGroupWithGid(jint(self.gid)) } } } var group: ACGroupVM! init() { super.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } func showPlaceholderWithImage(image: UIImage?, title: String?, subtitle: String?) { placeholder.setImage(image, title: title, subtitle: subtitle) showPlaceholder() } func showPlaceholder() { if placeholder.superview == nil { placeholder.frame = view.bounds view.addSubview(placeholder) } } func hidePlaceholder() { if placeholder.superview != nil { placeholder.removeFromSuperview() } } func shakeView(view: UIView, originalX: CGFloat) { var r = view.frame r.origin.x = originalX let originalFrame = r var rFirst = r rFirst.origin.x = r.origin.x + 4 r.origin.x = r.origin.x - 4 UIView.animateWithDuration(0.05, delay: 0.0, options: .Autoreverse, animations: { () -> Void in view.frame = rFirst }) { (finished) -> Void in if (finished) { UIView.animateWithDuration(0.05, delay: 0.0, options: [.Repeat, .Autoreverse], animations: { () -> Void in UIView.setAnimationRepeatCount(3) view.frame = r }, completion: { (finished) -> Void in view.frame = originalFrame }) } else { view.frame = originalFrame } } } func applyScrollUi(tableView: UITableView, cell: UITableViewCell?) { let offset = min(tableView.contentOffset.y, avatarHeight) if let userCell = cell as? UserPhotoCell { userCell.userAvatarView.frame = CGRectMake(0, offset, tableView.frame.width, avatarHeight - offset) } else if let groupCell = cell as? GroupPhotoCell { groupCell.groupAvatarView.frame = CGRectMake(0, offset, tableView.frame.width, avatarHeight - offset) } var fraction: Double = 0 if (offset > 0) { if (offset > avatarHeight - 64) { fraction = 1 } else { fraction = Double(offset) / (Double(avatarHeight) - 64) } } navigationController?.navigationBar.lt_setBackgroundColor(MainAppTheme.navigation.barSolidColor.alpha(fraction)) } func applyScrollUi(tableView: UITableView) { applyScrollUi(tableView, indexPath: NSIndexPath(forRow: 0, inSection: 0)) } func applyScrollUi(tableView: UITableView, indexPath: NSIndexPath) { applyScrollUi(tableView, cell: tableView.cellForRowAtIndexPath(indexPath)) } func pickAvatar(takePhoto:Bool, closure: (image: UIImage) -> ()) { self.pendingPickClosure = closure let pickerController = AAImagePickerController() pickerController.sourceType = (takePhoto ? UIImagePickerControllerSourceType.Camera : UIImagePickerControllerSourceType.PhotoLibrary) pickerController.mediaTypes = [kUTTypeImage as String] pickerController.view.backgroundColor = MainAppTheme.list.bgColor pickerController.navigationBar.tintColor = MainAppTheme.navigation.barColor pickerController.delegate = self pickerController.navigationBar.tintColor = MainAppTheme.navigation.titleColor pickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: MainAppTheme.navigation.titleColor] self.navigationController!.presentViewController(pickerController, animated: true, completion: nil) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() placeholder.frame = CGRectMake(0, 64, view.bounds.width, view.bounds.height - 64) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let c = content { Analytics.trackPageVisible(c) } if let u = uid { Actor.onProfileOpenWithUid(jint(u)) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if let c = content { Analytics.trackPageHidden(c) } if let u = uid { Actor.onProfileClosedWithUid(jint(u)) } } func dismiss() { dismissViewControllerAnimated(true, completion: nil) } func presentInNavigation(controller: UIViewController) { var navigation = AANavigationController() navigation.viewControllers = [controller] presentViewController(navigation, animated: true, completion: nil) } } extension AAViewController: UIImagePickerControllerDelegate, PECropViewControllerDelegate { func cropImage(image: UIImage) { let cropController = PECropViewController() cropController.cropAspectRatio = 1.0 cropController.keepingCropAspectRatio = true cropController.image = image cropController.delegate = self cropController.toolbarHidden = true navigationController!.presentViewController(UINavigationController(rootViewController: cropController), animated: true, completion: nil) } func cropViewController(controller: PECropViewController!, didFinishCroppingImage croppedImage: UIImage!) { if (pendingPickClosure != nil){ pendingPickClosure!(image: croppedImage) } pendingPickClosure = nil navigationController!.dismissViewControllerAnimated(true, completion: nil) } func cropViewControllerDidCancel(controller: PECropViewController!) { pendingPickClosure = nil navigationController!.dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { MainAppTheme.navigation.applyStatusBar() navigationController!.dismissViewControllerAnimated(true, completion: { () -> Void in self.cropImage(image) }) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { MainAppTheme.navigation.applyStatusBar() let image = info[UIImagePickerControllerOriginalImage] as! UIImage navigationController!.dismissViewControllerAnimated(true, completion: { () -> Void in self.cropImage(image) }) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { pendingPickClosure = nil MainAppTheme.navigation.applyStatusBar() self.dismissViewControllerAnimated(true, completion: nil) } }
29a1140e517f55423b2f83c5415fa27e
33.818182
144
0.622772
false
false
false
false
richardpiazza/SOSwift
refs/heads/master
Sources/SOSwift/AccessibilityAPI.swift
mit
1
import Foundation /// Indicates that the resource is compatible with the referenced accessibility API. public enum AccessibilityAPI: String, CaseIterable, Codable { case androidAccessibility = "AndroidAccessibility" case aria = "ARIA" case atk = "ATK" case atSPI = "AT-SPI" case blackberryAccessibility = "BlackberryAccessibility" case iAccessible2 = "iAccessible2" case iOSAccessibility = "iOSAccessibility" case javaAccessibility = "JavaAccessibility" case macOSXAccessibility = "MacOSXAccessibility" case msaa = "MSAA" case uiAutomation = "UIAutomation" public var displayValue: String { switch self { case .androidAccessibility: return "Android Accessibility" case .aria: return "Accessible Rich Internet Applications" case .atk: return "GNOME Accessibility Toolkit" case .atSPI: return "Assistive Technology Service Provider Interface" case .blackberryAccessibility: return "Blackberry Accessibility" case .iAccessible2: return "Microsoft Windows Accesibility" case .iOSAccessibility: return "iOS Accessibility" case .javaAccessibility: return "Java Accessibility" case .macOSXAccessibility: return "Mac OS Accessibiliy" case .msaa: return "Microsoft Active Accessibility" case .uiAutomation: return "UI Automation" } } }
1547b821f352ae5538cb119ba6b0fb26
42.40625
84
0.716343
false
false
false
false
citysite102/kapi-kaffeine
refs/heads/master
kapi-kaffeine/KPMenuUploadRequest.swift
mit
1
// // KPMenuUploadRequest.swift // kapi-kaffeine // // Created by MengHsiu Chang on 17/10/2017. // Copyright © 2017 kapi-kaffeine. All rights reserved. // import UIKit import PromiseKit import Alamofire class KPMenuUploadRequest: NetworkUploadRequest { typealias ResponseType = RawJsonResult private var cafeID: String! private var memberID: String! private var photoData: Data! var method: Alamofire.HTTPMethod { return .post } var endpoint: String { return "/menus" } var parameters: [String : Any]? { var parameters = [String : Any]() parameters["cafe_id"] = cafeID parameters["member_id"] = memberID return parameters } var fileData: Data? { return photoData } var fileKey: String? { return "menu1" } var fileName: String? { return "\(self.cafeID)-\(self.memberID)-\(arc4random_uniform(1000))" } var mimeType: String? { return "image/jpg" } var headers: [String : String] { return ["Content-Type":"multipart/form-data", "token":(KPUserManager.sharedManager.currentUser?.accessToken) ?? ""] } public func perform(_ cafeID: String, _ memberID: String?, _ photoData: Data!) -> Promise<(ResponseType)> { self.cafeID = cafeID self.memberID = memberID ?? KPUserManager.sharedManager.currentUser?.identifier self.photoData = photoData return networkClient.performUploadRequest(self).then(execute: responseHandler) } }
65512bfac29caed651a58adc8ab14622
25.015873
87
0.600976
false
false
false
false
artsy/eigen
refs/heads/main
ios/Artsy/View_Controllers/Live_Auctions/Views/AuctionLotMetadataStackScrollView.swift
mit
1
import UIKit import Interstellar class AuctionLotMetadataStackScrollView: ORStackScrollView { let aboveFoldStack = TextStack() fileprivate let toggle = AuctionLotMetadataStackScrollView.toggleSizeButton() var showAdditionalInformation: (() -> ())? var hideAdditionalInformation: (() -> ())? var aboveFoldHeightConstraint: NSLayoutConstraint! required init(viewModel: LiveAuctionLotViewModelType, salesPerson: LiveAuctionsSalesPersonType, sideMargin: String) { super.init(stackViewClass: TextStack.self) scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 2) /// Anything addded to `stack` here will be hidden by default guard let stack = stackView as? TextStack else { return } /// Splits the essential lot metadata and the "lot info" button let aboveFoldStackWrapper = UIView() // Sets up the above the fold stack let name = aboveFoldStack.addArtistName("") let title = aboveFoldStack.addArtworkName("", date: nil) title.numberOfLines = 1 let estimate = aboveFoldStack.addBodyText("", topMargin: "4") let currentBid = aboveFoldStack.addBodyText("", topMargin: "4") // Want to make the wrapper hold the stack on the left aboveFoldStackWrapper.addSubview(aboveFoldStack) aboveFoldStack.alignTop("0", leading: "0", toView: aboveFoldStackWrapper) aboveFoldStack.alignBottomEdge(withView: aboveFoldStackWrapper, predicate: "0") // Then the button on the right aboveFoldStackWrapper.addSubview(toggle) toggle.alignTopEdge(withView: aboveFoldStackWrapper, predicate: "0") toggle.alignTrailingEdge(withView: aboveFoldStackWrapper, predicate: "0") toggle.addTarget(self, action: #selector(toggleTapped), for: .touchUpInside) // Then glue them together with 20px margin aboveFoldStack.constrainTrailingSpace(toView: toggle, predicate: "0") // Add the above the fold stack, to the stack stackView.addSubview(aboveFoldStackWrapper, withTopMargin: "0", sideMargin: sideMargin) // set a constraint to force it to be in small mode first aboveFoldHeightConstraint = constrainHeight(toView: aboveFoldStackWrapper, predicate: "0") // ----- Below the fold 👇 ----- // if let medium = viewModel.lotArtworkMedium { stack.addBodyText(medium, topMargin: "20", sideMargin: sideMargin) } if let dimensions = viewModel.lotArtworkDimensions { stack.addBodyText(dimensions, topMargin: "4", sideMargin: sideMargin) } if let editionInfo = viewModel.lotEditionInfo { stack.addBodyText(editionInfo, topMargin: "4", sideMargin: sideMargin) } let separatorMargin = String(Int(sideMargin) ?? 0 + 40) if let artworkdescription = viewModel.lotArtworkDescription, artworkdescription.isEmpty == false { stack.addSmallLineBreak(separatorMargin) stack.addSmallHeading("Description", sideMargin: sideMargin) stack.addBodyMarkdown(artworkdescription, sideMargin: sideMargin) } if let blurb = viewModel.lotArtistBlurb, blurb.isEmpty == false { stack.addThickLineBreak(separatorMargin) stack.addBigHeading("About the Artist", sideMargin: sideMargin) stack.addBodyMarkdown(blurb, sideMargin: sideMargin) } name.text = viewModel.lotArtist title.setTitle(viewModel.lotName, date: viewModel.lotArtworkCreationDate) estimate.text = "Estimate: \(viewModel.estimateString ?? "")" viewModel.currentBidSignal.subscribe { newCurrentBid in guard let state: LotState = viewModel.lotStateSignal.peek() else { currentBid.text = "" return } switch state { case .liveLot, .upcomingLot: if let reserve = newCurrentBid.reserve { currentBid.text = "\(newCurrentBid.bid) \(reserve)" currentBid.makeSubstringFaint(reserve) } else { currentBid.text = newCurrentBid.bid } case .closedLot: if viewModel.isBeingSold && viewModel.userIsBeingSoldTo, let winningLotValueString = salesPerson.winningLotValueString(viewModel) { currentBid.text = "Sold for: \(winningLotValueString)" } else { currentBid.text = "" } } } isScrollEnabled = false let views = stack.subviews + aboveFoldStack.subviews for label in views.filter({ $0.isKind(of: UILabel.self) || $0.isKind(of: UITextView.self) }) { label.backgroundColor = .clear } } @objc fileprivate func toggleTapped(_ button: UIButton) { if aboveFoldHeightConstraint.isActive { showAdditionalInformation?() } else { hideAdditionalInformation?() } } func setShowInfoButtonEnabled(_ enabled: Bool, animated: Bool = true) { if animated { UIView.transition(with: toggle, duration: ARAnimationQuickDuration, options: [.transitionCrossDissolve], animations: { self.toggle.isEnabled = enabled }, completion: nil) } else { toggle.isEnabled = enabled } } func showFullMetadata(_ animated: Bool) { isScrollEnabled = true toggle.setTitle("HIDE INFO", for: UIControl.State()) toggle.setImage(UIImage(asset: .LiveAuctionsDisclosureTriangleDown), for: UIControl.State()) toggle.titleEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0) toggle.imageTopConstraint?.constant = 15 aboveFoldHeightConstraint.isActive = false UIView.animateSpringIf(animated, duration: ARAnimationDuration, delay: 0, damping: 0.9, velocity: 3.5, { self.superview?.layoutIfNeeded() }) { _ in self.flashScrollIndicators() } } func hideFullMetadata(_ animated: Bool) { isScrollEnabled = false toggle.setTitle("LOT INFO", for: UIControl.State()) toggle.setImage(UIImage(asset: .LiveAuctionsDisclosureTriangleUp), for: UIControl.State()) toggle.titleEdgeInsets = UIEdgeInsets.zero toggle.imageTopConstraint?.constant = 4 aboveFoldHeightConstraint.isActive = true UIView.animateSpringIf(animated, duration: ARAnimationDuration, delay: 0, damping: 0.9, velocity: 3.5) { self.contentOffset = CGPoint.zero self.superview?.layoutIfNeeded() } } /// A small class just to simplify changing the height constraint for the image view fileprivate class AuctionPushButton: UIButton { var imageTopConstraint: NSLayoutConstraint? } fileprivate class func toggleSizeButton() -> AuctionPushButton { let toggle = AuctionPushButton(type: .custom) // Adjusts where the text will be placed toggle.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 30, right: 17) toggle.titleLabel?.font = .sansSerifFont(withSize: 12) toggle.setTitle("LOT INFO", for: UIControl.State()) toggle.setTitleColor(.black, for: UIControl.State()) toggle.setTitleColor(.artsyGrayMedium(), for: .disabled) // Constrain the image to the left edge toggle.setImage(UIImage(asset: .LiveAuctionsDisclosureTriangleUp), for: UIControl.State()) toggle.imageView?.alignTrailingEdge(withView: toggle, predicate: "0") toggle.imageTopConstraint = toggle.imageView?.alignTopEdge(withView: toggle, predicate: "4") toggle.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .horizontal) toggle.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) // Extend its hit range, as it's like ~20px otherwise toggle.ar_extendHitTestSize(byWidth: 20, andHeight: 40) return toggle } override var intrinsicContentSize : CGSize { return aboveFoldStack.intrinsicContentSize } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
39ee8e10ac1a365a4c0672e0d1ff4b33
39.719807
130
0.654407
false
false
false
false
bolghuar/SlideMenuControllerSwift
refs/heads/master
Source/SlideMenuController.swift
mit
4
// // SlideMenuController.swift // // Created by Yuji Hato on 12/3/14. // import Foundation import UIKit public struct SlideMenuOptions { public static var leftViewWidth: CGFloat = 270.0 public static var leftBezelWidth: CGFloat = 16.0 public static var contentViewScale: CGFloat = 0.96 public static var contentViewOpacity: CGFloat = 0.5 public static var shadowOpacity: CGFloat = 0.0 public static var shadowRadius: CGFloat = 0.0 public static var shadowOffset: CGSize = CGSizeMake(0,0) public static var panFromBezel: Bool = true public static var animationDuration: CGFloat = 0.4 public static var rightViewWidth: CGFloat = 270.0 public static var rightBezelWidth: CGFloat = 16.0 public static var rightPanFromBezel: Bool = true public static var hideStatusBar: Bool = true public static var pointOfNoReturnWidth: CGFloat = 44.0 } public class SlideMenuController: UIViewController, UIGestureRecognizerDelegate { public enum SlideAction { case Open case Close } public enum TrackAction { case TapOpen case TapClose case FlickOpen case FlickClose } struct PanInfo { var action: SlideAction var shouldBounce: Bool var velocity: CGFloat } var opacityView = UIView() var mainContainerView = UIView() var leftContainerView = UIView() var rightContainerView = UIView() var mainViewController: UIViewController? var leftViewController: UIViewController? var leftPanGesture: UIPanGestureRecognizer? var leftTapGetsture: UITapGestureRecognizer? var rightViewController: UIViewController? var rightPanGesture: UIPanGestureRecognizer? var rightTapGesture: UITapGestureRecognizer? public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController leftViewController = leftMenuViewController initView() } public convenience init(mainViewController: UIViewController, rightMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController rightViewController = rightMenuViewController initView() } public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController, rightMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController leftViewController = leftMenuViewController rightViewController = rightMenuViewController initView() } deinit { } func initView() { mainContainerView = UIView(frame: view.bounds) mainContainerView.backgroundColor = UIColor.clearColor() mainContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth view.insertSubview(mainContainerView, atIndex: 0) var opacityframe: CGRect = view.bounds var opacityOffset: CGFloat = 0 opacityframe.origin.y = opacityframe.origin.y + opacityOffset opacityframe.size.height = opacityframe.size.height - opacityOffset opacityView = UIView(frame: opacityframe) opacityView.backgroundColor = UIColor.blackColor() opacityView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth opacityView.layer.opacity = 0.0 view.insertSubview(opacityView, atIndex: 1) var leftFrame: CGRect = view.bounds leftFrame.size.width = SlideMenuOptions.leftViewWidth leftFrame.origin.x = leftMinOrigin(); var leftOffset: CGFloat = 0 leftFrame.origin.y = leftFrame.origin.y + leftOffset leftFrame.size.height = leftFrame.size.height - leftOffset leftContainerView = UIView(frame: leftFrame) leftContainerView.backgroundColor = UIColor.clearColor() leftContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight view.insertSubview(leftContainerView, atIndex: 2) var rightFrame: CGRect = view.bounds rightFrame.size.width = SlideMenuOptions.rightViewWidth rightFrame.origin.x = rightMinOrigin() var rightOffset: CGFloat = 0 rightFrame.origin.y = rightFrame.origin.y + rightOffset; rightFrame.size.height = rightFrame.size.height - rightOffset rightContainerView = UIView(frame: rightFrame) rightContainerView.backgroundColor = UIColor.clearColor() rightContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight view.insertSubview(rightContainerView, atIndex: 3) addLeftGestures() addRightGestures() } public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) leftContainerView.hidden = true rightContainerView.hidden = true coordinator.animateAlongsideTransition(nil, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.closeLeftNonAnimation() self.closeRightNonAnimation() self.leftContainerView.hidden = false self.rightContainerView.hidden = false self.removeLeftGestures() self.removeRightGestures() self.addLeftGestures() self.addRightGestures() }) } public override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge.None } public override func viewWillLayoutSubviews() { // topLayoutGuideの値が確定するこのタイミングで各種ViewControllerをセットする setUpViewController(mainContainerView, targetViewController: mainViewController) setUpViewController(leftContainerView, targetViewController: leftViewController) setUpViewController(rightContainerView, targetViewController: rightViewController) } public override func openLeft() { setOpenWindowLevel() //leftViewControllerのviewWillAppearを呼ぶため leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true) openLeftWithVelocity(0.0) track(.TapOpen) } public override func openRight() { setOpenWindowLevel() //menuViewControllerのviewWillAppearを呼ぶため rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true) openRightWithVelocity(0.0) } public override func closeLeft() { leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true) closeLeftWithVelocity(0.0) setCloseWindowLebel() } public override func closeRight() { rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true) closeRightWithVelocity(0.0) setCloseWindowLebel() } public func addLeftGestures() { if (leftViewController != nil) { if leftPanGesture == nil { leftPanGesture = UIPanGestureRecognizer(target: self, action: "handleLeftPanGesture:") leftPanGesture!.delegate = self view.addGestureRecognizer(leftPanGesture!) } if leftTapGetsture == nil { leftTapGetsture = UITapGestureRecognizer(target: self, action: "toggleLeft") leftTapGetsture!.delegate = self view.addGestureRecognizer(leftTapGetsture!) } } } public func addRightGestures() { if (rightViewController != nil) { if rightPanGesture == nil { rightPanGesture = UIPanGestureRecognizer(target: self, action: "handleRightPanGesture:") rightPanGesture!.delegate = self view.addGestureRecognizer(rightPanGesture!) } if rightTapGesture == nil { rightTapGesture = UITapGestureRecognizer(target: self, action: "toggleRight") rightTapGesture!.delegate = self view.addGestureRecognizer(rightTapGesture!) } } } public func removeLeftGestures() { if leftPanGesture != nil { view.removeGestureRecognizer(leftPanGesture!) leftPanGesture = nil } if leftTapGetsture != nil { view.removeGestureRecognizer(leftTapGetsture!) leftTapGetsture = nil } } public func removeRightGestures() { if rightPanGesture != nil { view.removeGestureRecognizer(rightPanGesture!) rightPanGesture = nil } if rightTapGesture != nil { view.removeGestureRecognizer(rightTapGesture!) rightTapGesture = nil } } public func isTagetViewController() -> Bool { // Function to determine the target ViewController // Please to override it if necessary return true } public func track(trackAction: TrackAction) { // function is for tracking // Please to override it if necessary } struct LeftPanState { static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero static var wasOpenAtStartOfPan: Bool = false static var wasHiddenAtStartOfPan: Bool = false } func handleLeftPanGesture(panGesture: UIPanGestureRecognizer) { if !isTagetViewController() { return } if isRightOpen() { return } switch panGesture.state { case UIGestureRecognizerState.Began: LeftPanState.frameAtStartOfPan = leftContainerView.frame LeftPanState.startPointOfPan = panGesture.locationInView(view) LeftPanState.wasOpenAtStartOfPan = isLeftOpen() LeftPanState.wasHiddenAtStartOfPan = isLeftHidden() leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true) addShadowToView(leftContainerView) setOpenWindowLevel() case UIGestureRecognizerState.Changed: var translation: CGPoint = panGesture.translationInView(panGesture.view!) leftContainerView.frame = applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan) applyLeftOpacity() applyLeftContentViewScale() case UIGestureRecognizerState.Ended: var velocity:CGPoint = panGesture.velocityInView(panGesture.view) var panInfo: PanInfo = panLeftResultInfoForVelocity(velocity) if panInfo.action == .Open { if !LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(true, animated: true) } openLeftWithVelocity(panInfo.velocity) track(.FlickOpen) } else { if LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(false, animated: true) } closeLeftWithVelocity(panInfo.velocity) setCloseWindowLebel() track(.FlickClose) } default: break } } struct RightPanState { static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero static var wasOpenAtStartOfPan: Bool = false static var wasHiddenAtStartOfPan: Bool = false } func handleRightPanGesture(panGesture: UIPanGestureRecognizer) { if !isTagetViewController() { return } if isLeftOpen() { return } switch panGesture.state { case UIGestureRecognizerState.Began: RightPanState.frameAtStartOfPan = rightContainerView.frame RightPanState.startPointOfPan = panGesture.locationInView(view) RightPanState.wasOpenAtStartOfPan = isRightOpen() RightPanState.wasHiddenAtStartOfPan = isRightHidden() rightViewController?.beginAppearanceTransition(RightPanState.wasHiddenAtStartOfPan, animated: true) addShadowToView(rightContainerView) setOpenWindowLevel() case UIGestureRecognizerState.Changed: var translation: CGPoint = panGesture.translationInView(panGesture.view!) rightContainerView.frame = applyRightTranslation(translation, toFrame: RightPanState.frameAtStartOfPan) applyRightOpacity() applyRightContentViewScale() case UIGestureRecognizerState.Ended: var velocity: CGPoint = panGesture.velocityInView(panGesture.view) var panInfo: PanInfo = panRightResultInfoForVelocity(velocity) if panInfo.action == .Open { if !RightPanState.wasHiddenAtStartOfPan { rightViewController?.beginAppearanceTransition(true, animated: true) } openRightWithVelocity(panInfo.velocity) } else { if RightPanState.wasHiddenAtStartOfPan { rightViewController?.beginAppearanceTransition(false, animated: true) } closeRightWithVelocity(panInfo.velocity) setCloseWindowLebel() } default: break } } public func openLeftWithVelocity(velocity: CGFloat) { var xOrigin: CGFloat = leftContainerView.frame.origin.x var finalXOrigin: CGFloat = 0.0 var frame = leftContainerView.frame; frame.origin.x = finalXOrigin; var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } addShadowToView(leftContainerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() } } } public func openRightWithVelocity(velocity: CGFloat) { var xOrigin: CGFloat = rightContainerView.frame.origin.x // CGFloat finalXOrigin = SlideMenuOptions.rightViewOverlapWidth; var finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width var frame = rightContainerView.frame frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } addShadowToView(rightContainerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.rightContainerView.frame = frame strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.rightViewController?.endAppearanceTransition() } } } public func closeLeftWithVelocity(velocity: CGFloat) { var xOrigin: CGFloat = leftContainerView.frame.origin.x var finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = 0.0 strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.removeShadow(strongSelf.leftContainerView) strongSelf.enableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() } } } public func closeRightWithVelocity(velocity: CGFloat) { var xOrigin: CGFloat = rightContainerView.frame.origin.x var finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) var frame: CGRect = rightContainerView.frame frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.rightContainerView.frame = frame strongSelf.opacityView.layer.opacity = 0.0 strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.removeShadow(strongSelf.rightContainerView) strongSelf.enableContentInteraction() strongSelf.rightViewController?.endAppearanceTransition() } } } public override func toggleLeft() { if isLeftOpen() { closeLeft() setCloseWindowLebel() // closeMenuはメニュータップ時にも呼ばれるため、closeタップのトラッキングはここに入れる track(.TapClose) } else { openLeft() } } public func isLeftOpen() -> Bool { return leftContainerView.frame.origin.x == 0.0 } public func isLeftHidden() -> Bool { return leftContainerView.frame.origin.x <= leftMinOrigin() } public override func toggleRight() { if isRightOpen() { closeRight() setCloseWindowLebel() } else { openRight() } } public func isRightOpen() -> Bool { return rightContainerView.frame.origin.x == CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width } public func isRightHidden() -> Bool { return rightContainerView.frame.origin.x >= CGRectGetWidth(view.bounds) } public func changeMainViewController(mainViewController: UIViewController, close: Bool) { removeViewController(self.mainViewController) self.mainViewController = mainViewController setUpViewController(mainContainerView, targetViewController: mainViewController) if (close) { closeLeft() closeRight() } } public func changeLeftViewController(leftViewController: UIViewController, closeLeft:Bool) { removeViewController(self.leftViewController) self.leftViewController = leftViewController setUpViewController(leftContainerView, targetViewController: leftViewController) if closeLeft { self.closeLeft() } } public func changeRightViewController(rightViewController: UIViewController, closeRight:Bool) { removeViewController(self.rightViewController) self.rightViewController = rightViewController; setUpViewController(rightContainerView, targetViewController: rightViewController) if closeRight { self.closeRight() } } private func leftMinOrigin() -> CGFloat { return -SlideMenuOptions.leftViewWidth } private func rightMinOrigin() -> CGFloat { return CGRectGetWidth(view.bounds) } private func panLeftResultInfoForVelocity(velocity: CGPoint) -> PanInfo { var thresholdVelocity: CGFloat = 1000.0 var pointOfNoReturn: CGFloat = CGFloat(floor(leftMinOrigin())) + SlideMenuOptions.pointOfNoReturnWidth var leftOrigin: CGFloat = leftContainerView.frame.origin.x var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0) panInfo.action = leftOrigin <= pointOfNoReturn ? .Close : .Open; if velocity.x >= thresholdVelocity { panInfo.action = .Open panInfo.velocity = velocity.x } else if velocity.x <= (-1.0 * thresholdVelocity) { panInfo.action = .Close panInfo.velocity = velocity.x } return panInfo } private func panRightResultInfoForVelocity(velocity: CGPoint) -> PanInfo { var thresholdVelocity: CGFloat = -1000.0 var pointOfNoReturn: CGFloat = CGFloat(floor(CGRectGetWidth(view.bounds)) - SlideMenuOptions.pointOfNoReturnWidth) var rightOrigin: CGFloat = rightContainerView.frame.origin.x var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0) panInfo.action = rightOrigin >= pointOfNoReturn ? .Close : .Open if velocity.x <= thresholdVelocity { panInfo.action = .Open panInfo.velocity = velocity.x } else if (velocity.x >= (-1.0 * thresholdVelocity)) { panInfo.action = .Close panInfo.velocity = velocity.x } return panInfo } private func applyLeftTranslation(translation: CGPoint, toFrame:CGRect) -> CGRect { var newOrigin: CGFloat = toFrame.origin.x newOrigin += translation.x var minOrigin: CGFloat = leftMinOrigin() var maxOrigin: CGFloat = 0.0 var newFrame: CGRect = toFrame if newOrigin < minOrigin { newOrigin = minOrigin } else if newOrigin > maxOrigin { newOrigin = maxOrigin } newFrame.origin.x = newOrigin return newFrame } private func applyRightTranslation(translation: CGPoint, toFrame: CGRect) -> CGRect { var newOrigin: CGFloat = toFrame.origin.x newOrigin += translation.x var minOrigin: CGFloat = rightMinOrigin() // var maxOrigin: CGFloat = SlideMenuOptions.rightViewOverlapWidth var maxOrigin: CGFloat = rightMinOrigin() - rightContainerView.frame.size.width var newFrame: CGRect = toFrame if newOrigin > minOrigin { newOrigin = minOrigin } else if newOrigin < maxOrigin { newOrigin = maxOrigin } newFrame.origin.x = newOrigin return newFrame } private func getOpenedLeftRatio() -> CGFloat { var width: CGFloat = leftContainerView.frame.size.width var currentPosition: CGFloat = leftContainerView.frame.origin.x - leftMinOrigin() return currentPosition / width } private func getOpenedRightRatio() -> CGFloat { var width: CGFloat = rightContainerView.frame.size.width var currentPosition: CGFloat = rightContainerView.frame.origin.x return -(currentPosition - CGRectGetWidth(view.bounds)) / width } private func applyLeftOpacity() { var openedLeftRatio: CGFloat = getOpenedLeftRatio() var opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedLeftRatio opacityView.layer.opacity = Float(opacity) } private func applyRightOpacity() { var openedRightRatio: CGFloat = getOpenedRightRatio() var opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedRightRatio opacityView.layer.opacity = Float(opacity) } private func applyLeftContentViewScale() { var openedLeftRatio: CGFloat = getOpenedLeftRatio() var scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedLeftRatio); mainContainerView.transform = CGAffineTransformMakeScale(scale, scale) } private func applyRightContentViewScale() { var openedRightRatio: CGFloat = getOpenedRightRatio() var scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedRightRatio) mainContainerView.transform = CGAffineTransformMakeScale(scale, scale) } private func addShadowToView(targetContainerView: UIView) { targetContainerView.layer.masksToBounds = false targetContainerView.layer.shadowOffset = SlideMenuOptions.shadowOffset targetContainerView.layer.shadowOpacity = Float(SlideMenuOptions.shadowOpacity) targetContainerView.layer.shadowRadius = SlideMenuOptions.shadowRadius targetContainerView.layer.shadowPath = UIBezierPath(rect: targetContainerView.bounds).CGPath } private func removeShadow(targetContainerView: UIView) { targetContainerView.layer.masksToBounds = true mainContainerView.layer.opacity = 1.0 } private func removeContentOpacity() { opacityView.layer.opacity = 0.0 } private func addContentOpacity() { opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) } private func disableContentInteraction() { mainContainerView.userInteractionEnabled = false } private func enableContentInteraction() { mainContainerView.userInteractionEnabled = true } private func setOpenWindowLevel() { if (SlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelStatusBar + 1 } }) } } private func setCloseWindowLebel() { if (SlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelNormal } }) } } private func setUpViewController(targetView: UIView, targetViewController: UIViewController?) { if let viewController = targetViewController { addChildViewController(viewController) viewController.view.frame = targetView.bounds targetView.addSubview(viewController.view) viewController.didMoveToParentViewController(self) } } private func removeViewController(viewController: UIViewController?) { if let _viewController = viewController { _viewController.willMoveToParentViewController(nil) _viewController.view.removeFromSuperview() _viewController.removeFromParentViewController() } } public func closeLeftNonAnimation(){ setCloseWindowLebel() var finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin leftContainerView.frame = frame opacityView.layer.opacity = 0.0 mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) removeShadow(leftContainerView) enableContentInteraction() } public func closeRightNonAnimation(){ setCloseWindowLebel() var finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) var frame: CGRect = rightContainerView.frame frame.origin.x = finalXOrigin rightContainerView.frame = frame opacityView.layer.opacity = 0.0 mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) removeShadow(rightContainerView) enableContentInteraction() } //pragma mark – UIGestureRecognizerDelegate public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { var point: CGPoint = touch.locationInView(view) if gestureRecognizer == leftPanGesture { return slideLeftForGestureRecognizer(gestureRecognizer, point: point) } else if gestureRecognizer == rightPanGesture { return slideRightViewForGestureRecognizer(gestureRecognizer, withTouchPoint: point) } else if gestureRecognizer == leftTapGetsture { return isLeftOpen() && !isPointContainedWithinLeftRect(point) } else if gestureRecognizer == rightTapGesture { return isRightOpen() && !isPointContainedWithinRightRect(point) } return true } private func slideLeftForGestureRecognizer( gesture: UIGestureRecognizer, point:CGPoint) -> Bool{ return isLeftOpen() || SlideMenuOptions.panFromBezel && isLeftPointContainedWithinBezelRect(point) } private func isLeftPointContainedWithinBezelRect(point: CGPoint) -> Bool{ var leftBezelRect: CGRect = CGRectZero var tempRect: CGRect = CGRectZero var bezelWidth: CGFloat = SlideMenuOptions.leftBezelWidth CGRectDivide(view.bounds, &leftBezelRect, &tempRect, bezelWidth, CGRectEdge.MinXEdge) return CGRectContainsPoint(leftBezelRect, point) } private func isPointContainedWithinLeftRect(point: CGPoint) -> Bool { return CGRectContainsPoint(leftContainerView.frame, point) } private func slideRightViewForGestureRecognizer(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool { return isRightOpen() || SlideMenuOptions.rightPanFromBezel && isRightPointContainedWithinBezelRect(point) } private func isRightPointContainedWithinBezelRect(point: CGPoint) -> Bool { var rightBezelRect: CGRect = CGRectZero var tempRect: CGRect = CGRectZero //CGFloat bezelWidth = rightContainerView.frame.size.width; var bezelWidth: CGFloat = CGRectGetWidth(view.bounds) - SlideMenuOptions.rightBezelWidth CGRectDivide(view.bounds, &tempRect, &rightBezelRect, bezelWidth, CGRectEdge.MinXEdge) return CGRectContainsPoint(rightBezelRect, point) } private func isPointContainedWithinRightRect(point: CGPoint) -> Bool { return CGRectContainsPoint(rightContainerView.frame, point) } } extension UIViewController { public func slideMenuController() -> SlideMenuController? { var viewController: UIViewController? = self while viewController != nil { if viewController is SlideMenuController { return viewController as? SlideMenuController } viewController = viewController?.parentViewController } return nil; } public func addLeftBarButtonWithImage(buttonImage: UIImage) { var leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleLeft") navigationItem.leftBarButtonItem = leftButton; } public func addRightBarButtonWithImage(buttonImage: UIImage) { var rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleRight") navigationItem.rightBarButtonItem = rightButton; } public func toggleLeft() { slideMenuController()?.toggleLeft() } public func toggleRight() { slideMenuController()?.toggleRight() } public func openLeft() { slideMenuController()?.openLeft() } public func openRight() { slideMenuController()?.openRight() } public func closeLeft() { slideMenuController()?.closeLeft() } public func closeRight() { slideMenuController()?.closeRight() } // Please specify if you want menu gesuture give priority to than targetScrollView public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) { if let slideControlelr = slideMenuController() { let recognizers = slideControlelr.view.gestureRecognizers for recognizer in recognizers as! [UIGestureRecognizer] { if recognizer is UIPanGestureRecognizer { targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer) } } } } }
72fc574f854888776bf062cd8c3ee620
37.318332
153
0.643921
false
false
false
false
carambalabs/UnsplashKit
refs/heads/master
UnsplashKit/Classes/UnsplashSource/Factories/Source/SourceRequestFactory.swift
mit
1
import Foundation import CarambaKit import CoreGraphics #if os(OSX) import AppKit #else import UIKit #endif open class SourceRequestFactory { // MARK: - Singleton open static var instance: SourceRequestFactory = SourceRequestFactory() // MARK: - Attributes let requestBuilder: UrlRequestBuilder // MARK: - Init internal init(requestBuilder: UrlRequestBuilder) { self.requestBuilder = requestBuilder } public convenience init() { self.init(requestBuilder: UrlRequestBuilder(baseUrl: "https://source.unsplash.com")) } // MARK: - Public internal func random(_ size: CGSize? = nil, filter: SourceRequestFilter? = .none) -> URLRequest { return self.get(path: "random", size: size, filter: filter) } internal func search(_ terms: [String], size: CGSize? = nil, filter: SourceRequestFilter? = .none) -> URLRequest { return self.get(path: "featured", size: size, filter: filter, search: terms) } internal func category(_ category: SourceCategory, size: CGSize? = nil, filter: SourceRequestFilter? = .none) -> URLRequest { return self.get(path: "category/\(category.rawValue)", size: size, filter: filter) } internal func user(_ username: String, size: CGSize? = nil, filter: SourceRequestFilter? = .none) -> URLRequest { return self.get(path: "user/\(username)", size: size, filter: filter) } internal func userLikes(_ username: String, size: CGSize? = nil) -> URLRequest { return self.get(path: "user/\(username)/likes", size: size) } internal func collection(_ collectionID: String, size: CGSize? = nil) -> URLRequest { return self.get(path: "collection/\(collectionID)", size: size) } internal func photo(_ photoID: String, size: CGSize? = nil) -> URLRequest { return self.get(path: "/\(photoID)", size: size) } fileprivate func get(path: String, size: CGSize? = nil, filter: SourceRequestFilter? = .none, search: [String]? = nil) -> URLRequest { var fullPath = path if let size = size { fullPath += "/\(Int(size.width))x\(Int(size.height))" } if let filter = filter { fullPath += "/\(filter.rawValue)" } let request = self.requestBuilder.get(fullPath) if let terms = search { let requestWithParameters = request.with(parameters: ["search" : terms.joined(separator: ",") as AnyObject]) return requestWithParameters.build() as URLRequest } else { return request.build() as URLRequest } } } extension SourceRequestFactory { func searchParameterEncoding(_ request: NSURLRequest, params: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { let r = request as! NSMutableURLRequest if let params = params { if let searchTerms = params["search"] as? String { r.url = URL(string: "\(request.url!.absoluteString)?\(searchTerms)") } } return (request as! NSMutableURLRequest, nil) } }
5d7c616378de618e6315a7fea6ad91c7
33.03125
129
0.598714
false
false
false
false
zats/BrowserTV
refs/heads/master
BrowserTV/PreferencesViewController.swift
mit
1
// // PreferencesViewController.swift // BrowserTV // // Created by Sash Zats on 12/19/15. // Copyright © 2015 Sash Zats. All rights reserved. // import UIKit class PreferencesViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var URLs: [String] = [] private let service = CommunicationService() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) store.subscribe(self) service.start() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) store.unsubscribe(self) service.stop() } } // MARK: Gestures Handling extension PreferencesViewController { @IBAction func playPauseGestureAction(sender: AnyObject) { tableView.editing = !tableView.editing } @IBAction func menuAction(sender: AnyObject) { store.dispatch(Action(ActionKind.HidePreferences.rawValue)) } } extension PreferencesViewController: UITableViewDelegate { func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return .Delete } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { store.dispatch( Action( type: ActionKind.Remove.rawValue, payload:["index": indexPath.row] ) ) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { store.dispatch( Action( type: ActionKind.SelectedTab.rawValue, payload: ["index": indexPath.row] ) ) } } extension PreferencesViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return URLs.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let URLString = URLs[indexPath.row] cell.textLabel?.text = URLString return cell } } extension PreferencesViewController: StoreSubscriber { typealias StoreSubscriberStateType = AppState func newState(state: AppState) { let URLs = state.preferences.URLs.map{ String($0) } if self.URLs != URLs { self.URLs = URLs tableView.reloadData() } if let index = state.browser.selectedTabIndex { tableView.selectRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0), animated: true, scrollPosition: .Middle) } } }
ce8b8692e678cbcdadcdcb7365b20052
28.78
148
0.661182
false
false
false
false
SteveBarnegren/TweenKit
refs/heads/master
TweenKit/TweenKit/RepeatAction.swift
mit
1
// // RepeatAction.swift // TweenKit // // Created by Steve Barnegren on 19/03/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import Foundation /** Repeats an inner action a specified number of times */ public class RepeatAction: FiniteTimeAction { // MARK: - Public public var onBecomeActive: () -> () = {} public var onBecomeInactive: () -> () = {} /** Create with an action to repeat - Parameter action: The action to repeat - Parameter times: The number of repeats */ public init(action: FiniteTimeAction, times: Int) { self.action = action self.repeats = times self.duration = action.duration * Double(times) } // MARK: - Private Properties public var reverse: Bool = false { didSet{ action.reverse = reverse } } public internal(set) var duration: Double var action: FiniteTimeAction let repeats: Int var lastRepeatNumber = 0 // MARK: - Private Methods public func willBecomeActive() { lastRepeatNumber = 0 action.willBecomeActive() onBecomeActive() } public func didBecomeInactive() { action.didBecomeInactive() onBecomeInactive() } public func willBegin() { action.willBegin() } public func didFinish() { // We might have skipped over the action, so we still need to run the full cycle (lastRepeatNumber..<repeats-1).forEach{ _ in self.action.didFinish() self.action.willBegin() } action.didFinish() } public func update(t: CFTimeInterval) { let repeatNumber = Int( t * Double(repeats) ).constrained(max: repeats-1) (lastRepeatNumber..<repeatNumber).forEach{ _ in self.action.didFinish() self.action.willBegin() } let actionT = ( t * Double(repeats) ).fract // Avoid situation where fract is 0.0 because t is 1.0 if t > 0 && actionT == 0 { action.update(t: 1.0) } else{ action.update(t: actionT) } lastRepeatNumber = repeatNumber } } public extension FiniteTimeAction { func repeated(_ times: Int) -> RepeatAction { return RepeatAction(action: self, times: times) } }
17340fd6f3a665825c4d4af55214f7d6
23.32
88
0.57278
false
false
false
false
kperryua/swift
refs/heads/master
stdlib/public/SDK/Foundation/NSString.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Strings //===----------------------------------------------------------------------===// @available(*, unavailable, message: "Please use String or NSString") public class NSSimpleCString {} @available(*, unavailable, message: "Please use String or NSString") public class NSConstantString {} @_silgen_name("swift_convertStringToNSString") public // COMPILER_INTRINSIC func _convertStringToNSString(_ string: String) -> NSString { return string._bridgeToObjectiveC() } extension NSString : ExpressibleByStringLiteral { /// Create an instance initialized to `value`. public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init( extendedGraphemeClusterLiteral value: StaticString ) { self.init(stringLiteral: value) } /// Create an instance initialized to `value`. public required convenience init(stringLiteral value: StaticString) { var immutableResult: NSString if value.hasPointerRepresentation { immutableResult = NSString( bytesNoCopy: UnsafeMutableRawPointer(mutating: value.utf8Start), length: Int(value.utf8CodeUnitCount), encoding: value.isASCII ? String.Encoding.ascii.rawValue : String.Encoding.utf8.rawValue, freeWhenDone: false)! } else { var uintValue = value.unicodeScalar immutableResult = NSString( bytes: &uintValue, length: 4, encoding: String.Encoding.utf32.rawValue)! } self.init(string: immutableResult as String) } } extension NSString : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to prevent infinite recursion trying to bridge // AnyHashable to NSObject. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { // Consistently use Swift equality and hashing semantics for all strings. return AnyHashable(self as String) } } extension NSString { public convenience init(format: NSString, _ args: CVarArg...) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, arguments: va_args) } public convenience init( format: NSString, locale: Locale?, _ args: CVarArg... ) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, locale: locale, arguments: va_args) } public class func localizedStringWithFormat( _ format: NSString, _ args: CVarArg... ) -> Self { return withVaList(args) { self.init(format: format as String, locale: Locale.current, arguments: $0) } } public func appendingFormat(_ format: NSString, _ args: CVarArg...) -> NSString { return withVaList(args) { self.appending(NSString(format: format as String, arguments: $0) as String) as NSString } } } extension NSMutableString { public func appendFormat(_ format: NSString, _ args: CVarArg...) { return withVaList(args) { self.append(NSString(format: format as String, arguments: $0) as String) } } } extension NSString { /// Returns an `NSString` object initialized by copying the characters /// from another given string. /// /// - Returns: An `NSString` object initialized by copying the /// characters from `aString`. The returned object may be different /// from the original receiver. @nonobjc public convenience init(string aString: NSString) { self.init(string: aString as String) } } extension NSString : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(self as String) } }
7b3b2403f9fc1b3d6bc3286e00c90ba9
32.725191
97
0.659801
false
false
false
false
shajrawi/swift
refs/heads/master
test/Constraints/function.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift func f0(_ x: Float) -> Float {} func f1(_ x: Float) -> Float {} func f2(_ x: @autoclosure () -> Float) {} var f : Float _ = f0(f0(f)) _ = f0(1) _ = f1(f1(f)) f2(f) f2(1.0) func call_lvalue(_ rhs: @autoclosure () -> Bool) -> Bool { return rhs() } // Function returns func weirdCast<T, U>(_ x: T) -> U {} func ff() -> (Int) -> (Float) { return weirdCast } // Block <-> function conversions var funct: (Int) -> Int = { $0 } var block: @convention(block) (Int) -> Int = funct funct = block block = funct // Application of implicitly unwrapped optional functions var optFunc: ((String) -> String)! = { $0 } var s: String = optFunc("hi") // <rdar://problem/17652759> Default arguments cause crash with tuple permutation func testArgumentShuffle(_ first: Int = 7, third: Int = 9) { } testArgumentShuffle(third: 1, 2) // expected-error {{unnamed argument #2 must precede argument 'third'}} {{21-21=2, }} {{29-32=}} func rejectsAssertStringLiteral() { assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} } // <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads func process(_ line: UInt = #line, _ fn: () -> Void) {} func process(_ line: UInt = #line) -> Int { return 0 } func dangerous() throws {} func test() { process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}} try dangerous() test() } } // <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic class A { func a(_ text:String) { } func a(_ text:String, something:Int?=nil) { } } A().a(text:"sometext") // expected-error{{extraneous argument label 'text:' in call}}{{7-12=}} // <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type func r22451001() -> AnyObject {} print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}} // SR-590 Passing two parameters to a function that takes one argument of type Any crashes the compiler // SR-1028: Segmentation Fault: 11 when superclass init takes parameter of type 'Any' func sr590(_ x: Any) {} // expected-note {{'sr590' declared here}} sr590(3,4) // expected-error {{extra argument in call}} sr590() // expected-error {{missing argument for parameter #1 in call}} // Make sure calling with structural tuples still works. sr590(()) sr590((1, 2)) // SR-2657: Poor diagnostics when function arguments should be '@escaping'. private class SR2657BlockClass<T> { // expected-note 3 {{generic parameters are always considered '@escaping'}} let f: T init(f: T) { self.f = f } } func takesAny(_: Any) {} func foo(block: () -> (), other: () -> Int) { let _ = SR2657BlockClass(f: block) // expected-error@-1 {{converting non-escaping value to 'T' may allow it to escape}} let _ = SR2657BlockClass<()->()>(f: block) // expected-error@-1 {{converting non-escaping parameter 'block' to generic parameter 'T' may allow it to escape}} let _: SR2657BlockClass<()->()> = SR2657BlockClass(f: block) // expected-error@-1 {{converting non-escaping parameter 'block' to generic parameter 'T' may allow it to escape}} let _: SR2657BlockClass<()->()> = SR2657BlockClass<()->()>(f: block) // expected-error@-1 {{converting non-escaping parameter 'block' to generic parameter 'T' may allow it to escape}} _ = SR2657BlockClass<Any>(f: block) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} _ = SR2657BlockClass<Any>(f: other) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} takesAny(block) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} takesAny(other) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} } struct S { init<T>(_ x: T, _ y: T) {} // expected-note {{generic parameters are always considered '@escaping'}} init(fn: () -> Int) { self.init({ 0 }, fn) // expected-error {{converting non-escaping parameter 'fn' to generic parameter 'T' may allow it to escape}} } } protocol P { associatedtype U } func test_passing_noescape_function_to_dependent_member() { struct S<T : P> { // expected-note {{generic parameters are always considered '@escaping'}} func foo(_: T.U) {} } struct Q : P { typealias U = () -> Int } func test(_ s: S<Q>, fn: () -> Int) { s.foo(fn) // expected-error@-1 {{converting non-escaping parameter 'fn' to generic parameter 'Q.U' (aka '() -> Int') may allow it to escape}} } }
f60d41f929d66a03de23d2770821e44d
34.746269
152
0.663883
false
false
false
false
JGiola/swift
refs/heads/main
test/Interop/Cxx/reference/reference.swift
apache-2.0
8
// RUN: %empty-directory(%t) // RUN: %target-clangxx -c %S/Inputs/reference.cpp -I %S/Inputs -o %t/reference.o // RUN: %target-build-swift %s -I %S/Inputs -o %t/reference %t/reference.o -Xfrontend -enable-experimental-cxx-interop // RUN: %target-codesign %t/reference // RUN: %target-run %t/reference // // REQUIRES: executable_test import Reference import StdlibUnittest var ReferenceTestSuite = TestSuite("Reference") ReferenceTestSuite.test("read-lvalue-reference") { expectNotEqual(13, getStaticInt()) setStaticInt(13) expectEqual(13, getStaticIntRef().pointee) expectEqual(13, getConstStaticIntRef().pointee) } ReferenceTestSuite.test("read-rvalue-reference") { expectNotEqual(32, getStaticInt()) setStaticInt(32) expectEqual(32, getStaticIntRvalueRef().pointee) expectEqual(32, getConstStaticIntRvalueRef().pointee) } ReferenceTestSuite.test("write-lvalue-reference") { expectNotEqual(14, getStaticInt()) getStaticIntRef().pointee = 14 expectEqual(14, getStaticInt()) } ReferenceTestSuite.test("write-rvalue-reference") { expectNotEqual(41, getStaticInt()) getStaticIntRvalueRef().pointee = 41 expectEqual(41, getStaticInt()) } ReferenceTestSuite.test("pass-lvalue-reference") { expectNotEqual(21, getStaticInt()) var val: CInt = 21 setStaticIntRef(&val) expectEqual(21, getStaticInt()) } ReferenceTestSuite.test("pass-const-lvalue-reference") { expectNotEqual(22, getStaticInt()) let val: CInt = 22 setConstStaticIntRef(val) expectEqual(22, getStaticInt()) } ReferenceTestSuite.test("pass-rvalue-reference") { expectNotEqual(52, getStaticInt()) var val: CInt = 52 setStaticIntRvalueRef(&val) expectEqual(52, getStaticInt()) } ReferenceTestSuite.test("pass-const-rvalue-reference") { expectNotEqual(53, getStaticInt()) let val: CInt = 53 setConstStaticIntRvalueRef(val) expectEqual(53, getStaticInt()) } ReferenceTestSuite.test("func-reference") { let cxxF: @convention(c) () -> Int32 = getFuncRef() expectNotEqual(15, getStaticInt()) setStaticInt(15) expectEqual(15, cxxF()) } ReferenceTestSuite.test("func-rvalue-reference") { let cxxF: @convention(c) () -> Int32 = getFuncRvalueRef() expectNotEqual(61, getStaticInt()) setStaticInt(61) expectEqual(61, cxxF()) } ReferenceTestSuite.test("pod-struct-const-lvalue-reference") { expectNotEqual(getStaticInt(), 78) takeConstRef(78) expectEqual(getStaticInt(), 78) } ReferenceTestSuite.test("reference to template") { var val: CInt = 53 let ref = refToTemplate(&val) expectEqual(53, ref.pointee) ref.pointee = 42 expectEqual(42, val) } ReferenceTestSuite.test("const reference to template") { let val: CInt = 53 let ref = constRefToTemplate(val) expectEqual(53, ref.pointee) } runAllTests()
ba63e56db45acbac53811d68507d0a54
25.538462
118
0.737319
false
true
false
false
jpachecou/VIPER-Module-Generator
refs/heads/master
ViperModules/ViewController.swift
mit
1
// // ViewController.swift // ViperModules // // Created by Jonathan Pacheco on 29/12/15. // Copyright © 2015 Jonathan Pacheco. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var moduleNameCell: NSFormCell! @IBOutlet weak var projectNameCell: NSFormCell! @IBOutlet weak var developerNameCell: NSFormCell! @IBOutlet weak var organizationNameCell: NSFormCell! override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } @IBAction func generateModule(sender: AnyObject) { let model = ModuleModel().then { $0.moduleName = self.moduleNameCell.stringValue $0.projectName = self.projectNameCell.stringValue $0.developerName = self.developerNameCell.stringValue $0.organizationName = self.organizationNameCell.stringValue } let filesManager = FilesManager(moduleModel: model) filesManager.generateModule() } }
632727fe0de4d847498764aa593a7ecb
29.444444
75
0.642336
false
false
false
false
ZackKingS/Tasks
refs/heads/master
task/Classes/Main/Tools/UIViewController+ZBHUD.swift
apache-2.0
1
// // UIViewController+ZBHUD.swift // task // // Created by 柏超曾 on 2017/10/16. // Copyright © 2017年 柏超曾. All rights reserved. // import Foundation import UIKit import MBProgressHUD extension UIViewController{ func showHint(hint :String ){ //只显示文字 let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = MBProgressHUDMode.text hud.label.text = hint hud.margin = 10 hud.offset.y = 50 hud.removeFromSuperViewOnHide = true hud.hide(animated: true, afterDelay: 3) } }
4d3a5170751aa40b5ccf969611a0c159
18.7
72
0.614213
false
false
false
false
10533176/TafelTaferelen
refs/heads/master
Tafel Taferelen/Extension.swift
mit
1
// // AlertFunctions.swift // Tafel Taferelen // // Created by Femke van Son on 31-01-17. // Copyright © 2017 Femke van Son. All rights reserved. // import Foundation import Firebase extension UIViewController { // MARK: functions to give alert massages for the user interface func signupErrorAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction(title: "Ok", style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } func noGroupErrorAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction(title: "Ok", style: .default, handler: { action in let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "userVC") self.present(vc, animated: true, completion: nil) }) alert.addAction(action) present(alert, animated: true, completion: nil) } // MARK: getting the groupID of a user. WERKT NOG NIET, RETURNT VOORDAT DIE DE WAARDE HEEFT func hideKeyboardWhenTappedAroung(){ let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard(){ view.endEditing(true) } }
9364a32f15627f688a66318468570f0b
34.711111
131
0.675793
false
false
false
false
RyanTech/SwinjectMVVMExample
refs/heads/master
ExampleViewModel/ImageSearchTableViewModel.swift
mit
1
// // ImageSearchTableViewModel.swift // SwinjectMVVMExample // // Created by Yoichi Tagaya on 8/22/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import ReactiveCocoa import ExampleModel public final class ImageSearchTableViewModel: ImageSearchTableViewModeling { public var cellModels: PropertyOf<[ImageSearchTableViewCellModeling]> { return PropertyOf(_cellModels) } public var searching: PropertyOf<Bool> { return PropertyOf(_searching) } public var errorMessage: PropertyOf<String?> { return PropertyOf(_errorMessage) } private let _cellModels = MutableProperty<[ImageSearchTableViewCellModeling]>([]) private let _searching = MutableProperty<Bool>(false) private let _errorMessage = MutableProperty<String?>(nil) /// Accepts property injection. public var imageDetailViewModel: ImageDetailViewModelModifiable? public var loadNextPage: Action<(), (), NoError> { return Action(enabledIf: nextPageLoadable) { _ in return SignalProducer { observer, disposable in if let (_, observer) = self.nextPageTrigger.value { self._searching.value = true sendNext(observer, ()) } } } } private var nextPageLoadable: PropertyOf<Bool> { return PropertyOf( initialValue: false, producer: searching.producer.combineLatestWith(nextPageTrigger.producer).map { searching, trigger in !searching && trigger != nil }) } private let nextPageTrigger = MutableProperty<(SignalProducer<(), NoError>, Event<(), NoError> -> ())?>(nil) // SignalProducer buffer private let imageSearch: ImageSearching private let network: Networking private var foundImages = [ImageEntity]() public init(imageSearch: ImageSearching, network: Networking) { self.imageSearch = imageSearch self.network = network } public func startSearch() { func toCellModel(image: ImageEntity) -> ImageSearchTableViewCellModeling { return ImageSearchTableViewCellModel(image: image, network: self.network) as ImageSearchTableViewCellModeling } _searching.value = true nextPageTrigger.value = SignalProducer<(), NoError>.buffer() let (trigger, _) = nextPageTrigger.value! imageSearch.searchImages(nextPageTrigger: trigger) .map { response in (response.images, response.images.map { toCellModel($0) }) } .observeOn(UIScheduler()) .on(next: { images, cellModels in self.foundImages += images self._cellModels.value += cellModels self._searching.value = false }) .on(error: { error in self._errorMessage.value = error.description }) .on(event: { event in switch event { case .Completed, .Error, .Interrupted: self.nextPageTrigger.value = nil self._searching.value = false default: break } }) .start() } public func selectCellAtIndex(index: Int) { imageDetailViewModel?.update(foundImages, atIndex: index) } }
2b5fb2e11e64d94dc3fd553b3e9754a3
36.611111
137
0.615362
false
false
false
false
halo/LinkLiar
refs/heads/master
LinkLiarTests/PathsTests.swift
mit
1
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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 XCTest @testable import LinkLiar class PathTests: XCTestCase { func testConfigDirectory() { let path = Paths.configDirectory XCTAssertEqual("/Library/Application Support/io.github.halo.LinkLiar", path) } func testConfigDirectoryURL() { let url = Paths.configDirectoryURL XCTAssertEqual("/Library/Application Support/io.github.halo.LinkLiar", url.path) } func testConfigFile() { let path = Paths.configFile XCTAssertEqual("/Library/Application Support/io.github.halo.LinkLiar/config.json", path) } func testConfigFileURL() { let url = Paths.configFileURL XCTAssertEqual("/Library/Application Support/io.github.halo.LinkLiar/config.json", url.path) } func testHelperDirectory() { let path = Paths.helperDirectory XCTAssertEqual("/Library/PrivilegedHelperTools", path) } func testHelperDirectoryURL() { let url = Paths.helperDirectoryURL XCTAssertEqual("/Library/PrivilegedHelperTools", url.path) } func testHelperExecutable() { let path = Paths.helperExecutable XCTAssertEqual("/Library/PrivilegedHelperTools/io.github.halo.linkhelper", path) } func testHelperExecutableURL() { let url = Paths.helperExecutableURL XCTAssertEqual("/Library/PrivilegedHelperTools/io.github.halo.linkhelper", url.path) } func testDaemonsPlistDirectory() { let path = Paths.daemonsPlistDirectory XCTAssertEqual("/Library/LaunchDaemons", path) } func testDaemonsPlistDirectoryURL() { let url = Paths.daemonsPlistDirectoryURL XCTAssertEqual("/Library/LaunchDaemons", url.path) } func testDaemonPlistFile() { let path = Paths.daemonPlistFile XCTAssertEqual("/Library/LaunchDaemons/io.github.halo.linkdaemon.plist", path) } func testDaemonPlistFileURL() { let url = Paths.daemonPlistFileURL XCTAssertEqual("/Library/LaunchDaemons/io.github.halo.linkdaemon.plist", url.path) } func testHelperPlistFile() { let path = Paths.helperPlistFile XCTAssertEqual("/Library/LaunchDaemons/io.github.halo.linkhelper.plist", path) } func testHelperPlistFileURL() { let url = Paths.helperPlistFileURL XCTAssertEqual("/Library/LaunchDaemons/io.github.halo.linkhelper.plist", url.path) } func testDaemonPristineExecutable() { let path = Paths.daemonPristineExecutablePath XCTAssertTrue(path.hasSuffix("/LinkLiar.app/Contents/Resources/linkdaemon")) } func testDaemonPristineExecutableURL() { let url = Paths.daemonPristineExecutableURL XCTAssertTrue(url.path.hasSuffix("/LinkLiar.app/Contents/Resources/linkdaemon")) } func testDaemonDirectory() { let path = Paths.daemonDirectory XCTAssertEqual("/Library/Application Support/io.github.halo.linkdaemon", path) } func testDaemonDirectoryURL() { let url = Paths.daemonDirectoryURL XCTAssertEqual("/Library/Application Support/io.github.halo.linkdaemon", url.path) } func testDaemonExecutable() { let path = Paths.daemonExecutable XCTAssertEqual("/Library/Application Support/io.github.halo.linkdaemon/linkdaemon", path) } func testDaemonExecutableURL() { let url = Paths.daemonExecutableURL XCTAssertEqual("/Library/Application Support/io.github.halo.linkdaemon/linkdaemon", url.path) } }
4ac6c114923641767809915763bb32d9
35.02459
133
0.753129
false
true
false
false
darrarski/SwipeToReveal-iOS
refs/heads/master
ExampleTests/UI/TableExampleViewControllerSpec.swift
mit
1
import Quick import Nimble @testable import SwipeToRevealExample class TableExampleViewControllerSpec: QuickSpec { override func spec() { context("init with coder") { it("should throw asserion") { expect { () -> Void in _ = TableExampleViewController(coder: NSCoder()) }.to(throwAssertion()) } } context("init") { var sut: TableExampleViewController! beforeEach { sut = TableExampleViewController(assembly: Assembly()) } context("load view") { beforeEach { _ = sut.view sut.view.frame = CGRect(x: 0, y: 0, width: 320, height: 240) } describe("table view") { it("should have 1 section") { expect(sut.numberOfSections(in: sut.tableView)).to(equal(1)) } it("should have 100 rows in first section") { expect(sut.tableView(sut.tableView, numberOfRowsInSection: 0)).to(equal(100)) } it("should throw when asked for number of rows in second section") { expect { () -> Void in _ = sut.tableView(sut.tableView, numberOfRowsInSection: 1) }.to(throwAssertion()) } it("shuld not throw when asked for cell at valid index path") { expect { () -> Void in _ = sut.tableView(sut.tableView, cellForRowAt: IndexPath(row: 0, section: 0)) }.notTo(throwAssertion()) } it("should return correct height for a row") { expect(sut.tableView(sut.tableView, heightForRowAt: IndexPath(row: 0, section: 0))) .to(equal(88)) } it("should throw when asked for row height at invalid index path") { expect { () -> Void in _ = sut.tableView(sut.tableView, heightForRowAt: IndexPath(row: 0, section: 1)) }.to(throwAssertion()) } } } } } struct Assembly: TableExampleAssembly {} }
63d1b2253237460a3b65db84de915640
35.723077
110
0.466695
false
false
false
false
ijoshsmith/abandoned-strings
refs/heads/master
AbandonedStrings/main.swift
mit
1
#!/usr/bin/env xcrun swift // // main.swift // AbandonedStrings // // Created by Joshua Smith on 2/1/16. // Copyright © 2016 iJoshSmith. All rights reserved. // /* For overview and usage information refer to https://github.com/ijoshsmith/abandoned-strings */ import Foundation // MARK: - File processing let dispatchGroup = DispatchGroup.init() let serialWriterQueue = DispatchQueue.init(label: "writer") func findFilesIn(_ directories: [String], withExtensions extensions: [String]) -> [String] { let fileManager = FileManager.default var files = [String]() for directory in directories { guard let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: directory) else { print("Failed to create enumerator for directory: \(directory)") return [] } while let path = enumerator.nextObject() as? String { let fileExtension = (path as NSString).pathExtension.lowercased() if extensions.contains(fileExtension) { let fullPath = (directory as NSString).appendingPathComponent(path) files.append(fullPath) } } } return files } func contentsOfFile(_ filePath: String) -> String { do { return try String(contentsOfFile: filePath) } catch { print("cannot read file!!!") exit(1) } } func concatenateAllSourceCodeIn(_ directories: [String], withStoryboard: Bool) -> String { var extensions = ["h", "m", "swift", "jsbundle"] if withStoryboard { extensions.append("storyboard") } let sourceFiles = findFilesIn(directories, withExtensions: extensions) return sourceFiles.reduce("") { (accumulator, sourceFile) -> String in return accumulator + contentsOfFile(sourceFile) } } // MARK: - Identifier extraction let doubleQuote = "\"" func extractStringIdentifiersFrom(_ stringsFile: String) -> [String] { return contentsOfFile(stringsFile) .components(separatedBy: "\n") .map { $0.trimmingCharacters(in: CharacterSet.whitespaces) } .filter { $0.hasPrefix(doubleQuote) } .map { extractStringIdentifierFromTrimmedLine($0) } } func extractStringIdentifierFromTrimmedLine(_ line: String) -> String { let indexAfterFirstQuote = line.index(after: line.startIndex) let lineWithoutFirstQuote = line[indexAfterFirstQuote...] let endIndex = lineWithoutFirstQuote.index(of:"\"")! let identifier = lineWithoutFirstQuote[..<endIndex] return String(identifier) } // MARK: - Abandoned identifier detection func findStringIdentifiersIn(_ stringsFile: String, abandonedBySourceCode sourceCode: String) -> [String] { return extractStringIdentifiersFrom(stringsFile).filter { identifier in let quotedIdentifier = "\"\(identifier)\"" let quotedIdentifierForStoryboard = "\"@\(identifier)\"" let signalQuotedIdentifierForJs = "'\(identifier)'" let isAbandoned = (sourceCode.contains(quotedIdentifier) == false && sourceCode.contains(quotedIdentifierForStoryboard) == false && sourceCode.contains(signalQuotedIdentifierForJs) == false) return isAbandoned } } func stringsFile(_ stringsFile: String, without identifiers: [String]) -> String { return contentsOfFile(stringsFile) .components(separatedBy: "\n") .filter({ (line) in guard line.hasPrefix(doubleQuote) else { return true } // leave non-strings lines like comments in let lineIdentifier = extractStringIdentifierFromTrimmedLine(line.trimmingCharacters(in: CharacterSet.whitespaces)) return identifiers.contains(lineIdentifier) == false }) .joined(separator: "\n") } typealias StringsFileToAbandonedIdentifiersMap = [String: [String]] func findAbandonedIdentifiersIn(_ rootDirectories: [String], withStoryboard: Bool) -> StringsFileToAbandonedIdentifiersMap { var map = StringsFileToAbandonedIdentifiersMap() let sourceCode = concatenateAllSourceCodeIn(rootDirectories, withStoryboard: withStoryboard) let stringsFiles = findFilesIn(rootDirectories, withExtensions: ["strings"]) for stringsFile in stringsFiles { dispatchGroup.enter() DispatchQueue.global().async { let abandonedIdentifiers = findStringIdentifiersIn(stringsFile, abandonedBySourceCode: sourceCode) if abandonedIdentifiers.isEmpty == false { serialWriterQueue.async { map[stringsFile] = abandonedIdentifiers dispatchGroup.leave() } } else { NSLog("\(stringsFile) has no abandonedIdentifiers") dispatchGroup.leave() } } } dispatchGroup.wait() return map } // MARK: - Engine func getRootDirectories() -> [String]? { var c = [String]() for arg in CommandLine.arguments { c.append(arg) } c.remove(at: 0) if isOptionalParameterForStoryboardAvailable() { c.removeLast() } if isOptionaParameterForWritingAvailable() { c.remove(at: c.index(of: "write")!) } return c } func isOptionalParameterForStoryboardAvailable() -> Bool { return CommandLine.arguments.last == "storyboard" } func isOptionaParameterForWritingAvailable() -> Bool { return CommandLine.arguments.contains("write") } func displayAbandonedIdentifiersInMap(_ map: StringsFileToAbandonedIdentifiersMap) { for file in map.keys.sorted() { print("\(file)") for identifier in map[file]!.sorted() { print(" \(identifier)") } print("") } } if let rootDirectories = getRootDirectories() { print("Searching for abandoned resource strings…") let withStoryboard = isOptionalParameterForStoryboardAvailable() let map = findAbandonedIdentifiersIn(rootDirectories, withStoryboard: withStoryboard) if map.isEmpty { print("No abandoned resource strings were detected.") } else { print("Abandoned resource strings were detected:") displayAbandonedIdentifiersInMap(map) if isOptionaParameterForWritingAvailable() { map.keys.forEach { (stringsFilePath) in print("\n\nNow modifying \(stringsFilePath) ...") let updatedStringsFileContent = stringsFile(stringsFilePath, without: map[stringsFilePath]!) do { try updatedStringsFileContent.write(toFile: stringsFilePath, atomically: true, encoding: .utf8) } catch { print("ERROR writing file: \(stringsFilePath)") } } } } } else { print("Please provide the root directory for source code files as a command line argument.") }
3aa62b4e7876a707db8b0d42e5f9f327
34.852632
139
0.664856
false
false
false
false
peferron/algo
refs/heads/master
EPI/Dynamic Programming/The knapsack problem/swift/test.swift
mit
1
import Darwin func == (lhs: [Item], rhs: [Item]) -> Bool { guard lhs.count == rhs.count else { return false } for (i, array) in lhs.enumerated() { guard array == rhs[i] else { return false } } return true } let tests: [(items: [Item], subTests: [(capacity: Int, selection: [Int])])] = [ ( items: [ (value: 13, weight: 5), (value: 15, weight: 4), (value: 10, weight: 3), (value: 6, weight: 2), ], subTests: [ (capacity: 1, selection: []), (capacity: 2, selection: [3]), (capacity: 3, selection: [2]), (capacity: 4, selection: [1]), (capacity: 5, selection: [2, 3]), (capacity: 6, selection: [1, 3]), (capacity: 7, selection: [1, 2]), (capacity: 8, selection: [1, 2]), (capacity: 9, selection: [1, 2, 3]), (capacity: 10, selection: [1, 2, 3]), (capacity: 11, selection: [0, 1, 3]), (capacity: 12, selection: [0, 1, 2]), (capacity: 13, selection: [0, 1, 2]), (capacity: 14, selection: [0, 1, 2, 3]), ] ), ( items: [ (value: 65, weight: 20), (value: 35, weight: 8), (value: 245, weight: 60), (value: 195, weight: 55), (value: 65, weight: 40), (value: 150, weight: 70), (value: 275, weight: 85), (value: 155, weight: 25), (value: 120, weight: 30), (value: 320, weight: 65), (value: 75, weight: 75), (value: 40, weight: 10), (value: 200, weight: 95), (value: 100, weight: 50), (value: 220, weight: 40), (value: 99, weight: 10), ], subTests: [ (capacity: 130, selection: [7, 9, 14]), ] ) ] for test in tests { for subTest in test.subTests { let actual = select(test.items, capacity: subTest.capacity) guard actual == subTest.selection else { print("For items \(test.items) and capacity \(subTest.capacity), " + "expected selection to be \(subTest.selection), but was \(actual)") exit(1) } } }
5daf03f01b45b38021dbf982d9c8c684
30.310811
83
0.448856
false
true
false
false
Tomoki-n/iPhoneBeacon
refs/heads/master
iPhoneBeacon/ViewController.swift
mit
1
// // ViewController.swift // iPhoneBeacon // // Created by 山口将槻 on 2015/10/16. // Copyright © 2015年 山口将槻. All rights reserved. // import UIKit import CoreBluetooth import CoreLocation class ViewController: UIViewController, CBPeripheralManagerDelegate { @IBOutlet weak var cover: UIView! @IBOutlet weak var majorLabel: UILabel! @IBOutlet weak var minorLabel: UILabel! @IBOutlet weak var majorStepper: UIStepper! @IBOutlet weak var minorStepper: UIStepper! var peripheralManager:CBPeripheralManager! var myUUID:NSUUID! var startLocation:CGPoint? var major:UInt16 = 0 var minor:UInt16 = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil) self.myUUID = NSUUID(UUIDString: "00000000-88F6-1001-B000-001C4D2D20E6") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { print("state: \(peripheral.state)") } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first self.startLocation = touch?.locationInView(self.view) let myRegion = CLBeaconRegion(proximityUUID: self.myUUID!, major: self.major, minor: self.minor, identifier: self.myUUID.UUIDString) self.peripheralManager.startAdvertising(myRegion.peripheralDataWithMeasuredPower(nil) as? [String : AnyObject]) } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first let location = touch?.locationInView(self.view) if touch?.view?.tag == 1 { if self.cover.frame.origin.x > -40 && location!.x - self.startLocation!.x < 0 { self.cover.frame.origin.x = location!.x - self.startLocation!.x } } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { self.peripheralManager.stopAdvertising() UIView.animateWithDuration(0.4) { () -> Void in self.cover.frame.origin.x = 0 } } @IBAction func major(sender: AnyObject) { let value = NSNumber(double: majorStepper.value) self.majorLabel.text = String(value.integerValue) self.major = value.unsignedShortValue } @IBAction func minor(sender: AnyObject) { let value = NSNumber(double: minorStepper.value) self.minorLabel.text = String(value.integerValue) self.minor = value.unsignedShortValue } }
0fe92d254b4771540dd8427fa44bf38c
33.170732
140
0.669879
false
false
false
false
imclean/JLDishWashers
refs/heads/master
JLDishwasher/PromoMessage.swift
gpl-3.0
1
// // PromoMessage.swift // JLDishwasher // // Created by Iain McLean on 21/12/2016. // Copyright © 2016 Iain McLean. All rights reserved. // import Foundation public class PromoMessages { public var customSpecialOffer : CustomSpecialOffer? public var priceMatched : String? public var offer : String? public var bundleHeadline : String? public var customPromotionalMessage : String? /** Returns an array of PromoMessages based on given dictionary. Sample usage: let promoMessages_list = PromoMessages.modelsFromDictionaryArray(someDictionaryArrayFromJSON) - parameter array: NSArray from JSON dictionary. - returns: Array of PromoMessages Instances. */ public class func modelsFromDictionaryArray(array:NSArray) -> [PromoMessages] { var models:[PromoMessages] = [] for item in array { models.append(PromoMessages(dictionary: item as! NSDictionary)!) } return models } /** Constructs the object based on the given dictionary. Sample usage: let promoMessages = PromoMessages(someDictionaryFromJSON) - parameter dictionary: NSDictionary from JSON. - returns: PromoMessages Instance. */ required public init?(dictionary: NSDictionary) { if (dictionary["customSpecialOffer"] != nil) { customSpecialOffer = CustomSpecialOffer(dictionary: dictionary["customSpecialOffer"] as! NSDictionary) } priceMatched = dictionary["priceMatched"] as? String offer = dictionary["offer"] as? String bundleHeadline = dictionary["bundleHeadline"] as? String customPromotionalMessage = dictionary["customPromotionalMessage"] as? String } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary.setValue(self.customSpecialOffer?.dictionaryRepresentation(), forKey: "customSpecialOffer") dictionary.setValue(self.priceMatched, forKey: "priceMatched") dictionary.setValue(self.offer, forKey: "offer") dictionary.setValue(self.bundleHeadline, forKey: "bundleHeadline") dictionary.setValue(self.customPromotionalMessage, forKey: "customPromotionalMessage") return dictionary } }
713f6bfdce6a0df940089732b941ee4f
31.076923
159
0.671463
false
false
false
false
cwaffles/Soulcast
refs/heads/master
Soulcast/HistoryVC.swift
mit
1
// // HistoryVC.swift // Soulcast // // Created by June Kim on 2016-11-17. // Copyright © 2016 Soulcast-team. All rights reserved. // import Foundation import UIKit protocol HistoryVCDelegate: class { //TODO: } ///displays a list of souls played in the past in reverse chronological order since 24 hours ago class HistoryVC: UIViewController, UITableViewDelegate, SoulPlayerDelegate, HistoryDataSourceDelegate { //title label let tableView = UITableView()//table view let dataSource = HistoryDataSource() var selectedSoul: Soul? var playlisting: Bool = false var startedPlaylisting: Bool = false weak var delegate: HistoryVCDelegate? let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() addTableView() dataSource.fetch() // view.addSubview(IntegrationTestButton(frame:CGRect(x: 10, y: 10, width: 100, height: 100))) } func addTableView() { let tableHeight = view.bounds.height * 0.95 tableView.frame = CGRect(x: 0, y: view.bounds.height - tableHeight, width: screenWidth, height: tableHeight) view.addSubview(tableView) tableView.delegate = self tableView.dataSource = dataSource tableView.allowsMultipleSelectionDuringEditing = false tableView.allowsMultipleSelection = false dataSource.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: String(describing: UITableViewCell())) tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: String(describing: UITableViewHeaderFooterView())) refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged) tableView.addSubview(refreshControl) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) soulPlayer.subscribe(self) startPlaylisting() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) soulPlayer.unsubscribe(self) deselectAllRows() } func startPlaylisting() { let first = IndexPath(row: 0, section: 0) tableView.selectRow(at: first, animated: true, scrollPosition: .none) selectedSoul = dataSource.soul(forIndex: 0) // play first soul soulPlayer.reset() if let thisSoul = selectedSoul { soulPlayer.startPlaying(thisSoul) playlisting = true } } func playNextSoul() { if selectedSoul != nil { let nextIndex = dataSource.indexPath(forSoul: selectedSoul!).row + 1 let nextIndexPath = IndexPath(item: nextIndex , section: 0) selectedSoul = dataSource.soul(forIndex: nextIndex) tableView.selectRow(at: nextIndexPath, animated: true, scrollPosition: .none) } if selectedSoul != nil { soulPlayer.reset() soulPlayer.startPlaying(selectedSoul) } } func refresh(_ refreshControl:UIRefreshControl) { dataSource.fetch() } // UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { playlisting = false selectedSoul = dataSource.soul(forIndex:indexPath.row) if SoulPlayer.playing { soulPlayer.reset() tableView.deselectRow(at: indexPath, animated: true) } else { soulPlayer.reset() soulPlayer.startPlaying(selectedSoul) } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UITableViewHeaderFooterView(reuseIdentifier: String(describing: UITableViewHeaderFooterView())) return headerView } func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 55 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "Block" } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 55 } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { soulPlayer.reset() selectedSoul = nil } // HistoryDataSourceDelegate func willFetch() { //show loading refreshControl.beginRefreshing() } func didFetch(_ success: Bool) { if success { } else { //show failure, retry button. } refreshControl.endRefreshing() } func didUpdate(_ soulcount: Int) { tableView.reloadData() } func didFinishUpdating(_ soulCount: Int) { guard isViewLoaded && view.window != nil else { return } tableView.reloadData() //TODO: // if !startedPlaylisting { startPlaylisting() // } startedPlaylisting = true } func didRequestBlock(_ soul: Soul) { present(blockAlertController(soul), animated: true) { // } return } fileprivate func block(_ soul:Soul) { ServerFacade.block(soul, success: { //remove soul at index self.dataSource.remove(soul) }) { statusCode in print(statusCode) } } func blockAlertController(_ soul:Soul) -> UIAlertController { let controller = UIAlertController(title: "Block Soul", message: "You will no longer hear from the device that casted this soul.", preferredStyle: .alert) controller.addAction(UIAlertAction(title: "Block", style: .default, handler: {(action) in self.block(soul) })) controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in // })) return controller } //SoulPlayerDelegate func didStartPlaying(_ soul:Soul) { } func didFinishPlaying(_ soul:Soul) { //deselect current row if same if soul == selectedSoul { tableView.deselectRow(at: dataSource.indexPath(forSoul: soul) as IndexPath, animated: true) } if playlisting { playNextSoul() } } func didFailToPlay(_ soul:Soul) { } func deselectAllRows() { for rowIndex in 0...dataSource.soulCount() { let indexPath = IndexPath(row: rowIndex, section: 0) tableView.deselectRow(at: indexPath, animated: true) } } }
10f38a4995a87250653ea26774c05528
29.2891
158
0.697074
false
false
false
false
Doracool/BuildingBlock
refs/heads/master
BuildingBlock/BuildingBlock/ViewController.swift
mit
1
// // ViewController.swift // BuildingBlock // // Created by qingyun on 16/1/27. // Copyright © 2016年 河南青云信息技术有限公司. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController ,GameViewDelegate { // let 定义常量 var定义变量 //定义边距 let MARGINE:CGFloat = 10 //按钮的大小 let BUTTON_SIZE:CGFloat = 48 //按钮的透明度 let BUTTON_ALPHA:CGFloat = 0.4 //tabbar的高度 let TOOLBAR_HEIGHT:CGFloat = 44 //屏幕的宽度 //隐式解析 在可选类型的后边 加上 ! 就不用在使用时在后边加 ! 了 如果解析类型后边跟的是? 则在使用是需要解包 在后边加上 ! var screenWidth:CGFloat! //屏幕的高度 var screenHeight:CGFloat! var gameView:GameView! //播放音乐的方法库 var bgMusicPlayer:AVAudioPlayer! //速度的label var speedShow:UILabel! //分数的label var scoreShow:UILabel! var stopButton:UIButton! var button1: UIButton! var BGimg:UIImageView! var backBtn:UIButton! var btn:UIButton! override func viewDidLoad() { super.viewDidLoad() BGimg = UIImageView.init(frame: self.view.frame) // BGimg.image = UIImage(named: "时光十年") BGimg.backgroundColor = UIColor.blueColor() BGimg.alpha = 0.5 self.view.addSubview(BGimg) //背景颜色 self.view.backgroundColor = UIColor.whiteColor() //设置大小 let rect = UIScreen.mainScreen().bounds screenWidth = rect.size.width screenHeight = rect.size.height addToolBar() let gameRect = CGRectMake(rect.origin.x + MARGINE + 4, rect.origin.y + TOOLBAR_HEIGHT + 2 * MARGINE + 60 , rect.size.width - MARGINE * 2 - 9, rect.size.height - BUTTON_SIZE * 2 - TOOLBAR_HEIGHT - 89) gameView = GameView(frame: gameRect) gameView.delegate = self self.view.addSubview(gameView) backBtn = UIButton.init(type: UIButtonType.Custom) backBtn.addTarget(self, action: "back", forControlEvents: UIControlEvents.TouchUpInside) backBtn.setBackgroundImage(UIImage(named: "iconfont-fanhui"), forState: UIControlState.Normal) backBtn.setBackgroundImage(UIImage(named: "iconfont-fanhui"), forState: UIControlState.Highlighted) backBtn.frame.size = (backBtn.currentBackgroundImage?.size)! self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: backBtn) btn = UIButton.init(type: UIButtonType.Custom) btn.addTarget(self, action: "stopMusic", forControlEvents: UIControlEvents.TouchUpInside) btn.setBackgroundImage(UIImage(named: "OpenMusic"), forState: UIControlState.Normal) btn.setTitle("asd", forState: UIControlState.Normal) btn.titleLabel?.alpha = 0 btn.frame.size = (btn.currentBackgroundImage?.size)! self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: btn) //添加背景音乐 let bgMusicUrl = NSBundle.mainBundle().URLForResource("bgMusic", withExtension: "mp3") gameView.startGame() addButtons() do { try bgMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicUrl!)//解包 }catch { } bgMusicPlayer.numberOfLoops = -1 bgMusicPlayer.play() } //添加toolbar func addToolBar() { let toolBar = UIToolbar(frame: CGRectMake(0,MARGINE*2 + 44,screenWidth,TOOLBAR_HEIGHT)) self.view.addSubview(toolBar) //创建 一个显示速度的标签 let speedLabel = UILabel() speedLabel.frame = CGRectMake(0, 0, 50, TOOLBAR_HEIGHT) speedLabel.text = "速度:" let speedLabelItem = UIBarButtonItem(customView: speedLabel) //创建第二个显示速度值的标签 speedShow = UILabel() speedShow.frame = CGRectMake(0, 0, 20, TOOLBAR_HEIGHT) speedShow.textColor = UIColor.redColor() let speedShowItem = UIBarButtonItem(customView: speedShow) //创建第三个显示当前积分的标签 let scoreLabel = UILabel() scoreLabel.frame = CGRectMake(0, 0, 90, TOOLBAR_HEIGHT) scoreLabel.text = "升级分数:" let scoreLabelItem = UIBarButtonItem(customView: scoreLabel) //创建第四个显示积分值的标签 scoreShow = UILabel() scoreShow.frame = CGRectMake(0, 0, 40, TOOLBAR_HEIGHT) scoreShow.textColor = UIColor.redColor() let scoreShowItem = UIBarButtonItem(customView: scoreShow) let flexItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) toolBar.items = [speedLabelItem,speedShowItem,flexItem,scoreLabelItem,scoreShowItem] } //定义方向 func addButtons() { //左 let leftBtn = UIButton() leftBtn.frame = CGRectMake(screenWidth - BUTTON_SIZE * 3 - MARGINE - 14, screenHeight - BUTTON_SIZE * 2 - MARGINE, BUTTON_SIZE * 1.2, BUTTON_SIZE * 1.2) leftBtn.setImage(UIImage(named: "left"), forState: UIControlState.Normal) leftBtn.addTarget(self, action: "left:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(leftBtn) //旋转 let upBtn = UIButton() upBtn.frame = CGRectMake( MARGINE, screenHeight - BUTTON_SIZE - MARGINE * 3 + 5, BUTTON_SIZE * 1.2, BUTTON_SIZE * 1.2) upBtn.setImage(UIImage(named: "xuanzhuan"), forState: UIControlState.Normal) upBtn.addTarget(self, action: "up:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(upBtn) //右 let rightBtn = UIButton() rightBtn.frame = CGRectMake(screenWidth - BUTTON_SIZE - MARGINE, screenHeight - BUTTON_SIZE * 2 - MARGINE, BUTTON_SIZE * 1.2, BUTTON_SIZE * 1.2) rightBtn.setImage(UIImage(named: "right"), forState: UIControlState.Normal) rightBtn.addTarget(self, action: "right:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(rightBtn) //下 let downBtn = UIButton() downBtn.frame = CGRectMake(screenWidth - BUTTON_SIZE * 2 - MARGINE - 7, screenHeight - BUTTON_SIZE - MARGINE , BUTTON_SIZE * 1.2, BUTTON_SIZE * 1.2) downBtn.setImage(UIImage(named: "down"), forState: UIControlState.Normal) downBtn.addTarget(self, action: "down:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(downBtn) stopButton = UIButton.init(type: UIButtonType.Custom) stopButton.frame = CGRectMake(MARGINE * 2 + BUTTON_SIZE * 2, screenHeight - BUTTON_SIZE - MARGINE * 2, BUTTON_SIZE, BUTTON_SIZE) stopButton.setTitle("暂停", forState: UIControlState.Normal) stopButton.titleLabel?.alpha = 0 stopButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal) stopButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal) stopButton.addTarget(self, action: "stop:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(stopButton) } func left(sender:UIButton) { gameView.moveLeft() } func up(sender:UIButton){ gameView.rotate() } func right(sender:UIButton){ gameView.moveRight() } func down(sender:UIButton){ gameView.moveDown() } func stop(sender:UIButton){ if stopButton.titleLabel?.text == "暂停" { stopButton.setTitle("继续", forState: UIControlState.Normal) stopButton.setImage(UIImage(named: "countin"), forState: UIControlState.Normal) bgMusicPlayer.pause() gameView.gameSTop() }else { stopButton.setTitle("暂停", forState: UIControlState.Normal) stopButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal) bgMusicPlayer.play() gameView.gameSTop() } } func Continue(sender:UIButton){ button1.setTitle("zanting", forState: UIControlState.Normal) gameView.countinue() } func updataScore(score: Int) { self.title = "积分:\(score)" // self.scoreShow.text = "\(score)" } func updataSpeed(speed: Int) { // let SPlabel = UILabel() let string = speed * speed * 200 self.scoreShow.text = "\(string)" self.speedShow.text = "\(speed)" } func stopMusic() { if btn.titleLabel?.text == "asd" { bgMusicPlayer.pause() btn.setImage(UIImage(named: "StopMucic"), forState: UIControlState.Normal) btn.setTitle("dsa", forState: UIControlState.Normal) }else { bgMusicPlayer.play() btn.setImage(UIImage(named: "OpenMusic"), forState: UIControlState.Normal) btn.setTitle("asd", forState: UIControlState.Normal) } } func back() { bgMusicPlayer.pause() gameView.gameSTop() self.navigationController!.popToRootViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
dc65eed9f2dd57fe8ace1e16ae302b5b
35.294821
207
0.634248
false
false
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
refs/heads/master
iOSDFULibrary/Classes/Implementation/SecureDFU/Characteristics/SecureDFUPacket.swift
bsd-3-clause
1
/* * Copyright (c) 2019, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth internal class SecureDFUPacket: DFUCharacteristic { private let packetSize: UInt32 internal var characteristic: CBCharacteristic internal var logger: LoggerHelper /// Number of bytes of firmware already sent. private(set) var bytesSent: UInt32 = 0 /// Number of bytes sent at the last progress notification. /// This value is used to calculate the current speed. private var totalBytesSentSinceProgessNotification: UInt32 = 0 private var totalBytesSentWhenDfuStarted: UInt32 = 0 /// Current progress in percents (0-99). private var progressReported: UInt8 = 0 private var startTime: CFAbsoluteTime? private var lastTime: CFAbsoluteTime? internal var valid: Bool { return characteristic.properties.contains(.writeWithoutResponse) } required init(_ characteristic: CBCharacteristic, _ logger: LoggerHelper) { self.characteristic = characteristic self.logger = logger if #available(iOS 9.0, macOS 10.12, *) { let optService: CBService? = characteristic.service guard let peripheral = optService?.peripheral else { packetSize = 20 // Default MTU is 23. return } // Make the packet size the first word-aligned value that's less than the maximum. packetSize = UInt32(peripheral.maximumWriteValueLength(for: .withoutResponse)) & 0xFFFFFFFC if packetSize > 20 { // MTU is 3 bytes larger than payload // (1 octet for Op-Code and 2 octets for Att Handle). logger.v("MTU set to \(packetSize + 3)") } } else { packetSize = 20 // Default MTU is 23. } } // MARK: - Characteristic API methods /** Sends the whole content of the data object. - parameter data: The data to be sent. - parameter report: Method called in case of an error. */ func sendInitPacket(_ data: Data, onError report: ErrorCallback?) { // Get the peripheral object. let optService: CBService? = characteristic.service guard let peripheral = optService?.peripheral else { report?(.invalidInternalState, "Assert characteristic.service?.peripheral != nil failed") return } // Data may be sent in up-to-20-bytes packets. var offset: UInt32 = 0 var bytesToSend = UInt32(data.count) let packetUUID = characteristic.uuid.uuidString repeat { let packetLength = min(bytesToSend, packetSize) let packet = data.subdata(in: Int(offset) ..< Int(offset + packetLength)) logger.v("Writing to characteristic \(packetUUID)...") logger.d("peripheral.writeValue(0x\(packet.hexString), for: \(packetUUID), type: .withoutResponse)") peripheral.writeValue(packet, for: characteristic, type: .withoutResponse) offset += packetLength bytesToSend -= packetLength } while bytesToSend > 0 } /** Sends a given range of data from given firmware over DFU Packet characteristic. If the whole object is completed the completition callback will be called. - parameters: - prnValue: Packet Receipt Notification value used in the process. 0 to disable PRNs. - range: The range of the firmware that is to be sent in this object. - firmware: The whole firmware to be sent in this part. - progress: An optional progress delegate. - queue: The queue to dispatch progress events on. - complete: The completon callback. - report: Method called in case of an error. */ func sendNext(_ prnValue: UInt16, packetsFrom range: Range<Int>, of firmware: DFUFirmware, andReportProgressTo progress: DFUProgressDelegate?, on queue: DispatchQueue, andCompletionTo complete: @escaping Callback, onError report: ErrorCallback?) { let optService: CBService? = characteristic.service guard let peripheral = optService?.peripheral else { report?(.invalidInternalState, "Assert characteristic.service?.peripheral != nil failed") return } let objectData = firmware.data.subdata(in: range) let objectSizeInBytes = UInt32(objectData.count) let objectSizeInPackets = (objectSizeInBytes + packetSize - 1) / packetSize let packetsSent = (bytesSent + packetSize - 1) / packetSize let packetsLeft = objectSizeInPackets - packetsSent // Calculate how many packets should be sent before EOF or next receipt notification. var packetsToSendNow = min(UInt32(prnValue), packetsLeft) if prnValue == 0 { packetsToSendNow = packetsLeft } // This is called when we no longer have data to send (PRN received after the whole // object was sent). Fixes issue IDFU-9. if packetsToSendNow == 0 { complete() return } // Initialize timers. if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() lastTime = startTime totalBytesSentWhenDfuStarted = UInt32(range.lowerBound) totalBytesSentSinceProgessNotification = totalBytesSentWhenDfuStarted // Notify progress delegate that upload has started (0%). queue.async { progress?.dfuProgressDidChange( for: firmware.currentPart, outOf: firmware.parts, to: 0, currentSpeedBytesPerSecond: 0.0, avgSpeedBytesPerSecond: 0.0 ) } } let originalPacketsToSendNow = packetsToSendNow while packetsToSendNow > 0 { // Starting from iOS 11 and MacOS 10.13 the PRNs are no longer required due to new API. var canSendPacket = true if #available(iOS 11.0, macOS 10.13, *) { // The peripheral.canSendWriteWithoutResponse often returns false before even we // start sending, let's do a workaround. canSendPacket = bytesSent == 0 || peripheral.canSendWriteWithoutResponse } // If PRNs are enabled we will ignore the new API and base synchronization on PRNs only. guard canSendPacket || prnValue > 0 else { break } let bytesLeft = objectSizeInBytes - bytesSent let packetLength = min(bytesLeft, packetSize) let packet = objectData.subdata(in: Int(bytesSent) ..< Int(packetLength + bytesSent)) peripheral.writeValue(packet, for: characteristic, type: .withoutResponse) bytesSent += packetLength packetsToSendNow -= 1 // Calculate the total progress of the firmware, presented to the delegate. let totalBytesSent = UInt32(range.lowerBound) + bytesSent let currentProgress = UInt8(totalBytesSent * 100 / UInt32(firmware.data.count)) // in percantage (0-100) // Notify progress listener only if current progress has increased since last time. if currentProgress > progressReported { // Calculate current transfer speed in bytes per second. let now = CFAbsoluteTimeGetCurrent() let currentSpeed = Double(totalBytesSent - totalBytesSentSinceProgessNotification) / (now - lastTime!) let avgSpeed = Double(totalBytesSent - totalBytesSentWhenDfuStarted) / (now - startTime!) lastTime = now totalBytesSentSinceProgessNotification = totalBytesSent // Notify progress delegate of overall progress. queue.async { progress?.dfuProgressDidChange( for: firmware.currentPart, outOf: firmware.parts, to: Int(currentProgress), currentSpeedBytesPerSecond: currentSpeed, avgSpeedBytesPerSecond: avgSpeed ) } progressReported = currentProgress } // Notify handler of current object progress to start sending next one. if bytesSent == objectSizeInBytes { if prnValue == 0 || originalPacketsToSendNow < UInt32(prnValue) { complete() } else { // The whole object has been sent but the DFU target will // send a PRN notification as expected. // The sendData method will be called again // with packetsLeft = 0 (see line 132). // Do nothing. } } } } func resetCounters() { bytesSent = 0 } }
ad6ecb5c221bef8f4e5e1bb7262f013d
43.665289
118
0.616986
false
false
false
false
luizlopezm/ios-Luis-Trucking
refs/heads/master
Pods/SwiftForms/SwiftForms/cells/FormSwitchCell.swift
mit
1
// // FormSwitchCell.swift // SwiftForms // // Created by Miguel Angel Ortuno on 21/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit public class FormSwitchCell: FormTitleCell { // MARK: Cell views public let switchView = UISwitch() // MARK: FormBaseCell public override func configure() { super.configure() selectionStyle = .None switchView.addTarget(self, action: #selector(FormSwitchCell.valueChanged(_:)), forControlEvents: .ValueChanged) accessoryView = switchView } public override func update() { super.update() titleLabel.text = rowDescriptor.title if rowDescriptor.value != nil { switchView.on = rowDescriptor.value as! Bool } else { switchView.on = false rowDescriptor.value = false } } // MARK: Actions internal func valueChanged(_: UISwitch) { if switchView.on != rowDescriptor.value { rowDescriptor.value = switchView.on as Bool } } }
7fc52a8d01347886eca6bf86844afb46
22.326531
119
0.586177
false
false
false
false
piersb/macsterplan
refs/heads/master
Macsterplan/Campaign.swift
gpl-3.0
1
// // Campaign.swift // // // Created by Piers Beckley on 10/08/2015. // // import Foundation import CoreData public class Campaign: NSManagedObject { @NSManaged public var name: String @NSManaged public var characters: Set<GameCharacter>? @NSManaged public var players: Set<Player>? @NSManaged public var dateCreated: NSDate convenience init(context: NSManagedObjectContext) { // may be necessary to avoid the nil-return bug described at http://www.jessesquires.com/swift-coredata-and-testing/ let entityDescription = NSEntityDescription.entityForName("Campaign", inManagedObjectContext: context)! self.init(entity: entityDescription, insertIntoManagedObjectContext: context) } public func isPlayerInCampaign (aPlayer: Player) -> Bool { return players!.contains(aPlayer) } public func addPlayer (aNewPlayer: Player) { var items = self.mutableSetValueForKey("players") items.addObject(aNewPlayer) } public func listPlayers () -> Set<Player> { return players! } func removeList(values: NSSet) { var items = self.mutableSetValueForKey("lists"); for value in values { items.removeObject(value) } } public func addCharacter (aNewCharacter: GameCharacter) { var items = self.mutableSetValueForKey("characters") items.addObject(aNewCharacter) } public override func awakeFromInsert() { super.awakeFromInsert() self.dateCreated = NSDate() players = Set<Player>() } public override func awakeFromFetch() { super.awakeFromFetch() println("awaking from fetch") } }
bc62fae44e9de0cce2c608a8b4fe863c
25.477612
124
0.642978
false
false
false
false
lzpfmh/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers/Main/MainSplitViewController.swift
mit
1
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class MainSplitViewController: UISplitViewController { init() { super.init(nibName: nil, bundle: nil) preferredDisplayMode = .AllVisible if (interfaceOrientation == UIInterfaceOrientation.Portrait || interfaceOrientation == UIInterfaceOrientation.PortraitUpsideDown) { minimumPrimaryColumnWidth = CGFloat(300.0) maximumPrimaryColumnWidth = CGFloat(300.0) } else { minimumPrimaryColumnWidth = CGFloat(360.0) maximumPrimaryColumnWidth = CGFloat(360.0) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { super.willRotateToInterfaceOrientation(toInterfaceOrientation, duration: duration) if (toInterfaceOrientation == UIInterfaceOrientation.Portrait || toInterfaceOrientation == UIInterfaceOrientation.PortraitUpsideDown) { minimumPrimaryColumnWidth = CGFloat(300.0) maximumPrimaryColumnWidth = CGFloat(300.0) } else { minimumPrimaryColumnWidth = CGFloat(360.0) maximumPrimaryColumnWidth = CGFloat(360.0) } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
ecdf710cf458f0385f611f14b3ec3b78
35.902439
143
0.681878
false
false
false
false
penniooi/TestKichen
refs/heads/master
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendLikeCell.swift
mit
1
// // CBRecommendLikeCell.swift // TestKitchen // // Created by aloha on 16/8/17. // Copyright © 2016年 胡颉禹. All rights reserved. // import UIKit class CBRecommendLikeCell: UITableViewCell { //显示的数据 var model: CBRecommendwidgetListModel?{ didSet{ //显示按钮的文字和属性 showData() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } //显示图片和文字 func showData(){ for var i in 0..<8{ //显示图片的model if model?.widget_data?.count>i{ let imagemodel = model?.widget_data![i] if imagemodel?.type == "image"{ //获取图片视图 let index = i/2 let subView = self.contentView.viewWithTag(200+index) if subView?.isKindOfClass(UIImageView.self) == true{ let imageView = subView as! UIImageView imageView.kf_setImageWithURL(NSURL(string: (imagemodel?.content)!), placeholderImage: UIImage(named: "sdefaultImage.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } } if model?.widget_data?.count>i+1{ let textModel = model?.widget_data![i+1] if textModel?.type == "text"{ let subView = self.contentView.viewWithTag(300+i/2) if subView?.isKindOfClass(UILabel.self) == true{ let label = subView as! UILabel label.text = textModel?.content } } } i += 1 } } //创建cell的方法 class func creatLikeCellFor(tabView:UITableView,atIndexPath indexPath:NSIndexPath,withlistModel listModel:CBRecommendwidgetListModel)->CBRecommendLikeCell{ //猜你喜欢 let cellId = "CBRecommendLikeCellId" var cell = tabView.dequeueReusableCellWithIdentifier(cellId) as? CBRecommendLikeCell if nil == cell { cell = NSBundle.mainBundle().loadNibNamed("CBRecommendLikeCell", owner: nil, options: nil).last as? CBRecommendLikeCell } cell?.model = listModel return cell! } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
ddc3669f89d7339f078f26831c62f6f6
25.663462
208
0.49405
false
false
false
false
primetimer/PrimeFactors
refs/heads/master
PrimeFactors/Classes/PhiTable.swift
mit
1
// // PhiTable.swift // PrimeBase // // Created by Stephan Jancar on 29.11.16. // Copyright © 2016 esjot. All rights reserved. // import Foundation public class PhiTable { var usebackward = true //Use backward calculation via known pi var usecache = true var pcalc : PrimeCalculator! var pitable : PiTable! var maxpintable : UInt64 = 0 var primorial : [UInt64] = [] var primorial1 : [UInt64] = [] var phi : [[UInt64]] = [] var phitablesize = 7 var phicache = NSCache<NSString, NSNumber>() func ReleaseCache() { phicache = NSCache<NSString, NSNumber>() } var first : [UInt64] = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,71,73,79,83,89,97] private func CalcPrimorial(maxp: UInt64 = 23) { //23 because 2*3*...*23 < UInt32.max var prod : UInt64 = 1 var prod1 : UInt64 = 1 for p in self.first { if p > maxp { break } prod = prod * p prod1 = prod1 * (p-1) primorial.append(prod) primorial1.append(prod1) } } init(pcalc : PrimeCalculator, pitable: PiTable, phitablesize : Int = 7) { //verbose = piverbose self.pcalc = pcalc self.pitable = pitable self.phitablesize = phitablesize self.maxpintable = pitable.Pin(m: pitable.ValidUpto()) CalcPrimorial() Initphitable() } private func Initphitable() { phi = [[UInt64]] (repeating: [], count: phitablesize) for l in 0..<phitablesize { phi[l] = [UInt64] (repeating : 0, count : Int(primorial[l])) var count : UInt64 = 0 for k in 0..<primorial[l] { var relativeprime = true for pindex in 0...l { let p = pitable.NthPrime(n: pindex+1) if k % p == 0 { relativeprime = false break } } if relativeprime { count = count + 1 } phi[l][Int(k)] = count } } } //The Number of integers of the for form n = pi * pj //with pj >= pi > a-tth Prime func P2(x: UInt64, a: UInt64) -> UInt64 { #if true let starttime = CFAbsoluteTimeGetCurrent() #endif let r2 = x.squareRoot() let pib = pitable.Pin(m: r2) if a >= pib { return 0 } var p2 : UInt64 = 0 for i in a+1...pib { let p = pitable.NthPrime(n: Int(i)) let xp = x / p let pi = pitable.Pin(m: xp) p2 = p2 + pi - (i - 1) } #if false phideltap2time = phideltap2time + CFAbsoluteTimeGetCurrent() - starttime #endif return p2 } var rekurs = 0 //The Number of integers of the for form n = pi * pj * pk //with k >= pj >= pi > a-tth Prime func P3(x: UInt64, a: UInt64) -> UInt64 { let r3 = x.iroot3() let pi3 = pitable.Pin(m: r3) if a >= pi3 { return 0 } var p3 : UInt64 = 0 for i in a+1...pi3 { let p = pitable.NthPrime(n: Int(i)) let xp = x / p let rxp = xp.squareRoot() let bi = pitable.Pin(m: rxp) for j in i...bi { let q = pitable.NthPrime(n: (Int(j))) let xpq = x / (p*q) let pixpq = pitable.Pin(m: xpq) p3 = p3 + pixpq - (j-1) } } return p3 } //Calculates Phi aka Legendre sum func Phi(x: UInt64, nr: Int) -> UInt64 { if x == 0 { return 0 } assert (UInt64(nr) <= pitable.ValidUpto()) // phi(x) = primorial1 * (x / primorial) + phitable if nr == 0 { return x } if nr == 1 { return x - x/2 } if nr == 2 { return x - x/2 - x/3 + x/6 } if nr == 3 { return x - x/2 - x/3 + x/6 - x/5 + x/10 + x/15 - x/30 } if x < pitable.NthPrime(n: nr+1) { return 1 } if nr < phitablesize { let t = x / primorial[nr-1] let r = x - primorial[nr-1] * t let q = primorial1[nr-1] let y = q * t + phi[nr-1][Int(r)] return y } //Look in Cache var nskey : NSString = "" if usecache && nr < 500 { let key = String(x) + ":" + String(nr) nskey = NSString(string: key) if let cachedVersion = phicache.object(forKey: nskey) { return cachedVersion.uint64Value } } rekurs = rekurs + 1 let value = PhiCalc(x: x, nr: nr) if usecache && nr < 500 { let cachevalue = NSNumber(value: value) phicache.setObject(cachevalue, forKey: nskey) } //print("time: ",rekurs, x,nr,phideltafwdtime,phideltap2time) rekurs = rekurs - 1 return value } var phideltafwdtime = 0.0 var phideltap2time = 0.0 private func IsPhiByPix(x: UInt64, a: Int) -> Bool { if x>maxpintable { return false } let pa = pitable.NthPrime(n: a) if x < pa*pa { return true } return false } private func PhiCalc(x: UInt64, nr : Int) -> UInt64 { #if false if IsPhiByPix(x: x,a: nr) { let pix = pitable.Pin(m: x) let phi = pix - UInt64(nr) + 1 return phi } #endif if usebackward && x < maxpintable { // Use backward Formula // phi = 1 + pi(x) - nr + P2(x,nr) + P3(x,nr) // for x in p(nr) ... p(nr+1)^4 let pa = pitable.NthPrime(n: nr) //let pa1 = pitable.NthPrime(n: nr+1) if x <= pa { return 1 } let papow2 = pa * pa let papow4 = papow2 * papow2 #if false if pa1pow >= UInt64(UInt32.max / 2) { pa1pow = x+1 } // to avoid overflow else { pa1pow = pa1pow * pa1pow } #endif if x < papow4 { let pix = pitable.Pin(m: x) var p2 : UInt64 = 0 if x >= papow2 { p2 = P2(x: x, a : UInt64(nr)) } var p3 : UInt64 = 0 if x >= pa * pa * pa { p3 = P3(x: x, a: UInt64(nr)) } let phi = 1 + pix + p2 + p3 - UInt64(nr) return phi } } //Use forward Recursion #if true let starttime = CFAbsoluteTimeGetCurrent() #endif var result = Phi(x: x, nr: phitablesize - 1) #if false phideltafwdtime = phideltafwdtime + CFAbsoluteTimeGetCurrent() - starttime #endif var i = phitablesize while i <= nr { let p = self.pitable.NthPrime(n: i) let n2 = x / p if n2 < p { break } let dif = Phi(x: n2,nr: i-1) result = result - dif i = i + 1 } var k = nr while x < self.pitable.NthPrime(n: k+1) { k = k - 1 } let delta = (Int(i)-Int(k)-1) result = UInt64(Int(result) + delta) return result } }
71aca7725075b27619976174c64c08ff
19.67474
97
0.570879
false
false
false
false
tsolomko/SWCompression
refs/heads/develop
Sources/TAR/ContainerEntryType+Tar.swift
mit
1
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation extension ContainerEntryType { init(_ fileTypeIndicator: UInt8) { switch fileTypeIndicator { case 0, 48: // "0" self = .regular case 49: // "1" self = .hardLink case 50: // "2" self = .symbolicLink case 51: // "3" self = .characterSpecial case 52: // "4" self = .blockSpecial case 53: // "5" self = .directory case 54: // "6" self = .fifo case 55: // "7" self = .contiguous default: self = .unknown } } var fileTypeIndicator: UInt8 { switch self { case .regular: return 48 case .hardLink: return 49 case .symbolicLink: return 50 case .characterSpecial: return 51 case .blockSpecial: return 52 case .directory: return 53 case .fifo: return 54 case .contiguous: return 55 case .socket: return 0 case .unknown: return 0 } } }
e5e36c754d108b48b71766df54f406fd
21.137931
38
0.469626
false
false
false
false
4np/UitzendingGemist
refs/heads/master
UitzendingGemist/StillCollectionViewCell.swift
apache-2.0
1
// // StillCollectionViewCell.swift // UitzendingGemist // // Created by Jeroen Wesbeek on 18/07/16. // Copyright © 2016 Jeroen Wesbeek. All rights reserved. // import Foundation import UIKit import NPOKit import CocoaLumberjack class StillCollectionViewCell: UICollectionViewCell { @IBOutlet weak fileprivate var stillImageView: UIImageView! // MARK: Lifecycle override func layoutSubviews() { super.layoutSubviews() } override func prepareForReuse() { super.prepareForReuse() self.stillImageView.image = nil } // MARK: Focus engine override var canBecomeFocused: Bool { return false } // MARK: Configuration func configure(withStill still: NPOStill) { // Somehow in tvOS 10 / Xcode 8 / Swift 3 the frame will initially be 1000x1000 // causing the images to look compressed so hardcode the dimensions for now... // TODO: check if this is solved in later releases... //let size = self.stillImageView.frame.size let size = CGSize(width: 260, height: 146) _ = still.getImage(ofSize: size) { [weak self] image, error, _ in guard let image = image else { DDLogError("Could not fetch still image (\(String(describing: error)))") return } self?.stillImageView.image = image } } }
ce0cb20561e779e9f8495d2aeb3bcb50
26.358491
88
0.614483
false
false
false
false
schrockblock/subway-stations
refs/heads/master
SubwayStations/Classes/Station.swift
mit
1
// // Station.swift // Pods // // Created by Elliot Schrock on 6/28/16. // // import UIKit public protocol Station { var name: String! { get set } var stops: Array<Stop> { get set } } extension Station { public func distance(to point: (Double, Double), _ metric: ((Double, Double), (Double, Double)) -> Double) -> Double { let sortedStops = stops.filter { $0.location() != nil }.sorted { metric(point, $0.location()!) < metric(point, $1.location()!)} if let stop = sortedStops.first { return metric(point, stop.location()!) } return Double.infinity } } public func ==(lhs: Station, rhs: Station) -> Bool { if let lhsName = lhs.name { if let rhsName = rhs.name { if lhsName.lowercased() == rhsName.lowercased() { return true } let lhsArray = lhsName.lowercased().components(separatedBy: " ") let rhsArray = rhsName.lowercased().components(separatedBy: " ") if lhsArray.count == rhsArray.count { for lhsComponent in lhsArray { if !rhsArray.contains(lhsComponent){ return false } } for rhsComponent in rhsArray { if !lhsArray.contains(rhsComponent) { return false } } }else{ return false } return true; }else{ return false } }else{ return false } }
c65479577bcb0110f56c6b24eefae8b8
26.881356
135
0.487538
false
false
false
false
novi/proconapp
refs/heads/master
ProconApp/ProconManager/GameResultManageViewController.swift
bsd-3-clause
1
// // GameResultManageViewController.swift // ProconApp // // Created by ito on 2015/09/13. // Copyright (c) 2015年 Procon. All rights reserved. // import UIKit import AVFoundation import APIKit import ProconBase class GameResultManageViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var session: AVCaptureSession = AVCaptureSession() var previewLayer: CALayer = CALayer() var capturedStrings: Set<String> = Set() var isSending: Bool = false @IBOutlet weak var previewView: UIView! @IBOutlet weak var startStopButton: UIButton! override func viewDidLoad() { super.viewDidLoad() let layer = AVCaptureVideoPreviewLayer(session: session) layer.videoGravity = AVLayerVideoGravityResizeAspect; layer.frame = previewView.bounds self.previewLayer = layer self.previewView.layer.addSublayer(layer) reloadButtonState() /*let data = NSData(contentsOfFile: "") let str = NSString(data: data!, encoding: NSUTF8StringEncoding) self.processQRCode(str as! String) */ println(Constants.ManageAPIBaseURL) #if HOST_DEV self.navigationItem.title = "Dev" #elseif HOST_RELEASE self.navigationItem.title = "Prod" #endif #if HOST_RELEASE let alert = UIAlertController(title: "本番環境", message: Constants.ManageAPIBaseURL, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) #endif } func reloadButtonState() { if session.running { startStopButton.setTitle("読み取り停止", forState: .Normal) } else { startStopButton.setTitle("読み取り開始", forState: .Normal) } } @IBAction func startOrStopTapped(sender: AnyObject) { if session.running { session.stopRunning() for input in session.inputs { session.removeInput(input as! AVCaptureInput) } for output in session.outputs { session.removeOutput(output as! AVCaptureOutput) } } else { let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo).filter { if let device = $0 as? AVCaptureDevice { return device.position == .Back } return false } if devices.count == 0 { let alert = UIAlertController(title: "no device", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } if let device = devices.first as? AVCaptureDevice { let input = AVCaptureDeviceInput(device: device, error: nil) self.session.addInput(input) let output = AVCaptureMetadataOutput() self.session.addOutput(output) Logger.debug("\(output.availableMetadataObjectTypes)") if output.availableMetadataObjectTypes.count > 0 { output.metadataObjectTypes = [AVMetadataObjectTypeQRCode] output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) } else { let alert = UIAlertController(title: "no detector", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } session.startRunning() } self.reloadButtonState() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() previewLayer.frame = previewView.bounds } // MARK: Capture Delegate func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { for obj in metadataObjects { if let obj = obj as? AVMetadataMachineReadableCodeObject { if obj.type == AVMetadataObjectTypeQRCode, let str = obj.stringValue { // QR Code detected // base64 decode and decompress let compressed = NSData(base64EncodedString: str, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) if let data = compressed?.pr_decompress(), let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { self.processQRCode(str) } } } } } func processQRCode(str: String) { if capturedStrings.contains(str) { return // already captured } if isSending { return } capturedStrings.insert(str) let alert = UIAlertController(title: "送信しますか?", message: str, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "キャンセル", style: .Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "送信", style: .Default, handler: { _ in self.sendQRCode(str) })) self.presentViewController(alert, animated: true, completion: nil) let delay = 3.0 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { self.capturedStrings.remove(str) }) } func showError(str: String) { let alert = UIAlertController(title: "パースエラー", message: str, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } func sendQRCode(str: String) { let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) if data == nil { // TODO: guard showError("data conversion error") return } var error: NSError? = nil let obj = NSJSONSerialization.JSONObjectWithData(data!, options: .allZeros, error: &error) as? [String: AnyObject] if obj == nil || error != nil { showError("\(error ?? String())") return } let req = ManageAPI.Endpoint.UpdateGameResult(result: obj!) self.isSending = true let alert = UIAlertController(title: "送信中...", message: nil, preferredStyle: .Alert) self.presentViewController(alert, animated: true, completion: nil) AppAPI.sendRequest(req) { res in self.isSending = false alert.dismissViewControllerAnimated(true) { switch res { case .Success(_): break case .Failure(let box): // TODO, error Logger.error("\(box.value)") self.showError("\(box.value)") } } } } }
f2f59496e0c45f03429cc9de64fad73a
35.269231
162
0.574761
false
false
false
false
apple/swift-syntax
refs/heads/main
Sources/SwiftParser/Patterns.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// @_spi(RawSyntax) import SwiftSyntax extension Parser { /// Parse a pattern. /// /// Grammar /// ======= /// /// pattern → wildcard-pattern type-annotation? /// pattern → identifier-pattern type-annotation? /// pattern → value-binding-pattern /// pattern → tuple-pattern type-annotation? /// pattern → enum-case-pattern /// pattern → optional-pattern /// pattern → type-casting-pattern /// pattern → expression-pattern /// /// wildcard-pattern → _ /// /// identifier-pattern → identifier /// /// value-binding-pattern → 'var' pattern | 'let' pattern /// /// tuple-pattern → ( tuple-pattern-element-list opt ) /// /// enum-case-pattern → type-identifier? '.' enum-case-name tuple-pattern? /// /// optional-pattern → identifier-pattern '?' /// /// type-casting-pattern → is-pattern | as-pattern /// is-pattern → 'is' type /// as-pattern → pattern 'as' type /// /// expression-pattern → expression @_spi(RawSyntax) public mutating func parsePattern() -> RawPatternSyntax { enum ExpectedTokens: RawTokenKindSubset { case leftParen case wildcardKeyword case identifier case dollarIdentifier // For recovery case letKeyword case varKeyword init?(lexeme: Lexer.Lexeme) { switch lexeme.tokenKind { case .leftParen: self = .leftParen case .wildcardKeyword: self = .wildcardKeyword case .identifier: self = .identifier case .dollarIdentifier: self = .dollarIdentifier case .letKeyword: self = .letKeyword case .varKeyword: self = .varKeyword default: return nil } } var rawTokenKind: RawTokenKind { switch self { case .leftParen: return .leftParen case .wildcardKeyword: return .wildcardKeyword case .identifier: return .identifier case .dollarIdentifier: return .dollarIdentifier case .letKeyword: return .letKeyword case .varKeyword: return .varKeyword } } } switch self.at(anyIn: ExpectedTokens.self) { case (.leftParen, let handle)?: let lparen = self.eat(handle) let elements = self.parsePatternTupleElements() let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawPatternSyntax(RawTuplePatternSyntax( leftParen: lparen, elements: elements, unexpectedBeforeRParen, rightParen: rparen, arena: self.arena )) case (.wildcardKeyword, let handle)?: let wildcard = self.eat(handle) return RawPatternSyntax(RawWildcardPatternSyntax( wildcard: wildcard, typeAnnotation: nil, arena: self.arena )) case (.identifier, let handle)?: let identifier = self.eat(handle) return RawPatternSyntax(RawIdentifierPatternSyntax( identifier: identifier, arena: self.arena )) case (.dollarIdentifier, let handle)?: let dollarIdent = self.eat(handle) let unexpectedBeforeIdentifier = RawUnexpectedNodesSyntax(elements: [RawSyntax(dollarIdent)], arena: self.arena) return RawPatternSyntax(RawIdentifierPatternSyntax( unexpectedBeforeIdentifier, identifier: missingToken(.identifier), arena: self.arena )) case (.letKeyword, let handle)?, (.varKeyword, let handle)?: let letOrVar = self.eat(handle) let value = self.parsePattern() return RawPatternSyntax(RawValueBindingPatternSyntax( letOrVarKeyword: letOrVar, valuePattern: value, arena: self.arena )) case nil: if self.currentToken.tokenKind.isKeyword, !self.currentToken.isAtStartOfLine { // Recover if a keyword was used instead of an identifier let keyword = self.consumeAnyToken() return RawPatternSyntax(RawIdentifierPatternSyntax( RawUnexpectedNodesSyntax([keyword], arena: self.arena), identifier: missingToken(.identifier, text: nil), arena: self.arena )) } else { return RawPatternSyntax(RawMissingPatternSyntax(arena: self.arena)) } } } /// Parse a typed pattern. /// /// Grammar /// ======= /// /// typed-pattern → pattern ':' attributes? inout? type mutating func parseTypedPattern(allowRecoveryFromMissingColon: Bool = true) -> (RawPatternSyntax, RawTypeAnnotationSyntax?) { let pattern = self.parsePattern() // Now parse an optional type annotation. let colon = self.consume(if: .colon) var lookahead = self.lookahead() var type: RawTypeAnnotationSyntax? if let colon = colon { let result = self.parseResultType() type = RawTypeAnnotationSyntax( colon: colon, type: result, arena: self.arena ) } else if allowRecoveryFromMissingColon && !self.currentToken.isAtStartOfLine && lookahead.canParseType() { // Recovery if the user forgot to add ':' let result = self.parseResultType() type = RawTypeAnnotationSyntax( colon: self.missingToken(.colon, text: nil), type: result, arena: self.arena ) } return (pattern, type) } /// Parse the elements of a tuple pattern. /// /// Grammar /// ======= /// /// tuple-pattern-element-list → tuple-pattern-element | tuple-pattern-element ',' tuple-pattern-element-list /// tuple-pattern-element → pattern | identifier ':' pattern mutating func parsePatternTupleElements() -> RawTuplePatternElementListSyntax { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { return RawTuplePatternElementListSyntax(elements: [ RawTuplePatternElementSyntax( remainingTokens, labelName: nil, labelColon: nil, pattern: RawPatternSyntax(RawMissingPatternSyntax(arena: self.arena)), trailingComma: nil, arena: self.arena ) ], arena: self.arena) } var elements = [RawTuplePatternElementSyntax]() do { var keepGoing = true var loopProgress = LoopProgressCondition() while !self.at(any: [.eof, .rightParen]) && keepGoing && loopProgress.evaluate(currentToken) { // If the tuple element has a label, parse it. let labelAndColon = self.consume(if: .identifier, followedBy: .colon) let (label, colon) = (labelAndColon?.0, labelAndColon?.1) let pattern = self.parsePattern() let trailingComma = self.consume(if: .comma) keepGoing = trailingComma != nil elements.append(RawTuplePatternElementSyntax( labelName: label, labelColon: colon, pattern: pattern, trailingComma: trailingComma, arena: self.arena)) } } return RawTuplePatternElementListSyntax(elements: elements, arena: self.arena) } } extension Parser { /// Parse a pattern that appears immediately under syntax for conditionals like /// for-in loops and guard clauses. mutating func parseMatchingPattern(context: PatternContext) -> RawPatternSyntax { // Parse productions that can only be patterns. switch self.at(anyIn: MatchingPatternStart.self) { case (.varKeyword, let handle)?, (.letKeyword, let handle)?: let letOrVar = self.eat(handle) let value = self.parseMatchingPattern(context: .letOrVar) return RawPatternSyntax(RawValueBindingPatternSyntax( letOrVarKeyword: letOrVar, valuePattern: value, arena: self.arena)) case (.isKeyword, let handle)?: let isKeyword = self.eat(handle) let type = self.parseType() return RawPatternSyntax(RawIsTypePatternSyntax( isKeyword: isKeyword, type: type, arena: self.arena )) case nil: // matching-pattern ::= expr // Fall back to expression parsing for ambiguous forms. Name lookup will // disambiguate. let patternSyntax = self.parseSequenceExpression(.basic, pattern: context) if let pat = patternSyntax.as(RawUnresolvedPatternExprSyntax.self) { // The most common case here is to parse something that was a lexically // obvious pattern, which will come back wrapped in an immediate // RawUnresolvedPatternExprSyntax. // // FIXME: This is pretty gross. Let's find a way to disambiguate let // binding patterns much earlier. return RawPatternSyntax(pat.pattern) } let expr = RawExprSyntax(patternSyntax) return RawPatternSyntax(RawExpressionPatternSyntax(expression: expr, arena: self.arena)) } } } // MARK: Lookahead extension Parser.Lookahead { /// pattern ::= identifier /// pattern ::= '_' /// pattern ::= pattern-tuple /// pattern ::= 'var' pattern /// pattern ::= 'let' pattern mutating func canParsePattern() -> Bool { enum PatternStartTokens: RawTokenKindSubset { case identifier case wildcardKeyword case letKeyword case varKeyword case leftParen init?(lexeme: Lexer.Lexeme) { switch lexeme.tokenKind { case .identifier: self = .identifier case .wildcardKeyword: self = .wildcardKeyword case .letKeyword: self = .letKeyword case .varKeyword: self = .varKeyword case .leftParen: self = .leftParen default: return nil } } var rawTokenKind: RawTokenKind { switch self { case .identifier: return .identifier case .wildcardKeyword: return .wildcardKeyword case .letKeyword: return .letKeyword case .varKeyword: return .varKeyword case .leftParen: return .leftParen } } } switch self.at(anyIn: PatternStartTokens.self) { case (.identifier, let handle)?, (.wildcardKeyword, let handle)?: self.eat(handle) return true case (.letKeyword, let handle)?, (.varKeyword, let handle)?: self.eat(handle) return self.canParsePattern() case (.leftParen, _)?: return self.canParsePatternTuple() case nil: return false } } private mutating func canParsePatternTuple() -> Bool { guard self.consume(if: .leftParen) != nil else { return false } if !self.at(.rightParen) { var loopProgress = LoopProgressCondition() repeat { guard self.canParsePattern() else { return false } } while self.consume(if: .comma) != nil && loopProgress.evaluate(currentToken) } return self.consume(if: .rightParen) != nil } /// typed-pattern ::= pattern (':' type)? mutating func canParseTypedPattern() -> Bool { guard self.canParsePattern() else { return false } if self.consume(if: .colon) != nil { return self.canParseType() } return true } /// Determine whether we are at the start of a parameter name when /// parsing a parameter. /// If `allowMisplacedSpecifierRecovery` is `true`, then this will skip over any type /// specifiers before checking whether this lookahead starts a parameter name. mutating func startsParameterName(isClosure: Bool, allowMisplacedSpecifierRecovery: Bool) -> Bool { if allowMisplacedSpecifierRecovery { while self.consume(ifAnyIn: TypeSpecifier.self) != nil {} } // To have a parameter name here, we need a name. guard self.currentToken.canBeArgumentLabel(allowDollarIdentifier: true) else { return false } // If the next token is ':', this is a name. let nextTok = self.peek() if nextTok.tokenKind == .colon { return true } // If the next token can be an argument label, we might have a name. if nextTok.canBeArgumentLabel(allowDollarIdentifier: true) { // If the first name wasn't "isolated", we're done. if !self.atContextualKeyword("isolated") && !self.atContextualKeyword("some") && !self.atContextualKeyword("any") { return true } // "isolated" can be an argument label, but it's also a contextual keyword, // so look ahead one more token (two total) see if we have a ':' that would // indicate that this is an argument label. do { if self.at(.colon) { return true // isolated : } self.consumeAnyToken() return self.currentToken.canBeArgumentLabel(allowDollarIdentifier: true) && self.peek().tokenKind == .colon } } if nextTok.isOptionalToken || nextTok.isImplicitlyUnwrappedOptionalToken { return false } // The identifier could be a name or it could be a type. In a closure, we // assume it's a name, because the type can be inferred. Elsewhere, we // assume it's a type. return isClosure } }
eb39e773d9a6f6a4fe3c6d12cf89c1d7
33.197436
127
0.63545
false
false
false
false
apple/swift-lldb
refs/heads/stable
packages/Python/lldbsuite/test/lang/swift/protocol_optional/main.swift
apache-2.0
2
protocol Key { associatedtype Value } struct Key1: Key { typealias Value = Int? } struct KeyTransformer<K1: Key> { let input: K1.Value func printOutput() { let patatino = input print(patatino) //%self.expect('frame variable -d run-target -- patatino', substrs=['(Int?) patatino = 5']) //%self.expect('expr -d run-target -- patatino', substrs=['(Int?) $R0 = 5']) } } var xformer: KeyTransformer<Key1> = KeyTransformer(input: 5) xformer.printOutput()
35e80f1b30dff36890d8327f7c59d7be
24.65
115
0.614035
false
false
false
false
GitHubOfJW/JavenKit
refs/heads/master
JavenKit/JWCalendarViewController/View/JWCalendarView.swift
mit
1
// // JWCalendarView.swift // KitDemo // // Created by 朱建伟 on 2017/1/3. // Copyright © 2017年 zhujianwei. All rights reserved. // import UIKit //协议 public protocol JWCalendarViewDelegate: NSObjectProtocol { //天数 func numberOfDay(in calendarView:JWCalendarView) -> Int //缩进 func placeholders(in calendarView:JWCalendarView) -> Int; //单天的状态 func dayState(in calendarView:JWCalendarView,dayIndex:Int) -> JWCalendarView.DayItemType; //间隙 func rowPadding(in calendarView:JWCalendarView)-> CGFloat; //间隙 func columnPadding(in calendarView:JWCalendarView)-> CGFloat; } //展示日期的View public class JWCalendarView: UIView { //类型 public enum DayItemType:Int { case normal//普通 case selected//选中 case disabled//禁用 } weak var delegate:JWCalendarViewDelegate? //刷新 func reloadData() { self.setNeedsDisplay() } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.white } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //绘制 override public func draw(_ rect: CGRect) { super.draw(rect) if let delegate = self.delegate{ //天数 let numberOfDays:Int = delegate.numberOfDay(in: self) if numberOfDays <= 0{ return } //缩进 let placeholders:Int = delegate.placeholders(in: self) //总行数 let totlaRows:Int = (numberOfDays+placeholders + 7 - 1)/7 //行间距 let rowPadding:CGFloat = delegate.rowPadding(in: self) //列间距 let columnPadding:CGFloat = delegate.columnPadding(in: self) //按钮宽度 let itemW:CGFloat = (self.bounds.width-(8*columnPadding))/7 //高度 let itemH:CGFloat = (self.bounds.height-(CGFloat(totlaRows+1)*rowPadding))/CGFloat(totlaRows) //遍历刷新 for index in 0...numberOfDays{ //计算位置 let x:CGFloat = CGFloat((index + placeholders) % 7)*(itemW+columnPadding)+columnPadding let y:CGFloat = CGFloat((index + placeholders) / 7)*(itemH+rowPadding)+rowPadding let rect:CGRect = CGRect(x: x, y: y, width: itemW, height: itemH) let state:DayItemType = delegate.dayState(in: self, dayIndex: index) //上下文 let context:CGContext = UIGraphicsGetCurrentContext()! let fontSize:CGFloat = itemH * 0.5 let titleStr:NSString = NSString(string:String(format:"%zd",index+1)) let titleSize:CGSize = titleStr.boundingRect(with: CGSize(width:itemW,height:itemH), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize)], context: nil).size let offSetX:CGFloat = (itemW - titleSize.width)/2 let offSetY:CGFloat = (itemH - titleSize.height)/2 //绘制背景 switch state { case .normal: //普通 context.setFillColor(dayNormalColor.cgColor) context.addEllipse(in: rect) context.fillPath() //文字 titleStr.draw(at: CGPoint(x:rect.minX+offSetX,y: rect.minY + offSetY) , withAttributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize),NSForegroundColorAttributeName:dayNormalTextColor]) break case .selected: //选中 context.setFillColor(daySelectedColor.cgColor) context.addEllipse(in: rect) context.fillPath() //文字 titleStr.draw(at: CGPoint(x:rect.minX+offSetX,y: rect.minY + offSetY) , withAttributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize),NSForegroundColorAttributeName:daySelectedTextColor]) break case .disabled: //禁用 context.setFillColor(dayDisabledColor.cgColor) context.addEllipse(in: rect) context.fillPath() //文字 titleStr.draw(at: CGPoint(x:rect.minX+offSetX,y: rect.minY + offSetY) , withAttributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize),NSForegroundColorAttributeName:dayDisabledTextColor]) break } } } } }
050110fe82bada0769fc6049211f3ae4
30.378049
246
0.520793
false
false
false
false
chanhx/Octogit
refs/heads/master
iGithub/ViewControllers/List/RepositoryTableViewController.swift
gpl-3.0
2
// // RepositoryTableViewController.swift // iGithub // // Created by Chan Hocheung on 7/31/16. // Copyright © 2016 Hocheung. All rights reserved. // import UIKit class RepositoryTableViewController: BaseTableViewController { var viewModel: RepositoryTableViewModel! { didSet { viewModel.dataSource.asDriver() .skip(1) .do(onNext: { [unowned self] _ in self.tableView.refreshHeader?.endRefreshing() self.viewModel.hasNextPage ? self.tableView.refreshFooter?.endRefreshing() : self.tableView.refreshFooter?.endRefreshingWithNoMoreData() }) .do(onNext: { [unowned self] in if $0.count <= 0 { self.show(statusType: .empty) } else { self.hide(statusType: .empty) } }) .drive(tableView.rx.items(cellIdentifier: "RepositoryCell", cellType: RepositoryCell.self)) { row, element, cell in cell.shouldDisplayFullName = self.viewModel.shouldDisplayFullName cell.configure(withRepository: element) } .disposed(by: viewModel.disposeBag) viewModel.error.asDriver() .filter { $0 != nil } .drive(onNext: { [unowned self] in self.tableView.refreshHeader?.endRefreshing() self.tableView.refreshFooter?.endRefreshing() MessageManager.show(error: $0!) }) .disposed(by: viewModel.disposeBag) } } override func viewDidLoad() { super.viewDidLoad() tableView.register(RepositoryCell.self, forCellReuseIdentifier: "RepositoryCell") tableView.refreshHeader = RefreshHeader(target: viewModel, selector: #selector(viewModel.refresh)) tableView.refreshFooter = RefreshFooter(target: viewModel, selector: #selector(viewModel.fetchData)) tableView.refreshHeader?.beginRefreshing() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let repoVC = RepositoryViewController.instantiateFromStoryboard() repoVC.viewModel = viewModel.repoViewModel(forRow: indexPath.row) self.navigationController?.pushViewController(repoVC, animated: true) } }
10b2490c38fd31f284812b8abeff9ccb
37.044118
131
0.565906
false
false
false
false
ambas/Impala
refs/heads/master
Pod/Classes/CellProtocol.swift
mit
1
// // CellProtocol.swift // Impala // // Created by Ambas Chobsanti on 1/30/16. // Copyright © 2016 AM. All rights reserved. // import UIKit protocol ReuseableView { static var defaultReuseIdentifier: String { get } } extension ReuseableView where Self: UIView { static var defaultReuseIdentifier: String { return NSStringFromClass(self) } } extension UICollectionViewCell: ReuseableView { } extension UITableViewCell: ReuseableView { } protocol NibLoadableView: class { static var nibName:String { get } } extension NibLoadableView where Self: UIView { static var nibName: String { return NSStringFromClass(self).componentsSeparatedByString(".").last! } } extension UICollectionView { func register<T: UICollectionViewCell where T: ReuseableView>(_: T.Type){ registerClass(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } func register<T: UICollectionViewCell where T: ReuseableView, T: NibLoadableView>(_: T.Type) { let bundle = NSBundle(forClass: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) registerNib(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } func dequeueReusableCell<T: UICollectionViewCell where T: ReuseableView>(indexPath: NSIndexPath) -> T { guard let cell = dequeueReusableCellWithReuseIdentifier(T.defaultReuseIdentifier, forIndexPath: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } } extension UITableView { func register<T: UITableViewCell where T: ReuseableView>(_: T.Type) { registerClass(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier) } func register<T: UITableViewCell where T: ReuseableView, T: NibLoadableView>(_: T.Type) { let bundle = NSBundle(forClass: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) registerNib(nib, forCellReuseIdentifier: T.defaultReuseIdentifier) } func dequeueReusableCell<T: UITableViewCell where T: ReuseableView>(indexPath: NSIndexPath) -> T { guard let cell = dequeueReusableCellWithIdentifier(T.defaultReuseIdentifier) as? T else { fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } }
a8256383e0a01eeaff5ba1875c0dffc2
30.723684
127
0.69834
false
false
false
false
danger/danger-swift
refs/heads/master
Sources/Danger/DangerResults.swift
mit
1
import Foundation // MARK: - Violation /// The result of a warn, message, or fail. public struct Violation: Encodable { let message: String let file: String? let line: Int? init(message: String, file: String? = nil, line: Int? = nil) { self.message = message self.file = file self.line = line } } /// Meta information for showing in the text info public struct Meta: Encodable { let runtimeName = "Danger Swift" let runtimeHref = "https://danger.systems/swift" } // MARK: - Results /// The representation of what running a Dangerfile generates. struct DangerResults: Encodable { /// Failed messages. var fails = [Violation]() /// Messages for info. var warnings = [Violation]() /// A set of messages to show inline. var messages = [Violation]() /// Markdown messages to attach at the bottom of the comment. var markdowns = [Violation]() /// Information to pass back to Danger JS about the runtime let meta = Meta() }
0cd1ce294b93a6d8649dcf9df03aed9b
23.261905
66
0.647694
false
false
false
false
chrisamanse/UsbongKit
refs/heads/master
UsbongKit/LanguagesTableViewController.swift
apache-2.0
2
// // LanguagesTableViewController.swift // UsbongKit // // Created by Chris Amanse on 12/31/15. // Copyright © 2015 Usbong Social Systems, Inc. All rights reserved. // import UIKit class LanguagesTableViewController: UITableViewController { var store: IAPHelper = IAPHelper(bundles: []) { didSet { if isViewLoaded { tableView.reloadData() } } } var languages: [String] = [] { didSet { if isViewLoaded { tableView.reloadData() } } } var selectedLanguage = "" var didSelectLanguageCompletion: ((_ selectedLanguage: String) -> Void)? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismiss(_:))) // Subscribe to a notification that fires when a product is purchased. NotificationCenter.default.addObserver(self, selector: #selector(productPurchased(_:)), name: NSNotification.Name(rawValue: IAPHelperProductPurchasedNotification), object: nil) } func dismiss(_ sender: AnyObject?) { self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { NotificationCenter.default.removeObserver(self) } func productPurchased(_ sender: AnyObject?) { tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return languages.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "defaultCell", for: indexPath) let language = languages[indexPath.row] cell.textLabel?.text = language // If purchased, set text color to black if store.isLanguagePurchased(language) { cell.textLabel?.textColor = .black } else { cell.textLabel?.textColor = .lightGray } if language == selectedLanguage { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let targetLanguage = languages[indexPath.row] // Show purchase screen if unpurchased guard store.isLanguagePurchased(targetLanguage) else { print("Language is for purchase!") performSegue(withIdentifier: "showProducts", sender: tableView) return } // Pass through if not unpurchased // guard !IAPProducts.isUnpurchasedLanguage(targetLanguage) else { // // Unavailable // print("Language is for purchase!") // // performSegueWithIdentifier("showProducts", sender: tableView) // // return // } selectedLanguage = targetLanguage tableView.reloadData() self.dismiss(animated: true) { self.didSelectLanguageCompletion?(targetLanguage) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier ?? "" { case "showProducts": let destinationViewController = segue.destination as! PurchasesTableViewController destinationViewController.store = store default: break } } }
7c8b62363efa1c39e5a356baa98f2634
29.769231
184
0.59825
false
false
false
false
PGSSoft/AutoMate
refs/heads/master
AutoMate/Models/ServiceRequestAlerts.swift
mit
1
// swiftlint:disable identifier_name type_body_length trailing_comma file_length line_length /// Represents possible system service messages and label values on buttons. import XCTest #if os(iOS) extension SystemAlertAllow { /// Represents all possible "allow" buttons in system service messages. public static var allow: [String] { return readMessages(from: "SystemAlertAllow") } } extension SystemAlertDeny { /// Represents all possible "deny" buttons in system service messages. public static var deny: [String] { return readMessages(from: "SystemAlertDeny") } } /// Represents `AddressBookAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = AddressBookAlert(element: alert) else { /// XCTFail("Cannot create AddressBookAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct AddressBookAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `AddressBookAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `AddressBookAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `BluetoothPeripheralAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = BluetoothPeripheralAlert(element: alert) else { /// XCTFail("Cannot create BluetoothPeripheralAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct BluetoothPeripheralAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `BluetoothPeripheralAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `BluetoothPeripheralAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `CalendarAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = CalendarAlert(element: alert) else { /// XCTFail("Cannot create CalendarAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct CalendarAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `CalendarAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `CalendarAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `CallsAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = CallsAlert(element: alert) else { /// XCTFail("Cannot create CallsAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct CallsAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `CallsAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `CallsAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `CameraAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = CameraAlert(element: alert) else { /// XCTFail("Cannot create CameraAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct CameraAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `CameraAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `CameraAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `MediaLibraryAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = MediaLibraryAlert(element: alert) else { /// XCTFail("Cannot create MediaLibraryAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct MediaLibraryAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `MediaLibraryAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `MediaLibraryAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `MicrophoneAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = MicrophoneAlert(element: alert) else { /// XCTFail("Cannot create MicrophoneAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct MicrophoneAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `MicrophoneAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `MicrophoneAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `MotionAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = MotionAlert(element: alert) else { /// XCTFail("Cannot create MotionAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct MotionAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `MotionAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `MotionAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `PhotosAddAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = PhotosAddAlert(element: alert) else { /// XCTFail("Cannot create PhotosAddAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct PhotosAddAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `PhotosAddAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `PhotosAddAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `PhotosAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = PhotosAlert(element: alert) else { /// XCTFail("Cannot create PhotosAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct PhotosAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `PhotosAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `PhotosAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `RemindersAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = RemindersAlert(element: alert) else { /// XCTFail("Cannot create RemindersAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct RemindersAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `RemindersAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `RemindersAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `SiriAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = SiriAlert(element: alert) else { /// XCTFail("Cannot create SiriAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct SiriAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `SiriAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `SiriAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `SpeechRecognitionAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = SpeechRecognitionAlert(element: alert) else { /// XCTFail("Cannot create SpeechRecognitionAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct SpeechRecognitionAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `SpeechRecognitionAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `SpeechRecognitionAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `WillowAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = WillowAlert(element: alert) else { /// XCTFail("Cannot create WillowAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct WillowAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `WillowAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `WillowAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } #endif
ca64fb0131d9a79df6338d370e449cf4
30.006135
130
0.662693
false
false
false
false