repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
damonthecricket/my-utils
UnitTests/Foundation/Extensions/ArrayExtensionsTest.swift
1
3104
// // ArrayExtensionsClass.swift // MYUtils // // Created by Damon Cricket on 30.05.17. // Copyright © 2017 Trenlab. All rights reserved. // import XCTest class ArrayExtensionsTest: XCTestCase { // MARK: - Operators func testSum() { for mock in getSumData() { let firstResult = mock.first + mock.second var secondResult = mock.first secondResult += mock.second XCTAssertEqual(firstResult, mock.result) XCTAssertEqual(secondResult, mock.result) } } // MARK: - Enumerate func testEnum() { for mock in getEnumData() { var lastIDX: Int = 0 mock.enumerate {idx, value in XCTAssertEqual(value, mock[idx]) lastIDX = idx } XCTAssertTrue(lastIDX == (mock.count - 1)) } } func testMake() { for (source, multiplier, result) in getMakeData() { let rez = source.make {_, value in return value * multiplier } XCTAssertEqual(rez, result) } } // MARK: - Remove func testRemove() { for mock in getRemoveData() { var source = mock.source for removeElement in mock.remove { source.remove(element: removeElement) } XCTAssertEqual(source, mock.result) } } // MARK: - Data func getSumData() -> [(first: [Int], second: [Int], result: [Int])] { return [ (first: [-3, -2], second: [-1, 0], result: [-3, -2, -1, 0]), (first: [1, 2], second: [3, 4], result: [1, 2, 3, 4]), (first: [1, 2], second: [3, 4], result: [1, 2, 3, 4]), (first: [5, 6], second: [7, 8], result: [5, 6, 7, 8]) ] } func getEnumData() -> [[String]] { return [ ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["10", "11", "12", "13", "14", "15", "16", "17", "18", "19"], ["20", "21", "22", "23", "24", "25", "26", "27", "28", "29"], ["30", "31", "32", "33", "34", "35", "36", "37", "38", "39"] ] } func getMakeData() -> [(source: [Int], multiplier: Int, result: [Int])] { return [ (source: [1, 2, 3], multiplier: 2, result: [2, 4, 6]), (source: [3, 2, 1], multiplier: 2, result: [6, 4, 2]), (source: [10, 10, 10], multiplier: 4, result: [40, 40, 40]), (source: [1, 1, 1], multiplier: 4, result: [4, 4, 4]), (source: [1, 1, 1], multiplier: 1, result: [1, 1, 1]) ] } func getRemoveData() -> [(source: [Int], remove: [Int], result: [Int])] { return [ (source: [1, 2, 3], remove: [1, 2], result: [3]), (source: [3, 4, 5], remove: [6], result: [3, 4, 5]), (source: [3, 4, 5, 6], remove: [6], result: [3, 4, 5]), (source: [3, 4, 5, 6], remove: [3, 4, 5, 6], result: []), ] } }
mit
db1a910fbc3f6f23dba8d0db68f641a0
29.722772
77
0.43893
3.514156
false
true
false
false
fgengine/quickly
Quickly/ViewControllers/Form/QFormViewControllerMultiTextField.swift
1
9965
// // Quickly // open class QFormViewControllerMultiTextField : QFormViewControllerField { public private(set) var inputView: QDisplayView! public var inputEdgeInsets: UIEdgeInsets { set(inputEdgeInsets) { self.set(inputEdgeInsets: inputEdgeInsets, animated: false, completion: nil) } get { return self._inputEdgeInsets } } public private(set) var inputTitleView: QLabel! public private(set) var inputFieldView: QMultiTextField! public var inputFieldSpacing: CGFloat { set(inputFieldSpacing) { self.set(inputFieldSpacing: inputFieldSpacing, animated: false, completion: nil) } get { return self._inputFieldSpacing } } public private(set) var hintView: QLabel! public var hintEdgeInsets: UIEdgeInsets { set(hintEdgeInsets) { self.set(hintEdgeInsets: hintEdgeInsets, animated: false, completion: nil) } get { return self._hintEdgeInsets } } public private(set) var errorView: QLabel! public var errorEdgeInsets: UIEdgeInsets { set(errorEdgeInsets) { self.set(errorEdgeInsets: errorEdgeInsets, animated: false, completion: nil) } get { return self._errorEdgeInsets } } public var errorTextStyle: IQTextStyle public var text: String { set(value) { self.inputFieldView.unformatText = value } get { return self.inputFieldView.unformatText } } open override var isValid: Bool { get { self.loadViewIfNeeded() return self.inputFieldView.isValid } } private var _inputEdgeInsets: UIEdgeInsets private var _inputFieldSpacing: CGFloat private var _hintEdgeInsets: UIEdgeInsets private var _errorEdgeInsets: UIEdgeInsets private var _errorShowed: Bool private var _constraints: [NSLayoutConstraint] = [] { willSet { self.view.removeConstraints(self._constraints) } didSet { self.view.addConstraints(self._constraints) } } private var _inputConstraints: [NSLayoutConstraint] = [] { willSet { self.inputView.removeConstraints(self._inputConstraints) } didSet { self.inputView.addConstraints(self._inputConstraints) } } private var _inputFieldHeightConstraint: NSLayoutConstraint? { willSet { guard let constraint = self._inputFieldHeightConstraint else { return } self.inputFieldView.removeConstraint(constraint) } didSet { guard let constraint = self._inputFieldHeightConstraint else { return } self.inputFieldView.addConstraint(constraint) } } public init(errorTextStyle: IQTextStyle) { self.errorTextStyle = errorTextStyle self._inputEdgeInsets = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12) self._inputFieldSpacing = 8 self._hintEdgeInsets = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12) self._errorEdgeInsets = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12) self._errorShowed = false } open override func didLoad() { super.didLoad() self.inputView = QDisplayView(frame: CGRect.zero) self.inputView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.inputView) self.inputTitleView = QLabel(frame: CGRect.zero) self.inputTitleView.translatesAutoresizingMaskIntoConstraints = false self.inputView.addSubview(self.inputTitleView) self.inputFieldView = QMultiTextField(frame: CGRect.zero) self.inputFieldView.translatesAutoresizingMaskIntoConstraints = false self.inputFieldView.onEditing = { [weak self] textField in self?._editing() } self.inputFieldView.onChangedHeight = { [weak self] textField in self?._changedHeight() } self.inputView.addSubview(self.inputFieldView) self.hintView = QLabel(frame: CGRect.zero) self.hintView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.hintView) self.errorView = QLabel(frame: CGRect.zero) self.errorView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.errorView) self._relayout() } open override func beginEditing() { self.inputFieldView.beginEditing() } open func editing(text: String) { } public func set(inputEdgeInsets: UIEdgeInsets, animated: Bool, completion: (() -> Swift.Void)?) { if self._inputEdgeInsets != inputEdgeInsets { self._inputEdgeInsets = inputEdgeInsets self._relayout(animated: animated, completion: completion) } } public func set(inputFieldSpacing: CGFloat, animated: Bool, completion: (() -> Swift.Void)?) { if self._inputFieldSpacing != inputFieldSpacing { self._inputFieldSpacing = inputFieldSpacing self._relayout(animated: animated, completion: completion) } } public func set(hintEdgeInsets: UIEdgeInsets, animated: Bool, completion: (() -> Swift.Void)?) { if self._hintEdgeInsets != hintEdgeInsets { self._hintEdgeInsets = hintEdgeInsets self._relayout(animated: animated, completion: completion) } } public func set(errorEdgeInsets: UIEdgeInsets, animated: Bool, completion: (() -> Swift.Void)?) { if self._errorEdgeInsets != errorEdgeInsets { self._errorEdgeInsets = errorEdgeInsets self._relayout(animated: animated, completion: completion) } } } // MARK: Private private extension QFormViewControllerMultiTextField { func _relayout(animated: Bool, completion: (() -> Swift.Void)?) { self._relayout() if animated == true { UIView.animate(withDuration: 0.2, animations: { self.view.layoutIfNeeded() self.hintView.alpha = self._errorShowed == true ? 0 : 1 self.errorView.alpha = self._errorShowed == true ? 1 : 0 }, completion: { _ in completion?() }) } else { completion?() } } func _relayout() { if self._errorShowed == true { self._constraints = [ self.inputView.topLayout == self.view.topLayout, self.inputView.leadingLayout == self.view.leadingLayout, self.inputView.trailingLayout == self.view.trailingLayout, self.errorView.topLayout == self.inputView.bottomLayout.offset(self._errorEdgeInsets.top), self.errorView.leadingLayout == self.view.leadingLayout.offset(self._errorEdgeInsets.left), self.errorView.trailingLayout == self.view.trailingLayout.offset(-self._errorEdgeInsets.right), self.errorView.bottomLayout <= self.view.bottomLayout.offset(-self._errorEdgeInsets.bottom), self.hintView.topLayout == self.errorView.bottomLayout.offset(self._hintEdgeInsets.top), self.hintView.leadingLayout == self.view.leadingLayout.offset(self._hintEdgeInsets.left), self.hintView.trailingLayout == self.view.trailingLayout.offset(-self._hintEdgeInsets.right) ] } else { self._constraints = [ self.inputView.topLayout == self.view.topLayout, self.inputView.leadingLayout == self.view.leadingLayout, self.inputView.trailingLayout == self.view.trailingLayout, self.hintView.topLayout == self.inputView.bottomLayout.offset(self._hintEdgeInsets.top), self.hintView.leadingLayout == self.view.leadingLayout.offset(self._hintEdgeInsets.left), self.hintView.trailingLayout == self.view.trailingLayout.offset(-self._hintEdgeInsets.right), self.hintView.bottomLayout <= self.view.bottomLayout.offset(-self._hintEdgeInsets.bottom), self.errorView.topLayout == self.hintView.bottomLayout.offset(self._errorEdgeInsets.top), self.errorView.leadingLayout == self.view.leadingLayout.offset(self._errorEdgeInsets.left), self.errorView.trailingLayout == self.view.trailingLayout.offset(-self._errorEdgeInsets.right) ] } self._inputConstraints = [ self.inputTitleView.topLayout == self.inputView.topLayout.offset(self.inputEdgeInsets.top), self.inputTitleView.leadingLayout == self.inputView.leadingLayout.offset(self.inputEdgeInsets.left), self.inputTitleView.trailingLayout == self.inputView.trailingLayout.offset(-self.inputEdgeInsets.right), self.inputFieldView.topLayout == self.inputTitleView.bottomLayout.offset(self.inputFieldSpacing), self.inputFieldView.leadingLayout == self.inputView.leadingLayout.offset(self.inputEdgeInsets.left), self.inputFieldView.trailingLayout == self.inputView.trailingLayout.offset(-self.inputEdgeInsets.right), self.inputFieldView.bottomLayout == self.inputView.bottomLayout.offset(-self.inputEdgeInsets.bottom) ] self._inputFieldHeightConstraint = self.inputFieldView.heightLayout == self.inputFieldView.textHeight } func _editing() { self.editing(text: self.inputFieldView.unformatText) self._hideError() } func _changedHeight() { self._inputFieldHeightConstraint?.constant = self.inputFieldView.textHeight } func _showError(text: String) { self.errorView.text = QAttributedText(text: text, style: self.errorTextStyle) if self._errorShowed == false { self._errorShowed = true self._relayout(animated: true, completion: nil) } } func _hideError() { if self._errorShowed == true { self._errorShowed = false self._relayout(animated: true, completion: nil) } } }
mit
d1a9fe0b3e3a0ce7d5b9aff399bf9a8c
44.090498
116
0.656899
4.945409
false
false
false
false
vmanot/swift-package-manager
Sources/Basic/LazyCache.swift
1
1947
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// Thread-safe lazily cached methods. /// /// The `lazy` annotation in Swift does not result in a thread-safe accessor, /// which can make it an easy source of hard-to-find concurrency races. This /// class defines a wrapper designed to be used as an alternative for /// `lazy`. Example usage: /// /// ``` /// class Foo { /// var bar: Int { return barCache.getValue(self) } /// var barCache = LazyCache(someExpensiveMethod) /// /// func someExpensiveMethod() -> Int { ... } /// } /// ``` /// /// See: https://bugs.swift.org/browse/SR-1042 // // FIXME: This wrapper could benefit from local static variables, in which case // we could embed the cache object inside the accessor. public struct LazyCache<Class, T> { // FIXME: It would be nice to avoid a per-instance lock, but this type isn't // intended for creating large numbers of instances of. We also really want // a reader-writer lock or something similar here. private var lock = Lock() let body: (Class) -> () -> T var cachedValue: T? /// Create a lazy cache from a method value. public init(_ body: @escaping (Class) -> () -> T) { self.body = body } /// Get the cached value, computing it if necessary. public mutating func getValue(_ instance: Class) -> T { // FIXME: This is unfortunate, see note w.r.t. the lock. return lock.withLock { if let value = cachedValue { return value } else { let result = body(instance)() cachedValue = result return result } } } }
apache-2.0
ca9caeb8efb502c61a800e7290d2de90
33.157895
80
0.63585
4.160256
false
false
false
false
pluralsight/PSOperations
PSOperations/DispatchQoS.QoSClass+.swift
1
468
import Foundation extension DispatchQoS.QoSClass { init(qos: QualityOfService) { switch qos { case .userInteractive: self = .userInteractive case .userInitiated: self = .userInitiated case .utility: self = .utility case .background: self = .background case .default: self = .default @unknown default: self = .default } } }
apache-2.0
6ef443b7fa54df3c4591060157baaf54
22.4
35
0.523504
5.318182
false
false
false
false
sambulosenda/AERecord
AERecord/AERecord.swift
1
62206
// // AERecord.swift // // Copyright (c) 2014 Marko Tadić <[email protected]> http://tadija.net // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import CoreData let kAERecordPrintLog = true // this will soon be updated to Swift 2.0 error handling. // MARK: - AERecord (facade for shared instance of AEStack) /** This class is facade for accessing shared instance of `AEStack` (private class which is all about the Core Data Stack). */ public class AERecord { // MARK: Properties /// Managed object context for current thread. public class var defaultContext: NSManagedObjectContext { return AEStack.sharedInstance.defaultContext } /// Managed object context for main thread. public class var mainContext: NSManagedObjectContext { return AEStack.sharedInstance.mainContext } /// Managed object context for background thread. public class var backgroundContext: NSManagedObjectContext { return AEStack.sharedInstance.backgroundContext } /// Persistent Store Coordinator for current stack. public class var persistentStoreCoordinator: NSPersistentStoreCoordinator? { return AEStack.sharedInstance.persistentStoreCoordinator } // MARK: Setup Stack /** Returns the final URL in Application Documents Directory for the store with given name. :param: name Filename for the store. */ public class func storeURLForName(name: String) -> NSURL { return AEStack.storeURLForName(name) } /** Returns merged model from the bundle for given class. :param: forClass Class inside bundle with data model. */ public class func modelFromBundle(#forClass: AnyClass) -> NSManagedObjectModel { return AEStack.modelFromBundle(forClass: forClass) } /** Loads Core Data Stack *(creates new if it doesn't already exist)* with given options **(all options are optional)**. - Default option for `managedObjectModel` is `NSManagedObjectModel.mergedModelFromBundles(nil)!`. - Default option for `storeType` is `NSSQLiteStoreType`. - Default option for `storeURL` is `bundleIdentifier + ".sqlite"` inside `applicationDocumentsDirectory`. :param: managedObjectModel Managed object model for Core Data Stack. :param: storeType Store type for Persistent Store creation. :param: configuration Configuration for Persistent Store creation. :param: storeURL URL for Persistent Store creation. :param: options Options for Persistent Store creation. :returns: Optional error if something went wrong. */ public class func loadCoreDataStack(managedObjectModel: NSManagedObjectModel = AEStack.defaultModel, storeType: String = NSSQLiteStoreType, configuration: String? = nil, storeURL: NSURL = AEStack.defaultURL, options: [NSObject : AnyObject]? = nil) -> NSError? { return AEStack.sharedInstance.loadCoreDataStack(managedObjectModel: managedObjectModel, storeType: storeType, configuration: configuration, storeURL: storeURL, options: options) } /** Destroys Core Data Stack for given store URL *(stop notifications, reset contexts, remove persistent store and delete .sqlite file)*. **This action can't be undone.** :param: storeURL Store URL for stack to destroy. */ public class func destroyCoreDataStack(storeURL: NSURL = AEStack.defaultURL) { AEStack.sharedInstance.destroyCoreDataStack(storeURL: storeURL) } /** Deletes all records from all entities contained in the model. :param: context If not specified, `defaultContext` will be used. */ public class func truncateAllData(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.truncateAllData(context: context) } // MARK: Context Execute /** Executes given fetch request. :param: request Fetch request to execute. :param: context If not specified, `defaultContext` will be used. */ public class func executeFetchRequest(request: NSFetchRequest, context: NSManagedObjectContext? = nil) -> [NSManagedObject] { return AEStack.sharedInstance.executeFetchRequest(request, context: context) } // MARK: Context Save /** Saves context *(without waiting - returns immediately)*. :param: context If not specified, `defaultContext` will be used. */ public class func saveContext(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.saveContext(context: context) } /** Saves context with waiting *(returns when context is saved)*. :param: context If not specified, `defaultContext` will be used. */ public class func saveContextAndWait(context: NSManagedObjectContext? = nil) { AEStack.sharedInstance.saveContextAndWait(context: context) } // MARK: Context Faulting Objects /** Turns objects into faults for given Array of `NSManagedObjectID`. :param: objectIDS Array of `NSManagedObjectID` objects to turn into fault. :param: mergeChanges A Boolean value. :param: context If not specified, `defaultContext` will be used. */ public class func refreshObjects(#objectIDS: [NSManagedObjectID], mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { AEStack.refreshObjects(objectIDS: objectIDS, mergeChanges: mergeChanges, context: context) } /** Turns all registered objects into faults. :param: mergeChanges A Boolean value. :param: context If not specified, `defaultContext` will be used. */ public class func refreshAllRegisteredObjects(#mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { AEStack.refreshAllRegisteredObjects(mergeChanges: mergeChanges, context: context) } } // MARK: - CoreData Stack (AERecord heart:) private class AEStack { // MARK: Shared Instance class var sharedInstance: AEStack { struct Singleton { static let instance = AEStack() } return Singleton.instance } // MARK: Default settings class var bundleIdentifier: String { return NSBundle.mainBundle().bundleIdentifier! } class var defaultURL: NSURL { return storeURLForName(bundleIdentifier) } class var defaultModel: NSManagedObjectModel { return NSManagedObjectModel.mergedModelFromBundles(nil)! } // MARK: Properties var managedObjectModel: NSManagedObjectModel? var persistentStoreCoordinator: NSPersistentStoreCoordinator? var mainContext: NSManagedObjectContext! var backgroundContext: NSManagedObjectContext! var defaultContext: NSManagedObjectContext { if NSThread.isMainThread() { return mainContext } else { return backgroundContext } } // MARK: Setup Stack class func storeURLForName(name: String) -> NSURL { let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL let storeName = "\(name).sqlite" return applicationDocumentsDirectory.URLByAppendingPathComponent(storeName) } class func modelFromBundle(#forClass: AnyClass) -> NSManagedObjectModel { let bundle = NSBundle(forClass: forClass) return NSManagedObjectModel.mergedModelFromBundles([bundle])! } func loadCoreDataStack(managedObjectModel: NSManagedObjectModel = defaultModel, storeType: String = NSSQLiteStoreType, configuration: String? = nil, storeURL: NSURL = defaultURL, options: [NSObject : AnyObject]? = nil) -> NSError? { self.managedObjectModel = managedObjectModel // setup main and background contexts mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) // create the coordinator and store persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) if let coordinator = persistentStoreCoordinator { var error: NSError? if coordinator.addPersistentStoreWithType(storeType, configuration: configuration, URL: storeURL, options: options, error: &error) == nil { var userInfoDictionary = [NSObject : AnyObject]() userInfoDictionary[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" userInfoDictionary[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." userInfoDictionary[NSUnderlyingErrorKey] = error error = NSError(domain: AEStack.bundleIdentifier, code: 1, userInfo: userInfoDictionary) if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return error } else { // everything went ok mainContext.persistentStoreCoordinator = coordinator backgroundContext.persistentStoreCoordinator = coordinator startReceivingContextNotifications() return nil } } else { return NSError(domain: AEStack.bundleIdentifier, code: 2, userInfo: [NSLocalizedDescriptionKey : "Could not create NSPersistentStoreCoordinator from given NSManagedObjectModel."]) } } func destroyCoreDataStack(storeURL: NSURL = defaultURL) -> NSError? { // must load this core data stack first loadCoreDataStack(storeURL: storeURL) // because there is no persistentStoreCoordinator if destroyCoreDataStack is called before loadCoreDataStack // also if we're in other stack currently that persistentStoreCoordinator doesn't know about this storeURL stopReceivingContextNotifications() // stop receiving notifications for these contexts // reset contexts mainContext.reset() backgroundContext.reset() // finally, remove persistent store var error: NSError? if let coordinator = persistentStoreCoordinator { if let store = coordinator.persistentStoreForURL(storeURL) { if coordinator.removePersistentStore(store, error: &error) { NSFileManager.defaultManager().removeItemAtURL(storeURL, error: &error) } } } // reset coordinator and model persistentStoreCoordinator = nil managedObjectModel = nil if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return error ?? nil } func truncateAllData(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext if let mom = managedObjectModel { for entity in mom.entities as! [NSEntityDescription] { if let entityType = NSClassFromString(entity.managedObjectClassName) as? NSManagedObject.Type { entityType.deleteAll(context: moc) } } } } deinit { stopReceivingContextNotifications() if kAERecordPrintLog { println("\(NSStringFromClass(self.dynamicType)) deinitialized - function: \(__FUNCTION__) | line: \(__LINE__)\n") } } // MARK: Context Execute func executeFetchRequest(request: NSFetchRequest, context: NSManagedObjectContext? = nil) -> [NSManagedObject] { var fetchedObjects = [NSManagedObject]() let moc = context ?? defaultContext moc.performBlockAndWait { () -> Void in var error: NSError? if let result = moc.executeFetchRequest(request, error: &error) { if let managedObjects = result as? [NSManagedObject] { fetchedObjects = managedObjects } } if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } return fetchedObjects } // MARK: Context Save func saveContext(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext moc.performBlock { () -> Void in var error: NSError? if moc.hasChanges && !moc.save(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } } } func saveContextAndWait(context: NSManagedObjectContext? = nil) { let moc = context ?? defaultContext moc.performBlockAndWait { () -> Void in var error: NSError? if moc.hasChanges && !moc.save(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } } } // MARK: Context Sync func startReceivingContextNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: mainContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: backgroundContext) } func stopReceivingContextNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } @objc func contextDidSave(notification: NSNotification) { if let context = notification.object as? NSManagedObjectContext { let contextToRefresh = context == mainContext ? backgroundContext : mainContext contextToRefresh.performBlock({ () -> Void in contextToRefresh.mergeChangesFromContextDidSaveNotification(notification) }) } } // MARK: Context Faulting Objects class func refreshObjects(#objectIDS: [NSManagedObjectID], mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { for objectID in objectIDS { var error: NSError? context.performBlockAndWait({ () -> Void in if let object = context.existingObjectWithID(objectID, error: &error) { if !object.fault && error == nil { // turn managed object into fault context.refreshObject(object, mergeChanges: mergeChanges) } else { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } } }) } } class func refreshAllRegisteredObjects(#mergeChanges: Bool, context: NSManagedObjectContext = AERecord.defaultContext) { var registeredObjectIDS = [NSManagedObjectID]() for object in context.registeredObjects { if let managedObject = object as? NSManagedObject { registeredObjectIDS.append(managedObject.objectID) } } refreshObjects(objectIDS: registeredObjectIDS, mergeChanges: mergeChanges) } } // MARK: - NSManagedObject Extension /** This extension is all about **easy querying**. All queries are called as class functions on `NSManagedObject` (or it's custom subclass), and `defaultContext` is used if you don't specify any. */ public extension NSManagedObject { // MARK: General /** This property **must return correct entity name** because it's used all across other helpers to reference custom `NSManagedObject` subclass. You may override this property in your custom `NSManagedObject` subclass if needed (but it should work out of the box generally). */ class var entityName: String { var name = NSStringFromClass(self) name = name.componentsSeparatedByString(".").last return name } /// An `NSEntityDescription` object describes an entity in Core Data. class var entity: NSEntityDescription? { return NSEntityDescription.entityForName(entityName, inManagedObjectContext: AERecord.defaultContext) } /** Creates fetch request **(for any entity type)** for given predicate and sort descriptors *(which are optional)*. :param: predicate Predicate for fetch request. :param sortDescriptors Sort Descriptors for fetch request. :returns: The created fetch request. */ class func createFetchRequest(predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil) -> NSFetchRequest { let request = NSFetchRequest(entityName: entityName) request.predicate = predicate request.sortDescriptors = sortDescriptors return request } private static let defaultPredicateType: NSCompoundPredicateType = .AndPredicateType /** Creates predicate for given attributes and predicate type. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :returns: The created predicate. */ class func createPredicateForAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType) -> NSPredicate { var predicates = [NSPredicate]() for (attribute, value) in attributes { predicates.append(NSPredicate(format: "%K = %@", argumentArray: [attribute, value])) } let compoundPredicate = NSCompoundPredicate(type: predicateType, subpredicates: predicates) return compoundPredicate } // MARK: Creating /** Creates new instance of entity object. :param: context If not specified, `defaultContext` will be used. :returns: New instance of `Self`. */ class func create(context: NSManagedObjectContext = AERecord.defaultContext) -> Self { let entityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context) let object = self(entity: entityDescription!, insertIntoManagedObjectContext: context) return object } /** Creates new instance of entity object and set it with given attributes. :param: attributes Dictionary of attribute names and values. :param: context If not specified, `defaultContext` will be used. :returns: New instance of `Self` with set attributes. */ class func createWithAttributes(attributes: [NSObject : AnyObject], context: NSManagedObjectContext = AERecord.defaultContext) -> Self { let object = create(context: context) if attributes.count > 0 { object.setValuesForKeysWithDictionary(attributes) } return object } /** Finds the first record for given attribute and value or creates new if the it does not exist. :param: attribute Attribute name. :param: value Attribute value. :param: context If not specified, `defaultContext` will be used. :returns: Instance of managed object. */ class func firstOrCreateWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject { return firstOrCreateWithAttributes([attribute : value], context: context) } /** Finds the first record for given attributes or creates new if the it does not exist. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: context If not specified, `defaultContext` will be used. :returns: Instance of managed object. */ class func firstOrCreateWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject { let predicate = createPredicateForAttributes(attributes, predicateType: predicateType) let request = createFetchRequest(predicate: predicate) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? createWithAttributes(attributes, context: context) } // MARK: Finding First /** Finds the first record. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func first(sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let request = createFetchRequest(sortDescriptors: sortDescriptors) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? nil } /** Finds the first record for given predicate. :param: predicate Predicate. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func firstWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let request = createFetchRequest(predicate: predicate, sortDescriptors: sortDescriptors) request.fetchLimit = 1 let objects = AERecord.executeFetchRequest(request, context: context) return objects.first ?? nil } /** Finds the first record for given attribute and value. :param: attribute Attribute name. :param: value Attribute value. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func firstWithAttribute(attribute: String, value: AnyObject, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let predicate = NSPredicate(format: "%K = %@", argumentArray: [attribute, value]) return firstWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } /** Finds the first record for given attributes. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func firstWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let predicate = createPredicateForAttributes(attributes, predicateType: predicateType) return firstWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } /** Finds the first record ordered by given attribute. :param: name Attribute name. :param: ascending A Boolean value. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func firstOrderedByAttribute(name: String, ascending: Bool = true, context: NSManagedObjectContext = AERecord.defaultContext) -> NSManagedObject? { let sortDescriptors = [NSSortDescriptor(key: name, ascending: ascending)] return first(sortDescriptors: sortDescriptors, context: context) } // MARK: Finding All /** Finds all records. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func all(sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let request = createFetchRequest(sortDescriptors: sortDescriptors) let objects = AERecord.executeFetchRequest(request, context: context) return objects.count > 0 ? objects : nil } /** Finds all records for given predicate. :param: predicate Predicate. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func allWithPredicate(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let request = createFetchRequest(predicate: predicate, sortDescriptors: sortDescriptors) let objects = AERecord.executeFetchRequest(request, context: context) return objects.count > 0 ? objects : nil } /** Finds all records for given attribute and value. :param: attribute Attribute name. :param: value Attribute value. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func allWithAttribute(attribute: String, value: AnyObject, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let predicate = NSPredicate(format: "%K = %@", argumentArray: [attribute, value]) return allWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } /** Finds all records for given attributes. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional managed object. */ class func allWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [NSManagedObject]? { let predicate = createPredicateForAttributes(attributes, predicateType: predicateType) return allWithPredicate(predicate, sortDescriptors: sortDescriptors, context: context) } // MARK: Deleting /** Deletes instance of entity object. :param: context If not specified, `defaultContext` will be used. */ func delete(context: NSManagedObjectContext = AERecord.defaultContext) { context.deleteObject(self) } /** Deletes all records. :param: context If not specified, `defaultContext` will be used. */ class func deleteAll(context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.all(context: context) { for object in objects { context.deleteObject(object) } } } /** Deletes all records for given predicate. :param: predicate Predicate. :param: context If not specified, `defaultContext` will be used. */ class func deleteAllWithPredicate(predicate: NSPredicate, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithPredicate(predicate, context: context) { for object in objects { context.deleteObject(object) } } } /** Deletes all records for given attribute name and value. :param: attribute Attribute name. :param: value Attribute value. :param: context If not specified, `defaultContext` will be used. */ class func deleteAllWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithAttribute(attribute, value: value, context: context) { for object in objects { context.deleteObject(object) } } } /** Deletes all records for given attributes. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: context If not specified, `defaultContext` will be used. */ class func deleteAllWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, context: NSManagedObjectContext = AERecord.defaultContext) { if let objects = self.allWithAttributes(attributes, predicateType: predicateType, context: context) { for object in objects { context.deleteObject(object) } } } // MARK: Count /** Counts all records. :param: context If not specified, `defaultContext` will be used. :returns: Count of records. */ class func count(context: NSManagedObjectContext = AERecord.defaultContext) -> Int { return countWithPredicate(context: context) } /** Counts all records for given predicate. :param: predicate Predicate. :param: context If not specified, `defaultContext` will be used. :returns: Count of records. */ class func countWithPredicate(predicate: NSPredicate? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let request = createFetchRequest(predicate: predicate) request.includesSubentities = false var error: NSError? let count = context.countForFetchRequest(request, error: &error) if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return count } /** Counts all records for given attribute name and value. :param: attribute Attribute name. :param: value Attribute value. :param: context If not specified, `defaultContext` will be used. :returns: Count of records. */ class func countWithAttribute(attribute: String, value: AnyObject, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { return countWithAttributes([attribute : value], context: context) } /** Counts all records for given attributes. :param: attributes Dictionary of attribute names and values. :param: predicateType If not specified, `.AndPredicateType` will be used. :param: context If not specified, `defaultContext` will be used. :returns: Count of records. */ class func countWithAttributes(attributes: [NSObject : AnyObject], predicateType: NSCompoundPredicateType = defaultPredicateType, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let predicate = createPredicateForAttributes(attributes, predicateType: predicateType) return countWithPredicate(predicate: predicate, context: context) } // MARK: Distinct /** Gets distinct values for given attribute and predicate. :param: attribute Attribute name. :param: predicate Predicate. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional Array of `AnyObject`. */ class func distinctValuesForAttribute(attribute: String, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [AnyObject]? { var distinctValues = [AnyObject]() if let distinctRecords = distinctRecordsForAttributes([attribute], predicate: predicate, sortDescriptors: sortDescriptors, context: context) { for record in distinctRecords { if let value: AnyObject = record[attribute] { distinctValues.append(value) } } } return distinctValues.count > 0 ? distinctValues : nil } /** Gets distinct values for given attributes and predicate. :param: attributes Dictionary of attribute names and values. :param: predicate Predicate. :param: sortDescriptors Sort descriptors. :param: context If not specified, `defaultContext` will be used. :returns: Optional Array of `AnyObject`. */ class func distinctRecordsForAttributes(attributes: [String], predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> [Dictionary<String, AnyObject>]? { let request = createFetchRequest(predicate: predicate, sortDescriptors: sortDescriptors) request.resultType = .DictionaryResultType request.propertiesToFetch = attributes request.returnsDistinctResults = true var distinctRecords: [Dictionary<String, AnyObject>]? var error: NSError? if let distinctResult = context.executeFetchRequest(request, error: &error) as? [Dictionary<String, AnyObject>] { distinctRecords = distinctResult } if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } return distinctRecords } // MARK: Auto Increment /** Gets next ID for given attribute name. Attribute must be of `Int` type. :param: attribute Attribute name. :param: context If not specified, `defaultContext` will be used. :returns: Auto incremented ID. */ class func autoIncrementedIntegerAttribute(attribute: String, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { let sortDescriptor = NSSortDescriptor(key: attribute, ascending: false) if let object = self.first(sortDescriptors: [sortDescriptor], context: context) { if let max = object.valueForKey(attribute) as? Int { return max + 1 } else { return 0 } } else { return 0 } } // MARK: Turn Object Into Fault /** Turns object into fault. :param: mergeChanges A Boolean value. :param: context If not specified, `defaultContext` will be used. */ func refresh(mergeChanges: Bool = true, context: NSManagedObjectContext = AERecord.defaultContext) { AERecord.refreshObjects(objectIDS: [objectID], mergeChanges: mergeChanges, context: context) } // MARK: Batch Updating /** Updates data directly in persistent store **(iOS 8 and above)**. :param: predicate Predicate. :param: properties Properties to update. :param: resultType If not specified, `StatusOnlyResultType` will be used. :param: context If not specified, `defaultContext` will be used. :returns: Batch update result. */ class func batchUpdate(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, resultType: NSBatchUpdateRequestResultType = .StatusOnlyResultType, context: NSManagedObjectContext = AERecord.defaultContext) -> NSBatchUpdateResult? { // create request let request = NSBatchUpdateRequest(entityName: entityName) // set request parameters request.predicate = predicate request.propertiesToUpdate = properties request.resultType = resultType // execute request var batchResult: NSBatchUpdateResult? = nil context.performBlockAndWait { () -> Void in var error: NSError? if let result = context.executeRequest(request, error: &error) as? NSBatchUpdateResult { batchResult = result } if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } return batchResult } /** Updates data directly in persistent store **(iOS 8 and above)**. :param: predicate Predicate. :param: properties Properties to update. :param: context If not specified, `defaultContext` will be used. :returns: Count of updated objects. */ class func objectsCountForBatchUpdate(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) -> Int { if let result = batchUpdate(predicate: predicate, properties: properties, resultType: .UpdatedObjectsCountResultType, context: context) { if let count = result.result as? Int { return count } else { return 0 } } else { return 0 } } /** Updates data directly in persistent store **(iOS 8 and above)**. Objects are turned into faults after updating *(managed object context is refreshed)*. :param: predicate Predicate. :param: properties Properties to update. :param: context If not specified, `defaultContext` will be used. */ class func batchUpdateAndRefreshObjects(predicate: NSPredicate? = nil, properties: [NSObject : AnyObject]? = nil, context: NSManagedObjectContext = AERecord.defaultContext) { if let result = batchUpdate(predicate: predicate, properties: properties, resultType: .UpdatedObjectIDsResultType, context: context) { if let objectIDS = result.result as? [NSManagedObjectID] { AERecord.refreshObjects(objectIDS: objectIDS, mergeChanges: true, context: context) } } } } // MARK: - CoreData driven UITableViewController /** Swift version of class originaly created for **Stanford CS193p Winter 2013**. This class mostly just copies the code from `NSFetchedResultsController` documentation page into a subclass of `UITableViewController`. Just subclass this and set the `fetchedResultsController` property. The only `UITableViewDataSource` method you'll **HAVE** to implement is `tableView:cellForRowAtIndexPath:`. And you can use the `NSFetchedResultsController` method `objectAtIndexPath:` to do it. Remember that once you create an `NSFetchedResultsController`, you **CANNOT** modify its properties. If you want new fetch parameters (predicate, sorting, etc.), create a **NEW** `NSFetchedResultsController` and set this class's `fetchedResultsController` property again. */ public class CoreDataTableViewController: UITableViewController, NSFetchedResultsControllerDelegate { /// The controller *(this class fetches nothing if this is not set)*. public var fetchedResultsController: NSFetchedResultsController? { didSet { if let frc = fetchedResultsController { if frc != oldValue { frc.delegate = self performFetch() } } else { tableView.reloadData() } } } /** Causes the `fetchedResultsController` to refetch the data. You almost certainly never need to call this. The `NSFetchedResultsController` class observes the context (so if the objects in the context change, you do not need to call `performFetch` since the `NSFetchedResultsController` will notice and update the table automatically). This will also automatically be called if you change the `fetchedResultsController` property. */ public func performFetch() { if let frc = fetchedResultsController { var error: NSError? if !frc.performFetch(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } tableView.reloadData() } } private var _suspendAutomaticTrackingOfChangesInManagedObjectContext: Bool = false /** Turn this on before making any changes in the managed object context that are a one-for-one result of the user manipulating rows directly in the table view. Such changes cause the context to report them (after a brief delay), and normally our `fetchedResultsController` would then try to update the table, but that is unnecessary because the changes were made in the table already (by the user) so the `fetchedResultsController` has nothing to do and needs to ignore those reports. Turn this back off after the user has finished the change. Note that the effect of setting this to NO actually gets delayed slightly so as to ignore previously-posted, but not-yet-processed context-changed notifications, therefore it is fine to set this to YES at the beginning of, e.g., `tableView:moveRowAtIndexPath:toIndexPath:`, and then set it back to NO at the end of your implementation of that method. It is not necessary (in fact, not desirable) to set this during row deletion or insertion (but definitely for row moves). */ public var suspendAutomaticTrackingOfChangesInManagedObjectContext: Bool { get { return _suspendAutomaticTrackingOfChangesInManagedObjectContext } set (newValue) { if newValue == true { _suspendAutomaticTrackingOfChangesInManagedObjectContext = true } else { dispatch_after(0, dispatch_get_main_queue(), { self._suspendAutomaticTrackingOfChangesInManagedObjectContext = false }) } } } private var beganUpdates: Bool = false // MARK: NSFetchedResultsControllerDelegate /** Notifies the receiver that the fetched results controller is about to start processing of one or more changes due to an add, remove, move, or update. :param: controller The fetched results controller that sent the message. */ public func controllerWillChangeContent(controller: NSFetchedResultsController) { if !suspendAutomaticTrackingOfChangesInManagedObjectContext { tableView.beginUpdates() beganUpdates = true } } /** Notifies the receiver of the addition or removal of a section. :param: controller The fetched results controller that sent the message. :param: sectionInfo The section that changed. :param: sectionIndex The index of the changed section. :param: type The type of change (insert or delete). */ public func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { if !suspendAutomaticTrackingOfChangesInManagedObjectContext { switch type { case .Insert: tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } } /** Notifies the receiver that a fetched object has been changed due to an add, remove, move, or update. :param: controller The fetched results controller that sent the message. :param: anObject The object in controller’s fetched results that changed. :param: indexPath The index path of the changed object (this value is nil for insertions). :param: type The type of change. :param: newIndexPath The destination path for the object for insertions or moves (this value is nil for a deletion). */ public func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { if !suspendAutomaticTrackingOfChangesInManagedObjectContext { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) default: return } } } /** Notifies the receiver that the fetched results controller has completed processing of one or more changes due to an add, remove, move, or update. :param: controller The fetched results controller that sent the message. */ public func controllerDidChangeContent(controller: NSFetchedResultsController) { if beganUpdates { tableView.endUpdates() } } // MARK: UITableViewDataSource /** Asks the data source to return the number of sections in the table view. :param: tableView An object representing the table view requesting this information. :returns: The number of sections in tableView. */ override public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return fetchedResultsController?.sections?.count ?? 0 } /** Tells the data source to return the number of rows in a given section of a table view. (required) :param: tableView The table-view object requesting this information. :param: section An index number identifying a section in tableView. :returns: The number of rows in section. */ override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (fetchedResultsController?.sections?[section] as? NSFetchedResultsSectionInfo)?.numberOfObjects ?? 0 } /** Asks the data source for the title of the header of the specified section of the table view. :param: tableView An object representing the table view requesting this information. :param: section An index number identifying a section in tableView. :returns: A string to use as the title of the section header. */ override public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return (fetchedResultsController?.sections?[section] as? NSFetchedResultsSectionInfo)?.name } /** Asks the data source to return the index of the section having the given title and section title index. :param: tableView An object representing the table view requesting this information. :param: title The title as displayed in the section index of tableView. :param: index An index number identifying a section title in the array returned by sectionIndexTitlesForTableView:. :returns: An index number identifying a section. */ override public func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { return fetchedResultsController?.sectionForSectionIndexTitle(title, atIndex: index) ?? 0 } /** Asks the data source to return the titles for the sections for a table view. :param: tableView An object representing the table view requesting this information. :returns: An array of strings that serve as the title of sections in the table view and appear in the index list on the right side of the table view. */ override public func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { return fetchedResultsController?.sectionIndexTitles } } // MARK: - CoreData driven UICollectionViewController /** Same concept as `CoreDataTableViewController`, but modified for use with `UICollectionViewController`. This class mostly just copies the code from `NSFetchedResultsController` documentation page into a subclass of `UICollectionViewController`. Just subclass this and set the `fetchedResultsController`. The only `UICollectionViewDataSource` method you'll **HAVE** to implement is `collectionView:cellForItemAtIndexPath:`. And you can use the `NSFetchedResultsController` method `objectAtIndexPath:` to do it. Remember that once you create an `NSFetchedResultsController`, you **CANNOT** modify its properties. If you want new fetch parameters (predicate, sorting, etc.), create a **NEW** `NSFetchedResultsController` and set this class's `fetchedResultsController` property again. */ public class CoreDataCollectionViewController: UICollectionViewController, NSFetchedResultsControllerDelegate { /// The controller *(this class fetches nothing if this is not set)*. public var fetchedResultsController: NSFetchedResultsController? { didSet { if let frc = fetchedResultsController { if frc != oldValue { frc.delegate = self performFetch() } } else { collectionView?.reloadData() } } } /** Causes the `fetchedResultsController` to refetch the data. You almost certainly never need to call this. The `NSFetchedResultsController` class observes the context (so if the objects in the context change, you do not need to call `performFetch` since the `NSFetchedResultsController` will notice and update the collection view automatically). This will also automatically be called if you change the `fetchedResultsController` property. */ public func performFetch() { if let frc = fetchedResultsController { var error: NSError? if !frc.performFetch(&error) { if let err = error { if kAERecordPrintLog { println("Error occured in \(NSStringFromClass(self.dynamicType)) - function: \(__FUNCTION__) | line: \(__LINE__)\n\(err)") } } } collectionView?.reloadData() } } private var _suspendAutomaticTrackingOfChangesInManagedObjectContext: Bool = false /** Turn this on before making any changes in the managed object context that are a one-for-one result of the user manipulating cells directly in the collection view. Such changes cause the context to report them (after a brief delay), and normally our `fetchedResultsController` would then try to update the collection view, but that is unnecessary because the changes were made in the collection view already (by the user) so the `fetchedResultsController` has nothing to do and needs to ignore those reports. Turn this back off after the user has finished the change. Note that the effect of setting this to NO actually gets delayed slightly so as to ignore previously-posted, but not-yet-processed context-changed notifications, therefore it is fine to set this to YES at the beginning of, e.g., `collectionView:moveItemAtIndexPath:toIndexPath:`, and then set it back to NO at the end of your implementation of that method. It is not necessary (in fact, not desirable) to set this during row deletion or insertion (but definitely for cell moves). */ public var suspendAutomaticTrackingOfChangesInManagedObjectContext: Bool { get { return _suspendAutomaticTrackingOfChangesInManagedObjectContext } set (newValue) { if newValue == true { _suspendAutomaticTrackingOfChangesInManagedObjectContext = true } else { dispatch_after(0, dispatch_get_main_queue(), { self._suspendAutomaticTrackingOfChangesInManagedObjectContext = false }) } } } // MARK: NSFetchedResultsControllerDelegate Helpers private var sectionInserts = [Int]() private var sectionDeletes = [Int]() private var sectionUpdates = [Int]() private var objectInserts = [NSIndexPath]() private var objectDeletes = [NSIndexPath]() private var objectUpdates = [NSIndexPath]() private var objectMoves = [NSIndexPath]() private var objectReloads = NSMutableSet() private func updateSectionsAndObjects() { // sections if !self.sectionInserts.isEmpty { for sectionIndex in self.sectionInserts { self.collectionView?.insertSections(NSIndexSet(index: sectionIndex)) } self.sectionInserts.removeAll(keepCapacity: true) } if !self.sectionDeletes.isEmpty { for sectionIndex in self.sectionDeletes { self.collectionView?.deleteSections(NSIndexSet(index: sectionIndex)) } self.sectionDeletes.removeAll(keepCapacity: true) } if !self.sectionUpdates.isEmpty { for sectionIndex in self.sectionUpdates { self.collectionView?.reloadSections(NSIndexSet(index: sectionIndex)) } self.sectionUpdates.removeAll(keepCapacity: true) } // objects if !self.objectInserts.isEmpty { self.collectionView?.insertItemsAtIndexPaths(self.objectInserts) self.objectInserts.removeAll(keepCapacity: true) } if !self.objectDeletes.isEmpty { self.collectionView?.deleteItemsAtIndexPaths(self.objectDeletes) self.objectDeletes.removeAll(keepCapacity: true) } if !self.objectUpdates.isEmpty { self.collectionView?.reloadItemsAtIndexPaths(self.objectUpdates) self.objectUpdates.removeAll(keepCapacity: true) } if !self.objectMoves.isEmpty { let moveOperations = objectMoves.count / 2 var index = 0 for i in 0 ..< moveOperations { self.collectionView?.moveItemAtIndexPath(self.objectMoves[index], toIndexPath: self.objectMoves[index + 1]) index = index + 2 } self.objectMoves.removeAll(keepCapacity: true) } } // MARK: NSFetchedResultsControllerDelegate /** Notifies the receiver of the addition or removal of a section. :param: controller The fetched results controller that sent the message. :param: sectionInfo The section that changed. :param: sectionIndex The index of the changed section. :param: type The type of change (insert or delete). */ public func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: sectionInserts.append(sectionIndex) case .Delete: sectionDeletes.append(sectionIndex) case .Update: sectionUpdates.append(sectionIndex) default: break } } /** Notifies the receiver that a fetched object has been changed due to an add, remove, move, or update. :param: controller The fetched results controller that sent the message. :param: anObject The object in controller’s fetched results that changed. :param: indexPath The index path of the changed object (this value is nil for insertions). :param: type The type of change. :param: newIndexPath The destination path for the object for insertions or moves (this value is nil for a deletion). */ public func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: objectInserts.append(newIndexPath!) case .Delete: objectDeletes.append(indexPath!) case .Update: objectUpdates.append(indexPath!) case .Move: objectMoves.append(indexPath!) objectMoves.append(newIndexPath!) objectReloads.addObject(indexPath!) objectReloads.addObject(newIndexPath!) } } /** Notifies the receiver that the fetched results controller has completed processing of one or more changes due to an add, remove, move, or update. :param: controller The fetched results controller that sent the message. */ public func controllerDidChangeContent(controller: NSFetchedResultsController) { if !suspendAutomaticTrackingOfChangesInManagedObjectContext { // do batch updates on collection view collectionView?.performBatchUpdates({ () -> Void in self.updateSectionsAndObjects() }, completion: { (finished) -> Void in // reload moved items when finished if self.objectReloads.count > 0 { self.collectionView?.reloadItemsAtIndexPaths(self.objectReloads.allObjects) self.objectReloads.removeAllObjects() } }) } } // MARK: UICollectionViewDataSource /** Asks the data source for the number of sections in the collection view. :param: collectionView An object representing the collection view requesting this information. :returns: The number of sections in collectionView. */ override public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return fetchedResultsController?.sections?.count ?? 0 } /** Asks the data source for the number of items in the specified section. (required) :param: collectionView An object representing the collection view requesting this information. :param: section An index number identifying a section in collectionView. :returns: The number of rows in section. */ override public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (fetchedResultsController?.sections?[section] as? NSFetchedResultsSectionInfo)?.numberOfObjects ?? 0 } }
mit
bff74a6030a9a2219711a5946225ede1
42.773399
265
0.657514
5.641302
false
false
false
false
duliodenis/musicvideos
Music Videos/Music Videos/Controllers/MusicVideoTableViewCell.swift
1
1656
// // MusicVideoTableViewCell.swift // Music Videos // // Created by Dulio Denis on 2/20/16. // Copyright © 2016 Dulio Denis. All rights reserved. // import UIKit class MusicVideoTableViewCell: UITableViewCell { @IBOutlet weak var videoImageView: UIImageView! @IBOutlet weak var videoArtist: UILabel! @IBOutlet weak var videoTitle: UILabel! var video: MusicVideos? { didSet { updateCell() } } func updateCell() { // Use Preferred for for Accessibility videoTitle.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline) videoArtist.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline) videoTitle.text = video?.name videoArtist.text = video?.artist if video!.imageData != nil { // get data from array videoImageView.image = UIImage(data: video!.imageData!) } else { getVideoImages(video!, imageView: videoImageView) } } func getVideoImages(video: MusicVideos, imageView: UIImageView) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let data = NSData(contentsOfURL: NSURL(string: video.imageURL)!) var image: UIImage? if data != nil { video.imageData = data image = UIImage(data: data!) } // back to the main queue dispatch_async(dispatch_get_main_queue()) { imageView.image = image } } } }
mit
9269708bd9ceb8240953b18c38e4ba3c
27.050847
87
0.580665
5.076687
false
false
false
false
tecgirl/firefox-ios
Client/Frontend/Widgets/HistoryBackButton.swift
1
2556
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import SnapKit import Shared private struct HistoryBackButtonUX { static let HistoryHistoryBackButtonHeaderChevronInset: CGFloat = 10 static let HistoryHistoryBackButtonHeaderChevronSize: CGFloat = 20 static let HistoryHistoryBackButtonHeaderChevronLineWidth: CGFloat = 3.0 } class HistoryBackButton: UIButton { lazy var title: UILabel = { let label = UILabel() label.textColor = UIColor.theme.general.highlightBlue label.text = Strings.HistoryBackButtonTitle return label }() lazy var chevron: ChevronView = { let chevron = ChevronView(direction: .left) chevron.tintColor = UIColor.theme.general.highlightBlue chevron.lineWidth = HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronLineWidth return chevron }() lazy var topBorder: UIView = self.createBorderView() lazy var bottomBorder: UIView = self.createBorderView() override init(frame: CGRect) { super.init(frame: frame) isUserInteractionEnabled = true addSubview(topBorder) addSubview(chevron) addSubview(title) backgroundColor = UIColor.theme.tableView.headerBackground chevron.snp.makeConstraints { make in make.leading.equalTo(self.safeArea.leading).offset(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset) make.centerY.equalTo(self) make.size.equalTo(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronSize) } title.snp.makeConstraints { make in make.leading.equalTo(chevron.snp.trailing).offset(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset) make.trailing.greaterThanOrEqualTo(self).offset(-HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset) make.centerY.equalTo(self) } topBorder.snp.makeConstraints { make in make.leading.trailing.equalTo(self) make.top.equalTo(self).offset(-0.5) make.height.equalTo(0.5) } } fileprivate func createBorderView() -> UIView { let view = UIView() view.backgroundColor = UIColor.theme.homePanel.siteTableHeaderBorder return view } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
bd214c541787c0d3f9e9d1ea8ff511ae
35.514286
126
0.702269
5.101796
false
false
false
false
GuiminChu/HishowZone-iOS
HiShow/General/GMProfileViewController/GMProfileSubTableViewController.swift
1
1556
// // GMProfileSubTableViewController.swift // // Created by Chu Guimin on 2018/5/8. // Copyright © 2018年 Chu Guimin. All rights reserved. // import UIKit let kGMProfileSubTableViewControllerDidScrollNotification = "kGMProfileSubTableViewControllerDidScrollNotification" let kGMProfileSubTableViewControllerUserInfo = "kGMProfileSubTableViewControllerUserInfo" class GMProfileSubTableViewController: UITableViewController { weak var scrollView: UIScrollView? override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.showsVerticalScrollIndicator = false } override func scrollViewDidScroll(_ scrollView: UIScrollView) { if self.scrollView == nil { self.scrollView = scrollView } NotificationCenter.default.post(name: NSNotification.Name(rawValue: kGMProfileSubTableViewControllerDidScrollNotification), object: nil, userInfo: [kGMProfileSubTableViewControllerUserInfo : scrollView]) } // func addNotification() { // NotificationCenter.default.addObserver(self, selector: #selector(superScrollViewDidScroll(_:)), name: NSNotification.Name(rawValue: kWBProfileViewControllerTableViewDidScrollNotification), object: nil) // } // // @objc func superScrollViewDidScroll(_ notification: NSNotification) { // self.scrollView?.contentOffset = CGPoint.zero // } deinit { NotificationCenter.default.removeObserver(self) } }
mit
7bfab4f42f1a811ea002983ddd3220d7
34.295455
211
0.726336
5.142384
false
false
false
false
TZLike/GiftShow
GiftShow/GiftShow/Classes/ProductDetail/Controller/LeeProductWebDetailViewController.swift
1
1051
// // LeeHotCategoryViewController.swift // GiftShow // // Created by admin on 16/10/26. // Copyright © 2016年 Mr_LeeKi. All rights reserved. // import UIKit class LeeProductWebDetailViewController: UIViewController { var rank:NSNumber = 0 var html:String?{ didSet{ self.myWebView.loadHTMLString(html!, baseURL: nil) } } private lazy var topView:UIView = { let view = UIView() view.frame = CGRect(x:0,y:-10,width:WIDTH,height:30) view.backgroundColor = UIColor.white return view }() private lazy var myWebView:UIWebView = { let webView = UIWebView() webView.frame = CGRect(x:0,y:40,width:WIDTH,height:HEIGHT - 50) webView.backgroundColor = UIColor.clear return webView }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.colorWithHexString("f9f5f4") view.addSubview(topView) view.addSubview(myWebView) } }
apache-2.0
9bc80aa8aad58a48f6d51921565b0390
19.96
72
0.609733
4.208835
false
false
false
false
timd/Trackr
Trackr/SpaceViewController.swift
2
3114
// // ViewController.swift // Trackr // // Created by Tim Duckett on 05/11/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import UIKit class SpaceViewController: UIViewController { @IBOutlet var collectionView: UICollectionView! var cvData = [Int]() var minCellHeight: CGFloat! var maxCellHeight: CGFloat! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setupData() setupCollectionView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension SpaceViewController { func setupData() { for index in 0...20 { cvData.append(index) } } func setupCollectionView() { let layout = UICollectionViewFlowLayout() layout.scrollDirection = UICollectionViewScrollDirection.Vertical layout.itemSize = CGSizeMake(75, 75) layout.minimumInteritemSpacing = 10 layout.minimumLineSpacing = 10 collectionView.collectionViewLayout = layout maxCellHeight = min(collectionView.frame.size.width, collectionView.frame.size.height) / 2 minCellHeight = layout.itemSize.height let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: "didGetPinchGesture:") collectionView.addGestureRecognizer(pinchRecognizer) } func didGetPinchGesture(sender: UIPinchGestureRecognizer) { guard sender.numberOfTouches() == 2 else { return } let pointOne = sender.locationOfTouch(0, inView: collectionView) let pointTwo = sender.locationOfTouch(1, inView: collectionView) let dX = pointOne.x - pointTwo.x let dY = pointTwo.y - pointTwo.y let distance = sqrt(dX * dX + dY * dY) let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.minimumLineSpacing = distance / 5 layout.minimumInteritemSpacing = distance / 5 layout.invalidateLayout() } } extension SpaceViewController: UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return cvData.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellIdentifier", forIndexPath: indexPath) let cellLabel = cell.viewWithTag(1000) as! UILabel cellLabel.text = "Cell \(cvData[indexPath.row])" cell.layer.borderColor = UIColor.redColor().CGColor cell.layer.borderWidth = 2.0 return cell } }
mit
253e129db79a8030d3ddbbae6df22469
28.093458
130
0.650177
5.639493
false
false
false
false
dulingkang/OpenGL
OpenGLChapter1/OpenGLChapter1/OpenGLView.swift
1
2134
// // OpenGLView.swift // OpenGLChapter1 // // Created by ShawnDu on 15/12/11. // Copyright © 2015年 Shawn. All rights reserved. // import UIKit class OpenGLView: UIView { var eaglLayer: CAEAGLLayer! var context: EAGLContext? var colorRenderBuffer: GLuint = 1 override init(frame: CGRect) { super.init(frame: frame) self.config() } required init(coder: NSCoder) { super.init(coder: coder)! } func layerClass() -> AnyObject { return CAEAGLLayer.self } private func config() { self.setupLayer() self.setupContext() self.setupRenderBuffer() self.setupFrameBuffer() self.render() } private func setupLayer() { eaglLayer = CAEAGLLayer(layer: self.layer) eaglLayer.opaque = true self.layer.addSublayer(eaglLayer) } private func setupContext() { let api = EAGLRenderingAPI.OpenGLES3 if let context = EAGLContext.init(API: api) { self.context = context if !EAGLContext.setCurrentContext(context) { print("Failed to set current opengl context") exit(1) } } else { print("failed to initial opengl3.0 context") exit(1) } } private func setupRenderBuffer() { glGenRenderbuffers(1, &colorRenderBuffer) glBindRenderbuffer(GLenum(GL_RENDERBUFFER), colorRenderBuffer) context?.renderbufferStorage(Int(GL_RENDERBUFFER), fromDrawable: eaglLayer) } private func setupFrameBuffer() { var frameBuffer: GLuint = 0 glGenFramebuffers(1, &frameBuffer) glBindFramebuffer(GLenum(GL_FRAMEBUFFER), frameBuffer) glFramebufferRenderbuffer(GLenum(GL_FRAMEBUFFER), GLenum(GL_COLOR_ATTACHMENT0), GLenum(GL_RENDERBUFFER), colorRenderBuffer) } private func render() { glClearColor(0.6, 0.6, 0, 1.0) glClear(GLbitfield(GL_COLOR_BUFFER_BIT)) let success = context?.presentRenderbuffer(Int(GL_RENDERBUFFER)) print(success) } }
mit
0cbfb82479d3c12dcbb92578ce731ca5
26.675325
131
0.612389
3.998124
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/Utility/LikeButton.swift
1
3886
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit final class LikeButton: IconButton { // MARK: Properties typealias LikeButtonColors = SemanticColors.Button static var normalColor: UIColor { return LikeButtonColors.backgroundLikeEnabled } static var selectedColor: UIColor { return LikeButtonColors.backgroundLikeHighlighted } // MARK: Configuration func setSelected(_ selected: Bool, animated: Bool) { // Do not animate changes if the state does not change guard selected != self.isSelected else { return } if animated { guard let imageView = self.imageView else { return } let prevState: UIControl.State if self.isSelected { prevState = .selected } else { prevState = [] } let currentIcon = icon(for: prevState) ?? (prevState == .selected ? .liked : .like) let fakeImageView = UIImageView() fakeImageView.setIcon(currentIcon, size: .large, color: self.iconColor(for: prevState) ?? LikeButton.normalColor) fakeImageView.frame = imageView.frame imageView.superview!.addSubview(fakeImageView) let selectedIcon = icon(for: prevState) ?? .liked let animationImageView = UIImageView() animationImageView.setIcon(selectedIcon, size: .large, color: LikeButton.selectedColor) animationImageView.frame = imageView.frame imageView.superview!.addSubview(animationImageView) imageView.alpha = 0 if selected { // gets like animationImageView.alpha = 0.0 animationImageView.transform = CGAffineTransform(scaleX: 6.3, y: 6.3) UIView.animate(easing: .easeOutExpo, duration: 0.35, animations: { animationImageView.transform = CGAffineTransform.identity }) UIView.animate(easing: .easeOutQuart, duration: 0.35, animations: { animationImageView.alpha = 1 }, completion: { _ in animationImageView.removeFromSuperview() fakeImageView.removeFromSuperview() imageView.alpha = 1 self.isSelected = selected }) } else { UIView.animate(easing: .easeInExpo, duration: 0.35, animations: { animationImageView.transform = CGAffineTransform(scaleX: 6.3, y: 6.3) }) UIView.animate(easing: .easeInQuart, duration: 0.35, animations: { animationImageView.alpha = 0.0 }, completion: { _ in animationImageView.removeFromSuperview() fakeImageView.removeFromSuperview() imageView.alpha = 1 self.isSelected = selected }) } UIImpactFeedbackGenerator(style: .light).impactOccurred() } else { self.isSelected = selected } } }
gpl-3.0
8fbe69612a13c32647e1fd18bfde57d7
36.365385
125
0.590839
5.287075
false
false
false
false
agilecreativity/dotfiles
themes/osx-terminal-themes/tools/iterm2terminal.swift
2
4279
#!/usr/bin/xcrun swift import AppKit class ThemeConvertor { enum Error: ErrorType { case NoArguments, UnableToLoadITermFile(NSURL) } private let iTermFiles: [String] private let iTermColor2TerminalColorMap = [ "Ansi 0 Color": "ANSIBlackColor", "Ansi 1 Color": "ANSIRedColor", "Ansi 2 Color": "ANSIGreenColor", "Ansi 3 Color": "ANSIYellowColor", "Ansi 4 Color": "ANSIBlueColor", "Ansi 5 Color": "ANSIMagentaColor", "Ansi 6 Color": "ANSICyanColor", "Ansi 7 Color": "ANSIWhiteColor", "Ansi 8 Color": "ANSIBrightBlackColor", "Ansi 9 Color": "ANSIBrightRedColor", "Ansi 10 Color": "ANSIBrightGreenColor", "Ansi 11 Color": "ANSIBrightYellowColor", "Ansi 12 Color": "ANSIBrightBlueColor", "Ansi 13 Color": "ANSIBrightMagentaColor", "Ansi 14 Color": "ANSIBrightCyanColor", "Ansi 15 Color": "ANSIBrightWhiteColor", "Background Color": "BackgroundColor", "Foreground Color": "TextColor", "Selection Color": "SelectionColor", "Bold Color": "BoldTextColor", "Cursor Color": "CursorColor", ] required init(iTermFiles: [String]) throws { if iTermFiles.isEmpty { throw Error.NoArguments } self.iTermFiles = iTermFiles } func run() { for iTermFile in iTermFiles { let iTermFileURL = NSURL(fileURLWithPath: iTermFile).absoluteURL let folder = iTermFileURL.URLByDeletingLastPathComponent! let schemeName = iTermFileURL.URLByDeletingPathExtension!.lastPathComponent! let terminalFileURL = folder.URLByAppendingPathComponent("\(schemeName).terminal") do { try convertScheme(schemeName, fromITermFileAtURL: iTermFileURL, toTerminalFileAtURL: terminalFileURL) } catch Error.UnableToLoadITermFile(let iTermFileURL) { print("Error: Unable to load \(iTermFileURL)") } catch let error as NSError { print("Error: \(error.description)") } } } private func convertScheme(scheme: String, fromITermFileAtURL src: NSURL, toTerminalFileAtURL dest: NSURL) throws { guard let iTermScheme = NSDictionary(contentsOfURL: src) else { throw Error.UnableToLoadITermFile(src) } print("Converting \(src) -> \(dest)") var terminalScheme: [String: AnyObject] = [ "name" : scheme, "type" : "Window Settings", "ProfileCurrentVersion" : 2.04, "columnCount": 90, "rowCount": 50, ] if let font = archivedFontWithName("PragmataPro", size: 14) { terminalScheme["Font"] = font } for (iTermColorKey, iTermColorDict) in iTermScheme { if let iTermColorKey = iTermColorKey as? String, let terminalColorKey = iTermColor2TerminalColorMap[iTermColorKey], let iTermColorDict = iTermColorDict as? NSDictionary, let r = iTermColorDict["Red Component"]?.floatValue, let g = iTermColorDict["Green Component"]?.floatValue, let b = iTermColorDict["Blue Component"]?.floatValue { let color = NSColor(calibratedRed: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: 1) let colorData = NSKeyedArchiver.archivedDataWithRootObject(color) terminalScheme[terminalColorKey] = colorData } } NSDictionary(dictionary: terminalScheme).writeToURL(dest, atomically: true) } private func archivedFontWithName(name: String, size: CGFloat) -> NSData? { guard let font = NSFont(name: name, size: size) else { return nil } return NSKeyedArchiver.archivedDataWithRootObject(font) } } do { let iTermFiles = [String](Process.arguments.dropFirst()) try ThemeConvertor(iTermFiles: iTermFiles).run() } catch ThemeConvertor.Error.NoArguments { print("Error: no arguments provided") print("Usage: iTermColorsToTerminalColors FILE.ITermColors [...]") }
mit
85f975076b9fb8776a0226d2e82bbd02
37.205357
119
0.606684
4.707371
false
false
false
false
banjun/SwiftBeaker
Examples/08. Attributes.swift
1
4404
import Foundation import APIKit import URITemplate protocol URITemplateContextConvertible: Encodable {} extension URITemplateContextConvertible { var context: [String: String] { return ((try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: String]) ?? [:] } } public enum RequestError: Error { case encode } public enum ResponseError: Error { case undefined(Int, String?) case invalidData(Int, String?) } struct RawDataParser: DataParser { var contentType: String? {return nil} func parse(data: Data) -> Any { return data } } struct TextBodyParameters: BodyParameters { let contentType: String let content: String func buildEntity() throws -> RequestBodyEntity { guard let r = content.data(using: .utf8) else { throw RequestError.encode } return .data(r) } } public protocol APIBlueprintRequest: Request {} extension APIBlueprintRequest { public var dataParser: DataParser {return RawDataParser()} func contentMIMEType(in urlResponse: HTTPURLResponse) -> String? { return (urlResponse.allHeaderFields["Content-Type"] as? String)?.components(separatedBy: ";").first?.trimmingCharacters(in: .whitespaces) } func data(from object: Any, urlResponse: HTTPURLResponse) throws -> Data { guard let d = object as? Data else { throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse)) } return d } func string(from object: Any, urlResponse: HTTPURLResponse) throws -> String { guard let s = String(data: try data(from: object, urlResponse: urlResponse), encoding: .utf8) else { throw ResponseError.invalidData(urlResponse.statusCode, contentMIMEType(in: urlResponse)) } return s } func decodeJSON<T: Decodable>(from object: Any, urlResponse: HTTPURLResponse) throws -> T { return try JSONDecoder().decode(T.self, from: data(from: object, urlResponse: urlResponse)) } public func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any { return object } } protocol URITemplateRequest: Request { static var pathTemplate: URITemplate { get } associatedtype PathVars: URITemplateContextConvertible var pathVars: PathVars { get } } extension URITemplateRequest { // reconstruct URL to use URITemplate.expand. NOTE: APIKit does not support URITemplate format other than `path + query` public func intercept(urlRequest: URLRequest) throws -> URLRequest { var req = urlRequest req.url = URL(string: baseURL.absoluteString + type(of: self).pathTemplate.expand(pathVars.context))! return req } } /// indirect Codable Box-like container for recursive data structure definitions public class Indirect<V: Codable>: Codable { public var value: V public init(_ value: V) { self.value = value } public required init(from decoder: Decoder) throws { self.value = try V(from: decoder) } public func encode(to encoder: Encoder) throws { try value.encode(to: encoder) } } // MARK: - Transitions /// Retrieves the coupon with the given ID. struct Retrieve_a_Coupon: APIBlueprintRequest { let baseURL: URL var method: HTTPMethod {return .get} var path: String {return "/coupons/{id}"} enum Responses { case http200_application_json(Response200_application_json) struct Response200_application_json: Codable { /// ex. "250FF" var id: String /// Time stamp ex. 1415203908 var created: Int? /// A positive integer between 1 and 100 that represents the discount /// the coupon will apply. ex. 25 var percent_off: Int? /// Date after which the coupon can no longer be redeemed var redeem_by: Int? } } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses { let contentType = contentMIMEType(in: urlResponse) switch (urlResponse.statusCode, contentType) { case (200, "application/json"?): return .http200_application_json(try decodeJSON(from: object, urlResponse: urlResponse)) default: throw ResponseError.undefined(urlResponse.statusCode, contentType) } } } // MARK: - Data Structures
mit
98a225422cd72b84797d7462c48daa2b
31.865672
145
0.673706
4.549587
false
false
false
false
exponent/exponent
packages/expo-blur/ios/EXBlur/BlurEffectView.swift
2
2019
// Copyright 2015-present 650 Industries. All rights reserved. import UIKit /** This class is based on https://gist.github.com/darrarski/29a2a4515508e385c90b3ffe6f975df7 */ final class BlurEffectView: UIVisualEffectView { @Clamping(lowerBound: 0.01, upperBound: 1) var intensity: Double = 0.5 { didSet { setNeedsDisplay() } } @Containing(values: ["default", "light", "dark"]) var tint = "default" { didSet { visualEffect = UIBlurEffect(style: blurEffectStyleFrom(tint)) } } private var visualEffect: UIVisualEffect = UIBlurEffect(style: blurEffectStyleFrom("default")) { didSet { setNeedsDisplay() } } private var animator: UIViewPropertyAnimator? init() { super.init(effect: nil) } required init?(coder aDecoder: NSCoder) { nil } deinit { animator?.stopAnimation(true) } override func draw(_ rect: CGRect) { super.draw(rect) effect = nil animator?.stopAnimation(true) animator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [unowned self] in self.effect = visualEffect } animator?.fractionComplete = CGFloat(intensity) } } private func blurEffectStyleFrom(_ tint: String) -> UIBlurEffect.Style { switch tint { case "light": return .extraLight case "dark": return .dark case "default": return .light default: return .dark } } /** Property wrapper clamping the value between an upper and lower bound */ @propertyWrapper struct Clamping<Value: Comparable> { var wrappedValue: Value init(wrappedValue: Value, lowerBound: Value, upperBound: Value) { self.wrappedValue = max(lowerBound, min(upperBound, wrappedValue)) } } /** Property wrapper ensuring that the value is contained in list of valid values */ @propertyWrapper struct Containing<Value: Equatable> { var wrappedValue: Value init(wrappedValue: Value, values: [Value]) { let isValueValid = values.contains(wrappedValue) self.wrappedValue = isValueValid ? wrappedValue : values.first! } }
bsd-3-clause
c7a190c8935f994838fe247a841f13a9
23.325301
98
0.699851
4.112016
false
false
false
false
pisrc/blocks
Example/NewViewController.swift
1
941
// // NewViewController.swift // Blocks // // Created by ryan on 18/07/2017. // Copyright © 2017 pi. All rights reserved. // import UIKit class NewViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("modalPresentationStyle: \(modalPresentationStyle)") modalPresentationStyle = UIModalPresentationStyle.custom } deinit { print("[deinit] NewViewController") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let frame = presentationController?.frameOfPresentedViewInContainerView { view.frame = frame } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let frame = presentationController?.frameOfPresentedViewInContainerView { view.frame = frame } } }
mit
65e7ad6671ff846b1123da70ccc069c2
21.926829
84
0.634043
5.56213
false
false
false
false
eguchi-t/Zip
Zip/Zip.swift
1
13684
// // Zip.swift // Zip // // Created by Roy Marmelstein on 13/12/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation import minizip /// Zip error type public enum ZipError: ErrorType { /// File not found case FileNotFound /// Unzip fail case UnzipFail /// Zip fail case ZipFail /// User readable description public var description: String { switch self { case .FileNotFound: return NSLocalizedString("File not found.", comment: "") case .UnzipFail: return NSLocalizedString("Failed to unzip file.", comment: "") case .ZipFail: return NSLocalizedString("Failed to zip file.", comment: "") } } } /// Zip class public class Zip { /** Set of vaild file extensions */ internal static var customFileExtensions: Set<String> = [] // MARK: Lifecycle /** Init */ public init () { } // MARK: Unzip /** Unzip file - parameter zipFilePath: Local file path of zipped file. NSURL. - parameter destination: Local file path to unzip to. NSURL. - parameter overwrite: Overwrite bool. - parameter password: Optional password if file is protected. - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if unzipping fails or if fail is not found. Can be printed with a description variable. - notes: Supports implicit progress composition */ public class func unzipFile(zipFilePath: NSURL, destination: NSURL, overwrite: Bool, password: String?, progress: ((progress: Double) -> Void)?) throws { // File manager let fileManager = NSFileManager.defaultManager() // Check whether a zip file exists at path. guard let path = zipFilePath.path where destination.path != nil else { throw ZipError.FileNotFound } if fileManager.fileExistsAtPath(path) == false || fileExtensionIsInvalid(zipFilePath.pathExtension) { throw ZipError.FileNotFound } // Unzip set up var ret: Int32 = 0 var crc_ret: Int32 = 0 let bufferSize: UInt32 = 4096 var buffer = [CUnsignedChar](count: Int(bufferSize), repeatedValue: 0) // Progress handler set up var totalSize: Double = 0.0 var currentPosition: Double = 0.0 let fileAttributes = try fileManager.attributesOfItemAtPath(path) if let attributeFileSize = fileAttributes[NSFileSize] as? Double { totalSize += attributeFileSize } let progressTracker = NSProgress(totalUnitCount: Int64(totalSize)) progressTracker.cancellable = false progressTracker.pausable = false progressTracker.kind = NSProgressKindFile // Begin unzipping let zip = unzOpen64(path) defer { unzClose(zip) } if unzGoToFirstFile(zip) != UNZ_OK { throw ZipError.UnzipFail } repeat { if let cPassword = password?.cStringUsingEncoding(NSASCIIStringEncoding) { ret = unzOpenCurrentFilePassword(zip, cPassword) } else { ret = unzOpenCurrentFile(zip) } if ret != UNZ_OK { throw ZipError.UnzipFail } var fileInfo = unz_file_info64() memset(&fileInfo, 0, sizeof(unz_file_info)) ret = unzGetCurrentFileInfo64(zip, &fileInfo, nil, 0, nil, 0, nil, 0) if ret != UNZ_OK { unzCloseCurrentFile(zip) throw ZipError.UnzipFail } currentPosition += Double(fileInfo.compressed_size) let fileNameSize = Int(fileInfo.size_filename) + 1 let fileName = UnsafeMutablePointer<CChar>.alloc(fileNameSize) if fileName == nil { throw ZipError.UnzipFail } unzGetCurrentFileInfo64(zip, &fileInfo, fileName, UInt(fileNameSize), nil, 0, nil, 0) fileName[Int(fileInfo.size_filename)] = 0 guard var pathString = String(CString: fileName, encoding: NSUTF8StringEncoding) else { throw ZipError.UnzipFail } var isDirectory = false let fileInfoSizeFileName = Int(fileInfo.size_filename-1) if fileName[fileInfoSizeFileName] == "/".cStringUsingEncoding(NSUTF8StringEncoding)?.first || fileName[fileInfoSizeFileName] == "\\".cStringUsingEncoding(NSUTF8StringEncoding)?.first { isDirectory = true } free(fileName) if pathString.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "/\\")) != nil { pathString = pathString.stringByReplacingOccurrencesOfString("\\", withString: "/") } guard let fullPath = destination.URLByAppendingPathComponent(pathString)!.path else { throw ZipError.UnzipFail } let creationDate = NSDate() let directoryAttributes = [NSFileCreationDate: creationDate, NSFileModificationDate: creationDate] do { if isDirectory { try fileManager.createDirectoryAtPath(fullPath, withIntermediateDirectories: true, attributes: directoryAttributes) } else { let parentDirectory = (fullPath as NSString).stringByDeletingLastPathComponent try fileManager.createDirectoryAtPath(parentDirectory, withIntermediateDirectories: true, attributes: directoryAttributes) } } catch {} if fileManager.fileExistsAtPath(fullPath) && !isDirectory && !overwrite { unzCloseCurrentFile(zip) ret = unzGoToNextFile(zip) } var filePointer: UnsafeMutablePointer<FILE> filePointer = fopen(fullPath, "wb") while filePointer != nil { let readBytes = unzReadCurrentFile(zip, &buffer, bufferSize) if readBytes > 0 { fwrite(buffer, Int(readBytes), 1, filePointer) } else { break } } fclose(filePointer) crc_ret = unzCloseCurrentFile(zip) if crc_ret == UNZ_CRCERROR { throw ZipError.UnzipFail } ret = unzGoToNextFile(zip) // Update progress handler if let progressHandler = progress{ progressHandler(progress: (currentPosition/totalSize)) } progressTracker.completedUnitCount = Int64(currentPosition) } while (ret == UNZ_OK && ret != UNZ_END_OF_LIST_OF_FILE) // Completed. Update progress handler. if let progressHandler = progress{ progressHandler(progress: 1.0) } progressTracker.completedUnitCount = Int64(totalSize) } // MARK: Zip /** Zip files. - parameter paths: Array of NSURL filepaths. - parameter zipFilePath: Destination NSURL, should lead to a .zip filepath. - parameter password: Password string. Optional. - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if zipping fails. - notes: Supports implicit progress composition */ public class func zipFiles(paths: [NSURL], zipFilePath: NSURL, password: String?, progress: ((progress: Double) -> Void)?) throws { // File manager let fileManager = NSFileManager.defaultManager() // Check whether a zip file exists at path. guard let destinationPath = zipFilePath.path else { throw ZipError.FileNotFound } // Process zip paths let processedPaths = ZipUtilities().processZipPaths(paths) // Zip set up let chunkSize: Int = 16384 // Progress handler set up var currentPosition: Double = 0.0 var totalSize: Double = 0.0 // Get totalSize for progress handler for path in processedPaths { do { let filePath = path.filePath() let fileAttributes = try fileManager.attributesOfItemAtPath(filePath) let fileSize = fileAttributes[NSFileSize] as? Double if let fileSize = fileSize { totalSize += fileSize } } catch {} } let progressTracker = NSProgress(totalUnitCount: Int64(totalSize)) progressTracker.cancellable = false progressTracker.pausable = false progressTracker.kind = NSProgressKindFile // Begin Zipping let zip = zipOpen(destinationPath, APPEND_STATUS_CREATE) for path in processedPaths { let filePath = path.filePath() var isDirectory: ObjCBool = false fileManager.fileExistsAtPath(filePath, isDirectory: &isDirectory) if !isDirectory { let input = fopen(filePath, "r") if input == nil { throw ZipError.ZipFail } let fileName = path.fileName var zipInfo: zip_fileinfo = zip_fileinfo(tmz_date: tm_zip(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0), dosDate: 0, internal_fa: 0, external_fa: 0) do { let fileAttributes = try fileManager.attributesOfItemAtPath(filePath) if let fileDate = fileAttributes[NSFileModificationDate] as? NSDate { let components = NSCalendar.currentCalendar().components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: fileDate) zipInfo.tmz_date.tm_sec = UInt32(components.second) zipInfo.tmz_date.tm_min = UInt32(components.minute) zipInfo.tmz_date.tm_hour = UInt32(components.hour) zipInfo.tmz_date.tm_mday = UInt32(components.day) zipInfo.tmz_date.tm_mon = UInt32(components.month) - 1 zipInfo.tmz_date.tm_year = UInt32(components.year) } if let fileSize = fileAttributes[NSFileSize] as? Double { currentPosition += fileSize } } catch {} let buffer = malloc(chunkSize) if let password = password, let fileName = fileName { zipOpenNewFileInZip3(zip, fileName, &zipInfo, nil, 0, nil, 0, nil, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password, 0) } else if let fileName = fileName { zipOpenNewFileInZip3(zip, fileName, &zipInfo, nil, 0, nil, 0, nil, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, nil, 0) } else { throw ZipError.ZipFail } var length: Int = 0 while feof(input) == 0 { length = fread(buffer, 1, chunkSize, input) zipWriteInFileInZip(zip, buffer, UInt32(length)) } // Update progress handler if let progressHandler = progress{ progressHandler(progress: (currentPosition/totalSize)) } progressTracker.completedUnitCount = Int64(currentPosition) zipCloseFileInZip(zip) free(buffer) fclose(input) } } zipClose(zip, nil) // Completed. Update progress handler. if let progressHandler = progress{ progressHandler(progress: 1.0) } progressTracker.completedUnitCount = Int64(totalSize) } /** Check if file extension is invalid. - parameter fileExtension: A file extension. - returns: false if the extension is a valid file extension, otherwise true. */ internal class func fileExtensionIsInvalid(fileExtension: String?) -> Bool { guard let fileExtension = fileExtension else { return true } return !isValidFileExtension(fileExtension) } /** Add a file extension to the set of custom file extensions - parameter fileExtension: A file extension. */ public class func addCustomFileExtension(fileExtension: String) { customFileExtensions.insert(fileExtension) } /** Remove a file extension from the set of custom file extensions - parameter fileExtension: A file extension. */ public class func removeCustomFileExtension(fileExtension: String) { customFileExtensions.remove(fileExtension) } /** Check if a specific file extension is valid - parameter fileExtension: A file extension. - returns: true if the extension valid, otherwise false. */ public class func isValidFileExtension(fileExtension: String) -> Bool { let validFileExtensions: Set<String> = customFileExtensions.union(["zip", "cbz"]) return validFileExtensions.contains(fileExtension) } }
mit
6257fa8d7303c2909e988cc8d46b28aa
37.982906
196
0.580136
5.180992
false
false
false
false
beallej/krlx-app
KRLX/KRLX/RecentlyHeardTableViewController.swift
1
4933
// // RecentlyHeardTableViewController.swift // KRLX // // This file handles all things associated the recently heard view where users can view the last five songs that were played by the DJ(s). // Created by Josie Bealle, Phuong Dinh, Maraki Ketema, Naomi Yamamoto// Copyright (c) 2015 AppCoda. All rights reserved. //// import UIKit class RecentlyHeardTableViewController: UITableViewController, PlayPause { @IBOutlet weak var menuButton:UIBarButtonItem! @IBOutlet weak var spinnyWidget: UIActivityIndicatorView! var scraper : ScrapeAssistant! var buttonPlay: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton var buttonPause: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton var appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate override func viewDidLoad() { super.viewDidLoad() self.appDelegate.setUpPlayPause(self) //Connect to menu self.appDelegate.setUpSWRevealVC(self, menuButton: self.menuButton) // Hide empty cells self.tableView.tableFooterView = UIView() //pull to refresh power! //http://www.andrewcbancroft.com/2015/03/17/basics-of-pull-to-refresh-for-swift-developers/ self.refreshControl?.tintColor = UIColor.grayColor() self.refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged) //Pull songs from server, load into table self.scraper = ScrapeAssistant() self.loadSongs() } //Pull to refresh func handleRefresh(refreshControl: UIRefreshControl) { self.loadSongs() } //Pull songs from server asynchronously and puts them in table func loadSongs(){ dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { self.scraper.scrapeRecentlyHeard() dispatch_async(dispatch_get_main_queue()) { self.spinnyWidget.stopAnimating() self.tableView.reloadData() //This has to be set here, after the tableview has been loaded, as opposed to as within viewDidLoad/willAppear/didAppear (at those points, the tableview has not yet been loaded because we're loading it asynchronously) self.refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh") if (self.refreshControl!.refreshing) { self.refreshControl?.endRefreshing() } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return appDelegate.loadedSongHeaders.count } //popoulate table override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell : UITableViewCell! let song = appDelegate.loadedSongHeaders[indexPath.row] as! SongHeader //The one with the album art if indexPath.row == 0{ var cell = tableView.dequeueReusableCellWithIdentifier("firstSong", forIndexPath: indexPath) as! FirstSongTableViewCell cell.title.text = song.getTitle() cell.artist.text = song.getArtist() //if returns nil, this should not be the first song! if let url = song.getURL(){ let cellImage = UIImage(data: NSData(contentsOfURL: NSURL(string: url)!)!) cell.albumArt.image = cellImage } return cell } //Other songs else{ var cell = tableView.dequeueReusableCellWithIdentifier("otherSong", forIndexPath: indexPath) as! OtherSongTableViewCell cell.title.text = song.getTitle() cell.artist.text = song.getArtist() return cell } } //Needed because first cell is bigger to fit the album art override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0{ return 100 } else{ return 50 } } @IBAction func musicButtonClicked(sender: AnyObject) { self.appDelegate.musicButtonClicked(self) } }
mit
7662968ee6cb09de73f67edf26d3321d
34.489209
233
0.628015
5.242295
false
false
false
false
black-lotus/dnCalendar-iOS
dnCalendar/DNCalendarMenuDayView.swift
1
2697
// // DNCalendarMenuDayView.swift // dnCalendar // // Created by romdoni agung purbayanto on 5/16/16. // Copyright © 2016 romdoni agung purbayanto. All rights reserved. // import UIKit class DNCalendarMenuDayView: UIView { var dataSource: DNCalendarMenuDataSource! func build() { var dayNames: Array<String> = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday"] if let customDayNames: Array<String> = dataSource.dnCalendarMenuDayNames() { dayNames = customDayNames } var x: CGFloat = 0 var y: CGFloat = 0 var offset: CGFloat = 0 // custom offset if let customOffset: CGFloat = dataSource.dnCalendarMenuDayOffset() { offset = customOffset y = customOffset } let width: CGFloat = (self.frame.size.width/7) - offset for i in 0..<dayNames.count { let view: UIView = UIView(frame: CGRectMake(x, y, width, self.frame.size.height - (offset * 2))) view.backgroundColor = UIColor.whiteColor() // custom background color if let customBackgroundColor: UIColor = dataSource.dnCalendarMenuBackgroundColor() { view.backgroundColor = customBackgroundColor } let label: UILabel = UILabel(frame: CGRectMake(0, 0, width, self.frame.size.height - (offset * 2))) label.textAlignment = NSTextAlignment.Center label.text = "\(dayNames[i])" // set font if let customFont: UIFont = dataSource.dnCalendarMenuFont() { label.font = customFont } // set label color if let labelColor: UIColor = dataSource.dnCalendarMenuLabelColor() { label.textColor = labelColor } // validate holiday if let holidays: Array<DNCalendarDayName> = dataSource.dnCalendarMenuHolidayWeeks() { for j in 0..<holidays.count { let dayIndex: Int = holidays[j].rawValue if dayIndex == i { if let holidayLabelColor: UIColor = dataSource.dnCalendarMenuHolidayLabelColor() { label.textColor = holidayLabelColor } break } } } view.addSubview(label) self.addSubview(view) x = x + width + offset } } }
apache-2.0
7dd882313ba04bf44a609825f0d5b385
32.283951
116
0.521884
5.11575
false
false
false
false
apatronl/Left
Pods/Nuke/Sources/Nuke.swift
2
3120
// The MIT License (MIT) // // Copyright (c) 2016 Alexander Grebenyuk (github.com/kean). import Foundation #if os(macOS) import AppKit.NSImage /// Alias for NSImage public typealias Image = NSImage #else import UIKit.UIImage /// Alias for UIImage public typealias Image = UIImage #endif /// Loads an image into the given target. /// /// For more info see `loadImage(with:into:)` method of `Manager`. public func loadImage(with url: URL, into target: Target) { Manager.shared.loadImage(with: url, into: target) } /// Loads an image into the given target. /// /// For more info see `loadImage(with:into:)` method of `Manager`. public func loadImage(with request: Request, into target: Target) { Manager.shared.loadImage(with: request, into: target) } /// Loads an image and calls the given `handler`. The method itself /// **doesn't do** anything when the image is loaded - you have full /// control over how to display it, etc. /// /// The handler only gets called if the request is still associated with the /// `target` by the time it's completed. /// /// See `loadImage(with:into:)` method for more info. public func loadImage(with url: URL, into target: AnyObject, handler: @escaping Manager.Handler) { Manager.shared.loadImage(with: url, into: target, handler: handler) } /// Loads an image and calls the given `handler`. /// /// For more info see `loadImage(with:into:handler:)` method of `Manager`. public func loadImage(with request: Request, into target: AnyObject, handler: @escaping Manager.Handler) { Manager.shared.loadImage(with: request, into: target, handler: handler) } /// Cancels an outstanding request associated with the target. public func cancelRequest(for target: AnyObject) { Manager.shared.cancelRequest(for: target) } public extension Manager { /// Shared `Manager` instance. /// /// Shared manager is created with `Loader.shared` and `Cache.shared`. public static var shared = Manager(loader: Loader.shared, cache: Cache.shared) } public extension Loader { /// Shared `Loading` object. /// /// Shared loader is created with `DataLoader()`, `DataDecoder()` and // `Cache.shared`. The resulting loader is wrapped in a `Deduplicator`. public static var shared: Loading = Deduplicator(loader: Loader(loader: DataLoader(), decoder: DataDecoder(), cache: Cache.shared)) } public extension Cache { /// Shared `Cache` instance. public static var shared = Cache() } internal final class Lock { var mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1) init() { pthread_mutex_init(mutex, nil) } deinit { pthread_mutex_destroy(mutex) mutex.deinitialize() mutex.deallocate(capacity: 1) } /// In critical places it's better to use lock() and unlock() manually func sync<T>(_ closure: (Void) -> T) -> T { pthread_mutex_lock(mutex) defer { pthread_mutex_unlock(mutex) } return closure() } func lock() { pthread_mutex_lock(mutex) } func unlock() { pthread_mutex_unlock(mutex) } }
mit
840d974277d450d7afa663c0ee78e3de
31.164948
135
0.68109
4.020619
false
false
false
false
eyehook/Test
Test/GameViewController.swift
1
1393
// // GameViewController.swift // Test // // Created on 8/2/17. // Copyright © 2017 Eyehook Games LLC. All rights reserved. // MIT License // import UIKit import SpriteKit import GameplayKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let view = self.view as! SKView? { // Load the SKScene from 'GameScene.sks' if let scene = SKScene(fileNamed: "GameScene") { // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFill // Present the scene view.presentScene(scene) } view.ignoresSiblingOrder = true view.showsFPS = true view.showsNodeCount = true } } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override var prefersStatusBarHidden: Bool { return true } }
mit
8faf937221281f5403e4621257915d4f
23.857143
77
0.576868
5.4375
false
false
false
false
gribozavr/swift
test/NameBinding/reference-dependencies-fine.swift
1
23867
// REQUIRES: shell // Also uses awk: // XFAIL OS=windows // RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-swift-frontend -enable-fine-grained-dependencies -typecheck -primary-file %t/main.swift %S/Inputs/reference-dependencies-helper.swift -emit-reference-dependencies-path - > %t.swiftdeps // Check that the output is deterministic. // RUN: %target-swift-frontend -enable-fine-grained-dependencies -typecheck -primary-file %t/main.swift %S/Inputs/reference-dependencies-helper.swift -emit-reference-dependencies-path - > %t-2.swiftdeps // Merge each entry onto one line and sort to overcome order differences // RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps // RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh <%t-2.swiftdeps >%t-2-processed.swiftdeps // RUN: diff %t-processed.swiftdeps %t-2-processed.swiftdeps // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t-processed.swiftdeps // RUN: %FileCheck %s -check-prefix=CHECK-TOPLEVEL < %t-processed.swiftdeps // RUN: %FileCheck %s -check-prefix=CHECK-MEMBER < %t-processed.swiftdeps // RUN: %FileCheck %s -check-prefix=CHECK-NOMINAL < %t-processed.swiftdeps // RUN: %FileCheck %s -check-prefix=CHECK-NOMINAL-2 < %t-processed.swiftdeps // RUN: %FileCheck %s -check-prefix=CHECK-POTENTIALMEMBER < %t-processed.swiftdeps // CHECK-TOPLEVEL-DAG: topLevel interface '' IntWrapper true // CHECK-TOPLEVEL-DAG: topLevel interface '' '==' true // CHECK-TOPLEVEL-DAG: topLevel interface '' '<' true // CHECK-TOPLEVEL-DAG: topLevel interface '' '***' true // CHECK-TOPLEVEL-DAG: topLevel interface '' ^^^ true // CHECK-TOPLEVEL-DAG: topLevel interface '' Subclass true // CHECK-TOPLEVEL-DAG: topLevel interface '' MyArray true // CHECK-TOPLEVEL-DAG: topLevel interface '' someGlobal true // CHECK-TOPLEVEL-DAG: topLevel interface '' ExpressibleByExtraFloatLiteral true // CHECK-TOPLEVEL-DAG: topLevel interface '' ThreeTilde true // CHECK-TOPLEVEL-DAG: topLevel interface '' overloadedOnProto true // CHECK-TOPLEVEL-DAG: topLevel interface '' FourTilde true // CHECK-TOPLEVEL-DAG: topLevel interface '' FourTildeImpl true // CHECK-TOPLEVEL-DAG: topLevel interface '' FiveTildeImpl true // CHECK-TOPLEVEL-DAG: topLevel interface '' topLevelComputedProperty true // CHECK-TOPLEVEL-DAG: topLevel interface '' lookUpManyTopLevelNames true // CHECK-TOPLEVEL-DAG: topLevel interface '' testOperators true // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelForMemberLookup true // CHECK-TOPLEVEL-DAG: topLevel interface '' lookUpMembers true // CHECK-TOPLEVEL-DAG: topLevel interface '' publicUseOfMember true // CHECK-TOPLEVEL-DAG: topLevel interface '' Outer true // CHECK-TOPLEVEL-DAG: topLevel interface '' eof true // CHECK-TOPLEVEL-DAG: topLevel interface '' '~~~' true // CHECK-TOPLEVEL-DAG: topLevel interface '' '~~~~' true // CHECK-TOPLEVEL-DAG: topLevel interface '' '~~~~~' true // CHECK-TOPLEVEL-DAG: topLevel implementation '' IntWrapper true // CHECK-TOPLEVEL-DAG: topLevel implementation '' '==' true // CHECK-TOPLEVEL-DAG: topLevel implementation '' '<' true // CHECK-TOPLEVEL-DAG: topLevel implementation '' '***' true // CHECK-TOPLEVEL-DAG: topLevel implementation '' ^^^ true // CHECK-TOPLEVEL-DAG: topLevel implementation '' Subclass true // CHECK-TOPLEVEL-DAG: topLevel implementation '' MyArray true // CHECK-TOPLEVEL-DAG: topLevel implementation '' someGlobal true // CHECK-TOPLEVEL-DAG: topLevel implementation '' ExpressibleByExtraFloatLiteral true // CHECK-TOPLEVEL-DAG: topLevel implementation '' ThreeTilde true // CHECK-TOPLEVEL-DAG: topLevel implementation '' overloadedOnProto true // CHECK-TOPLEVEL-DAG: topLevel implementation '' FourTilde true // CHECK-TOPLEVEL-DAG: topLevel implementation '' FourTildeImpl true // CHECK-TOPLEVEL-DAG: topLevel implementation '' FiveTildeImpl true // CHECK-TOPLEVEL-DAG: topLevel implementation '' topLevelComputedProperty true // CHECK-TOPLEVEL-DAG: topLevel implementation '' lookUpManyTopLevelNames true // CHECK-TOPLEVEL-DAG: topLevel implementation '' testOperators true // CHECK-TOPLEVEL-DAG: topLevel implementation '' TopLevelForMemberLookup true // CHECK-TOPLEVEL-DAG: topLevel implementation '' lookUpMembers true // CHECK-TOPLEVEL-DAG: topLevel implementation '' publicUseOfMember true // CHECK-TOPLEVEL-DAG: topLevel implementation '' Outer true // CHECK-TOPLEVEL-DAG: topLevel implementation '' eof true // CHECK-TOPLEVEL-DAG: topLevel implementation '' '~~~' true // CHECK-TOPLEVEL-DAG: topLevel implementation '' '~~~~' true // CHECK-TOPLEVEL-DAG: topLevel implementation '' '~~~~~' true // CHECK-NOMINAL-DAG: nominal interface 4main10IntWrapperV '' true // CHECK-NOMINAL-DAG: nominal interface 4main10IntWrapperV16InnerForNoReasonV '' true // CHECK-NOMINAL-DAG: nominal interface 4main8SubclassC '' true // CHECK-NOMINAL-DAG: nominal interface Sb4mainE11InnerToBoolV '' true // CHECK-NOMINAL-DAG: nominal interface 4main9Sentinel1V '' true // CHECK-NOMINAL-DAG: nominal interface 4main9Sentinel2V '' true // CHECK-NOMINAL-DAG: nominal implementation 4main10IntWrapperV '' true // CHECK-NOMINAL-DAG: nominal implementation 4main10IntWrapperV16InnerForNoReasonV '' true // CHECK-NOMINAL-DAG: nominal implementation 4main8SubclassC '' true // CHECK-NOMINAL-DAG: nominal implementation Sb4mainE11InnerToBoolV '' true // CHECK-NOMINAL-DAG: nominal implementation 4main9Sentinel1V '' true // CHECK-NOMINAL-DAG: nominal implementation 4main9Sentinel2V '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main10IntWrapperV '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main10IntWrapperV16InnerForNoReasonV '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main8SubclassC '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember interface s25ExpressibleByArrayLiteralP '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember interface Sb '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember interface Sb4mainE11InnerToBoolV '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main9Sentinel1V '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main9Sentinel2V '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember implementation 4main10IntWrapperV '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember implementation 4main10IntWrapperV16InnerForNoReasonV '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember implementation 4main8SubclassC '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember implementation s25ExpressibleByArrayLiteralP '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember implementation Sb '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember implementation Sb4mainE11InnerToBoolV '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember implementation 4main9Sentinel1V '' true // CHECK-POTENTIALMEMBER-DAG: potentialMember implementation 4main9Sentinel2V '' true // CHECK-MEMBER-DAG: member interface s25ExpressibleByArrayLiteralP useless true // CHECK-MEMBER-DAG: member interface s25ExpressibleByArrayLiteralP useless2 true // CHECK-MEMBER-DAG: member interface Sb InnerToBool true // CHECK-MEMBER-DAG: member interface {{.*[0-9]}}FourTildeImplV '~~~~' true // CHECK-MEMBER-DAG: member interface {{.*[0-9]}}FiveTildeImplV '~~~~~' true // CHECK-MEMBER-DAG: member implementation s25ExpressibleByArrayLiteralP useless true // CHECK-MEMBER-DAG: member implementation s25ExpressibleByArrayLiteralP useless2 true // CHECK-MEMBER-DAG: member implementation Sb InnerToBool true // CHECK-MEMBER-DAG: member implementation {{.*[0-9]}}FourTildeImplV '~~~~' true // CHECK-MEMBER-DAG: member implementation {{.*[0-9]}}FiveTildeImplV '~~~~~' true // CHECK-TOPLEVEL-DAG: topLevel interface '' Comparable false struct IntWrapper: Comparable { // CHECK-TOPLEVEL-DAG: topLevel interface '' Int false var value: Int struct InnerForNoReason {} // CHECK-TOPLEVEL-DAG: topLevel interface '' TypeReferencedOnlyBySubscript false subscript(_: TypeReferencedOnlyBySubscript) -> Void { return () } // CHECK-TOPLEVEL-DAG: topLevel interface '' TypeReferencedOnlyByPrivateSubscript false private subscript(_: TypeReferencedOnlyByPrivateSubscript) -> Void { return () } } // CHECK-TOPLEVEL-DAG: topLevel interface '' Bool false func ==(lhs: IntWrapper, rhs: IntWrapper) -> Bool { return lhs.value == rhs.value } func <(lhs: IntWrapper, rhs: IntWrapper) -> Bool { return lhs.value < rhs.value } // Test operator lookup without a use of the same operator. // This is declared in the other file. prefix func ***(lhs: IntWrapper) {} // This is provided as an operator but not implemented here. prefix operator ^^^ // CHECK-TOPLEVEL-DAG: topLevel interface '' ClassFromOtherFile false class Subclass : ClassFromOtherFile {} // CHECK-TOPLEVEL-DAG: topLevel interface '' Array false typealias MyArray = Array<Bool> // CHECK-TOPLEVEL-DAG: topLevel interface '' ExpressibleByArrayLiteral false extension ExpressibleByArrayLiteral { func useless() {} } // CHECK-TOPLEVEL-DAG: topLevel interface '' OtherFileElementType false extension ExpressibleByArrayLiteral where ArrayLiteralElement == OtherFileElementType { func useless2() {} } // CHECK-TOPLEVEL-DAG: topLevel interface '' IntegerLiteralType false let someGlobal = 42 extension Bool { struct InnerToBool {} } // CHECK-TOPLEVEL-DAG: topLevel interface '' ExpressibleByOtherFileAliasForFloatLiteral false protocol ExpressibleByExtraFloatLiteral : ExpressibleByOtherFileAliasForFloatLiteral { } // CHECK-TOPLEVEL-DAG: topLevel interface '' ExpressibleByUnicodeScalarLiteral false private protocol ExpressibleByExtraCharLiteral : ExpressibleByUnicodeScalarLiteral { } prefix operator ~~~ protocol ThreeTilde { prefix static func ~~~(lhs: Self) } private struct ThreeTildeTypeImpl : ThreeTilde { } func overloadedOnProto<T>(_: T) {} func overloadedOnProto<T: ThreeTilde>(_: T) {} private prefix func ~~~(_: ThreeTildeTypeImpl) {} prefix operator ~~~~ protocol FourTilde { prefix static func ~~~~(arg: Self) } struct FourTildeImpl : FourTilde {} extension FourTildeImpl { prefix static func ~~~~(arg: FourTildeImpl) {} } // ~~~~~ is declared in the other file. struct FiveTildeImpl {} extension FiveTildeImpl { prefix static func ~~~~~(arg: FiveTildeImpl) {} } var topLevelComputedProperty: Bool { return true } func lookUpManyTopLevelNames() { // CHECK-TOPLEVEL-DAG: topLevel interface '' Dictionary false let _: Dictionary = [1:1] // CHECK-TOPLEVEL-DAG: topLevel interface '' UInt false // CHECK-TOPLEVEL-DAG: topLevel interface '' '+' false let _: UInt = [1, 2].reduce(0, +) // CHECK-TOPLEVEL-DAG: topLevel interface '' '-' false let _: UInt = 3 - 2 - 1 // CHECK-TOPLEVEL-DAG: topLevel interface '' AliasFromOtherFile false let _: AliasFromOtherFile = 1 // CHECK-TOPLEVEL-DAG: topLevel interface '' funcFromOtherFile false funcFromOtherFile() // "CInt" is not used as a top-level name here. // CHECK-TOPLEVEL-DAG: topLevel interface '' StringLiteralType false // NEGATIVE-NOT: "CInt" _ = "abc" // NEGATIVE-NOT: - "max" print(Int.max) // NEGATIVE-NOT: - "Stride" let _: Int.Stride = 0 // CHECK-TOPLEVEL-DAG: topLevel interface '' OtherFileOuterType false _ = OtherFileOuterType.InnerType.sharedConstant _ = OtherFileOuterType.InnerType() // CHECK-TOPLEVEL-DAG: topLevel interface '' OtherFileAliasForSecret false _ = OtherFileAliasForSecret.constant // CHECK-TOPLEVEL-DAG: topLevel interface '' otherFileUse false // CHECK-TOPLEVEL-DAG: topLevel interface '' otherFileGetImpl false otherFileUse(otherFileGetImpl()) // CHECK-TOPLEVEL-DAG: topLevel interface '' otherFileUseGeneric false // CHECK-TOPLEVEL-DAG: topLevel interface '' otherFileGetImpl2 false otherFileUseGeneric(otherFileGetImpl2()) // CHECK-TOPLEVEL-DAG: topLevel interface '' getOtherFileIntArray false for _ in getOtherFileIntArray() {} // CHECK-TOPLEVEL-DAG: topLevel interface '' getOtherFileEnum false switch getOtherFileEnum() { case .Value: break default: break } _ = .Value as OtherFileEnumWrapper.Enum let _: OtherFileEnumWrapper.Enum = .Value _ = OtherFileEnumWrapper.Enum.Value _ = { (_: PrivateTopLevelStruct.ValueType) -> PrivateTopLevelStruct2.ValueType? in return nil } typealias X = OtherFileEnumWrapper.Enum let value: Any = .Value as X switch value { case is OtherFileEnumWrapper.Enum: break default: break } // CHECK-TOPLEVEL-DAG: topLevel interface '' '~=' false switch 42 { case 50: break default: break } for _: OtherFileEnumWrapper.Enum in EmptyIterator<X>() {} // CHECK-TOPLEVEL-DAG: topLevel interface '' otherFileGetNonImpl false overloadedOnProto(otherFileGetNonImpl()) } func testOperators<T: Starry>(generic: T, specific: Flyswatter) { // CHECK-TOPLEVEL-DAG: topLevel interface '' '****' false // CHECK-TOPLEVEL-DAG: topLevel interface '' '*****' false // CHECK-TOPLEVEL-DAG: topLevel interface '' '******' false ****generic generic*****0 0******generic ****specific specific*****0 0******specific } // CHECK-NOMINAL-DAG: nominal interface 4main23TopLevelForMemberLookupV '' true // CHECK-NOMINAL-DAG: nominal implementation 4main23TopLevelForMemberLookupV '' true struct TopLevelForMemberLookup { static func m1() {} static func m2() {} static func m3() {} } func lookUpMembers() { TopLevelForMemberLookup.m1() TopLevelForMemberLookup.m3() } public let publicUseOfMember: () = TopLevelForMemberLookup.m2() struct Outer { struct Inner { func method() { // CHECK-TOPLEVEL-DAG: topLevel interface '' CUnsignedInt false let _: CUnsignedInt = 5 } } } // CHECK-TOPLEVEL-DAG: topLevel interface '' privateFunc false private func privateFunc() {} // CHECK-TOPLEVEL-DAG: topLevel interface '' topLevel1 false var use1 = topLevel1() // CHECK-TOPLEVEL-DAG: topLevel interface '' topLevel2 false var use2 = { topLevel2() } // CHECK-TOPLEVEL-DAG: topLevel interface '' topLevel3 false var use3 = { ({ topLevel3() })() } // CHECK-TOPLEVEL-DAG: topLevel interface '' topLevel4 false // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelProto1 false struct Use4 : TopLevelProto1 { var use4 = topLevel4() } // CHECK-TOPLEVEL-DAG: topLevel interface '' '*' false _ = 42 * 30 // FIXME: Incorrectly marked non-private dependencies // CHECK-TOPLEVEL-DAG: topLevel interface '' topLevel6 false _ = topLevel6() // CHECK-TOPLEVEL-DAG: topLevel interface '' topLevel7 false private var use7 = topLevel7() // CHECK-TOPLEVEL-DAG: topLevel interface '' topLevel8 false var use8: Int = topLevel8() // CHECK-TOPLEVEL-DAG: topLevel interface '' topLevel9 false var use9 = { () -> Int in return topLevel9() } // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelTy1 false func useTy1(_ x: TopLevelTy1) {} // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelTy2 false func useTy2() -> TopLevelTy2 {} // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelTy3 false // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelProto2 false extension Use4 : TopLevelProto2 { var useTy3: TopLevelTy3? { return nil } } // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelStruct false // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelStruct2 false let useTy4 = { (_: TopLevelStruct.ValueType) -> TopLevelStruct2.ValueType? in return nil } // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelStruct3 false // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelStruct4 false typealias useTy5 = TopLevelStruct3.ValueType let useTy6: TopLevelStruct4.ValueType = 0 struct StructForDeclaringProperties { // CHECK-TOPLEVEL-DAG: topLevel interface '' TopLevelStruct5 false var prop: TopLevelStruct5.ValueType { return 0 } } // CHECK-TOPLEVEL-DAG: topLevel interface '' privateTopLevel1 false func private1(_ a: Int = privateTopLevel1()) {} // CHECK-TOPLEVEL-DAG: topLevel interface '' privateTopLevel2 false // CHECK-TOPLEVEL-DAG: topLevel interface '' PrivateProto1 false private struct Private2 : PrivateProto1 { var private2 = privateTopLevel2() } // CHECK-TOPLEVEL-DAG: topLevel interface '' privateTopLevel3 false func outerPrivate3() { let _ = { privateTopLevel3() } } // CHECK-TOPLEVEL-DAG: topLevel interface '' PrivateTopLevelTy1 false private extension Use4 { var privateTy1: PrivateTopLevelTy1? { return nil } } // CHECK-TOPLEVEL-DAG: topLevel interface '' PrivateTopLevelTy2 false // CHECK-TOPLEVEL-DAG: topLevel interface '' PrivateProto2 false extension Private2 : PrivateProto2 { // FIXME: This test is supposed to check that we get this behavior /without/ // marking the property private, just from the base type. private var privateTy2: PrivateTopLevelTy2? { return nil } } // CHECK-TOPLEVEL-DAG: topLevel interface '' PrivateTopLevelTy3 false func outerPrivateTy3() { func inner(_ a: PrivateTopLevelTy3?) {} inner(nil) } // CHECK-TOPLEVEL-DAG: topLevel interface '' PrivateTopLevelStruct3 false private typealias PrivateTy4 = PrivateTopLevelStruct3.ValueType // CHECK-TOPLEVEL-DAG: topLevel interface '' PrivateTopLevelStruct4 false private func privateTy5(_ x: PrivateTopLevelStruct4.ValueType) -> PrivateTopLevelStruct4.ValueType { return x } // Deliberately empty. private struct PrivateTy6 {} // CHECK-TOPLEVEL-DAG: topLevel interface '' PrivateProto3 false extension PrivateTy6 : PrivateProto3 {} // CHECK-TOPLEVEL-DAG: topLevel interface '' ProtoReferencedOnlyInGeneric false func genericTest<T: ProtoReferencedOnlyInGeneric>(_: T) {} // CHECK-TOPLEVEL-DAG: topLevel interface '' ProtoReferencedOnlyInPrivateGeneric false private func privateGenericTest<T: ProtoReferencedOnlyInPrivateGeneric>(_: T) {} struct PrivateStoredProperty { // CHECK-TOPLEVEL-DAG: topLevel interface '' TypeReferencedOnlyByPrivateVar false private var value: TypeReferencedOnlyByPrivateVar } class PrivateStoredPropertyRef { // CHECK-TOPLEVEL-DAG: topLevel interface '' TypeReferencedOnlyByPrivateClassVar false private var value: TypeReferencedOnlyByPrivateClassVar? } struct Sentinel1 {} private protocol ExtensionProto {} extension OtherFileTypeToBeExtended : ExtensionProto { private func foo() {} } private extension OtherFileTypeToBeExtended { var bar: Bool { return false } } struct Sentinel2 {} // CHECK-MEMBER-DAG: member interface 4main10IntWrapperV Int false // CHECK-MEMBER-DAG: member interface 4main10IntWrapperV deinit false // CHECK-POTENTIALMEMBER-DAG: potentialMember interface SL '' false // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main18ClassFromOtherFileC '' false // CHECK-MEMBER-DAG: member interface Si max false // CHECK-POTENTIALMEMBER-DAG: potentialMember interface s25ExpressibleByFloatLiteralP '' false // CHECK-POTENTIALMEMBER-DAG: potentialMember interface s33ExpressibleByUnicodeScalarLiteralP '' false // CHECK-MEMBER-DAG: member interface Sx Stride false // CHECK-MEMBER-DAG: member interface Sa reduce false // CHECK-MEMBER-DAG: member interface 4main17OtherFileIntArrayV deinit false // CHECK-MEMBER-DAG: member interface 4main18OtherFileOuterTypeV InnerType false // CHECK-MEMBER-DAG: member interface 4main18OtherFileOuterTypeV05InnerE0V init false // CHECK-MEMBER-DAG: member interface 4main18OtherFileOuterTypeV05InnerE0V sharedConstant false // CHECK-MEMBER-DAG: member interface 4main26OtherFileSecretTypeWrapperV0dE0V constant false // CHECK-MEMBER-DAG: member interface 4main25OtherFileProtoImplementorV deinit false // CHECK-MEMBER-DAG: member interface 4main26OtherFileProtoImplementor2V deinit false // CHECK-MEMBER-DAG: member interface s15EmptyCollectionV8IteratorV init false // CHECK-MEMBER-DAG: member interface 4main13OtherFileEnumO Value false // CHECK-MEMBER-DAG: member interface 4main20OtherFileEnumWrapperV Enum false // CHECK-MEMBER-DAG: member interface 4main14TopLevelStructV ValueType false // CHECK-MEMBER-DAG: member interface 4main15TopLevelStruct2V ValueType false // CHECK-MEMBER-DAG: member interface 4main15TopLevelStruct3V ValueType false // CHECK-MEMBER-DAG: member interface 4main15TopLevelStruct4V ValueType false // CHECK-MEMBER-DAG: member interface 4main15TopLevelStruct5V ValueType false // CHECK-MEMBER-DAG: member interface 4main21PrivateTopLevelStructV ValueType false // CHECK-MEMBER-DAG: member interface 4main22PrivateTopLevelStruct2V ValueType false // CHECK-MEMBER-DAG: member interface 4main22PrivateTopLevelStruct3V ValueType false // CHECK-MEMBER-DAG: member interface 4main22PrivateTopLevelStruct4V ValueType false // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main14TopLevelProto1P '' false // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main14TopLevelProto2P '' false // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main13PrivateProto1P '' false // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main13PrivateProto2P '' false // CHECK-POTENTIALMEMBER-DAG: potentialMember interface 4main13PrivateProto3P '' false // CHECK-NOMINAL-2-DAG: nominal interface Sa '' false // CHECK-NOMINAL-2-DAG: nominal interface Sb '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main18ClassFromOtherFileC '' false // CHECK-NOMINAL-2-DAG: nominal interface SL '' false // CHECK-NOMINAL-2-DAG: nominal interface s25ExpressibleByFloatLiteralP '' false // CHECK-NOMINAL-2-DAG: nominal interface s33ExpressibleByUnicodeScalarLiteralP '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main18OtherFileOuterTypeV05InnerE0V '' false // CHECK-NOMINAL-2-DAG: nominal interface Si '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main13OtherFileEnumO '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main20OtherFileEnumWrapperV '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main17OtherFileIntArrayV '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main18OtherFileOuterTypeV '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main25OtherFileProtoImplementorV '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main26OtherFileProtoImplementor2V '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main13PrivateProto1P '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main13PrivateProto2P '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main13PrivateProto3P '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main21PrivateTopLevelStructV '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main22PrivateTopLevelStruct2V '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main22PrivateTopLevelStruct3V '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main22PrivateTopLevelStruct4V '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main26OtherFileSecretTypeWrapperV0dE0V '' false // CHECK-NOMINAL-2-DAG: nominal interface Sx '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main14TopLevelProto1P '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main14TopLevelProto2P '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main14TopLevelStructV '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main15TopLevelStruct2V '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main15TopLevelStruct3V '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main15TopLevelStruct4V '' false // CHECK-NOMINAL-2-DAG: nominal interface 4main15TopLevelStruct5V '' false // String is not used anywhere in this file, though a string literal is. // NEGATIVE-NOT: "String" // These are used by the other file in this module, but not by this one. // NEGATIVE-NOT: "ExpressibleByFloatLiteral" // NEGATIVE-NOT: "Int16" // NEGATIVE-NOT: "OtherFileProto" // NEGATIVE-NOT: "OtherFileProtoImplementor" // NEGATIVE-NOT: "OtherFileProto2" // NEGATIVE-NOT: "OtherFileProtoImplementor2" // OtherFileSecretTypeWrapper is never used directly in this file. // NEGATIVE-NOT: "OtherFileSecretTypeWrapper" // NEGATIVE-NOT: "4main26OtherFileSecretTypeWrapperV" let eof: () = ()
apache-2.0
8f8de3f1943c18716582edc0c62a32a3
42.792661
202
0.76369
3.973859
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift
21
1609
// // ByteExtension.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 07/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // #if os(Linux) || os(Android) || os(FreeBSD) import Glibc #else import Darwin #endif public protocol _UInt8Type {} extension UInt8: _UInt8Type {} /** casting */ extension UInt8 { /** cast because UInt8(<UInt32>) because std initializer crash if value is > byte */ static func with(value: UInt64) -> UInt8 { let tmp = value & 0xFF return UInt8(tmp) } static func with(value: UInt32) -> UInt8 { let tmp = value & 0xFF return UInt8(tmp) } static func with(value: UInt16) -> UInt8 { let tmp = value & 0xFF return UInt8(tmp) } } /** Bits */ extension UInt8 { init(bits: [Bit]) { self.init(integerFrom(bits) as UInt8) } /** array of bits */ func bits() -> [Bit] { let totalBitsCount = MemoryLayout<UInt8>.size * 8 var bitsArray = [Bit](repeating: Bit.zero, count: totalBitsCount) for j in 0 ..< totalBitsCount { let bitVal: UInt8 = 1 << UInt8(totalBitsCount - 1 - j) let check = self & bitVal if (check != 0) { bitsArray[j] = Bit.one } } return bitsArray } func bits() -> String { var s = String() let arr: [Bit] = self.bits() for idx in arr.indices { s += (arr[idx] == Bit.one ? "1" : "0") if (idx.advanced(by: 1) % 8 == 0) { s += " " } } return s } }
mit
9b3b9f1eb7f6cde723efe06bf954bfb7
21.661972
88
0.535115
3.536264
false
false
false
false
SoneeJohn/WWDC
WWDC/RemoteEnvironment.swift
1
3567
// // RemoteEnvironment.swift // WWDC // // Created by Guilherme Rambo on 21/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Foundation import CloudKit import ConfCore final class RemoteEnvironment: NSObject { private struct Constants { static let environmentRecordType = "Environment" static let subscriptionDefaultsName = "remoteEnvironmentSubscriptionID" } private lazy var container: CKContainer = CKContainer.default() private lazy var database: CKDatabase = { return self.container.publicCloudDatabase }() static let shared: RemoteEnvironment = RemoteEnvironment() func start() { #if ICLOUD guard !Arguments.disableRemoteEnvironment else { return } fetch() createSubscriptionIfNeeded() #endif } private func fetch() { #if ICLOUD let query = CKQuery(recordType: Constants.environmentRecordType, predicate: NSPredicate(value: true)) let operation = CKQueryOperation(query: query) operation.recordFetchedBlock = { record in guard let env = Environment(record) else { NSLog("Error parsing remote environment") return } Environment.setCurrent(env) } operation.queryCompletionBlock = { [unowned self] _, error in if let error = error { NSLog("Error fetching remote environment: \(error)") DispatchQueue.main.asyncAfter(deadline: .now() + 10) { self.fetch() } } } database.add(operation) #endif } private let environmentSubscriptionID = "REMOTE-ENVIRONMENT" private func createSubscriptionIfNeeded() { CloudKitHelper.subscriptionExists(with: environmentSubscriptionID, in: database) { [unowned self] exists in if !exists { self.doCreateSubscription() } } } private func doCreateSubscription() { let options: CKQuerySubscriptionOptions = [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion] let subscription = CKQuerySubscription(recordType: Constants.environmentRecordType, predicate: NSPredicate(value: true), subscriptionID: environmentSubscriptionID, options: options) database.save(subscription) { _, error in if let error = error { NSLog("[RemoteEnvironment] Error creating subscription: \(error)") } } } func processSubscriptionNotification(with userInfo: [String : Any]) -> Bool { let notification = CKNotification(fromRemoteNotificationDictionary: userInfo) // check if the remote notification is for us, if not, tell the caller that we haven't handled it guard notification.subscriptionID == environmentSubscriptionID else { return false } // notification for environment change fetch() return true } } extension Environment { init?(_ record: CKRecord) { guard let baseURLStr = record["baseURL"] as? String, URL(string: baseURLStr) != nil else { return nil } baseURL = baseURLStr videosPath = "/videos.json" liveVideosPath = "/videos_live.json" newsPath = "/news.json" sessionsPath = "/sessions.json" } }
bsd-2-clause
55bc87d81f3d74a3671e6250485d00fe
30.557522
120
0.606562
5.486154
false
false
false
false
Baglan/MCResource
Classes/BackgroundDownloadHelper.swift
1
3535
// // BackgroundDownloadHelper.swift // MCResourceLoader // // Created by Baglan on 08/11/2016. // Copyright © 2016 Mobile Creators. All rights reserved. // import Foundation class BackgroundDownloadHelper: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDownloadDelegate { static let defaultSessionId = "BackgroundDownloadHelper" static var completionHandler: (() -> Void)? fileprivate var session: URLSession! let sessionId: String init(sessionId: String) { self.sessionId = sessionId super.init() let configuration = URLSessionConfiguration.background(withIdentifier: sessionId) session = URLSession( configuration: configuration, delegate: self, delegateQueue: nil ) } // MARK: - Managing downloads var urls = [URL:Set<URL>]() var completionHandlers = [URL: [(Error?) -> Void]]() func download(from: URL, to: URL, completionHandler: @escaping (Error?) -> Void) { var handlers = completionHandlers[from] ?? [(Error?) -> Void]() handlers.append(completionHandler) completionHandlers[from] = handlers var localUrls = urls[from] ?? Set<URL>() localUrls.insert(to) urls[from] = localUrls startNewTasks() } func startNewTasks() { session.getAllTasks { [unowned self] (tasks) in let taskUrls = tasks.map({ (task) -> URL? in return task.originalRequest?.url }) for url in taskUrls { if let url = url, !self.urls.keys.contains(url) { self.session.downloadTask(with: url) } } } } // MARK: - URLSessionDelegate func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { if let completionHandler = type(of: self).completionHandler { OperationQueue.main.addOperation { completionHandler() } } type(of: self).completionHandler = nil } // MARK: - URLSessionDownloadDelegate func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let url = downloadTask.originalRequest?.url else { return } do { // Store donwloaded file if var localUrls = urls[url], let firstUrl = localUrls.popFirst() { // Move to first try FileManager.default.moveItem(at: location, to: firstUrl) // Copy from first to the rest for localUrl in localUrls { try FileManager.default.copyItem(at: firstUrl, to: localUrl) } } // Call completion handlers if let handlers = self.completionHandlers[url] { for handler in handlers { handler(nil) } } } catch { NSLog("[\(String(describing: type(of: self)))] \(error.localizedDescription)") } } // MARK: - URLSessionTaskDelegate func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { } // MARK: - Shared instance static let sharedInstance = BackgroundDownloadHelper(sessionId: BackgroundDownloadHelper.defaultSessionId) }
mit
19d95eef75cea64392c06afd791d3970
31.127273
120
0.576118
5.453704
false
false
false
false
BenEmdon/swift-algorithm-club
Merge Sort/MergeSort.playground/Contents.swift
1
2304
/* Top-down recursive version */ func mergeSort(_ array: [Int]) -> [Int] { guard array.count > 1 else { return array } let middleIndex = array.count / 2 let leftArray = mergeSort(Array(array[0..<middleIndex])) let rightArray = mergeSort(Array(array[middleIndex..<array.count])) return merge(leftPile: leftArray, rightPile: rightArray) } func merge(leftPile: [Int], rightPile: [Int]) -> [Int] { var leftIndex = 0 var rightIndex = 0 var orderedPile = [Int]() while leftIndex < leftPile.count && rightIndex < rightPile.count { if leftPile[leftIndex] < rightPile[rightIndex] { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 } else if leftPile[leftIndex] > rightPile[rightIndex] { orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } else { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } } while leftIndex < leftPile.count { orderedPile.append(leftPile[leftIndex]) leftIndex += 1 } while rightIndex < rightPile.count { orderedPile.append(rightPile[rightIndex]) rightIndex += 1 } return orderedPile } let array = [2, 1, 5, 4, 9] let sortedArray = mergeSort(array) /* Bottom-up iterative version */ func mergeSortBottomUp<T>(_ a: [T], _ isOrderedBefore: (T, T) -> Bool) -> [T] { let n = a.count var z = [a, a] // the two working arrays var d = 0 // z[d] is used for reading, z[1 - d] for writing var width = 1 while width < n { var i = 0 while i < n { var j = i var l = i var r = i + width let lmax = min(l + width, n) let rmax = min(r + width, n) while l < lmax && r < rmax { if isOrderedBefore(z[d][l], z[d][r]) { z[1 - d][j] = z[d][l] l += 1 } else { z[1 - d][j] = z[d][r] r += 1 } j += 1 } while l < lmax { z[1 - d][j] = z[d][l] j += 1 l += 1 } while r < rmax { z[1 - d][j] = z[d][r] j += 1 r += 1 } i += width*2 } width *= 2 // in each step, the subarray to merge becomes larger d = 1 - d // swap active array } return z[d] } mergeSortBottomUp(array, <)
mit
66eda1e5e8fdc7af67273cba41e910f3
22.272727
79
0.555556
3.39823
false
false
false
false
storehouse/Advance
Sources/Advance/Internal/Animation.swift
1
2188
/// Interpolates between values over a specified duration. /// /// - parameter Value: The type of value to be animated. struct Animation<Value: VectorConvertible> { /// The initial value at time 0. let from: Value /// The final value when the animation is finished. let to: Value /// The duration of the animation in seconds. let duration: Double /// The timing function that is used to map elapsed time to an /// interpolated value. let timingFunction: TimingFunction /// The current value. private (set) var value: Value private (set) var velocity: Value private var elapsed: Double = 0.0 /// Creates a new `BasicAnimation` instance. /// /// - parameter from: The value at time `0`. /// - parameter to: The value at the end of the animation. /// - parameter duration: How long (in seconds) the animation should last. /// - parameter timingFunction: The timing function to use. init(from: Value, to: Value, duration: Double, timingFunction: TimingFunction) { self.from = from self.to = to self.duration = duration self.timingFunction = timingFunction self.value = from self.velocity = from self.velocity.animatableData = .zero } /// Returns `true` if the advanced time is `>=` duration. var isFinished: Bool { return elapsed >= duration } /// Advances the animation. /// /// - parameter elapsed: The time (in seconds) to advance the animation. mutating func advance(by time: Double) { let starting = value elapsed += time var progress = elapsed / duration progress = max(progress, 0.0) progress = min(progress, 1.0) let adjustedProgress = timingFunction.solve(at: progress, epsilon: 1.0 / (duration * 1000.0)) value.animatableData = interpolate(from: from.animatableData, to: to.animatableData, alpha: adjustedProgress) var vel = value.animatableData - starting.animatableData vel.scale(by: 1.0/time) velocity.animatableData = vel } }
bsd-2-clause
b4750171a5386012da97420f3822cfb6
31.176471
117
0.622029
4.675214
false
false
false
false
Zig1375/SwiftClickHouse
Sources/SwiftClickHouse/Core/ClickHouseBlock.swift
1
7160
import Foundation public class ClickHouseBlock { let is_overflows : UInt8; let bucket_num : Int32; var columns : [String : [ClickHouseValue]] = [:]; public init(is_overflows : UInt8 = 0, bucket_num : Int32 = -1) { self.is_overflows = is_overflows; self.bucket_num = bucket_num; } public func append(name : String, value : ClickHouseValue) { if (self.columns[name] == nil) { self.columns[name] = []; } self.columns[name]!.append(value); } // UInt8 public func append(name : String, value : UInt8) { self.append(name: name, value: [value]); } public func append(name : String, value : [ UInt8 ]) { for val in value { let t = ClickHouseValue(type : .UInt8, number : NSNumber(value : val)); self.append(name: name, value: t); } } // Int8 public func append(name : String, value : Int8) { self.append(name: name, value: [value]); } public func append(name : String, value : [ Int8 ]) { for val in value { let t = ClickHouseValue(type : .Int8, number : NSNumber(value : val)); self.append(name: name, value: t); } } // UInt16 public func append(name : String, value : UInt16) { self.append(name: name, value: [value]); } public func append(name : String, value : [ UInt16 ]) { for val in value { let t = ClickHouseValue(type : .UInt16, number : NSNumber(value : val)); self.append(name: name, value: t); } } // Int16 public func append(name : String, value : Int16) { self.append(name: name, value: [value]); } public func append(name : String, value : [ Int16 ]) { for val in value { let t = ClickHouseValue(type : .Int16, number : NSNumber(value : val)); self.append(name: name, value: t); } } // UInt32 public func append(name : String, value : UInt32) { self.append(name: name, value: [value]); } public func append(name : String, value : [ UInt32 ]) { for val in value { let t = ClickHouseValue(type : .UInt32, number : NSNumber(value : val)); self.append(name: name, value: t); } } // Int32 public func append(name : String, value : Int32) { self.append(name: name, value: [value]); } public func append(name : String, value : [ Int32 ]) { for val in value { let t = ClickHouseValue(type : .Int32, number : NSNumber(value : val)); self.append(name: name, value: t); } } // UInt64 public func append(name : String, value : UInt64) { self.append(name: name, value: [value]); } public func append(name : String, value : [ UInt64 ]) { for val in value { let t = ClickHouseValue(type : .UInt64, number : NSNumber(value : val)); self.append(name: name, value: t); } } // Int64 public func append(name : String, value : Int64) { self.append(name: name, value: [value]); } public func append(name : String, value : [ Int64 ]) { for val in value { let t = ClickHouseValue(type : .Int64, number : NSNumber(value : val)); self.append(name: name, value: t); } } // Int public func append(name : String, value : Int) { self.append(name: name, value: [value]); } public func append(name : String, value : [ Int ]) { for val in value { let t = ClickHouseValue(type : .Int64, number : NSNumber(value : val)); self.append(name: name, value: t); } } // String public func append(name : String, value : String) { self.append(name: name, value: [value]); } public func append(name : String, value : [ String ]) { for val in value { let t = ClickHouseValue(type : .String, string: val); self.append(name: name, value: t); } } // Date public func append(name : String, value : Date) { self.append(name: name, value: [value]); } public func append(name : String, value : [ Date ]) { for val in value { let t = ClickHouseValue(type : .Date, date : val); self.append(name: name, value: t); } } public func append(name : String, datetime : Date) { let t = ClickHouseValue(type : .DateTime, date : datetime); self.append(name: name, value: t); } func addToBuffer(buffer : ByteBuffer, revision : UInt64) throws { // Считаем кол-во строк let rows = (self.columns.count > 0) ? self.columns.first!.value.count : 0; for (_, column) in self.columns { if (rows != column.count) { throw ClickHouseError.WrongRowsCount; } } buffer.add(ClientCodes.Data.rawValue); if (revision >= Connection.DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES) { buffer.add(""); } if (revision >= Connection.DBMS_MIN_REVISION_WITH_BLOCK_INFO) { buffer.add(UInt64(1)); buffer.addFixed(self.is_overflows); buffer.add(UInt64(2)); buffer.addFixed(self.bucket_num); buffer.add(UInt64(0)); } buffer.add(UInt64(self.columns.count)); buffer.add(UInt64(rows)); for (name, column) in self.columns { let type = column.first!.type; buffer.add(name); buffer.add(type.getName()); ClickHouseBlock.saveColumn(buffer: buffer, type: type, column: column); } } static func saveColumn(buffer : ByteBuffer, type : ClickHouseType, column : [ClickHouseValue]) { for row in column { switch (type) { case .Int8 : buffer.addFixed(row.int8!); case .Int16 : buffer.addFixed(row.int16!); case .Int32 : buffer.addFixed(row.int32!); case .Int64 : buffer.addFixed(row.int64!); case .UInt8 : buffer.addFixed(row.uint8!); case .UInt16 : buffer.addFixed(row.uint16!); case .UInt32 : buffer.addFixed(row.uint32!); case .UInt64 : buffer.addFixed(row.uint64!); case .Float32 : buffer.addFixed(row.float!); case .Float64 : buffer.addFixed(row.double!); case .Enum8 : buffer.add(row.string); case .Enum16 : buffer.add(row.string); case .String : buffer.add(row.string); case .FixedString : buffer.add(row.string); case .Date : buffer.addFixed(UInt16(row.date!.timeIntervalSince1970 / 86400)); case .DateTime : buffer.addFixed(UInt32(row.date!.timeIntervalSince1970)); case .Array : ColumnArray.save(buffer : buffer, type : type, row : row); default : break; } } } }
mit
f9befc6d16b8c937b4eeacff159e5060
29.922078
100
0.537729
3.869447
false
false
false
false
storehouse/Advance
Samples/SampleApp-iOS/Sources/AppDelegate.swift
1
2430
import UIKit import Advance @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) let a = ActivityViewController() let g = GesturesViewController() let s = SpringsViewController() let decay = DecayViewController() window?.rootViewController = BrowserViewController(viewControllers: [a, decay, s, g]) window?.makeKeyAndVisible() 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:. } }
bsd-2-clause
e1d42c2320718633408c565e5dd55769
48.591837
285
0.734156
5.926829
false
false
false
false
idapgroup/IDPDesign
Tests/iOS/iOSTests/Specs/Lens+UILongPressGestureRecognizerSpec.swift
1
2860
// // Lens+UILongPressGestureRecognizerSpec.swift // iOSTests // // Created by Oleksa 'trimm' Korin on 9/2/17. // Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved. // import Quick import Nimble import UIKit @testable import IDPDesign extension UILongPressGestureRecognizer: UILongPressGestureRecognizerProtocol { } class LensUILongPressGestureRecognizerSpec: QuickSpec { override func spec() { describe("Lens+UILongPressGestureRecognizerSpec") { context("numberOfTapsRequired") { it("should get and set") { let lens: Lens<UILongPressGestureRecognizer, Int> = numberOfTapsRequired() let object = UILongPressGestureRecognizer() let value: Int = 2 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.numberOfTapsRequired).to(equal(value)) } } context("numberOfTouchesRequired") { it("should get and set") { let lens: Lens<UILongPressGestureRecognizer, Int> = numberOfTouchesRequired() let object = UILongPressGestureRecognizer() let value: Int = 2 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.numberOfTouchesRequired).to(equal(value)) } } context("minimumPressDuration") { it("should get and set") { let lens: Lens<UILongPressGestureRecognizer, CFTimeInterval> = minimumPressDuration() let object = UILongPressGestureRecognizer() let value: CFTimeInterval = 2 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.minimumPressDuration).to(equal(value)) } } context("allowableMovement") { it("should get and set") { let lens: Lens<UILongPressGestureRecognizer, CGFloat> = allowableMovement() let object = UILongPressGestureRecognizer() let value: CGFloat = 0.5 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.allowableMovement).to(equal(value)) } } } } }
bsd-3-clause
25dcae9fbcc1db71f361f68698a9f43f
33.445783
105
0.558587
5.907025
false
false
false
false
chengxianghe/MissGe
MissGe/MissGe/Class/Project/UI/Controller/Mine/MLMineViewController.swift
1
7459
// // MLMineViewController.swift // MissLi // // Created by chengxianghe on 16/7/19. // Copyright © 2016年 cn. All rights reserved. // import UIKit class MLMineViewController: UITableViewController { @IBOutlet weak var logoutBtn: UIButton! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var bestAnswerNumLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var userEditButton: UIButton! @IBOutlet weak var loginButtonXConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() self.tableView.tableHeaderView?.setHeight(kScreenWidth/320*120) iconImageView.layer.cornerRadius = (kScreenWidth/320*120 - 24 * 2 - 18) / 2.0 if MLNetConfig.isUserLogin() { self.loginSuccessed() } else { self.logoutSuccessed() } NotificationCenter.default.addObserver(self, selector: #selector(self.loginSuccessed), name: NSNotification.Name(rawValue: kUserLoginSuccessed), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.logoutSuccessed), name: NSNotification.Name(rawValue: kUserLogoutSuccessed), object: nil) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() if kisIPad() { loginButtonXConstraint.constant = -50 } } @objc func loginSuccessed() { self.tableView.tableFooterView?.setHeight(50 + 20) self.userEditButton.isHidden = false self.loginButton.isHidden = true self.logoutBtn.isHidden = false self.nameLabel.isHidden = false self.bestAnswerNumLabel.isHidden = false self.nameLabel.text = MLNetConfig.shareInstance.user.nickname self.nameLabel.text = "最佳答案\(MLNetConfig.shareInstance.user.p_bests)个" self.iconImageView.yy_setImage(with: MLNetConfig.shareInstance.user.avatar, placeholder: UIImage(named: "portrait_bg_77x77_")) } @objc func logoutSuccessed() { self.tableView.tableFooterView?.setHeight(0) self.userEditButton.isHidden = true self.loginButton.isHidden = false self.logoutBtn.isHidden = true self.nameLabel.isHidden = true self.bestAnswerNumLabel.isHidden = true self.iconImageView.image = UIImage(named: "portrait_bg_77x77_") } override var preferredStatusBarStyle : UIStatusBarStyle { return UIStatusBarStyle.lightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onLogoutBtnClick(_ sender: UIButton) { MLNetConfig.updateUser(nil) NotificationCenter.default.post(name: Notification.Name(rawValue: kUserLogoutSuccessed), object: nil) } @IBAction func onIconBtnClick(_ sender: UIButton) { } // MARK: - Table view data source override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 15 } return 10 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 3 { return CGFloat.leastNormalMagnitude } return 5 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) print(indexPath) let sec = indexPath.section let row = indexPath.row switch sec { case 1: if !MLNetConfig.isUserLogin() { let goLogin = UIAlertAction.init(title: "去登录", style: UIAlertActionStyle.default, handler: {[weak self] (action) in let loginVCNav = kLoadVCFromSB(nil, stroyBoard: "Account")! self?.present(loginVCNav, animated: true, completion: nil) }) let cancel = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: nil) self.showAlert("您还未登录", message: nil, actions: [cancel, goLogin]) return } if row == 0 { // 收藏 self.performSegue(withIdentifier: "MineToFavorite", sender: nil) } else if row == 1 { // 评论 self.performSegue(withIdentifier: "MineToComment", sender: nil) } case 3: if row == 0 { // 设置 print("设置") } else if row == 1 { // 评分 _ = kJumpToAppStoreComment(appid: kAppId) // kJumpToAppSetting() } default: break } } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "MineToUserEdit" { let vc = segue.destination as! MLUserController vc.uid = MLNetConfig.shareInstance.userId } } }
mit
053235d028b41925f18f6311fdea3359
34.605769
167
0.637321
5.069131
false
false
false
false
psartzetakis/JRPageViewControllerKit
Tests/PageViewControllerKitTests.swift
1
3030
// // PageViewControllerKitTests.swift // PageViewControllerKitTests // // Created by Panagiotis Sartzetakis on 28/05/2016. // Copyright © 2016 Panagiotis Sartzetakis. All rights reserved. // import XCTest @testable import JRPageViewControllerKit class PageViewControllerKitTests: XCTestCase { let fakeView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 530)) let mainViewController = UIViewController(nibName: nil, bundle: nil) override func setUp() { super.setUp() UIApplication.shared.keyWindow?.rootViewController = mainViewController _ = mainViewController.view } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test_bothDelegate_andDataSource_areNotNil() { // GIVEN: A factory. let factory: ((Int) -> FakeViewController) = { index in return FakeViewController(index: index) } // WHEN: We instantiate a pageViewControllerManager. let pageViewControllerManager = PageViewControllerManager(insertIn: fakeView, inViewController: mainViewController, totalPages: 2, viewControllerForIndex: factory) // THEN: The delegate and the dataSource are not nil. XCTAssertNotNil(pageViewControllerManager.dataSource) XCTAssertNotNil(pageViewControllerManager.delegate) } func test_thatWhenCallingShowWithinRange_theViewControllerThatIsAppeared_isTheCorrectOne() { // GIVEN: A factory and pageViewControllerManager. let factory: ((Int) -> FakeViewController) = { index in return FakeViewController(index: index) } let pageViewControllerManager = PageViewControllerManager(insertIn: fakeView, inViewController: mainViewController, totalPages: 2, viewControllerForIndex: factory) // WHEN: We request to show a viewController at a specific index. pageViewControllerManager.show(viewControllerAt: 1, animated: false) // THEN: The viewController that is displayed is the correct one. XCTAssertEqual(pageViewControllerManager.activeIndex, 1) } func test_thatWhenCallingShowOutOfRange_theViewController_doesNotChange() { // GIVEN: A factory and pageViewControllerManager. let factory: ((Int) -> FakeViewController) = { index in return FakeViewController(index: index) } let pageViewControllerManager = PageViewControllerManager(insertIn: fakeView, inViewController: mainViewController, totalPages: 2, viewControllerForIndex: factory) // WHEN: We request to show a viewController for an index that doesn't exist. pageViewControllerManager.show(viewControllerAt: 2, animated: false) // THEN: The viewController that is displayed remains unchanged. XCTAssertEqual(pageViewControllerManager.activeIndex, 0) } }
mit
91360ba0991e890ad9c952e02b36d0ac
38.855263
171
0.69858
5.332746
false
true
false
false
keygx/Swift-Helpers
Helpers/Helpers/Helpers/FileManagerHelper.swift
1
5805
// // FileManager.swift // Helpers // // Created by keygx on 2015/07/31. // Copyright (c) 2015年 keygx. All rights reserved. // import Foundation class FileManagerHelper { let manager = NSFileManager() /** Path: //Documents/.. */ func documentDirectory(path: String = "") -> String { let doc = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String return doc.stringByAppendingPathComponent(path) } /** Path: //tmp/.. */ func tmpDirectory(path: String = "") -> String { let tmp = NSTemporaryDirectory() return tmp.stringByAppendingPathComponent(path) } /** Exists at Path */ func existsAtPath(path: String) -> Bool { return manager.fileExistsAtPath(path) } /** //path/to/file1, file2, file3 ....... [path : Directory] */ func fileNameList(path: String) -> [String]? { if existsAtPath(path) { let list = manager.contentsOfDirectoryAtPath(path, error: nil) if let list = list { var pathList: [String] = [] var i = 0 for fileName in list { let name: String = fileName as! String ++i pathList.append(path.stringByAppendingPathComponent(name)) } if i == list.count { return pathList } else { return nil } } else { return nil } } else { return nil } } /** File Info */ func fileInfo(path: String) -> [NSObject : AnyObject]? { return manager.attributesOfItemAtPath(path, error: nil) } /** Make Directory */ func makeDir(path: String) -> Bool { if !existsAtPath(path) { let success = manager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil, error: nil) if success { return true } else { return false } } else { return false } } /** Save Binary File */ func writeFile(path: String, data: NSData) -> Bool { let success = data.writeToFile(path, atomically: true) if success { return true } else { return false } } /** Read Binary File */ func readFile(path: String) -> NSData? { if existsAtPath(path) { return NSData(contentsOfFile: path) } return nil } /** Excluding iCloud Backup */ func excludedFromBackup(path: String) -> Bool { let url = NSURL.fileURLWithPath(path) if let url = url { let success = url.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey, error: nil) if success { println("Set Excluding \(url.lastPathComponent) From Backup") } else { println("Error Excluding \(url.lastPathComponent) From Backup") } return success } else { return false } } /** Remove at Path */ func remove(path: String) -> Bool { if existsAtPath(path) { let success = manager.removeItemAtPath(path, error: nil) return success } else { return false } } /** Remove all files [path : Directory] */ func removeAll(path: String) -> Bool { let list = fileNameList(path) if let list = list { var i = 0 for filePath in list { remove(filePath) ++i } if i == list.count { return true } else { return false } } else { return false } } /** Remove files at elapsed time settings [path : Directory] */ func removePastTime(path: String, elapsedTime: NSTimeInterval) -> [String]? { let list = fileNameList(path) if let list = list { var pathList: [String] = [] for filePath in list { if elapsedFileModificationDate(filePath, elapsedTime: elapsedTime) { let success = remove(filePath) if success { pathList.append(filePath) } } } return pathList } else { return nil } } /** Check elapsed time elapsedTime:Sec. (ex.) 1d:60x60x24 86400.00 3d:60x60x24x3 259200.00 1w:60x60x24x7 604800.00 1m:60x60x24x30 2592000.00 */ func elapsedFileModificationDate(path: String, elapsedTime: NSTimeInterval) -> Bool { if existsAtPath(path) { let fileAttribures: NSDictionary = manager.attributesOfItemAtPath(path, error: nil)! let diff = NSDate(timeIntervalSinceNow: 0.0).timeIntervalSinceDate(fileAttribures.fileModificationDate()!) if elapsedTime < diff { return true } else { return false } } else { return false } } }
mit
49e93e7af5f910fa8e46ced6e21f1976
23.693617
125
0.46924
5.246835
false
false
false
false
khizkhiz/swift
test/Generics/deduction.swift
2
9504
// RUN: %target-parse-verify-swift //===----------------------------------------------------------------------===// // Deduction of generic arguments //===----------------------------------------------------------------------===// func identity<T>(value: T) -> T { return value } func identity2<T>(value: T) -> T { return value } func identity2<T>(value: T) -> Int { return 0 } struct X { } struct Y { } func useIdentity(x: Int, y: Float, i32: Int32) { var x2 = identity(x) var y2 = identity(y) // Deduction that involves the result type x2 = identity(17) var i32_2 : Int32 = identity(17) // Deduction where the result type and input type can get different results var xx : X, yy : Y xx = identity(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}} xx = identity2(yy) // expected-error{{cannot convert value of type 'Y' to expected argument type 'X'}} } // FIXME: Crummy diagnostic! func twoIdentical<T>(x: T, _ y: T) -> T {} func useTwoIdentical(xi: Int, yi: Float) { var x = xi, y = yi x = twoIdentical(x, x) y = twoIdentical(y, y) x = twoIdentical(x, 1) x = twoIdentical(1, x) y = twoIdentical(1.0, y) y = twoIdentical(y, 1.0) twoIdentical(x, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func mySwap<T>(x: inout T, _ y: inout T) { let tmp = x x = y y = tmp } func useSwap(xi: Int, yi: Float) { var x = xi, y = yi mySwap(&x, &x) mySwap(&y, &y) mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}} // expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}} mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func takeTuples<T, U>(_: (T, U), _: (U, T)) { } func useTuples(x: Int, y: Float, z: (Float, Int)) { takeTuples((x, y), (y, x)) takeTuples((x, y), (x, y)) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}} // FIXME: Use 'z', which requires us to fix our tuple-conversion // representation. } func acceptFunction<T, U>(f: (T) -> U, _ t: T, _ u: U) {} func passFunction(f: (Int) -> Float, x: Int, y: Float) { acceptFunction(f, x, y) acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note {{in call to function 'returnTuple'}} func testReturnTuple(x: Int, y: Float) { returnTuple(x) // expected-error{{generic parameter 'T' could not be inferred}} var _ : (Int, Float) = returnTuple(x) var _ : (Float, Float) = returnTuple(y) // <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands var _ : (Int, Float) = returnTuple(y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} } func confusingArgAndParam<T, U>(f: (T) -> U, _ g: (U) -> T) { confusingArgAndParam(g, f) confusingArgAndParam(f, g) } func acceptUnaryFn<T, U>(f: (T) -> U) { } func acceptUnaryFnSame<T>(f: (T) -> T) { } func acceptUnaryFnRef<T, U>(f: inout (T) -> U) { } func acceptUnaryFnSameRef<T>(f: inout (T) -> T) { } func unaryFnIntInt(_: Int) -> Int {} func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}} func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}} // Variable forms of the above functions var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt func passOverloadSet() { // Passing a non-generic function to a generic function acceptUnaryFn(unaryFnIntInt) acceptUnaryFnSame(unaryFnIntInt) // Passing an overloaded function set to a generic function // FIXME: Yet more terrible diagnostics. acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}} acceptUnaryFnSame(unaryFnOvl) // Passing a variable of function type to a generic function acceptUnaryFn(unaryFnIntIntVar) acceptUnaryFnSame(unaryFnIntIntVar) // Passing a variable of function type to a generic function to an inout parameter acceptUnaryFnRef(&unaryFnIntIntVar) acceptUnaryFnSameRef(&unaryFnIntIntVar) acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}} } func acceptFnFloatFloat(f: (Float) -> Float) {} func acceptFnDoubleDouble(f: (Double) -> Double) {} func passGeneric() { acceptFnFloatFloat(identity) acceptFnFloatFloat(identity2) } //===----------------------------------------------------------------------===// // Simple deduction for generic member functions //===----------------------------------------------------------------------===// struct SomeType { func identity<T>(x: T) -> T { return x } func identity2<T>(x: T) -> T { return x } // expected-note 2{{found this candidate}} func identity2<T>(x: T) -> Float { } // expected-note 2{{found this candidate}} func returnAs<T>() -> T {} } func testMemberDeduction(sti: SomeType, ii: Int, fi: Float) { var st = sti, i = ii, f = fi i = st.identity(i) f = st.identity(f) i = st.identity2(i) f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}} i = st.returnAs() f = st.returnAs() acceptFnFloatFloat(st.identity) acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}} acceptFnDoubleDouble(st.identity2) } struct StaticFuncs { static func chameleon<T>() -> T {} func chameleon2<T>() -> T {} } struct StaticFuncsGeneric<U> { // FIXME: Nested generics are very broken // static func chameleon<T>() -> T {} } func chameleon<T>() -> T {} func testStatic(sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) { var x: Int16 x = StaticFuncs.chameleon() x = sf.chameleon2() // FIXME: Nested generics are very broken // x = sfi.chameleon() // typealias SFI = StaticFuncsGeneric<Int> // x = SFI.chameleon() _ = x } //===----------------------------------------------------------------------===// // Deduction checking for constraints //===----------------------------------------------------------------------===// protocol IsBefore { func isBefore(other: Self) -> Bool } func min2<T : IsBefore>(x: T, _ y: T) -> T { if y.isBefore(x) { return y } return x } extension Int : IsBefore { func isBefore(other: Int) -> Bool { return self < other } } func callMin(x: Int, y: Int, a: Float, b: Float) { min2(x, y) min2(a, b) // expected-error{{argument type 'Float' does not conform to expected type 'IsBefore'}} } func rangeOfIsBefore< R : IteratorProtocol where R.Element : IsBefore >(range: R) { } func callRangeOfIsBefore(ia: [Int], da: [Double]) { rangeOfIsBefore(ia.makeIterator()) rangeOfIsBefore(da.makeIterator()) // expected-error{{ambiguous reference to member 'makeIterator()'}} } //===----------------------------------------------------------------------===// // Deduction for member operators //===----------------------------------------------------------------------===// protocol Addable { func +(x: Self, y: Self) -> Self } func addAddables<T : Addable, U>(x: T, y: T, u: U) -> T { u + u // expected-error{{binary operator '+' cannot be applied to two 'U' operands}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }} return x+y } //===----------------------------------------------------------------------===// // Deduction for bound generic types //===----------------------------------------------------------------------===// struct MyVector<T> { func size() -> Int {} } func getVectorSize<T>(v: MyVector<T>) -> Int { return v.size() } func ovlVector<T>(v: MyVector<T>) -> X {} func ovlVector<T>(v: MyVector<MyVector<T>>) -> Y {} func testGetVectorSize(vi: MyVector<Int>, vf: MyVector<Float>) { var i : Int i = getVectorSize(vi) i = getVectorSize(vf) getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<_>'}} var x : X, y : Y x = ovlVector(vi) x = ovlVector(vf) var vvi : MyVector<MyVector<Int>> y = ovlVector(vvi) var yy = ovlVector(vvi) yy = y y = yy } // <rdar://problem/15104554> postfix operator <*> {} protocol MetaFunction { associatedtype Result postfix func <*> (_: Self) -> Result? } protocol Bool_ {} struct False : Bool_ {} struct True : Bool_ {} postfix func <*> <B:Bool_>(_: Test<B>) -> Int? { return .none } postfix func <*> (_: Test<True>) -> String? { return .none } class Test<C: Bool_> : MetaFunction { typealias Result = Int } // picks first <*> typealias Inty = Test<True>.Result var iy : Inty = 5 // okay, because we picked the first <*> var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}} // rdar://problem/20577950 class DeducePropertyParams { let badSet: Set = ["Hello"] } // SR-69 struct A {} func foo() { for i in min(1,2) { // expected-error{{type 'Int' does not conform to protocol 'Sequence'}} } let j = min(Int(3), Float(2.5)) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}} let k = min(A(), A()) // expected-error{{argument type 'A' does not conform to expected type 'Comparable'}} let oi : Int? = 5 let l = min(3, oi) // expected-error{{value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?}} }
apache-2.0
02067fafc51e0c13d16943f51b2f421a
30.68
150
0.6008
3.729984
false
false
false
false
Jude309307972/JudeTest
03-swift.playground/Contents.swift
1
5663
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // 集合类型 collection types var shoppingList:[String] = ["eggs","milk"] var List = ["eggs", "milk"] print("the shopping list contains \(shoppingList.count) items") if shoppingList.isEmpty { print("the shopping list is empty") } else { print("the shopping list is not empty") } shoppingList.append("flour") shoppingList += ["baking powder"] shoppingList += ["chocolate spread","cheese","butter"] var fistItem = shoppingList[1] shoppingList[0] = "six eggs" shoppingList.insert("maple syrup", atIndex: 0) let mapleSyrup = shoppingList.removeAtIndex(0) fistItem = shoppingList[0] let apples = shoppingList.removeLast() for item in shoppingList { print(item) } var someInts = [Int]() print("someInts is of type [Int] with \(someInts.count) items") someInts.append(3) someInts = [] var threeDoubles = [Double](count: 3, repeatedValue: 0.0) var anotherThreeDouble = Array(count: 3, repeatedValue: 2.5) var sixDoubles = threeDoubles + anotherThreeDouble // 字典 var airports:[String:String] = ["TYO" : "Tokyo", "DUB": "Dubin"] print("the dictionary of airports cont") print("the dictionary of airports contains \(airports.count) items") if airports.isEmpty { print("the airports dictionary is empty") } else { print("the airports dictionary is not empty") } airports["LHR"] = "London" airports["LHR"] = "London Heathrow" if let oldValue = airports.updateValue("Dublin Internation", forKey: "DUB"){ print("the old value for Dub was \(oldValue)") } if let airportName = airports["DUB"] { print("the name of the airport is \(airportName)") } else { print("the ") } airports["APL"] = "apple internation" airports["APL"] = nil if let removedValue = airports.removeValueForKey("DUB") { print(" name is \(removedValue)") } else { print("111") } for (airportCode, airportName) in airports { print("\(airportCode):\(airportName)") } for airportCode in airports.keys { print("airport code:\(airportCode)") } for airportName in airports.values { print("airportName \(airportName)") } let airportCodes = Array(airports.keys) let airportNames = Array(airports.values) var namesOfIntegers = Dictionary<Int, String>() namesOfIntegers[16] = "sixteen" namesOfIntegers = [:] // 类和结构体 struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } let someResolution = Resolution() let someVideoMode = VideoMode() print("the width of someResolution is \(someResolution.width)") print("the width of someVideoMode is \(someVideoMode.resolution.width)") someVideoMode.resolution.width = 1280 print("the width of someVideoMode is \(someVideoMode.resolution.width)") let vga = Resolution(width: 640, height: 480) let hd = Resolution(width: 1920, height: 1080) var cinema = hd cinema.width = 2048 print("cinema is now \(cinema.width) pixels wide") print("cinema is now \(hd.width) pixels wide") let tenEighty = VideoMode() tenEighty.resolution = hd tenEighty.interlaced = true tenEighty.name = "1080i" tenEighty.frameRate = 25.0 let alsoTenEighty = tenEighty alsoTenEighty.frameRate = 30.0 print("the frameRate property of tenEighty is now \(tenEighty.frameRate)") if tenEighty === alsoTenEighty { print("====") } else { print("!===") } // Properties struct FixedLengthRange { var firstValue: Int let length: Int } var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) rangeOfThreeItems.firstValue = 6 let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4) //rangeOfFourItems.firstValue = 6 class DataImporter { var fileName = "data.txt" } class DataManager { lazy var importer = DataImporter() var data = [String]() } let manager = DataManager() manager.data.append("some data") manager.data.append("some more data") print(manager.importer.fileName) // 计算属性 struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center: Point{ get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set (newCenter){ origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0)) let initialSquareCenter = square.center print("square.origin is now at(\(square.origin.x), \(square.origin.y))") square.center = Point(x: 15.0, y: 15.0) print("square.origin is now at(\(square.origin.x), \(square.origin.y))") // 属性控制器 class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps){ print("about to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 300 // 全局变量和局部变量 struct SomeStructure { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 34 } } enum SomeEnumeration { static var storedType = "some value " static var computedType: Int { return 34 } } class SomeClass { class var computedType : Int { return 34 } }
apache-2.0
57964d006ca185c30bc9bfbf37020cdd
21.066929
87
0.670294
3.592949
false
false
false
false
XiaoChenYung/GitSwift
GitSwift/ViewModel/UserListViewModel.swift
1
2259
// // UserListViewModel.swift // GitSwift // // Created by tm on 2017/7/28. // Copyright © 2017年 tm. All rights reserved. // import UIKit import RxCocoa import RxSwift import Domain import NetWork class UserListViewModel: ViewModel, ViewModelType { var loginViewModel: LoginViewModel override init(service: ViewModelServiceImp, params: Dictionary<String, Any>?, provider: Domain.UseCaseProvider?) { self.loginViewModel = LoginViewModel(service: service, params: params, provider: provider) super.init(service: service, params: params, provider: provider) self.title.value = "用户列表" } struct Input { let trigger: Driver<Void> let selection: Driver<IndexPath> } struct Output { let fetching: Driver<Bool> let users: Driver<[User]> let selectedPost: Driver<User> let error: Driver<Error> } func transform(input: UserListViewModel.Input) -> UserListViewModel.Output { let activityIndicator = ActivityIndicator() let errorTracker = ErrorTracker() let users = input.trigger.flatMapLatest { () -> SharedSequence<DriverSharingStrategy, [User]> in // guard let gprovider = self.provider else { // assert(false, "listProvider == nil") // } // if let listProvider as NetWork.UseCaseProvider { // return listProvider.makeAllUserUseCase() // } let listProvider = self.provider as! NetWork.UseCaseProvider let userCase = listProvider.makeAllUserUseCase() return userCase.users().trackActivity(activityIndicator) .trackError(errorTracker) .asDriver(onErrorJustReturn: []) } let fetching = activityIndicator.asDriver() let errors = errorTracker.asDriver() let selectedUser = input.selection.withLatestFrom(users) { (indexPath, users) -> User in return users[indexPath.row] }.do(onNext: { [unowned self] (user) in self.service.pushViewModel(viewModel: self.loginViewModel) }) return Output(fetching: fetching, users: users, selectedPost: selectedUser, error: errors) } }
mit
39419e767ac8e89c65adb0756a000aec
34.68254
118
0.63968
4.6639
false
false
false
false
garygriswold/Bible.js
Plugins/AWS/src/ios/AWS/Zip.swift
2
15497
// // Zip.swift // Zip // // Created by Roy Marmelstein on 13/12/2015. // Copyright © 2015 Roy Marmelstein. All rights reserved. // import Foundation import minizip //#include "unzip.h" //#include "zip.h" /// Zip error type public enum ZipError: Error { /// File not found case fileNotFound /// Unzip fail case unzipFail /// Zip fail case zipFail /// User readable description public var description: String { switch self { case .fileNotFound: return NSLocalizedString("File not found.", comment: "") case .unzipFail: return NSLocalizedString("Failed to unzip file.", comment: "") case .zipFail: return NSLocalizedString("Failed to zip file.", comment: "") } } } public enum ZipCompression: Int { case NoCompression case BestSpeed case DefaultCompression case BestCompression internal var minizipCompression: Int32 { switch self { case .NoCompression: return Z_NO_COMPRESSION case .BestSpeed: return Z_BEST_SPEED case .DefaultCompression: return Z_DEFAULT_COMPRESSION case .BestCompression: return Z_BEST_COMPRESSION } } } /// Zip class public class Zip { /** Set of vaild file extensions */ internal static var customFileExtensions: Set<String> = [] // MARK: Lifecycle /** Init - returns: Zip object */ public init () { } // MARK: Unzip /** Unzip file - parameter zipFilePath: Local file path of zipped file. NSURL. - parameter destination: Local file path to unzip to. NSURL. - parameter overwrite: Overwrite bool. - parameter password: Optional password if file is protected. - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if unzipping fails or if fail is not found. Can be printed with a description variable. - notes: Supports implicit progress composition */ public class func unzipFile(_ zipFilePath: URL, destination: URL, overwrite: Bool, password: String?, progress: ((_ progress: Double) -> ())? = nil, fileOutputHandler: ((_ unzippedFile: URL) -> Void)? = nil) throws { // File manager let fileManager = FileManager.default // Check whether a zip file exists at path. let path = zipFilePath.path if fileManager.fileExists(atPath: path) == false || fileExtensionIsInvalid(zipFilePath.pathExtension) { throw ZipError.fileNotFound } // Unzip set up var ret: Int32 = 0 var crc_ret: Int32 = 0 let bufferSize: UInt32 = 4096 var buffer = Array<CUnsignedChar>(repeating: 0, count: Int(bufferSize)) // Progress handler set up var totalSize: Double = 0.0 var currentPosition: Double = 0.0 let fileAttributes = try fileManager.attributesOfItem(atPath: path) if let attributeFileSize = fileAttributes[FileAttributeKey.size] as? Double { totalSize += attributeFileSize } let progressTracker = Progress(totalUnitCount: Int64(totalSize)) progressTracker.isCancellable = false progressTracker.isPausable = false progressTracker.kind = ProgressKind.file // Begin unzipping let zip = unzOpen64(path) defer { unzClose(zip) } if unzGoToFirstFile(zip) != UNZ_OK { throw ZipError.unzipFail } repeat { if let cPassword = password?.cString(using: String.Encoding.ascii) { ret = unzOpenCurrentFilePassword(zip, cPassword) } else { ret = unzOpenCurrentFile(zip); } if ret != UNZ_OK { throw ZipError.unzipFail } var fileInfo = unz_file_info64() memset(&fileInfo, 0, MemoryLayout<unz_file_info>.size) ret = unzGetCurrentFileInfo64(zip, &fileInfo, nil, 0, nil, 0, nil, 0) if ret != UNZ_OK { unzCloseCurrentFile(zip) throw ZipError.unzipFail } currentPosition += Double(fileInfo.compressed_size) let fileNameSize = Int(fileInfo.size_filename) + 1 //let fileName = UnsafeMutablePointer<CChar>(allocatingCapacity: fileNameSize) let fileName = UnsafeMutablePointer<CChar>.allocate(capacity: fileNameSize) unzGetCurrentFileInfo64(zip, &fileInfo, fileName, UInt(fileNameSize), nil, 0, nil, 0) fileName[Int(fileInfo.size_filename)] = 0 var pathString = String(cString: fileName) guard pathString.count > 0 else { throw ZipError.unzipFail } var isDirectory = false let fileInfoSizeFileName = Int(fileInfo.size_filename-1) if (fileName[fileInfoSizeFileName] == "/".cString(using: String.Encoding.utf8)?.first || fileName[fileInfoSizeFileName] == "\\".cString(using: String.Encoding.utf8)?.first) { isDirectory = true; } free(fileName) if pathString.rangeOfCharacter(from: CharacterSet(charactersIn: "/\\")) != nil { pathString = pathString.replacingOccurrences(of: "\\", with: "/") } let fullPath = destination.appendingPathComponent(pathString).path let creationDate = Date() let directoryAttributes = [FileAttributeKey.creationDate : creationDate, FileAttributeKey.modificationDate : creationDate] do { if isDirectory { try fileManager.createDirectory(atPath: fullPath, withIntermediateDirectories: true, attributes: directoryAttributes) } else { let parentDirectory = (fullPath as NSString).deletingLastPathComponent try fileManager.createDirectory(atPath: parentDirectory, withIntermediateDirectories: true, attributes: directoryAttributes) } } catch {} if fileManager.fileExists(atPath: fullPath) && !isDirectory && !overwrite { unzCloseCurrentFile(zip) ret = unzGoToNextFile(zip) } var writeBytes: UInt64 = 0 var filePointer: UnsafeMutablePointer<FILE>? filePointer = fopen(fullPath, "wb") while filePointer != nil { let readBytes = unzReadCurrentFile(zip, &buffer, bufferSize) if readBytes > 0 { guard fwrite(buffer, Int(readBytes), 1, filePointer) == 1 else { throw ZipError.unzipFail } writeBytes += UInt64(readBytes) } else { break } } fclose(filePointer) crc_ret = unzCloseCurrentFile(zip) if crc_ret == UNZ_CRCERROR { throw ZipError.unzipFail } guard writeBytes == fileInfo.uncompressed_size else { throw ZipError.unzipFail } //Set file permissions from current fileInfo if fileInfo.external_fa != 0 { let permissions = (fileInfo.external_fa >> 16) & 0x1FF //We will devifne a valid permission range between Owner read only to full access if permissions >= 0o400 && permissions <= 0o777 { do { try fileManager.setAttributes([.posixPermissions : permissions], ofItemAtPath: fullPath) } catch { print("Failed to set permissions to file \(fullPath), error: \(error)") } } } ret = unzGoToNextFile(zip) // Update progress handler if let progressHandler = progress{ progressHandler((currentPosition/totalSize)) } if let fileHandler = fileOutputHandler, let fileUrl = URL(string: fullPath) { fileHandler(fileUrl) } progressTracker.completedUnitCount = Int64(currentPosition) } while (ret == UNZ_OK && ret != UNZ_END_OF_LIST_OF_FILE) // Completed. Update progress handler. if let progressHandler = progress{ progressHandler(1.0) } progressTracker.completedUnitCount = Int64(totalSize) } // MARK: Zip /** Zip files. - parameter paths: Array of NSURL filepaths. - parameter zipFilePath: Destination NSURL, should lead to a .zip filepath. - parameter password: Password string. Optional. - parameter compression: Compression strategy - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if zipping fails. - notes: Supports implicit progress composition */ public class func zipFiles(paths: [URL], zipFilePath: URL, password: String?, compression: ZipCompression = .DefaultCompression, progress: ((_ progress: Double) -> ())?) throws { // File manager let fileManager = FileManager.default // Check whether a zip file exists at path. let destinationPath = zipFilePath.path // Process zip paths let processedPaths = ZipUtilities().processZipPaths(paths) // Zip set up let chunkSize: Int = 16384 // Progress handler set up var currentPosition: Double = 0.0 var totalSize: Double = 0.0 // Get totalSize for progress handler for path in processedPaths { do { let filePath = path.filePath() let fileAttributes = try fileManager.attributesOfItem(atPath: filePath) let fileSize = fileAttributes[FileAttributeKey.size] as? Double if let fileSize = fileSize { totalSize += fileSize } } catch {} } let progressTracker = Progress(totalUnitCount: Int64(totalSize)) progressTracker.isCancellable = false progressTracker.isPausable = false progressTracker.kind = ProgressKind.file // Begin Zipping let zip = zipOpen(destinationPath, APPEND_STATUS_CREATE) for path in processedPaths { let filePath = path.filePath() var isDirectory: ObjCBool = false fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory) if !isDirectory.boolValue { let input = fopen(filePath, "r") if input == nil { throw ZipError.zipFail } let fileName = path.fileName var zipInfo: zip_fileinfo = zip_fileinfo(tmz_date: tm_zip(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0), dosDate: 0, internal_fa: 0, external_fa: 0) do { let fileAttributes = try fileManager.attributesOfItem(atPath: filePath) if let fileDate = fileAttributes[FileAttributeKey.modificationDate] as? Date { let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fileDate) zipInfo.tmz_date.tm_sec = UInt32(components.second!) zipInfo.tmz_date.tm_min = UInt32(components.minute!) zipInfo.tmz_date.tm_hour = UInt32(components.hour!) zipInfo.tmz_date.tm_mday = UInt32(components.day!) zipInfo.tmz_date.tm_mon = UInt32(components.month!) - 1 zipInfo.tmz_date.tm_year = UInt32(components.year!) } if let fileSize = fileAttributes[FileAttributeKey.size] as? Double { currentPosition += fileSize } } catch {} let buffer = malloc(chunkSize) if let password = password, let fileName = fileName { zipOpenNewFileInZip3(zip, fileName, &zipInfo, nil, 0, nil, 0, nil,Z_DEFLATED, compression.minizipCompression, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password, 0) } else if let fileName = fileName { zipOpenNewFileInZip3(zip, fileName, &zipInfo, nil, 0, nil, 0, nil,Z_DEFLATED, compression.minizipCompression, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, nil, 0) } else { throw ZipError.zipFail } var length: Int = 0 while (feof(input) == 0) { length = fread(buffer, 1, chunkSize, input) zipWriteInFileInZip(zip, buffer, UInt32(length)) } // Update progress handler if let progressHandler = progress{ progressHandler((currentPosition/totalSize)) } progressTracker.completedUnitCount = Int64(currentPosition) zipCloseFileInZip(zip) free(buffer) fclose(input) } } zipClose(zip, nil) // Completed. Update progress handler. if let progressHandler = progress{ progressHandler(1.0) } progressTracker.completedUnitCount = Int64(totalSize) } /** Check if file extension is invalid. - parameter fileExtension: A file extension. - returns: false if the extension is a valid file extension, otherwise true. */ internal class func fileExtensionIsInvalid(_ fileExtension: String?) -> Bool { guard let fileExtension = fileExtension else { return true } return !isValidFileExtension(fileExtension) } /** Add a file extension to the set of custom file extensions - parameter fileExtension: A file extension. */ public class func addCustomFileExtension(_ fileExtension: String) { customFileExtensions.insert(fileExtension) } /** Remove a file extension from the set of custom file extensions - parameter fileExtension: A file extension. */ public class func removeCustomFileExtension(_ fileExtension: String) { customFileExtensions.remove(fileExtension) } /** Check if a specific file extension is valid - parameter fileExtension: A file extension. - returns: true if the extension valid, otherwise false. */ public class func isValidFileExtension(_ fileExtension: String) -> Bool { let validFileExtensions: Set<String> = customFileExtensions.union(["zip", "cbz"]) return validFileExtensions.contains(fileExtension) } }
mit
c498505a8c31d50c6fb954953c2cf4c4
36.339759
220
0.567695
5.160173
false
false
false
false
JiongXing/PhotoBrowser
Sources/JXPhotoBrowser/JXPhotoBrowserFadeAnimator.swift
1
2177
// // JXPhotoBrowserFadeAnimator.swift // JXPhotoBrowser // // Created by JiongXing on 2019/11/25. // Copyright © 2019 JiongXing. All rights reserved. // import UIKit open class JXPhotoBrowserFadeAnimator: NSObject, JXPhotoBrowserAnimatedTransitioning { open var showDuration: TimeInterval = 0.25 open var dismissDuration: TimeInterval = 0.25 public var isNavigationAnimation: Bool = false public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return isForShow ? showDuration : dismissDuration } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let browser = photoBrowser else { transitionContext.completeTransition(!transitionContext.transitionWasCancelled) return } if isNavigationAnimation, isForShow, let fromView = transitionContext.view(forKey: .from), let fromViewSnapshot = snapshot(with: fromView), let toView = transitionContext.view(forKey: .to) { toView.insertSubview(fromViewSnapshot, at: 0) } if isForShow { browser.maskView.alpha = 0 browser.browserView.alpha = 0 if let toView = transitionContext.view(forKey: .to) { transitionContext.containerView.addSubview(toView) } } else { if isNavigationAnimation, let fromView = transitionContext.view(forKey: .from), let toView = transitionContext.view(forKey: .to) { transitionContext.containerView.insertSubview(toView, belowSubview: fromView) } } browser.browserView.isHidden = true UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { browser.browserView.isHidden = false browser.maskView.alpha = self.isForShow ? 1.0 : 0 browser.browserView.alpha = self.isForShow ? 1.0 : 0 }) { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
mit
4bb013f4ef9c5cca374beaabead110d8
38.563636
120
0.662224
5.481108
false
false
false
false
xivol/MCS-V3-Mobile
examples/swift/SwiftBasics.playground/Pages/Functions.xcplaygroundpage/Contents.swift
1
2427
/*: ## Functions [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next) **** */ func printMeSomething() { print("Something!") } printMeSomething() func giveMeSomething() -> String { return "Something!" } giveMeSomething() //: ### Parameters //: Each function parameter has both an **argument label** and a **parameter name**. func square(of x: Int) -> Int { return x * x } square(of: 5) //: If you don’t want an argument label for a parameter, write an underscore `_` instead of an explicit argument label for that parameter. func sqr(_ x: Int) -> Int { return x * x } sqr(12) //: Function parameters are constants by default. If you want a function to modify a parameter’s value, define that parameter as an in-out parameter instead. func sort(_ a: inout Int, _ b: inout Int) { if a > b { (a, b) = (b, a) } } var a = 13, b = 8 sort( &a, &b) a b //: You can use a tuple type as the return type for a function to return multiple values as part of one compound return value. func minmax(_ a: Int, _ b:Int) -> (Int, Int) { return a > b ? (b, a) : (a, b) } let (min, max) = minmax(181, 11) min max //: ### Functional type let transform: (Int) -> Int = square for i in 1...10 { transform(i) } func calc(_ fun: (Int) -> Int, arg: Int) -> Int { return fun(arg) } calc(sqr, arg: 5) calc(-, arg:7) //: You can also define function inside the body of another functions, known as nested functions. func operation(_ c: Character) -> (Int,Int) -> Int { func add( a: Int, b: Int) -> Int { return a + b } func sub( a: Int, b: Int) -> Int { return a - b } func mul( a: Int, b: Int) -> Int { return a * b } func div( a: Int, b: Int) -> Int { return a / b } switch c { case "*": return mul case "/": return div case "-": return sub default: return add } } let op = operation("+") op(1, 2) //: ### Closures var modulus = { (a: Int, b: Int) in return a % b } modulus(15,4) //: Argument type inferrence. type(of: modulus) modulus = { a, b in return a % b } modulus(15,4) //: Closures implicitly return result of the last operator. modulus = { a, b in a % b } modulus(15,4) //: Shorthand parameter names. modulus = { $0 % $1 } modulus(15,4) //: **** //: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
mit
799f755c1eb0d80418c10f058ea45c3d
21.820755
158
0.589086
3.199735
false
false
false
false
heptal/kathy
Kathy/IRCSession.swift
1
4631
// // IRCSession.swift // Kathy // // Created by Michael Bujol on 6/13/16. // Copyright © 2016 heptal. All rights reserved. // import Cocoa import CocoaAsyncSocket.GCDAsyncSocket protocol IRCDelegate: class { func didReceiveBroadcast(_ message: String) func didReceiveMessage(_ message: String) func didReceiveUnreadMessageOnChannel(_ channel: String) func didReceiveError(_ error: NSError) } class IRCSession: NSObject { var socket: GCDAsyncSocket! let readTimeout = -1.0 let writeTimeout = 30.0 let tag = -1 var currentNick: String! let channels = NSArrayController() let consoleChannelName = "Server Console" unowned let delegate: IRCDelegate init(delegate: IRCDelegate) { self.delegate = delegate super.init() let delegateQueue = DispatchQueue(label: "com.heptal.Kathy.tcpQueue", attributes: []) socket = GCDAsyncSocket(delegate: self, delegateQueue: delegateQueue) // socket.IPv4PreferredOverIPv6 = false currentNick = UserDefaults.standard.string(forKey: "nick") channels.addObject(Channel(name: consoleChannelName)) } func readSocket() { socket.readData(to: GCDAsyncSocket.crlfData(), withTimeout: readTimeout, tag: tag) } func connectToHost(_ host: String, port: UInt16) { do { try socket.connect(toHost: host, onPort: port) if port == 6697 { socket.startTLS([kCFStreamSSLPeerName as String: host as NSObject]) } readSocket() } catch let error as NSError { delegate.didReceiveError(error) } } func authenticate() { let userDefaults = UserDefaults.standard if let nick = userDefaults.string(forKey: "nick") { let user = userDefaults.string(forKey: "user") ?? nick let realName = userDefaults.string(forKey: "realName") ?? nick let invisible = userDefaults.bool(forKey: "invisible") ? "8" : "0" if let pass = userDefaults.string(forKey: "pass") { sendIRCMessage(IRCMessage(command: "PASS", params: pass)) } sendIRCMessage(IRCMessage(command: "NICK", params: nick)) sendIRCMessage(IRCMessage(command: "USER", params: "\(user) \(invisible) * :\(realName)")) } else { sendIRCMessage(IRCMessage(command: "QUIT", params: nil)) } } func sendIRCMessage(_ message: IRCMessage) { socket.write(message.data as Data!, withTimeout: writeTimeout, tag: tag) } func command(_ cmd: String) { if cmd.hasPrefix("/server") { if let matches = " ([^: ]+)[: ]?(.*)?".captures(cmd), let server = matches.first { connectToHost(server, port: UInt16(matches.last!) ?? 6697) } return } if cmd.hasPrefix("/msg") { if let matches = " (\\S+) (.*)".captures(cmd), let nick = matches.first, let message = matches.last { command("/PRIVMSG \(nick) :\(message)") } return } if let matches = "/(\\S*) ?(.*)".captures(cmd), let command = matches.first, let params = matches.last { sendIRCMessage(IRCMessage(command: command, params: params)) } } func getChannel(_ channelName: String) -> Channel? { return (channels.arrangedObjects as? Array<Channel>)?.filter { channelName == $0.name }.first } func setupChannel(_ channelName: String) -> Channel? { if getChannel(channelName) == nil { let channel = Channel(name: channelName) if Thread.isMainThread { channels.addObject(channel) } else { DispatchQueue.main.sync { self.channels.addObject(channel) } } } return getChannel(channelName) } func appendMessageToChannel(_ channelName: String, message: String) { if let channel = setupChannel(channelName) { channel.log.append(message) if let currentChannel = channels.selectedObjects.first as? Channel { if channel.name == currentChannel.name { DispatchQueue.main.async { self.delegate.didReceiveMessage(message) } } else if channel.name != consoleChannelName { DispatchQueue.main.async { self.delegate.didReceiveUnreadMessageOnChannel(channelName) } } } } } }
apache-2.0
5f9ceebc6cf1cc4f720e846537da293c
32.071429
113
0.582289
4.579624
false
false
false
false
Chaosspeeder/YourGoals
YourGoals/Business/ImageUpdater.swift
1
861
// // File.swift // YourGoals // // Created by André Claaßen on 28.10.17. // Copyright © 2017 André Claaßen. All rights reserved. // import Foundation import UIKit class ImageUpdater:StorageManagerWorker { func updateImage(forGoal goal:Goal, image: UIImage?) throws { let oldImageData = goal.imageData if let image = image { guard let data = image.jpegData(compressionQuality: 0.6) else { throw GoalError.imageNotJPegError } let imageData = self.manager.imageDataStore.createPersistentObject() imageData.data = data goal.imageData = imageData } else { goal.imageData = nil } if oldImageData != nil { self.manager.context.delete(oldImageData!) } } }
lgpl-3.0
c69e9a0a5ae060f29ed52ebbe7ca9532
24.176471
80
0.578271
4.677596
false
false
false
false
nvzqz/Sage
Sources/Tables.swift
1
3941
// // Tables.swift // Sage // // Copyright 2016-2017 Nikolai Vazquez // // 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. // /// Returns the pawn attack table for `color`. internal func _pawnAttackTable(for color: Color) -> [Bitboard] { if color.isWhite { return _whitePawnAttackTable } else { return _blackPawnAttackTable } } /// A lookup table of all white pawn attack bitboards. internal let _whitePawnAttackTable = Square.all.map { square in return Bitboard(square: square)._pawnAttacks(for: ._white) } /// A lookup table of all black pawn attack bitboards. internal let _blackPawnAttackTable = Square.all.map { square in return Bitboard(square: square)._pawnAttacks(for: ._black) } /// A lookup table of all king attack bitboards. internal let _kingAttackTable = Square.all.map { square in return Bitboard(square: square)._kingAttacks() } /// A lookup table of all knight attack bitboards. internal let _knightAttackTable = Square.all.map { square in return Bitboard(square: square)._knightAttacks() } /// Returns the squares between `start` and `end`. private func _between(_ start: Square, _ end: Square) -> Bitboard { let start = UInt64(start.hashValue) let end = UInt64(end.hashValue) let max = UInt64.max let a2a7: UInt64 = 0x0001010101010100 let b2g7: UInt64 = 0x0040201008040200 let h1b7: UInt64 = 0x0002040810204080 let between = (max << start) ^ (max << end) let file = (end & 7) &- (start & 7) let rank = ((end | 7) &- start) >> 3 var line = ((file & 7) &- 1) & a2a7 line += 2 &* (((rank & 7) &- 1) >> 58) line += (((rank &- file) & 15) &- 1) & b2g7 line += (((rank &+ file) & 15) &- 1) & h1b7 line = line &* (between & (0 &- between)) return Bitboard(rawValue: line & between) } /// Returns the triangle index for `start` and `end`. internal func _triangleIndex(_ start: Square, _ end: Square) -> Int { var a = start.hashValue var b = end.hashValue var d = a &- b d &= d >> 31 b = b &+ d a = a &- d b = b &* (b ^ 127) return (b >> 1) + a } /// A lookup table of squares between two squares. internal let _betweenTable: [Bitboard] = { #if swift(>=3) var table = [Bitboard](repeating: 0, count: 2080) #else var table = [Bitboard](count: 2080, repeatedValue: 0) #endif for start in Square.all { for end in Square.all { let index = _triangleIndex(start, end) table[index] = _between(start, end) } } return table }() /// A lookup table of lines for two squares. internal let _lineTable: [Bitboard] = { #if swift(>=3) var table = [Bitboard](repeating: 0, count: 2080) #else var table = [Bitboard](count: 2080, repeatedValue: 0) #endif for start in Square.all { for end in Square.all { let startBB = Bitboard(square: start) let endBB = Bitboard(square: end) let index = _triangleIndex(start, end) let rookAttacks = startBB._rookAttacks() let bishopAttacks = startBB._bishopAttacks() if rookAttacks[end] { table[index] = startBB | endBB | (rookAttacks & endBB._rookAttacks()) } else if bishopAttacks[end] { table[index] = startBB | endBB | (bishopAttacks & endBB._bishopAttacks()) } } } return table }()
apache-2.0
7f13797af59b539a4aa80856a42767f5
31.570248
89
0.622685
3.5
false
false
false
false
Vanlol/MyYDW
SwiftCocoa/Resource/Discover/Controller/CommunityMessageViewController.swift
1
7562
// // CommunityMessageViewController.swift // SwiftCocoa // // Created by admin on 2017/7/20. // Copyright © 2017年 admin. All rights reserved. // import UIKit import WebKit class CommunityMessageViewController: BaseViewController { var userContentCtrl:WKUserContentController! fileprivate lazy var webVi:WKWebView = { let webConfig = WKWebViewConfiguration() let userContent = WKUserContentController() //userContent.add(self, name: "JSMethod") webConfig.userContentController = userContent //self.userContentCtrl = userContent let web = WKWebView(frame: CGRect.zero, configuration: webConfig) web.translatesAutoresizingMaskIntoConstraints = false web.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: -64, right: 0) web.backgroundColor = 0xEDF3FF.HexColor web.navigationDelegate = self web.uiDelegate = self return web }() override func viewDidLoad() { super.viewDidLoad() initNav() initWebView() loadUrl() } /** * 注销方法 */ deinit { //userContentCtrl.removeScriptMessageHandler(forName: "JSMethod") } /** * 初始化nav */ fileprivate func initNav() { view.backgroundColor = 0xEDF3FF.HexColor setUpSystemNav(title: "消息", hexColorBg: 0xffffff) navigationItem.leftBarButtonItem = UIBarButtonItem.backItemWithImage(image: "4_nav_return_icon", target: self, action: #selector(backButtonClick)) } //MARK: 返回按钮点击事件 func backButtonClick() { navigationController?.popViewController(animated: true) } /** * 初始化view */ fileprivate func initWebView() { view.addSubview(webVi) let leading = NSLayoutConstraint(item: webVi, attribute: .leading, relatedBy: .equal, toItem: webVi.superview, attribute: .leading, multiplier: 1.0, constant: 0.0) let top = NSLayoutConstraint(item: webVi, attribute: .top, relatedBy: .equal, toItem: webVi.superview, attribute: .top, multiplier: 1.0, constant: 0.0) let trailing = NSLayoutConstraint(item: webVi, attribute: .trailing, relatedBy: .equal, toItem: webVi.superview, attribute: .trailing, multiplier: 1.0, constant: 0.0) let bottom = NSLayoutConstraint(item: webVi, attribute: .bottom, relatedBy: .equal, toItem: webVi.superview, attribute: .bottom, multiplier: 1.0, constant: 0.0) webVi.superview?.addConstraints([leading,trailing,top,bottom]) } /** * 加载url */ fileprivate func loadUrl() { let urlStr = W.YD_DONGTAI + U.getMobile()! Print.dlog(urlStr) webVi.load(URLRequest(url: URL(string: urlStr)!)) } } //extension CommunityMessageViewController:WKScriptMessageHandler { // // func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { // Print.dlog(userContentController) // Print.dlog(message.name) // } // //} extension CommunityMessageViewController:WKUIDelegate { // func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { // Print.dlog("runJavaScriptAlertPanelWithMessage") // } // // func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { // Print.dlog("runJavaScriptConfirmPanelWithMessage") // } // // func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { // Print.dlog("runJavaScriptTextInputPanelWithPrompt") // } // // func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { // Print.dlog("createWebViewWith") // return WKWebView() // } // // @available(iOS 10.0, *) // func webView(_ webView: WKWebView, shouldPreviewElement elementInfo: WKPreviewElementInfo) -> Bool { // Print.dlog("shouldPreviewElement") // return true // } // // func webView(_ webView: WKWebView, commitPreviewingViewController previewingViewController: UIViewController) { // Print.dlog("commitPreviewingViewController") // } // // @available(iOS 10.0, *) // func webView(_ webView: WKWebView, previewingViewControllerForElement elementInfo: WKPreviewElementInfo, defaultActions previewActions: [WKPreviewActionItem]) -> UIViewController? { // Print.dlog("previewingViewControllerForElement") // return UIViewController() // } } extension CommunityMessageViewController:WKNavigationDelegate { /** * 1. 实现decisionHandler回调,允许接入 */ // func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { // // Print.dlog("decidePolicyFor") // // Print.dlog(navigationAction.navigationType) // // Print.dlog(navigationAction.request.url) // // Print.dlog(navigationAction.sourceFrame.isMainFrame) // // Print.dlog(navigationAction.targetFrame?.isMainFrame) // decisionHandler(.allow) // } /** * 2. didStartProvisionalNavigation */ func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { // Print.dlog("didStartProvisionalNavigation") } /** * 3. 实现decisionHandler回调,允许接入 */ // func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { //// Print.dlog("decidePolicyFor") // decisionHandler(.allow) // } /** * 4. didCommit */ func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { // Print.dlog("didCommit") } /** * 5. didFinish */ // func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // Print.dlog("didFinish") // webView.evaluateJavaScript("app.showRed('" + "true,false" + "')") { (data, error) in // Print.dlog("调用了JS方法") // Print.dlog(data) // } // } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { Print.dlog("didFail") } func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { Print.dlog("didReceiveServerRedirectForProvisionalNavigation") } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { Print.dlog("didReceive challenge") } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { Print.dlog("didFailProvisionalNavigation") } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { Print.dlog("webViewWebContentProcessDidTerminate") } }
apache-2.0
cc008515656ef50c296acc26c2ca6911
35.99505
203
0.671752
4.664794
false
false
false
false
Prodisky/LASS-Dial
Watch Extension/ComplicationController.swift
1
6139
// // ComplicationController.swift // Watch Extension // // Created by Paul Wu on 2016/1/26. // Copyright © 2016年 Prodisky Inc. All rights reserved. // import ClockKit import WatchKit class ComplicationController: NSObject, CLKComplicationDataSource { private var nextRenewTime = NSDate(timeIntervalSinceNow: 0) private var name = "" private var data = "" private var time = "" var modularImage = StyleKitDial.imageOfDataRing(frame: WKInterfaceDevice.currentDevice().preferredContentSizeCategory == "UICTContentSizeCategoryL" ? CGRectMake(0, 0, 58, 58) : CGRectMake(0, 0, 52, 52), data: "", unit: "", value: 0) var circularImage = StyleKitDial.imageOfDataRing(frame: WKInterfaceDevice.currentDevice().preferredContentSizeCategory == "UICTContentSizeCategoryL" ? CGRectMake(0, 0, 44, 44) : CGRectMake(0, 0, 40, 40), data: "", unit: "", value: 0) private func renew() { if NSDate(timeIntervalSinceNow: 0).timeIntervalSinceDate(nextRenewTime) < 0 { return } nextRenewTime = NSDate(timeIntervalSinceNow: 120) Data.shared.locationManager.requestLocation() Data.shared.getItems({(items:[String]) in guard let item = items.first else { return } Data.shared.getItem(item, got: {(dataItem:Data.Item) in self.name = dataItem.dataName self.modularImage = StyleKitDial.imageOfDataRing(frame: WKInterfaceDevice.currentDevice().preferredContentSizeCategory == "UICTContentSizeCategoryL" ? CGRectMake(0, 0, 58, 58) : CGRectMake(0, 0, 52, 52), data: dataItem.dataString, unit: dataItem.dataUnit, value: dataItem.dataFraction, colorR: dataItem.colorR, colorG: dataItem.colorG, colorB: dataItem.colorB, colorA: dataItem.colorA) self.circularImage = StyleKitDial.imageOfDataRing(frame: WKInterfaceDevice.currentDevice().preferredContentSizeCategory == "UICTContentSizeCategoryL" ? CGRectMake(0, 0, 44, 44) : CGRectMake(0, 0, 40, 40), data: dataItem.dataString, unit: dataItem.dataUnit, value: dataItem.dataFraction, colorR: dataItem.colorR, colorG: dataItem.colorG, colorB: dataItem.colorB, colorA: dataItem.colorA) self.data = dataItem.dataString + " " + dataItem.dataUnit self.time = dataItem.publishTime }) }) } private func getComplicationTemplate(complication: CLKComplication)->CLKComplicationTemplate? { renew() switch complication.family { case .CircularSmall: let template = CLKComplicationTemplateCircularSmallRingImage() template.imageProvider = CLKImageProvider(onePieceImage: circularImage) return template case .ModularSmall: let template = CLKComplicationTemplateModularSmallSimpleImage() template.imageProvider = CLKImageProvider(onePieceImage: modularImage) return template case .ModularLarge: let template = CLKComplicationTemplateModularLargeStandardBody() template.headerTextProvider = CLKSimpleTextProvider(text: name) template.body1TextProvider = CLKSimpleTextProvider(text: data) template.body2TextProvider = CLKSimpleTextProvider(text: time) return template case .UtilitarianSmall: let template = CLKComplicationTemplateUtilitarianSmallFlat() template.textProvider = CLKSimpleTextProvider(text: data) return template case .UtilitarianLarge: let template = CLKComplicationTemplateUtilitarianLargeFlat() template.textProvider = CLKSimpleTextProvider(text: name + ":" + data) return template } } // MARK: - Timeline Configuration func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) { handler([.None]) } func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) { handler(nil) } func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) { handler(nil) } func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) { handler(.ShowOnLockScreen) } // MARK: - Timeline Population func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) { if let complication = self.getComplicationTemplate(complication) { handler(CLKComplicationTimelineEntry(date: NSDate(), complicationTemplate: complication)) } else { handler(nil) } } func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) { // Call the handler with the timeline entries prior to the given date handler(nil) } func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) { // Call the handler with the timeline entries after to the given date handler(nil) } // MARK: - Update Scheduling func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) { // Call the handler with the date when you would next like to be given the opportunity to update your complication content handler(nil); } // MARK: - Placeholder Templates func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) { // This method will be called once per supported complication, and the results will be cached handler(self.getComplicationTemplate(complication)) } func requestedUpdateDidBegin() { if NSDate(timeIntervalSinceNow: 0).timeIntervalSinceDate(nextRenewTime) > 0 { renew() } for complication in CLKComplicationServer.sharedInstance().activeComplications { //Data.shared.Log("ComplicationController requestedUpdateDidBegin extend reload TimelineForComplication") CLKComplicationServer.sharedInstance().extendTimelineForComplication(complication) CLKComplicationServer.sharedInstance().reloadTimelineForComplication(complication) } } }
mit
3ec87632698d75ce50b01063f5ec105c
48.088
390
0.755867
4.85443
false
false
false
false
likumb/SimpleMemo
SimpleMemo/AppDelegate.swift
2
3644
// // AppDelegate.swift // SimpleMemo // // Created by  李俊 on 2017/2/25. // Copyright © 2017年 Lijun. All rights reserved. // import UIKit import CoreData import EvernoteSDK import SMKit enum ShortcutItemType: String { case newMemo = "com.likumb.Memo.newMemo" case paste = "com.likumb.Memo.paste" } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navigationController: UINavigationController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let mainController = MemoListViewController() navigationController = UINavigationController(rootViewController: mainController) window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.white window?.rootViewController = navigationController window?.makeKeyAndVisible() loadDefaultMemos() loadOldMemos() // Need a `EvernoteKey.swift` file, and init `evernoteKey` and `evernoteSecret`. ENSession.setSharedSessionConsumerKey(evernoteKey, consumerSecret: evernoteSecret, optionalHost: nil) ENSession.shared.fetchSimpleMemoNoteBook() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: SMColor.title] return true } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { let didHandle = ENSession.shared.handleOpenURL(url) return didHandle } func applicationDidEnterBackground(_ application: UIApplication) { CoreDataStack.default.saveContext() } func applicationWillTerminate(_ application: UIApplication) { CoreDataStack.default.saveContext() } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { var handle = false guard let shortcutItemType = ShortcutItemType(rawValue: shortcutItem.type) else { completionHandler(handle) return } handle = true var text: String? = nil switch shortcutItemType { case .newMemo: break case .paste: text = UIPasteboard.general.string } let memoVC = MemoViewController(text: text) navigationController?.pushViewController(memoVC, animated: true) completionHandler(handle) } } private extension AppDelegate { func loadDefaultMemos() { let oldVersion = UserDefaults.standard.object(forKey: "MemoVersion") as? String if oldVersion != nil { return } let dict = Bundle.main.infoDictionary! if let version = dict["CFBundleShortVersionString"] as? String { UserDefaults.standard.set(version, forKey: "MemoVersion") } guard let path = Bundle.main.path(forResource: "DefaultMemos", ofType: "plist"), let memos = NSArray(contentsOfFile: path) as? [String] else { return } for memoText in memos { let memo = Memo.newMemo() memo.text = memoText CoreDataStack.default.saveContext() } } func loadOldMemos() { let oldMemos = UserDefaults.standard.object(forKey: "OldMemos") as? String if oldMemos != nil { return } let memos = OldCoreDataStack.sharded.fetchOldMemos() for memo in memos { let newMemo = Memo.newMemo() newMemo.createDate = memo.changeDate newMemo.updateDate = Date() newMemo.isUpload = memo.isUpload newMemo.text = memo.text newMemo.noteRef = memo.noteRef } CoreDataStack.default.saveContext() UserDefaults.standard.set("OldMemos", forKey: "OldMemos") } }
mit
71763f7ebdc2876b70e21ed904989a54
29.049587
153
0.720847
4.505576
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift
27
2244
// // SerialDisposable.swift // Rx // // Created by Krunoslav Zaher on 3/12/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ public class SerialDisposable : DisposeBase, Cancelable { var lock = SpinLock() // state private var _current = nil as Disposable? private var _disposed = false /** - returns: Was resource disposed. */ public var disposed: Bool { get { return _disposed } } /** Initializes a new instance of the `SerialDisposable`. */ override public init() { super.init() } /** Gets or sets the underlying disposable. Assigning this property disposes the previous disposable object. If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. */ public var disposable: Disposable { get { return self.lock.calculateLocked { return self.disposable } } set (newDisposable) { let disposable: Disposable? = self.lock.calculateLocked { if _disposed { return newDisposable } else { let toDispose = _current _current = newDisposable return toDispose } } if let disposable = disposable { disposable.dispose() } } } /** Disposes the underlying disposable as well as all future replacements. */ public func dispose() { let disposable: Disposable? = self.lock.calculateLocked { if _disposed { return nil } else { _disposed = true return _current } } if let disposable = disposable { disposable.dispose() } } }
gpl-3.0
d2ae8a005245a5ddec0c9ac9379a4dcd
25.104651
192
0.547683
5.62406
false
false
false
false
xedin/swift
test/SILGen/objc_dynamic_init.swift
8
2078
// RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/objc_dynamic_init.h %s | %FileCheck %s // REQUIRES: objc_interop import Foundation protocol Hoozit { init() } protocol Wotsit { init() } class Gadget: NSObject, Hoozit { required override init() { super.init() } } // CHECK-LABEL: sil hidden [ossa] @$s17objc_dynamic_init6GadgetCACycfC : $@convention(method) (@thick Gadget.Type) -> @owned Gadget // CHECK: [[OBJC_METATYPE:%.*]] = thick_to_objc_metatype %0 : $@thick Gadget.Type to $@objc_metatype Gadget.Type // CHECK: [[SELF:%.*]] = alloc_ref_dynamic [objc] %1 : $@objc_metatype Gadget.Type, $Gadget // CHECK: [[INIT:%.*]] = function_ref @$s17objc_dynamic_init6GadgetCACycfcTD : $@convention(method) (@owned Gadget) -> @owned Gadget // CHECK: [[NEW_SELF:%.*]] = apply [[INIT]]([[SELF]]) : $@convention(method) (@owned Gadget) -> @owned Gadget // CHECK: return [[NEW_SELF]] // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s17objc_dynamic_init6GadgetCAA6HoozitA2aDPxycfCTW : $@convention(witness_method: Hoozit) (@thick Gadget.Type) -> @out Gadget { // CHECK: function_ref @$s17objc_dynamic_init6GadgetCACycfC class Gizmo: Gadget, Wotsit { required init() { super.init() } } class Thingamabob: ObjCBaseWithInitProto { required init(proto: Int) { super.init(proto: proto) } } final class Bobamathing: Thingamabob { required init(proto: Int) { super.init(proto: proto) } } // CHECK-LABEL: sil hidden [ossa] @$s17objc_dynamic_init8callInityyF : $@convention(thin) () -> () // CHECK: [[METATYPE:%.*]] = metatype $@thick Gadget.Type // CHECK: [[CTOR:%.*]] = function_ref @$s17objc_dynamic_init6GadgetCACycfC // CHECK: [[INSTANCE:%.*]] = apply [[CTOR]]([[METATYPE]]) // CHECK: destroy_value [[INSTANCE]] func callInit() { let metatype = Gadget.self _ = metatype.init() } // CHECK-LABEL: sil_vtable Gadget { // CHECK-NOT: #Gadget.init!allocator.1 // CHECK-LABEL: sil_vtable Gizmo { // CHECK-NOT: #Gadget.init!allocator.1
apache-2.0
0394aaec0bea9c78f04a8e882abd37ce
31.984127
185
0.655919
3.17737
false
false
false
false
sekouperry/news-pro
codecanyon-11884937-wp-news-pro/Code_Documentation/Code/WPNews2/WPNews2/ISInAppBrowser.swift
1
7179
// // ISInAppBrowser.swift // SwiftInAppBrowswer // // Created by Istvan Szabo on 2014. 12. 28.. // Copyright (c) 2014. Istvan Szabo. All rights reserved. // import UIKit import MessageUI import Social class ISInAppBrowser: UIViewController, UIWebViewDelegate, MFMailComposeViewControllerDelegate { @IBOutlet var webView: UIWebView! @IBOutlet var activity: UIActivityIndicatorView! @IBOutlet var backButton: UIBarButtonItem! @IBOutlet var forwardButton: UIBarButtonItem! @IBOutlet weak var progressBar: UIProgressView! var webTitle: String! var sidebar: ISFrostedSidebar! var webViewLoads:Int = 0 override func viewDidLoad() { super.viewDidLoad() self.progressBar.hidden = true let url = NSURL(string:webTitle) let request = NSURLRequest(URL: url!) webView.loadRequest(request) sidebar = ISFrostedSidebar(itemImages: [ UIImage(named: "Safari")!, UIImage(named: "Facebook")!, UIImage(named: "Twitter")!, UIImage(named: "SendMail")!, UIImage(named: "Dismiss")!], colors: [ UIColor(red: 240/255, green: 159/255, blue: 254/255, alpha: 0.1), UIColor(red: 240/255, green: 159/255, blue: 254/255, alpha: 0.1), UIColor(red: 255/255, green: 137/255, blue: 167/255, alpha: 0.1), UIColor(red: 126/255, green: 242/255, blue: 195/255, alpha: 0.1), UIColor(red: 119/255, green: 152/255, blue: 255/255, alpha: 0.1)], selectedItemIndices: NSIndexSet(index: 0)) sidebar.isSingleSelect = true sidebar.actionForIndex = [ 0: {self.sidebar.dismissAnimated(true, completion: { finished in self.openSafari()}) }, 1: {self.sidebar.dismissAnimated(true, completion: { finished in self.facebookComposer()}) }, 2: {self.sidebar.dismissAnimated(true, completion: { finished in self.twitterComposer()}) }, 3: {self.sidebar.dismissAnimated(true, completion: { finished in self.sendEmail()}) }, 4: {self.sidebar.dismissAnimated(true, completion: { finished in println("Dismiss")}) },] } @IBAction func openFrosted(sender: AnyObject) { self.sidebar.showInViewController(self, animated: true) } @IBAction func close(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func back(sender: AnyObject) { webView.goBack() } @IBAction func forw(sender: AnyObject) { webView.goForward() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true); var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateStatusBar"), userInfo: nil, repeats: false); } func updateStatusBar() { UIApplication.sharedApplication().statusBarHidden=true; } func openSafari() { let alert = ISAlertView() alert.addButton("Open Safari") { println("Open Safari") UIApplication.sharedApplication().openURL(NSURL(string:self.webTitle)!); } alert.showOpenSafari(("Open existing browser"), subTitle:("Please choose") ) } func facebookComposer(){ var controller: SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook) controller.setInitialText("InAppBrowser") controller.addImage(nil) self.presentViewController(controller, animated: true, completion: nil) } func twitterComposer(){ var controller: SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter) controller.setInitialText("InAppBrowser") controller.addImage(nil) self.presentViewController(controller, animated: true, completion: nil) } func webViewDidStartLoad(webView: UIWebView) { activity.startAnimating() self.backButton.enabled = self.webView.canGoBack self.forwardButton.enabled = self.webView.canGoForward if webViewLoads == 0 { self.startLoadingProgressBar() } webViewLoads++ } func webViewDidFinishLoad(webView: UIWebView) { activity.stopAnimating() self.backButton.enabled = self.webView.canGoBack self.forwardButton.enabled = self.webView.canGoForward webViewLoads-- if webViewLoads == 0 { self.stopLoadingProgressBar() } } func webView(webView: UIWebView, didFailLoadWithError error: NSError) { webViewLoads-- } var timer:NSTimer! var isLoading:Bool! func startLoadingProgressBar() { self.progressBar.hidden = false self.progressBar.progress = 0 isLoading = true timer = NSTimer.scheduledTimerWithTimeInterval(0.016667, target: self, selector: "timerCallback", userInfo: nil, repeats: true) } func stopLoadingProgressBar() { isLoading = false } func timerCallback() { if (isLoading == true) { self.progressBar.progress += 0.01 if self.progressBar.progress > 0.95 { self.progressBar.progress = 0.95 } } else { if self.progressBar.progress >= 1 { timer.invalidate() self.progressBar.hidden = true } else { self.progressBar.progress += 0.05 } } } func sendEmail(){ let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.presentViewController(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() } } func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setToRecipients(["[email protected]"]) //Customize, add your mail mailComposerVC.setSubject("Sending you an in InAppBrowser e-mail...") mailComposerVC.setMessageBody("Sending e-mail in InAppBrowser is not so bad!", isHTML: false) return mailComposerVC } func showSendMailErrorAlert() { let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK") sendMailErrorAlert.show() } // MARK: MFMailComposeViewControllerDelegate Method func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { controller.dismissViewControllerAnimated(true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
a6a58c7f8b27cbd2d72c8660619c5581
35.075377
213
0.640897
5.109609
false
false
false
false
Tangdixi/DCExplosion
Example (Explodable)/Example (Explodable)/CellController.swift
1
1590
// // ViewController.swift // Example (Explodable) // // Created by tang dixi on 7/6/2016. // Copyright © 2016 Tangdixi. All rights reserved. // import UIKit extension UIView:Explodable { } var data = ["1", "2", "3", "4", "5"] class CellController: UIViewController, Explodable { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. data = ["1", "2", "3", "4", "5"] } @IBAction func refreshTapped(_ sender: AnyObject) { data = ["1", "2", "3", "4", "5", "6"] tableView.reloadData() } } extension CellController:UITableViewDelegate { func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } } extension CellController:UITableViewDataSource { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.explodeRowAtIndexPath(indexPath, duration:1 ,direction: .right) { data.remove(at: indexPath.row) } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.imageView?.image = UIImage(named: "image") cell.textLabel?.text = data[indexPath.row] return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } }
mit
db64f44f5c4b980e2b23a798e9163616
23.446154
98
0.676526
4.074359
false
false
false
false
Chris-Perkins/Lifting-Buddy
Lifting Buddy/HeaderView.swift
1
10478
// // HeaderView.swift // Lifting Buddy // // Created by Christopher Perkins on 7/20/17. // Copyright © 2017 Christopher Perkins. All rights reserved. // /// Header View shown at the top of the application at all times import UIKit import CDAlertView import GBVersionTracking class HeaderView: UIView { // MARK: View properties // Lifting Buddy's URL private static let appURL = URL(string: "http://chrisperkins.me/LiftingBuddy/")! // Bar below status bar public let contentView: UIView // Bar that displays title of app public let titleBar: UILabel // Button to display info about the app public let aboutButton: UIButton // Dividing bar public let divideView: UIView // View for different buttons public let sectionView: SectionView // MARK: View inits override init(frame: CGRect) { contentView = UIView() titleBar = UILabel() aboutButton = UIButton() divideView = UIView() sectionView = SectionView() super.init(frame: frame) aboutButton.addTarget(self, action: #selector(aboutButtonPress(sender:)), for: .touchUpInside) addSubview(contentView) contentView.addSubview(titleBar) contentView.addSubview(aboutButton) contentView.addSubview(divideView) contentView.addSubview(sectionView) createAndActivateContentViewConstraints() createAndActivateTitleBarConstraints() createAndActiveAboutButtonConstraints() createAndActivateDivideViewConstraints() createAndActivateSectionViewConstraints() } required init?(coder aDecoder: NSCoder) { contentView = UIView() titleBar = UILabel() aboutButton = UIButton() divideView = UIView() sectionView = SectionView() super.init(coder: aDecoder) aboutButton.addTarget(self, action: #selector(aboutButtonPress(sender:)), for: .touchUpInside) addSubview(contentView) contentView.addSubview(titleBar) contentView.addSubview(aboutButton) contentView.addSubview(divideView) contentView.addSubview(sectionView) createAndActivateContentViewConstraints() createAndActivateTitleBarConstraints() createAndActiveAboutButtonConstraints() createAndActivateDivideViewConstraints() createAndActivateSectionViewConstraints() } // MARK: View overrides override func layoutSubviews() { super.layoutSubviews() // Self backgroundColor = .niceBlue // title bar titleBar.text = NSLocalizedString("Info.AppName", comment: "") titleBar.font = titleBar.font.withSize(20.0) titleBar.textColor = .white titleBar.textAlignment = .center // About button aboutButton.setImage(#imageLiteral(resourceName: "Info"), for: .normal) // divide view divideView.layer.zPosition = 1 divideView.backgroundColor = .primaryBlackWhiteColor divideView.alpha = 0.2 } // MARK: Event functions // Shows information about the app on dialog open @objc private func aboutButtonPress(sender: UIButton) { viewContainingController()?.performSegue(withIdentifier: "toSettings", sender: viewContainingController()) } // MARK: Constraints // Cling to top, bottom, left, right private func createAndActivateContentViewConstraints() { contentView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: contentView, withCopyView: self, attribute: .top, plusConstant: statusBarHeight).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: contentView, withCopyView: self, attribute: .bottom).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: contentView, withCopyView: self, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: contentView, withCopyView: self, attribute: .right).isActive = true } // Cling to top of contentview, bottom to divideView ; centerx and width copy from contentview private func createAndActivateTitleBarConstraints() { titleBar.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleBar, withCopyView: contentView, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleBar, withCopyView: divideView, attribute: .bottom).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleBar, withCopyView: contentView, attribute: .centerX).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleBar, withCopyView: contentView, attribute: .width, plusConstant: -100).isActive = true } // Place a little from the right of the contentview's right ; center vertically in container // height/width 32. private func createAndActiveAboutButtonConstraints() { aboutButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: aboutButton, withCopyView: contentView, attribute: .right, plusConstant: -10).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: aboutButton, withCopyView: contentView, attribute: .top, plusConstant: 10).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: aboutButton, withCopyView: divideView, attribute: .bottom, plusConstant: -10).isActive = true NSLayoutConstraint(item: aboutButton, attribute: .height, relatedBy: .equal, toItem: aboutButton, attribute: .width, multiplier: 1, constant: 0).isActive = true } // center vert in contentview ; cling to left, right to content view ; height 1 private func createAndActivateDivideViewConstraints() { divideView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: divideView, withCopyView: contentView, attribute: .centerY, plusConstant: 5).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: divideView, withCopyView: contentView, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: divideView, withCopyView: contentView, attribute: .right).isActive = true NSLayoutConstraint.createHeightConstraintForView(view: divideView, height: 1).isActive = true } // cling to top of divideview ; bottom,left,right of contentView private func createAndActivateSectionViewConstraints() { sectionView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.createViewAttributeCopyConstraint(view: sectionView, withCopyView: divideView, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: sectionView, withCopyView: contentView, attribute: .bottom).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: sectionView, withCopyView: contentView, attribute: .left).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: sectionView, withCopyView: contentView, attribute: .right).isActive = true } }
mit
83bc503f6500f7f35031b2832c44566f
46.40724
114
0.516942
7.853823
false
false
false
false
sschiau/swift
test/IRGen/opaque_result_type_substitution.swift
2
3364
// RUN: %target-swift-frontend -disable-availability-checking -emit-ir -primary-file %s | %FileCheck %s protocol E {} struct Pair<T, V> : E { var fst : T var snd : V init(_ f: T, _ s: V) { self.fst = f self.snd = s } func foobar() -> some E { return self } } public func usePair<T, V>(_ t: T, _ v: V) { var x = Pair(t, v) let q = x.foobar() let u = x.foobar() let p = Pair(q, u) print(p) } protocol P { } struct C<S : Hashable> { struct Inner {} init(_ s: S) { } func getInner() -> Inner { return Inner() } } struct O<T> { var t: T init(_ t: T) { self.t = t } } struct M<T, V> : P { init(_ f: T, _ s: V) { } func foobar() -> some P { return self } } public func test2<S : Hashable, T, V>(_ s: S, _ t: T, _ v: V) { var x = M(C(s).getInner(), t) let q = x.foobar() let u = x.foobar() let y = O(q) print(y) } // CHECK-LABEL: define{{.*}} swiftcc void @"$s31opaque_result_type_substitution7usePairyyx_q_tr0_lF"({{.*}}, %swift.type* %T, %swift.type* %V) // CHECK: [[PAIR_TV:%.*]] = call swiftcc %swift.metadata_response @"$s31opaque_result_type_substitution4PairVMa"({{.*}}, %swift.type* %T, %swift.type* %V) // CHECK: [[MD:%.*]] = extractvalue %swift.metadata_response [[PAIR_TV]], 0 // CHECK: [[PAIR_OPAQUE:%.*]] = call swiftcc %swift.metadata_response @"$s31opaque_result_type_substitution4PairVMa"({{.*}}, %swift.type* [[MD]], %swift.type* [[MD]]) // CHECK: [[MD2:%.*]] = extractvalue %swift.metadata_response [[PAIR_OPAQUE]], 0 // CHECK: call {{.*}}* @"$s31opaque_result_type_substitution4PairVyAC6foobarQryFQOyxq__Qo_AEGr0_lWOh"({{.*}}, %swift.type* {{.*}}, %swift.type* [[MD2]]) public protocol Thing { } public struct Thingy : Thing {} public protocol KeyProto { associatedtype Value } extension KeyProto { public static func transform3<T : Thing>( _ transform: @escaping (A<Self>) -> T) -> some Thing { return Thingy() } } public struct A<Key : KeyProto> {} extension A { public func transform2<T>(_ transform: @escaping (Key.Value) -> T) -> Thingy { return Thingy() } } struct AKey : KeyProto { typealias Value = Int } extension Thing { public func transform<K>(key _: K.Type = K.self, transform: @escaping (inout K) -> Void) -> some Thing { return Thingy() } } struct OutterThing<Content : Thing> : Thing { let content: Content init(_ c: Content) { self.content = c } var body: some Thing { return AKey.transform3 { y in y.transform2 { i in self.content.transform( key: Thingy.self) { value in } } } } } public protocol W {} struct Key : W {} extension W { public static func transform(_ transform: @escaping (P1<Self>) -> ()) -> some W { return Key() } } public struct P1<Key : W> { } extension P1 { public func transform2<T>(_ transform: @escaping (Key) -> T) { } } public struct T<Content> : W { public init(content : ()->Content) {} } public struct Content<Content> : W { public init(content: Content) {} } extension W { func moo() -> some W { return Content(content: self) } } struct Test<Label : W> { var label: Label // This function used to crash. var dontCrash: some W { return Key.transform { y in y.transform2 { i in T() { return self.label }.moo() } } } }
apache-2.0
29d476b363c560371f90cae00c0ef92f
19.512195
167
0.58264
3.041591
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCryptoDomain/Sources/FeatureCryptoDomainDomain/Models/OrderDomainUserInfo.swift
1
776
// Copyright © Blockchain Luxembourg S.A. All rights reserved. public struct OrderDomainUserInfo: Equatable { public let nabuUserId: String public let nabuUserName: String? public let resolutionRecords: [ResolutionRecord] public init( nabuUserId: String, nabuUserName: String?, resolutionRecords: [ResolutionRecord] ) { self.nabuUserId = nabuUserId self.nabuUserName = nabuUserName self.resolutionRecords = resolutionRecords } } public struct ResolutionRecord: Equatable { public let symbol: String public let walletAddress: String public init( symbol: String, walletAddress: String ) { self.symbol = symbol self.walletAddress = walletAddress } }
lgpl-3.0
29c5070393c167420db86e58a20924be
24.833333
62
0.673548
4.813665
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Tests/FeatureTransactionDomainTests/QuotesEngineTests.swift
1
2538
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine @testable import FeatureTransactionDomain import TestKit import XCTest final class QuotesEngineTest: XCTestCase { var sut: QuotesEngine! var expirationTimer: PassthroughSubject<Void, Never>! override func setUp() { super.setUp() expirationTimer = .init() sut = QuotesEngine( repository: OrderQuoteRepositoryMock(), timer: { _ in self.expirationTimer.eraseToAnyPublisher() } ) } override func tearDown() { expirationTimer = nil sut = nil super.tearDown() } func test_emitsData_immediatelyAfterStartPolling() throws { let e = expectation(description: "Returns Quote") e.expectedFulfillmentCount = 1 let cancellable = sut.quotePublisher .sink(receiveValue: { _ in e.fulfill() }) sut.startPollingRate(direction: .onChain, pair: .btc_eth) wait(for: [e], timeout: 5) cancellable.cancel() } func test_emitsData_immediatelyAfterAmountUpdate() throws { let e = expectation(description: "Returns Quote") e.expectedFulfillmentCount = 2 let cancellable = sut.quotePublisher .sink(receiveValue: { _ in e.fulfill() }) sut.startPollingRate(direction: .onChain, pair: .btc_eth) sut.update(amount: 100) wait(for: [e], timeout: 5) cancellable.cancel() } func test_emitsData_afterQuoteExpiratonStartPolling() throws { let e = expectation(description: "Returns Quote") e.expectedFulfillmentCount = 3 let cancellable = sut.quotePublisher .sink(receiveValue: { _ in e.fulfill() }) sut.startPollingRate(direction: .onChain, pair: .btc_eth) expirationTimer.send(()) expirationTimer.send(()) wait(for: [e], timeout: 5) cancellable.cancel() } func test_stopsEmittingData_afterStopSignal() throws { let e = expectation(description: "Returns Quote") e.expectedFulfillmentCount = 1 let cancellable = sut.quotePublisher .sink(receiveValue: { _ in e.fulfill() }) sut.startPollingRate(direction: .onChain, pair: .btc_eth) sut.stop() sut.update(amount: 100) expirationTimer.send(()) wait(for: [e], timeout: 5) cancellable.cancel() } }
lgpl-3.0
09ce199324e62276a21e7a6e4a91878c
26.27957
70
0.598345
4.530357
false
true
false
false
tensorflow/examples
lite/examples/speech_commands/ios/SpeechCommands/ModelDataHandler/ModelDataHandler.swift
1
8728
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import TensorFlowLite import UIKit /// A result from invoking the `Interpreter`. struct Result { let recognizedCommand: RecognizedCommand? let inferenceTime: Double } /// Information about a model file or labels file. typealias FileInfo = (name: String, extension: String) /// Information about the ConvActions model. enum ConvActions { static let modelInfo: FileInfo = (name: "conv_actions_frozen", extension: "tflite") static let labelsInfo: FileInfo = (name: "conv_actions_labels", extension: "txt") } /// This class handles all data preprocessing and makes calls to run inference on a given audio /// buffer by invoking the TensorFlow Lite `Interpreter`. It then formats the inferences obtained /// and averages the recognized commands by running them through RecognizeCommands. class ModelDataHandler { // MARK: - Internal Properties /// The current thread count used by the TensorFlow Lite Interpreter. let threadCount: Int let threadCountLimit = 10 let sampleRate = 16000 // MARK: - Private Properties private var buffer:[Int] = [] private var recognizeCommands: RecognizeCommands? private let audioBufferInputTensorIndex = 0 private let sampleRateInputTensorIndex = 1 private let labelOffset = 2 private let sampleDuration = 1000 private let minimumCount = 3 private let averageWindowDuration = 1000.0 private let suppressionMs = 1500.0 private let threshold = 0.5 private let minTimeBetweenSamples = 30.0 private let maxInt16AsFloat32: Float32 = 32767.0 /// List of labels from the given labels file. private var labels: [String] = [] /// TensorFlow Lite `Interpreter` object for performing inference on a given model. private var interpreter: Interpreter private var recordingLength: Int { return (sampleRate * sampleDuration) / 1000 } // MARK: - Initialization /// A failable initializer for `ModelDataHandler`. A new instance is created if the model and /// labels files are successfully loaded from the app's main bundle. Default `threadCount` is 1. init?(modelFileInfo: FileInfo, labelsFileInfo: FileInfo, threadCount: Int = 1) { let modelFilename = modelFileInfo.name // Construct the path to the model file. guard let modelPath = Bundle.main.path( forResource: modelFilename, ofType: modelFileInfo.extension ) else { print("Failed to load the model file with name: \(modelFilename).") return nil } // Specify the options for the `Interpreter`. self.threadCount = threadCount var options = InterpreterOptions() options.threadCount = threadCount do { // Create the `Interpreter`. interpreter = try Interpreter(modelPath: modelPath, options: options) // Allocate memory for the model's input `Tensor`s. try interpreter.allocateTensors() } catch let error { print("Failed to create the interpreter with error: \(error.localizedDescription)") return nil } loadLabels(fileInfo: labelsFileInfo) recognizeCommands = RecognizeCommands( averageWindowDuration: averageWindowDuration, detectionThreshold: 0.3, minimumTimeBetweenSamples: minTimeBetweenSamples, suppressionTime: suppressionMs, minimumCount: minimumCount, classLabels: labels ) } // MARK: - Internal Methods /// Invokes the `Interpreter` and processes and returns the inference results. func runModel(onBuffer buffer: [Int16]) -> Result? { let interval: TimeInterval let outputTensor: Tensor do { // Copy the `[Int16]` buffer data as an array of `Float`s to the audio buffer input `Tensor`'s. let audioBufferData = Data(copyingBufferOf: buffer.map { Float($0) / maxInt16AsFloat32 }) try interpreter.copy(audioBufferData, toInputAt: audioBufferInputTensorIndex) // Copy the sample rate data to the sample rate input `Tensor`. var rate = Int32(sampleRate) let sampleRateData = Data(bytes: &rate, count: MemoryLayout.size(ofValue: rate)) try interpreter.copy(sampleRateData, toInputAt: sampleRateInputTensorIndex) // Run inference by invoking the `Interpreter`. let startDate = Date() try interpreter.invoke() interval = Date().timeIntervalSince(startDate) * 1000 // Get the output `Tensor` to process the inference results. outputTensor = try interpreter.output(at: 0) } catch let error { print("Failed to invoke the interpreter with error: \(error.localizedDescription)") return nil } // Gets the formatted and averaged results. let scores = [Float32](unsafeData: outputTensor.data) ?? [] let command = getResults(withScores: scores) // Returns result. let result = Result(recognizedCommand: command, inferenceTime: interval) return result } /// Returns the labels other than silence and unknown for display. func offsetLabelsForDisplay() -> [String] { return Array(labels[labelOffset..<labels.count]) } // MARK: - Private Methods /// Formats the results and runs them through Recognize Commands to average the results over a /// window duration. private func getResults(withScores scores: [Float]) -> RecognizedCommand? { var results: [Float] = [] for i in 0..<labels.count { results.append(scores[i]) } // Runs results through recognize commands. let command = recognizeCommands?.process( latestResults: results, currentTime: Date().timeIntervalSince1970 * 1000 ) // Check if command is new and the identified result is not silence or unknown. guard let newCommand = command, let index = labels.index(of: newCommand.name), newCommand.isNew, index >= labelOffset else { return nil } return newCommand } /// Loads the labels from the labels file and stores them in the `labels` property. private func loadLabels(fileInfo: FileInfo) { let filename = fileInfo.name let fileExtension = fileInfo.extension guard let fileURL = Bundle.main.url(forResource: filename, withExtension: fileExtension) else { fatalError("Labels file not found in bundle. Please add a labels file with name " + "\(filename).\(fileExtension) and try again.") } do { let contents = try String(contentsOf: fileURL, encoding: .utf8) labels = contents.components(separatedBy: .newlines) } catch { fatalError("Labels file named \(filename).\(fileExtension) cannot be read. Please add a " + "valid labels file and try again.") } } } // MARK: - Extensions extension Data { /// Creates a new buffer by copying the buffer pointer of the given array. /// /// - Warning: The given array's element type `T` must be trivial in that it can be copied bit /// for bit with no indirection or reference-counting operations; otherwise, reinterpreting /// data from the resulting buffer has undefined behavior. /// - Parameter array: An array with elements of type `T`. init<T>(copyingBufferOf array: [T]) { self = array.withUnsafeBufferPointer(Data.init) } } extension Array { /// Creates a new array from the bytes of the given unsafe data. /// /// - Warning: The array's `Element` type must be trivial in that it can be copied bit for bit /// with no indirection or reference-counting operations; otherwise, copying the raw bytes in /// the `unsafeData`'s buffer to a new array returns an unsafe copy. /// - Note: Returns `nil` if `unsafeData.count` is not a multiple of /// `MemoryLayout<Element>.stride`. /// - Parameter unsafeData: The data containing the bytes to turn into an array. init?(unsafeData: Data) { guard unsafeData.count % MemoryLayout<Element>.stride == 0 else { return nil } #if swift(>=5.0) self = unsafeData.withUnsafeBytes { .init($0.bindMemory(to: Element.self)) } #else self = unsafeData.withUnsafeBytes { .init(UnsafeBufferPointer<Element>( start: $0, count: unsafeData.count / MemoryLayout<Element>.stride )) } #endif // swift(>=5.0) } }
apache-2.0
be36d59b65200076585d559b823504d7
35.983051
101
0.702108
4.453061
false
false
false
false
hbang/TermHere
TermHere Common/ServiceRunner.swift
1
2690
// // ServiceRunner.swift // TermHere // // Created by Adam Demasi on 17/11/17. // Copyright © 2017 HASHBANG Productions. All rights reserved. // import Cocoa class ServiceRunner { fileprivate static var pasteboard: NSPasteboard = { let bundleIdentifier = Bundle.main.bundleIdentifier! return NSPasteboard(name: NSPasteboard.Name(rawValue: "\(bundleIdentifier).pasteboard")) }() class func serviceName(forAppURL appURL: URL, fallbackAppURL: URL, fallbackService: String) -> String { // get the bundle for the user specified app, or our fallback if necessary guard let bundle = Bundle(url: appURL) ?? Bundle(url: fallbackAppURL) else { fatalError("specified app and fallback app not found!") } return serviceName(forBundle: bundle) ?? fallbackService } class func serviceName(forBundle bundle: Bundle) -> String? { let activationType = Preferences.sharedInstance.terminalActivationType var serviceName: String? = nil // if we’re aware of a service we can directly use, we definitely want to use that. otherwise // we’re stuck trying a url open via NSWorkspace if bundle.bundleIdentifier! == "com.apple.Terminal" { switch activationType { case .newTab, .sameTab: serviceName = "New Terminal Tab at Folder" break case .newWindow: serviceName = "New Terminal at Folder" break } } else if bundle.bundleIdentifier! == "com.googlecode.iterm2" { switch activationType { case .newTab, .sameTab: serviceName = "New iTerm2 Tab Here" break case .newWindow: serviceName = "New iTerm2 Window Here" break } } return serviceName } class func run(service: String, withFileURLs fileURLs: [URL]) -> Bool { // completely undocumented as far as i can tell, but NSPerformService() must be called from the // main thread. otherwise it’ll crash when displaying error messages as an NSAlert() because it // doesn’t jump to the main thread before calling runModal! // TODO: radar if !Thread.isMainThread { fatalError("ServiceRunner.run() called from non-main thread!") } var pasteboardItems: [NSPasteboardItem] = [] // loop over each item and create an NSPasteboardItem for it. this allows us to send all items // to the service in one go for url in fileURLs { let item = NSPasteboardItem() item.setString(url.path, forType: .compatString) pasteboardItems.append(item) } pasteboard.declareTypes([ .compatString ], owner: nil) pasteboard.writeObjects(pasteboardItems) if !NSPerformService(service, self.pasteboard) { NSLog("service execution failed, and we don’t know why!!") return false } return true } }
apache-2.0
ca71059521997aa197d90bce8d17c11d
29.101124
104
0.709593
3.849138
false
false
false
false
vmachiel/swift
LearningSwift.playground/Pages/Tuples and Multiple Return Types.xcplaygroundpage/Contents.swift
1
1997
// Tuples are just a group of values. Use them anywhere you use a type. // This one has a type of String, Int, Double let tupleValues: (String, Int, Double) = ("Hello", 5, 0.58) // They can be used to assign many variables at once (unpacking) let (word, number, value) = tupleValues print(number) // You can access tuple values by index: print(tupleValues.2) // Or you can name tuples, which is preferred. let tupleValues2: (w: String, i: Int, v: Double) = ("Hello", 5, 0.58) print(tupleValues2.w) // you can stil unpack: let (word2, number2, value2) = tupleValues2 // or you can even skip an unpack: let (word3, _, value3) = tupleValues // Now the second element of the tuple isn't set to a variable. print(word3) print(value3) // As seen in functions, tuples can be return types: func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { // initial values, made with array values var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } else if score < min { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics(scores: [4, 130, 34, 9, 11, 94]) statistics.sum // access by name! statistics.2 // access by index! // You can use tuples to tests multiple values let somePoint = (1, 1) switch somePoint { case (0, 0): print("It's on the origin") case (_, 0): print("It's somewhere on the x asis") case (0, _): print("It's somewhere on the y asis") case (-2...2, -2...2): print("I'ts inside or one the box") default: print("I'ts outside of the box") } // Using where in tuples: let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y: print("(\(x), \(y)) is on the line x == y") case let (x, y) where x == -y: print("(\(x), \(y)) is on the line x == -y") case let (x, y): print("(\(x), \(y)) is just some arbitrary point") }
mit
fa1591b35e574380a6b06640c616416f
23.353659
75
0.61993
3.257749
false
false
false
false
xiaowinner/YXWShineButton
YXWShineClickLayer.swift
1
1774
import UIKit @objc public class YXWShineClickLayer: CALayer { var color: UIColor = UIColor.lightGray var fillColor: UIColor = UIColor(rgb: (255, 102, 102)) var image: YXWShineImage = .heart { didSet { maskLayer.contents = image.getImage()?.cgImage } } var animDuration: Double = 0.5 var clicked: Bool = false { didSet { if clicked { backgroundColor = fillColor.cgColor }else { backgroundColor = color.cgColor } } } let maskLayer = CALayer() //MARK: Public Methods func startAnim() { let anim = CAKeyframeAnimation(keyPath: "transform.scale") anim.duration = animDuration anim.values = [0.4, 1, 0.9, 1] anim.calculationMode = kCAAnimationCubic maskLayer.add(anim, forKey: "scale") } //MARK: Override override public func layoutSublayers() { maskLayer.frame = bounds if clicked { backgroundColor = fillColor.cgColor }else { backgroundColor = color.cgColor } maskLayer.contents = image.getImage()?.cgImage } //MARK: Initial Methods override init() { super.init() mask = maskLayer } override init(layer: Any) { super.init(layer: layer) if mask == nil { mask = maskLayer } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
333807ef058da752e19039fa5b89d511
20.373494
66
0.490981
5.408537
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Extension/Date.swift
1
2298
// // Date.swift // selluv-ios // // Created by 조백근 on 2017. 1. 12.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import Foundation extension Date { static func isBetween(start: Date, end: Date) -> Bool { return Date.isBetween(start: start, end: end, someday: Date()) } static func isBetween(start: Date, end: Date, someday: Date) -> Bool { let fallsBetween = (start...end).contains(someday) return fallsBetween } static func timeAgoSince(_ date: Date) -> String { let calendar = Calendar.current let now = Date() let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year] let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: []) if let year = components.year, year >= 2 { return "\(year) 년 전" } if let year = components.year, year >= 1 { return "지난해" } if let month = components.month, month >= 2 { return "\(month) 개월 전" } if let month = components.month, month >= 1 { return "지난달" } if let week = components.weekOfYear, week >= 2 { return "\(week) 주 전" } if let week = components.weekOfYear, week >= 1 { return "지난주" } if let day = components.day, day >= 2 { return "\(day) 일 전" } if let day = components.day, day >= 1 { return "어제" } if let hour = components.hour, hour >= 2 { return "\(hour) 시간 전" } if let hour = components.hour, hour >= 1 { return "한시간 전" } if let minute = components.minute, minute >= 2 { return "\(minute) 분 전" } if let minute = components.minute, minute >= 1 { return "일분전" } if let second = components.second, second >= 3 { return "\(second) seconds ago" } return "지금" } }
mit
c19f086f68731df9331c0336aaa29413
24.528736
105
0.478163
4.060329
false
false
false
false
6ag/BaoKanIOS
BaoKanIOS/Classes/Module/News/View/Column/JFEditColumnViewCell.swift
1
3115
// // JFEditColumnCollectionViewCell.swift // BaoKanIOS // // Created by zhoujianfeng on 16/5/31. // Copyright © 2016年 六阿哥. All rights reserved. // import UIKit protocol JFEditColumnViewCellDelegate { func deleteItemWithIndexPath(_ indexPath: IndexPath) -> Void } class JFEditColumnViewCell: UICollectionViewCell { var delegate: JFEditColumnViewCellDelegate? var indexPath: IndexPath? override init(frame: CGRect) { super.init(frame: frame) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 准备UI */ fileprivate func prepareUI() { contentView.backgroundColor = UIColor.clear contentView.addSubview(contentLabel) contentView.addSubview(deleteButton) } /** 配置cell */ func configCell(_ dataArray: [[String : String]], withIndexPath indexPath: IndexPath) { self.indexPath = indexPath contentLabel.isHidden = false contentLabel.text = dataArray[indexPath.row]["classname"]! if (indexPath.section == 0 && indexPath.row == 0) { contentLabel.textColor = UIColor.colorWithRGB(214, g: 39, b: 48) contentLabel.layer.masksToBounds = true contentLabel.layer.borderColor = UIColor.clear.cgColor contentLabel.layer.borderWidth = 0.0 } else { contentLabel.textColor = UIColor.colorWithRGB(101, g: 101, b: 101) contentLabel.layer.masksToBounds = true contentLabel.layer.cornerRadius = self.contentView.bounds.height * 0.5 contentLabel.layer.borderColor = UIColor.colorWithRGB(211, g: 211, b: 211).cgColor; contentLabel.layer.borderWidth = 0.45 } } /** 点击了删除按钮 */ func didTappedDeleteButton(_ button: UIButton) { delegate?.deleteItemWithIndexPath(indexPath!) } deinit { if let gestures = gestureRecognizers { for pan in gestures { removeGestureRecognizer(pan) } } } // MARK: - 懒加载 lazy var contentLabel: UILabel = { let contentLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.contentView.bounds.size.width, height: self.contentView.bounds.size.height)) contentLabel.center = self.contentView.center contentLabel.textAlignment = NSTextAlignment.center contentLabel.font = UIFont.systemFont(ofSize: 15) contentLabel.numberOfLines = 1 contentLabel.adjustsFontSizeToFitWidth = true contentLabel.minimumScaleFactor = 0.1 return contentLabel }() lazy var deleteButton: UIButton = { let deleteButton = UIButton(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) deleteButton.setBackgroundImage(UIImage(named: "delete"), for: UIControlState()) deleteButton.addTarget(self, action: #selector(didTappedDeleteButton(_:)), for: UIControlEvents.touchUpInside) return deleteButton }() }
apache-2.0
07fbb787d4d95a4b35e41ba0cd163740
31.744681
149
0.638402
4.885714
false
false
false
false
iCodeForever/ifanr
ifanr/ifanr/Controllers/MainViewController/MainViewController.swift.LOCAL.6044.swift
1
5230
// // MainViewController.swift // ifanr // // Created by 梁亦明 on 16/6/29. // Copyright © 2016年 ifanrOrg. All rights reserved. // /** 主界面 这个控制器用来控制 首页,玩物志,快讯,Appso,MindStore和菜单界面 */ import UIKit class MainViewController: UIViewController { //MARK: --------------------------- Life Cycle -------------------------- override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.blackColor() self.view.addSubview(collectionView) self.view.addSubview(fpsLabel) // 添加根控制器 self.addrootViewController() self.view.addSubview(headerView) self.view.addSubview(self.hamburgButton) self.view.addSubview(self.circleButton) self.setUpLayout() } /** 隐藏状态栏 */ override func prefersStatusBarHidden() -> Bool { return true } //MARK: --------------------------- Private Methods -------------------------- /** 添加跟控制器 */ private func addrootViewController() { self.addChildViewController(newsFlashController) self.addChildViewController(homeViewController) self.addChildViewController(playzhiController) self.addChildViewController(appSoController) self.addChildViewController(mindStoreController) homeViewController.view.size = CGSize(width: self.view.width, height: self.view.height-20) viewArray.append(newsFlashController.view) viewArray.append(homeViewController.view) viewArray.append(playzhiController.view) viewArray.append(appSoController.view) viewArray.append(mindStoreController.view) } // 布局 private func setUpLayout() { self.hamburgButton.snp_makeConstraints { (make) in make.right.equalTo(-15) make.top.equalTo(35) make.width.height.equalTo(45) } self.circleButton.snp_makeConstraints { (make) in make.left.equalTo(15) make.top.equalTo(35) make.width.height.equalTo(45) } } //MARK: --------------------------- Getter and Setter -------------------------- // 首页 let homeViewController = HomeViewController() // 快讯 let newsFlashController = NewsFlashController() // Appso let appSoController = AppSoViewController() // 玩物志 let playzhiController = PlayingZhiController() // MindStore let mindStoreController = MindStoreViewController() var viewArray = [UIView]() /// fps标签 private lazy var fpsLabel: YYFPSLabel = { var fpsLabel: YYFPSLabel = YYFPSLabel(frame: CGRect(x: UIConstant.UI_MARGIN_20, y: self.view.height-40, width: 0, height: 0)) fpsLabel.sizeToFit() return fpsLabel }() private lazy var headerView: MainHeaderView = { var headerView: MainHeaderView = MainHeaderView(frame: CGRect(x: 0, y: 0, width: 5*UIConstant.SCREEN_WIDTH, height: 20)) return headerView }() private lazy var collectionView: UICollectionView = { let collectionLayout = UICollectionViewFlowLayout() collectionLayout.scrollDirection = .Horizontal collectionLayout.minimumLineSpacing = 0 collectionLayout.itemSize = CGSize(width: self.view.width, height: self.view.height-UIConstant.UI_MARGIN_20) var collectionView = UICollectionView(frame: CGRect(x: 0, y: UIConstant.UI_MARGIN_20, width: self.view.width, height: self.view.height-UIConstant.UI_MARGIN_20), collectionViewLayout: collectionLayout) collectionView.registerClass(MainCollectionViewCell.self) collectionView.pagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.delegate = self collectionView.dataSource = self return collectionView; }() private lazy var hamburgButton : UIButton = { let hamburgButton = UIButton() hamburgButton.setImage(UIImage(imageLiteral:"ic_hamburg"), forState: .Normal) return hamburgButton }() private lazy var circleButton: UIButton = { let circleButton = UIButton() circleButton.setImage(UIImage(imageLiteral: "ic_circle"), forState: .Normal) return circleButton }() } extension MainViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewArray.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(indexPath) as MainCollectionViewCell cell.childVCView = viewArray[indexPath.row] return cell } } extension MainViewController: UIScrollViewDelegate { func scrollViewDidScroll(scrollView: UIScrollView) { let scale = self.view.width/(self.view.width*0.5-20) headerView.x = -scrollView.contentOffset.x/scale } }
mit
c32bf59036789fd86126bcda4eb44784
33.093333
208
0.647761
4.89751
false
false
false
false
prey/prey-ios-client
Prey/Classes/HomeVC.swift
1
12318
// // HomeVC.swift // Prey // // Created by Javier Cala Uribe on 27/11/14. // Copyright (c) 2014 Prey, Inc. All rights reserved. // import UIKit class HomeVC: UIViewController, UITextFieldDelegate, UIGestureRecognizerDelegate { // MARK: Properties @IBOutlet var titleLbl : UILabel! @IBOutlet var subtitleLbl : UILabel! @IBOutlet var shieldImg : UIImageView! @IBOutlet var camouflageImg : UIImageView! @IBOutlet var passwordInput : UITextField! @IBOutlet var loginBtn : UIButton! @IBOutlet var forgotBtn : UIButton! @IBOutlet var accountImg : UIImageView! @IBOutlet var accountSbtLbl : UILabel! @IBOutlet var accountTlLbl : UILabel! @IBOutlet var accountBtn : UIButton! @IBOutlet var settingsImg : UIImageView! @IBOutlet var settingsSbtLbl : UILabel! @IBOutlet var settingsTlLbl : UILabel! @IBOutlet var settingsBtn : UIButton! var hidePasswordInput = false // MARK: Init override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // View title for GAnalytics //self.screenName = "Login" // Dismiss Keyboard on tap outside let recognizer = UITapGestureRecognizer(target: self, action:#selector(self.dismissKeyboard(_:))) view.addGestureRecognizer(recognizer) // Config init hidePasswordInputOption(hidePasswordInput) // Config texts configureTexts() // Hide camouflage image configCamouflageMode(PreyConfig.sharedInstance.isCamouflageMode) } func configureTexts() { loginBtn.setTitle("Log In".localized, for:.normal) forgotBtn.setTitle("Forgot your password?".localized, for:.normal) passwordInput.placeholder = "Type in your password".localized subtitleLbl.text = "current device status".localized accountTlLbl.text = "PREY ACCOUNT".localized accountSbtLbl.text = "REMOTE CONTROL FROM YOUR".localized settingsTlLbl.text = "PREY SETTINGS".localized settingsSbtLbl.text = "CONFIGURE".localized } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool){ super.viewWillAppear(animated) // Hide navigationBar when appear this ViewController self.navigationController?.isNavigationBarHidden = true // Listen for changes to keyboard visibility so that we can adjust the text view accordingly. let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(HomeVC.handleKeyboardWillShowNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(HomeVC.handleKeyboardWillHideNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) // Hide navigationBar when appear this ViewController self.navigationController?.isNavigationBarHidden = false let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) notificationCenter.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } // Hide password input func hidePasswordInputOption(_ value:Bool) { // Input subview self.changeHiddenFor(view:self.passwordInput, value:value) self.changeHiddenFor(view:self.loginBtn, value:value) self.changeHiddenFor(view:self.forgotBtn, value:value) // Menu subview self.changeHiddenFor(view:self.accountImg, value:!value) self.changeHiddenFor(view:self.accountSbtLbl, value:!value) self.changeHiddenFor(view:self.accountTlLbl, value:!value) self.changeHiddenFor(view:self.accountBtn, value:!value) self.changeHiddenFor(view:self.settingsImg, value:!value) self.changeHiddenFor(view:self.settingsSbtLbl, value:!value) self.changeHiddenFor(view:self.settingsTlLbl, value:!value) self.changeHiddenFor(view:self.settingsBtn, value:!value) } // Set hidden object func changeHiddenFor(view:UIView!, value:Bool) { if view != nil { view.isHidden = value } } // Set camouflageMode func configCamouflageMode(_ isCamouflage:Bool) { subtitleLbl.isHidden = isCamouflage titleLbl.isHidden = isCamouflage shieldImg.isHidden = isCamouflage forgotBtn.isHidden = isCamouflage camouflageImg.isHidden = !isCamouflage // Change icon image if #available(iOS 10.3, *) { if UIApplication.shared.supportsAlternateIcons && PreyConfig.sharedInstance.needChangeIcon { let iconString = (isCamouflage) ? alternativeIcon : nil UIApplication.shared.setAlternateIconName(iconString, completionHandler:{(error) in if (error != nil) { PreyConfig.sharedInstance.needChangeIcon = true } else { PreyConfig.sharedInstance.needChangeIcon = false } PreyConfig.sharedInstance.saveValues() }) } } } // MARK: Keyboard Event Notifications @objc func handleKeyboardWillShowNotification(_ notification: Notification) { keyboardWillChangeFrameWithNotification(notification, showsKeyboard: true) } @objc func handleKeyboardWillHideNotification(_ notification: Notification) { keyboardWillChangeFrameWithNotification(notification, showsKeyboard: false) } @objc func dismissKeyboard(_ tapGesture: UITapGestureRecognizer) { // Dismiss keyboard if is inside from UIView if (self.view.frame.contains(tapGesture.location(in: self.view))) { self.view.endEditing(true); } } func keyboardWillChangeFrameWithNotification(_ notification: Notification, showsKeyboard: Bool) { let userInfo = (notification as NSNotification).userInfo! let animationDuration: TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue // Convert the keyboard frame from screen to view coordinates. let keyboardScreenBeginFrame = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue let keyboardScreenEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let keyboardViewBeginFrame = view.convert(keyboardScreenBeginFrame, from: view.window) let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window) let originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y self.view.center.y += originDelta view.setNeedsUpdateConstraints() UIView.animate(withDuration: animationDuration, delay: 0, options: .beginFromCurrentState, animations: { self.view.layoutIfNeeded() }, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { let nextTage = textField.tag + 1; // Try to find next responder let nextResponder = textField.superview?.viewWithTag(nextTage) if (nextResponder == nil) { checkPassword(nil) } return false } // MARK: Functions // Send GAnalytics event func sendEventGAnalytics() { // if let tracker = GAI.sharedInstance().defaultTracker { // // let dimensionValue = PreyConfig.sharedInstance.isPro ? "Pro" : "Free" // tracker.set(GAIFields.customDimension(for: 1), value:dimensionValue) // // let params:NSObject = GAIDictionaryBuilder.createEvent(withCategory: "UserActivity", action:"Log In", label:"Log In", value:nil).build() // tracker.send(params as! [NSObject : AnyObject]) // } } // Go to Settings @IBAction func goToSettings(_ sender: UIButton) { if let resultController = self.storyboard!.instantiateViewController(withIdentifier: StoryboardIdVC.settings.rawValue) as? SettingsVC { self.navigationController?.pushViewController(resultController, animated: true) } } // Go to Control Panel @IBAction func goToControlPanel(_ sender: UIButton) { if let token = PreyConfig.sharedInstance.tokenPanel { let params = String(format:"token=%@", token) let controller : UIViewController if #available(iOS 10.0, *) { controller = WebKitVC(withURL:URL(string:URLSessionPanel)!, withParameters:params, withTitle:"Control Panel Web") } else { controller = WebVC(withURL:URL(string:URLSessionPanel)!, withParameters:params, withTitle:"Control Panel Web") } if #available(iOS 13, *) {controller.modalPresentationStyle = .fullScreen} self.present(controller, animated:true, completion:nil) } else { displayErrorAlert("Error, retry later.".localized, titleMessage:"We have a situation!".localized) } } // Run web forgot @IBAction func runWebForgot(_ sender: UIButton) { let controller : UIViewController if #available(iOS 10.0, *) { controller = WebKitVC(withURL:URL(string:URLForgotPanel)!, withParameters:nil, withTitle:"Forgot Password Web") } else { controller = WebVC(withURL:URL(string:URLForgotPanel)!, withParameters:nil, withTitle:"Forgot Password Web") } if #available(iOS 13, *) {controller.modalPresentationStyle = .fullScreen} self.present(controller, animated:true, completion:nil) } // Check password @IBAction func checkPassword(_ sender: UIButton?) { // Check password length guard let pwdInput = passwordInput.text else { displayErrorAlert("Password must be at least 6 characters".localized, titleMessage:"We have a situation!".localized) return } if pwdInput.count < 6 { displayErrorAlert("Password must be at least 6 characters".localized, titleMessage:"We have a situation!".localized) return } // Hide keyboard self.view.endEditing(true) // Show ActivityIndicator let actInd = UIActivityIndicatorView(initInView: self.view, withText:"Please wait".localized) self.view.addSubview(actInd) actInd.startAnimating() // Check userApiKey length guard let userApiKey = PreyConfig.sharedInstance.userApiKey else { displayErrorAlert("Wrong password. Try again.".localized, titleMessage:"We have a situation!".localized) return } // Get Token for Control Panel PreyUser.getTokenFromPanel(userApiKey, userPassword:pwdInput, onCompletion:{(isSuccess: Bool) in // Hide ActivityIndicator DispatchQueue.main.async { actInd.stopAnimating() // Change inputView if isSuccess { self.sendEventGAnalytics() self.hidePasswordInputOption(true) } } }) } }
gpl-3.0
f59eccd1f0660058cb4cf79617106b27
39.519737
173
0.625913
5.273116
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.ChatTests/Helpers/AlertSpec.swift
1
776
// // AskSpec.swift // Rocket.ChatTests // // Created by Luca Justin Zimmermann on 26/01/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import XCTest @testable import Rocket_Chat class AlertSpec: XCTestCase { func testTitleMessage() { let title = "test" let message = "me" let alert = Alert(title: title, message: message) XCTAssert(alert.title == title, "Title matches") XCTAssert(alert.message == message, "Message matches") } func testKey() { let key = "alert.connection.invalid_url" let alert = Alert(key: key) XCTAssert(alert.title == localized(key + ".title"), "Title matches") XCTAssert(alert.message == localized(key + ".message"), "Message matches") } }
mit
3f0d33bf9d30c1988687d379be364ba5
24.833333
82
0.627097
3.894472
false
true
false
false
mozilla-mobile/focus-ios
Blockzilla/Utilities/LocalContentBlocker.swift
5
2045
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit class ContentBlockerHelper { static let shared = ContentBlockerHelper() var handler: (([WKContentRuleList]) -> Void)? func reload() { guard let handler = handler else { return } getBlockLists(callback: handler) } func getBlockLists(callback: @escaping ([WKContentRuleList]) -> Void) { let enabledList = Utils.getEnabledLists() var returnList = [WKContentRuleList]() let dispatchGroup = DispatchGroup() let listStore = WKContentRuleListStore.default() for list in enabledList { dispatchGroup.enter() listStore?.lookUpContentRuleList(forIdentifier: list) { (ruleList, error) in if let ruleList = ruleList { returnList.append(ruleList) dispatchGroup.leave() } else { ContentBlockerHelper.compileItem(item: list) { ruleList in returnList.append(ruleList) dispatchGroup.leave() } } } } dispatchGroup.notify(queue: .global()) { callback(returnList) } } private static func compileItem(item: String, callback: @escaping (WKContentRuleList) -> Void) { let path = Bundle.main.path(forResource: item, ofType: "json")! guard let jsonFileContent = try? String(contentsOfFile: path, encoding: String.Encoding.utf8) else { fatalError("Rule list for \(item) doesn't exist!") } WKContentRuleListStore.default().compileContentRuleList(forIdentifier: item, encodedContentRuleList: jsonFileContent) { (ruleList, error) in guard let ruleList = ruleList else { fatalError("problem compiling \(item)") } callback(ruleList) } } }
mpl-2.0
94766b5aa02132787478b54918c96d19
37.584906
161
0.615648
4.869048
false
false
false
false
PrashantMangukiya/SwiftUIDemo
Demo12-UIScrollView/Demo12-UIScrollView/ViewController.swift
1
2532
// // ViewController.swift // Demo12-UIScrollView // // Created by Prashant on 28/09/15. // Copyright © 2015 PrashantKumar Mangukiya. All rights reserved. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { // outlet - scroll view @IBOutlet var myScrollView: UIScrollView! // image view var myImageView: UIImageView! // MARK: - view functions override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // remove top padding from scroll view // view controller will put top padding within scroll view automatically. // by setting this property to false will remove that top padding. self.automaticallyAdjustsScrollViewInsets = false // set scroll view delegate (used for zoom) self.myScrollView.delegate = self // create image self.myImageView = UIImageView(image: UIImage(named: "bg")) } // must written within view did appear, so it will have proper width and height available. override func viewDidAppear(_ animated: Bool) { // set scroll view content size same as image size self.myScrollView.contentSize = self.myImageView.bounds.size // auto resize sub view self.myScrollView.autoresizesSubviews = true // set content at (top,let) within scroll view self.myScrollView.contentOffset = CGPoint.zero // set scroll view bg color self.myScrollView.backgroundColor = UIColor.darkGray // add imageview within scroll view self.myScrollView.addSubview(self.myImageView) } // reset scale when layout changed override func viewWillLayoutSubviews() { // set scroll view min, max and current zoom scale let currentZoomScale = self.myScrollView.bounds.height/self.myImageView.bounds.size.height self.myScrollView.minimumZoomScale = currentZoomScale / 2 self.myScrollView.maximumZoomScale = 1.0 self.myScrollView.zoomScale = currentZoomScale } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - scroll view delegate func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.myImageView } }
mit
4249d1c1959998fb412fa42e64a4e61e
29.493976
98
0.647175
5.362288
false
false
false
false
apple/swift
test/Generics/rdar94746399.swift
5
795
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s // CHECK-LABEL: .P1@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.[P1]T.[P2]T, Self.[P1]T : P2> protocol P1 { associatedtype T: P2 where T.T == Self } // CHECK-LABEL: .P2@ // CHECK-NEXT: Requirement signature: <Self where Self == Self.[P2]T.[P1]T, Self.[P2]T : P1> protocol P2 { associatedtype T: P1 where T.T == Self } class SomeClass {} // CHECK-LABEL: .P3@ // CHECK-NEXT: Requirement signature: <Self where Self : P2, Self.[P2]T : SomeClass> protocol P3: P2 where T: SomeClass {} protocol P4 { associatedtype T } // CHECK-LABEL: .foo@ // CHECK-NEXT: Generic signature: <T where T : P4, T.[P4]T : P1, T.[P4]T.[P1]T : P3> func foo<T: P4>(_: T) where T.T: P1, T.T.T: P3 {}
apache-2.0
d385139d0e7c710a8d7d3cfef481eb47
28.444444
92
0.645283
2.606557
false
false
false
false
philipbannon/iOS
FriendBookPlus/FriendBookPlus/FriendDetailViewController.swift
1
1066
// // FriendDetailViewController.swift // FriendBookPlus // // Created by Philip Bannon on 06/01/2016. // Copyright © 2016 Philip Bannon. All rights reserved. // import UIKit class FriendDetailViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var birthdayLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var avatarImageView: UIImageView! var friend = Friend() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.nameLabel.text = "Name: \(self.friend.name)" self.phoneLabel.text = "Phone: : \(self.friend.phoneNumber)" self.birthdayLabel.text = "DOB: \(self.friend.birthday)" self.avatarImageView.image = self.friend.avatar self.avatarImageView.contentMode = UIViewContentMode.ScaleAspectFit } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
126dc3e189e10ca5e66ade6e1d239525
28.583333
75
0.687324
4.650655
false
false
false
false
magicmon/Mentions
Mentions/Classes/MentionParser.swift
1
4086
// // MentionParser.swift // Mentions // // Created by magicmon on 2017. 3. 28.. // // public enum ParserPattern: String { case mention = "\\[([\\w\\d\\sㄱ-ㅎㅏ-ㅣ가-힣.]{1,})\\]" case html = "<a( ){1,}class=(\"at-username\"|'at-username')>(\\s)*(\\d{0,})(\\s)*<( )*\\/a>" case custom = "@((?!@).)*" } extension UIView { func parse(_ text: String?, pattern: ParserPattern, template: String, prefixMention: String = "@") -> (String?, [(String, NSRange)]?) { guard var matchText = text else { return (nil, nil) } var matchUsers: [(String, NSRange)] = [] while true { guard let match = matchText.getFirstElements(pattern) else { break } let firstFindedText = matchText.substringFromNSRange(match.range) let data = firstFindedText.replacingOccurrences(of: pattern.rawValue, with: template, options: .regularExpression, range: firstFindedText.range(of: firstFindedText)) if data.count > 0 { matchText = matchText.replacing(pattern: pattern, range: match.range, withTemplate: "\(prefixMention)\(template)") let matchRange = NSRange(location: match.range.location, length: data.utf16.count + 1) matchText = matchText.replacing("\(prefixMention)\(data)", range: matchRange) matchUsers.append((data, matchRange)) } } // print("\(matchText)") // TODO: [, ], /의 개수를 찾아 제거. // for user in matchUsers { // let string = matchText.substring(to: matchText.index(matchText.startIndex, offsetBy: user.1.location)) // print("<\(string)>") // // if let idx = string.characters.index(of: "[") { // let pos = string.characters.distance(from: string.startIndex, to: idx) // print("Found [ at position \(pos)") // } // } // replacing matchText = matchText.replacingOccurrences(of: "\\[", with: "[") matchText = matchText.replacingOccurrences(of: "\\]", with: "]") matchText = matchText.replacingOccurrences(of: "\\\\", with: "\\") if matchUsers.count > 0 { return (matchText, matchUsers) } return (matchText, nil) } } // MARK: - Element extension String { func getElements(_ pattern: ParserPattern = .mention) -> [NSTextCheckingResult] { guard let elementRegex = try? NSRegularExpression(pattern: pattern.rawValue, options: [.caseInsensitive]) else { return [] } return elementRegex.matches(in: self, options: [], range: NSRange(0..<self.utf16.count)) } func getFirstElements(_ pattern: ParserPattern = .mention) -> NSTextCheckingResult? { guard let elementRegex = try? NSRegularExpression(pattern: pattern.rawValue, options: [.caseInsensitive]) else { return nil } return elementRegex.firstMatch(in: self, options: [], range: NSRange(0..<self.utf16.count)) } func replacing(pattern: ParserPattern = .mention, range: NSRange? = nil, withTemplate: String) -> String { guard let regex = try? NSRegularExpression(pattern: pattern.rawValue, options: [.caseInsensitive]) else { return self } if let range = range { return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: withTemplate) } else { return regex.stringByReplacingMatches(in: self, options: [], range: NSRange(0..<self.utf16.count), withTemplate: withTemplate) } } func replacing(_ withString: String, range: NSRange) -> String { if let textRange = self.rangeFromNSRange(range) { return self.replacingCharacters(in: textRange, with: withString) } return self } }
mit
e3e8e86db5f718be5bab946b5c5bdba7
36.574074
177
0.564317
4.483978
false
false
false
false
honghaoz/2048-Solver-AI
2048 AI/AI/TDLearning/Transition.swift
1
1145
// Copyright © 2019 ChouTi. All rights reserved. // // Transition.swift // 2048 Solver // // Created by yansong li on 2015-03-31. // Copyright (c) 2015 Honghao Zhang. All rights reserved. // // import Foundation class Transition { private var state: State2048 private var action: Action2048 private var afterState: State2048 private var reward: Double private var isTerminal: Bool init(state: State2048, action: Action2048, afterState: State2048, reward: Double, isTerminal: Bool) { self.state = state self.action = action self.afterState = afterState self.reward = reward self.isTerminal = isTerminal } convenience init(state: State2048, action: Action2048, afterState: State2048, reward: Double) { self.init(state: state, action: action, afterState: afterState, reward: reward, isTerminal: false) } func getState() -> State2048 { return state } func getAction() -> Action2048 { return action } func getAfterState() -> State2048 { return afterState } func getReward() -> Double { return reward } func getTerminal() -> Bool { return isTerminal } }
gpl-2.0
58ab60fbd8b1f6f9dc826e4f4d75a038
21
103
0.689685
3.917808
false
false
false
false
SwiftGen/templates
Pods/Stencil/Sources/Parser.swift
6
2372
public func until(_ tags: [String]) -> ((TokenParser, Token) -> Bool) { return { parser, token in if let name = token.components().first { for tag in tags { if name == tag { return true } } } return false } } /// A class for parsing an array of tokens and converts them into a collection of Node's public class TokenParser { public typealias TagParser = (TokenParser, Token) throws -> NodeType fileprivate var tokens: [Token] fileprivate let environment: Environment public init(tokens: [Token], environment: Environment) { self.tokens = tokens self.environment = environment } /// Parse the given tokens into nodes public func parse() throws -> [NodeType] { return try parse(nil) } public func parse(_ parse_until:((_ parser:TokenParser, _ token:Token) -> (Bool))?) throws -> [NodeType] { var nodes = [NodeType]() while tokens.count > 0 { let token = nextToken()! switch token { case .text(let text): nodes.append(TextNode(text: text)) case .variable: nodes.append(VariableNode(variable: try compileFilter(token.contents))) case .block: if let parse_until = parse_until , parse_until(self, token) { prependToken(token) return nodes } if let tag = token.components().first { let parser = try findTag(name: tag) nodes.append(try parser(self, token)) } case .comment: continue } } return nodes } public func nextToken() -> Token? { if tokens.count > 0 { return tokens.remove(at: 0) } return nil } public func prependToken(_ token:Token) { tokens.insert(token, at: 0) } func findTag(name: String) throws -> Extension.TagParser { for ext in environment.extensions { if let filter = ext.tags[name] { return filter } } throw TemplateSyntaxError("Unknown template tag '\(name)'") } func findFilter(_ name: String) throws -> FilterType { for ext in environment.extensions { if let filter = ext.filters[name] { return filter } } throw TemplateSyntaxError("Unknown filter '\(name)'") } public func compileFilter(_ token: String) throws -> Resolvable { return try FilterExpression(token: token, parser: self) } }
mit
66013c8a03520065619d03bbb3cdf321
23.204082
108
0.612985
4.266187
false
false
false
false
chashmeetsingh/Youtube-iOS
YouTube Demo/FeedCell.swift
1
2403
// // FeedCell.swift // YouTube Demo // // Created by Chashmeet Singh on 11/01/17. // Copyright © 2017 Chashmeet Singh. All rights reserved. // import UIKit class FeedCell: BaseCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.delegate = self cv.dataSource = self cv.backgroundColor = .white return cv }() let cellId = "cellId" var videos: [Video]? func fetchVideos() { ApiService.sharedInstance.fetchVideos(completion: { (videos: [Video]) in self.videos = videos self.collectionView.reloadData() }) } override func setupViews() { super.setupViews() fetchVideos() addSubview(collectionView) addConstraintsWithFormat(format: "H:|[v0]|", view: collectionView) addConstraintsWithFormat(format: "V:|[v0]|", view: collectionView) collectionView.register(VideoCell.self, forCellWithReuseIdentifier: cellId) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return videos?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! VideoCell cell.video = videos?[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = (frame.width - 16 - 16) * 9 / 16 return CGSize(width: frame.width, height: height + 16 + 88) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let videoLauncher = VideoLauncher() videoLauncher.showVideoPlayer() } }
mit
2d8db9f4efa6a5e505aa634cab04b8a2
32.830986
170
0.668609
5.534562
false
false
false
false
LYM-mg/MGDYZB
MGDYZB/MGDYZB/Class/Home/View/CollectionPrettyCell.swift
1
1665
// // CollectionPrettyCell.swift // MGDYZB // // Created by ming on 16/10/26. // Copyright © 2016年 ming. All rights reserved. // import UIKit class CollectionPrettyCell: UICollectionViewCell { // MARK:- 控件属性 @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameBtn: UIButton! @IBOutlet weak var cityBtn: UIButton! // MARK:- 定义模型 var anchor : AnchorModel? { didSet { // 0.校验模型是否有值 guard let anchor = anchor else { return } // 1.取出在线人数显示的文字 var onlineStr : String = "" if Int(anchor.online) >= 10000 { onlineStr = "\(Int(anchor.online)/10000)万人在线" } else { onlineStr = "\(anchor.online)人在线" } onlineBtn.setTitle(onlineStr, for: UIControlState()) onlineBtn.sizeToFit() // 2.昵称的显示 nickNameBtn.setTitle(anchor.nickname, for: UIControlState()) // 3.设置位置(所在的城市) cityBtn.setTitle(anchor.anchor_city, for: UIControlState()) // 4.设置封面图片 guard let iconURL = URL(string: anchor.vertical_src) else { return } iconImageView.kf.setImage(with: iconURL, placeholder: #imageLiteral(resourceName: "placehoderImage")) } } override func awakeFromNib() { super.awakeFromNib() iconImageView.layer.cornerRadius = 6 iconImageView.clipsToBounds = true } }
mit
0cae7c4a02dd6198b845b97bbb97ee70
28.320755
114
0.573359
4.638806
false
false
false
false
dreamsxin/swift
stdlib/public/SDK/OpenCL/OpenCL.swift
10
946
//===----------------------------------------------------------------------===// // // 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 OpenCL // Clang module @available(OSX, introduced: 10.7) public func clSetKernelArgsListAPPLE( _ kernel: cl_kernel, _ uint: cl_uint, _ args: CVarArg... ) -> cl_int { // The variable arguments are num_args arguments that are the following: // cl_uint arg_indx, // size_t arg_size, // const void *arg_value, return withVaList(args) { clSetKernelArgsVaListAPPLE(kernel, uint, $0) } }
apache-2.0
bab1e3bda206902a00a6c13bee8ae774
38.416667
80
0.582452
4.261261
false
false
false
false
mflint/ios-tldr-viewer
tldr-viewer/SpotlightSearch.swift
1
1333
// // SpotlightSearch.swift // tldr-viewer // // Created by Matthew Flint on 30/01/2016. // Copyright © 2016 Green Light. All rights reserved. // import Foundation import CoreSpotlight import CoreServices import UIKit struct SpotlightSearch { func addToIndex(command: Command) { guard let firstVariant = command.variants.first else { return } let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String) // Add metadata that supplies details about the item. attributeSet.title = command.name attributeSet.contentDescription = firstVariant.summary() if let image = UIImage(named: "AppIcon") { attributeSet.thumbnailData = image.pngData() } // Create an item with a unique identifier, a domain identifier, and the attribute set you created earlier. let item = CSSearchableItem(uniqueIdentifier: command.name, domainIdentifier: "uk.co.greenlightapps.tldr-viewer", attributeSet: attributeSet) item.expirationDate = Date.distantFuture // Add the item to the on-device index. CSSearchableIndex.default().indexSearchableItems([item]) { error in if error != nil { print(error!.localizedDescription) } } } }
mit
739f60c282cc9d35835904ac70909b19
34.052632
149
0.665916
4.757143
false
false
false
false
hyperoslo/Orchestra
OrchestraTests/Specs/KapellmeisterSpec.swift
1
1491
import Quick import Nimble @testable import Orchestra class KapellmeisterSpec: QuickSpec { override func spec() { describe("Kapellmeister") { var engine: Kapellmeister! let defaultTheme = ThemeList.hyper let amazingTheme = Theme(name: "Amazing", audioFormat: "aiff") beforeEach { engine = Kapellmeister() } describe("#defaultTheme") { it("has a valid default theme") { expect(Kapellmeister.defaultTheme).to(equal(defaultTheme)) } } describe("#player") { it("uses a default theme") { expect(engine.player.theme).to(equal(Kapellmeister.defaultTheme)) } } describe("#autoPlay") { it("is enabled by default") { expect(engine.autoPlay).to(beFalse()) } } describe("#theme") { it("has a valid default theme") { expect(engine.theme).to(equal(Kapellmeister.defaultTheme)) } it("sets a new theme to the player") { engine.theme = amazingTheme expect(engine.theme).to(equal(amazingTheme)) expect(engine.player.theme).to(equal(engine.theme)) } } describe("#reset") { it("restores defaults") { engine.theme = amazingTheme engine.autoPlay = true engine.reset() expect(engine.theme).to(equal(Kapellmeister.defaultTheme)) expect(engine.autoPlay).to(beFalse()) } } } } }
mit
74bdc52e78ed279b942b183a5bc44c8e
23.442623
75
0.575453
4.096154
false
false
false
false
RedMadRobot/DAO
DAO/Classes/Core/Entity.swift
1
1273
// // Entity.swift // DAO // // Created by Igor Bulyga on 05.02.16. // Copyright © 2016 RedMadRobot LLC. All rights reserved. // import Foundation /// Parent class for all entities. open class Entity: Hashable { /// Hash value for compare entities. open func hash(into hasher: inout Hasher) { hasher.combine(entityId) } /// Unique entity identifer. open var entityId: String required public init() { entityId = UUID().uuidString } /// Creates an instance with identifier. /// /// - Parameter entityId: unique entity identifier. public init(entityId: String) { self.entityId = entityId } /// Redefine this function in child class for proper equality. /// /// - Parameter other: entity compare with. /// - Returns: result of comparison. open func equals<T>(_ other: T) -> Bool where T: Entity { return self.entityId == other.entityId } } /// Custom operator `==` for `Entity` and subclasses. /// /// - Parameters: /// - lhs: left entity to compare. /// - rhs: right entity to compare. /// - Returns: result of comparison. public func ==<T>(lhs: T, rhs: T) -> Bool where T: Entity { return lhs.equals(rhs) }
mit
24e8daf2b67d24975b4880f74d365d80
21.315789
66
0.603774
4.156863
false
false
false
false
sprejjs/Virtual-Tourist-App
Virtual_Tourist/Virtual Tourist/View Controllers/AlbumViewController.swift
1
5972
// // Created by Vlad Spreys on 6/04/15. // Copyright (c) 2015 Spreys.com. All rights reserved. // import Foundation import UIKit import MapKit import CoreData class AlbumViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet var mapView: MKMapView! @IBOutlet var collectionView: UICollectionView! @IBOutlet weak var loadingOverlay: UIView! var btnNewCollection: UIButton? var lblNoImages: UILabel? var album: Album! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) mapView.addAnnotation(album) mapView.showAnnotations([album], animated: true) navigationController?.isNavigationBarHidden = false retrieveNewCollection() } fileprivate func retrieveNewCollection() { loadingOverlay.isHidden = false album.getPhotos({ (photos:[Photo]) in //Hide loading overlay with animation UIView.transition(with: self.loadingOverlay, duration: TimeInterval(0.4), options: UIViewAnimationOptions.transitionCrossDissolve, animations: {}, completion: {(finished: Bool) -> () in }) self.loadingOverlay.isHidden = true //Reload collection view self.collectionView.reloadData() }); } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if album.photos == nil { return 0 } else { return album.photos!.count } } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let newCollection = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "footer", for: indexPath) self.btnNewCollection = newCollection.subviews[0] as? UIButton self.lblNoImages = newCollection.subviews[1] as? UILabel //Hide display elements if album.photos != nil && album.photos!.count > 0 { lblNoImages?.isHidden = true btnNewCollection?.isHidden = false } else { lblNoImages?.isHidden = false btnNewCollection?.isHidden = true } return newCollection } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //Deque cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! PhotoCell //Check the cache let imageId = self.album.photos![indexPath.item].objectID.uriRepresentation().lastPathComponent if let imageFromCache = AppDelegate.Cache.imageCache.imageWithIdentifier(imageId) { cell.imageView.image = imageFromCache cell.loadingOverlay.stopAnimating() cell.loadingOverlay.isHidden = true } else { //Asyncrhoniously load image from URL: let imageUrl = URL(string: album.photos![indexPath.item].url) DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.background).async(execute: { let image = UIImage(data: try! Data(contentsOf: imageUrl!)) //update cache let id = self.album.photos![indexPath.item].objectID.uriRepresentation().lastPathComponent AppDelegate.Cache.imageCache.storeImage(image, withIdentifier: id) DispatchQueue.main.async(execute: { //Check if this is still the right cell and not a re-used one if let updateCell = collectionView.cellForItem(at: indexPath) as? PhotoCell { //Display loaded image updateCell.imageView.image = image //Hide loading overla with animation UIView.transition(with: cell.loadingOverlay, duration: TimeInterval(0.4), options: UIViewAnimationOptions.transitionCrossDissolve, animations: {}, completion: {(finished: Bool) -> () in }) updateCell.loadingOverlay.isHidden = true //Enable "New Collection" button if all of the images have been loaded if self.btnNewCollection != nil { self.btnNewCollection!.isEnabled = self.allImagesLoaded } } }) }) } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { //Delete the image from cache let id = self.album.photos![indexPath.item].objectID.uriRepresentation().lastPathComponent AppDelegate.Cache.imageCache.storeImage(nil, withIdentifier: id) //Remove core data object album.photos![indexPath.item].album = nil collectionView.reloadData() try! sharedContext.save() } fileprivate var allImagesLoaded: Bool { var loaded = true for photo in album.photos! { let imageId = photo.objectID.uriRepresentation().lastPathComponent if AppDelegate.Cache.imageCache.imageWithIdentifier(imageId) == nil { loaded = false } } return loaded } @IBAction func newCollection() { album.removeAllPhotos() retrieveNewCollection() } fileprivate var sharedContext: NSManagedObjectContext { let appDeleate = UIApplication.shared.delegate as! AppDelegate return appDeleate.managedObjectContext! } }
apache-2.0
0c9b84969119a5d12e46302f8317e114
38.549669
212
0.610348
5.901186
false
false
false
false
Hypercoin/Hypercoin-mac
Hypercoin/ViewController/ListMarketViewController.swift
1
5935
// // ListMarketViewController.swift // Hypercoin // // Created by Benjamin Prieur on 18/10/2017. // Copyright © 2017 Hypercoin. All rights reserved. // import Cocoa import Marshal class ListMarketViewController: NSViewController { enum CellType { case title case value case percent var columnIndex: Int { switch self { case .title: return 0 case .value: return 1 case .percent: return 2 } } var cellIdentifier: String { switch self { case .title: return "CryptoTitleCell" case .value: return "CryptoValueCell" case .percent: return "CryptoPercentCell" } } } // ********************************************************************* // MARK: - Properties @IBOutlet fileprivate weak var tableView: NSTableView! @IBOutlet fileprivate weak var loader: NSProgressIndicator! let service = CoinMarketCapService() var market: [MarketCap] = [] var coinNotifaction: [String: NotifiactionStatus] = [:] var refreshTimer: Timer? // ********************************************************************* // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.backgroundColor = .clear refreshTimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(loadData), userInfo: nil, repeats: true) } // ********************************************************************* // MARK: - Storyboard instantiation static func freshController() -> ListMarketViewController { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) let identifier = NSStoryboard.SceneIdentifier(rawValue: "ListCapViewController") guard let viewcontroller = storyboard.instantiateController(withIdentifier: identifier) as? ListMarketViewController else { fatalError("Why cant i find ListCapViewController? - Check Main.storyboard") } return viewcontroller } // ********************************************************************* // MARK: - IBActions @IBAction func killApp(_ sender: AnyObject) { NSApplication.shared.terminate(self) } } // ********************************************************************* // MARK: - NSTableViewDataSource extension ListMarketViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return market.count } } extension ListMarketViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { var cellIdentifier: String = "" guard let tableColumn = tableColumn else { print("TableColumn must be available") return nil } switch tableColumn { case tableView.tableColumns[CellType.title.columnIndex]: cellIdentifier = CellType.title.cellIdentifier let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView cell?.textField?.stringValue = market[row].name return cell case tableView.tableColumns[CellType.value.columnIndex]: cellIdentifier = CellType.value.cellIdentifier let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView cell?.textField?.stringValue = "\(market[row].price[.usd]!)" return cell case tableView.tableColumns[CellType.percent.columnIndex]: cellIdentifier = CellType.percent.cellIdentifier let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? CryptoPercentCell if let percentChange = market[row].percentChange[.daily] { cell?.bgPercent.layer?.backgroundColor = percentChange < 0 ? NSColor.red.cgColor : NSColor.green.cgColor cell?.bgPercent.updateLayer() cell?.textField?.stringValue = "\(percentChange)%" } return cell default: break } return nil } func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 40 } } private extension ListMarketViewController { @objc func loadData() { loader.startAnimation(self) _ = service.getMarketCap().subscribe { [weak self] event in // _ = service.getStubMarketCap().subscribe { event in guard let `self` = self else { return } self.loader.stopAnimation(self) if let items = event.element { print("Reload data") self.market = items self.tableView.reloadData() self.notifyWhenCurrencyVariationAppear(currency: "Bitcoin") self.notifyWhenCurrencyVariationAppear(currency: "Litecoin") } else if !event.isCompleted { print("somethings wrong happen with the service") } } } func notifyWhenCurrencyVariationAppear(currency: String) { guard let currencyData = market.filter({ $0.name == currency }).first else { print("No \(currency) item in your list... How \(currency) could disappear... Another joke from Flipper the dolphin") return } guard let dailyPercentChange = currencyData.percentChange[.daily] else { return } let currentStatus = coinNotifaction[currency] ?? .none if abs(dailyPercentChange) > 5, currentStatus == .none { let notification = NSUserNotification() notification.title = "\(currency) News" notification.informativeText = "\(currency) has \(dailyPercentChange)% change" notification.soundName = NSUserNotificationDefaultSoundName NSUserNotificationCenter.default.deliver(notification) coinNotifaction[currency] = dailyPercentChange > 0 ? .up : .down } else if abs(dailyPercentChange) < 5, currentStatus != .none { let notification = NSUserNotification() notification.title = "\(currency) News" notification.informativeText = "\(currency) has \(dailyPercentChange)% change" notification.soundName = NSUserNotificationDefaultSoundName NSUserNotificationCenter.default.deliver(notification) coinNotifaction[currency] = .none } } }
mit
a83686ee6fa4820e1518994aa75135f9
29.746114
139
0.692956
4.331387
false
false
false
false
Burning-Man-Earth/iBurn-iOS
iBurn/DataObject.swift
1
1039
// // DataObject.swift // iBurn // // Created by Chris Ballinger on 7/30/18. // Copyright © 2018 Burning Man Earth. All rights reserved. // import Foundation @objc(DataObjectWithMetadata) public class DataObject: NSObject { @objc let object: BRCDataObject @objc let metadata: BRCObjectMetadata @objc public init(object: BRCDataObject, metadata: BRCObjectMetadata) { self.object = object self.metadata = metadata } } @objc public protocol DataObjectProvider: NSObjectProtocol { func dataObjectAtIndexPath(_ indexPath: IndexPath) -> DataObject? } extension YapViewHandler: DataObjectProvider { public func dataObjectAtIndexPath(_ indexPath: IndexPath) -> DataObject? { var dataObject: DataObject? = nil let _: BRCDataObject? = object(at: indexPath) { (object, transaction) in let metadata = object.metadata(with: transaction) dataObject = DataObject(object: object, metadata: metadata) } return dataObject } }
mpl-2.0
d8b7561ede0035624d22e1c0087ef6d8
28.657143
80
0.679191
4.552632
false
false
false
false
jacky-tay/iOSSwiftJsonViewer
JSONViewer/JSONViewerViewController.swift
1
11672
// // JSONViewerViewController.swift // JSONViewer // // Created by Jacky Tay on 8/04/16. // // The MIT License (MIT) // // Copyright (c) 2016 Jacky Tay // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit let JSONViewerViewControllerIdentifier = "JSONViewerViewController" public class JSONViewerViewController: UIViewController { private var searchBar: UISearchBar? private var searchBarButton: UIBarButtonItem? @IBOutlet weak var tableView: UITableView! var jsonArray: JSONArray? var jsonObject: JSONObject? var searchText: String? private var keyWidth:CGFloat = 120 public class func getViewController() -> JSONViewerViewController? { let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: JSONViewerViewController.self)) let viewController = storyboard.instantiateViewController(withIdentifier: JSONViewerViewControllerIdentifier) as? JSONViewerViewController return viewController } public class func getViewController(jsonString: String) -> JSONViewerViewController? { let viewController = getViewController() if let data = jsonString.data(using: .utf8) { let json = try? JSONSerialization.jsonObject(with: data, options: []) if let array = json as? Array<AnyObject> { viewController?.jsonArray = JSONArray(content: array, section: nil) } else if let dictionary = json as? Dictionary<String, AnyObject> { let object = JSONObject(content: dictionary, section: nil) viewController?.jsonObject = object } } return viewController } override public func viewDidLoad() { super.viewDidLoad() searchBarButton = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(showSearch)) searchBar = UISearchBar() searchBar?.placeholder = "Search" searchBar?.showsCancelButton = true searchBar?.delegate = self if let searchText = searchText, !searchText.isEmpty { searchBar?.text = searchText //searchBar(searchBar, textDidChange: searchText) } else { filterBySearch(searchText: nil) } tableView.estimatedRowHeight = 50 tableView.rowHeight = UITableViewAutomaticDimension } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidChanged(notification:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidDismiss), name: .UIKeyboardWillHide, object: nil) navigationItem.rightBarButtonItem = searchBarButton } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let seletedIndex = tableView.indexPathForSelectedRow { tableView.deselectRow(at: seletedIndex, animated: true) } } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } func filterBySearch(searchText: String?) { _ = jsonArray?.filterBySearch(query: searchText) _ = jsonObject?.filterBySearch(query: searchText) let font = UIFont.systemFont(ofSize: 17) let allUniqueKeys = Set(jsonObject?.getAllKeys(includeSubLevel: false) ?? jsonArray?.getAllKeys(includeSubLevel: false) ?? []) let allKeyWidth = allUniqueKeys.map { ($0).calculateTextSize(width: nil, height: nil, font: font).width } keyWidth = allKeyWidth.max() ?? 120.0 tableView.reloadData() } @objc private dynamic func keyboardDidChanged(notification: Notification) { guard let keyboardFrame = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return } let frameEnd = keyboardFrame.cgRectValue tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: frameEnd.height, right: 0) } @objc private dynamic func keyboardDidDismiss() { tableView.contentInset = UIEdgeInsets.zero } } extension JSONViewerViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { var section = 1 if let array = jsonArray, (array.display.first is JSONArray || array.display.first is JSONObject) { section = array.display.count } return section } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var count = jsonObject?.display.count ?? 0 if let array = jsonArray, array.display.count > section { // if item at section is a JSON object, then display it as seperated section if let object = array.display[section] as? JSONObject { count = object.display.count } else if let subArray = array.display[section] as? JSONArray { count = subArray.display.count } else { count = array.display[section] is NSNull ? 1 : array.display.count } } return count == 0 ? 1 : count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var key = Searchable(value: "" as AnyObject) var value: Searchable? = nil if let dictionary = jsonObject, dictionary.display.count > indexPath.row { key = dictionary.display[indexPath.row].searchableKey value = dictionary.display[indexPath.row].searchableValue } else if let array = jsonArray, array.display.count > indexPath.section { if let dictionary = array.display[indexPath.section] as? JSONObject, dictionary.display.count > indexPath.row { key = dictionary.display[indexPath.row].searchableKey value = dictionary.display[indexPath.row].searchableValue } else if let jsonValue = array.display[indexPath.row] as? Searchable { key = Searchable(value: String(format: "Item %i", jsonValue.index ?? 0) as AnyObject) value = jsonValue } else if let subArray = array.display[indexPath.section] as? JSONArray, subArray.display.count > indexPath.row { if let jsonValue = subArray.display[indexPath.row] as? Searchable { key = Searchable(value: String(format: "Item %i", jsonValue.index ?? 0) as AnyObject) value = jsonValue } } } if value != nil { let cell = tableView.dequeueReusableCell(withIdentifier: JSONItemTableViewCellIdentifier, for: indexPath) (cell as? JSONItemTableViewCell)?.updateContent(key: key, value: value, keyWidth: keyWidth) return cell } else { return tableView.dequeueReusableCell(withIdentifier: JSONItemNoResultTableViewCellIdentifier, for: indexPath) } } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title = navigationItem.title ?? "Section" if let array = jsonArray, array.display.count > section { if let object = array.display[section] as? JSONObject { title = String(format: "%@ %i", title, object.section ?? 0) } else if let subArray = array.display[section] as? JSONArray { title = String(format: "%@ %i", title, subArray.section ?? 0) } } else { return nil } return title } } extension JSONViewerViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let viewController = JSONViewerViewController.getViewController() { var key = "" var value: AnyObject? // JSON child if let dictionary = jsonObject, dictionary.display.count > indexPath.row { key = dictionary.display[indexPath.row].key value = dictionary.display[indexPath.row].value } else if let array = jsonArray, array.display.count > indexPath.section { if let object = array.display[indexPath.section] as? JSONObject, object.display.count > indexPath.row { key = object.display[indexPath.row].key value = object.display[indexPath.row].value } } if let array = value as? JSONArray { viewController.jsonArray = array } else if let dictionary = value as? JSONObject { viewController.jsonObject = dictionary } else { value = nil } if value != nil { viewController.title = key viewController.searchText = searchBar?.text navigationController?.pushViewController(viewController, animated: true) } // if value != nil } // if let viewController, cell } } extension JSONViewerViewController: UISearchBarDelegate { @objc fileprivate dynamic func showSearch() { navigationItem.titleView = searchBar navigationItem.rightBarButtonItem = nil navigationItem.setHidesBackButton(true, animated: true) searchBar?.becomeFirstResponder() } public func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { filterBySearch(searchText: nil) searchBar.text = nil searchBar.resignFirstResponder() navigationItem.rightBarButtonItem = searchBarButton navigationItem.titleView = nil navigationItem.setHidesBackButton(false, animated: true) } public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true } public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = false } public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { filterBySearch(searchText: searchText) } } extension JSONViewerViewController: JSONFilterViewControllerDelegate { func userFilterResult(keys: [String]) { } }
mit
4f960c064cdb09cc80602bd3b1042959
41.137184
148
0.655843
5.213042
false
false
false
false
xiangpengzhu/QuickStart
QuickStart/UIKit+Extension/UIImage+Extension.swift
1
2907
// // UIImage+Extension.swift // LibTest // // Created by zxp on 15/10/20. // Copyright © 2015年 zxp. All rights reserved. // import UIKit extension UIImage { //MARK: - 创建图片 /** 使用颜色实例化图片 - parameter color: 颜色值 - parameter rect: 图片大小 - returns: 图片 */ public convenience init?(color: UIColor, rect: CGRect) { UIGraphicsBeginImageContext(rect.size); let context = UIGraphicsGetCurrentContext(); context?.setFillColor(color.cgColor); context?.fill(rect); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); guard let data = UIImageJPEGRepresentation(image!, 1.0) else {self.init(); return} self.init(data: data) } /** 使用颜色实例化图片,大小为1像素 - parameter color: 颜色 - returns: 图片 */ public convenience init?(color: UIColor) { self.init(color: color, rect: CGRect(x: 0, y: 0, width: 1.0, height: 1.0)) } /** 可以模版渲染的图片。用于使用颜色改变图片颜色 - returns: 图片 */ public func renderingImage() -> UIImage { return self.withRenderingMode(.alwaysTemplate) } /// 在不改变图片宽高比例的情况下,适配图片大小 /// /// - Parameter size: 要适配的大小 /// - Returns: 新的图片 public func adjustToSize(size: CGSize) -> UIImage? { guard size.width > 0 && size.height > 0 else { return self } let limitSize = size var size = self.size guard size.width > 0 && size.height > 0 else { return self } var needChange = false if size.width / size.height > limitSize.width / limitSize.height { //以宽度为准 if size.width > limitSize.width { let r = size.width / limitSize.width size = CGSize(width: limitSize.width, height: size.height / r) needChange = true } } else { //以高度为准 if size.height > limitSize.height { let r = size.height / limitSize.height size = CGSize(width: size.width / r, height: limitSize.height) needChange = true } } if (needChange) { UIGraphicsBeginImageContext(size); let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height); self.draw(in: rect) let newimg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newimg; } else { return self; } } }
gpl-3.0
203605be7e6aef1e098d35686a385321
24.884615
90
0.527117
4.509213
false
false
false
false
bparish628/iFarm-Health
iOS/iFarm-Health/Pods/Charts/Source/Charts/Renderers/LineChartRenderer.swift
4
27600
// // LineChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class LineChartRenderer: LineRadarRenderer { @objc open weak var dataProvider: LineChartDataProvider? @objc public init(dataProvider: LineChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } open override func drawData(context: CGContext) { guard let lineData = dataProvider?.lineData else { return } for i in 0 ..< lineData.dataSetCount { guard let set = lineData.getDataSetByIndex(i) else { continue } if set.isVisible { if !(set is ILineChartDataSet) { fatalError("Datasets for LineChartRenderer must conform to ILineChartDataSet") } drawDataSet(context: context, dataSet: set as! ILineChartDataSet) } } } @objc open func drawDataSet(context: CGContext, dataSet: ILineChartDataSet) { if dataSet.entryCount < 1 { return } context.saveGState() context.setLineWidth(dataSet.lineWidth) if dataSet.lineDashLengths != nil { context.setLineDash(phase: dataSet.lineDashPhase, lengths: dataSet.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } // if drawing cubic lines is enabled switch dataSet.mode { case .linear: fallthrough case .stepped: drawLinear(context: context, dataSet: dataSet) case .cubicBezier: drawCubicBezier(context: context, dataSet: dataSet) case .horizontalBezier: drawHorizontalBezier(context: context, dataSet: dataSet) } context.restoreGState() } @objc open func drawCubicBezier(context: CGContext, dataSet: ILineChartDataSet) { guard let dataProvider = dataProvider, let animator = animator else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! let intensity = dataSet.cubicIntensity // the path for the cubic-spline let cubicPath = CGMutablePath() let valueToPixelMatrix = trans.valueToPixelMatrix if _xBounds.range >= 1 { var prevDx: CGFloat = 0.0 var prevDy: CGFloat = 0.0 var curDx: CGFloat = 0.0 var curDy: CGFloat = 0.0 // Take an extra point from the left, and an extra from the right. // That's because we need 4 points for a cubic bezier (cubic=4), otherwise we get lines moving and doing weird stuff on the edges of the chart. // So in the starting `prev` and `cur`, go -2, -1 // And in the `lastIndex`, add +1 let firstIndex = _xBounds.min + 1 let lastIndex = _xBounds.min + _xBounds.range var prevPrev: ChartDataEntry! = nil var prev: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 2, 0)) var cur: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 1, 0)) var next: ChartDataEntry! = cur var nextIndex: Int = -1 if cur == nil { return } // let the spline start cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix) for j in stride(from: firstIndex, through: lastIndex, by: 1) { prevPrev = prev prev = cur cur = nextIndex == j ? next : dataSet.entryForIndex(j) nextIndex = j + 1 < dataSet.entryCount ? j + 1 : j next = dataSet.entryForIndex(nextIndex) if next == nil { break } prevDx = CGFloat(cur.x - prevPrev.x) * intensity prevDy = CGFloat(cur.y - prevPrev.y) * intensity curDx = CGFloat(next.x - prev.x) * intensity curDy = CGFloat(next.y - prev.y) * intensity cubicPath.addCurve( to: CGPoint( x: CGFloat(cur.x), y: CGFloat(cur.y) * CGFloat(phaseY)), control1: CGPoint( x: CGFloat(prev.x) + prevDx, y: (CGFloat(prev.y) + prevDy) * CGFloat(phaseY)), control2: CGPoint( x: CGFloat(cur.x) - curDx, y: (CGFloat(cur.y) - curDy) * CGFloat(phaseY)), transform: valueToPixelMatrix) } } context.saveGState() if dataSet.isDrawFilledEnabled { // Copy this path because we make changes to it let fillPath = cubicPath.mutableCopy() drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds) } context.beginPath() context.addPath(cubicPath) context.setStrokeColor(drawingColor.cgColor) context.strokePath() context.restoreGState() } @objc open func drawHorizontalBezier(context: CGContext, dataSet: ILineChartDataSet) { guard let dataProvider = dataProvider, let animator = animator else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! // the path for the cubic-spline let cubicPath = CGMutablePath() let valueToPixelMatrix = trans.valueToPixelMatrix if _xBounds.range >= 1 { var prev: ChartDataEntry! = dataSet.entryForIndex(_xBounds.min) var cur: ChartDataEntry! = prev if cur == nil { return } // let the spline start cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix) for j in stride(from: (_xBounds.min + 1), through: _xBounds.range + _xBounds.min, by: 1) { prev = cur cur = dataSet.entryForIndex(j) let cpx = CGFloat(prev.x + (cur.x - prev.x) / 2.0) cubicPath.addCurve( to: CGPoint( x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), control1: CGPoint( x: cpx, y: CGFloat(prev.y * phaseY)), control2: CGPoint( x: cpx, y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix) } } context.saveGState() if dataSet.isDrawFilledEnabled { // Copy this path because we make changes to it let fillPath = cubicPath.mutableCopy() drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds) } context.beginPath() context.addPath(cubicPath) context.setStrokeColor(drawingColor.cgColor) context.strokePath() context.restoreGState() } open func drawCubicFill( context: CGContext, dataSet: ILineChartDataSet, spline: CGMutablePath, matrix: CGAffineTransform, bounds: XBounds) { guard let dataProvider = dataProvider else { return } if bounds.range <= 0 { return } let fillMin = dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0 var pt1 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min + bounds.range)?.x ?? 0.0), y: fillMin) var pt2 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min)?.x ?? 0.0), y: fillMin) pt1 = pt1.applying(matrix) pt2 = pt2.applying(matrix) spline.addLine(to: pt1) spline.addLine(to: pt2) spline.closeSubpath() if dataSet.fill != nil { drawFilledPath(context: context, path: spline, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: spline, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } fileprivate var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2) @objc open func drawLinear(context: CGContext, dataSet: ILineChartDataSet) { guard let dataProvider = dataProvider, let animator = animator, let viewPortHandler = self.viewPortHandler else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let isDrawSteppedEnabled = dataSet.mode == .stepped let pointsPerEntryPair = isDrawSteppedEnabled ? 4 : 2 let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) // if drawing filled is enabled if dataSet.isDrawFilledEnabled && entryCount > 0 { drawLinearFill(context: context, dataSet: dataSet, trans: trans, bounds: _xBounds) } context.saveGState() context.setLineCap(dataSet.lineCapType) // more than 1 color if dataSet.colors.count > 1 { if _lineSegments.count != pointsPerEntryPair { // Allocate once in correct size _lineSegments = [CGPoint](repeating: CGPoint(), count: pointsPerEntryPair) } for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { var e: ChartDataEntry! = dataSet.entryForIndex(j) if e == nil { continue } _lineSegments[0].x = CGFloat(e.x) _lineSegments[0].y = CGFloat(e.y * phaseY) if j < _xBounds.max { e = dataSet.entryForIndex(j + 1) if e == nil { break } if isDrawSteppedEnabled { _lineSegments[1] = CGPoint(x: CGFloat(e.x), y: _lineSegments[0].y) _lineSegments[2] = _lineSegments[1] _lineSegments[3] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)) } else { _lineSegments[1] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)) } } else { _lineSegments[1] = _lineSegments[0] } for i in 0..<_lineSegments.count { _lineSegments[i] = _lineSegments[i].applying(valueToPixelMatrix) } if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x)) { break } // make sure the lines don't do shitty things outside bounds if !viewPortHandler.isInBoundsLeft(_lineSegments[1].x) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)) { continue } // get the color that is set for this line-segment context.setStrokeColor(dataSet.color(atIndex: j).cgColor) context.strokeLineSegments(between: _lineSegments) } } else { // only one color per dataset var e1: ChartDataEntry! var e2: ChartDataEntry! e1 = dataSet.entryForIndex(_xBounds.min) if e1 != nil { context.beginPath() var firstPoint = true for x in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { e1 = dataSet.entryForIndex(x == 0 ? 0 : (x - 1)) e2 = dataSet.entryForIndex(x) if e1 == nil || e2 == nil { continue } let pt = CGPoint( x: CGFloat(e1.x), y: CGFloat(e1.y * phaseY) ).applying(valueToPixelMatrix) if firstPoint { context.move(to: pt) firstPoint = false } else { context.addLine(to: pt) } if isDrawSteppedEnabled { context.addLine(to: CGPoint( x: CGFloat(e2.x), y: CGFloat(e1.y * phaseY) ).applying(valueToPixelMatrix)) } context.addLine(to: CGPoint( x: CGFloat(e2.x), y: CGFloat(e2.y * phaseY) ).applying(valueToPixelMatrix)) } if !firstPoint { context.setStrokeColor(dataSet.color(atIndex: 0).cgColor) context.strokePath() } } } context.restoreGState() } open func drawLinearFill(context: CGContext, dataSet: ILineChartDataSet, trans: Transformer, bounds: XBounds) { guard let dataProvider = dataProvider else { return } let filled = generateFilledPath( dataSet: dataSet, fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0, bounds: bounds, matrix: trans.valueToPixelMatrix) if dataSet.fill != nil { drawFilledPath(context: context, path: filled, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: filled, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } /// Generates the path that is used for filled drawing. fileprivate func generateFilledPath(dataSet: ILineChartDataSet, fillMin: CGFloat, bounds: XBounds, matrix: CGAffineTransform) -> CGPath { let phaseY = animator?.phaseY ?? 1.0 let isDrawSteppedEnabled = dataSet.mode == .stepped let matrix = matrix var e: ChartDataEntry! let filled = CGMutablePath() e = dataSet.entryForIndex(bounds.min) if e != nil { filled.move(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix) filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix) } // create a new path for x in stride(from: (bounds.min + 1), through: bounds.range + bounds.min, by: 1) { guard let e = dataSet.entryForIndex(x) else { continue } if isDrawSteppedEnabled { guard let ePrev = dataSet.entryForIndex(x-1) else { continue } filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(ePrev.y * phaseY)), transform: matrix) } filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix) } // close up e = dataSet.entryForIndex(bounds.range + bounds.min) if e != nil { filled.addLine(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix) } filled.closeSubpath() return filled } open override func drawValues(context: CGContext) { guard let dataProvider = dataProvider, let lineData = dataProvider.lineData, let animator = animator, let viewPortHandler = self.viewPortHandler else { return } if isDrawingValuesAllowed(dataProvider: dataProvider) { var dataSets = lineData.dataSets let phaseY = animator.phaseY var pt = CGPoint() for i in 0 ..< dataSets.count { guard let dataSet = dataSets[i] as? ILineChartDataSet else { continue } if !shouldDrawValues(forDataSet: dataSet) { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let iconsOffset = dataSet.iconsOffset // make sure the values do not interfear with the circles var valOffset = Int(dataSet.circleRadius * 1.75) if !dataSet.isDrawCirclesEnabled { valOffset = valOffset / 2 } _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) for j in stride(from: _xBounds.min, through: min(_xBounds.min + _xBounds.range, _xBounds.max), by: 1) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.x) pt.y = CGFloat(e.y * phaseY) pt = pt.applying(valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } if dataSet.isDrawValuesEnabled { ChartUtils.drawText( context: context, text: formatter.stringForValue( e.y, entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler), point: CGPoint( x: pt.x, y: pt.y - CGFloat(valOffset) - valueFont.lineHeight), align: .center, attributes: [NSAttributedStringKey.font: valueFont, NSAttributedStringKey.foregroundColor: dataSet.valueTextColorAt(j)]) } if let icon = e.icon, dataSet.isDrawIconsEnabled { ChartUtils.drawImage(context: context, image: icon, x: pt.x + iconsOffset.x, y: pt.y + iconsOffset.y, size: icon.size) } } } } } open override func drawExtras(context: CGContext) { drawCircles(context: context) } fileprivate func drawCircles(context: CGContext) { guard let dataProvider = dataProvider, let lineData = dataProvider.lineData, let animator = animator, let viewPortHandler = self.viewPortHandler else { return } let phaseY = animator.phaseY let dataSets = lineData.dataSets var pt = CGPoint() var rect = CGRect() context.saveGState() for i in 0 ..< dataSets.count { guard let dataSet = lineData.getDataSetByIndex(i) as? ILineChartDataSet else { continue } if !dataSet.isVisible || !dataSet.isDrawCirclesEnabled || dataSet.entryCount == 0 { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) let circleRadius = dataSet.circleRadius let circleDiameter = circleRadius * 2.0 let circleHoleRadius = dataSet.circleHoleRadius let circleHoleDiameter = circleHoleRadius * 2.0 let drawCircleHole = dataSet.isDrawCircleHoleEnabled && circleHoleRadius < circleRadius && circleHoleRadius > 0.0 let drawTransparentCircleHole = drawCircleHole && (dataSet.circleHoleColor == nil || dataSet.circleHoleColor == NSUIColor.clear) for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.x) pt.y = CGFloat(e.y * phaseY) pt = pt.applying(valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the circles don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } context.setFillColor(dataSet.getCircleColor(atIndex: j)!.cgColor) rect.origin.x = pt.x - circleRadius rect.origin.y = pt.y - circleRadius rect.size.width = circleDiameter rect.size.height = circleDiameter if drawTransparentCircleHole { // Begin path for circle with hole context.beginPath() context.addEllipse(in: rect) // Cut hole in path rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter context.addEllipse(in: rect) // Fill in-between context.fillPath(using: .evenOdd) } else { context.fillEllipse(in: rect) if drawCircleHole { context.setFillColor(dataSet.circleHoleColor!.cgColor) // The hole rect rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter context.fillEllipse(in: rect) } } } } context.restoreGState() } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let dataProvider = dataProvider, let lineData = dataProvider.lineData, let animator = animator else { return } let chartXMax = dataProvider.chartXMax context.saveGState() for high in indices { guard let set = lineData.getDataSetByIndex(high.dataSetIndex) as? ILineChartDataSet , set.isHighlightEnabled else { continue } guard let e = set.entryForXValue(high.x, closestToY: high.y) else { continue } if !isInBoundsX(entry: e, dataSet: set) { continue } context.setStrokeColor(set.highlightColor.cgColor) context.setLineWidth(set.highlightLineWidth) if set.highlightLineDashLengths != nil { context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } let x = high.x // get the x-position let y = high.y * Double(animator.phaseY) if x > chartXMax * animator.phaseX { continue } let trans = dataProvider.getTransformer(forAxis: set.axisDependency) let pt = trans.pixelForValues(x: x, y: y) high.setDraw(pt: pt) // draw the lines drawHighlightLines(context: context, point: pt, set: set) } context.restoreGState() } }
apache-2.0
2b715dd5eb02816bed5ce166ded4cdd4
34.890767
155
0.488188
5.764411
false
false
false
false
kstaring/swift
stdlib/public/core/Character.swift
1
15352
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A single extended grapheme cluster, which approximates a user-perceived /// character. /// /// The `Character` type represents a character made up of one or more Unicode /// scalar values, grouped by a Unicode boundary algorithm. Generally, a /// `Character` instance matches what the reader of a string will perceive as /// a single character. The number of visible characters is generally the most /// natural way to count the length of a string. /// /// let greeting = "Hello! 🐥" /// print("Character count: \(greeting.characters.count)") /// // Prints "Character count: 8" /// /// Because each character in a string can be made up of one or more Unicode /// code points, the number of characters in a string may not match the length /// of the Unicode code point representation or the length of the string in a /// particular binary representation. /// /// print("Unicode code point count: \(greeting.unicodeScalars.count)") /// // Prints "Unicode code point count: 15" /// /// print("UTF-8 representation count: \(greeting.utf8.count)") /// // Prints "UTF-8 representation count: 18" /// /// Every `Character` instance is composed of one or more Unicode code points /// that are grouped together as an *extended grapheme cluster*. The way these /// code points are grouped is defined by a canonical, localized, or otherwise /// tailored Unicode segmentation algorithm. /// /// For example, a country's Unicode flag character is made up of two regional /// indicator code points that correspond to that country's ISO 3166-1 alpha-2 /// code. The alpha-2 code for The United States is "US", so its flag /// character is made up of the Unicode code points `"\u{1F1FA}"` (REGIONAL /// INDICATOR SYMBOL LETTER U) and `"\u{1F1F8}"` (REGIONAL INDICATOR SYMBOL /// LETTER S). When placed next to each other in a Swift string literal, these /// two code points are combined into a single grapheme cluster, represented /// by a `Character` instance in Swift. /// /// let usFlag: Character = "\u{1F1FA}\u{1F1F8}" /// print(usFlag) /// // Prints "🇺🇸" /// /// For more information about the Unicode terms used in this discussion, see /// the [Unicode.org glossary][glossary]. In particular, this discussion /// mentions [extended grapheme clusters][clusters] and [Unicode scalar /// values][scalars]. /// /// [glossary]: http://www.unicode.org/glossary/ /// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster /// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value public struct Character : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral, ExpressibleByExtendedGraphemeClusterLiteral, Hashable { // Fundamentally, it is just a String, but it is optimized for the // common case where the UTF-8 representation fits in 63 bits. The // remaining bit is used to discriminate between small and large // representations. In the small representation, the unused bytes // are filled with 0xFF. // // If the grapheme cluster can be represented as `.small`, it // should be represented as such. @_versioned internal enum Representation { // A _StringBuffer whose first grapheme cluster is self. // NOTE: may be more than 1 Character long. case large(_StringBuffer._Storage) case small(Builtin.Int63) } /// Creates a character containing the given Unicode scalar value. /// /// - Parameter scalar: The Unicode scalar value to convert into a character. public init(_ scalar: UnicodeScalar) { var asInt: UInt64 = 0 var shift: UInt64 = 0 let output: (UTF8.CodeUnit) -> Void = { asInt |= UInt64($0) << shift shift += 8 } UTF8.encode(scalar, into: output) asInt |= (~0) << shift _representation = .small(Builtin.trunc_Int64_Int63(asInt._value)) } @effects(readonly) public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = Character( String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value)))) } /// Creates a character with the specified value. /// /// Do not call this initializer directly. It is used by the compiler when you /// use a string literal to initialize a `Character` instance. For example: /// /// let snowflake: Character = "❄︎" /// print(snowflake) /// // Prints "❄︎" /// /// The assignment to the `snowflake` constant calls this initializer behind /// the scenes. public init(unicodeScalarLiteral value: Character) { self = value } @effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { self = Character( String( _builtinExtendedGraphemeClusterLiteral: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII)) } /// Creates a character with the specified value. /// /// Do not call this initializer directly. It is used by the compiler when /// you use a string literal to initialize a `Character` instance. For /// example: /// /// let oBreve: Character = "o\u{306}" /// print(oBreve) /// // Prints "ŏ" /// /// The assignment to the `oBreve` constant calls this initializer behind the /// scenes. public init(extendedGraphemeClusterLiteral value: Character) { self = value } /// Creates a character from a single-character string. /// /// The following example creates a new character from the uppercase version /// of a string that only holds one character. /// /// let a = "a" /// let capitalA = Character(a.uppercased()) /// /// - Parameter s: The single-character string to convert to a `Character` /// instance. `s` must contain exactly one extended grapheme cluster. public init(_ s: String) { // The small representation can accept up to 8 code units as long // as the last one is a continuation. Since the high bit of the // last byte is used for the enum's discriminator, we have to // reconstruct it. As a result, we can't store 0x7f in the final // byte, because we wouldn't be able to distinguish it from an // unused 0xFF byte. Rather than trying to squeeze in other // one-byte code points there, we simplify decoding by banning // starting a code point in the last byte, and assuming that its // high bit is 1. _precondition( s._core.count != 0, "Can't form a Character from an empty String") _precondition( s.index(after: s.startIndex) == s.endIndex, "Can't form a Character from a String containing more than one extended grapheme cluster") let (count, initialUTF8) = s._core._encodeSomeUTF8(from: 0) // Notice that the result of sizeof() is a small non-zero number and can't // overflow when multiplied by 8. let bits = MemoryLayout.size(ofValue: initialUTF8) &* 8 &- 1 if _fastPath( count == s._core.count && (initialUTF8 & (1 << numericCast(bits))) != 0) { _representation = .small(Builtin.trunc_Int64_Int63(initialUTF8._value)) } else { if let native = s._core.nativeBuffer, native.start == s._core._baseAddress! { _representation = .large(native._storage) return } var nativeString = "" nativeString.append(s) _representation = .large(nativeString._core.nativeBuffer!._storage) } } /// Returns the index of the lowest byte that is 0xFF, or 8 if /// there is none. static func _smallSize(_ value: UInt64) -> Int { var mask: UInt64 = 0xFF for i in 0..<8 { if (value & mask) == mask { return i } mask <<= 8 } return 8 } static func _smallValue(_ value: Builtin.Int63) -> UInt64 { return UInt64(Builtin.zext_Int63_Int64(value)) | (1<<63) } internal struct _SmallUTF8 : RandomAccessCollection { typealias Indices = CountableRange<Int> var indices: CountableRange<Int> { return startIndex..<endIndex } init(_ u8: UInt64) { let utf8Count = Character._smallSize(u8) _sanityCheck(utf8Count <= 8, "Character with more than 8 UTF-8 code units") self.count = UInt16(utf8Count) self.data = u8 } /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. var endIndex: Int { return Int(count) } /// Access the code unit at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. subscript(position: Int) -> UTF8.CodeUnit { _sanityCheck(position >= 0) _sanityCheck(position < Int(count)) // Note: using unchecked arithmetic because overflow cannot happen if the // above sanity checks hold. return UTF8.CodeUnit( truncatingBitPattern: data >> (UInt64(position) &* 8)) } internal struct Iterator : IteratorProtocol { init(_ data: UInt64) { self._data = data } internal mutating func next() -> UInt8? { let result = UInt8(truncatingBitPattern: _data) if result == 0xFF { return nil } _data = (_data >> 8) | 0xFF00_0000_0000_0000 return result } internal var _data: UInt64 } internal func makeIterator() -> Iterator { return Iterator(data) } var count: UInt16 var data: UInt64 } struct _SmallUTF16 : RandomAccessCollection { typealias Indices = CountableRange<Int> init(_ u8: UInt64) { let count = UTF16.transcodedLength( of: _SmallUTF8(u8).makeIterator(), decodedAs: UTF8.self, repairingIllFormedSequences: true)!.0 _sanityCheck(count <= 4, "Character with more than 4 UTF-16 code units") self.count = UInt16(count) var u16: UInt64 = 0 let output: (UTF16.CodeUnit) -> Void = { u16 = u16 << 16 u16 = u16 | UInt64($0) } _ = transcode( _SmallUTF8(u8).makeIterator(), from: UTF8.self, to: UTF16.self, stoppingOnError: false, into: output) self.data = u16 } /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. var endIndex: Int { return Int(count) } /// Access the code unit at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. subscript(position: Int) -> UTF16.CodeUnit { _sanityCheck(position >= 0) _sanityCheck(position < Int(count)) // Note: using unchecked arithmetic because overflow cannot happen if the // above sanity checks hold. return UTF16.CodeUnit(truncatingBitPattern: data >> ((UInt64(count) &- UInt64(position) &- 1) &* 16)) } var count: UInt16 var data: UInt64 } /// The character's hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. public var hashValue: Int { // FIXME(performance): constructing a temporary string is extremely // wasteful and inefficient. return String(self).hashValue } typealias UTF16View = String.UTF16View var utf16: UTF16View { return String(self).utf16 } @_versioned internal var _representation: Representation } extension Character : CustomStringConvertible { public var description: String { return String(describing: self) } } extension Character : LosslessStringConvertible {} extension Character : CustomDebugStringConvertible { /// A textual representation of the character, suitable for debugging. public var debugDescription: String { return String(self).debugDescription } } extension String { /// Creates a string containing the given character. /// /// - Parameter c: The character to convert to a string. public init(_ c: Character) { switch c._representation { case let .small(_63bits): let value = Character._smallValue(_63bits) let smallUTF8 = Character._SmallUTF8(value) self = String._fromWellFormedCodeUnitSequence( UTF8.self, input: smallUTF8) case let .large(value): let buf = String(_StringCore(_StringBuffer(value))) self = buf[buf.startIndex..<buf.index(after: buf.startIndex)] } } } /// `.small` characters are stored in an Int63 with their UTF-8 representation, /// with any unused bytes set to 0xFF. ASCII characters will have all bytes set /// to 0xFF except for the lowest byte, which will store the ASCII value. Since /// 0x7FFFFFFFFFFFFF80 or greater is an invalid UTF-8 sequence, we know if a /// value is ASCII by checking if it is greater than or equal to /// 0x7FFFFFFFFFFFFF00. internal var _minASCIICharReprBuiltin: Builtin.Int63 { @inline(__always) get { let x: Int64 = 0x7FFFFFFFFFFFFF00 return Builtin.truncOrBitCast_Int64_Int63(x._value) } } extension Character : Equatable { public static func == (lhs: Character, rhs: Character) -> Bool { switch (lhs._representation, rhs._representation) { case let (.small(lbits), .small(rbits)) where Bool(Builtin.cmp_uge_Int63(lbits, _minASCIICharReprBuiltin)) && Bool(Builtin.cmp_uge_Int63(rbits, _minASCIICharReprBuiltin)): return Bool(Builtin.cmp_eq_Int63(lbits, rbits)) default: // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) == String(rhs) } } } extension Character : Comparable { public static func < (lhs: Character, rhs: Character) -> Bool { switch (lhs._representation, rhs._representation) { case let (.small(lbits), .small(rbits)) where // Note: This is consistent with Foundation but unicode incorrect. // See String._compareASCII. Bool(Builtin.cmp_uge_Int63(lbits, _minASCIICharReprBuiltin)) && Bool(Builtin.cmp_uge_Int63(rbits, _minASCIICharReprBuiltin)): return Bool(Builtin.cmp_ult_Int63(lbits, rbits)) default: // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) < String(rhs) } } }
apache-2.0
4066120f675503c9772e3d3b811e7f9a
34.331797
96
0.657493
4.178202
false
false
false
false
natecook1000/swift
test/SILOptimizer/infinite_recursion.swift
3
2843
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify func a() { // expected-warning {{all paths through this function will call itself}} a() } func b(_ x : Int) { // expected-warning {{all paths through this function will call itself}} if x != 0 { b(x) } else { b(x+1) } } func c(_ x : Int) { if x != 0 { c(5) } } func d(_ x : Int) { // expected-warning {{all paths through this function will call itself}} var x = x if x != 0 { x += 1 } return d(x) } // Doesn't warn on mutually recursive functions func e() { f() } func f() { e() } func g() { // expected-warning {{all paths through this function will call itself}} while true { // expected-note {{condition always evaluates to true}} g() } g() // expected-warning {{will never be executed}} } func h(_ x : Int) { while (x < 5) { h(x+1) } } func i(_ x : Int) { // expected-warning {{all paths through this function will call itself}} var x = x while (x < 5) { x -= 1 } i(0) } func j() -> Int { // expected-warning {{all paths through this function will call itself}} return 5 + j() } func k() -> Any { // expected-warning {{all paths through this function will call itself}} return type(of: k()) } class S { convenience init(a: Int) { // expected-warning {{all paths through this function will call itself}} self.init(a: a) } init(a: Int?) {} static func a() { // expected-warning {{all paths through this function will call itself}} return a() } func b() { // expected-warning {{all paths through this function will call itself}} var i = 0 repeat { i += 1 b() } while (i > 5) } var bar: String = "hi!" } class T: S { // No warning, calls super override func b() { var i = 0 repeat { i += 1 super.b() } while (i > 5) } override var bar: String { get { return super.bar } set { // expected-warning {{all paths through this function will call itself}} self.bar = newValue } } } func == (l: S?, r: S?) -> Bool { // expected-warning {{all paths through this function will call itself}} if l == nil && r == nil { return true } guard let l = l, let r = r else { return false } return l === r } public func == <Element>(lhs: Array<Element>, rhs: Array<Element>) -> Bool { // expected-warning {{all paths through this function will call itself}} return lhs == rhs } func factorial(_ n : UInt) -> UInt { // expected-warning {{all paths through this function will call itself}} return (n != 0) ? factorial(n - 1) * n : factorial(1) } func tr(_ key: String) -> String { // expected-warning {{all paths through this function will call itself}} return tr(key) ?? key // expected-warning {{left side of nil coalescing operator '??' has non-optional type}} }
apache-2.0
3e33a71630c9fe8d685a643dc17e8be4
22.495868
149
0.595849
3.384524
false
false
false
false
iadmir/Signal-iOS
Signal/src/UserInterface/Strings.swift
2
3293
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation /** * Strings re-used in multiple places should be added here. */ @objc class CommonStrings: NSObject { static let dismissButton = NSLocalizedString("DISMISS_BUTTON_TEXT", comment: "Short text to dismiss current modal / actionsheet / screen") static let cancelButton = NSLocalizedString("TXT_CANCEL_TITLE", comment:"Label for the cancel button in an alert or action sheet.") static let retryButton = NSLocalizedString("RETRY_BUTTON_TEXT", comment:"Generic text for button that retries whatever the last action was.") } @objc class MessageStrings: NSObject { static let newGroupDefaultTitle = NSLocalizedString("NEW_GROUP_DEFAULT_TITLE", comment: "Used in place of the group name when a group has not yet been named.") } @objc class CallStrings: NSObject { static let callStatusFormat = NSLocalizedString("CALL_STATUS_FORMAT", comment: "embeds {{Call Status}} in call screen label. For ongoing calls, {{Call Status}} is a seconds timer like 01:23, otherwise {{Call Status}} is a short text like 'Ringing', 'Busy', or 'Failed Call'") static let confirmAndCallButtonTitle = NSLocalizedString("SAFETY_NUMBER_CHANGED_CONFIRM_CALL_ACTION", comment: "alert button text to confirm placing an outgoing call after the recipients Safety Number has changed.") static let callBackAlertTitle = NSLocalizedString("CALL_USER_ALERT_TITLE", comment: "Title for alert offering to call a user.") static let callBackAlertMessageFormat = NSLocalizedString("CALL_USER_ALERT_MESSAGE_FORMAT", comment: "Message format for alert offering to call a user. Embeds {{the user's display name or phone number}}.") static let callBackAlertCallButton = NSLocalizedString("CALL_USER_ALERT_CALL_BUTTON", comment: "Label for call button for alert offering to call a user.") // MARK: Notification actions static let callBackButtonTitle = NSLocalizedString("CALLBACK_BUTTON_TITLE", comment: "notification action") static let showThreadButtonTitle = NSLocalizedString("SHOW_THREAD_BUTTON_TITLE", comment: "notification action") // MARK: Missed Call Notification static let missedCallNotificationBodyWithoutCallerName = NSLocalizedString("MISSED_CALL", comment: "notification title") static let missedCallNotificationBodyWithCallerName = NSLocalizedString("MSGVIEW_MISSED_CALL_WITH_NAME", comment: "notification title. Embeds {{caller's name or phone number}}") // MARK: Missed with changed identity notification (for not previously verified identity) static let missedCallWithIdentityChangeNotificationBodyWithoutCallerName = NSLocalizedString("MISSED_CALL_WITH_CHANGED_IDENTITY_BODY_WITHOUT_CALLER_NAME", comment: "notification title") static let missedCallWithIdentityChangeNotificationBodyWithCallerName = NSLocalizedString("MISSED_CALL_WITH_CHANGED_IDENTITY_BODY_WITH_CALLER_NAME", comment: "notification title. Embeds {{caller's name or phone number}}") } @objc class SafetyNumberStrings: NSObject { static let confirmSendButton = NSLocalizedString("SAFETY_NUMBER_CHANGED_CONFIRM_SEND_ACTION", comment: "button title to confirm sending to a recipient whose safety number recently changed") }
gpl-3.0
d9f972a102e890ab8d0d318b490975bc
69.06383
279
0.764045
4.744957
false
false
false
false
dnevera/ImageMetalling
ImageMetalling-09/ImageMetalling-09/ViewController.swift
1
20280
// // ViewController.swift // ImageMetalling-08 // // Created by denis svinarchuk on 01.01.16. // Copyright © 2016 ImageMetalling. All rights reserved. // import Cocoa import IMProcessing import SnapKit class IMPLabel: NSTextField { override init(frame frameRect: NSRect) { super.init(frame: frameRect) drawsBackground = false bezeled = false editable = false alignment = .Center textColor = IMPColor.lightGrayColor() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ViewController: NSViewController { // // Контекст процессинга // var context = IMPContext() // // Окно представления загруженной картинки // var imageView:IMPImageView! // // Окно вывода гистограммы изображения // var histogramView:IMPHistogramView! // // Основной фильтр // var filter:IMPAutoWBFilter! // // Фильтр CLUT из фалов формата Adobe Cube // Будем использовать для того, что бы проверить насколько влияет нормализация // на последущую обработку, т.е. то ради того чего применяется нормализация цветовой гаммы // var lutFilter:IMPLutFilter? override func viewDidLoad() { super.viewDidLoad() if !IMPContext.supportsSystemDevice { self.asyncChanges({ () -> Void in let alert = NSAlert(error: NSError(domain: "com.imagemetalling.08", code: 0, userInfo: [ NSLocalizedFailureReasonErrorKey:"MTL initialization error", NSLocalizedDescriptionKey:"The system does not support MTL..." ])) alert.runModal() }) return } configurePannel() // // Создаем фильтр автоматической коррекции баланса цветов // filter = IMPAutoWBFilter(context: context) // // Профилируем обработку через анализ распределения весов на цветовом круге. // Снижаем влияние автоматической коррекции в зависимости от сюжета и замысла нашего // фильтра. Форма снижения или увеличения opacity, а по сути силы воздействия AWB, // может быть произвольной. // // В конкретном примере: // 1. мы снижаем долю насыщенности желого, если доминантный цвет изображения желто-красный. // 2. учитываем вес голубых и синих оттенков для снижения влияения на сюжетах с явно выраженным // участием сине-голубых цветов // // filter.colorsAnalyzeHandler = { (solver, opacityIn, wbFilter, hsvFilter) in // // Получаем доминантный цвет изображения // let dominanta = self.filter.dominantColor! // // Переходим в пространство HSV // let hsv = dominanta.rgb.tohsv() // // Получаем тон доминантного цвета // let hue = hsv.hue * 360 // // Просто выводим для справки // self.dominantLabel.stringValue = String(format: "%4.0fº", hue) self.neutralsWLabel.stringValue = String(format: "%4.0f%", solver.neutralWeights.neutrals*100) // // Учитываем состав доминантного цвета // var reds_yellows_weights = // // количество красного с учетом перекрытия красных оттенков из // цветового круга HSV и степенью перекрытия с соседними цветами 1 // hue.overlapWeight(ramp: IMProcessing.hsv.reds, overlap: 1) + // // к красным добавляем количество желтого // hue.overlapWeight(ramp: IMProcessing.hsv.yellows, overlap: 1) // // Веса оставшихся оттенков в доминантном цвете // let other_colors = solver.colorWeights.cyans + solver.colorWeights.greens + solver.colorWeights.blues + solver.colorWeights.magentas reds_yellows_weights -= other_colors if (reds_yellows_weights < 0.0 /* 10% */) { // // Если желто-красного немного вообще неучитываем в снижении // reds_yellows_weights = 0.0; // it is a yellow/red image } // // Снижаем насыщенность желтых оттенков в изображении // hsvFilter.adjustment.yellows.saturation = -0.1 * reds_yellows_weights self.yellowsWLabel.stringValue = String(format: "%4.0f%", reds_yellows_weights*100) // // Результирующая прозрачность слоя AWB // var opacity:Float = opacityIn // // Для сине-голубых оттенков изображения снижаем долю влияния AWB фильтра // вычисляем общий вес (по сути площадь) // let cyan_blues = solver.colorWeights.cyans + solver.colorWeights.blues let rest = 1 - cyan_blues self.bluesWLabel.stringValue = String(format: "%4.0f%", cyan_blues*100) // // Какая-то выдуманная функиця снижения прозрачности AWB от веса сине-голубых оттенков // opacity *= rest < cyan_blues ? 1-sqrt(pow(cyan_blues,2) - pow(rest, 2)) : 1 self.opacityLabel.stringValue = String(format: "%4.0f%", opacity*100) return opacity } imageView = IMPImageView(context: context, frame: view.bounds) imageView.filter = filter imageView.backgroundColor = IMPColor(color: IMPPrefs.colors.background) // // Добавляем наблюдателя к фильтру для обработки результатов // фильтрования // filter.addDestinationObserver { (destination) -> Void in // передаем картинку показывателю кистограммы self.histogramView.filter?.source = destination } view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.snp_makeConstraints { (make) -> Void in make.top.equalTo(imageView.superview!).offset(10) make.bottom.equalTo(imageView.superview!).offset(0) make.left.equalTo(imageView.superview!).offset(10) make.right.equalTo(pannelScrollView.snp_left).offset(0) } IMPDocument.sharedInstance.addDocumentObserver { (file, type) -> Void in if type == .Image { do{ // // Загружаем файл и связываем источником фильтра // self.imageView.filter?.source = try IMPJpegProvider(context: self.context, file: file) self.asyncChanges({ () -> Void in self.zoomFit() }) } catch let error as NSError { self.asyncChanges({ () -> Void in let alert = NSAlert(error: error) alert.runModal() }) } } else if type == .LUT { do { // // Инициализируем дескриптор CLUT // var description = IMPImageProvider.LutDescription() // // Загружаем CLUT // let lutProvider = try IMPImageProvider(context: self.context, cubeFile: file, description: &description) if let lut = self.lutFilter{ // // Если CLUT-фильтр добавлен - обновляем его LUT-таблицу из файла с полученным дескриптором // lut.update(lutProvider, description:description) } else{ // // Создаем новый фильтр LUT // self.lutFilter = IMPLutFilter(context: self.context, lut: lutProvider, description: description) } // // Добавляем LUT-фильтр, если этот фильтр уже был добавленб ничего не происходит // self.filter.addFilter(self.lutFilter!) } catch let error as NSError { self.asyncChanges({ () -> Void in let alert = NSAlert(error: error) alert.runModal() }) } } } IMPMenuHandler.sharedInstance.addMenuObserver { (item) -> Void in if let tag = IMPMenuTag(rawValue: item.tag) { switch tag { case .zoomFit: self.zoomFit() case .zoom100: self.zoom100() case .resetLut: if let l = self.lutFilter { self.filter.removeFilter(l) } break } } } } // // Вся остальная часть относится к визуальному представления данных // private func zoomFit(){ asyncChanges { () -> Void in self.imageView.sizeFit() } } private func zoom100(){ asyncChanges { () -> Void in self.imageView.sizeOriginal() } } override func viewDidAppear() { if IMPContext.supportsSystemDevice { super.viewDidAppear() asyncChanges { () -> Void in self.imageView.sizeFit() } } } var q = dispatch_queue_create("ViewController", DISPATCH_QUEUE_CONCURRENT) private func asyncChanges(block:()->Void) { dispatch_async(q, { () -> Void in // // немного того, но... :) // dispatch_after(0, dispatch_get_main_queue()) { () -> Void in block() } }) } var dominantLabel = IMPLabel() var neutralsWLabel = IMPLabel() var yellowsWLabel = IMPLabel() var bluesWLabel = IMPLabel() var opacityLabel = IMPLabel() private func configureWeightsPannel(view:NSView){ let label1 = IMPLabel() sview.addSubview(label1) label1.stringValue = "Dominant color hue:" label1.snp_makeConstraints { (make) -> Void in make.top.equalTo(view.snp_bottom).offset(10) make.left.equalTo(sview).offset(10) make.height.equalTo(20) } sview.addSubview(dominantLabel) dominantLabel.stringValue = "0" dominantLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(view.snp_bottom).offset(10) make.left.equalTo(label1.snp_right).offset(10) make.height.equalTo(20) } allHeights+=40 let label2 = IMPLabel() sview.addSubview(label2) label2.stringValue = "Neutrals color weights:" label2.snp_makeConstraints { (make) -> Void in make.top.equalTo(label1.snp_bottom).offset(10) make.left.equalTo(sview).offset(10) make.height.equalTo(20) } sview.addSubview(neutralsWLabel) neutralsWLabel.stringValue = "0" neutralsWLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(dominantLabel.snp_bottom).offset(10) make.left.equalTo(label2.snp_right).offset(10) make.height.equalTo(20) } allHeights+=40 let label3 = IMPLabel() sview.addSubview(label3) label3.stringValue = "Reds/Yellows weights in dominat:" label3.snp_makeConstraints { (make) -> Void in make.top.equalTo(label2.snp_bottom).offset(10) make.left.equalTo(sview).offset(10) make.height.equalTo(20) } sview.addSubview(yellowsWLabel) yellowsWLabel.stringValue = "0" yellowsWLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(neutralsWLabel.snp_bottom).offset(10) make.left.equalTo(label3.snp_right).offset(10) make.height.equalTo(20) } allHeights+=40 let label4 = IMPLabel() sview.addSubview(label4) label4.stringValue = "Cyans/Blues weights:" label4.snp_makeConstraints { (make) -> Void in make.top.equalTo(label3.snp_bottom).offset(10) make.left.equalTo(sview).offset(10) make.height.equalTo(20) } sview.addSubview(bluesWLabel) bluesWLabel.stringValue = "0" bluesWLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(yellowsWLabel.snp_bottom).offset(10) make.left.equalTo(label4.snp_right).offset(10) make.height.equalTo(20) } allHeights+=40 let label5 = IMPLabel() sview.addSubview(label5) label5.stringValue = "AWB opacity:" label5.snp_makeConstraints { (make) -> Void in make.top.equalTo(label4.snp_bottom).offset(10) make.left.equalTo(sview).offset(10) make.height.equalTo(20) } sview.addSubview(opacityLabel) opacityLabel.stringValue = "0" opacityLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(bluesWLabel.snp_bottom).offset(10) make.left.equalTo(label5.snp_right).offset(10) make.height.equalTo(20) } allHeights+=40 } var pannelScrollView = NSScrollView() var sview:NSView! var allHeights = CGFloat(0) private func configurePannel(){ pannelScrollView.wantsLayer = true view.addSubview(pannelScrollView) pannelScrollView.drawsBackground = false pannelScrollView.allowsMagnification = false pannelScrollView.contentView.wantsLayer = true sview = NSView(frame: pannelScrollView.bounds) sview.wantsLayer = true sview.layer?.backgroundColor = IMPColor.clearColor().CGColor pannelScrollView.documentView = sview pannelScrollView.snp_makeConstraints { (make) -> Void in make.width.equalTo(280) make.top.equalTo(pannelScrollView.superview!).offset(10) make.bottom.equalTo(pannelScrollView.superview!).offset(10) make.right.equalTo(pannelScrollView.superview!).offset(-10) } sview.snp_makeConstraints { (make) -> Void in make.edges.equalTo(pannelScrollView).inset(NSEdgeInsetsMake(10, 10, 10, 10)) } histogramView = IMPHistogramView(context: context, frame: view.bounds) sview.addSubview(histogramView) histogramView.snp_makeConstraints { (make) -> Void in make.top.equalTo(sview).offset(0) make.left.equalTo(sview).offset(0) make.right.equalTo(sview).offset(0) make.height.equalTo(200) } allHeights+=200 let last = configureFilterSettings() configureWeightsPannel(last) } private func configureFilterSettings() -> NSView { let awbLabel = IMPLabel(frame: view.bounds) sview.addSubview(awbLabel) awbLabel.stringValue = "White Balance" awbLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(histogramView.snp_bottom).offset(20) make.right.equalTo(sview).offset(0) make.height.equalTo(20) } allHeights+=40 let awbSlider = NSSlider(frame: view.bounds) awbSlider.minValue = 0 awbSlider.maxValue = 100 awbSlider.integerValue = 100 awbSlider.action = #selector(ViewController.changeAWB(_:)) awbSlider.continuous = true sview.addSubview(awbSlider) awbSlider.snp_makeConstraints { (make) -> Void in make.top.equalTo(awbLabel.snp_bottom).offset(5) make.left.equalTo(sview).offset(0) make.right.equalTo(sview).offset(0) } allHeights+=40 let clutLabel = IMPLabel(frame: view.bounds) sview.addSubview(clutLabel) clutLabel.stringValue = "CLUT Impact" clutLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(awbSlider.snp_bottom).offset(20) make.right.equalTo(sview).offset(0) make.height.equalTo(20) } allHeights+=40 let clutSlider = NSSlider(frame: view.bounds) clutSlider.minValue = 0 clutSlider.maxValue = 100 clutSlider.integerValue = 100 clutSlider.action = #selector(ViewController.changeClut(_:)) clutSlider.continuous = true sview.addSubview(clutSlider) clutSlider.snp_makeConstraints { (make) -> Void in make.top.equalTo(clutLabel.snp_bottom).offset(5) make.left.equalTo(sview).offset(0) make.right.equalTo(sview).offset(0) } allHeights+=40 return clutSlider } func changeAWB(sender:NSSlider){ let value = sender.floatValue/100 asyncChanges { () -> Void in self.filter.adjustment.blending.opacity = value } } func changeClut(sender:NSSlider){ let value = sender.floatValue/100 asyncChanges { () -> Void in self.lutFilter?.adjustment.blending.opacity = value } } override func viewDidLayout() { let h = view.bounds.height < allHeights ? allHeights : view.bounds.height sview.snp_remakeConstraints { (make) -> Void in make.top.equalTo(pannelScrollView).offset(0) make.left.equalTo(pannelScrollView).offset(0) make.right.equalTo(pannelScrollView).offset(0) make.height.equalTo(h) } } }
mit
0e4cf1b090c81262d7e95030cfcc1b2a
33.405556
124
0.54567
4.183517
false
false
false
false
steamclock/internetmap
iOS/TimedMessageLabel.swift
1
846
// // TimedMessageLabel.swift // Internet Map // // Created by Nigel Brooke on 2018-03-06. // Copyright © 2018 Peer1. All rights reserved. // import UIKit public class TimedMessageLabel: UILabel { private var hidingTimer: Timer? public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) alpha = 0.0 } @objc public func setErrorString(_ error: String) { text = error hidingTimer?.invalidate() hidingTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.hidingTimerFired), userInfo: nil, repeats: false) UIView.animate(withDuration: 0.75) { self.alpha = 1.0 } } @objc private func hidingTimerFired() { UIView.animate(withDuration: 0.75) { self.alpha = 0.0 } } }
mit
99ba2885a68d6ccfe01b4ab7c5aa66b0
23.142857
148
0.623669
3.967136
false
false
false
false
ello/ello-ios
Sources/Networking/Fragments.swift
1
7544
//// /// Fragments.swift // struct Fragments: Equatable { //| //| FRAGMENTS //| static let categoryPostActions = Fragments( """ fragment categoryPostActions on CategoryPostActions { feature { href label method } unfeature { href label method } } """ ) static let imageProps = Fragments( """ fragment imageProps on Image { url metadata { height width type size } } """ ) static let tshirtProps = Fragments( """ fragment tshirtProps on TshirtImageVersions { regular { ...imageProps } large { ...imageProps } original { ...imageProps } } """, needs: [imageProps] ) static let responsiveProps = Fragments( """ fragment responsiveProps on ResponsiveImageVersions { mdpi { ...imageProps } hdpi { ...imageProps } xhdpi { ...imageProps } optimized { ...imageProps } } """, needs: [imageProps] ) static let authorProps = Fragments( """ fragment authorProps on User { id username name currentUserState { relationshipPriority } settings { hasCommentingEnabled hasLovesEnabled hasRepostingEnabled hasSharingEnabled isCollaborateable isHireable } avatar { ...tshirtProps } coverImage { ...responsiveProps } } """, needs: [tshirtProps, responsiveProps] ) static let categoryProps = Fragments( """ fragment categoryProps on Category { id name slug order allowInOnboarding isCreatorType level description tileImage { ...tshirtProps } } """, needs: [tshirtProps] ) static let pageHeaderUserProps = Fragments( """ fragment pageHeaderUserProps on User { id username name avatar { ...tshirtProps } coverImage { ...responsiveProps } } """, needs: [tshirtProps, responsiveProps] ) static let assetProps = Fragments( """ fragment assetProps on Asset { id attachment { ...responsiveProps } } """ ) static let contentProps = Fragments( """ fragment contentProps on ContentBlocks { linkUrl kind data links { assets } } """ ) static let postSummary = Fragments( """ fragment postSummary on Post { id token createdAt summary { ...contentProps } author { ...authorProps } artistInviteSubmission { id artistInvite { id } } assets { ...assetProps } postStats { lovesCount commentsCount viewsCount repostsCount } currentUserState { watching loved reposted } } """, needs: [contentProps, assetProps, imageProps, tshirtProps, responsiveProps, authorProps] ) static let postDetails = Fragments( """ fragment postDetails on Post { ...postSummary content { ...contentProps } repostContent { ...contentProps } categoryPosts { id actions { ...categoryPostActions } status category { ...categoryProps } featuredAt submittedAt removedAt unfeaturedAt featuredBy { id username name } submittedBy { id username name } } repostedSource { ...postSummary } } """, needs: [contentProps, postSummary, categoryPostActions, categoryProps] ) static let loveDetails = Fragments( """ fragment loveDetails on Love { id post { ...postDetails } user { id } } """, needs: [postDetails] ) static let commentDetails = Fragments( """ fragment commentDetails on Comment { id createdAt parentPost { id } assets { ...assetProps } author { ...authorProps } content { ...contentProps } summary { ...contentProps } } """, needs: [authorProps, contentProps, assetProps] ) static let userDetails = Fragments( """ fragment userDetails on User { id username name formattedShortBio location badges externalLinksList { url text icon } # isCommunity userStats { totalViewsCount postsCount lovesCount followersCount followingCount } currentUserState { relationshipPriority } settings { hasCommentingEnabled hasLovesEnabled hasRepostingEnabled hasSharingEnabled isCollaborateable isHireable } avatar { ...tshirtProps } coverImage { ...responsiveProps } categoryUsers(roles: [CURATOR, FEATURED, MODERATOR]) { id category { ...categoryProps } createdAt updatedAt role } } """, needs: [tshirtProps, responsiveProps, categoryProps] ) //| //| REQUEST BODIES //| static let categoriesBody = Fragments( """ id name slug description order allowInOnboarding isCreatorType level tileImage { ...tshirtProps } """, needs: [tshirtProps] ) static let categoryAdminsBody = Fragments( """ categoryUsers(roles: [CURATOR, MODERATOR]) { role user { ...authorProps } } """, needs: [authorProps] ) static let pageHeaderBody = Fragments( """ id postToken category { id } kind header subheader image { ...responsiveProps } ctaLink { text url } user { ...pageHeaderUserProps } """, needs: [responsiveProps, pageHeaderUserProps] ) static let postStreamBody = Fragments( """ next isLastPage posts { ...postDetails } """, needs: [postDetails] ) static let commentStreamBody = Fragments( """ next isLastPage comments { ...commentDetails } """, needs: [commentDetails] ) static let postBody = Fragments( """ ...postDetails """, needs: [postDetails] ) static let userBody = Fragments( """ ...userDetails """, needs: [userDetails] ) static let loveStreamBody = Fragments( """ next isLastPage loves { ...loveDetails } """, needs: [loveDetails] ) let string: String let needs: [Fragments] var dependencies: [Fragments] { return (needs + needs.flatMap { $0.dependencies }).unique() } init(_ string: String, needs: [Fragments] = []) { self.string = string self.needs = needs } static func == (lhs: Fragments, rhs: Fragments) -> Bool { return lhs.string == rhs.string } }
mit
861e7a2d9e47b2e86e2ed625997bdaa5
23.653595
96
0.503844
5.294035
false
false
false
false
ayshrimali/Appium-UIAutomation
testProjects/iOS/Appium-UIAutomation/Appium-UIAutomation/RegisterViewController.swift
1
2290
// // RegisterViewController.swift // Appium-UIAutomation // // Created by Anjum Shrimali on 4/5/17. // Copyright © 2017 IshiSystems. All rights reserved. // import Foundation import UIKit class RegisterViewController: UIViewController { @IBOutlet weak var txtDisplayName: UITextField! @IBOutlet weak var txtUsername: UITextField! @IBOutlet weak var txtPassword: UITextField! @IBOutlet weak var btnRegister: UIButton! @IBOutlet weak var btnLogin: UIButton! override func viewDidLoad() { super.viewDidLoad() } func validate() -> String? { let trimDisplayName: String? = self.txtDisplayName.text?.trimmingCharacters(in: CharacterSet(charactersIn: " ")) guard (trimDisplayName?.lengthOfBytes(using: .utf8))! > 0 else { return "Please enter display name" } let trimUsername: String? = self.txtUsername.text?.trimmingCharacters(in: CharacterSet(charactersIn: " ")) guard (trimUsername?.lengthOfBytes(using: .utf8))! > 0 else { return "Please enter username" } let trimPass: String? = self.txtPassword.text?.trimmingCharacters(in: CharacterSet(charactersIn: " ")) guard (trimPass?.lengthOfBytes(using: .utf8))! > 0 else { return "Please enter password" } return nil } @IBAction func btnRegisterPressed(_ sender: UIButton) { txtDisplayName.resignFirstResponder() txtUsername.resignFirstResponder() txtPassword.resignFirstResponder() let errorMessage = self.validate() if errorMessage == nil { Utility.shared.register(displayName: txtDisplayName.text!, username: txtUsername.text!, password: txtPassword.text!) AlertUtility.showAlert(title: "", message: "Registered successfully", presentOn: self, handler: {(action:UIAlertAction) -> Void in self.navigationController!.popViewController(animated: true) }) } else { AlertUtility.showAlert(title: "", message: errorMessage, presentOn: self) } } @IBAction func btnLoginPressed(_ sender: UIButton) { self.navigationController!.popViewController(animated: true) } }
apache-2.0
457fa6ca55351e3c46db6b860a0f24fe
34.215385
142
0.647007
4.943844
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/CodeStar/CodeStar_Shapes.swift
1
57752
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension CodeStar { // MARK: Enums // MARK: Shapes public struct AssociateTeamMemberRequest: AWSEncodableShape { /// A user- or system-generated token that identifies the entity that requested the team member association to the project. This token can be used to repeat the request. public let clientRequestToken: String? /// The ID of the project to which you will add the IAM user. public let projectId: String /// The AWS CodeStar project role that will apply to this user. This role determines what actions a user can take in an AWS CodeStar project. public let projectRole: String /// Whether the team member is allowed to use an SSH public/private key pair to remotely access project resources, for example Amazon EC2 instances. public let remoteAccessAllowed: Bool? /// The Amazon Resource Name (ARN) for the IAM user you want to add to the AWS CodeStar project. public let userArn: String public init(clientRequestToken: String? = nil, projectId: String, projectRole: String, remoteAccessAllowed: Bool? = nil, userArn: String) { self.clientRequestToken = clientRequestToken self.projectId = projectId self.projectRole = projectRole self.remoteAccessAllowed = remoteAccessAllowed self.userArn = userArn } public func validate(name: String) throws { try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 256) try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 1) try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, pattern: "^[\\w:/-]+$") try self.validate(self.projectId, name: "projectId", parent: name, max: 15) try self.validate(self.projectId, name: "projectId", parent: name, min: 2) try self.validate(self.projectId, name: "projectId", parent: name, pattern: "^[a-z][a-z0-9-]+$") try self.validate(self.projectRole, name: "projectRole", parent: name, pattern: "^(Owner|Viewer|Contributor)$") try self.validate(self.userArn, name: "userArn", parent: name, max: 95) try self.validate(self.userArn, name: "userArn", parent: name, min: 32) try self.validate(self.userArn, name: "userArn", parent: name, pattern: "^arn:aws:iam::\\d{12}:user(?:(\\u002F)|(\\u002F[\\u0021-\\u007E]+\\u002F))[\\w+=,.@-]+$") } private enum CodingKeys: String, CodingKey { case clientRequestToken case projectId case projectRole case remoteAccessAllowed case userArn } } public struct AssociateTeamMemberResult: AWSDecodableShape { /// The user- or system-generated token from the initial request that can be used to repeat the request. public let clientRequestToken: String? public init(clientRequestToken: String? = nil) { self.clientRequestToken = clientRequestToken } private enum CodingKeys: String, CodingKey { case clientRequestToken } } public struct Code: AWSEncodableShape { /// The repository to be created in AWS CodeStar. Valid values are AWS CodeCommit or GitHub. After AWS CodeStar provisions the new repository, the source code files provided with the project request are placed in the repository. public let destination: CodeDestination /// The location where the source code files provided with the project request are stored. AWS CodeStar retrieves the files during project creation. public let source: CodeSource public init(destination: CodeDestination, source: CodeSource) { self.destination = destination self.source = source } public func validate(name: String) throws { try self.destination.validate(name: "\(name).destination") try self.source.validate(name: "\(name).source") } private enum CodingKeys: String, CodingKey { case destination case source } } public struct CodeCommitCodeDestination: AWSEncodableShape { /// The name of the AWS CodeCommit repository to be created in AWS CodeStar. public let name: String public init(name: String) { self.name = name } public func validate(name: String) throws { try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^\\S[\\w.-]*$") } private enum CodingKeys: String, CodingKey { case name } } public struct CodeDestination: AWSEncodableShape { /// Information about the AWS CodeCommit repository to be created in AWS CodeStar. This is where the source code files provided with the project request will be uploaded after project creation. public let codeCommit: CodeCommitCodeDestination? /// Information about the GitHub repository to be created in AWS CodeStar. This is where the source code files provided with the project request will be uploaded after project creation. public let gitHub: GitHubCodeDestination? public init(codeCommit: CodeCommitCodeDestination? = nil, gitHub: GitHubCodeDestination? = nil) { self.codeCommit = codeCommit self.gitHub = gitHub } public func validate(name: String) throws { try self.codeCommit?.validate(name: "\(name).codeCommit") try self.gitHub?.validate(name: "\(name).gitHub") } private enum CodingKeys: String, CodingKey { case codeCommit case gitHub } } public struct CodeSource: AWSEncodableShape { /// Information about the Amazon S3 location where the source code files provided with the project request are stored. public let s3: S3Location public init(s3: S3Location) { self.s3 = s3 } public func validate(name: String) throws { try self.s3.validate(name: "\(name).s3") } private enum CodingKeys: String, CodingKey { case s3 } } public struct CreateProjectRequest: AWSEncodableShape { /// A user- or system-generated token that identifies the entity that requested project creation. This token can be used to repeat the request. public let clientRequestToken: String? /// The description of the project, if any. public let description: String? /// The ID of the project to be created in AWS CodeStar. public let id: String /// The display name for the project to be created in AWS CodeStar. public let name: String /// A list of the Code objects submitted with the project request. If this parameter is specified, the request must also include the toolchain parameter. public let sourceCode: [Code]? /// The tags created for the project. public let tags: [String: String]? /// The name of the toolchain template file submitted with the project request. If this parameter is specified, the request must also include the sourceCode parameter. public let toolchain: Toolchain? public init(clientRequestToken: String? = nil, description: String? = nil, id: String, name: String, sourceCode: [Code]? = nil, tags: [String: String]? = nil, toolchain: Toolchain? = nil) { self.clientRequestToken = clientRequestToken self.description = description self.id = id self.name = name self.sourceCode = sourceCode self.tags = tags self.toolchain = toolchain } public func validate(name: String) throws { try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 256) try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 1) try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, pattern: "^[\\w:/-]+$") try self.validate(self.description, name: "description", parent: name, max: 1024) try self.validate(self.description, name: "description", parent: name, pattern: "^$|^\\S(.*\\S)?$") try self.validate(self.id, name: "id", parent: name, max: 15) try self.validate(self.id, name: "id", parent: name, min: 2) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-z][a-z0-9-]+$") try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^\\S(.*\\S)?$") try self.sourceCode?.forEach { try $0.validate(name: "\(name).sourceCode[]") } try self.tags?.forEach { try validate($0.key, name: "tags.key", parent: name, max: 128) try validate($0.key, name: "tags.key", parent: name, min: 1) try validate($0.key, name: "tags.key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$") try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256) try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$") } try self.toolchain?.validate(name: "\(name).toolchain") } private enum CodingKeys: String, CodingKey { case clientRequestToken case description case id case name case sourceCode case tags case toolchain } } public struct CreateProjectResult: AWSDecodableShape { /// The Amazon Resource Name (ARN) of the created project. public let arn: String /// A user- or system-generated token that identifies the entity that requested project creation. public let clientRequestToken: String? /// The ID of the project. public let id: String /// Reserved for future use. public let projectTemplateId: String? public init(arn: String, clientRequestToken: String? = nil, id: String, projectTemplateId: String? = nil) { self.arn = arn self.clientRequestToken = clientRequestToken self.id = id self.projectTemplateId = projectTemplateId } private enum CodingKeys: String, CodingKey { case arn case clientRequestToken case id case projectTemplateId } } public struct CreateUserProfileRequest: AWSEncodableShape { /// The name that will be displayed as the friendly name for the user in AWS CodeStar. public let displayName: String /// The email address that will be displayed as part of the user's profile in AWS CodeStar. public let emailAddress: String /// The SSH public key associated with the user in AWS CodeStar. If a project owner allows the user remote access to project resources, this public key will be used along with the user's private key for SSH access. public let sshPublicKey: String? /// The Amazon Resource Name (ARN) of the user in IAM. public let userArn: String public init(displayName: String, emailAddress: String, sshPublicKey: String? = nil, userArn: String) { self.displayName = displayName self.emailAddress = emailAddress self.sshPublicKey = sshPublicKey self.userArn = userArn } public func validate(name: String) throws { try self.validate(self.displayName, name: "displayName", parent: name, max: 64) try self.validate(self.displayName, name: "displayName", parent: name, min: 1) try self.validate(self.displayName, name: "displayName", parent: name, pattern: "^\\S(.*\\S)?$") try self.validate(self.emailAddress, name: "emailAddress", parent: name, max: 128) try self.validate(self.emailAddress, name: "emailAddress", parent: name, min: 3) try self.validate(self.emailAddress, name: "emailAddress", parent: name, pattern: "^[\\w-.+]+@[\\w-.+]+$") try self.validate(self.sshPublicKey, name: "sshPublicKey", parent: name, max: 16384) try self.validate(self.sshPublicKey, name: "sshPublicKey", parent: name, pattern: "^[\\t\\r\\n\\u0020-\\u00FF]*$") try self.validate(self.userArn, name: "userArn", parent: name, max: 95) try self.validate(self.userArn, name: "userArn", parent: name, min: 32) try self.validate(self.userArn, name: "userArn", parent: name, pattern: "^arn:aws:iam::\\d{12}:user(?:(\\u002F)|(\\u002F[\\u0021-\\u007E]+\\u002F))[\\w+=,.@-]+$") } private enum CodingKeys: String, CodingKey { case displayName case emailAddress case sshPublicKey case userArn } } public struct CreateUserProfileResult: AWSDecodableShape { /// The date the user profile was created, in timestamp format. public let createdTimestamp: Date? /// The name that is displayed as the friendly name for the user in AWS CodeStar. public let displayName: String? /// The email address that is displayed as part of the user's profile in AWS CodeStar. public let emailAddress: String? /// The date the user profile was last modified, in timestamp format. public let lastModifiedTimestamp: Date? /// The SSH public key associated with the user in AWS CodeStar. This is the public portion of the public/private keypair the user can use to access project resources if a project owner allows the user remote access to those resources. public let sshPublicKey: String? /// The Amazon Resource Name (ARN) of the user in IAM. public let userArn: String public init(createdTimestamp: Date? = nil, displayName: String? = nil, emailAddress: String? = nil, lastModifiedTimestamp: Date? = nil, sshPublicKey: String? = nil, userArn: String) { self.createdTimestamp = createdTimestamp self.displayName = displayName self.emailAddress = emailAddress self.lastModifiedTimestamp = lastModifiedTimestamp self.sshPublicKey = sshPublicKey self.userArn = userArn } private enum CodingKeys: String, CodingKey { case createdTimestamp case displayName case emailAddress case lastModifiedTimestamp case sshPublicKey case userArn } } public struct DeleteProjectRequest: AWSEncodableShape { /// A user- or system-generated token that identifies the entity that requested project deletion. This token can be used to repeat the request. public let clientRequestToken: String? /// Whether to send a delete request for the primary stack in AWS CloudFormation originally used to generate the project and its resources. This option will delete all AWS resources for the project (except for any buckets in Amazon S3) as well as deleting the project itself. Recommended for most use cases. public let deleteStack: Bool? /// The ID of the project to be deleted in AWS CodeStar. public let id: String public init(clientRequestToken: String? = nil, deleteStack: Bool? = nil, id: String) { self.clientRequestToken = clientRequestToken self.deleteStack = deleteStack self.id = id } public func validate(name: String) throws { try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 256) try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 1) try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, pattern: "^[\\w:/-]+$") try self.validate(self.id, name: "id", parent: name, max: 15) try self.validate(self.id, name: "id", parent: name, min: 2) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-z][a-z0-9-]+$") } private enum CodingKeys: String, CodingKey { case clientRequestToken case deleteStack case id } } public struct DeleteProjectResult: AWSDecodableShape { /// The Amazon Resource Name (ARN) of the deleted project. public let projectArn: String? /// The ID of the primary stack in AWS CloudFormation that will be deleted as part of deleting the project and its resources. public let stackId: String? public init(projectArn: String? = nil, stackId: String? = nil) { self.projectArn = projectArn self.stackId = stackId } private enum CodingKeys: String, CodingKey { case projectArn case stackId } } public struct DeleteUserProfileRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the user to delete from AWS CodeStar. public let userArn: String public init(userArn: String) { self.userArn = userArn } public func validate(name: String) throws { try self.validate(self.userArn, name: "userArn", parent: name, max: 95) try self.validate(self.userArn, name: "userArn", parent: name, min: 32) try self.validate(self.userArn, name: "userArn", parent: name, pattern: "^arn:aws:iam::\\d{12}:user(?:(\\u002F)|(\\u002F[\\u0021-\\u007E]+\\u002F))[\\w+=,.@-]+$") } private enum CodingKeys: String, CodingKey { case userArn } } public struct DeleteUserProfileResult: AWSDecodableShape { /// The Amazon Resource Name (ARN) of the user deleted from AWS CodeStar. public let userArn: String public init(userArn: String) { self.userArn = userArn } private enum CodingKeys: String, CodingKey { case userArn } } public struct DescribeProjectRequest: AWSEncodableShape { /// The ID of the project. public let id: String public init(id: String) { self.id = id } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 15) try self.validate(self.id, name: "id", parent: name, min: 2) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-z][a-z0-9-]+$") } private enum CodingKeys: String, CodingKey { case id } } public struct DescribeProjectResult: AWSDecodableShape { /// The Amazon Resource Name (ARN) for the project. public let arn: String? /// A user- or system-generated token that identifies the entity that requested project creation. public let clientRequestToken: String? /// The date and time the project was created, in timestamp format. public let createdTimeStamp: Date? /// The description of the project, if any. public let description: String? /// The ID of the project. public let id: String? /// The display name for the project. public let name: String? /// The ID for the AWS CodeStar project template used to create the project. public let projectTemplateId: String? /// The ID of the primary stack in AWS CloudFormation used to generate resources for the project. public let stackId: String? /// The project creation or deletion status. public let status: ProjectStatus? public init(arn: String? = nil, clientRequestToken: String? = nil, createdTimeStamp: Date? = nil, description: String? = nil, id: String? = nil, name: String? = nil, projectTemplateId: String? = nil, stackId: String? = nil, status: ProjectStatus? = nil) { self.arn = arn self.clientRequestToken = clientRequestToken self.createdTimeStamp = createdTimeStamp self.description = description self.id = id self.name = name self.projectTemplateId = projectTemplateId self.stackId = stackId self.status = status } private enum CodingKeys: String, CodingKey { case arn case clientRequestToken case createdTimeStamp case description case id case name case projectTemplateId case stackId case status } } public struct DescribeUserProfileRequest: AWSEncodableShape { /// The Amazon Resource Name (ARN) of the user. public let userArn: String public init(userArn: String) { self.userArn = userArn } public func validate(name: String) throws { try self.validate(self.userArn, name: "userArn", parent: name, max: 95) try self.validate(self.userArn, name: "userArn", parent: name, min: 32) try self.validate(self.userArn, name: "userArn", parent: name, pattern: "^arn:aws:iam::\\d{12}:user(?:(\\u002F)|(\\u002F[\\u0021-\\u007E]+\\u002F))[\\w+=,.@-]+$") } private enum CodingKeys: String, CodingKey { case userArn } } public struct DescribeUserProfileResult: AWSDecodableShape { /// The date and time when the user profile was created in AWS CodeStar, in timestamp format. public let createdTimestamp: Date /// The display name shown for the user in AWS CodeStar projects. For example, this could be set to both first and last name ("Mary Major") or a single name ("Mary"). The display name is also used to generate the initial icon associated with the user in AWS CodeStar projects. If spaces are included in the display name, the first character that appears after the space will be used as the second character in the user initial icon. The initial icon displays a maximum of two characters, so a display name with more than one space (for example "Mary Jane Major") would generate an initial icon using the first character and the first character after the space ("MJ", not "MM"). public let displayName: String? /// The email address for the user. Optional. public let emailAddress: String? /// The date and time when the user profile was last modified, in timestamp format. public let lastModifiedTimestamp: Date /// The SSH public key associated with the user. This SSH public key is associated with the user profile, and can be used in conjunction with the associated private key for access to project resources, such as Amazon EC2 instances, if a project owner grants remote access to those resources. public let sshPublicKey: String? /// The Amazon Resource Name (ARN) of the user. public let userArn: String public init(createdTimestamp: Date, displayName: String? = nil, emailAddress: String? = nil, lastModifiedTimestamp: Date, sshPublicKey: String? = nil, userArn: String) { self.createdTimestamp = createdTimestamp self.displayName = displayName self.emailAddress = emailAddress self.lastModifiedTimestamp = lastModifiedTimestamp self.sshPublicKey = sshPublicKey self.userArn = userArn } private enum CodingKeys: String, CodingKey { case createdTimestamp case displayName case emailAddress case lastModifiedTimestamp case sshPublicKey case userArn } } public struct DisassociateTeamMemberRequest: AWSEncodableShape { /// The ID of the AWS CodeStar project from which you want to remove a team member. public let projectId: String /// The Amazon Resource Name (ARN) of the IAM user or group whom you want to remove from the project. public let userArn: String public init(projectId: String, userArn: String) { self.projectId = projectId self.userArn = userArn } public func validate(name: String) throws { try self.validate(self.projectId, name: "projectId", parent: name, max: 15) try self.validate(self.projectId, name: "projectId", parent: name, min: 2) try self.validate(self.projectId, name: "projectId", parent: name, pattern: "^[a-z][a-z0-9-]+$") try self.validate(self.userArn, name: "userArn", parent: name, max: 95) try self.validate(self.userArn, name: "userArn", parent: name, min: 32) try self.validate(self.userArn, name: "userArn", parent: name, pattern: "^arn:aws:iam::\\d{12}:user(?:(\\u002F)|(\\u002F[\\u0021-\\u007E]+\\u002F))[\\w+=,.@-]+$") } private enum CodingKeys: String, CodingKey { case projectId case userArn } } public struct DisassociateTeamMemberResult: AWSDecodableShape { public init() {} } public struct GitHubCodeDestination: AWSEncodableShape { /// Description for the GitHub repository to be created in AWS CodeStar. This description displays in GitHub after the repository is created. public let description: String? /// Whether to enable issues for the GitHub repository. public let issuesEnabled: Bool /// Name of the GitHub repository to be created in AWS CodeStar. public let name: String /// The GitHub username for the owner of the GitHub repository to be created in AWS CodeStar. If this repository should be owned by a GitHub organization, provide its name. public let owner: String /// Whether the GitHub repository is to be a private repository. public let privateRepository: Bool /// The GitHub user's personal access token for the GitHub repository. public let token: String /// The type of GitHub repository to be created in AWS CodeStar. Valid values are User or Organization. public let type: String public init(description: String? = nil, issuesEnabled: Bool, name: String, owner: String, privateRepository: Bool, token: String, type: String) { self.description = description self.issuesEnabled = issuesEnabled self.name = name self.owner = owner self.privateRepository = privateRepository self.token = token self.type = type } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 1000) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.description, name: "description", parent: name, pattern: "^\\S(.*\\S)?$") try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^\\S[\\w.-]*$") try self.validate(self.owner, name: "owner", parent: name, max: 100) try self.validate(self.owner, name: "owner", parent: name, min: 1) try self.validate(self.owner, name: "owner", parent: name, pattern: "^\\S(.*\\S)?$") try self.validate(self.token, name: "token", parent: name, min: 1) try self.validate(self.type, name: "type", parent: name, pattern: "^(user|organization|User|Organization)$") } private enum CodingKeys: String, CodingKey { case description case issuesEnabled case name case owner case privateRepository case token case type } } public struct ListProjectsRequest: AWSEncodableShape { /// The maximum amount of data that can be contained in a single set of results. public let maxResults: Int? /// The continuation token to be used to return the next set of results, if the results cannot be returned in one response. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 512) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$") } private enum CodingKeys: String, CodingKey { case maxResults case nextToken } } public struct ListProjectsResult: AWSDecodableShape { /// The continuation token to use when requesting the next set of results, if there are more results to be returned. public let nextToken: String? /// A list of projects. public let projects: [ProjectSummary] public init(nextToken: String? = nil, projects: [ProjectSummary]) { self.nextToken = nextToken self.projects = projects } private enum CodingKeys: String, CodingKey { case nextToken case projects } } public struct ListResourcesRequest: AWSEncodableShape { /// The maximum amount of data that can be contained in a single set of results. public let maxResults: Int? /// The continuation token for the next set of results, if the results cannot be returned in one response. public let nextToken: String? /// The ID of the project. public let projectId: String public init(maxResults: Int? = nil, nextToken: String? = nil, projectId: String) { self.maxResults = maxResults self.nextToken = nextToken self.projectId = projectId } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 512) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$") try self.validate(self.projectId, name: "projectId", parent: name, max: 15) try self.validate(self.projectId, name: "projectId", parent: name, min: 2) try self.validate(self.projectId, name: "projectId", parent: name, pattern: "^[a-z][a-z0-9-]+$") } private enum CodingKeys: String, CodingKey { case maxResults case nextToken case projectId } } public struct ListResourcesResult: AWSDecodableShape { /// The continuation token to use when requesting the next set of results, if there are more results to be returned. public let nextToken: String? /// An array of resources associated with the project. public let resources: [Resource]? public init(nextToken: String? = nil, resources: [Resource]? = nil) { self.nextToken = nextToken self.resources = resources } private enum CodingKeys: String, CodingKey { case nextToken case resources } } public struct ListTagsForProjectRequest: AWSEncodableShape { /// The ID of the project to get tags for. public let id: String /// Reserved for future use. public let maxResults: Int? /// Reserved for future use. public let nextToken: String? public init(id: String, maxResults: Int? = nil, nextToken: String? = nil) { self.id = id self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 15) try self.validate(self.id, name: "id", parent: name, min: 2) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-z][a-z0-9-]+$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 512) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$") } private enum CodingKeys: String, CodingKey { case id case maxResults case nextToken } } public struct ListTagsForProjectResult: AWSDecodableShape { /// Reserved for future use. public let nextToken: String? /// The tags for the project. public let tags: [String: String]? public init(nextToken: String? = nil, tags: [String: String]? = nil) { self.nextToken = nextToken self.tags = tags } private enum CodingKeys: String, CodingKey { case nextToken case tags } } public struct ListTeamMembersRequest: AWSEncodableShape { /// The maximum number of team members you want returned in a response. public let maxResults: Int? /// The continuation token for the next set of results, if the results cannot be returned in one response. public let nextToken: String? /// The ID of the project for which you want to list team members. public let projectId: String public init(maxResults: Int? = nil, nextToken: String? = nil, projectId: String) { self.maxResults = maxResults self.nextToken = nextToken self.projectId = projectId } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 512) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$") try self.validate(self.projectId, name: "projectId", parent: name, max: 15) try self.validate(self.projectId, name: "projectId", parent: name, min: 2) try self.validate(self.projectId, name: "projectId", parent: name, pattern: "^[a-z][a-z0-9-]+$") } private enum CodingKeys: String, CodingKey { case maxResults case nextToken case projectId } } public struct ListTeamMembersResult: AWSDecodableShape { /// The continuation token to use when requesting the next set of results, if there are more results to be returned. public let nextToken: String? /// A list of team member objects for the project. public let teamMembers: [TeamMember] public init(nextToken: String? = nil, teamMembers: [TeamMember]) { self.nextToken = nextToken self.teamMembers = teamMembers } private enum CodingKeys: String, CodingKey { case nextToken case teamMembers } } public struct ListUserProfilesRequest: AWSEncodableShape { /// The maximum number of results to return in a response. public let maxResults: Int? /// The continuation token for the next set of results, if the results cannot be returned in one response. public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 512) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$") } private enum CodingKeys: String, CodingKey { case maxResults case nextToken } } public struct ListUserProfilesResult: AWSDecodableShape { /// The continuation token to use when requesting the next set of results, if there are more results to be returned. public let nextToken: String? /// All the user profiles configured in AWS CodeStar for an AWS account. public let userProfiles: [UserProfileSummary] public init(nextToken: String? = nil, userProfiles: [UserProfileSummary]) { self.nextToken = nextToken self.userProfiles = userProfiles } private enum CodingKeys: String, CodingKey { case nextToken case userProfiles } } public struct ProjectStatus: AWSDecodableShape { /// In the case of a project creation or deletion failure, a reason for the failure. public let reason: String? /// The phase of completion for a project creation or deletion. public let state: String public init(reason: String? = nil, state: String) { self.reason = reason self.state = state } private enum CodingKeys: String, CodingKey { case reason case state } } public struct ProjectSummary: AWSDecodableShape { /// The Amazon Resource Name (ARN) of the project. public let projectArn: String? /// The ID of the project. public let projectId: String? public init(projectArn: String? = nil, projectId: String? = nil) { self.projectArn = projectArn self.projectId = projectId } private enum CodingKeys: String, CodingKey { case projectArn case projectId } } public struct Resource: AWSDecodableShape { /// The Amazon Resource Name (ARN) of the resource. public let id: String public init(id: String) { self.id = id } private enum CodingKeys: String, CodingKey { case id } } public struct S3Location: AWSEncodableShape { /// The Amazon S3 object key where the source code files provided with the project request are stored. public let bucketKey: String? /// The Amazon S3 bucket name where the source code files provided with the project request are stored. public let bucketName: String? public init(bucketKey: String? = nil, bucketName: String? = nil) { self.bucketKey = bucketKey self.bucketName = bucketName } public func validate(name: String) throws { try self.validate(self.bucketName, name: "bucketName", parent: name, max: 63) try self.validate(self.bucketName, name: "bucketName", parent: name, min: 3) } private enum CodingKeys: String, CodingKey { case bucketKey case bucketName } } public struct TagProjectRequest: AWSEncodableShape { /// The ID of the project you want to add a tag to. public let id: String /// The tags you want to add to the project. public let tags: [String: String] public init(id: String, tags: [String: String]) { self.id = id self.tags = tags } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 15) try self.validate(self.id, name: "id", parent: name, min: 2) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-z][a-z0-9-]+$") try self.tags.forEach { try validate($0.key, name: "tags.key", parent: name, max: 128) try validate($0.key, name: "tags.key", parent: name, min: 1) try validate($0.key, name: "tags.key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$") try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256) try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$") } } private enum CodingKeys: String, CodingKey { case id case tags } } public struct TagProjectResult: AWSDecodableShape { /// The tags for the project. public let tags: [String: String]? public init(tags: [String: String]? = nil) { self.tags = tags } private enum CodingKeys: String, CodingKey { case tags } } public struct TeamMember: AWSDecodableShape { /// The role assigned to the user in the project. Project roles have different levels of access. For more information, see Working with Teams in the AWS CodeStar User Guide. public let projectRole: String /// Whether the user is allowed to remotely access project resources using an SSH public/private key pair. public let remoteAccessAllowed: Bool? /// The Amazon Resource Name (ARN) of the user in IAM. public let userArn: String public init(projectRole: String, remoteAccessAllowed: Bool? = nil, userArn: String) { self.projectRole = projectRole self.remoteAccessAllowed = remoteAccessAllowed self.userArn = userArn } private enum CodingKeys: String, CodingKey { case projectRole case remoteAccessAllowed case userArn } } public struct Toolchain: AWSEncodableShape { /// The service role ARN for AWS CodeStar to use for the toolchain template during stack provisioning. public let roleArn: String? /// The Amazon S3 location where the toolchain template file provided with the project request is stored. AWS CodeStar retrieves the file during project creation. public let source: ToolchainSource /// The list of parameter overrides to be passed into the toolchain template during stack provisioning, if any. public let stackParameters: [String: String]? public init(roleArn: String? = nil, source: ToolchainSource, stackParameters: [String: String]? = nil) { self.roleArn = roleArn self.source = source self.stackParameters = stackParameters } public func validate(name: String) throws { try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1224) try self.validate(self.roleArn, name: "roleArn", parent: name, min: 1) try self.source.validate(name: "\(name).source") try self.stackParameters?.forEach { try validate($0.key, name: "stackParameters.key", parent: name, max: 30) try validate($0.key, name: "stackParameters.key", parent: name, min: 1) try validate($0.key, name: "stackParameters.key", parent: name, pattern: "^\\S(.*\\S)?$") try validate($0.value, name: "stackParameters[\"\($0.key)\"]", parent: name, max: 100) try validate($0.value, name: "stackParameters[\"\($0.key)\"]", parent: name, min: 1) try validate($0.value, name: "stackParameters[\"\($0.key)\"]", parent: name, pattern: "^\\S(.*\\S)?$") } } private enum CodingKeys: String, CodingKey { case roleArn case source case stackParameters } } public struct ToolchainSource: AWSEncodableShape { /// The Amazon S3 bucket where the toolchain template file provided with the project request is stored. public let s3: S3Location public init(s3: S3Location) { self.s3 = s3 } public func validate(name: String) throws { try self.s3.validate(name: "\(name).s3") } private enum CodingKeys: String, CodingKey { case s3 } } public struct UntagProjectRequest: AWSEncodableShape { /// The ID of the project to remove tags from. public let id: String /// The tags to remove from the project. public let tags: [String] public init(id: String, tags: [String]) { self.id = id self.tags = tags } public func validate(name: String) throws { try self.validate(self.id, name: "id", parent: name, max: 15) try self.validate(self.id, name: "id", parent: name, min: 2) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-z][a-z0-9-]+$") try self.tags.forEach { try validate($0, name: "tags[]", parent: name, max: 128) try validate($0, name: "tags[]", parent: name, min: 1) try validate($0, name: "tags[]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$") } } private enum CodingKeys: String, CodingKey { case id case tags } } public struct UntagProjectResult: AWSDecodableShape { public init() {} } public struct UpdateProjectRequest: AWSEncodableShape { /// The description of the project, if any. public let description: String? /// The ID of the project you want to update. public let id: String /// The name of the project you want to update. public let name: String? public init(description: String? = nil, id: String, name: String? = nil) { self.description = description self.id = id self.name = name } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 1024) try self.validate(self.description, name: "description", parent: name, pattern: "^$|^\\S(.*\\S)?$") try self.validate(self.id, name: "id", parent: name, max: 15) try self.validate(self.id, name: "id", parent: name, min: 2) try self.validate(self.id, name: "id", parent: name, pattern: "^[a-z][a-z0-9-]+$") try self.validate(self.name, name: "name", parent: name, max: 100) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^\\S(.*\\S)?$") } private enum CodingKeys: String, CodingKey { case description case id case name } } public struct UpdateProjectResult: AWSDecodableShape { public init() {} } public struct UpdateTeamMemberRequest: AWSEncodableShape { /// The ID of the project. public let projectId: String /// The role assigned to the user in the project. Project roles have different levels of access. For more information, see Working with Teams in the AWS CodeStar User Guide. public let projectRole: String? /// Whether a team member is allowed to remotely access project resources using the SSH public key associated with the user's profile. Even if this is set to True, the user must associate a public key with their profile before the user can access resources. public let remoteAccessAllowed: Bool? /// The Amazon Resource Name (ARN) of the user for whom you want to change team membership attributes. public let userArn: String public init(projectId: String, projectRole: String? = nil, remoteAccessAllowed: Bool? = nil, userArn: String) { self.projectId = projectId self.projectRole = projectRole self.remoteAccessAllowed = remoteAccessAllowed self.userArn = userArn } public func validate(name: String) throws { try self.validate(self.projectId, name: "projectId", parent: name, max: 15) try self.validate(self.projectId, name: "projectId", parent: name, min: 2) try self.validate(self.projectId, name: "projectId", parent: name, pattern: "^[a-z][a-z0-9-]+$") try self.validate(self.projectRole, name: "projectRole", parent: name, pattern: "^(Owner|Viewer|Contributor)$") try self.validate(self.userArn, name: "userArn", parent: name, max: 95) try self.validate(self.userArn, name: "userArn", parent: name, min: 32) try self.validate(self.userArn, name: "userArn", parent: name, pattern: "^arn:aws:iam::\\d{12}:user(?:(\\u002F)|(\\u002F[\\u0021-\\u007E]+\\u002F))[\\w+=,.@-]+$") } private enum CodingKeys: String, CodingKey { case projectId case projectRole case remoteAccessAllowed case userArn } } public struct UpdateTeamMemberResult: AWSDecodableShape { /// The project role granted to the user. public let projectRole: String? /// Whether a team member is allowed to remotely access project resources using the SSH public key associated with the user's profile. public let remoteAccessAllowed: Bool? /// The Amazon Resource Name (ARN) of the user whose team membership attributes were updated. public let userArn: String? public init(projectRole: String? = nil, remoteAccessAllowed: Bool? = nil, userArn: String? = nil) { self.projectRole = projectRole self.remoteAccessAllowed = remoteAccessAllowed self.userArn = userArn } private enum CodingKeys: String, CodingKey { case projectRole case remoteAccessAllowed case userArn } } public struct UpdateUserProfileRequest: AWSEncodableShape { /// The name that is displayed as the friendly name for the user in AWS CodeStar. public let displayName: String? /// The email address that is displayed as part of the user's profile in AWS CodeStar. public let emailAddress: String? /// The SSH public key associated with the user in AWS CodeStar. If a project owner allows the user remote access to project resources, this public key will be used along with the user's private key for SSH access. public let sshPublicKey: String? /// The name that will be displayed as the friendly name for the user in AWS CodeStar. public let userArn: String public init(displayName: String? = nil, emailAddress: String? = nil, sshPublicKey: String? = nil, userArn: String) { self.displayName = displayName self.emailAddress = emailAddress self.sshPublicKey = sshPublicKey self.userArn = userArn } public func validate(name: String) throws { try self.validate(self.displayName, name: "displayName", parent: name, max: 64) try self.validate(self.displayName, name: "displayName", parent: name, min: 1) try self.validate(self.displayName, name: "displayName", parent: name, pattern: "^\\S(.*\\S)?$") try self.validate(self.emailAddress, name: "emailAddress", parent: name, max: 128) try self.validate(self.emailAddress, name: "emailAddress", parent: name, min: 3) try self.validate(self.emailAddress, name: "emailAddress", parent: name, pattern: "^[\\w-.+]+@[\\w-.+]+$") try self.validate(self.sshPublicKey, name: "sshPublicKey", parent: name, max: 16384) try self.validate(self.sshPublicKey, name: "sshPublicKey", parent: name, pattern: "^[\\t\\r\\n\\u0020-\\u00FF]*$") try self.validate(self.userArn, name: "userArn", parent: name, max: 95) try self.validate(self.userArn, name: "userArn", parent: name, min: 32) try self.validate(self.userArn, name: "userArn", parent: name, pattern: "^arn:aws:iam::\\d{12}:user(?:(\\u002F)|(\\u002F[\\u0021-\\u007E]+\\u002F))[\\w+=,.@-]+$") } private enum CodingKeys: String, CodingKey { case displayName case emailAddress case sshPublicKey case userArn } } public struct UpdateUserProfileResult: AWSDecodableShape { /// The date the user profile was created, in timestamp format. public let createdTimestamp: Date? /// The name that is displayed as the friendly name for the user in AWS CodeStar. public let displayName: String? /// The email address that is displayed as part of the user's profile in AWS CodeStar. public let emailAddress: String? /// The date the user profile was last modified, in timestamp format. public let lastModifiedTimestamp: Date? /// The SSH public key associated with the user in AWS CodeStar. This is the public portion of the public/private keypair the user can use to access project resources if a project owner allows the user remote access to those resources. public let sshPublicKey: String? /// The Amazon Resource Name (ARN) of the user in IAM. public let userArn: String public init(createdTimestamp: Date? = nil, displayName: String? = nil, emailAddress: String? = nil, lastModifiedTimestamp: Date? = nil, sshPublicKey: String? = nil, userArn: String) { self.createdTimestamp = createdTimestamp self.displayName = displayName self.emailAddress = emailAddress self.lastModifiedTimestamp = lastModifiedTimestamp self.sshPublicKey = sshPublicKey self.userArn = userArn } private enum CodingKeys: String, CodingKey { case createdTimestamp case displayName case emailAddress case lastModifiedTimestamp case sshPublicKey case userArn } } public struct UserProfileSummary: AWSDecodableShape { /// The display name of a user in AWS CodeStar. For example, this could be set to both first and last name ("Mary Major") or a single name ("Mary"). The display name is also used to generate the initial icon associated with the user in AWS CodeStar projects. If spaces are included in the display name, the first character that appears after the space will be used as the second character in the user initial icon. The initial icon displays a maximum of two characters, so a display name with more than one space (for example "Mary Jane Major") would generate an initial icon using the first character and the first character after the space ("MJ", not "MM"). public let displayName: String? /// The email address associated with the user. public let emailAddress: String? /// The SSH public key associated with the user in AWS CodeStar. If a project owner allows the user remote access to project resources, this public key will be used along with the user's private key for SSH access. public let sshPublicKey: String? /// The Amazon Resource Name (ARN) of the user in IAM. public let userArn: String? public init(displayName: String? = nil, emailAddress: String? = nil, sshPublicKey: String? = nil, userArn: String? = nil) { self.displayName = displayName self.emailAddress = emailAddress self.sshPublicKey = sshPublicKey self.userArn = userArn } private enum CodingKeys: String, CodingKey { case displayName case emailAddress case sshPublicKey case userArn } } }
apache-2.0
bfd5d5ed20afe0d611a02023decb056d
45.914703
685
0.622039
4.702549
false
false
false
false
DaiYue/HAMLeetcodeSwiftSolutions
solutions/2_Add_Two_Numbers.playground/Contents.swift
1
1848
// #2 Add Two Numbers https://leetcode.com/problems/add-two-numbers/ // 简单的单链表处理。考虑几种情况:1. 两个数位数相等,且最高位不需进位 2. 两个数位数相等,且最高位需要进位 3. 两个数位数不相等 // 有些算法会在结果的头部先创建一个 dummy,val 任意,真正的头结点直接往 dummy 后面插。最后返回 dummy -> next // 时间复杂度:O(n) 空间复杂度:O(1) public class ListNode { public var val: Int public var next: ListNode? public init(_ val: Int) { self.val = val self.next = nil } } class Solution { func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { if l1 == nil { return l2 } if l2 == nil { return l1 } var l1Tail:ListNode? = l1 var l2Tail:ListNode? = l2 var head:ListNode? = nil var tail:ListNode? = nil var carry = 0 while l1Tail != nil || l2Tail != nil { let sum = (l1Tail?.val ?? 0) + (l2Tail?.val ?? 0) + carry carry = sum / 10 let val = sum % 10 let node = ListNode(val) if head == nil { head = node } else { tail!.next = node } tail = node l1Tail = l1Tail?.next l2Tail = l2Tail?.next } if carry != 0 { tail?.next = ListNode(carry) } return head; } } let n1 = ListNode(2) let n2 = ListNode(4) n1.next = n2 let n3 = ListNode(9) n2.next = n3 let n4 = ListNode(5) let n5 = ListNode(6) n4.next = n5 let n6 = ListNode(4) n5.next = n6 let solution = Solution(); let nr = solution.addTwoNumbers(n1, n4)
mit
f9d55b68189f003d205d21f8e5434adb
21.75
71
0.493895
3.243564
false
false
false
false
4faramita/TweeBox
TweeBox/UserParams.swift
1
909
// // UserParams.swift // TweeBox // // Created by 4faramita on 2017/8/20. // Copyright © 2017年 4faramita. All rights reserved. // import Foundation class UserParams: ParamsProtocol { public var userID: String? public var screenName: String? public var includeEntities = true init(userID: String?, screenName: String?) { self.userID = userID self.screenName = screenName } public func getParams() -> [String: Any] { var params = [String: String]() guard (userID != nil || screenName != nil) else { return params } if userID != nil { params["user_id"] = userID } else { params["screen_name"] = screenName } params["include_entities"] = includeEntities.description return params } }
mit
0847576f3011ca8bbe811b7563389af8
20.069767
64
0.540839
4.575758
false
false
false
false
festrs/DotaComp
DotaComp/LiveGamesTableViewCell.swift
1
1281
// // EventSoonTableViewCell.swift // DotaComp // // Created by Felipe Dias Pereira on 2016-10-27. // Copyright © 2016 Felipe Dias Pereira. All rights reserved. // import UIKit class LiveGamesTableViewCell: UITableViewCell { @IBOutlet weak var team1Label: UILabel! @IBOutlet weak var team2Label: UILabel! @IBOutlet weak var bestOfLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var backView: UIView! override func awakeFromNib() { super.awakeFromNib() backView.layer.cornerRadius = 8 backView.layer.masksToBounds = true } func setUpCell(liveGame: Game) { let direTeam = liveGame.direTeam?.teamName.map { $0 } ?? "" let radiantTeam = liveGame.radiantTeam?.teamName.map { $0 } ?? "" team1Label.text = radiantTeam team2Label.text = direTeam timeLabel.text = "LIVE" bestOfLabel.text = getSeriesType(seriesType: liveGame.seriesType!) } func getSeriesType(seriesType: Int) -> String { switch seriesType { case 0: return "Best of 1" case 1: return "Best of 3" case 2: return "Best of 5" default: return "" } } }
mit
1fa2ab45495accbf876a62525a293aed
25.122449
74
0.603906
4.183007
false
false
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
Example/Pods/ZIPFoundation/Sources/ZIPFoundation/Archive+Reading.swift
1
7391
// // Archive+Reading.swift // ZIPFoundation // // Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation extension Archive { /// Read a ZIP `Entry` from the receiver and write it to `url`. /// /// - Parameters: /// - entry: The ZIP `Entry` to read. /// - url: The destination file URL. /// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed). /// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance. /// - progress: A progress object that can be used to track or cancel the extract operation. /// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`. /// - Throws: An error if the destination file cannot be written or the entry contains malformed content. public func extract(_ entry: Entry, to url: URL, bufferSize: UInt32 = defaultReadChunkSize, skipCRC32: Bool = false, progress: Progress? = nil) throws -> CRC32 { let fileManager = FileManager() var checksum = CRC32(0) switch entry.type { case .file: guard !fileManager.itemExists(at: url) else { throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path]) } try fileManager.createParentDirectoryStructure(for: url) let destinationRepresentation = fileManager.fileSystemRepresentation(withPath: url.path) guard let destinationFile: UnsafeMutablePointer<FILE> = fopen(destinationRepresentation, "wb+") else { throw CocoaError(.fileNoSuchFile) } defer { fclose(destinationFile) } let consumer = { _ = try Data.write(chunk: $0, to: destinationFile) } checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, consumer: consumer) case .directory: let consumer = { (_: Data) in try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, consumer: consumer) case .symlink: guard !fileManager.itemExists(at: url) else { throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: url.path]) } let consumer = { (data: Data) in guard let linkPath = String(data: data, encoding: .utf8) else { throw ArchiveError.invalidEntryPath } try fileManager.createParentDirectoryStructure(for: url) try fileManager.createSymbolicLink(atPath: url.path, withDestinationPath: linkPath) } checksum = try self.extract(entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, consumer: consumer) } let attributes = FileManager.attributes(from: entry) try fileManager.setAttributes(attributes, ofItemAtPath: url.path) return checksum } /// Read a ZIP `Entry` from the receiver and forward its contents to a `Consumer` closure. /// /// - Parameters: /// - entry: The ZIP `Entry` to read. /// - bufferSize: The maximum size of the read buffer and the decompression buffer (if needed). /// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance. /// - progress: A progress object that can be used to track or cancel the extract operation. /// - consumer: A closure that consumes contents of `Entry` as `Data` chunks. /// - Returns: The checksum of the processed content or 0 if the `skipCRC32` flag was set to `true`.. /// - Throws: An error if the destination file cannot be written or the entry contains malformed content. public func extract(_ entry: Entry, bufferSize: UInt32 = defaultReadChunkSize, skipCRC32: Bool = false, progress: Progress? = nil, consumer: Consumer) throws -> CRC32 { var checksum = CRC32(0) let localFileHeader = entry.localFileHeader fseek(self.archiveFile, entry.dataOffset, SEEK_SET) progress?.totalUnitCount = self.totalUnitCountForReading(entry) switch entry.type { case .file: guard let compressionMethod = CompressionMethod(rawValue: localFileHeader.compressionMethod) else { throw ArchiveError.invalidCompressionMethod } switch compressionMethod { case .none: checksum = try self.readUncompressed(entry: entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, with: consumer) case .deflate: checksum = try self.readCompressed(entry: entry, bufferSize: bufferSize, skipCRC32: skipCRC32, progress: progress, with: consumer) } case .directory: try consumer(Data()) progress?.completedUnitCount = self.totalUnitCountForReading(entry) case .symlink: let localFileHeader = entry.localFileHeader let size = Int(localFileHeader.compressedSize) let data = try Data.readChunk(of: size, from: self.archiveFile) checksum = data.crc32(checksum: 0) try consumer(data) progress?.completedUnitCount = self.totalUnitCountForReading(entry) } return checksum } // MARK: - Helpers private func readUncompressed(entry: Entry, bufferSize: UInt32, skipCRC32: Bool, progress: Progress? = nil, with consumer: Consumer) throws -> CRC32 { let size = Int(entry.centralDirectoryStructure.uncompressedSize) return try Data.consumePart(of: size, chunkSize: Int(bufferSize), skipCRC32: skipCRC32, provider: { (_, chunkSize) -> Data in return try Data.readChunk(of: Int(chunkSize), from: self.archiveFile) }, consumer: { (data) in if progress?.isCancelled == true { throw ArchiveError.cancelledOperation } try consumer(data) progress?.completedUnitCount += Int64(data.count) }) } private func readCompressed(entry: Entry, bufferSize: UInt32, skipCRC32: Bool, progress: Progress? = nil, with consumer: Consumer) throws -> CRC32 { let size = Int(entry.centralDirectoryStructure.compressedSize) return try Data.decompress(size: size, bufferSize: Int(bufferSize), skipCRC32: skipCRC32, provider: { (_, chunkSize) -> Data in return try Data.readChunk(of: chunkSize, from: self.archiveFile) }, consumer: { (data) in if progress?.isCancelled == true { throw ArchiveError.cancelledOperation } try consumer(data) progress?.completedUnitCount += Int64(data.count) }) } }
bsd-3-clause
bab8e655d982bab35ab4ba58b5245cd1
54.56391
120
0.624628
4.907039
false
false
false
false
ta2yak/MaterialKit
Source/MKTableViewCell.swift
1
2390
// // MKTableViewCell.swift // MaterialKit // // Created by Le Van Nghia on 11/15/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit public class MKTableViewCell : UITableViewCell { @IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation { didSet { mkLayer.rippleLocation = rippleLocation } } @IBInspectable public var rippleAniDuration: Float = 0.75 @IBInspectable public var backgroundAniDuration: Float = 1.0 @IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear @IBInspectable public var shadowAniEnabled: Bool = true // color @IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) { didSet { mkLayer.setCircleLayerColor(rippleLayerColor) } } @IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) { didSet { mkLayer.setBackgroundLayerColor(backgroundLayerColor) } } private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.contentView.layer) private var contentViewResized = false override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayer() } private func setupLayer() { selectionStyle = .None mkLayer.setBackgroundLayerColor(backgroundLayerColor) mkLayer.setCircleLayerColor(rippleLayerColor) mkLayer.ripplePercent = 1.2 } override public func touchesBegan(touches: NSSet, withEvent event: UIEvent) { super.touchesBegan(touches, withEvent: event) if let firstTouch = touches.anyObject() as? UITouch { if !contentViewResized { mkLayer.superLayerDidResize() contentViewResized = true } mkLayer.didChangeTapLocation(firstTouch.locationInView(contentView)) mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(rippleAniDuration)) mkLayer.animateAlphaForBackgroundLayer(MKTimingFunction.Linear, duration: CFTimeInterval(backgroundAniDuration)) } } }
mit
9118b1e857b5e7e56e65b97418a6ae3b
34.671642
152
0.686611
5.161987
false
false
false
false
mikekavouras/Glowb-iOS
Glowb/Wizard/Models/DeviceConnection.swift
1
5556
// // SetupConnection.swift // ParticleConnect // // Created by Mike Kavouras on 8/29/16. // Copyright © 2016 Mike Kavouras. All rights reserved. // enum ResultType<Value, Err: Error> { case success(Value) case failure(Err) } enum ConnectionError: Error { case noSpaceAvailable case jsonParseError case couldNotConnect case timeout } protocol DeviceConnectionDelegate: class { func deviceConnection(connection: DeviceConnection, didReceiveData data: String) func deviceConnection(connection: DeviceConnection, didUpdateState state: DeviceConnectionState) } enum DeviceConnectionState { case opened case closed case openTimeout case error case unknown } class DeviceConnection: NSObject { var ipAddress: String = "" var port: Int = 0 var inputStream: InputStream? var outputStream: OutputStream? var timeoutTimer: Timer? var receivedDataBuffer = "" var streamState: (input: Bool, output: Bool) = (false, false) var isOpen: Bool { return (true, true) == streamState } weak var delegate: DeviceConnectionDelegate? // MARK: Life cycle init(withIPAddress ipAddress: String, port: Int) { self.ipAddress = ipAddress self.port = port super.init() initSocket() timeoutTimer = Timer(timeInterval: 5.0, target: self, selector: #selector(self.socketOpenTimeoutHandler(timer:)), userInfo: nil, repeats: false) RunLoop.current.add(timeoutTimer!, forMode: .commonModes) } deinit { close() } // should throw stream error if not inited private func initSocket() { Stream.getStreamsToHost(withName: ipAddress, port: port, inputStream: &inputStream, outputStream: &outputStream) guard let inputStream = inputStream, let outputStream = outputStream else { return } [inputStream, outputStream].forEach { stream in stream.delegate = self stream.schedule(in: RunLoop.current, forMode: .defaultRunLoopMode) } inputStream.open() outputStream.open() } @objc func socketOpenTimeoutHandler(timer: Timer) { timer.invalidate() delegate?.deviceConnection(connection: self, didUpdateState: .openTimeout) } func writeString(_ string: String) { guard isOpen, let buffer = string.data(using: .utf8, allowLossyConversion: true), let outputStream = outputStream else { delegate?.deviceConnection(connection: self, didUpdateState: .error) return } DispatchQueue.main.async { [unowned self] in if outputStream.hasSpaceAvailable { let _ = buffer.withUnsafeBytes { outputStream.write($0, maxLength: buffer.count) } } else { self.delegate?.deviceConnection(connection: self, didUpdateState: .error) } } } private func close() { timeoutTimer?.invalidate() outputStream?.remove(from: RunLoop.current, forMode: .defaultRunLoopMode) outputStream?.close() inputStream?.remove(from: RunLoop.current, forMode: .defaultRunLoopMode) inputStream?.close() } } // MARK: Stream delegate extension DeviceConnection: StreamDelegate { func stream(_ aStream: Stream, handle eventCode: Stream.Event) { if eventCode == .openCompleted { if aStream == inputStream { streamState = (true, streamState.output) } if aStream == outputStream { streamState = (streamState.input, true) } if case (true, true) = streamState { delegate?.deviceConnection(connection: self, didUpdateState: .opened) } return } if eventCode == .hasSpaceAvailable || eventCode == .hasBytesAvailable { guard let inputStream = inputStream else { return } if aStream == inputStream { var buffer = [UInt8](repeatElement(0, count: 1024)) while inputStream.hasBytesAvailable { let len = inputStream.read(&buffer, maxLength: buffer.count) if let data = String(bytesNoCopy: &buffer, length: len, encoding: .ascii, freeWhenDone: false) { receivedDataBuffer.append(data) } } } return } if eventCode == .endEncountered { timeoutTimer?.invalidate() if aStream == outputStream { streamState = (streamState.input, false) } if aStream == inputStream { streamState = (false, streamState.output) if case (_, true) = streamState { outputStream?.close() } delegate?.deviceConnection(connection: self, didUpdateState: .closed) if !receivedDataBuffer.isEmpty { delegate?.deviceConnection(connection: self, didReceiveData: receivedDataBuffer) } } return } if eventCode == .errorOccurred { delegate?.deviceConnection(connection: self, didUpdateState: .error) return } } }
mit
77005a068ac1ffde1433b44836272149
29.355191
152
0.579118
5.305635
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
RxSwiftGuideRead/RxSwift-master/RxExample/RxExample/Examples/GitHubSignup/DefaultImplementations.swift
3
3370
// // DefaultImplementations.swift // RxExample // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import struct Foundation.CharacterSet import struct Foundation.URL import struct Foundation.URLRequest import struct Foundation.NSRange import class Foundation.URLSession import func Foundation.arc4random class GitHubDefaultValidationService: GitHubValidationService { let API: GitHubAPI static let sharedValidationService = GitHubDefaultValidationService(API: GitHubDefaultAPI.sharedAPI) init (API: GitHubAPI) { self.API = API } // validation let minPasswordCount = 5 func validateUsername(_ username: String) -> Observable<ValidationResult> { if username.isEmpty { return .just(.empty) } // this obviously won't be if username.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) != nil { return .just(.failed(message: "Username can only contain numbers or digits")) } let loadingValue = ValidationResult.validating return API .usernameAvailable(username) .map { available in if available { return .ok(message: "Username available") } else { return .failed(message: "Username already taken") } } .startWith(loadingValue) } func validatePassword(_ password: String) -> ValidationResult { let numberOfCharacters = password.count if numberOfCharacters == 0 { return .empty } if numberOfCharacters < minPasswordCount { return .failed(message: "Password must be at least \(minPasswordCount) characters") } return .ok(message: "Password acceptable") } func validateRepeatedPassword(_ password: String, repeatedPassword: String) -> ValidationResult { if repeatedPassword.count == 0 { return .empty } if repeatedPassword == password { return .ok(message: "Password repeated") } else { return .failed(message: "Password different") } } } class GitHubDefaultAPI : GitHubAPI { let URLSession: Foundation.URLSession static let sharedAPI = GitHubDefaultAPI( URLSession: Foundation.URLSession.shared ) init(URLSession: Foundation.URLSession) { self.URLSession = URLSession } func usernameAvailable(_ username: String) -> Observable<Bool> { // this is ofc just mock, but good enough let url = URL(string: "https://github.com/\(username.URLEscaped)")! let request = URLRequest(url: url) return self.URLSession.rx.response(request: request) .map { pair in return pair.response.statusCode == 404 } .catchErrorJustReturn(false) } func signup(_ username: String, password: String) -> Observable<Bool> { // this is also just a mock let signupResult = arc4random() % 5 == 0 ? false : true return Observable.just(signupResult) .delay(.seconds(1), scheduler: MainScheduler.instance) } }
mit
2f2ee49d8bc3b788d664cc7d2d34bf1e
28.552632
104
0.60938
5.175115
false
false
false
false
madcato/OSFramework
Sources/OSFramework/UIViewController+showAlert.swift
1
1475
// // UIViewController+showAlert.swift // OSFramework // // Created by Daniel Vela on 19/04/2017. // Copyright © 2017 Daniel Vela. All rights reserved. // import Foundation public extension UIViewController { func showAlert(_ message: String, title: String? = nil, onFinish: @escaping () -> Void = {}) { if #available(iOS 8.0, *) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in onFinish() }) self.present(alert, animated: true) {} } else { let alertView = UIAlertView(title: nil, message: message, delegate: nil, cancelButtonTitle: "OK") alertView.show() } } static func showAlertOnTopController(_ message: String, title: String? = nil, onFinish: @escaping () -> Void = {}) { var rootViewController = UIApplication.shared.keyWindow?.rootViewController if let navigationController = rootViewController as? UINavigationController { rootViewController = navigationController.viewControllers.first } if let tabBarController = rootViewController as? UITabBarController { rootViewController = tabBarController.selectedViewController } rootViewController?.showAlert(message, title: title, onFinish: onFinish) } }
mit
4acb492ef29afbb163fb62ab42f0c8a6
41.114286
109
0.627544
5.245552
false
false
false
false
shuoli84/RxSwift
RxSwift/RxSwift/Observables/Implementations/Sink.swift
4
1581
// // Sink.swift // Rx // // Created by Krunoslav Zaher on 2/19/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Sink<O : ObserverType> : Disposable { private typealias Element = O.Element typealias State = ( observer: O?, cancel: Disposable, disposed: Bool ) private var lock = Lock() private var _state: State var observer: O? { get { return lock.calculateLocked { _state.observer } } } var cancel: Disposable { get { return lock.calculateLocked { _state.cancel } } } var state: State { get { return lock.calculateLocked { _state } } } init(observer: O, cancel: Disposable) { #if TRACE_RESOURCES OSAtomicIncrement32(&resourceCount) #endif _state = ( observer: observer, cancel: cancel, disposed: false ) } func dispose() { var cancel: Disposable? = lock.calculateLocked { if _state.disposed { return nil } var cancel = _state.cancel _state.disposed = true _state.observer = nil _state.cancel = NopDisposable.instance return cancel } if let cancel = cancel { cancel.dispose() } } deinit { #if TRACE_RESOURCES OSAtomicDecrement32(&resourceCount) #endif } }
mit
f60c09d2c51439c3e5ad6d86382d9639
19.545455
60
0.504744
4.834862
false
false
false
false
apple/swift-nio-http2
Tests/NIOHTTP2Tests/TestUtilities.swift
1
42190
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin.C #elseif os(Linux) || os(FreeBSD) || os(Android) import Glibc #else #endif import XCTest import NIOCore import NIOEmbedded import NIOHTTP1 @testable import NIOHTTP2 import NIOHPACK struct NoFrameReceived: Error { } // MARK:- Test helpers we use throughout these tests to encapsulate verbose // and noisy code. extension XCTestCase { /// Have two `EmbeddedChannel` objects send and receive data from each other until /// they make no forward progress. func interactInMemory(_ first: EmbeddedChannel, _ second: EmbeddedChannel, file: StaticString = #filePath, line: UInt = #line) { var operated: Bool func readBytesFromChannel(_ channel: EmbeddedChannel) -> ByteBuffer? { guard let data = try? assertNoThrowWithValue(channel.readOutbound(as: IOData.self)) else { return nil } switch data { case .byteBuffer(let b): return b case .fileRegion(let f): return f.asByteBuffer(allocator: channel.allocator) } } repeat { operated = false if let data = readBytesFromChannel(first) { operated = true XCTAssertNoThrow(try second.writeInbound(data), file: (file), line: line) } if let data = readBytesFromChannel(second) { operated = true XCTAssertNoThrow(try first.writeInbound(data), file: (file), line: line) } } while operated } /// Deliver all the bytes currently flushed on `sourceChannel` to `targetChannel`. func deliverAllBytes(from sourceChannel: EmbeddedChannel, to targetChannel: EmbeddedChannel, file: StaticString = #filePath, line: UInt = #line) { // Collect the serialized data. var frameBuffer = sourceChannel.allocator.buffer(capacity: 1024) while case .some(.byteBuffer(var buf)) = try? assertNoThrowWithValue(sourceChannel.readOutbound(as: IOData.self)) { frameBuffer.writeBuffer(&buf) } XCTAssertNoThrow(try targetChannel.writeInbound(frameBuffer), file: (file), line: line) } /// Given two `EmbeddedChannel` objects, verify that each one performs the handshake: specifically, /// that each receives a SETTINGS frame from its peer and a SETTINGS ACK for its own settings frame. /// /// If the handshake has not occurred, this will definitely call `XCTFail`. It may also throw if the /// channel is now in an indeterminate state. func assertDoHandshake(client: EmbeddedChannel, server: EmbeddedChannel, clientSettings: [HTTP2Setting] = nioDefaultSettings, serverSettings: [HTTP2Setting] = nioDefaultSettings, file: StaticString = #filePath, line: UInt = #line) throws { // This connects are not semantically right, but are required in order to activate the // channels. //! FIXME: Replace with registerAlreadyConfigured0 once EmbeddedChannel propagates this // call to its channelcore. let socket = try SocketAddress(unixDomainSocketPath: "/fake") _ = try client.connect(to: socket).wait() _ = try server.connect(to: socket).wait() // First the channels need to interact. self.interactInMemory(client, server, file: (file), line: line) // Now keep an eye on things. Each channel should first have been sent a SETTINGS frame. let clientReceivedSettings = try client.assertReceivedFrame(file: (file), line: line) let serverReceivedSettings = try server.assertReceivedFrame(file: (file), line: line) // Each channel should also have a settings ACK. let clientReceivedSettingsAck = try client.assertReceivedFrame(file: (file), line: line) let serverReceivedSettingsAck = try server.assertReceivedFrame(file: (file), line: line) // Check that these SETTINGS frames are ok. clientReceivedSettings.assertSettingsFrame(expectedSettings: serverSettings, ack: false, file: (file), line: line) serverReceivedSettings.assertSettingsFrame(expectedSettings: clientSettings, ack: false, file: (file), line: line) clientReceivedSettingsAck.assertSettingsFrame(expectedSettings: [], ack: true, file: (file), line: line) serverReceivedSettingsAck.assertSettingsFrame(expectedSettings: [], ack: true, file: (file), line: line) client.assertNoFramesReceived(file: (file), line: line) server.assertNoFramesReceived(file: (file), line: line) } /// Assert that sending the given `frames` into `sender` causes them all to pop back out again at `receiver`, /// and that `sender` has received no frames. /// /// Optionally returns the frames received. @discardableResult func assertFramesRoundTrip(frames: [HTTP2Frame], sender: EmbeddedChannel, receiver: EmbeddedChannel, file: StaticString = #filePath, line: UInt = #line) throws -> [HTTP2Frame] { for frame in frames { sender.write(frame, promise: nil) } sender.flush() self.interactInMemory(sender, receiver, file: (file), line: line) sender.assertNoFramesReceived(file: (file), line: line) var receivedFrames = [HTTP2Frame]() for frame in frames { let receivedFrame = try receiver.assertReceivedFrame(file: (file), line: line) receivedFrame.assertFrameMatches(this: frame, file: (file), line: line) receivedFrames.append(receivedFrame) } return receivedFrames } /// Asserts that sending new settings from `sender` to `receiver` leads to an appropriate settings ACK. Does not assert that no other frames have been /// received. func assertSettingsUpdateWithAck(_ newSettings: HTTP2Settings, sender: EmbeddedChannel, receiver: EmbeddedChannel, file: StaticString = #filePath, line: UInt = #line) throws { let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(newSettings))) sender.writeAndFlush(frame, promise: nil) self.interactInMemory(sender, receiver, file: (file), line: line) try receiver.assertReceivedFrame(file: (file), line: line).assertFrameMatches(this: frame) try sender.assertReceivedFrame(file: (file), line: line).assertFrameMatches(this: HTTP2Frame(streamID: .rootStream, payload: .settings(.ack))) } } extension EmbeddedChannel { /// This function attempts to obtain a HTTP/2 frame from a connection. It must already have been /// sent, as this function does not call `interactInMemory`. If no frame has been received, this /// will call `XCTFail` and then throw: this will ensure that the test will not proceed past /// this point if no frame was received. func assertReceivedFrame(file: StaticString = #filePath, line: UInt = #line) throws -> HTTP2Frame { guard let frame: HTTP2Frame = try assertNoThrowWithValue(self.readInbound()) else { XCTFail("Did not receive frame", file: (file), line: line) throw NoFrameReceived() } return frame } /// Asserts that the connection has not received a HTTP/2 frame at this time. func assertNoFramesReceived(file: StaticString = #filePath, line: UInt = #line) { let content: HTTP2Frame? = try? assertNoThrowWithValue(self.readInbound()) XCTAssertNil(content, "Received unexpected content: \(content!)", file: (file), line: line) } /// Retrieve all sent frames. func sentFrames(file: StaticString = #filePath, line: UInt = #line) throws -> [HTTP2Frame] { var receivedFrames: [HTTP2Frame] = Array() while let frame = try assertNoThrowWithValue(self.readOutbound(as: HTTP2Frame.self), file: (file), line: line) { receivedFrames.append(frame) } return receivedFrames } } extension HTTP2Frame { /// Asserts that the given frame is a SETTINGS frame. func assertSettingsFrame(expectedSettings: [HTTP2Setting], ack: Bool, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, .rootStream, "Got unexpected stream ID for SETTINGS: \(self.streamID)", file: (file), line: line) self.payload.assertSettingsFramePayload(expectedSettings: expectedSettings, ack: ack, file: (file), line: line) } func assertSettingsFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, .rootStream, "Got unexpected stream ID for SETTINGS: \(self.streamID)", file: (file), line: line) self.payload.assertSettingsFramePayloadMatches(this: frame.payload, file: (file), line: line) } /// Asserts that this frame matches a give other frame. func assertFrameMatches(this frame: HTTP2Frame, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) { switch frame.payload { case .headers: self.assertHeadersFrameMatches(this: frame, file: (file), line: line) case .data: self.assertDataFrameMatches(this: frame, fileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) case .goAway: self.assertGoAwayFrameMatches(this: frame, file: (file), line: line) case .ping: self.assertPingFrameMatches(this: frame, file: (file), line: line) case .settings: self.assertSettingsFrameMatches(this: frame, file: (file), line: line) case .rstStream: self.assertRstStreamFrameMatches(this: frame, file: (file), line: line) case .priority: self.assertPriorityFrameMatches(this: frame, file: (file), line: line) case .pushPromise: self.assertPushPromiseFrameMatches(this: frame, file: (file), line: line) case .windowUpdate: self.assertWindowUpdateFrameMatches(this: frame, file: (file), line: line) case .alternativeService: self.assertAlternativeServiceFrameMatches(this: frame, file: (file), line: line) case .origin: self.assertOriginFrameMatches(this: frame, file: (file), line: line) } } /// Asserts that a given frame is a HEADERS frame matching this one. func assertHeadersFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, frame.streamID, "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) self.payload.assertHeadersFramePayloadMatches(this: frame.payload, file: (file), line: line) } enum HeadersType { case request case response case trailers case doNotValidate } /// Asserts the given frame is a HEADERS frame. func assertHeadersFrame(endStream: Bool, streamID: HTTP2StreamID, headers: HPACKHeaders, priority: HTTP2Frame.StreamPriorityData? = nil, type: HeadersType? = nil, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, streamID, "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) self.payload.assertHeadersFramePayload(endStream: endStream, headers: headers, priority: priority, type: type, file: file, line: line) } /// Asserts that a given frame is a DATA frame matching this one. /// /// This function always converts the DATA frame to a bytebuffer, for use with round-trip testing. func assertDataFrameMatches(this frame: HTTP2Frame, fileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, frame.streamID, "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) self.payload.assertDataFramePayloadMatches(this: frame.payload, fileRegionToByteBuffer: fileRegionToByteBuffer, file: (file), line: line) } /// Assert the given frame is a DATA frame with the appropriate settings. func assertDataFrame(endStream: Bool, streamID: HTTP2StreamID, payload: ByteBuffer, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, streamID, "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) self.payload.assertDataFramePayload(endStream: endStream, payload: payload, file: file, line: line) } func assertGoAwayFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, .rootStream, "Goaway frame must be on the root stream!", file: (file), line: line) self.payload.assertGoAwayFramePayloadMatches(this: frame.payload) } func assertGoAwayFrame(lastStreamID: HTTP2StreamID, errorCode: UInt32, opaqueData: [UInt8]?, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, .rootStream, "Goaway frame must be on the root stream!", file: (file), line: line) self.payload.assertGoAwayFramePayload(lastStreamID: lastStreamID, errorCode: errorCode, opaqueData: opaqueData, file: (file), line: line) } func assertPingFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, .rootStream, "Ping frame must be on the root stream!", file: (file), line: line) self.payload.assertPingFramePayloadMatches(this: frame.payload, file: (file), line: line) } func assertPingFrame(ack: Bool, opaqueData: HTTP2PingData, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, .rootStream, "Ping frame must be on the root stream!", file: (file), line: line) self.payload.assertPingFramePayload(ack: ack, opaqueData: opaqueData, file: (file), line: line) } func assertWindowUpdateFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, frame.streamID, "Unexpected stream ID!", file: (file), line: line) self.payload.assertWindowUpdateFramePayloadMatches(this: frame.payload, file: (file), line: line) } func assertWindowUpdateFrame(streamID: HTTP2StreamID, windowIncrement: Int, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, streamID, "Unexpected stream ID!", file: (file), line: line) self.payload.assertWindowUpdateFramePayload(windowIncrement: windowIncrement, file: (file), line: line) } func assertRstStreamFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, frame.streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) self.payload.assertRstStreamFramePayloadMatches(this: frame.payload, file: (file), line: line) } func assertRstStreamFrame(streamID: HTTP2StreamID, errorCode: HTTP2ErrorCode, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) self.payload.assertRstStreamFramePayload(errorCode: errorCode, file: (file), line: line) } func assertPriorityFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, frame.streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) self.payload.assertPriorityFramePayloadMatches(this: frame.payload, file: (file), line: line) } func assertPriorityFrame(streamPriorityData: HTTP2Frame.StreamPriorityData, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) self.payload.assertPriorityFramePayload(streamPriorityData: streamPriorityData, file: (file), line: line) } func assertPushPromiseFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, frame.streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) self.payload.assertPushPromiseFramePayloadMatches(this: frame.payload, file: (file), line: line) } func assertPushPromiseFrame(streamID: HTTP2StreamID, pushedStreamID: HTTP2StreamID, headers: HPACKHeaders, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(self.streamID, streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) self.payload.assertPushPromiseFramePayload(pushedStreamID: pushedStreamID, headers: headers, file: (file), line: line) } func assertAlternativeServiceFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(.rootStream, self.streamID, "ALTSVC frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) self.payload.assertAlternativeServiceFramePayloadMatches(this: frame.payload, file: (file), line: line) } func assertAlternativeServiceFrame(origin: String?, field: ByteBuffer?, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(.rootStream, self.streamID, "ALTSVC frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) self.payload.assertAlternativeServiceFramePayload(origin: origin, field: field, file: (file), line: line) } func assertOriginFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(.rootStream, self.streamID, "ORIGIN frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) self.payload.assertOriginFramePayloadMatches(this: frame.payload, file: (file), line: line) } func assertOriginFrame(streamID: HTTP2StreamID, origins: [String], file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(.rootStream, self.streamID, "ORIGIN frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) self.payload.assertOriginFramePayload(origins: origins, file: (file), line: line) } } extension HTTP2Frame.FramePayload { func assertFramePayloadMatches(this payload: HTTP2Frame.FramePayload, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) { switch self { case .headers: self.assertHeadersFramePayloadMatches(this: payload, file: (file), line: line) case .data: self.assertDataFramePayloadMatches(this: payload, fileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) case .goAway: self.assertGoAwayFramePayloadMatches(this: payload, file: (file), line: line) case .ping: self.assertPingFramePayloadMatches(this: payload, file: (file), line: line) case .settings: self.assertSettingsFramePayloadMatches(this: payload, file: (file), line: line) case .rstStream: self.assertRstStreamFramePayloadMatches(this: payload, file: (file), line: line) case .priority: self.assertPriorityFramePayloadMatches(this: payload, file: (file), line: line) case .pushPromise: self.assertPushPromiseFramePayloadMatches(this: payload, file: (file), line: line) case .windowUpdate: self.assertWindowUpdateFramePayloadMatches(this: payload, file: (file), line: line) case .alternativeService: self.assertAlternativeServiceFramePayloadMatches(this: payload, file: (file), line: line) case .origin: self.assertOriginFramePayloadMatches(this: payload, file: (file), line: line) } } /// Asserts that a given frame is a HEADERS frame matching this one. func assertHeadersFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .headers(let payload) = self else { preconditionFailure("Headers frames can never match non-headers frames") } self.assertHeadersFramePayload(endStream: payload.endStream, headers: payload.headers, priority: payload.priorityData, file: file, line: line) } func assertHeadersFramePayload(endStream: Bool, headers: HPACKHeaders, priority: HTTP2Frame.StreamPriorityData? = nil, type: HTTP2Frame.HeadersType? = nil, file: StaticString = #filePath, line: UInt = #line) { guard case .headers(let actualPayload) = self else { XCTFail("Expected HEADERS payload, got \(self) instead", file: (file), line: line) return } XCTAssertEqual(actualPayload.endStream, endStream, "Unexpected endStream: expected \(endStream), got \(actualPayload.endStream)", file: (file), line: line) XCTAssertEqual(headers, actualPayload.headers, "Non-equal headers: expected \(headers), got \(actualPayload.headers)", file: (file), line: line) XCTAssertEqual(priority, actualPayload.priorityData, "Non-equal priorities: expected \(String(describing: priority)), got \(String(describing: actualPayload.priorityData))", file: (file), line: line) switch type { case .some(.request): XCTAssertNoThrow(try actualPayload.headers.validateRequestBlock(), "\(actualPayload.headers) not a valid \(type!) headers block", file: (file), line: line) case .some(.response): XCTAssertNoThrow(try actualPayload.headers.validateResponseBlock(), "\(actualPayload.headers) not a valid \(type!) headers block", file: (file), line: line) case .some(.trailers): XCTAssertNoThrow(try actualPayload.headers.validateTrailersBlock(), "\(actualPayload.headers) not a valid \(type!) headers block", file: (file), line: line) case .some(.doNotValidate): () // alright, let's not validate then case .none: XCTAssertTrue((try? actualPayload.headers.validateRequestBlock()) != nil || (try? actualPayload.headers.validateResponseBlock()) != nil || (try? actualPayload.headers.validateTrailersBlock()) != nil, "\(actualPayload.headers) not a valid request/response/trailers header block", file: (file), line: line) } } /// Asserts that a given frame is a DATA frame matching this one. /// /// This function always converts the DATA frame to a bytebuffer, for use with round-trip testing. func assertDataFramePayloadMatches(this payload: HTTP2Frame.FramePayload, fileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) { guard case .data(let actualPayload) = payload else { XCTFail("Expected DATA frame, got \(self) instead", file: (file), line: line) return } switch (actualPayload.data, fileRegionToByteBuffer) { case (.byteBuffer(let bufferPayload), _): self.assertDataFramePayload(endStream: actualPayload.endStream, payload: bufferPayload, file: (file), line: line) case (.fileRegion(let filePayload), true): // Sorry about creating an allocator from thin air here! let expectedPayload = filePayload.asByteBuffer(allocator: ByteBufferAllocator()) self.assertDataFramePayload(endStream: actualPayload.endStream, payload: expectedPayload, file: (file), line: line) case (.fileRegion(let filePayload), false): self.assertDataFramePayload(endStream: actualPayload.endStream, payload: filePayload, file: (file), line: line) } } func assertDataFramePayload(endStream: Bool, payload: ByteBuffer, file: StaticString = #filePath, line: UInt = #line) { guard case .data(let actualFrameBody) = self else { XCTFail("Expected DATA payload, got \(self) instead", file: (file), line: line) return } guard case .byteBuffer(let actualPayload) = actualFrameBody.data else { XCTFail("Expected ByteBuffer DATA payload, got \(actualFrameBody.data) instead", file: (file), line: line) return } XCTAssertEqual(actualFrameBody.endStream, endStream, "Unexpected endStream: expected \(endStream), got \(actualFrameBody.endStream)", file: (file), line: line) XCTAssertEqual(actualPayload, payload, "Unexpected body: expected \(payload), got \(actualPayload)", file: (file), line: line) } func assertDataFramePayload(endStream: Bool, payload: FileRegion, file: StaticString = #filePath, line: UInt = #line) { guard case .data(let actualFrameBody) = self else { XCTFail("Expected DATA frame, got \(self) instead", file: (file), line: line) return } guard case .fileRegion(let actualPayload) = actualFrameBody.data else { XCTFail("Expected FileRegion DATA frame, got \(actualFrameBody.data) instead", file: (file), line: line) return } XCTAssertEqual(actualFrameBody.endStream, endStream, "Unexpected endStream: expected \(endStream), got \(actualFrameBody.endStream)", file: (file), line: line) XCTAssertEqual(actualPayload, payload, "Unexpected body: expected \(payload), got \(actualPayload)", file: (file), line: line) } func assertGoAwayFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .goAway(let lastStreamID, let errorCode, let opaqueData) = payload else { preconditionFailure("Goaway frames can never match non-Goaway frames.") } self.assertGoAwayFramePayload(lastStreamID: lastStreamID, errorCode: UInt32(http2ErrorCode: errorCode), opaqueData: opaqueData.flatMap { $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) }, file: (file), line: line) } func assertGoAwayFramePayload(lastStreamID: HTTP2StreamID, errorCode: UInt32, opaqueData: [UInt8]?, file: StaticString = #filePath, line: UInt = #line) { guard case .goAway(let actualLastStreamID, let actualErrorCode, let actualOpaqueData) = self else { XCTFail("Expected GOAWAY frame, got \(self) instead", file: (file), line: line) return } let integerErrorCode = UInt32(http2ErrorCode: actualErrorCode) let byteArrayOpaqueData = actualOpaqueData.flatMap { $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) } XCTAssertEqual(lastStreamID, actualLastStreamID, "Unexpected last stream ID: expected \(lastStreamID), got \(actualLastStreamID)", file: (file), line: line) XCTAssertEqual(integerErrorCode, errorCode, "Unexpected error code: expected \(errorCode), got \(integerErrorCode)", file: (file), line: line) XCTAssertEqual(byteArrayOpaqueData, opaqueData, "Unexpected opaque data: expected \(String(describing: opaqueData)), got \(String(describing: byteArrayOpaqueData))", file: (file), line: line) } func assertPingFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .ping(let opaqueData, let ack) = payload else { preconditionFailure("Ping frames can never match non-Ping frames.") } self.assertPingFramePayload(ack: ack, opaqueData: opaqueData, file: (file), line: line) } func assertPingFramePayload(ack: Bool, opaqueData: HTTP2PingData, file: StaticString = #filePath, line: UInt = #line) { guard case .ping(let actualPingData, let actualAck) = self else { XCTFail("Expected PING frame, got \(self) instead", file: (file), line: line) return } XCTAssertEqual(actualAck, ack, "Non-matching ACK: expected \(ack), got \(actualAck)", file: (file), line: line) XCTAssertEqual(actualPingData, opaqueData, "Non-matching ping data: expected \(opaqueData), got \(actualPingData)", file: (file), line: line) } /// Asserts that the given frame is a SETTINGS frame. func assertSettingsFramePayload(expectedSettings: [HTTP2Setting], ack: Bool, file: StaticString = #filePath, line: UInt = #line) { guard case .settings(let payload) = self else { XCTFail("Expected SETTINGS frame, got \(self) instead", file: (file), line: line) return } switch payload { case .ack: XCTAssertEqual(expectedSettings, [], "Got unexpected settings: expected \(expectedSettings), got []", file: (file), line: line) XCTAssertTrue(ack, "Got unexpected value for ack: expected \(ack), got true", file: (file), line: line) case .settings(let actualSettings): XCTAssertEqual(expectedSettings, actualSettings, "Got unexpected settings: expected \(expectedSettings), got \(actualSettings)", file: (file), line: line) XCTAssertFalse(false, "Got unexpected value for ack: expected \(ack), got false", file: (file), line: line) } } func assertSettingsFramePayloadMatches(this framePayload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .settings(let payload) = framePayload else { preconditionFailure("Settings frames can never match non-settings frames") } switch payload { case .ack: self.assertSettingsFramePayload(expectedSettings: [], ack: true, file: (file), line: line) case .settings(let expectedSettings): self.assertSettingsFramePayload(expectedSettings: expectedSettings, ack: false, file: (file), line: line) } } func assertWindowUpdateFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .windowUpdate(let increment) = payload else { XCTFail("WINDOW_UPDATE frames can never match non-WINDOW_UPDATE frames", file: (file), line: line) return } self.assertWindowUpdateFramePayload(windowIncrement: increment) } func assertWindowUpdateFramePayload(windowIncrement: Int, file: StaticString = #filePath, line: UInt = #line) { guard case .windowUpdate(let actualWindowIncrement) = self else { XCTFail("Expected WINDOW_UPDATE frame, got \(self) instead", file: (file), line: line) return } XCTAssertEqual(windowIncrement, actualWindowIncrement, "Unexpected window increment!", file: (file), line: line) } func assertRstStreamFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .rstStream(let errorCode) = payload else { preconditionFailure("RstStream frames can never match non-RstStream frames.") } self.assertRstStreamFramePayload(errorCode: errorCode, file: (file), line: line) } func assertRstStreamFramePayload(errorCode: HTTP2ErrorCode, file: StaticString = #filePath, line: UInt = #line) { guard case .rstStream(let actualErrorCode) = self else { XCTFail("Expected RST_STREAM frame, got \(self) instead", file: (file), line: line) return } XCTAssertEqual(actualErrorCode, errorCode, "Non-matching error-code: expected \(errorCode), got \(actualErrorCode)", file: (file), line: line) } func assertPriorityFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .priority(let expectedPriorityData) = payload else { preconditionFailure("Priority frames can never match non-Priority frames.") } self.assertPriorityFramePayload(streamPriorityData: expectedPriorityData, file: (file), line: line) } func assertPriorityFramePayload(streamPriorityData: HTTP2Frame.StreamPriorityData, file: StaticString = #filePath, line: UInt = #line) { guard case .priority(let actualPriorityData) = self else { XCTFail("Expected PRIORITY frame, got \(self) instead", file: (file), line: line) return } XCTAssertEqual(streamPriorityData, actualPriorityData, file: (file), line: line) } func assertPushPromiseFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .pushPromise(let payload) = payload else { preconditionFailure("PushPromise frames can never match non-PushPromise frames.") } self.assertPushPromiseFramePayload(pushedStreamID: payload.pushedStreamID, headers: payload.headers, file: (file), line: line) } func assertPushPromiseFramePayload(pushedStreamID: HTTP2StreamID, headers: HPACKHeaders, file: StaticString = #filePath, line: UInt = #line) { guard case .pushPromise(let actualPayload) = self else { XCTFail("Expected PUSH_PROMISE frame, got \(self) instead", file: (file), line: line) return } XCTAssertEqual(pushedStreamID, actualPayload.pushedStreamID, "Non matching pushed stream IDs: expected \(pushedStreamID), got \(actualPayload.pushedStreamID)", file: (file), line: line) XCTAssertEqual(headers, actualPayload.headers, "Non matching pushed headers: expected \(headers), got \(actualPayload.headers)", file: (file), line: line) } func assertAlternativeServiceFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .alternativeService(let origin, let field) = payload else { preconditionFailure("AltSvc frames can never match non-AltSvc frames.") } self.assertAlternativeServiceFramePayload(origin: origin, field: field, file: (file), line: line) } func assertAlternativeServiceFramePayload(origin: String?, field: ByteBuffer?, file: StaticString = #filePath, line: UInt = #line) { guard case .alternativeService(let actualOrigin, let actualField) = self else { XCTFail("Expected ALTSVC frame, got \(self) instead", file: (file), line: line) return } XCTAssertEqual(origin, actualOrigin, "Non matching origins: expected \(String(describing: origin)), got \(String(describing: actualOrigin))", file: (file), line: line) XCTAssertEqual(field, actualField, "Non matching field: expected \(String(describing: field)), got \(String(describing: actualField))", file: (file), line: line) } func assertOriginFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { guard case .origin(let origins) = payload else { preconditionFailure("ORIGIN frames can never match non-ORIGIN frames.") } self.assertOriginFramePayload(origins: origins, file: (file), line: line) } func assertOriginFramePayload(origins: [String], file: StaticString = #filePath, line: UInt = #line) { guard case .origin(let actualPayload) = self else { XCTFail("Expected ORIGIN frame, got \(self) instead", file: (file), line: line) return } XCTAssertEqual(origins, actualPayload, "Non matching origins: expected \(origins), got \(actualPayload)", file: (file), line: line) } } extension Array where Element == HTTP2Frame { func assertFramesMatch<Candidate: Collection>(_ target: Candidate, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) where Candidate.Element == HTTP2Frame { guard self.count == target.count else { XCTFail("Different numbers of frames: expected \(target.count), got \(self.count)", file: (file), line: line) return } for (expected, actual) in zip(target, self) { expected.assertFrameMatches(this: actual, dataFileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) } } } extension Array where Element == HTTP2Frame.FramePayload { func assertFramePayloadsMatch<Candidate: Collection>(_ target: Candidate, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) where Candidate.Element == HTTP2Frame.FramePayload { guard self.count == target.count else { XCTFail("Different numbers of frame payloads: expected \(target.count), got \(self.count)", file: (file), line: line) return } for (expected, actual) in zip(target, self) { expected.assertFramePayloadMatches(this: actual, dataFileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) } } } /// Runs the body with a temporary file, optionally containing some file content. func withTemporaryFile<T>(content: String? = nil, _ body: (NIOFileHandle, String) throws -> T) rethrows -> T { let (fd, path) = openTemporaryFile() let fileHandle = NIOFileHandle(descriptor: fd) defer { XCTAssertNoThrow(try fileHandle.close()) XCTAssertEqual(0, unlink(path)) } if let content = content { Array(content.utf8).withUnsafeBufferPointer { ptr in var toWrite = ptr.count var start = ptr.baseAddress! while toWrite > 0 { let rc = write(fd, start, toWrite) if rc >= 0 { toWrite -= rc start = start + rc } else { fatalError("Hit error: \(String(cString: strerror(errno)))") } } XCTAssertEqual(0, lseek(fd, 0, SEEK_SET)) } } return try body(fileHandle, path) } func openTemporaryFile() -> (CInt, String) { let template = "\(FileManager.default.temporaryDirectory.path)/niotestXXXXXXX" var templateBytes = template.utf8 + [0] let templateBytesCount = templateBytes.count let fd = templateBytes.withUnsafeMutableBufferPointer { ptr in ptr.baseAddress!.withMemoryRebound(to: Int8.self, capacity: templateBytesCount) { (ptr: UnsafeMutablePointer<Int8>) in return mkstemp(ptr) } } templateBytes.removeLast() return (fd, String(decoding: templateBytes, as: UTF8.self)) } extension FileRegion { func asByteBuffer(allocator: ByteBufferAllocator) -> ByteBuffer { var fileBuffer = allocator.buffer(capacity: self.readableBytes) fileBuffer.writeWithUnsafeMutableBytes(minimumWritableBytes: self.readableBytes) { ptr in let rc = try! self.fileHandle.withUnsafeFileDescriptor { fd -> Int in lseek(fd, off_t(self.readerIndex), SEEK_SET) return read(fd, ptr.baseAddress!, self.readableBytes) } precondition(rc == self.readableBytes) return rc } precondition(fileBuffer.readableBytes == self.readableBytes) return fileBuffer } } extension NIOCore.NIOFileHandle { func appendBuffer(_ buffer: ByteBuffer) { var written = 0 while written < buffer.readableBytes { let rc = buffer.withUnsafeReadableBytes { ptr in try! self.withUnsafeFileDescriptor { fd -> Int in lseek(fd, 0, SEEK_END) return write(fd, ptr.baseAddress! + written, ptr.count - written) } } precondition(rc > 0) written += rc } } } func assertNoThrowWithValue<T>(_ body: @autoclosure () throws -> T, defaultValue: T? = nil, message: String? = nil, file: StaticString = #filePath, line: UInt = #line) throws -> T { do { return try body() } catch { XCTFail("\(message.map { $0 + ": " } ?? "")unexpected error \(error) thrown", file: (file), line: line) if let defaultValue = defaultValue { return defaultValue } else { throw error } } }
apache-2.0
cbf5d87383462419baaeec94a24a05e3
53.298584
223
0.652429
4.594359
false
false
false
false
teklabs/MyTabBarApp
MyTabBarApp/TabBarViewController.swift
1
1197
// // TabBarViewController.swift // MyTabBarApp // // Created by teklabsco on 11/16/15. // Copyright © 2015 Teklabs, LLC. All rights reserved. // import Foundation @objc protocol TabBarControllerDelegate { func tabBarController(tabBarController: UITabBarController) } class TabBarViewController: UITabBarController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var navController: UINavigationController? var currentUser: PFObject? override func viewDidLoad() { super.viewDidLoad() // iOS 7 style //self.tabBar.tintColor = UIColor(red: 254.0/255.0, green: 149.0/255.0, blue: 50.0/255.0, alpha: 1.0) self.tabBar.tintColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0) //self.tabBar.barTintColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0) self.tabBar.barTintColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0) self.navController = UINavigationController() } override func preferredStatusBarStyle() -> UIStatusBarStyle { //return UIStatusBarStyle.LightContent return UIStatusBarStyle.Default } }
gpl-3.0
1050c2776d71640b7bf3268df4792624
32.25
113
0.70903
3.725857
false
false
false
false